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
17package androidx.webkit;
18
19import junit.framework.Assert;
20
21import java.util.concurrent.Callable;
22
23/**
24 * A class for checking a specific statement {@link #check()} through polling, either until the
25 * statement is true, or until timing out.
26 *
27 * Copy-pasted from CTS: com.android.compatibility.common.util.PollingCheck.
28 */
29public abstract class PollingCheck {
30    private static final long TIME_SLICE = 50;
31    private long mTimeout = 3000;
32
33    public PollingCheck(long timeout) {
34        mTimeout = timeout;
35    }
36
37    protected abstract boolean check();
38
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
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}
76