• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * 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 com.android.systemui
18 
19 import org.junit.rules.TestWatcher
20 import org.junit.runner.Description
21 import org.junit.runners.model.MultipleFailureException
22 
23 /**
24  * Rule that allows teardown steps to be added right next to the places where it becomes clear they
25  * are needed. This can avoid the need for complicated or conditional logic in a single teardown
26  * method. Examples:
27  * ```
28  * @get:Rule teardownRule = OnTeardownRule()
29  *
30  * // setup and teardown right next to each other
31  * @Before
32  * fun setUp() {
33  *   val oldTimeout = getGlobalTimeout()
34  *   teardownRule.onTeardown { setGlobalTimeout(oldTimeout) }
35  *   overrideGlobalTimeout(5000)
36  * }
37  *
38  * // add teardown logic for fixtures that aren't used in every test
39  * fun addCustomer() {
40  *   val id = globalDatabase.addCustomer(TEST_NAME, TEST_ADDRESS, ...)
41  *   teardownRule.onTeardown { globalDatabase.deleteCustomer(id) }
42  * }
43  * ```
44  */
45 class OnTeardownRule : TestWatcher() {
46     private var canAdd = true
47     private val teardowns = mutableListOf<() -> Unit>()
48 
onTeardownnull49     fun onTeardown(teardownRunnable: () -> Unit) {
50         if (!canAdd) {
51             throw IllegalStateException("Cannot add new teardown routines after test complete.")
52         }
53         teardowns.add(teardownRunnable)
54     }
55 
onTeardownnull56     fun onTeardown(teardownRunnable: Runnable) {
57         if (!canAdd) {
58             throw IllegalStateException("Cannot add new teardown routines after test complete.")
59         }
60         teardowns.add { teardownRunnable.run() }
61     }
62 
finishednull63     override fun finished(description: Description?) {
64         canAdd = false
65         val errors = mutableListOf<Throwable>()
66         teardowns.reversed().forEach {
67             try {
68                 it()
69             } catch (e: Throwable) {
70                 errors.add(e)
71             }
72         }
73         MultipleFailureException.assertEmpty(errors)
74     }
75 }
76