1 /* 2 * Copyright (C) 2018 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 android.testing; 18 19 import junit.framework.Assert; 20 import java.util.concurrent.Callable; 21 22 public abstract class PollingCheck { 23 private static final long TIME_SLICE = 50; 24 private long mTimeout = 3000; 25 26 public static interface PollingCheckCondition { canProceed()27 boolean canProceed(); 28 } 29 PollingCheck()30 public PollingCheck() { 31 } 32 PollingCheck(long timeout)33 public PollingCheck(long timeout) { 34 mTimeout = timeout; 35 } 36 check()37 protected abstract boolean check(); 38 run()39 public void run() { 40 if (check()) { 41 return; 42 } 43 44 long timeout = mTimeout; 45 while (timeout > 0) { 46 try { 47 Thread.sleep(TIME_SLICE); 48 } catch (InterruptedException e) { 49 Assert.fail("unexpected InterruptedException"); 50 } 51 52 if (check()) { 53 return; 54 } 55 56 timeout -= TIME_SLICE; 57 } 58 59 Assert.fail("unexpected timeout"); 60 } 61 check(CharSequence message, long timeout, Callable<Boolean> condition)62 public static void check(CharSequence message, long timeout, Callable<Boolean> condition) 63 throws Exception { 64 while (timeout > 0) { 65 if (condition.call()) { 66 return; 67 } 68 69 Thread.sleep(TIME_SLICE); 70 timeout -= TIME_SLICE; 71 } 72 73 Assert.fail(message.toString()); 74 } 75 waitFor(final PollingCheckCondition condition)76 public static void waitFor(final PollingCheckCondition condition) { 77 new PollingCheck() { 78 @Override 79 protected boolean check() { 80 return condition.canProceed(); 81 } 82 }.run(); 83 } 84 waitFor(long timeout, final PollingCheckCondition condition)85 public static void waitFor(long timeout, final PollingCheckCondition condition) { 86 new PollingCheck(timeout) { 87 @Override 88 protected boolean check() { 89 return condition.canProceed(); 90 } 91 }.run(); 92 } 93 } 94 95