• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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.traces
18 
19 import java.util.function.Predicate
20 
21 /**
22  * The utility class to wait a condition with customized options. The default retry policy is 5
23  * times with interval 1 second.
24  *
25  * @param <T> The type of the object to validate.
26  *
27  * <p>Sample:</p> <pre> // Simple case. if (Condition.waitFor("true value", () -> true)) {
28  *
29  * ```
30  *     println("Success");
31  * ```
32  *
33  * } // Wait for customized result with customized validation. String result =
34  * Condition.waitForResult(new Condition<String>("string comparison")
35  *
36  * ```
37  *         .setResultSupplier(() -> "Result string")
38  *         .setResultValidator(str -> str.equals("Expected string"))
39  *         .setRetryIntervalMs(500)
40  *         .setRetryLimit(3)
41  *         .setOnFailure(str -> println("Failed on " + str)));
42  * ```
43  *
44  * </pre>
45  *
46  * @param message The message to show what is waiting for.
47  * @param condition If it returns true, that means the condition is satisfied.
48  */
49 open class Condition<T>
50 @JvmOverloads
51 constructor(protected open val message: String = "", protected open val condition: Predicate<T>) {
52     /** @return if [value] satisfies the condition */
isSatisfiednull53     fun isSatisfied(value: T): Boolean {
54         return condition.test(value)
55     }
56 
57     /** @return the negation of the current assertion */
<lambda>null58     fun negate(): Condition<T> = Condition(message = "!$message") { !this.condition.test(it) }
59 
60     /** @return a formatted message for the passing or failing condition on a state */
getMessagenull61     open fun getMessage(value: T): String = "$message(passed=${isSatisfied(value)})"
62 
63     override fun toString(): String = this.message
64 }
65