1 /*
<lambda>null2 * Copyright 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 androidx.testutils
18
19 import android.app.Activity
20 import androidx.fragment.app.FragmentActivity
21 import androidx.test.core.app.ActivityScenario
22 import androidx.test.ext.junit.rules.ActivityScenarioRule
23 import java.io.Closeable
24
25 /** Run [block] using [ActivityScenario.onActivity], returning the result of the block. */
26 inline fun <reified A : Activity, T : Any> ActivityScenarioRule<A>.withActivity(
27 crossinline block: A.() -> T
28 ): T = scenario.withActivity(block)
29
30 /** Run [block] using [ActivityScenario.onActivity], returning the result of the block. */
31 inline fun <reified A : Activity, T : Any> ActivityScenario<A>.withActivity(
32 crossinline block: A.() -> T
33 ): T {
34 lateinit var value: T
35 var err: Throwable? = null
36 onActivity { activity ->
37 try {
38 value = block(activity)
39 } catch (t: Throwable) {
40 err = t
41 }
42 }
43 err?.let { throw it }
44 return value
45 }
46
waitForExecutionnull47 inline fun <reified A : FragmentActivity> ActivityScenario<A>.waitForExecution(cycles: Int = 2) {
48 try {
49 for (i in 0 until cycles) {
50 withActivity {}
51 }
52 } catch (throwable: Throwable) {
53 throw RuntimeException(throwable)
54 }
55 }
56
57 /**
58 * Run [block] in a [use] block when using [ActivityScenario.launch], rather than just a [with]
59 * block to ensure the Activity is closed once test is complete.
60 */
withUsenull61 fun <C : Closeable> withUse(closeable: C, block: C.() -> Unit) {
62 closeable.use { block(it) }
63 }
64