1 /*
2  * Copyright 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 package androidx.glance.testing
17 
18 /**
19  * Wrapper for matcher lambdas and related details
20  *
21  * @param description a string explaining to the developer what conditions were being tested.
22  * @param matcher a lambda performing the actual logic of matching on the GlanceNode
23  */
24 class GlanceNodeMatcher<R>(
25     internal val description: String,
26     private val matcher: (GlanceNode<R>) -> Boolean
27 ) {
28     /** Returns whether the given node is matched by this matcher. */
matchesnull29     fun matches(node: GlanceNode<R>): Boolean {
30         return matcher(node)
31     }
32 
33     /** Returns whether at least one of the given nodes is matched by this matcher. */
matchesAnynull34     fun matchesAny(nodes: Iterable<GlanceNode<R>>): Boolean {
35         return nodes.any(matcher)
36     }
37 
38     /**
39      * Returns whether the given node is matched by this and the [other] matcher.
40      *
41      * @param other matcher that should also match in addition to current matcher
42      */
andnull43     infix fun and(other: GlanceNodeMatcher<R>): GlanceNodeMatcher<R> {
44         return GlanceNodeMatcher("($description) && (${other.description})") {
45             matcher(it) && other.matches(it)
46         }
47     }
48 
49     /**
50      * Returns whether the given node is matched by this or the [other] matcher.
51      *
52      * @param other matcher that can be tested to match if the current matcher doesn't.
53      */
ornull54     infix fun or(other: GlanceNodeMatcher<R>): GlanceNodeMatcher<R> {
55         return GlanceNodeMatcher("($description) || (${other.description})") {
56             matcher(it) || other.matches(it)
57         }
58     }
59 
60     /** Returns whether the given node does not match the matcher. */
notnull61     operator fun not(): GlanceNodeMatcher<R> {
62         return GlanceNodeMatcher(("NOT ($description)")) { !matcher(it) }
63     }
64 }
65