forked from vkolgi/tuneup_js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
uiautomation-ext.js
644 lines (561 loc) · 19.2 KB
/
uiautomation-ext.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
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
#import "assertions.js";
#import "lang-ext.js";
extend(UIATableView.prototype, {
/**
* A shortcut for:
* this.cells().firstWithName(name)
*/
cellNamed: function (name) {
return this.cells().firstWithName(name);
},
/**
* Asserts that this table has a cell with the name (accessibility label)
* matching the given +name+ argument.
*/
assertCellNamed: function (name) {
assertNotNull(this.cellNamed(name), "No table cell found named '" + name + "'");
}
});
var isNotNil = function () {
var ret = undefined !== this && null != this && this.toString() != "[object UIAElementNil]";
return ret;
};
extend(UIAElement.prototype, {
/**
* Dump tree in json format for copy/paste use in AssertWindow and friends
*/
elementJSONDump: function (recursive, attributes, visibleOnly) {
if (visibleOnly && !this.isVisible()) {
return "";
}
if (!attributes) {
attributes = ["name", "label", "value", "isVisible"];
}
else if (attributes == 'ALL') {
attributes = ["name",
"label",
"value"
].concat(this.getMethods().filter(function (method) {
return method.match(/^(is|has)/)
}));
}
var jsonStr = "";
attributes.forEach(function (attr) {
try {
var value = this[attr]();
if (value != null) { //don't print null values
var valueType = typeof (value);
//quote strings and numbers. true/false unquoted.
if (valueType == "string" || valueType == "number") {
value = "'" + value + "'";
}
jsonStr += attr + ': ' + value + ',\n';
}
}
catch (e) {}
}, this);
if (recursive) {
var children = this.elements().toArray();
if (children.length > 0) {
var curType = null;
children.sort().forEach(function (child) {
function elementTypeToUIAGetter(elementType, parent) {
//almost all types follow a simple name to getter convention.
//UIAImage => images. UIAWindow => windows.
var getter = elementType.substring(3).lcfirst() + 's';
if (elementType == "UIACollectionCell" || elementType == "UIATableCell") {
getter = "cells";
}
if (parent && !eval('parent.' + getter)) {
//Note: we can't use introspection to list valid methods on the parents
//because they are all "native" methods and aren't visible.
//so the valid getter must be looked up in the documentation and mapped above
UIALogger.logError("elementTypeToUIAGetter could not determine getter for " + elementType);
}
return elementType.substring(3).lcfirst() + 's';
}
var objType = Object.prototype.toString.call(child); //[object UIAWindow]
objType = objType.substring(8, objType.length - 1); //UIAWindow
// there's a bug that causes leaf elements to have child references
// back up to UIAApplication, thus the check for that
// this means we can't dump from the "target" level - only mainWindow and below
// hopefully this bug goes away 2013-07-02
if (objType == "UIAApplication" || objType == "UIAElementNil" || (visibleOnly && !child.isVisible())) {
//skip this child
return;
}
if (objType == "UIACollectionCell" && !this.isVisible()) {
//elements() shows invisible cells that cells() does not
return;
}
if (curType && curType != objType) {
//close off open list
jsonStr += "],\n";
}
if (!curType || curType != objType) {
curType = objType;
//open a new list
jsonStr += elementTypeToUIAGetter(objType, this) + ": [\n";
}
var childJsonStr = child.elementJSONDump(true, attributes, visibleOnly);
if (childJsonStr) {
jsonStr += "{\n";
jsonStr += childJsonStr.replace(/^/gm, " ").replace(/ $/, '');
jsonStr += "},\n";
}
else {
//child has no attributes to report (all null)
jsonStr += " null,\n";
}
}, this);
if (curType) {
//close off open list
jsonStr += "],\n";
}
}
}
return jsonStr;
},
logElementJSON: function (attributes) {
//TODO dump the path to the object in the debug line
//ex: target.frontMostApp().mainWindow().toolbars()[0].buttons()["Library"]
UIALogger.logDebug("logElementJSON: " + (attributes ? "[" + attributes + "]" : '') + "\n" + this.elementJSONDump(false, attributes));
},
logVisibleElementJSON: function (attributes) {
//TODO dump the path to the object in the debug line
//ex: target.frontMostApp().mainWindow().toolbars()[0].buttons()["Library"]
UIALogger.logDebug("logVisibleElementJSON: " + (attributes ? "[" + attributes + "]" : '') + "\n" + this.elementJSONDump(false, attributes, true));
},
logElementTreeJSON: function (attributes) {
UIALogger.logDebug("logElementTreeJSON: " + (attributes ? "[" + attributes + "]" : '') + "\n" + this.elementJSONDump(true, attributes));
},
logVisibleElementTreeJSON: function (attributes) {
UIALogger.logDebug("logVisibleElementTreeJSON: " + (attributes ? "[" + attributes + "]" : '') + "\n" + this.elementJSONDump(true, attributes, true));
},
/**
* Poll till the item becomes visible, up to a specified timeout
*/
waitUntilVisible: function (timeoutInSeconds) {
this.waitUntil(function (element) {
return element;
}, function (element) {
return element.isVisible();
}, timeoutInSeconds, "to become visible");
},
/**
* Wait until element becomes invisible
*/
waitUntilInvisible: function (timeoutInSeconds) {
this.waitUntil(function (element) {
return element;
}, function (element) {
return !element.isVisible();
}, timeoutInSeconds, "to become invisible");
},
/**
* Wait until child element with name is added
*/
waitUntilFoundByName: function (name, timeoutInSeconds) {
this.waitUntil(function (element) {
return element.elements().firstWithName(name);
}, function (element) {
return element.isValid();
}, timeoutInSeconds, ["to become valid (with name '", name, "')"].join(""));
},
/**
* Wait until child element with name is removed
*/
waitUntilNotFoundByName: function (name, timeoutInSeconds) {
this.waitUntil(function (element) {
return element.elements().firstWithName(name);
}, function (element) {
return !element.isValid();
}, timeoutInSeconds, ["to become invalid (with name '", name, "'')"].join(""));
},
/**
* Wait until lookup_function(this) returns a valid lookup
* For convenience, return the element that was found
* Allow a label for more helpful error messages
*/
waitUntilAccessorSuccess: function (lookup_function, timeoutInSeconds, label) {
var isNotUseless = function (elem) {
return elem !== null && elem.isNotNil();
}
// this function will be referenced in waitUntil -- it supplies
// the name of what we are waiting for
var label_fn = function () {
return label;
}
if (!isNotUseless(this)) {
throw "waitUntilAccessorSuccess: won't work because the top element isn't valid";
}
this.waitUntil(function (element) {
// annotate the found elements with the label function if they are nil
try {
var possibleMatch = lookup_function(element);
if (!possibleMatch.isNotNil() && label !== undefined) possibleMatch.label = label_fn;
return possibleMatch;
}
catch (e) {
var fakeNil = new UIAElementNil();
if (label !== undefined) fakeNil.label = label_fn;
return fakeNil;
}
}, isNotUseless,
timeoutInSeconds, "to become an acceptable return value from the given function");
return lookup_function(this);
},
/**
* Wait until the element has the given name
*/
waitUntilHasName: function (name, timeoutInSeconds) {
this.waitUntil(function (element) {
return element;
}, function (element) {
return element.name() == name;
}, timeoutInSeconds, "to have the name '" + name + "'");
},
/**
* Wait until element fulfills condition
*/
waitUntil: function (filterFunction, conditionFunction, timeoutInSeconds, description) {
timeoutInSeconds = timeoutInSeconds == null ? 5 : timeoutInSeconds;
var element = this;
var delay = 0.25;
UIATarget.localTarget().pushTimeout(0);
try {
retry(function () {
var filteredElement = filterFunction(element);
if (!conditionFunction(filteredElement)) {
if (!(filteredElement !== null && filteredElement.isNotNil())) {
var label = (filteredElement && filteredElement.label) ? filteredElement.label() : "Element";
// make simple error message if the element doesn't exist
throw ([label, "failed", description,
"within", timeoutInSeconds, "seconds."
].join(" "));
}
else {
// build a detailed error message with all available info on the current element
var elementDescription = filteredElement.toString();
if (filteredElement.name !== undefined) {
var elemName = filteredElement.name();
if (elemName !== null && elemName != "") {
elementDescription += " with name '" + elemName + "'";
}
}
throw (["Element", elementDescription,
"failed", description,
"within", timeoutInSeconds, "seconds."
].join(" "));
}
}
}, Math.max(1, timeoutInSeconds / delay), delay);
}
catch (e) {
throw e;
}
finally {
UIATarget.localTarget().popTimeout();
}
},
/**
* A shortcut for waiting an element to become visible and tap.
*/
vtap: function (timeout) {
if (undefined === timeout) timeout = 10;
this.waitUntilVisible(timeout);
this.tap();
},
/**
* A shortcut for scrolling to a visible item and and tap.
*/
svtap: function (timeout) {
if (undefined === timeout) timeout = 1;
try {
this.scrollToVisible();
} catch (e) {
// iOS 6 hack when no scrolling is needed
if (e.toString() != "scrollToVisible cannot be used on the element because it does not have a scrollable ancestor.") {
throw e;
}
}
//this.waitUntilVisible(timeout);
this.tap();
},
/**
* A shortcut for touching an element and waiting for it to disappear.
*/
tapAndWaitForInvalid: function () {
this.tap();
this.waitForInvalid();
},
isNotNil: isNotNil,
});
extend(UIAElementNil.prototype, {
isNotNil: function () {
return false;
},
isValid: function () {
return false;
},
isVisible: function () {
return false;
}
});
extend(UIAApplication.prototype, {
/**
* A shortcut for getting the current view controller's title from the
* navigation bar. If there is no navigation bar, this method returns null
*/
navigationTitle: function () {
navBar = this.mainWindow().navigationBar();
if (navBar) {
return navBar.name();
}
return null;
},
/**
* A shortcut for checking that the interface orientation in either
* portrait mode
*/
isPortraitOrientation: function () {
var orientation = this.interfaceOrientation();
return orientation == UIA_DEVICE_ORIENTATION_PORTRAIT ||
orientation == UIA_DEVICE_ORIENTATION_PORTRAIT_UPSIDEDOWN;
},
/**
* A shortcut for checking that the interface orientation in one of the
* landscape orientations.
*/
isLandscapeOrientation: function () {
var orientation = this.interfaceOrientation();
return orientation == UIA_DEVICE_ORIENTATION_LANDSCAPELEFT ||
orientation == UIA_DEVICE_ORIENTATION_LANDSCAPERIGHT;
}
});
extend(UIANavigationBar.prototype, {
/**
* Asserts that the left button's name matches the given +name+ argument
*/
assertLeftButtonNamed: function (name) {
assertEquals(name, this.leftButton().name());
},
/**
* Asserts that the right button's name matches the given +name+ argument
*/
assertRightButtonNamed: function (name) {
assertEquals(name, this.rightButton().name());
}
});
extend(UIATarget.prototype, {
/**
* A shortcut for checking that the interface orientation in either
* portrait mode
*/
isPortraitOrientation: function () {
var orientation = this.deviceOrientation();
return orientation == UIA_DEVICE_ORIENTATION_PORTRAIT ||
orientation == UIA_DEVICE_ORIENTATION_PORTRAIT_UPSIDEDOWN;
},
/**
* A shortcut for checking that the interface orientation in one of the
* landscape orientations.
*/
isLandscapeOrientation: function () {
var orientation = this.deviceOrientation();
return orientation == UIA_DEVICE_ORIENTATION_LANDSCAPELEFT ||
orientation == UIA_DEVICE_ORIENTATION_LANDSCAPERIGHT;
},
/**
* Determine if we are running on a simulator.
*/
isSimulator: function() {
return this.model().match(/Simulator/) !== null;
},
/**
* A convenience method for detecting that you're running on an iPad
*/
isDeviceiPad: function () {
//model is iPhone Simulator, even when running in iPad mode
return this.model().match(/^iPad/) !== null ||
this.name().match(/iPad Simulator/) !== null;
},
/**
* A convenience method for detecting that you're running on an
* iPhone or iPod touch
*/
isDeviceiPhone: function () {
return this.model().match(/^iPad/) === null &&
this.name().match(/^iPad Simulator$/) === null;
},
/**
* A shortcut for checking if target device is iPhone 5 (or iPod Touch
* 5th generation)
*/
isDeviceiPhone5: function () {
var isIphone = this.isDeviceiPhone();
var deviceScreen = this.rect();
return isIphone && deviceScreen.size.height == 568;
},
/**
* A convenience method for producing screenshots without status bar
*/
captureAppScreenWithName: function (imageName) {
var appRect = this.rect();
appRect.origin.y += 20.0;
appRect.size.height -= 20.0;
return this.captureRectWithName(appRect, imageName);
},
logDeviceInfo: function () {
UIALogger.logMessage("Dump Device:");
UIALogger.logMessage(" model: " + this.model());
UIALogger.logMessage(" rect: " + JSON.stringify(this.rect()));
UIALogger.logMessage(" name: " + this.name());
UIALogger.logMessage(" systemName: " + this.systemName());
UIALogger.logMessage(" systemVersion: " + this.systemVersion());
}
});
extend(UIAKeyboard.prototype, {
KEYBOARD_TYPE_UNKNOWN: -1,
KEYBOARD_TYPE_ALPHA: 0,
KEYBOARD_TYPE_ALPHA_CAPS: 1,
KEYBOARD_TYPE_NUMBER_AND_PUNCTUATION: 2,
KEYBOARD_TYPE_NUMBER: 3,
keyboardType: function () {
if (this.keys().length < 12) {
return this.KEYBOARD_TYPE_NUMBER;
}
else if (this.keys().firstWithName("a").isNotNil()) {
return this.KEYBOARD_TYPE_ALPHA;
}
else if (this.keys().firstWithName("A").isNotNil()) {
return this.KEYBOARD_TYPE_ALPHA_CAPS;
}
else if (this.keys().firstWithName("1").isNotNil()) {
return this.KEYBOARD_TYPE_NUMBER_AND_PUNCTUATION;
}
else {
return this.KEYBOARD_TYPE_UNKNOWN;
}
}
});
var typeString = function (pstrString, pbClear) {
pstrString = pstrString.toString();
// handle keyboard not being focused
if (!this.hasKeyboardFocus()) {
this.tap();
}
var kb, db; // keyboard, deleteButton
var seconds = 2;
var waitTime = 0.25;
var maxAttempts = seconds / waitTime;
var noSuccess = true;
var failMsg = null;
// attempt to get a successful keypress several times -- using the first character
// this is a hack for iOS 6.x where the keyboard is sometimes "visible" before usable
while ((pbClear || noSuccess) && 0 < maxAttempts--) {
try {
kb = target.frontMostApp().keyboard();
// handle clearing
if (pbClear) {
db = kb.buttons()["Delete"];
if (!db.isNotNil()) db = kb.keys()["Delete"]; // compatibilty hack
// touchAndHold doesn't work without this next line... not sure why :(
db.tap();
pbClear = false; // prevent clear on next iteration
db.touchAndHold(3.7);
}
if (pstrString.length !== 0) {
kb.typeString(pstrString.charAt(0));
}
noSuccess = false; // here + no error caught means done
}
catch (e) {
failMsg = e;
UIATarget.localTarget().delay(waitTime);
}
}
// report any errors that prevented success
if (0 > maxAttempts && null !== failMsg) throw "typeString caught error: " + failMsg.toString();
// now type the rest of the string
if (pstrString.length > 0) kb.typeString(pstrString.substr(1));
};
extend(UIATextField.prototype, {
typeString: typeString,
clear: function () {
this.typeString("", true);
}
});
extend(UIATextView.prototype, {
typeString: typeString,
clear: function () {
this.typeString("", true);
}
});
extend(UIAPickerWheel.prototype, {
/*
* Better implementation than UIAPickerWheel.selectValue
* Works also for texts
* Poorly works not for UIDatePickers -> because .values() which get all values of wheel does not work :(
* I think this is a bug in UIAutomation!
*/
scrollToValue: function (valueToSelect) {
var element = this;
var values = this.values();
var pickerValue = element.value();
// convert to string
valueToSelect = valueToSelect + "";
// some wheels return for .value() "17. 128 of 267" ?? don't know why
// throw away all after "." but be careful lastIndexOf is used because the value can
// also have "." in it!! e.g.: "1.2. 13 of 27"
if (pickerValue.lastIndexOf(".") != -1) {
var currentValue = pickerValue.substr(0, pickerValue.lastIndexOf("."));
}
else {
var currentValue = element.value();
}
var currentValueIndex = values.indexOf(currentValue);
var valueToSelectIndex = values.indexOf(valueToSelect);
if (valueToSelectIndex == -1) {
fail("value: " + valueToSelect + " not found in Wheel!");
}
var elementsToScroll = valueToSelectIndex - currentValueIndex;
UIALogger.logDebug("number of elements to scroll: " + elementsToScroll);
if (elementsToScroll > 0) {
for (i = 0; i < elementsToScroll; i++) {
element.tapWithOptions({
tapOffset: {
x: 0.35,
y: 0.67
}
});
target.delay(0.7);
}
}
else {
for (i = 0; i > elementsToScroll; i--) {
element.tapWithOptions({
tapOffset: {
x: 0.35,
y: 0.31
}
});
target.delay(0.7);
}
}
},
/*
* Wheels filled with values return for .value() "17. 128 of 267"
* ?? don't know why -> for comparisons this is unuseful!!
* If you want to check a value of a wheel this function is very helpful
*/
realValue: function () {
// current value of wheel
var pickerValue = this.value();
// throw away all after "." but be careful lastIndexOf is used because the value can
if (pickerValue.lastIndexOf(".") != -1) {
return pickerValue.substr(0, pickerValue.lastIndexOf("."));
}
return this.value();
}
});