aboutsummaryrefslogtreecommitdiff
path: root/libs/UiAutomatorLib/src/com/android/afwtest/uiautomator/test/AfwTestUiWatcher.java
blob: 3d9ba2f8940007b828509e39a05174742b46b56d (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
/*
 * 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.test;

import static com.android.afwtest.common.Constants.KEY_MUTE_APP_CRASH_DIALOGS;
import static com.android.afwtest.uiautomator.Constants.ANDROID_PKG_NAME;
import static com.android.afwtest.uiautomator.Constants.MANAGED_PROVISIONING_PKG_NAME;
import static com.android.afwtest.uiautomator.utils.WidgetUtils.safeClick;
import static com.android.afwtest.uiautomator.utils.WidgetUtils.safeClickAny;

import android.support.test.uiautomator.By;
import android.support.test.uiautomator.BySelector;
import android.support.test.uiautomator.UiDevice;
import android.support.test.uiautomator.UiObject2;
import android.support.test.uiautomator.UiWatcher;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Button;

import com.android.afwtest.common.test.TestConfig;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;

/**
 * {@link UiWatcher} to handle common unexpected scenarios.
 *
 * <p>
 * This is a singleton class. There can be only one
 * </p>
 */
public final class AfwTestUiWatcher implements UiWatcher {

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

    /**
     * Unique name of this ui watcher.
     */
    private static final String UI_WATCHER_NAME = "afw-test-uiwatcher";

    /**
     * Regex string for app crashed message.
     */
    private static final String APP_STOPPED_MSG_REGEX = "Unfortunately,.*has stopped.*";

    /**
     * {@link Pattern} to match app crashed message.
     */
    private static final Pattern APP_STOPPED_MSG_PATTERN = Pattern.compile(APP_STOPPED_MSG_REGEX);

    /**
     * {@link BySelector} for app crashed message.
     */
    private static final BySelector APP_STOPPED_MSG_SELECTOR =
            By.res(ANDROID_PKG_NAME, "message")
                    .text(APP_STOPPED_MSG_PATTERN);

    /**
     * {@link BySelector} for "OK" button on app crash dialog.
     */
    private static final BySelector APP_STOPPED_DIALOG_OK_BUTTON_SELECTOR =
            By.clazz(Button.class.getName())
                    .text("OK");

    /**
     * Words to match for "Accept" button's text or description.
     */
    private static final String[] ACCEPT_WORDS = {
            "[aA]ccept", "ACCEPT",
            "[aA]gree", "AGREE",
            "[aA]llow", "ALLOW"};

    /**
     * {@link Pattern} to match any "Accept" word in {@link #ACCEPT_WORDS}.
     */
    private static final Pattern ACCEPT_BTN_PATTERN =
            Pattern.compile(TextUtils.join("|", ACCEPT_WORDS));

    /**
     * Buttons with text matching {@link #ACCEPT_BTN_PATTERN}.
     */
    private static final BySelector ACCEPT_BTN_TEXT_SELECTOR =
            By.enabled(true)
                    .checkable(false)
                    .clickable(true)
                    .text(ACCEPT_BTN_PATTERN);

    /**
     * Buttons with content description matching {@link #ACCEPT_BTN_PATTERN}.
     */
    private static final BySelector ACCEPT_BTN_DESC_SELECTOR =
            By.enabled(true)
                    .checkable(false)
                    .clickable(true)
                    .desc(ACCEPT_BTN_PATTERN);

    /**
     * Non-null string indicates fatal app crashed.
     */
    private static String sFatalAppCrashMsg;

    /**
     * Assert if any of these app crashes.
     */
    private static final List<String> FATAL_APP_CRASHES =
            Arrays.asList(MANAGED_PROVISIONING_PKG_NAME,
                    "Setup Wizard");

    /**
     * List of packages whose crash should be ignored.
     */
    private final List<String> mAppCrashWhitelist;

    /**
     * {@link UiDevice} object.
     */
    private final UiDevice mUiDevice;

    /**
     * Constructor.
     *
     * @param uiDevice {@link UiDevice} object
     */
    private AfwTestUiWatcher(UiDevice uiDevice) throws Exception {
        mUiDevice = uiDevice;
        mAppCrashWhitelist = new ArrayList<String>();
        mAppCrashWhitelist.add("Google Play services");
        mAppCrashWhitelist.addAll(TestConfig.getDefault().getAppCrashWhitelist());
    }

    /**
     * Registers this ui watcher.
     *
     * @param uiDevice {@link UiDevice} object
     */
    public static void register(UiDevice uiDevice) throws Exception {
        uiDevice.registerWatcher(UI_WATCHER_NAME, new AfwTestUiWatcher(uiDevice));
    }

    /**
     * Unregisters this ui watcher.
     *
     * @param uiDevice {@link UiDevice} object
     */
    public static void unregister(UiDevice uiDevice) {
        uiDevice.removeWatcher(UI_WATCHER_NAME);
    }

    public static String getFatalAppCrashMsg() {
        return sFatalAppCrashMsg;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public boolean checkForCondition() {

        // The order of the conditions matters.
        try {
            return clearAppStoppedDialog() || checkAcceptButtons();
        } catch (Exception e) {
            // Don't throw exception as it will crashes the test runner
            Log.e(TAG, UI_WATCHER_NAME, e);
            return false;
        }
    }

    /**
     * Clears dialogs: "Unfortunately, {app name} has stopped."
     *
     * @return {@code true} if any dialog is dismissed, {@code false} otherwise
     */
    private boolean clearAppStoppedDialog() throws IOException {

        if (mUiDevice.hasObject(APP_STOPPED_MSG_SELECTOR)
                && mUiDevice.hasObject(APP_STOPPED_DIALOG_OK_BUTTON_SELECTOR)) {

            UiObject2 msgWidget = mUiDevice.findObject(APP_STOPPED_MSG_SELECTOR);
            if (msgWidget != null) {
                String msg = msgWidget.getText();
                Log.w(TAG, String.format("Found app crash dialog: %s", msg));
                if (isFatalAppCrash(msg)) {
                    Log.w(TAG, String.format("Fatal app crash. Test should abort.", msg));
                    sFatalAppCrashMsg = msg;
                    return true;
                }
                Log.w(TAG, String.format("Auto closing: %s", msg));
                sFatalAppCrashMsg = null;
                return safeClick(mUiDevice.findObject(APP_STOPPED_DIALOG_OK_BUTTON_SELECTOR));
            }
        }

        return false;
    }

    /**
     * Checks if app crash is fatal.
     *
     * @param appCrashMsg App crash message
     * @return {@code true} if app crash is fatal, {@code false} otherwise.
     */
    private boolean isFatalAppCrash(String appCrashMsg) throws IOException {
        for (String app : FATAL_APP_CRASHES) {
            if (appCrashMsg.contains(app)) {
                return true;
            }
        }

        // if muting all app crash dialog is enabled, return
        if (TestConfig.getDefault().muteAppCrashDialogs()) {
            Log.i(TAG, String.format("%s=true", KEY_MUTE_APP_CRASH_DIALOGS));
            return false;
        }

        // otherwise, auto close whitelisted app crashes, assert on others.
        for (String app : mAppCrashWhitelist) {
            if (appCrashMsg.contains(app)) {
                Log.w(TAG, String.format("Whitelisted app crash: %s", app));
                return false;
            }
        }

        return true;
    }

    /**
     * Clicks any visible accept button.
     *
     * @return {@code true} if any button found and clicked successfully;
     *         {@code false} otherwise
     */
    private boolean checkAcceptButtons() {
        return safeClickAny(mUiDevice.findObjects(ACCEPT_BTN_TEXT_SELECTOR)) ||
                safeClickAny(mUiDevice.findObjects(ACCEPT_BTN_DESC_SELECTOR));
    }
}