forked from flyingfisher/selenium-html-js-converter
-
Notifications
You must be signed in to change notification settings - Fork 1
/
selenium-utils.js
289 lines (248 loc) · 8.79 KB
/
selenium-utils.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
/**
* A hacky way to implement *AndWait Selenese commands. Native wd doesn't offer
* commands equivalent to e.g. clickAndWait or dragAndDropAndWait (actually
* neither dragAndDrop nor AndWait exist in wd) or clickAndWait. We work around
* it wrapping all *AndWait commands in code that first taints the document body
* with a class, then runs the base command, and waits for a new document ready
* state without the tainted body.
*
* @param {function} code The code to execute
* @param {WdSyncClient.browser} wdBrowser (optional) Browser instance
* @return {void}
*/
function doAndWait (code, wdBrowser) {
if (typeof wdBrowser !== 'object') {
wdBrowser = browser;
}
wdBrowser.execute('document.body.className += " SHTML2JSC"');
code();
withRetry(function () {
if (wdBrowser.execute("return document.readyState") !== 'complete' || wdBrowser.hasElementByCssSelector('body.SHTML2JSC'))
throw new Error('Page did not load in time');
}, wdBrowser);
}
/**
* Implements waitForPageToLoad selenese command. As opposed to the Selenium
* IDE implementation, this one actually waits for all resources to have been
* loaded.
*
* @param {WdSyncClient.browser} wdBrowser (optional) Browser instance.
* @return {void}
*/
function waitForPageToLoad (wdBrowser) {
if (typeof wdBrowser !== 'object') {
wdBrowser = browser;
}
withRetry(function () {
if (wdBrowser.execute("return document.readyState") !== 'complete')
throw new Error('Page did not load in time');
});
}
function getRuntimeOptions (opts) {
if (typeof opts.lbParam === 'object') {
options.lbParam = opts.lbParam;
}
if (opts.baseUrl && typeof opts.baseUrl === 'string') {
options.baseUrl = opts.baseUrl;
if (opts.forceBaseUrl && typeof opts.forceBaseUrl === 'boolean') {
options.forceBaseUrl = opts.forceBaseUrl;
}
}
if (opts.screenshotFolder && typeof opts.screenshotFolder === 'string') {
options.screenshotFolder = opts.screenshotFolder;
}
if (opts.timeout && isNumber(opts.timeout)) {
options.timeout = opts.timeout;
}
if (opts.retries && isNumber(opts.retries)) {
options.retries = opts.retries;
}
}
function isNumber (val) {
return typeof val === 'number' && !isNaN(val);
}
function isAlertPresent (wdBrowser) {
if (typeof wdBrowser !== 'object') {
wdBrowser = browser;
}
try {
wdBrowser.alertText();
return true;
} catch (e) {
return false;
}
}
function closeAlertAndGetItsText (acceptNextAlert, wdBrowser) {
if (typeof wdBrowser !== 'object') {
wdBrowser = browser;
}
try {
var alertText = wdBrowser.alertText() ;
if (acceptNextAlert) {
wdBrowser.acceptAlert();
} else {
wdBrowser.dismissAlert();
}
return alertText;
} catch (ignore) {}
}
function isEmptyArray (arr) {
return arr instanceof Array && arr.length === 0;
}
function waitFor (checkFunc, expression, timeout, pollFreq, wdBrowser) {
if (typeof wdBrowser !== 'object') {
wdBrowser = browser;
}
if (!isNumber(timeout)) {
timeout = options.timeout;
}
if (!isNumber(pollFreq)) {
pollFreq = 200;
}
var val;
var timeLeft = timeout;
while (!val) {
val = checkFunc();
if (val)
break;
if (timeLeft < 0) {
throw new Error('Timed out after ' + timeout + ' msecs waiting for expression: ' + expression);
}
wdBrowser.sleep(pollFreq);
timeLeft -= pollFreq;
}
return val;
}
function createFolderPath (path) {
var fs = require('fs');
var folders = path.split(/[/\\]+/);
path = '';
while (folders.length) {
/* This works for both absolute and relative paths, as split on an absolute path will have resulted in an array with the first bit empty. Safe for absolute Windows paths as well: */
path += folders.shift() + '/';
if (!fs.existsSync(path)) {
fs.mkdirSync(path);
} else if (!fs.statSync(path).isDirectory()) {
throw new Error("Cannot create directory '" + path + "'. File of same name already exists.");
}
}
}
/**
* Prefix a (relative) path with a base url.
*
* If the path itself is an absolute one including a domain, it'll be returned as-is, unless force is set to true, in
* which case the existing domain is replaced with the base.
*
* When optional arguments are when omitted, values from glocal options object are used.
*
* @param {string} path The path to prefix with the base url
* @param {string} base (optional) The base url
* @param {bool} force (optional) If true, force prefixing even if path is an absolute url
* @return {string} The prefixed url
*/
function addBaseUrl (path, base, force) {
if (typeof base !== 'string') {
base = options.baseUrl;
}
if (typeof force !== 'boolean') {
force = options.forceBaseUrl;
}
if (path.match(/^http/)) {
if (force) {
return path.replace(/^http(s?):\/\/[^/]+/, base).replace(/([^:])\/\/+/g, '$1/');
}
return path;
}
return (base + '/' + path).replace(/([^:])\/\/+/g, '$1/');
}
/**
* Focuses the topmost window on the stack of handles in the browser.
*
* After a WdSyncClient.browser.close() wd does not automatically restore focus
* to the previous window on the stack, so you may execute this function to
* ensure that subsequent tests won't be targeting a defunct window handle.
*
* @param {WdSyncClient.browser} wdBrowser (optional) Browser instance.
* @return {void}
*/
function refocusWindow (wdBrowser) {
if (typeof wdBrowser !== 'object') {
wdBrowser = browser;
}
var handles = wdBrowser.windowHandles();
if (handles.length) {
try {
wdBrowser.window(handles[handles.length-1]);
} catch (e) {
console.warn('Failed to automatically restore focus to topmost window on browser stack. Error:', e);
}
}
}
/**
* Tries to execute an Error throwing function, and if an error is thrown, one
* or more retries are attempted until <timeout> msecs have passed.
*
* Pauses between retries are increasing in length. The pause before the final
* retry will be half the total timeout. The pause before the second-to-last
* will be half of the last one's, and so forth. The first attempt will have the
* same pause as that of the first retry.
*
* Optional arguments use glocal values when omitted
*
* @param {function} code The code to execute
* @param {WdSyncClient.browser} wdBrowser (optional) Browser instance
* @param {number} retries (optional) The max number of retries
* @param {number} timeout (optional) The max number of msecs to keep trying
* @return {mixed} Whatever the code block returns
*/
function withRetry (code, wdBrowser, retries, timeout) {
if (typeof wdBrowser !== 'object') {
wdBrowser = browser;
}
if (!isNumber(retries)) {
retries = options.retries;
}
if (!isNumber(timeout)) {
timeout = options.timeout;
}
var durations = [timeout];
var err;
while (retries) {
durations[0] = Math.ceil(durations[0]/2);
durations.unshift(durations[0]);
--retries;
}
for (var i = 0; i < durations.length; ++i) {
try {
return code();
} catch (e) {
err = e;
wdBrowser.sleep(durations[i]);
}
}
throw(err);
}
/**
* Triggers a keyboard event on the provided wd browser element.
*
* @param {WD Element} element Target DOM element to trigger the event on
* @param {string} event Keyboard event (keyup|keydown|keypress)
* @param {keyCode} key Charcode to use
* @return {void}
*/
function keyEvent (element, event, keyCode) {
browser.execute(functionBody(function () {
var element = arguments[0];
var event = arguments[1];
var keyCode = arguments[2];
var ev = window.document.createEvent('KeyboardEvent');
if (ev.initKeyEvent)
ev.initKeyEvent(event, true, true, window, 0, 0, 0, 0, 0, keyCode);
else
ev.initKeyboardEvent(event, true, true, window, 0, 0, 0, 0, 0, keyCode);
return element.dispatchEvent(ev);
}), [element.rawElement, event, keyCode]);
}
function functionBody (func) {
return func.toString().replace(/^function[^{]+{/, '').replace(/}[^}]*$/, '');
}