1 /*
2  * Copyright (C) 2022 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.companion.cts.common
18 
19 import kotlin.time.Duration
20 import kotlin.time.Duration.Companion.milliseconds
21 import kotlin.time.Duration.Companion.seconds
22 
23 interface InvocationTracker<T> {
24     val invocations: List<T>
25 
26     /**
27      * Await invocations of this callback by the given [actions].
28      */
assertInvokedByActionsnull29     fun assertInvokedByActions(
30         timeout: Duration = 1.seconds,
31         minOccurrences: Int = 1,
32         actions: () -> Unit
33     ) {
34         require(minOccurrences > 0) {
35             "Must expect at least one callback occurrence. (Given $minOccurrences)"
36         }
37         val expectedInvocationCount = invocations.size + minOccurrences
38         actions()
39         if (!waitFor(timeout, interval = 100.milliseconds) {
40                 invocations.size >= expectedInvocationCount
41         }) {
42             throw AssertionError(
43                 "Callback was invoked ${invocations.size} times after $timeout ms! " +
44                         "Expected at least $minOccurrences times."
45             )
46         }
47     }
48 
clearRecordedInvocationsnull49     fun clearRecordedInvocations()
50 
51     fun recordInvocation(invocation: T)
52 }
53 
54 internal class InvocationContainer<T> : InvocationTracker<T> {
55     private val _invocations: MutableList<T> = mutableListOf()
56     override val invocations: List<T>
57         @Synchronized
58         get() = _invocations
59 
60     @Synchronized
61     override fun clearRecordedInvocations() = _invocations.clear()
62 
63     @Synchronized
64     override fun recordInvocation(invocation: T) {
65         _invocations.add(invocation)
66     }
67 }
68