This repository has been archived by the owner on Jul 29, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
Copy pathrunner.ts
400 lines (366 loc) · 12.9 KB
/
runner.ts
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
import {EventEmitter} from 'events';
import * as q from 'q';
import {promise as wdpromise, Session} from 'selenium-webdriver';
import * as util from 'util';
import {ProtractorBrowser} from './browser';
import {Config} from './config';
import {AttachSession, BrowserStack, Direct, DriverProvider, Hosted, Local, Mock, Sauce} from './driverProviders';
import {Logger} from './logger';
import {Plugins} from './plugins';
import {protractor} from './ptor';
import * as helper from './util';
declare let global: any;
declare let process: any;
let logger = new Logger('runner');
/*
* Runner is responsible for starting the execution of a test run and triggering
* setup, teardown, managing config, etc through its various dependencies.
*
* The Protractor Runner is a node EventEmitter with the following events:
* - testPass
* - testFail
* - testsDone
*
* @param {Object} config
* @constructor
*/
export class Runner extends EventEmitter {
config_: Config;
preparer_: any;
driverprovider_: DriverProvider;
o: any;
plugins_: Plugins;
constructor(config: Config) {
super();
this.config_ = config;
if (config.v8Debug) {
// Call this private function instead of sending SIGUSR1 because Windows.
process['_debugProcess'](process.pid);
}
if (config.nodeDebug) {
process['_debugProcess'](process.pid);
let flow = wdpromise.controlFlow();
flow.execute(() => {
let nodedebug = require('child_process').fork('debug', ['localhost:5858']);
process.on('exit', function() {
nodedebug.kill('SIGTERM');
});
nodedebug.on('exit', function() {
process.exit(1);
});
}, 'start the node debugger');
flow.timeout(1000, 'waiting for debugger to attach');
}
if (config.capabilities && config.capabilities.seleniumAddress) {
config.seleniumAddress = config.capabilities.seleniumAddress;
}
this.loadDriverProvider_(config);
this.setTestPreparer(config.onPrepare);
}
/**
* Registrar for testPreparers - executed right before tests run.
* @public
* @param {string/Fn} filenameOrFn
*/
setTestPreparer(filenameOrFn: string|Function): void {
this.preparer_ = filenameOrFn;
}
/**
* Executor of testPreparer
* @public
* @return {q.Promise} A promise that will resolve when the test preparers
* are finished.
*/
runTestPreparer(): q.Promise<any> {
return this.plugins_.onPrepare().then(() => {
return helper.runFilenameOrFn_(this.config_.configDir, this.preparer_);
});
}
/**
* Grab driver provider based on type
* @private
*
* Priority
* 1) if directConnect is true, use that
* 2) if seleniumAddress is given, use that
* 3) if a Sauce Labs account is given, use that
* 4) if a seleniumServerJar is specified, use that
* 5) try to find the seleniumServerJar in protractor/selenium
*/
loadDriverProvider_(config: Config) {
this.config_ = config;
if (this.config_.directConnect) {
this.driverprovider_ = new Direct(this.config_);
} else if (this.config_.seleniumAddress) {
if (this.config_.seleniumSessionId) {
this.driverprovider_ = new AttachSession(this.config_);
} else {
this.driverprovider_ = new Hosted(this.config_);
}
} else if (this.config_.browserstackUser && this.config_.browserstackKey) {
this.driverprovider_ = new BrowserStack(this.config_);
} else if (this.config_.sauceUser && this.config_.sauceKey) {
this.driverprovider_ = new Sauce(this.config_);
} else if (this.config_.seleniumServerJar) {
this.driverprovider_ = new Local(this.config_);
} else if (this.config_.mockSelenium) {
this.driverprovider_ = new Mock(this.config_);
} else {
this.driverprovider_ = new Local(this.config_);
}
}
/**
* Responsible for cleaning up test run and exiting the process.
* @private
* @param {int} Standard unix exit code
*/
exit_ = function(exitCode: number): any {
return helper.runFilenameOrFn_(this.config_.configDir, this.config_.onCleanUp, [exitCode])
.then((returned): number | any => {
if (typeof returned === 'number') {
return returned;
} else {
return exitCode;
}
});
};
/**
* Getter for the Runner config object
* @public
* @return {Object} config
*/
getConfig(): Config {
return this.config_;
}
/**
* Get the control flow used by this runner.
* @return {Object} WebDriver control flow.
*/
controlFlow(): any {
return wdpromise.controlFlow();
}
/**
* Sets up convenience globals for test specs
* @private
*/
setupGlobals_(browser_: ProtractorBrowser) {
// Keep $, $$, element, and by/By under the global protractor namespace
protractor.browser = browser_;
protractor.$ = browser_.$;
protractor.$$ = browser_.$$;
protractor.element = browser_.element;
protractor.by = protractor.By = ProtractorBrowser.By;
protractor.wrapDriver = ProtractorBrowser.wrapDriver;
protractor.ExpectedConditions = browser_.ExpectedConditions;
if (!this.config_.noGlobals) {
// Export protractor to the global namespace to be used in tests.
global.browser = browser_;
global.$ = browser_.$;
global.$$ = browser_.$$;
global.element = browser_.element;
global.by = global.By = protractor.By;
global.ExpectedConditions = protractor.ExpectedConditions;
}
global.protractor = protractor;
if (!this.config_.skipSourceMapSupport) {
// Enable sourcemap support for stack traces.
require('source-map-support').install();
}
// Required by dart2js machinery.
// https://code.google.com/p/dart/source/browse/branches/bleeding_edge/dart/sdk/lib/js/dart2js/js_dart2js.dart?spec=svn32943&r=32943#487
global.DartObject = function(o: any) {
this.o = o;
};
}
/**
* Create a new driver from a driverProvider. Then set up a
* new protractor instance using this driver.
* This is used to set up the initial protractor instances and any
* future ones.
*
* @param {?Plugin} The plugin functions
*
* @return {Protractor} a protractor instance.
* @public
*/
createBrowser(plugins: any): any {
let config = this.config_;
let driver = this.driverprovider_.getNewDriver();
let browser_ = ProtractorBrowser.wrapDriver(
driver, config.baseUrl, config.rootElement, config.untrackOutstandingTimeouts);
browser_.params = config.params;
if (plugins) {
browser_.plugins_ = plugins;
}
if (config.getPageTimeout) {
browser_.getPageTimeout = config.getPageTimeout;
}
if (config.allScriptsTimeout) {
browser_.allScriptsTimeout = config.allScriptsTimeout;
}
if (config.debuggerServerPort) {
browser_.debuggerServerPort = config.debuggerServerPort;
}
if (config.useAllAngular2AppRoots) {
browser_.useAllAngular2AppRoots();
}
if (config.ng12Hybrid) {
browser_.ng12Hybrid = config.ng12Hybrid;
}
browser_.ready = driver.manage().timeouts().setScriptTimeout(config.allScriptsTimeout);
browser_.getProcessedConfig = () => {
return wdpromise.fulfilled(config);
};
browser_.forkNewDriverInstance = (opt_useSameUrl: boolean, opt_copyMockModules: boolean) => {
let newBrowser = this.createBrowser(plugins);
if (opt_copyMockModules) {
newBrowser.mockModules_ = browser_.mockModules_;
}
if (opt_useSameUrl) {
browser_.driver.getCurrentUrl().then((url: string) => {
newBrowser.get(url);
});
}
return newBrowser;
};
browser_.restart = () => {
// Note: because tests are not paused at this point, any async
// calls here are not guaranteed to complete before the tests resume.
this.driverprovider_.quitDriver(browser_.driver);
browser_ = browser_.forkNewDriverInstance(false, true);
this.setupGlobals_(browser_);
};
return browser_;
}
/**
* Final cleanup on exiting the runner.
*
* @return {q.Promise} A promise which resolves on finish.
* @private
*/
shutdown_(): q.Promise<any> {
return q.all(this.driverprovider_.getExistingDrivers().map((webdriver) => {
return this.driverprovider_.quitDriver(webdriver);
}));
}
/**
* The primary workhorse interface. Kicks off the test running process.
*
* @return {q.Promise} A promise which resolves to the exit code of the tests.
* @public
*/
run(): q.Promise<any> {
let testPassed: boolean;
let plugins = this.plugins_ = new Plugins(this.config_);
let pluginPostTestPromises: any;
let browser_: any;
let results: any;
if (this.config_.framework !== 'explorer' && !this.config_.specs.length) {
throw new Error('Spec patterns did not match any files.');
}
// 1) Setup environment
// noinspection JSValidateTypes
return this.driverprovider_.setupEnv()
.then(() => {
// 2) Create a browser and setup globals
browser_ = this.createBrowser(plugins);
this.setupGlobals_(browser_);
return browser_.ready.then(browser_.getSession)
.then(
(session: Session) => {
logger.debug(
'WebDriver session successfully started with capabilities ' +
util.inspect(session.getCapabilities()));
},
(err: Error) => {
logger.error('Unable to start a WebDriver session.');
throw err;
});
// 3) Setup plugins
})
.then(() => {
return plugins.setup();
// 4) Execute test cases
})
.then(() => {
// Do the framework setup here so that jasmine and mocha globals are
// available to the onPrepare function.
let frameworkPath = '';
if (this.config_.framework === 'jasmine' || this.config_.framework === 'jasmine2') {
frameworkPath = './frameworks/jasmine.js';
} else if (this.config_.framework === 'mocha') {
frameworkPath = './frameworks/mocha.js';
} else if (this.config_.framework === 'debugprint') {
// Private framework. Do not use.
frameworkPath = './frameworks/debugprint.js';
} else if (this.config_.framework === 'explorer') {
// Private framework. Do not use.
frameworkPath = './frameworks/explorer.js';
} else if (this.config_.framework === 'custom') {
if (!this.config_.frameworkPath) {
throw new Error(
'When config.framework is custom, ' +
'config.frameworkPath is required.');
}
frameworkPath = this.config_.frameworkPath;
} else {
throw new Error(
'config.framework (' + this.config_.framework + ') is not a valid framework.');
}
if (this.config_.restartBrowserBetweenTests) {
let restartDriver = () => {
browser_.restart();
};
this.on('testPass', restartDriver);
this.on('testFail', restartDriver);
}
// We need to save these promises to make sure they're run, but we
// don't
// want to delay starting the next test (because we can't, it's just
// an event emitter).
pluginPostTestPromises = [];
this.on('testPass', (testInfo: any) => {
pluginPostTestPromises.push(plugins.postTest(true, testInfo));
});
this.on('testFail', (testInfo: any) => {
pluginPostTestPromises.push(plugins.postTest(false, testInfo));
});
logger.debug('Running with spec files ' + this.config_.specs);
return require(frameworkPath).run(this, this.config_.specs);
// 5) Wait for postTest plugins to finish
})
.then((testResults: any) => {
results = testResults;
return q.all(pluginPostTestPromises);
// 6) Teardown plugins
})
.then(() => {
return plugins.teardown();
// 7) Teardown
})
.then(() => {
results = helper.joinTestLogs(results, plugins.getResults());
this.emit('testsDone', results);
testPassed = results.failedCount === 0;
if (this.driverprovider_.updateJob) {
return this.driverprovider_.updateJob({'passed': testPassed}).then(() => {
return this.driverprovider_.teardownEnv();
});
} else {
return this.driverprovider_.teardownEnv();
}
// 8) Let plugins do final cleanup
})
.then(() => {
return plugins.postResults();
// 9) Exit process
})
.then(() => {
let exitCode = testPassed ? 0 : 1;
return this.exit_(exitCode);
})
.fin(() => {
return this.shutdown_();
});
}
}