1 /*
<lambda>null2  * Copyright (C) 2019 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 android.net.testutils
18 
19 import android.os.HandlerThread
20 import com.android.testutils.waitForIdle
21 import org.junit.Test
22 import org.junit.runner.RunWith
23 import org.junit.runners.JUnit4
24 import kotlin.test.assertEquals
25 
26 const val ATTEMPTS = 50 // Causes the test to take about 150ms on aosp_crosshatch-eng.
27 const val TIMEOUT_MS = 200
28 
29 @RunWith(JUnit4::class)
30 class HandlerUtilsTest {
31     @Test
32     fun testWaitForIdle() {
33         val handlerThread = HandlerThread("testHandler").apply { start() }
34 
35         // Tests that waitForIdle can be called many times without ill impact if the service is
36         // already idle.
37         repeat(ATTEMPTS) {
38             handlerThread.waitForIdle(TIMEOUT_MS)
39         }
40 
41         // Tests that calling waitForIdle waits for messages to be processed. Use both an
42         // inline runnable that's instantiated at each loop run and a runnable that's instantiated
43         // once for all.
44         val tempRunnable = object : Runnable {
45             // Use StringBuilder preferentially to StringBuffer because StringBuilder is NOT
46             // thread-safe. It's part of the point that both runnables run on the same thread
47             // so if anything is wrong in that space it's better to opportunistically use a class
48             // where things might go wrong, even if there is no guarantee of failure.
49             var memory = StringBuilder()
50             override fun run() {
51                 memory.append("b")
52             }
53         }
54         repeat(ATTEMPTS) { i ->
55             handlerThread.threadHandler.post({ tempRunnable.memory.append("a"); })
56             handlerThread.threadHandler.post(tempRunnable)
57             handlerThread.waitForIdle(TIMEOUT_MS)
58             assertEquals(tempRunnable.memory.toString(), "ab".repeat(i + 1))
59         }
60     }
61 }
62