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 javax.annotation.CheckReturnValue
24
25 /**
26 * Utility to do cleanup in tests without replacing exceptions with those from a finally block.
27 *
28 * This utility is meant for tests that want to do cleanup after they execute their test
29 * logic, whether the test fails (and throws) or not.
30 *
31 * The usual way of doing this is to have a try{}finally{} block and put cleanup in finally{}.
32 * However, if any code in finally{} throws, the exception thrown in finally{} is thrown before
33 * any thrown in try{} ; that means errors reported from tests are from finally{} even if they
34 * have been caused by errors in try{}. This is unhelpful in tests, because it results in a
35 * stacktrace for a symptom rather than a stacktrace for a cause.
36 *
37 * To alleviate this, tests are encouraged to make sure the code in finally{} can't throw, or
38 * that the code in try{} can't cause it to fail. This is not always realistic ; not only does
39 * it require the developer thinks about complex interactions of code, test code often relies
40 * on bricks provided by other teams, not controlled by the team writing the test, which may
41 * start throwing with an update (see b/198998862 for an example).
42 *
43 * This utility allows a different approach : it offers a new construct, tryTest{}cleanup{} similar
44 * to try{}finally{}, but that will always throw the first exception that happens. In other words,
45 * if only tryTest{} throws or only cleanup{} throws, that exception will be thrown, but contrary
46 * to the standard try{}finally{}, if both throws, the construct throws the exception that happened
47 * in tryTest{} rather than the one that happened in cleanup{}.
48 *
49 * Kotlin usage is as try{}finally{}, but with multiple finally{} blocks :
50 * tryTest {
51 * testing code
52 * } cleanupStep {
53 * cleanup code 1
54 * } cleanupStep {
55 * cleanup code 2
56 * } cleanup {
57 * cleanup code 3
58 * }
59 * Catch blocks can be added with the following syntax :
60 * tryTest {
61 * testing code
62 * }.catch<ExceptionType> { it ->
63 * do something to it
64 * }
65 *
66 * Java doesn't allow this kind of syntax, so instead a function taking lambdas is provided.
67 * testAndCleanup(() -> {
68 * testing code
69 * }, () -> {
70 * cleanup code 1
71 * }, () -> {
72 * cleanup code 2
73 * });
74 */
75
76 @CheckReturnValue
77 fun <T> tryTest(block: () -> T) = TryExpr(
78 try {
79 Result.success(block())
80 } catch (e: Throwable) {
81 Result.failure(e)
82 })
83
84 // Some downstream branches have an older kotlin that doesn't know about value classes.
85 // TODO : Change this to "value class" when aosp no longer merges into such branches.
86 @Suppress("INLINE_CLASS_DEPRECATED")
87 inline class TryExpr<T>(val result: Result<T>) {
catchnull88 inline infix fun <reified E : Throwable> catch(block: (E) -> T): TryExpr<T> {
89 val originalException = result.exceptionOrNull()
90 if (originalException !is E) return this
91 return TryExpr(try {
92 Result.success(block(originalException))
93 } catch (e: Throwable) {
94 Result.failure(e)
95 })
96 }
97
98 @CheckReturnValue
cleanupStepnull99 inline infix fun cleanupStep(block: () -> Unit): TryExpr<T> {
100 try {
101 block()
102 } catch (e: Throwable) {
103 val originalException = result.exceptionOrNull()
104 return TryExpr(if (null == originalException) {
105 Result.failure(e)
106 } else {
107 originalException.addSuppressed(e)
108 Result.failure(originalException)
109 })
110 }
111 return this
112 }
113
cleanupnull114 inline infix fun cleanup(block: () -> Unit): T = cleanupStep(block).result.getOrThrow()
115 }
116
117 // Java support
118 fun <T> testAndCleanup(tryBlock: ThrowingSupplier<T>, vararg cleanupBlock: ThrowingRunnable): T {
119 return cleanupBlock.fold(tryTest { tryBlock.get() }) { previousExpr, nextCleanup ->
120 previousExpr.cleanupStep { nextCleanup.run() }
121 }.cleanup {}
122 }
testAndCleanupnull123 fun testAndCleanup(tryBlock: ThrowingRunnable, vararg cleanupBlock: ThrowingRunnable) {
124 return testAndCleanup(ThrowingSupplier { tryBlock.run() }, *cleanupBlock)
125 }
126