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 { 27 private TestUtils() { } 28 29 /** 30 * Block until the given Handler thread becomes idle, or until timeoutMs has passed. 31 */ 32 public static void waitForIdleHandler(HandlerThread handlerThread, long timeoutMs) { 33 // TODO: convert to getThreadHandler once it is available on aosp 34 waitForIdleLooper(handlerThread.getLooper(), timeoutMs); 35 } 36 37 /** 38 * Block until the given Looper becomes idle, or until timeoutMs has passed. 39 */ 40 public static void waitForIdleLooper(Looper looper, long timeoutMs) { 41 waitForIdleHandler(new Handler(looper), timeoutMs); 42 } 43 44 /** 45 * Block until the given Handler becomes idle, or until timeoutMs has passed. 46 */ 47 public static void waitForIdleHandler(Handler handler, long timeoutMs) { 48 final ConditionVariable cv = new ConditionVariable(); 49 handler.post(() -> cv.open()); 50 if (!cv.block(timeoutMs)) { 51 fail(handler.toString() + " did not become idle after " + timeoutMs + " ms"); 52 } 53 } 54 } 55