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.flicker.assertions
18 
19 /**
20  * Utility class to store assertions with an identifier to help generate more useful debug data when
21  * dealing with multiple assertions.
22  *
23  * @param predicate Assertion to execute
24  * @param name Assertion name
25  * @param isOptional If the assertion is optional (can fail) or not (must pass)
26  */
27 open class NamedAssertion<T>(
28     val predicate: (T) -> Unit,
29     override val name: String,
30     override val isOptional: Boolean = false
31 ) : Assertion<T> {
invokenull32     override operator fun invoke(target: T) = predicate(target)
33     override fun toString(): String = "Assertion($name)${if (isOptional) "[optional]" else ""}"
34 
35     /**
36      * We can't check the actual assertion is the same. We are checking for the name, which should
37      * have a 1:1 correspondence with the assertion, but there is no actual guarantee of the same
38      * execution of the assertion even if isEqual() is true.
39      */
40     override fun equals(other: Any?): Boolean {
41         if (other !is NamedAssertion<*>) {
42             return false
43         }
44         if (name != other.name) {
45             return false
46         }
47         if (isOptional != other.isOptional) {
48             return false
49         }
50         return true
51     }
52 
hashCodenull53     override fun hashCode(): Int {
54         var result = predicate.hashCode()
55         result = 31 * result + name.hashCode()
56         result = 31 * result + isOptional.hashCode()
57         return result
58     }
59 }
60