aboutsummaryrefslogtreecommitdiff
path: root/libs/UiAutomatorLib/src/com/android/afwtest/uiautomator/utils/WidgetUtils.java
blob: 1c2b8095f24e0cab5fed2d4f70acb4b40facd28f (plain)
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
/*
 * Copyright (C) 2016 The Android Open Source Project
 *
 * 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.
 */

package com.android.afwtest.uiautomator.utils;

import android.graphics.Rect;
import android.support.test.uiautomator.BySelector;
import android.support.test.uiautomator.Direction;
import android.support.test.uiautomator.StaleObjectException;
import android.support.test.uiautomator.UiDevice;
import android.support.test.uiautomator.UiObject;
import android.support.test.uiautomator.UiObject2;
import android.support.test.uiautomator.UiObjectNotFoundException;
import android.support.test.uiautomator.UiScrollable;
import android.support.test.uiautomator.UiSelector;
import android.support.test.uiautomator.Until;
import android.util.Log;
import android.widget.TextView;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * Widget utils.
 */
public class WidgetUtils {

    private static final String TAG = "afwtest.WidgetUtils";

    /**
     * Waiting time for each call to UiDevice.wait().
     */
    private static final long DEFAULT_UI_WAIT_TIME_MS = TimeUnit.SECONDS.toMillis(5);

    /**
     * Number of attempts to call {@link UiDevice#wait()} to avoid {@link StaleObjectException}.
     */
    private static final int DEFAULT_UI_ATTEMPTS_COUNT = 3;

    /**
     * Margin of swipe's starting and ending points inside the target.
     */
    private static final float DEFAULT_SWIPE_DEADZONE_PCT = 0.1f;

    /**
     * Swipe's length as object's dimension percentage.
     */
    private static final float DEFAULT_SWIPE_PCT = 0.7f;

    /**
     * Clicks on given {@link UiObject2} without throwing any exception.
     *
     * @param obj {@link UiObject2} to click
     * @return {@code true} if clicked, {@code false} otherwise
     */
    public static boolean safeClick(UiObject2 obj) {
        String widgetProps = getWidgetPropertiesAsString(obj);
        try {
            obj.click();
            Log.d(TAG, String.format("Clicked: %s", widgetProps));
            return true;
        } catch(Exception e) {
            Log.e(TAG, String.format("Failed to click: %s", widgetProps) , e);
            return false;
        }
    }

    /**
     * Tries to click any of the given list of buttons; return if any button
     * clicked successfully.
     *
     * @param btns list of buttons to click
     * @return {@code true} if any button clicked successfully; {@code false} otherwise
     */
    public static boolean safeClickAny(List<UiObject2> btns) {
        for (UiObject2 obj : btns) {
            if (safeClick(obj)) {
                return true;
            }
        }

        return false;
    }

    /**
     * Perform fling gesture on given {@link UiObject2} until it cannot scroll any more without
     * throwing any exception.
     *
     * @param obj {@link UiObject2} to scroll
     * @param direction The direction in which to fling
     * @return {@code true} if fling performed, {@code false} otherwise
     */
    public static boolean safeFling(UiObject2 obj, Direction direction) {
        String widgetProps = getWidgetPropertiesAsString(obj);

        try {
            // Set limit to 100 times.
            for (int i = 0; i < 100; ++i) {
                if (!obj.fling(direction)) {
                    break;
                }
            }
            Log.d(TAG, String.format("Scrolled: %s", widgetProps));
            return true;
        } catch(Exception e) {
            Log.e(TAG, String.format("Failed to scroll: %s", widgetProps), e);
            return false;
        }
    }

    /**
     * Waits for a widget without throwing any exception (N attempts).
     *
     * @param uiDevice {@link UiDevice} object
     * @param selector {@link BySelector} of the widget to wait
     * @param timeoutMS timeout in milliseconds
     * @param attempts number of attempts.
     * @return {@link UiObject2} if expected widget appears within timeout, {@code null} otherwise
     */
    public static UiObject2 safeWait(UiDevice uiDevice, BySelector selector, long timeoutMS,
            int attempts) {
        for (int i = 0; i < attempts; ++i) {
            UiObject2 widget = safeWait(uiDevice, selector, timeoutMS);
            if (widget != null) {
                return  widget;
            }
        }

        return null;
    }

    /**
     * Waits for a widget without throwing any exception.
     *
     * @param uiDevice {@link UiDevice} object
     * @param selector {@link BySelector} of the widget to wait
     * @param timeoutMS timeout in milliseconds
     * @return {@link UiObject2} if expected widget appears within timeout, {@code null} otherwise
     */
    public static UiObject2 safeWait(UiDevice uiDevice, BySelector selector, long timeoutMS) {
        try {
            return uiDevice.wait(Until.findObject(selector), timeoutMS);
        } catch (Exception e) {
            Log.e(TAG, "Failed to wait for widget ", e);
        }

        return null;
    }

    /**
     * Waits for a widget without throwing any exception.
     *
     * @param uiDevice {@link UiDevice} object
     * @param selector {@link BySelector} of the widget to wait
     * @return {@link UiObject2} if expected widget appears within default timeout,
     *         {@code null} otherwise
     */
    public static UiObject2 safeWait(UiDevice uiDevice, BySelector selector) {
        return safeWait(uiDevice, selector, DEFAULT_UI_WAIT_TIME_MS, DEFAULT_UI_ATTEMPTS_COUNT);
    }

    /**
     * Waits for a widget and click on it without throwing any exception.
     *
     * @param uiDevice {@link UiDevice} object
     * @param selector {@link BySelector} of the widget to wait
     * @return {@code true} if click action was performed, {@code false} otherwise.
     */
    public static boolean safeWaitAndClick(UiDevice uiDevice, BySelector selector) {
        try {
            waitAndClick(uiDevice, selector);
            return true;
        } catch (Exception e) {
            Log.e(TAG, "Failed to wait and click for widget ", e);
        }

        return false;
    }

    /**
     * Waits for a widget and click on it.
     *
     * @param uiDevice {@link UiDevice} object
     * @param selector {@link BySelector} of the widget to wait
     */
    public static void waitAndClick(UiDevice uiDevice, BySelector selector)
            throws Exception {
        waitAndClick(uiDevice, selector, DEFAULT_UI_WAIT_TIME_MS, DEFAULT_UI_ATTEMPTS_COUNT);
    }

    /**
     * Waits and click on a child widget without throwing any exception.
     *
     * @param uiDevice {@link UiDevice} object
     * @param parent {@link BySelector} of the parent widget to wait
     * @param child {@link BySelector} of the child widget to wait
     * @param timeoutMS timeout in milliseconds
     * @return {@code true} if click action was performed, {@code false} otherwise
     */
    public static boolean safeWaitAndClick(UiDevice uiDevice, BySelector parent, BySelector child,
            long timeoutMS) {
        try {
            waitAndClick(uiDevice, parent, child, timeoutMS);
            return true;
        } catch (Exception e) {
            Log.e(TAG, "Failed to wait and click on child widget ", e);
        }

        return false;
    }

    /**
     * Waits and click on a child widget.
     *
     * @param uiDevice {@link UiDevice} object
     * @param parent {@link BySelector} of the parent widget to wait
     * @param child {@link BySelector} of the child widget to wait
     * @param timeoutMS timeout in milliseconds
     */
    public static void waitAndClick(UiDevice uiDevice, BySelector parent, BySelector child,
            long timeoutMS) throws Exception {
        UiObject2 object = wait(uiDevice, parent, child, timeoutMS);
        if (object == null) {
            throw new Exception(String.format("Child widget(%s) not found", child.toString()));
        }
        object.click();
    }

    /**
     * Waits for a child object into a parent widget.
     *
     * @param uiDevice {@link UiDevice} object
     * @param parent {@link BySelector} of the parent widget to wait
     * @param child {@link BySelector} of the child widget to wait
     * @param timeoutMS timeout in milliseconds
     * @return {@link UiObject2} if expected widget appears within timeout, {@code null} otherwise
     */
    public static UiObject2 wait(UiDevice uiDevice, BySelector parent, BySelector child,
            long timeoutMS) throws Exception {

        UiObject2 parentWidget = WidgetUtils.safeWait(uiDevice, parent, timeoutMS);
        if (parentWidget == null) {
            throw new Exception(String.format("Parent(%s) widget not found", parent.toString()));
        }

        return parentWidget.findObject(child);
    }

    /**
     * Waits for a widget and click on it without throwing any exception.
     *
     * @param uiDevice {@link UiDevice} object
     * @param selector {@link BySelector} of the widget to wait
     * @param timeoutMS timeout in milliseconds
     * @return {@code true} if click action was performed, {@code false} otherwise.
     */
    public static boolean safeWaitAndClick(UiDevice uiDevice, BySelector selector, long timeoutMS) {
        try {
            waitAndClick(uiDevice, selector, timeoutMS);
            return true;
        } catch (Exception e) {
            Log.e(TAG, "Failed to wait and click for widget ", e);
        }

        return false;
    }

    /**
     * Waits for a widget and click on it (N attempts).
     *
     * @param uiDevice {@link UiDevice} object
     * @param selector {@link BySelector} of the widget to wait
     * @param timeoutMS timeout in milliseconds
     * @param attempts number of attempts
     */
    public static void waitAndClick(UiDevice uiDevice, BySelector selector, long timeoutMS,
            int attempts) throws Exception {
        for (int i = 0; i < attempts; ++i) {
            if(safeWaitAndClick(uiDevice, selector, timeoutMS)) {
                return;
            }
        }

        throw new Exception(String.format("UI object not found: %s after %d attempts",
                selector.toString(),
                attempts));
    }

    /**
     * Waits for a widget and click on it.
     *
     * @param uiDevice {@link UiDevice} object
     * @param selector {@link BySelector} of the widget to wait
     * @param timeoutMS timeout in milliseconds
     */
    public static void waitAndClick(UiDevice uiDevice, BySelector selector, long timeoutMS)
            throws Exception {
        UiObject2 object = uiDevice.wait(Until.findObject(selector), timeoutMS);
        if (object == null) {
            throw new Exception(String.format("UI object not found: %s", selector.toString()));
        }
        object.click();
    }

    /**
     * Waits for all elements with given {@link BySelector} to be gone.
     *
     * @param uiDevice {@link UiDevice} object
     * @param selector {@link BySelector} of the UI elements to wait
     * @param timeoutMs timeout in mmilliseconds
     */
    public static void waitToBeGone(UiDevice uiDevice, BySelector selector, long timeoutMs)
            throws Exception {
        uiDevice.wait(Until.gone(selector), timeoutMs);
    }

    /**
     * Waits for all elements with given {@link BySelector} to be gone.
     *
     * @param uiDevice {@link UiDevice} object
     * @param selector {@link BySelector} of the UI elements to wait
     */
    public static void waitToBeGone(UiDevice uiDevice, BySelector selector) throws Exception {
        waitToBeGone(uiDevice, selector, DEFAULT_UI_WAIT_TIME_MS);
    }

    /**
     * Scrolls a scrollable UI widget so that an item with certain {@link TextView} text is in view.
     *
     * @param container Selector for the scrollable widget.
     * @param item Text that appears in the target item.
     * @return The target item as a {@link UiObject} when it first appears, or {@code null} if
     *         not found.
     * @throws UiObjectNotFoundException If the scrollable does not exist.
     */
    public static UiObject scrollToItem(UiSelector container, String item)
            throws UiObjectNotFoundException {
        UiSelector itemSelector = new UiSelector().className(TextView.class).text(item);
        return scrollToItem(container, itemSelector);
    }

    /**
     * Scrolls a scrollable UI widget so that a certain item is in view.
     *
     * @param container Selector for the scrollable widget.
     * @param item Selector that specifies the target item.
     * @return The target item as a {@link UiObject} when it first appears, or {@code null} if
     *         not found.
     * @throws UiObjectNotFoundException If the scrollable does not exist.
     */
    public static UiObject scrollToItem(UiSelector container, UiSelector item)
            throws UiObjectNotFoundException {
        UiScrollable scrollable = new UiScrollable(container);
        if (!scrollable.waitForExists(DEFAULT_UI_WAIT_TIME_MS)) {
            throw new UiObjectNotFoundException("Cannot find scrollable " + scrollable);
        }

        if (scrollable.scrollIntoView(item)) {
            return scrollable.getChild(item);
        } else {
            return null;
        }
    }

    /**
     * Scrolls vertically a scrollable UI widget so that a certain item is in view.
     *
     * @param uiDevice current {@link UiDevice}.
     * @param container {@link BySelector} of a scrollable container.
     * @param item {@link BySelector} of an item to scroll to.
     * @return The target item as a {@link UiObject2} when it first appears, or {@code null} if
     *         not found.
     * @throws UiObjectNotFoundException If the scrollable does not exist.
     */
    public static UiObject2 scrollToItem(UiDevice uiDevice,
            BySelector container,
            BySelector item) throws UiObjectNotFoundException {
        return scrollToItem(uiDevice, container, item, false);
    }

    /**
     * Scrolls a scrollable UI widget so that a certain item is in view.
     *
     * @param uiDevice current {@link UiDevice}.
     * @param container {@link BySelector} of a scrollable container.
     * @param item {@link BySelector} of an item to scroll to.
     * @param isHorizontal {@code true} if scrollable is horizontal, {@code false} otherwise.
     * @return The target item as a {@link UiObject2} when it first appears, or {@code null} if
     *         not found.
     * @throws UiObjectNotFoundException If the scrollable does not exist.
     */
    public static UiObject2 scrollToItem(UiDevice uiDevice,
            BySelector container,
            BySelector item,
            boolean isHorizontal) throws UiObjectNotFoundException {

        // Find scrollable object
        final UiObject2 scrollable = safeWait(uiDevice, container);
        if (scrollable == null) {
            throw new UiObjectNotFoundException("Cannot find scrollable " + container);
        }

        setGestureMargins(scrollable, DEFAULT_SWIPE_DEADZONE_PCT);

        // Determine scrolling direction
        final Direction scrollDirection = isHorizontal ? Direction.RIGHT : Direction.DOWN;
        final Direction oppositeDirection = Direction.reverse(scrollDirection);

        // Scroll to the beginning of the scrollable
        while (scrollable.scroll(oppositeDirection, DEFAULT_SWIPE_PCT));

        // Scroll while target item is not visible and scrolling is still possible
        UiObject2 foundItem = scrollable.findObject(item);
        boolean isScrollingPossible = true;
        while (foundItem == null && isScrollingPossible) {
            isScrollingPossible = scrollable.scroll(scrollDirection, DEFAULT_SWIPE_PCT);
            foundItem = scrollable.findObject(item);
        }
        uiDevice.waitForIdle();
        return foundItem;
    }

    /**
     * Set target object's gesture margins.
     * @param target target object.
     * @param marginPct gesture margin as target's dimension percentage.
     */
    private static void setGestureMargins(UiObject2 target, float marginPct) {
        final Rect bounds = target.getVisibleBounds();
        final int horizontalMargin = (int)(bounds.width() * marginPct);
        final int verticalMargin = (int)(bounds.height() * marginPct);
        target.setGestureMargins(horizontalMargin,
                verticalMargin,
                horizontalMargin,
                verticalMargin);
    }

    /**
     * Gets properties of a {@link UiObject2} as a String, for debugging purpose.
     *
     * @param widget {@link UiObject2} to get properties from
     * @return properties of given {@link UiObject2} as String
     */
    public static String getWidgetPropertiesAsString(UiObject2 widget) {
        try {
            return String.format("text=[%s],desc=[%s],res=[%s],pkg=[%s],class=[%s]",
                    widget.getText(),
                    widget.getContentDescription(),
                    widget.getResourceName(),
                    widget.getApplicationPackage(),
                    widget.getClassName());
        } catch (Exception e) {
            Log.e(TAG, "Failed to get properties from a widget", e);
        }

        return null;
    }

    /**
     * Gets the package name of a {@link UiObject2} safely.
     *
     * @param widget {@link UiObject2} to get property from
     * @return package name of given widget or null if there is any error
     */
    public static String getPackageName(UiObject2 widget) {
        try {
            return widget.getApplicationPackage();
        } catch (Exception e) {
            Log.e(TAG, "Failed to get package name from a widget", e);
        }

        return null;
    }

    /**
     * Gets the text of a {@link UiObject2} safely.
     *
     * @param widget {@link UiObject2} to get property from
     * @return text of given widget or null if there is any error
     */
    public static String getText(UiObject2 widget) {
        try {
            return widget.getText();
        } catch (Exception e) {
            Log.e(TAG, "Failed to get text from a widget", e);
        }

        return null;
    }

    /**
     * Gets the content description of a {@link UiObject2} safely.
     *
     * @param widget {@link UiObject2} to get property from
     * @return content description of given widget or null if there is any error
     */
    public static String getContentDescription(UiObject2 widget) {
        try {
            return widget.getContentDescription();
        } catch (Exception e) {
            Log.e(TAG, "Failed to get text from a widget", e);
        }

        return null;
    }
}