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.net.module.util 18 19 import android.os.HandlerThread 20 import com.android.testutils.DevSdkIgnoreRunner 21 import com.android.testutils.DevSdkIgnoreRunner.MonitorThreadLeak 22 import com.android.testutils.waitForIdle 23 import kotlin.test.assertEquals 24 import kotlin.test.assertTrue 25 import org.junit.After 26 import org.junit.Test 27 import org.junit.runner.RunWith 28 import kotlin.test.assertFailsWith 29 import kotlin.test.assertFalse 30 31 const val THREAD_BLOCK_TIMEOUT_MS = 1000L 32 const val TEST_REPEAT_COUNT = 100 33 34 @MonitorThreadLeak 35 @RunWith(DevSdkIgnoreRunner::class) 36 class HandlerUtilsTest { <lambda>null37 val handlerThread = HandlerThread("HandlerUtilsTestHandlerThread").also { 38 it.start() 39 } 40 val handler = handlerThread.threadHandler 41 42 @Test testRunWithScissorsnull43 fun testRunWithScissors() { 44 // Repeat the test a fair amount of times to ensure that it does not pass by chance. 45 repeat(TEST_REPEAT_COUNT) { 46 var result = false 47 HandlerUtils.runWithScissorsForDump(handler, { 48 assertEquals(Thread.currentThread(), handlerThread) 49 result = true 50 }, THREAD_BLOCK_TIMEOUT_MS) 51 // Assert that the result is modified on the handler thread, but can also be seen from 52 // the current thread. The assertion should pass if the runWithScissors provides 53 // the guarantee where the assignment happens-before the assertion. 54 assertTrue(result) 55 } 56 } 57 58 @Test testIsRunningOnHandlerThreadnull59 fun testIsRunningOnHandlerThread() { 60 assertFalse(HandlerUtils.isRunningOnHandlerThread(handler)) 61 handler.post{ 62 assertTrue(HandlerUtils.isRunningOnHandlerThread(handler)) 63 } 64 handler.waitForIdle(THREAD_BLOCK_TIMEOUT_MS) 65 } 66 67 @Test testEnsureRunningOnHandlerThreadnull68 fun testEnsureRunningOnHandlerThread() { 69 assertFailsWith<IllegalStateException>{ HandlerUtils.ensureRunningOnHandlerThread(handler) } 70 handler.post{ 71 HandlerUtils.ensureRunningOnHandlerThread(handler) 72 } 73 handler.waitForIdle(THREAD_BLOCK_TIMEOUT_MS) 74 } 75 76 @After tearDownnull77 fun tearDown() { 78 handlerThread.quitSafely() 79 handlerThread.join() 80 } 81 } 82