1 // Copyright 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 package org.chromium.content.browser.test.util;
7 import static org.chromium.base.test.util.ScalableTimeout.scaleTimeout;
9 import android.os.SystemClock;
12 * Helper methods for creating and managing criteria.
15 * If possible, use callbacks or testing delegates instead of criteria as they
16 * do not introduce any polling delays. Should only use Criteria if no suitable
17 * other approach exists.
19 public class CriteriaHelper {
21 /** The default maximum time to wait for a criteria to become valid. */
22 public static final long DEFAULT_MAX_TIME_TO_POLL = scaleTimeout(3000);
23 /** The default polling interval to wait between checking for a satisfied criteria. */
24 public static final long DEFAULT_POLLING_INTERVAL = 50;
27 * Checks whether the given Criteria is satisfied at a given interval, until either
28 * the criteria is satisfied, or the specified maxTimeoutMs number of ms has elapsed.
29 * @param criteria The Criteria that will be checked.
30 * @param maxTimeoutMs The maximum number of ms that this check will be performed for
32 * @param checkIntervalMs The number of ms between checks.
33 * @return true iff checking has ended with the criteria being satisfied.
34 * @throws InterruptedException
36 public static boolean pollForCriteria(Criteria criteria, long maxTimeoutMs,
37 long checkIntervalMs) throws InterruptedException {
38 boolean isSatisfied = criteria.isSatisfied();
39 long startTime = SystemClock.uptimeMillis();
40 while (!isSatisfied && SystemClock.uptimeMillis() - startTime < maxTimeoutMs) {
41 Thread.sleep(checkIntervalMs);
42 isSatisfied = criteria.isSatisfied();
48 * Checks whether the given Criteria is satisfied polling at a default interval.
50 * @param criteria The Criteria that will be checked.
51 * @return iff checking has ended with the criteria being satisfied.
52 * @throws InterruptedException
53 * @see #pollForCriteria(Criteria, long, long)
55 public static boolean pollForCriteria(Criteria criteria) throws InterruptedException {
56 return pollForCriteria(criteria, DEFAULT_MAX_TIME_TO_POLL, DEFAULT_POLLING_INTERVAL);
60 * Performs the runnable action, then checks whether the given criteria are satisfied
61 * until the specified timeout, using the pollForCriteria method. If not, then the runnable
62 * action is performed again, to a maximum of maxAttempts tries.
64 public static boolean runUntilCriteria(Runnable runnable, Criteria criteria,
65 int maxAttempts, long maxTimeoutMs, long checkIntervalMs) throws InterruptedException {
67 boolean success = false;
68 while (count < maxAttempts && !success) {
71 success = pollForCriteria(criteria, maxTimeoutMs, checkIntervalMs);