summaryrefslogtreecommitdiff
path: root/tests/tests/assist/src/android/assist/cts/AssistTestBase.java
blob: c89119bdea1dc3aa307a365406fc92a67960a23f (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
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
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
/*
 * Copyright (C) 2015 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 android.assist.cts;

import static androidx.test.platform.app.InstrumentationRegistry.getInstrumentation;

import static com.android.compatibility.common.util.ShellUtils.runShellCommand;

import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;

import static org.junit.Assert.fail;

import android.app.ActivityManager;
import android.app.assist.AssistContent;
import android.app.assist.AssistStructure;
import android.app.assist.AssistStructure.ViewNode;
import android.assist.common.AutoResetLatch;
import android.assist.common.Utils;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Point;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.os.LocaleList;
import android.os.RemoteCallback;
import android.provider.Settings;
import android.util.Log;
import android.util.Pair;
import android.view.Display;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.widget.EditText;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.rule.ActivityTestRule;

import com.android.compatibility.common.util.SettingsStateChangerRule;
import com.android.compatibility.common.util.SettingsStateManager;
import com.android.compatibility.common.util.SettingsUtils;
import com.android.compatibility.common.util.StateKeeperRule;
import com.android.compatibility.common.util.ThrowingRunnable;
import com.android.compatibility.common.util.Timeout;

import org.junit.After;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Rule;
import org.junit.rules.RuleChain;
import org.junit.runner.RunWith;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.Consumer;

@RunWith(AndroidJUnit4.class)
abstract class AssistTestBase {
    private static final String TAG = "AssistTestBase";

    protected static final String FEATURE_VOICE_RECOGNIZERS = "android.software.voice_recognizers";

    // TODO: use constants from Settings (should be @TestApi)
    private static final String ASSIST_STRUCTURE_ENABLED = "assist_structure_enabled";
    private static final String ASSIST_SCREENSHOT_ENABLED = "assist_screenshot_enabled";

    private static final Timeout TIMEOUT = new Timeout(
            "AssistTestBaseTimeout",
            10000,
            2F,
            10000
    );

    private static final long SLEEP_BEFORE_RETRY_MS = 250L;

    private static final Context sContext = getInstrumentation().getTargetContext();

    private static final SettingsStateManager sStructureEnabledMgr = new SettingsStateManager(
            sContext, SettingsUtils.NAMESPACE_SECURE, ASSIST_STRUCTURE_ENABLED);
    private static final SettingsStateManager sScreenshotEnabledMgr = new SettingsStateManager(
            sContext, SettingsUtils.NAMESPACE_SECURE, ASSIST_SCREENSHOT_ENABLED);

    private final SettingsStateChangerRule mServiceSetterRule = new SettingsStateChangerRule(
            sContext, Settings.Secure.VOICE_INTERACTION_SERVICE,
            "android.assist.service/.MainInteractionService");
    private final StateKeeperRule<String> mStructureEnabledKeeperRule = new StateKeeperRule<>(
            sStructureEnabledMgr);
    private final StateKeeperRule<String> mScreenshotEnabledKeeperRule = new StateKeeperRule<>(
            sScreenshotEnabledMgr);
    private final ActivityTestRule<TestStartActivity> mActivityTestRule =
            new ActivityTestRule<>(TestStartActivity.class, false, false);

    @Rule
    public final RuleChain mLookAllTheseRules = RuleChain
            .outerRule(mServiceSetterRule)
            .around(mStructureEnabledKeeperRule)
            .around(mScreenshotEnabledKeeperRule)
            .around(mActivityTestRule);

    protected ActivityManager mActivityManager;
    private TestStartActivity mTestActivity;
    protected boolean mIsActivityIdNull;
    protected AssistContent mAssistContent;
    protected AssistStructure mAssistStructure;
    protected boolean mScreenshot;
    protected Bundle mAssistBundle;
    protected Context mContext;
    private AutoResetLatch mReadyLatch = new AutoResetLatch(1);
    private AutoResetLatch mHas3pResumedLatch = new AutoResetLatch(1);
    private AutoResetLatch mHasTestDestroyedLatch = new AutoResetLatch(1);
    private AutoResetLatch mSessionCompletedLatch = new AutoResetLatch(1);
    protected AutoResetLatch mAssistDataReceivedLatch = new AutoResetLatch();

    protected ActionLatchReceiver mActionLatchReceiver;

    private final RemoteCallback mRemoteCallback = new RemoteCallback((result) -> {
        String action = result.getString(Utils.EXTRA_REMOTE_CALLBACK_ACTION);
        mActionLatchReceiver.onAction(result, action);
    });

    @Nullable
    protected RemoteCallback m3pActivityCallback;
    @Nullable
    protected RemoteCallback mSecondary3pActivityCallback;

    protected boolean mScreenshotMatches;
    private Point mDisplaySize;
    private String mTestName;
    private View mView;

    @BeforeClass
    public static void setFeatures() {
        setFeaturesEnabled(StructureEnabled.TRUE, ScreenshotEnabled.TRUE);
        logContextAndScreenshotSetting();
    }

    @Before
    public final void setUp() throws Exception {
        mContext = sContext;

        // reset old values
        mScreenshotMatches = false;
        mScreenshot = false;
        mAssistStructure = null;
        mAssistContent = null;
        mAssistBundle = null;
        mIsActivityIdNull = false;

        mActionLatchReceiver = new ActionLatchReceiver();

        prepareDevice();

        customSetup();
    }

    /**
     * Test-specific setup - doesn't need to call {@code super} neither use <code>@Before</code>.
     */
    protected void customSetup() throws Exception {
    }

    @After
    public final void tearDown() throws Exception {
        customTearDown();
        mTestActivity.finish();
        mContext.sendBroadcast(new Intent(Utils.HIDE_SESSION));

        if (m3pActivityCallback != null) {
            m3pActivityCallback.sendResult(Utils.bundleOfRemoteAction(Utils.ACTION_END_OF_TEST));
        }

        if (mSecondary3pActivityCallback != null) {
            mSecondary3pActivityCallback
                    .sendResult(Utils.bundleOfRemoteAction(Utils.ACTION_END_OF_TEST));
        }

        mSessionCompletedLatch.await(3, TimeUnit.SECONDS);
    }

    /**
     * Test-specific teardown - doesn't need to call {@code super} neither use <code>@After</code>.
     */
    protected void customTearDown() throws Exception {
    }

    private void prepareDevice() throws Exception {
        Log.d(TAG, "prepareDevice()");

        // Unlock screen.
        runShellCommand("input keyevent KEYCODE_WAKEUP");

        // Dismiss keyguard, in case it's set as "Swipe to unlock".
        runShellCommand("wm dismiss-keyguard");
    }

    protected void startTest(String testName) throws Exception {
        Log.i(TAG, "Starting test activity for TestCaseType = " + testName);
        Intent intent = new Intent();
        intent.putExtra(Utils.TESTCASE_TYPE, testName);
        intent.setAction("android.intent.action.START_TEST_" + testName);
        intent.putExtra(Utils.EXTRA_REMOTE_CALLBACK, mRemoteCallback);
        intent.addFlags(Intent.FLAG_ACTIVITY_MATCH_EXTERNAL);

        mTestActivity.startActivity(intent);
        waitForTestActivityOnDestroy();
    }

    protected void start3pApp(String testCaseName) throws Exception {
        start3pApp(testCaseName, null);
    }

    protected void start3pApp(String testCaseName, Bundle extras) throws Exception {
        Intent intent = new Intent();
        intent.putExtra(Utils.TESTCASE_TYPE, testCaseName);
        Utils.setTestAppAction(intent, testCaseName);
        intent.putExtra(Utils.EXTRA_REMOTE_CALLBACK, mRemoteCallback);
        intent.addFlags(Intent.FLAG_ACTIVITY_MATCH_EXTERNAL);

        // In devices which support multi-window Activity positioning by default (such as foldables)
        // it is necessary to launch additional activities ("screen fillers") so we may validate the
        // entire screenshot captured by the Assistant (full display, not individual DisplayAreas)
        if (m3pActivityCallback == null) { // first time start3pApp is called
            intent.putExtra(Utils.EXTRA_REMOTE_CALLBACK_RECEIVING,
                    createRemoteCallbackReceiver(callback -> m3pActivityCallback = callback));
        } else if (mSecondary3pActivityCallback == null) { // second time
            // launch 3pApp on adjacent screen in test cases that need a "screen filler".
            // necessary configuration to ensure Activity can be launched in another DisplayArea
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_LAUNCH_ADJACENT
                    // as we are reusing this intent setup, unconditionally start a new task
                    | Intent.FLAG_ACTIVITY_MULTIPLE_TASK);
            intent.putExtra(Utils.EXTRA_REMOTE_CALLBACK_RECEIVING, createRemoteCallbackReceiver(
                    remoteCallback -> mSecondary3pActivityCallback = remoteCallback));
        } else {
            throw new IllegalStateException("start3pApp supports a maximum of two App instances.");
        }

        if (extras != null) {
            intent.putExtras(extras);
        }

        mTestActivity.startActivity(intent);
        waitForOnResume();
    }

    private RemoteCallback createRemoteCallbackReceiver(Consumer<RemoteCallback> consumer) {
        return new RemoteCallback((results) -> {
            String action = results.getString(Utils.EXTRA_REMOTE_CALLBACK_ACTION);
            if (action.equals(Utils.EXTRA_REMOTE_CALLBACK_RECEIVING_ACTION)) {
                consumer.accept(results.getParcelable(Utils.EXTRA_REMOTE_CALLBACK_RECEIVING));
            }
        }, new Handler(mContext.getMainLooper()));
    }

    /**
     * Starts the shim service activity
     */
    protected void startTestActivity(String testName) {
        Intent intent = new Intent();
        mTestName = testName;
        intent.setAction("android.intent.action.TEST_START_ACTIVITY_" + testName);
        intent.putExtra(Utils.TESTCASE_TYPE, testName);
        intent.putExtra(Utils.EXTRA_REMOTE_CALLBACK, mRemoteCallback);
        mTestActivity = mActivityTestRule.launchActivity(intent);
        mActivityManager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
    }

    /**
     * Called when waiting for Assistant's Broadcast Receiver to be setup
     */
    protected void waitForAssistantToBeReady() throws Exception {
        Log.i(TAG, "waiting for assistant to be ready before continuing");
        if (!mReadyLatch.await(Utils.TIMEOUT_MS, TimeUnit.MILLISECONDS)) {
            fail("Assistant was not ready before timeout of: " + Utils.TIMEOUT_MS + "msec");
        }
    }

    private void waitForOnResume() throws Exception {
        Log.i(TAG, "waiting for onResume() before continuing");
        if (!mHas3pResumedLatch.await(Utils.ACTIVITY_ONRESUME_TIMEOUT_MS, TimeUnit.MILLISECONDS)) {
            fail("Activity failed to resume in " + Utils.ACTIVITY_ONRESUME_TIMEOUT_MS + "msec");
        }
    }

    private void waitForTestActivityOnDestroy() throws Exception {
        Log.i(TAG, "waiting for mTestActivity onDestroy() before continuing");
        if (!mHasTestDestroyedLatch.await(Utils.ACTIVITY_ONRESUME_TIMEOUT_MS, TimeUnit.MILLISECONDS)) {
            fail("mTestActivity failed to destroy in " + Utils.ACTIVITY_ONRESUME_TIMEOUT_MS + "msec");
        }
    }

    /**
     * Send broadcast to MainInteractionService to start a session
     */
    protected AutoResetLatch startSession() {
        return startSession(new Bundle());
    }

    protected AutoResetLatch startSession(Bundle extras) {
        return startSession(mTestName, extras);
    }

    protected AutoResetLatch startSession(String testName, Bundle extras) {
        Intent intent = new Intent(Utils.BROADCAST_INTENT_START_ASSIST);
        Log.i(TAG, "passed in class test name is: " + testName);
        intent.putExtra(Utils.TESTCASE_TYPE, testName);
        addDimensionsToIntent(intent);
        intent.putExtras(extras);
        intent.putExtra(Utils.EXTRA_REMOTE_CALLBACK, mRemoteCallback);
        intent.setPackage("android.assist.service");

        mContext.sendBroadcast(intent);
        return mAssistDataReceivedLatch;
    }

    /**
     * Calculate display dimensions (including navbar) to pass along in the given intent.
     */
    private void addDimensionsToIntent(Intent intent) {
        if (mDisplaySize == null) {
            Display.Mode dMode = mTestActivity.getWindowManager().getDefaultDisplay().getMode();
            mDisplaySize = new Point(dMode.getPhysicalWidth(), dMode.getPhysicalHeight());
        }
        Rect bounds = mTestActivity.getWindowManager().getMaximumWindowMetrics().getBounds();
        intent.putExtra(Utils.DISPLAY_AREA_BOUNDS_KEY, bounds);
        intent.putExtra(Utils.DISPLAY_WIDTH_KEY, mDisplaySize.x);
        intent.putExtra(Utils.DISPLAY_HEIGHT_KEY, mDisplaySize.y);
    }

    protected boolean waitForContext(AutoResetLatch sessionLatch) throws Exception {
        if (!sessionLatch.await(Utils.getAssistDataTimeout(mTestName), TimeUnit.MILLISECONDS)) {
            fail("Fail to receive broadcast in " + Utils.getAssistDataTimeout(mTestName) + "msec");
        }
        Log.i(TAG, "Received broadcast with all information.");
        return true;
    }

    /**
     * Checks the nullness of the received
     * {@link android.service.voice.VoiceInteractionSession.ActivityId}.
     *
     * @param isActivityIdNull True if activityId should be null.
     */
    protected void verifyActivityIdNullness(boolean isActivityIdNull) {
        if (mIsActivityIdNull != isActivityIdNull) {
            fail(String.format("Should %s have been null - ActivityId: %s",
                    isActivityIdNull ? "" : "not", mIsActivityIdNull));
        }
    }

    /**
     * Checks that the nullness of values are what we expect.
     *
     * @param isBundleNull True if assistBundle should be null.
     * @param isStructureNull True if assistStructure should be null.
     * @param isContentNull True if assistContent should be null.
     * @param isScreenshotNull True if screenshot should be null.
     */
    protected void verifyAssistDataNullness(boolean isBundleNull, boolean isStructureNull,
            boolean isContentNull, boolean isScreenshotNull) {

        if ((mAssistContent == null) != isContentNull) {
            fail(String.format("Should %s have been null - AssistContent: %s",
                    isContentNull ? "" : "not", mAssistContent));
        }

        if ((mAssistStructure == null) != isStructureNull) {
            fail(String.format("Should %s have been null - AssistStructure: %s",
                    isStructureNull ? "" : "not", mAssistStructure));
        }

        if ((mAssistBundle == null) != isBundleNull) {
            fail(String.format("Should %s have been null - AssistBundle: %s",
                    isBundleNull ? "" : "not", mAssistBundle));
        }

        if (mScreenshot == isScreenshotNull) {
            fail(String.format("Should %s have been null - Screenshot: %s",
                    isScreenshotNull ? "":"not", mScreenshot));
        }
    }

    /**
     * Sends a broadcast with the specified scroll positions to the test app.
     */
    protected void scrollTestApp(int scrollX, int scrollY, boolean scrollTextView,
            boolean scrollScrollView) {
        mTestActivity.scrollText(scrollX, scrollY, scrollTextView, scrollScrollView);
        Intent intent = null;
        if (scrollTextView) {
            intent = new Intent(Utils.SCROLL_TEXTVIEW_ACTION);
        } else if (scrollScrollView) {
            intent = new Intent(Utils.SCROLL_SCROLLVIEW_ACTION);
        }
        intent.putExtra(Utils.SCROLL_X_POSITION, scrollX);
        intent.putExtra(Utils.SCROLL_Y_POSITION, scrollY);
        mContext.sendBroadcast(intent);
    }

    /**
     * Verifies the view hierarchy of the backgroundApp matches the assist structure.
     * @param backgroundApp ComponentName of app the assistant is invoked upon
     * @param isSecureWindow Denotes whether the activity has FLAG_SECURE set
     */
    protected void verifyAssistStructure(ComponentName backgroundApp, boolean isSecureWindow) {
        // Check component name matches
        assertThat(mAssistStructure.getActivityComponent().flattenToString())
                .isEqualTo(backgroundApp.flattenToString());
        long acquisitionStart = mAssistStructure.getAcquisitionStartTime();
        long acquisitionEnd = mAssistStructure.getAcquisitionEndTime();
        assertThat(acquisitionStart).isGreaterThan(0L);
        assertThat(acquisitionEnd).isGreaterThan(0L);
        assertThat(acquisitionEnd).isAtLeast(acquisitionStart);
        Log.i(TAG, "Traversing down structure for: " + backgroundApp.flattenToString());
        mView = mTestActivity.findViewById(android.R.id.content).getRootView();
        verifyHierarchy(mAssistStructure, isSecureWindow);
    }

    protected static void logContextAndScreenshotSetting() {
        Log.i(TAG, "Context is: " + sStructureEnabledMgr.get());
        Log.i(TAG, "Screenshot is: " + sScreenshotEnabledMgr.get());
    }

    /**
     * Recursively traverse and compare properties in the View hierarchy with the Assist Structure.
     */
    public void verifyHierarchy(AssistStructure structure, boolean isSecureWindow) {
        Log.i(TAG, "verifyHierarchy");

        int numWindows = structure.getWindowNodeCount();
        // TODO: multiple windows?
        assertWithMessage("Number of windows don't match").that(numWindows).isEqualTo(1);
        int[] appLocationOnScreen = new int[2];
        mView.getLocationOnScreen(appLocationOnScreen);

        for (int i = 0; i < numWindows; i++) {
            AssistStructure.WindowNode windowNode = structure.getWindowNodeAt(i);
            Log.i(TAG, "Title: " + windowNode.getTitle());
            // Verify top level window bounds are as big as the app and pinned to its top-left
            // corner.
            assertWithMessage("Window left position wrong: was %s", windowNode.getLeft())
                    .that(appLocationOnScreen[0]).isEqualTo(windowNode.getLeft());
            assertWithMessage("Window top position wrong: was %s", windowNode.getTop())
                    .that(appLocationOnScreen[1]).isEqualTo(windowNode.getTop());
            traverseViewAndStructure(
                    mView,
                    windowNode.getRootViewNode(),
                    isSecureWindow);
        }
    }

    private void traverseViewAndStructure(View parentView, ViewNode parentNode,
            boolean isSecureWindow) {
        ViewGroup parentGroup;

        if (parentView == null && parentNode == null) {
            Log.i(TAG, "Views are null, done traversing this branch.");
            return;
        } else if (parentNode == null || parentView == null) {
            fail(String.format("Views don't match. View: %s, Node: %s", parentView, parentNode));
        }

        // Debugging
        Log.i(TAG, "parentView is of type: " + parentView.getClass().getName());
        if (parentView instanceof ViewGroup) {
            for (int childInt = 0; childInt < ((ViewGroup) parentView).getChildCount();
                    childInt++) {
                Log.i(TAG,
                        "viewchild" + childInt + " is of type: "
                        + ((ViewGroup) parentView).getChildAt(childInt).getClass().getName());
            }
        }
        String parentViewId = null;
        if (parentView.getId() > 0) {
            parentViewId = mTestActivity.getResources().getResourceEntryName(parentView.getId());
            Log.i(TAG, "View ID: " + parentViewId);
        }

        Log.i(TAG, "parentNode is of type: " + parentNode.getClassName());
        for (int nodeInt = 0; nodeInt < parentNode.getChildCount(); nodeInt++) {
            Log.i(TAG,
                    "nodechild" + nodeInt + " is of type: "
                    + parentNode.getChildAt(nodeInt).getClassName());
        }
        Log.i(TAG, "Node ID: " + parentNode.getIdEntry());

        assertWithMessage("IDs do not match").that(parentNode.getIdEntry()).isEqualTo(parentViewId);

        int numViewChildren = 0;
        int numNodeChildren = 0;
        if (parentView instanceof ViewGroup) {
            numViewChildren = ((ViewGroup) parentView).getChildCount();
        }
        numNodeChildren = parentNode.getChildCount();

        if (isSecureWindow) {
            assertWithMessage("ViewNode property isAssistBlocked is false")
                    .that(parentNode.isAssistBlocked()).isTrue();
            assertWithMessage("Secure window should only traverse root node")
                    .that(numNodeChildren).isEqualTo(0);
            isSecureWindow = false;
        } else if (parentNode.getClassName().equals("android.webkit.WebView")) {
            // WebView will also appear to have no children while the node does, traverse node
            assertWithMessage("AssistStructure returned a WebView where the view wasn't one").that(
                    parentView instanceof WebView).isTrue();

            boolean textInWebView = false;

            for (int i = numNodeChildren - 1; i >= 0; i--) {
               textInWebView |= traverseWebViewForText(parentNode.getChildAt(i));
            }
            assertWithMessage("Did not find expected strings inside WebView").that(textInWebView)
                    .isTrue();
        } else {
            assertWithMessage("Number of children did not match").that(numNodeChildren)
                    .isEqualTo(numViewChildren);

            verifyViewProperties(parentView, parentNode);

            if (parentView instanceof ViewGroup) {
                parentGroup = (ViewGroup) parentView;

                // TODO: set a max recursion level
                for (int i = numNodeChildren - 1; i >= 0; i--) {
                    View childView = parentGroup.getChildAt(i);
                    ViewNode childNode = parentNode.getChildAt(i);

                    // if isSecureWindow, should not have reached this point.
                    assertThat(isSecureWindow).isFalse();
                    traverseViewAndStructure(childView, childNode, isSecureWindow);
                }
            }
        }
    }

    /**
     * Return true if the expected strings are found in the WebView, else fail.
     */
    private boolean traverseWebViewForText(ViewNode parentNode) {
        boolean textFound = false;
        if (parentNode.getText() != null
                && parentNode.getText().toString().equals(Utils.WEBVIEW_HTML_GREETING)) {
            return true;
        }
        for (int i = parentNode.getChildCount() - 1; i >= 0; i--) {
            textFound |= traverseWebViewForText(parentNode.getChildAt(i));
        }
        return textFound;
    }

    /**
     * Return true if the expected domain is found in the WebView, else fail.
     */
    protected void verifyAssistStructureHasWebDomain(String domain) {
        assertThat(traverse(mAssistStructure.getWindowNodeAt(0).getRootViewNode(), (n) -> {
            return n.getWebDomain() != null && domain.equals(n.getWebDomain());
        })).isTrue();
    }

    /**
     * Return true if the expected LocaleList is found in the WebView, else fail.
     */
    protected void verifyAssistStructureHasLocaleList(LocaleList localeList) {
        assertThat(traverse(mAssistStructure.getWindowNodeAt(0).getRootViewNode(), (n) -> {
            return n.getLocaleList() != null && localeList.equals(n.getLocaleList());
        })).isTrue();
    }

    interface ViewNodeVisitor {
        boolean visit(ViewNode node);
    }

    private boolean traverse(ViewNode parentNode, ViewNodeVisitor visitor) {
        if (visitor.visit(parentNode)) {
            return true;
        }
        for (int i = parentNode.getChildCount() - 1; i >= 0; i--) {
            if (traverse(parentNode.getChildAt(i), visitor)) {
                return true;
            }
        }
        return false;
    }

    protected static void setFeaturesEnabled(StructureEnabled structure,
            ScreenshotEnabled screenshot) {
        Log.i(TAG, "setFeaturesEnabled(" + structure + ", " + screenshot + ")");
        sStructureEnabledMgr.set(structure.value);
        sScreenshotEnabledMgr.set(screenshot.value);
    }

    /**
     * Compare view properties of the view hierarchy with that reported in the assist structure.
     */
    private void verifyViewProperties(View parentView, ViewNode parentNode) {
        assertWithMessage("Left positions do not match").that(parentNode.getLeft())
                .isEqualTo(parentView.getLeft());
        assertWithMessage("Top positions do not match").that(parentNode.getTop())
                .isEqualTo(parentView.getTop());
        assertWithMessage("Opaque flags do not match").that(parentNode.isOpaque())
                .isEqualTo(parentView.isOpaque());

        int viewId = parentView.getId();

        if (viewId > 0) {
            if (parentNode.getIdEntry() != null) {
                assertWithMessage("View IDs do not match.").that(parentNode.getIdEntry())
                        .isEqualTo(mTestActivity.getResources().getResourceEntryName(viewId));
            }
        } else {
            assertWithMessage("View Node should not have an ID").that(parentNode.getIdEntry())
                    .isNull();
        }

        Log.i(TAG, "parent text: " + parentNode.getText());
        if (parentView instanceof TextView) {
            Log.i(TAG, "view text: " + ((TextView) parentView).getText());
        }

        assertWithMessage("Scroll X does not match").that(parentNode.getScrollX())
                .isEqualTo(parentView.getScrollX());
        assertWithMessage("Scroll Y does not match").that(parentNode.getScrollY())
                .isEqualTo(parentView.getScrollY());
        assertWithMessage("Heights do not match").that(parentNode.getHeight())
                .isEqualTo(parentView.getHeight());
        assertWithMessage("Widths do not match").that(parentNode.getWidth())
                .isEqualTo(parentView.getWidth());

        if (parentView instanceof TextView) {
            if (parentView instanceof EditText) {
              assertWithMessage("Text selection start does not match")
                      .that(parentNode.getTextSelectionStart())
                      .isEqualTo(((EditText) parentView).getSelectionStart());
              assertWithMessage("Text selection end does not match")
                .that(parentNode.getTextSelectionEnd())
                      .isEqualTo(((EditText) parentView).getSelectionEnd());
            }
            TextView textView = (TextView) parentView;
            assertThat(parentNode.getTextSize()).isWithin(0.01F).of(textView.getTextSize());
            String viewString = textView.getText().toString();
            String nodeString = parentNode.getText().toString();

            if (parentNode.getScrollX() == 0 && parentNode.getScrollY() == 0) {
                Log.i(TAG, "Verifying text within TextView at the beginning");
                Log.i(TAG, "view string: " + viewString);
                Log.i(TAG, "node string: " + nodeString);
                assertWithMessage("String length is unexpected: original string - %s, "
                        + "string in AssistData - %s", viewString.length(), nodeString.length())
                                .that(viewString.length()).isAtLeast(nodeString.length());
                assertWithMessage("Expected a longer string to be shown").that(
                        nodeString.length()).isAtLeast(Math.min(viewString.length(), 30));
                for (int x = 0; x < parentNode.getText().length(); x++) {
                    assertWithMessage("Char not equal at index: %s", x).that(
                            parentNode.getText().charAt(x)).isEqualTo(
                            ((TextView) parentView).getText().toString().charAt(x));
                }
            } else if (parentNode.getScrollX() == parentView.getWidth()) {

            }
        } else {
            assertThat(parentNode.getText()).isNull();
        }
    }

    protected void setAssistResults(Bundle assistData) {
        mIsActivityIdNull = assistData.getBoolean(Utils.ASSIST_IS_ACTIVITY_ID_NULL);;
        mAssistBundle = assistData.getBundle(Utils.ASSIST_BUNDLE_KEY);
        mAssistStructure = assistData.getParcelable(Utils.ASSIST_STRUCTURE_KEY);
        mAssistContent = assistData.getParcelable(Utils.ASSIST_CONTENT_KEY);

        mScreenshot = assistData.getBoolean(Utils.ASSIST_SCREENSHOT_KEY, false);

        mScreenshotMatches = assistData.getBoolean(Utils.COMPARE_SCREENSHOT_KEY, false);
    }

    protected void eventuallyWithSessionClose(@NonNull ThrowingRunnable runnable) throws Throwable {
        AtomicReference<Throwable> innerThrowable = new AtomicReference<>();
        try {
            TIMEOUT.run(getClass().getName(), SLEEP_BEFORE_RETRY_MS, () -> {
                try {
                    runnable.run();
                    return runnable;
                } catch (Throwable throwable) {
                    // Immediately close the session so the next run can redo its action
                    mContext.sendBroadcast(new Intent(Utils.HIDE_SESSION));
                    mSessionCompletedLatch.await(2, TimeUnit.SECONDS);
                    innerThrowable.set(throwable);
                    return null;
                }
            });
        } catch (Throwable throwable) {
            Throwable inner = innerThrowable.get();
            if (inner != null) {
                throw inner;
            } else {
                throw throwable;
            }
        }
    }

    protected enum StructureEnabled {
        TRUE("1"), FALSE("0");

        private final String value;

        private StructureEnabled(String value) {
            this.value = value;
        }

        @Override
        public String toString() {
            return "structure_" + (value.equals("1") ? "enabled" : "disabled");
        }

    }

    protected enum ScreenshotEnabled {
        TRUE("1"), FALSE("0");

        private final String value;

        private ScreenshotEnabled(String value) {
            this.value = value;
        }

        @Override
        public String toString() {
            return "screenshot_" + (value.equals("1") ? "enabled" : "disabled");
        }
    }

    public class ActionLatchReceiver {

        private final Map<String, AutoResetLatch> entries = new HashMap<>();

        protected ActionLatchReceiver(Pair<String, AutoResetLatch>... entries) {
            for (Pair<String, AutoResetLatch> entry : entries) {
                if (entry.second == null) {
                    throw new IllegalArgumentException("Test cannot pass in a null latch");
                }
                this.entries.put(entry.first, entry.second);
            }

            this.entries.put(Utils.HIDE_SESSION_COMPLETE, mSessionCompletedLatch);
            this.entries.put(Utils.APP_3P_HASRESUMED, mHas3pResumedLatch);
            this.entries.put(Utils.TEST_ACTIVITY_DESTROY, mHasTestDestroyedLatch);
            this.entries.put(Utils.ASSIST_RECEIVER_REGISTERED, mReadyLatch);
            this.entries.put(Utils.BROADCAST_ASSIST_DATA_INTENT, mAssistDataReceivedLatch);
        }

        protected ActionLatchReceiver(String action, AutoResetLatch latch) {
            this(Pair.create(action, latch));
        }

        protected void onAction(Bundle bundle, String action) {
            switch (action) {
                case Utils.BROADCAST_ASSIST_DATA_INTENT:
                    AssistTestBase.this.setAssistResults(bundle);
                    // fall-through
                default:
                    AutoResetLatch latch = entries.get(action);
                    if (latch == null) {
                        Log.e(TAG, this.getClass() + ": invalid action " + action);
                    } else {
                        latch.countDown();
                    }
                    break;
            }
        }
    }
}