1 /* 2 * Copyright (C) 2023 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.telephony.imsmedia; 18 19 import static org.junit.Assert.fail; 20 21 import android.testing.TestableLooper; 22 23 import org.junit.After; 24 import org.junit.Before; 25 26 import java.util.ArrayList; 27 import java.util.List; 28 29 public class ImsMediaTest { 30 protected List<TestableLooper> mTestableLoopers = new ArrayList<>(); 31 protected TestableLooper mTestableLooper; 32 protected Object mTestClass; 33 34 @Before setUp()35 public void setUp() { 36 mTestableLooper = TestableLooper.get(mTestClass); 37 if (mTestableLooper != null) { 38 monitorTestableLooper(mTestableLooper); 39 } 40 } 41 42 @After tearDown()43 public void tearDown() throws Exception { 44 if (!mTestableLoopers.isEmpty()) { 45 for (TestableLooper looper : mTestableLoopers) { 46 looper.getLooper().quit(); 47 } 48 } 49 // Unmonitor TestableLooper for ImsMediaTest class 50 if (mTestableLooper != null) { 51 unmonitorTestableLooper(mTestableLooper); 52 } 53 // Destroy all newly created TestableLoopers so they can be reused 54 for (TestableLooper looper : mTestableLoopers) { 55 looper.destroy(); 56 } 57 TestableLooper.remove(mTestClass); 58 59 } 60 monitorTestableLooper(TestableLooper looper)61 private void monitorTestableLooper(TestableLooper looper) { 62 if (!mTestableLoopers.contains(looper)) { 63 mTestableLoopers.add(looper); 64 } 65 } 66 unmonitorTestableLooper(TestableLooper looper)67 private void unmonitorTestableLooper(TestableLooper looper) { 68 if (mTestableLoopers.contains(looper)) { 69 mTestableLoopers.remove(looper); 70 } 71 } 72 areAllTestableLoopersIdle()73 private boolean areAllTestableLoopersIdle() { 74 for (TestableLooper looper : mTestableLoopers) { 75 if (!looper.getLooper().getQueue().isIdle()) return false; 76 } 77 return true; 78 } 79 processAllMessages()80 public void processAllMessages() { 81 if (mTestableLoopers.isEmpty()) { 82 fail("mTestableLoopers is empty. Please make sure to add @RunWithLooper annotation"); 83 } 84 while (!areAllTestableLoopersIdle()) { 85 for (TestableLooper looper : mTestableLoopers) looper.processAllMessages(); 86 } 87 } 88 } 89