1 /*
<lambda>null2  * Copyright (C) 2024 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.permissionmultidevice.cts
18 
19 import android.os.SystemClock
20 import androidx.test.uiautomator.BySelector
21 import androidx.test.uiautomator.StaleObjectException
22 import androidx.test.uiautomator.UiObject2
23 import com.android.compatibility.common.util.UiAutomatorUtils2
24 import com.google.common.truth.Truth
25 
26 object UiAutomatorUtils {
27     fun waitFindObject(selector: BySelector): UiObject2 {
28         return findObjectWithRetry({ t -> UiAutomatorUtils2.waitFindObject(selector, t) })!!
29     }
30 
31     fun waitFindObject(selector: BySelector, timeoutMillis: Long): UiObject2 {
32         return findObjectWithRetry(
33             { t -> UiAutomatorUtils2.waitFindObject(selector, t) },
34             timeoutMillis
35         )!!
36     }
37 
38     fun click(selector: BySelector, timeoutMillis: Long = 20_000) {
39         waitFindObject(selector, timeoutMillis).click()
40     }
41 
42     fun findTextForView(selector: BySelector): String {
43         val timeoutMs = 10000L
44 
45         var exception: Exception? = null
46         var view: UiObject2? = null
47         try {
48             view = waitFindObject(selector, timeoutMs)
49         } catch (e: Exception) {
50             exception = e
51         }
52         Truth.assertThat(exception).isNull()
53         Truth.assertThat(view).isNotNull()
54         return view!!.text
55     }
56 
57     private fun findObjectWithRetry(
58         automatorMethod: (timeoutMillis: Long) -> UiObject2?,
59         timeoutMillis: Long = 20_000L
60     ): UiObject2? {
61         val startTime = SystemClock.elapsedRealtime()
62         return try {
63             automatorMethod(timeoutMillis)
64         } catch (e: StaleObjectException) {
65             val remainingTime = timeoutMillis - (SystemClock.elapsedRealtime() - startTime)
66             if (remainingTime <= 0) {
67                 throw e
68             }
69             automatorMethod(remainingTime)
70         }
71     }
72 }
73