-
Notifications
You must be signed in to change notification settings - Fork 1
/
Utils.java
729 lines (640 loc) · 19.5 KB
/
Utils.java
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
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
package utils;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import android.os.RemoteException;
import com.android.uiautomator.core.UiCollection;
import com.android.uiautomator.core.UiDevice;
import com.android.uiautomator.core.UiObject;
import com.android.uiautomator.core.UiObjectNotFoundException;
import com.android.uiautomator.core.UiScrollable;
import com.android.uiautomator.core.UiSelector;
import com.android.uiautomator.testrunner.UiAutomatorTestCase;
public class Utils {
public enum Orientation {
LEFT, RIGHT, UP, DOWN
};
public static final String homeDir = "/storage/sdcard0";
public static final String traceBase = homeDir + "/traces";
public static final int SPAM_BACK = 10;
public static void runAsRoot(String[] cmds) {
try {
Process p = Runtime.getRuntime().exec("su");
DataOutputStream os = new DataOutputStream(p.getOutputStream());
for (String tmpCmd : cmds) {
os.writeBytes(tmpCmd + "\n");
}
os.writeBytes("exit\n");
os.flush();
} catch (Exception e) {
e.getStackTrace();
}
}
/**
* Run a shell command as user
*
* @param cmd to launch
* @param wait for the end of the process
* @return the return code of this command (0 if ok, -1 if cmd error)
*/
public static int runAsUser(String cmd, boolean wait) {
try {
Process p = Runtime.getRuntime().exec(cmd);
if (wait)
return p.waitFor();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
return -1;
}
public static int runAsUser(String cmd) {
return runAsUser(cmd, true);
}
public static void runAsUser(String[] cmds, boolean wait) {
for (String cmd : cmds) {
runAsUser(cmd, wait);
}
}
public static void runAsUser(String[] cmds) {
runAsUser(cmds, true);
}
private static int getRand10() {
return (int)(10.0 * Math.random());
}
/**
* Create a new file in /storage/sdcard0
* @pre: /storage/sdcard0/random_seed_orig should be present and we need
* root rights (easier for us)
* @param output: name of the output file
*/
public static void createFile(String output) {
String catCommand = "cat ";
for (int i = 0; i < 100; i++) { // 50 + 100 + 50k
catCommand += homeDir + "/random_seed_" + getRand10() + " "
+ homeDir + "/random_seed_orig_" + getRand10() + " "
+ homeDir + "/random_seed_" + getRand10() + " ";
}
catCommand += "> " + homeDir + "/" + output;
String[] commands = new String[11];
for (int i = 0; i < commands.length - 1; i++) {
commands[i] = "dd if=/dev/urandom of=" + homeDir + "/random_seed_" +
i + " bs=1 count=50001";
}
commands[commands.length - 1] = catCommand;
Utils.runAsRoot(commands);
}
/**
* Launch Tcpdump on the device and save the trace in the folder app
*
* @param app
* The folder to save trace
*/
public static void launchTcpdump(String app, String iface) {
long now = new Date().getTime();
String dir = traceBase + "/" + app;
String[] commands = {
"mkdir -p " + dir,
"tcpdump -i " + iface + " -w " + dir + "/"
+ app + "_" + now + ".pcap &"
+ " echo $! > " + traceBase + "/tcpdump.pid" };
Utils.runAsRoot(commands);
}
/**
* Kill the tcpdump process launched
*/
public static void killTcpdump() {
String[] commands = {
"kill `cat " + traceBase + "/tcpdump.pid`",
"rm -f " + traceBase + "/tcpdump.pid" };
Utils.runAsRoot(commands);
}
/**
* Kill app by swiping it in the RecentApps panel
*/
public static boolean swipeApp(UiAutomatorTestCase t, String appText) {
t.getUiDevice().pressHome(); // if we're already in recent apps
try {
t.getUiDevice().pressRecentApps();
} catch (RemoteException e) {
e.printStackTrace();
return false;
}
t.sleep(1000);
boolean success = false;
UiObject app = Utils.getObjectWithText(appText);
if (success = (app == null))
System.out.println("Found!");
else {
List<UiObject> available = getElems(
"com.android.systemui:id/recents_bg_protect",
"com.android.systemui:id/app_label");
for (UiObject uiObject : available) {
try {
if (success = (uiObject.getText().equals(appText)))
break;
} catch (UiObjectNotFoundException e) {
System.out.println("App not found " + appText);
}
}
}
if (success)
swipeToEnd(app, t.getUiDevice(), Orientation.LEFT, 10);
t.getUiDevice().pressHome(); // go back home
return success;
}
public static void customAssertTrue(UiAutomatorTestCase t, String msg,
boolean succeeded) {
if (!succeeded) {
returnToHomeScreen(t);
UiAutomatorTestCase.assertTrue("msg", false);
}
}
public static void returnToHomeScreen(UiAutomatorTestCase t) {
for (int i = 0; i < SPAM_BACK; i++) {
t.getUiDevice().pressBack();
}
}
public static void killApp(String packageName) {
String[] commands = { "am force-stop " + packageName };
Utils.runAsRoot(commands);
}
public static boolean openApp(UiAutomatorTestCase t, String appText,
String packageName, String mainActivity, boolean kill)
throws UiObjectNotFoundException {
// Wake up, kill app (if found) and pressHome before opening an app
try {
t.getUiDevice().wakeUp();
t.getUiDevice().setOrientationNatural();
} catch (RemoteException e1) { // not a big deal
e1.printStackTrace();
}
if (kill)
killApp(packageName);
t.getUiDevice().pressHome();
// Try with am if possible ; else, fallback to the manual method
if (mainActivity != null) {
String cmd = "am start -n " + packageName + "/" + mainActivity;
if (runAsUser(cmd, true) == 0)
return true;
System.out.println("Not able to start " + appText + " with am");
}
UiObject allAppsButton = new UiObject(
new UiSelector().description("Apps"));
allAppsButton.clickAndWaitForNewWindow();
UiScrollable appViews = new UiScrollable(
new UiSelector().scrollable(true));
appViews.setAsHorizontalList();
boolean succeed = false;
UiObject settingsApp;
int i = 0;
/*
* It seems there is a bug: flingForward ou scrollToEnd don't go to the
* end...
*/
while (!succeed) {
try {
settingsApp = appViews.getChildByText(new UiSelector()
.className(android.widget.TextView.class.getName()),
appText, i >= 14); // do not scroll, did in the catch
succeed = true;
settingsApp.clickAndWaitForNewWindow();
}
catch (UiObjectNotFoundException e) {
// move to one new panel each time
if (i < 7 || i >= 14)
appViews.flingForward();
else
appViews.flingBackward();
}
if (i > 20)
throw new UiObjectNotFoundException("App not found");
i++;
}
// Validate that the package name is the expected one
UiObject appValidation = new UiObject(
new UiSelector().packageName(packageName));
return appValidation.exists();
}
public static boolean openApp(UiAutomatorTestCase t, String appText,
String packageName, boolean kill) throws UiObjectNotFoundException {
return openApp(t, appText, packageName, null, kill);
}
public static boolean openApp(UiAutomatorTestCase t, String appText,
String packageName, String mainActivity)
throws UiObjectNotFoundException {
return openApp(t, appText, packageName, mainActivity, true);
}
public static boolean openApp(UiAutomatorTestCase t, String appText,
String packageName) throws UiObjectNotFoundException {
return openApp(t, appText, packageName, true);
}
public static double getDoubleFromParam(UiAutomatorTestCase t, String key) {
String multTime = t.getParams().getString(key);
if (multTime == null)
return 1.;
try {
return Double.parseDouble(multTime);
} catch (NumberFormatException e) {
return 1.;
}
}
public static double getMultTime(UiAutomatorTestCase t) {
return getDoubleFromParam(t, "mult-time");
}
/////////////////////////////////////////
// UiObject //
/////////////////////////////////////////
public static UiObject getObject(String id)
throws UiObjectNotFoundException {
UiObject obj = new UiObject(new UiSelector().resourceId(id));
if (!obj.exists())
throw new UiObjectNotFoundException("Object with id " + id
+ " not found");
return obj;
}
public static UiObject getObjectWithDescription(String desc) {
return new UiObject(new UiSelector().description(desc));
}
public static UiObject getObjectWithId(String id, int instance) {
return new UiObject(new UiSelector().resourceId(id).instance(instance));
}
public static UiObject getObjectWithId(String id) {
return getObjectWithId(id, 0);
}
public static UiObject getObjectWithClassName(String className, int instance) {
return new UiObject(new UiSelector().className(className).instance(
instance));
}
public static UiObject getObjectWithClassNameAndText(String className,
String text) {
return new UiObject(new UiSelector().className(className).text(text));
}
public static UiObject getObjectWithText(String text) {
return new UiObject(new UiSelector().text(text));
}
public static UiScrollable getScrollableWithId(String id) {
return new UiScrollable(new UiSelector().resourceId(id));
}
public static UiScrollable getScrollableListView() {
return new UiScrollable(
new UiSelector().className(android.widget.ListView.class
.getName()));
}
public static boolean hasObject(String id) {
try {
return getObject(id) != null;
} catch (UiObjectNotFoundException e) {
return false;
}
}
public static boolean click(String id) {
try {
return click(getObject(id));
} catch (UiObjectNotFoundException e) {
return false;
}
}
public static boolean click(UiObject obj) {
try {
return obj.click();
} catch (UiObjectNotFoundException e) {
return false;
}
}
/**
* Click on the className UiObject containing as child the text text
*/
public static boolean click(UiScrollable list, String className, String text) {
try {
UiObject item = list.getChildByText(
new UiSelector().className(className), text, true);
return item.click();
} catch (UiObjectNotFoundException e) {
return false;
}
}
public static boolean clickOnTheMiddle(UiAutomatorTestCase t) {
UiDevice dev = t.getUiDevice();
return dev.click(dev.getDisplayWidth() / 2, dev.getDisplayHeight() / 2);
}
public static boolean clickAndWaitForNewWindow(String id) {
try {
return clickAndWaitForNewWindow(getObject(id));
} catch (UiObjectNotFoundException e) {
return false;
}
}
public static boolean clickAndWaitForNewWindow(UiObject obj) {
try {
return obj.clickAndWaitForNewWindow();
} catch (UiObjectNotFoundException e) {
return false;
}
}
public static boolean clickAndWaitLoadingWindow(UiAutomatorTestCase t,
UiObject button, String connectingId, String connectingText,
boolean checkEnable)
throws UiObjectNotFoundException {
button.click(); // just start
t.sleep(500);
// Wait for connection, max 20 sec
for (int i = 0; i < 40; i++) {
if (Utils.hasObject(connectingId)
&& Utils.hasText(connectingText, connectingText)) {
System.out.println("Still connecting");
t.sleep(500);
} else if (checkEnable)
// no object or another message, ok, we're connected if checked
return button.isChecked();
else
return true;
}
return false;
}
public static boolean longClick(UiObject obj) {
try {
return obj.longClick();
} catch (UiObjectNotFoundException e) {
return false;
}
}
public static boolean longClick(String id) {
try {
return longClick(getObject(id));
} catch (UiObjectNotFoundException e) {
return false;
}
}
public static boolean longPress(UiObject obj) {
return longPress(obj, 750);
}
public static boolean longPress(String id) {
return longPress(id, 750);
}
public static boolean longPress(UiObject obj, int msec) {
return swipe(obj, Orientation.LEFT, msec / 5);
}
public static boolean longPress(String id, int msec) {
return swipe(id, Orientation.LEFT, msec / 5);
}
public static boolean swipe(String id, Orientation orientation, int steps) {
try {
return swipe(getObject(id), orientation, steps);
} catch (UiObjectNotFoundException e) {
return false;
}
}
public static boolean swipe(UiObject obj, Orientation orientation, int steps) {
try {
switch (orientation) {
case DOWN:
return obj.swipeDown(steps);
case UP:
return obj.swipeUp(steps);
case LEFT:
return obj.swipeLeft(steps);
case RIGHT:
return obj.swipeRight(steps);
default:
return false;
}
} catch (UiObjectNotFoundException e) {
return false;
}
}
public static boolean swipeToEnd(UiObject obj, UiDevice device,
Orientation orientation, int steps) {
try {
switch (orientation) {
case DOWN:
return obj.dragTo(obj.getBounds().centerX(),
device.getDisplayHeight(), steps);
case UP:
return obj.dragTo(obj.getBounds().centerX(), 0, steps);
case LEFT:
return obj.dragTo(0, obj.getBounds().centerY(), steps);
case RIGHT:
return obj.dragTo(device.getDisplayWidth(), obj.getBounds()
.centerY(), steps);
default:
return false;
}
} catch (UiObjectNotFoundException e) {
return false;
}
}
/**
* Set `text` to object with id `id` and clear text before
*/
public static boolean setText(String id, String text, boolean clear) {
try {
return setText(getObject(id), text, clear);
} catch (UiObjectNotFoundException e) {
return false;
}
}
public static boolean setText(String id, String text) {
return setText(id, text, false);
}
/**
* Set `text` to object `obj` and clear text before
*/
public static boolean setText(UiObject obj, String text, boolean clear) {
try {
if (clear)
obj.clearTextField();
return obj.setText(text);
} catch (UiObjectNotFoundException e) {
return false;
}
}
public static boolean setText(UiObject obj, String text) {
return setText(obj, text, true);
}
public static boolean hasText(String id, String text) {
try {
return hasText(getObject(id), text);
} catch (UiObjectNotFoundException e) {
return false;
}
}
public static boolean hasText(UiObject obj, String text) {
try {
return obj.getText().equals(text);
} catch (UiObjectNotFoundException e) {
return false;
}
}
public static boolean hasTextAndClick(String id, String text) {
if (hasText(id, text))
return click(id);
return true;
}
public static boolean hasTextAndClick(UiObject obj, String text) {
if (hasText(obj, text))
return click(obj);
return true;
}
public static boolean scrollBackward(UiScrollable obj) {
try {
return obj.scrollBackward();
} catch (UiObjectNotFoundException e) {
return false;
}
}
public static boolean scrollForward(UiScrollable obj) {
try {
return obj.scrollForward();
} catch (UiObjectNotFoundException e) {
return false;
}
}
public static boolean scrollForward(UiScrollable obj, int steps) {
try {
return obj.scrollForward(steps);
} catch (UiObjectNotFoundException e) {
return false;
}
}
public static int getChildCount(UiObject obj) {
try {
return obj.getChildCount();
} catch (UiObjectNotFoundException e) {
return 0;
}
}
public static boolean swipeLeft(UiObject obj, int steps) {
try {
return obj.swipeLeft(steps);
} catch (UiObjectNotFoundException e) {
return false;
}
}
public static List<UiObject> getElems(String parentId, String childId) {
List<UiObject> childs = new ArrayList<UiObject>();
try {
UiCollection parent = new UiCollection(
new UiSelector().resourceId(parentId));
int count = parent.getChildCount(new UiSelector()
.resourceId(childId));
for (int i = 0; i < count; ++i) {
UiObject child = parent.getChild(new UiSelector().resourceId(
childId).instance(i));
childs.add(child);
}
} catch (UiObjectNotFoundException e) {
e.printStackTrace();
}
return childs;
}
/**
* Find a layout in a listView with a title name
* @param titleText title to find
* @param layoutClassName layout to find
* @param listViewId ID of the list view (if any: else should be null)
* @param titleID ID of the title widget (if != "android:id/title")
* @param minChildCount minimum child count needed
* (e.g. 2 if you need a text + a checkbox)
* @return the layout or null
* @throws UiObjectNotFoundException
*/
public static UiObject findLayoutWithTitle(String titleText,
String layoutClassName, String listViewId, String titleID,
int minChildCount)
throws UiObjectNotFoundException {
// find ListView widget
UiCollection listView;
if (listViewId != null)
listView = new UiCollection(new UiSelector().resourceId(listViewId));
else
listView = new UiCollection(
new UiSelector().className(android.widget.ListView.class
.getName()));
String tID = titleID != null ? titleID : "android:id/title";
// should have a few childs in *Layout widgets
int count = listView.getChildCount(new UiSelector()
.className(layoutClassName));
for (int i = 0; i < count; i++) {
// Get linearLayout: should have at least one title
UiObject layout = listView.getChild(new UiSelector()
.className(layoutClassName).instance(i));
if (minChildCount > 0 && layout.getChildCount() < minChildCount)
continue;
UiObject title = layout.getChild(new UiSelector().resourceId(tID));
// if we found the right entry
if (title.exists() && title.getText().equals(titleText))
return layout;
}
return null;
}
/**
* Find a layout with a text in a list
*
* @param titleText title of the text
* @param layoutClassName layout to find
* @param minChildCount minimum child count needed
* (e.g. 2 if you need a text + a checkbox)
* @param listViewId ID of the listView (if any: else should be null)
* @param titleID ID of the title widget
* @param isVertical If the list is vertical or not
* @return the layout or null
* @throws UiObjectNotFoundException
*/
public static UiObject findLayoutInList(String titleText,
String layoutClassName, int minChildCount, String listViewId,
String titleID, boolean isVertical)
throws UiObjectNotFoundException {
UiScrollable list;
if (listViewId != null)
list = Utils.getScrollableWithId(listViewId);
else
list = Utils.getScrollableListView();
if (isVertical)
list.setAsVerticalList();
else
list.setAsHorizontalList();
boolean lastCheck = false;
while (true) {
UiObject layout = findLayoutWithTitle(titleText, layoutClassName,
listViewId, titleID, minChildCount);
if (layout != null || lastCheck)
return layout;
lastCheck = !Utils.scrollForward(list); // true: end of the list
}
}
/**
* Find a checkbox linked to a title in a generic list
* @param listViewId ID of the listView (if any: else should be null)
* @param titleText title of the text
* @param checkboxID ID of the listView (if != android:id/checkbox)
* @return a checkbox or null
* @throws UiObjectNotFoundException
*/
public static UiObject findCheckBoxInListWithTitle(String listViewId,
String titleText, String checkboxID)
throws UiObjectNotFoundException {
UiObject layout = findLayoutInList(titleText,
android.widget.LinearLayout.class.getName(), 2, listViewId,
null, true);
if (layout != null)
return layout.getChild(new UiSelector()
.resourceId("android:id/checkbox"));
return null;
}
public static void checkBox(UiObject checkBox, boolean enable)
throws UiObjectNotFoundException {
if ((enable && !checkBox.isChecked())
|| (!enable && checkBox.isChecked()))
Utils.click(checkBox);
}
public static void listMoveUp(String listViewId)
throws UiObjectNotFoundException {
UiScrollable list = Utils.getScrollableWithId(listViewId);
list.setAsVerticalList();
list.scrollToBeginning(10);
}
}