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 android.tools.flicker.rules
18 
19 import android.app.Instrumentation
20 import android.tools.FLICKER_TAG
21 import android.tools.device.apphelpers.StandardAppHelper
22 import android.tools.traces.component.ComponentNameMatcher
23 import android.tools.traces.parsers.WindowManagerStateHelper
24 import android.tools.withTracing
25 import android.util.Log
26 import androidx.test.platform.app.InstrumentationRegistry
27 import org.junit.rules.TestWatcher
28 import org.junit.runner.Description
29 
30 /**
31  * Launches an app before the test
32  *
33  * @param instrumentation Instrumentation mechanism to use
34  * @param wmHelper WM/SF synchronization helper
35  * @param appHelper App to launch
36  * @param clearCacheAfterParsing If the caching used while parsing the proto should be
37  *
38  * ```
39  *                               cleared or remain in memory
40  * ```
41  */
42 class LaunchAppRule
43 @JvmOverloads
44 constructor(
45     private val appHelper: StandardAppHelper,
46     private val instrumentation: Instrumentation = appHelper.instrumentation,
47     private val clearCacheAfterParsing: Boolean = true,
48     private val wmHelper: WindowManagerStateHelper =
49         WindowManagerStateHelper(clearCacheAfterParsing = clearCacheAfterParsing)
50 ) : TestWatcher() {
51     @JvmOverloads
52     constructor(
53         componentMatcher: ComponentNameMatcher,
54         appName: String = "",
55         instrumentation: Instrumentation = InstrumentationRegistry.getInstrumentation(),
56         clearCache: Boolean = true,
57         wmHelper: WindowManagerStateHelper =
58             WindowManagerStateHelper(clearCacheAfterParsing = clearCache)
59     ) : this(
60         StandardAppHelper(instrumentation, appName, componentMatcher),
61         instrumentation,
62         clearCache,
63         wmHelper
64     )
65 
startingnull66     override fun starting(description: Description?) {
67         withTracing("LaunchAppRule:starting") {
68             Log.v(FLICKER_TAG, "Launching app $appHelper")
69             appHelper.launchViaIntent()
70             appHelper.exit(wmHelper)
71         }
72     }
73 }
74