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 com.android.internal.util;
18 
19 import static org.junit.Assert.fail;
20 
21 import android.os.ConditionVariable;
22 import android.os.Handler;
23 import android.os.HandlerThread;
24 import android.os.Looper;
25 
26 public final class TestUtils {
TestUtils()27     private TestUtils() { }
28 
29     /**
30      * Block until the given Handler thread becomes idle, or until timeoutMs has passed.
31      */
waitForIdleHandler(HandlerThread handlerThread, long timeoutMs)32     public static void waitForIdleHandler(HandlerThread handlerThread, long timeoutMs) {
33         waitForIdleHandler(handlerThread.getThreadHandler(), timeoutMs);
34     }
35 
36     /**
37      * Block until the given Looper becomes idle, or until timeoutMs has passed.
38      */
waitForIdleLooper(Looper looper, long timeoutMs)39     public static void waitForIdleLooper(Looper looper, long timeoutMs) {
40         waitForIdleHandler(new Handler(looper), timeoutMs);
41     }
42 
43     /**
44      * Block until the given Handler becomes idle, or until timeoutMs has passed.
45      */
waitForIdleHandler(Handler handler, long timeoutMs)46     public static void waitForIdleHandler(Handler handler, long timeoutMs) {
47         final ConditionVariable cv = new ConditionVariable();
48         handler.post(() -> cv.open());
49         if (!cv.block(timeoutMs)) {
50             fail(handler.toString() + " did not become idle after " + timeoutMs + " ms");
51         }
52     }
53 }
54