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.safetycenter.testing
18 
19 import org.junit.rules.TestRule
20 import org.junit.runner.Description
21 import org.junit.runners.model.Statement
22 
23 /** A JUnit [TestRule] that performs setup and reset steps before and after Safety Center tests. */
24 class SafetyCenterTestRule(
25     private val safetyCenterTestHelper: SafetyCenterTestHelper,
26     private val withNotifications: Boolean = false
27 ) : TestRule {
28 
applynull29     override fun apply(base: Statement, description: Description): Statement {
30         return object : Statement() {
31             override fun evaluate() {
32                 setup()
33                 try {
34                     base.evaluate()
35                 } finally {
36                     reset()
37                 }
38             }
39         }
40     }
41 
setupnull42     private fun setup() {
43         safetyCenterTestHelper.setup()
44         if (withNotifications) {
45             TestNotificationListener.setup(safetyCenterTestHelper.context)
46         }
47     }
48 
resetnull49     private fun reset() {
50         safetyCenterTestHelper.reset()
51         if (withNotifications) {
52             // It is important to reset the notification listener last because it waits/ensures that
53             // all notifications have been removed before returning.
54             TestNotificationListener.reset(safetyCenterTestHelper.context)
55         }
56     }
57 }
58