1 /*
<lambda>null2  * Copyright (C) 2021 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 @file:JvmName("Cleanup")
18 
19 package com.android.testutils
20 
21 import com.android.testutils.FunctionalUtils.ThrowingRunnable
22 import com.android.testutils.FunctionalUtils.ThrowingSupplier
23 import java.util.function.Consumer
24 import javax.annotation.CheckReturnValue
25 
26 /**
27  * Utility to do cleanup in tests without replacing exceptions with those from a finally block.
28  *
29  * This utility is meant for tests that want to do cleanup after they execute their test
30  * logic, whether the test fails (and throws) or not.
31  *
32  * The usual way of doing this is to have a try{}finally{} block and put cleanup in finally{}.
33  * However, if any code in finally{} throws, the exception thrown in finally{} is thrown before
34  * any thrown in try{} ; that means errors reported from tests are from finally{} even if they
35  * have been caused by errors in try{}. This is unhelpful in tests, because it results in a
36  * stacktrace for a symptom rather than a stacktrace for a cause.
37  *
38  * To alleviate this, tests are encouraged to make sure the code in finally{} can't throw, or
39  * that the code in try{} can't cause it to fail. This is not always realistic ; not only does
40  * it require the developer thinks about complex interactions of code, test code often relies
41  * on bricks provided by other teams, not controlled by the team writing the test, which may
42  * start throwing with an update (see b/198998862 for an example).
43  *
44  * This utility allows a different approach : it offers a new construct, tryTest{}cleanup{} similar
45  * to try{}finally{}, but that will always throw the first exception that happens. In other words,
46  * if only tryTest{} throws or only cleanup{} throws, that exception will be thrown, but contrary
47  * to the standard try{}finally{}, if both throws, the construct throws the exception that happened
48  * in tryTest{} rather than the one that happened in cleanup{}.
49  *
50  * Kotlin usage is as try{}finally{}, but with multiple finally{} blocks :
51  * tryTest {
52  *   testing code
53  * } cleanupStep {
54  *   cleanup code 1
55  * } cleanupStep {
56  *   cleanup code 2
57  * } cleanup {
58  *   cleanup code 3
59  * }
60  * Catch blocks can be added with the following syntax :
61  * tryTest {
62  *   testing code
63  * }.catch<ExceptionType> { it ->
64  *   do something to it
65  * }
66  *
67  * Java doesn't allow this kind of syntax, so instead a function taking lambdas is provided.
68  * testAndCleanup(() -> {
69  *   testing code
70  * }, () -> {
71  *   cleanup code 1
72  * }, () -> {
73  *   cleanup code 2
74  * });
75  */
76 
77 object TryTestConfig {
78     private var diagnosticsCollector: Consumer<Throwable>? = null
79 
80     /**
81      * Set the diagnostics collector to be used in case of failure in [tryTest].
82      *
83      * @return The previous collector.
84      */
85     fun swapDiagnosticsCollector(collector: Consumer<Throwable>?): Consumer<Throwable>? {
86         val oldCollector = diagnosticsCollector
87         diagnosticsCollector = collector
88         return oldCollector
89     }
90 
91     fun reportError(e: Throwable) {
92         diagnosticsCollector?.accept(e)
93     }
94 }
95 
96 @CheckReturnValue
tryTestnull97 fun <T> tryTest(block: () -> T) = TryExpr(
98         try {
99             Result.success(block())
100         } catch (e: Throwable) {
101             Result.failure(e)
102         }, skipErrorReporting = false)
103 
104 class TryExpr<T>(val result: Result<T>, val skipErrorReporting: Boolean) {
catchnull105     inline infix fun <reified E : Throwable> catch(block: (E) -> T): TryExpr<T> {
106         val originalException = result.exceptionOrNull()
107         if (originalException !is E) return this
108         return TryExpr(try {
109             Result.success(block(originalException))
110         } catch (e: Throwable) {
111             Result.failure(e)
112         }, this.skipErrorReporting)
113     }
114 
115     @CheckReturnValue
cleanupStepnull116     inline infix fun cleanupStep(block: () -> Unit): TryExpr<T> {
117         // Report errors before the cleanup step, but after catch blocks that may suppress it
118         val originalException = result.exceptionOrNull()
119         var nextSkipErrorReporting = skipErrorReporting
120         if (!skipErrorReporting && originalException != null) {
121             TryTestConfig.reportError(originalException)
122             nextSkipErrorReporting = true
123         }
124         try {
125             block()
126         } catch (e: Throwable) {
127             return if (null == originalException) {
128                 if (!skipErrorReporting) {
129                     TryTestConfig.reportError(e)
130                 }
131                 TryExpr(Result.failure(e), skipErrorReporting = true)
132             } else {
133                 originalException.addSuppressed(e)
134                 TryExpr(Result.failure(originalException), true)
135             }
136         }
137         return TryExpr(result, nextSkipErrorReporting)
138     }
139 
cleanupnull140     inline infix fun cleanup(block: () -> Unit): T = cleanupStep(block).result.getOrThrow()
141 }
142 
143 // Java support
144 fun <T> testAndCleanup(tryBlock: ThrowingSupplier<T>, vararg cleanupBlock: ThrowingRunnable): T {
145     return cleanupBlock.fold(tryTest { tryBlock.get() }) { previousExpr, nextCleanup ->
146         previousExpr.cleanupStep { nextCleanup.run() }
147     }.cleanup {}
148 }
testAndCleanupnull149 fun testAndCleanup(tryBlock: ThrowingRunnable, vararg cleanupBlock: ThrowingRunnable) {
150     return testAndCleanup(ThrowingSupplier { tryBlock.run() }, *cleanupBlock)
151 }
152