1 /* 2 * Copyright (C) 2017 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17 package androidx.wear.widget.util; 18 19 import android.support.test.espresso.PerformException; 20 import android.support.test.espresso.UiController; 21 import android.support.test.espresso.ViewAction; 22 import android.support.test.espresso.util.HumanReadables; 23 import android.support.test.espresso.util.TreeIterables; 24 import android.view.View; 25 26 import org.hamcrest.Matchers; 27 import org.hamcrest.StringDescription; 28 29 import java.util.concurrent.TimeoutException; 30 31 public class AsyncViewActions { 32 33 /** Perform action of waiting for a specific view id. */ 34 public static ViewAction waitForMatchingView( 35 final org.hamcrest.Matcher<? extends View> viewMatcher, final long millis) { 36 return new ViewAction() { 37 @Override 38 public void perform(UiController uiController, View view) { 39 uiController.loopMainThreadUntilIdle(); 40 final long startTime = System.currentTimeMillis(); 41 final long endTime = startTime + millis; 42 do { 43 for (View child : TreeIterables.breadthFirstViewTraversal(view)) { 44 // found matching view 45 if (viewMatcher.matches(child)) { 46 return; 47 } 48 } 49 uiController.loopMainThreadForAtLeast(100); // at least 3 frames 50 } while (System.currentTimeMillis() < endTime); 51 52 // timeout happens 53 throw new PerformException.Builder() 54 .withActionDescription(this.getDescription()) 55 .withViewDescription(HumanReadables.describe(view)) 56 .withCause(new TimeoutException()) 57 .build(); 58 } 59 60 @Override 61 public String getDescription() { 62 return "Wait for view which matches " + StringDescription.asString(viewMatcher); 63 } 64 65 @Override 66 public org.hamcrest.Matcher<View> getConstraints() { 67 return Matchers.any(View.class); 68 } 69 }; 70 } 71 } 72