1 // Copyright 2014 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.cronet_test_apk;
7 import static org.chromium.base.test.util.ScalableTimeout.scaleTimeout;
9 import android.os.SystemClock;
12 * Helper methods for creating and managing criteria.
14 * If possible, use callbacks or testing delegates instead of criteria as they
15 * do not introduce any polling delays. Should only use Criteria if no suitable
16 * other approach exists.
18 public class CriteriaHelper {
20 /** The default maximum time to wait for a criteria to become valid. */
21 public static final long DEFAULT_MAX_TIME_TO_POLL = scaleTimeout(3000);
24 * The default polling interval to wait between checking for a satisfied
27 public static final long DEFAULT_POLLING_INTERVAL = 50;
30 * Checks whether the given Criteria is satisfied at a given interval, until
31 * either the criteria is satisfied, or the specified maxTimeoutMs number of
34 * @param criteria The Criteria that will be checked.
35 * @param maxTimeoutMs The maximum number of ms that this check will be
36 * performed for before timeout.
37 * @param checkIntervalMs The number of ms between checks.
38 * @return true iff checking has ended with the criteria being satisfied.
39 * @throws InterruptedException
41 public static boolean pollForCriteria(Criteria criteria, long maxTimeoutMs,
42 long checkIntervalMs) throws InterruptedException {
43 boolean isSatisfied = criteria.isSatisfied();
44 long startTime = SystemClock.uptimeMillis();
45 while (!isSatisfied &&
46 SystemClock.uptimeMillis() - startTime < maxTimeoutMs) {
47 Thread.sleep(checkIntervalMs);
48 isSatisfied = criteria.isSatisfied();
54 * Checks whether the given Criteria is satisfied polling at a default
57 * @param criteria The Criteria that will be checked.
58 * @return iff checking has ended with the criteria being satisfied.
59 * @throws InterruptedException
60 * @see #pollForCriteria(Criteria, long, long)
62 public static boolean pollForCriteria(Criteria criteria)
63 throws InterruptedException {
64 return pollForCriteria(criteria, DEFAULT_MAX_TIME_TO_POLL,
65 DEFAULT_POLLING_INTERVAL);
69 * Performs the runnable action, then checks whether the given criteria are
70 * satisfied until the specified timeout, using the pollForCriteria method.
71 * If not, then the runnable action is performed again, to a maximum of
74 public static boolean runUntilCriteria(Runnable runnable, Criteria criteria,
75 int maxAttempts, long maxTimeoutMs, long checkIntervalMs)
76 throws InterruptedException {
78 boolean success = false;
79 while (count < maxAttempts && !success) {
82 success = pollForCriteria(criteria, maxTimeoutMs, checkIntervalMs);