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