forked from SideeX/sideex
-
Notifications
You must be signed in to change notification settings - Fork 0
/
locatorBuilders.js
executable file
·623 lines (570 loc) · 20.4 KB
/
locatorBuilders.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
/*
* Copyright 2005 Shinya Kasatani
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
function LocatorBuilders(window) {
this.window = window;
//this.log = new Log("LocatorBuilders");
}
LocatorBuilders.prototype.detach = function() {
if (this.window._locator_pageBot) {
//this.log.debug(this.window);
this.window._locator_pageBot = undefined;
// Firefox 3 (beta 5) throws "Security Manager vetoed action" when we use delete operator like this:
// delete this.window._locator_pageBot;
}
};
LocatorBuilders.prototype.pageBot = function() {
var pageBot = this.window._locator_pageBot;
if (pageBot == null) {
//pageBot = BrowserBot.createForWindow(this.window);
pageBot = new MozillaBrowserBot(this.window);
var self = this;
pageBot.getCurrentWindow = function() {
return self.window;
};
this.window._locator_pageBot = pageBot;
}
return pageBot;
};
LocatorBuilders.prototype.buildWith = function(name, e, opt_contextNode) {
return LocatorBuilders.builderMap[name].call(this, e, opt_contextNode);
};
LocatorBuilders.prototype.elementEquals = function(name, e, locator) {
var fe = this.findElement(locator);
//TODO: add match function to the ui locator builder, note the inverted parameters
return (e == fe) || (LocatorBuilders.builderMap[name] && LocatorBuilders.builderMap[name].match && LocatorBuilders.builderMap[name].match(e, fe));
};
LocatorBuilders.prototype.build = function(e) {
var locators = this.buildAll(e);
if (locators.length > 0) {
return locators[0][0];
} else {
return "LOCATOR_DETECTION_FAILED";
}
};
LocatorBuilders.prototype.buildAll = function(el) {
var e = core.firefox.unwrap(el); //Samit: Fix: Do the magic to get it to work in Firefox 4
var xpathLevel = 0;
var maxLevel = 10;
var locator;
var locators = [];
//this.log.debug("getLocator for element " + e);
var coreLocatorStrategies = this.pageBot().locationStrategies;
for (var i = 0; i < LocatorBuilders.order.length; i++) {
var finderName = LocatorBuilders.order[i];
//this.log.debug("trying " + finderName);
try {
locator = this.buildWith(finderName, e);
if (locator) {
locator = String(locator);
//this.log.debug("locator=" + locator);
// test the locator. If a is_fuzzy_match() heuristic function is
// defined for the location strategy, use it to determine the
// validity of the locator's results. Otherwise, maintain existing
// behavior.
// try {
// //alert(PageBot.prototype.locateElementByUIElement);
// //Samit: The is_fuzzy_match stuff is buggy - comparing builder name with a locator name usually results in an exception :(
// var is_fuzzy_match = this.pageBot().locationStrategies[finderName].is_fuzzy_match;
// if (is_fuzzy_match) {
// if (is_fuzzy_match(this.findElement(locator), e)) {
// locators.push([ locator, finderName ]);
// }
// }
// else {
// if (e == this.findElement(locator)) {
// locators.push([ locator, finderName ]);
// }
// }
// }
// catch (exception) {
// if (e == this.findElement(locator)) {
// locators.push([ locator, finderName ]);
// }
// }
//Samit: The following is a quickfix for above commented code to stop exceptions on almost every locator builder
//TODO: the builderName should NOT be used as a strategy name, create a feature to allow locatorBuilders to specify this kind of behaviour
//TODO: Useful if a builder wants to capture a different element like a parent. Use the this.elementEquals
var fe = this.findElement(locator);
if ((e == fe) || (coreLocatorStrategies[finderName] && coreLocatorStrategies[finderName].is_fuzzy_match && coreLocatorStrategies[finderName].is_fuzzy_match(fe, e))) {
locators.push([locator, finderName]);
}
}
} catch (e) {
// TODO ignore the buggy locator builder for now
//this.log.debug("locator exception: " + e);
}
}
return locators;
};
LocatorBuilders.prototype.findElement = function(locator) {
try {
return this.pageBot().findElement(locator);
} catch (error) {
//this.log.debug("findElement failed: " + error + ", locator=" + locator);
return null;
}
};
/*
* Class methods
*/
LocatorBuilders.order = [];
LocatorBuilders.builderMap = {};
LocatorBuilders._preferredOrder = [];
// NOTE: for some reasons we does not use this part
// classObservable(LocatorBuilders);
LocatorBuilders.add = function(name, finder) {
this.order.push(name);
this.builderMap[name] = finder;
this._orderChanged();
};
/**
* Call when the order or preferred order changes
*/
LocatorBuilders._orderChanged = function() {
var changed = this._ensureAllPresent(this.order, this._preferredOrder);
this._sortByRefOrder(this.order, this._preferredOrder);
if (changed) {
// NOTE: for some reasons we does not use this part
// this.notify('preferredOrderChanged', this._preferredOrder);
}
};
/**
* Set the preferred order of the locator builders
*
* @param preferredOrder can be an array or a comma separated string of names
*/
LocatorBuilders.setPreferredOrder = function(preferredOrder) {
if (typeof preferredOrder === 'string') {
this._preferredOrder = preferredOrder.split(',');
} else {
this._preferredOrder = preferredOrder;
}
this._orderChanged();
};
/**
* Returns the locator builders preferred order as an array
*/
LocatorBuilders.getPreferredOrder = function() {
return this._preferredOrder;
};
/**
* Sorts arrayToSort in the order of elements in sortOrderReference
* @param arrayToSort
* @param sortOrderReference
*/
LocatorBuilders._sortByRefOrder = function(arrayToSort, sortOrderReference) {
var raLen = sortOrderReference.length;
arrayToSort.sort(function(a, b) {
var ai = sortOrderReference.indexOf(a);
var bi = sortOrderReference.indexOf(b);
return (ai > -1 ? ai : raLen) - (bi > -1 ? bi : raLen);
});
};
/**
* Function to add to the bottom of destArray elements from source array that do not exist in destArray
* @param sourceArray
* @param destArray
*/
LocatorBuilders._ensureAllPresent = function(sourceArray, destArray) {
var changed = false;
sourceArray.forEach(function(e) {
if (destArray.indexOf(e) == -1) {
destArray.push(e);
changed = true;
}
});
return changed;
};
/*
* Utility function: Encode XPath attribute value.
*/
LocatorBuilders.prototype.attributeValue = function(value) {
if (value.indexOf("'") < 0) {
return "'" + value + "'";
} else if (value.indexOf('"') < 0) {
return '"' + value + '"';
} else {
var result = 'concat(';
var part = "";
while (true) {
var apos = value.indexOf("'");
var quot = value.indexOf('"');
if (apos < 0) {
result += "'" + value + "'";
break;
} else if (quot < 0) {
result += '"' + value + '"';
break;
} else if (quot < apos) {
part = value.substring(0, apos);
result += "'" + part + "'";
value = value.substring(part.length);
} else {
part = value.substring(0, quot);
result += '"' + part + '"';
value = value.substring(part.length);
}
result += ',';
}
result += ')';
return result;
}
};
LocatorBuilders.prototype.xpathHtmlElement = function(name) {
if (this.window.document.contentType == 'application/xhtml+xml') {
// "x:" prefix is required when testing XHTML pages
return "x:" + name;
} else {
return name;
}
};
LocatorBuilders.prototype.relativeXPathFromParent = function(current) {
var index = this.getNodeNbr(current);
var currentPath = '/' + this.xpathHtmlElement(current.nodeName.toLowerCase());
if (index > 0) {
currentPath += '[' + (index + 1) + ']';
}
return currentPath;
};
LocatorBuilders.prototype.getNodeNbr = function(current) {
var childNodes = current.parentNode.childNodes;
var total = 0;
var index = -1;
for (var i = 0; i < childNodes.length; i++) {
var child = childNodes[i];
if (child.nodeName == current.nodeName) {
if (child == current) {
index = total;
}
total++;
}
}
return index;
};
LocatorBuilders.prototype.getCSSSubPath = function(e) {
var css_attributes = ['id', 'name', 'class', 'type', 'alt', 'title', 'value'];
for (var i = 0; i < css_attributes.length; i++) {
var attr = css_attributes[i];
var value = e.getAttribute(attr);
if (value) {
if (attr == 'id')
return '#' + value;
if (attr == 'class')
return e.nodeName.toLowerCase() + '.' + value.replace(" ", ".").replace("..", ".");
return e.nodeName.toLowerCase() + '[' + attr + '="' + value + '"]';
}
}
if (this.getNodeNbr(e))
return e.nodeName.toLowerCase() + ':nth-of-type(' + this.getNodeNbr(e) + ')';
else
return e.nodeName.toLowerCase();
};
LocatorBuilders.prototype.preciseXPath = function(xpath, e) {
//only create more precise xpath if needed
if (this.findElement(xpath) != e) {
var result = e.ownerDocument.evaluate(xpath, e.ownerDocument, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
//skip first element (result:0 xpath index:1)
for (var i = 0, len = result.snapshotLength; i < len; i++) {
var newPath = 'xpath=(' + xpath + ')[' + (i + 1) + ']';
if (this.findElement(newPath) == e) {
return newPath;
}
}
}
return xpath;
}
/*
* ===== builders =====
*/
LocatorBuilders.add('ui', function(pageElement) {
return UIMap.getInstance().getUISpecifierString(pageElement,
this.window.document);
});
LocatorBuilders.add('id', function(e) {
if (e.id) {
return 'id=' + e.id;
}
return null;
});
LocatorBuilders.add('link', function(e) {
if (e.nodeName == 'A') {
var text = e.textContent;
if (!text.match(/^\s*$/)) {
return "link=" + exactMatchPattern(text.replace(/\xA0/g, " ").replace(/^\s*(.*?)\s*$/, "$1"));
}
}
return null;
});
LocatorBuilders.add('name', function(e) {
if (e.name) {
return 'name=' + e.name;
}
return null;
});
LocatorBuilders.add('css', function(e) {
var current = e;
var sub_path = this.getCSSSubPath(e);
while (this.findElement("css=" + sub_path) != e && current.nodeName.toLowerCase() != 'html') {
sub_path = this.getCSSSubPath(current.parentNode) + ' > ' + sub_path;
current = current.parentNode;
}
return "css=" + sub_path;
});
/*
* This function is called from DOM locatorBuilders
*/
LocatorBuilders.prototype.findDomFormLocator = function(form) {
if (form.hasAttribute('name')) {
var name = form.getAttribute('name');
var locator = "document." + name;
if (this.findElement(locator) == form) {
return locator;
}
locator = "document.forms['" + name + "']";
if (this.findElement(locator) == form) {
return locator;
}
}
var forms = this.window.document.forms;
for (var i = 0; i < forms.length; i++) {
if (form == forms[i]) {
return "document.forms[" + i + "]";
}
}
return null;
};
LocatorBuilders.add('dom:name', function(e) {
if (e.form && e.name) {
var formLocator = this.findDomFormLocator(e.form);
if (formLocator) {
var candidates = [formLocator + "." + e.name,
formLocator + ".elements['" + e.name + "']"
];
for (var c = 0; c < candidates.length; c++) {
var locator = candidates[c];
var found = this.findElement(locator);
if (found) {
if (found == e) {
return locator;
} else if (found instanceof NodeList) {
// multiple elements with same name
for (var i = 0; i < found.length; i++) {
if (found[i] == e) {
return locator + "[" + i + "]";
}
}
}
}
}
}
}
return null;
});
LocatorBuilders.add('xpath:link', function(e) {
if (e.nodeName == 'A') {
var text = e.textContent;
if (!text.match(/^\s*$/)) {
return this.preciseXPath("//" + this.xpathHtmlElement("a") + "[contains(text(),'" + text.replace(/^\s+/, '').replace(/\s+$/, '') + "')]", e);
}
}
return null;
});
LocatorBuilders.add('xpath:img', function(e) {
if (e.nodeName == 'IMG') {
if (e.alt != '') {
return this.preciseXPath("//" + this.xpathHtmlElement("img") + "[@alt=" + this.attributeValue(e.alt) + "]", e);
} else if (e.title != '') {
return this.preciseXPath("//" + this.xpathHtmlElement("img") + "[@title=" + this.attributeValue(e.title) + "]", e);
} else if (e.src != '') {
return this.preciseXPath("//" + this.xpathHtmlElement("img") + "[contains(@src," + this.attributeValue(e.src) + ")]", e);
}
}
return null;
});
LocatorBuilders.add('xpath:attributes', function(e) {
const PREFERRED_ATTRIBUTES = ['id', 'name', 'value', 'type', 'action', 'onclick'];
var i = 0;
function attributesXPath(name, attNames, attributes) {
var locator = "//" + this.xpathHtmlElement(name) + "[";
for (i = 0; i < attNames.length; i++) {
if (i > 0) {
locator += " and ";
}
var attName = attNames[i];
locator += '@' + attName + "=" + this.attributeValue(attributes[attName]);
}
locator += "]";
return this.preciseXPath(locator, e);
}
if (e.attributes) {
var atts = e.attributes;
var attsMap = {};
for (i = 0; i < atts.length; i++) {
var att = atts[i];
attsMap[att.name] = att.value;
}
var names = [];
// try preferred attributes
for (i = 0; i < PREFERRED_ATTRIBUTES.length; i++) {
var name = PREFERRED_ATTRIBUTES[i];
if (attsMap[name] != null) {
names.push(name);
var locator = attributesXPath.call(this, e.nodeName.toLowerCase(), names, attsMap);
if (e == this.findElement(locator)) {
return locator;
}
}
}
}
return null;
});
LocatorBuilders.add('xpath:idRelative', function(e) {
var path = '';
var current = e;
while (current != null) {
if (current.parentNode != null) {
path = this.relativeXPathFromParent(current) + path;
if (1 == current.parentNode.nodeType && // ELEMENT_NODE
current.parentNode.getAttribute("id")) {
return this.preciseXPath("//" + this.xpathHtmlElement(current.parentNode.nodeName.toLowerCase()) +
"[@id=" + this.attributeValue(current.parentNode.getAttribute('id')) + "]" +
path, e);
}
} else {
return null;
}
current = current.parentNode;
}
return null;
});
LocatorBuilders.add('xpath:href', function(e) {
if (e.attributes && e.hasAttribute("href")) {
href = e.getAttribute("href");
if (href.search(/^http?:\/\//) >= 0) {
return this.preciseXPath("//" + this.xpathHtmlElement("a") + "[@href=" + this.attributeValue(href) + "]", e);
} else {
// use contains(), because in IE getAttribute("href") will return absolute path
return this.preciseXPath("//" + this.xpathHtmlElement("a") + "[contains(@href, " + this.attributeValue(href) + ")]", e);
}
}
return null;
});
LocatorBuilders.add('dom:index', function(e) {
if (e.form) {
var formLocator = this.findDomFormLocator(e.form);
if (formLocator) {
var elements = e.form.elements;
for (var i = 0; i < elements.length; i++) {
if (elements[i] == e) {
return formLocator + ".elements[" + i + "]";
}
}
}
}
return null;
});
LocatorBuilders.add('xpath:position', function(e, opt_contextNode) {
//this.log.debug("positionXPath: e=" + e);
var path = '';
var current = e;
while (current != null && current != opt_contextNode) {
var currentPath;
if (current.parentNode != null) {
currentPath = this.relativeXPathFromParent(current);
} else {
currentPath = '/' + this.xpathHtmlElement(current.nodeName.toLowerCase());
}
path = currentPath + path;
var locator = '/' + path;
if (e == this.findElement(locator)) {
return locator;
}
current = current.parentNode;
//this.log.debug("positionXPath: current=" + current);
}
return null;
});
/*
//Chi-En Huang, SELAB, CSIE, NCKU, 2016/01/06
LocatorBuilders.add('tac', function(e) {
//this.log.debug("tac: e=" + e);
var l;
var c;
var od;
var d;
for (d = e; d.parentElement != null; d = d.parentElement) {}
var h = d.ownerDocument.getElementsByTagName("HTML");
var hs = h.length;
for (var i = 0; i < hs; i++) {
if (h[i] == null) {
continue;
}
var hc = h[i].children;
var hcs = hc.length;
for (var j = 0; j < hcs; j++) {
if (hc[j] == null) {
continue;
}
if (hc[j].tagName == "DIV") {
h[i].removeChild(hc[j]);
}
}
}
var nse = d.ownerDocument.getElementsByTagName("NOSCRIPT");
var nses = nse.length;
for (var i = 0; i < nses; i++) {
nse[i].innerHTML = "";
}
l = "";
c = e;
od = d.outerHTML;
while (c != null) {
if (c.parentElement != null) {
var se = c.parentElement.children;
var tc = 0;
var ttc = 0;
var ifd = false;
for (var i = 0; i < se.length; i++) {
if (se[i].tagName == c.tagName && !ifd) {
tc++;
ttc++;
} else if (se[i].tagName == c.tagName) {
ttc++;
}
if (se[i] == c) {
ifd = true;
}
}
if (ttc > 1) {
l = "/" + c.tagName.toLowerCase() + "[" + tc + "]" + l;
} else {
l = "/" + c.tagName.toLowerCase() + l;
}
} else {
l = "/" + c.tagName.toLowerCase() + l;
if (true) {
var sideex = "tac=" + l + "::[tac]::" + od;
return sideex;
}
}
c = c.parentElement;
}
return null;
});
*/
// Samit: Warning: The old method of setting the order using LocatorBuilders.order is now deprecated
// You can change the priority of builders by setting LocatorBuilders.order.
//LocatorBuilders.order = ['ui', 'id', 'link', 'name', 'css', 'dom:name', 'xpath:link', 'xpath:img', 'xpath:attributes', 'xpath:idRelative', 'xpath:href', 'dom:index', 'xpath:position'];