1 /*
2  * Copyright (C) 2020 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.testutils
18 
19 import com.android.net.module.util.ArrayTrackRecord
20 import kotlin.test.assertEquals
21 import kotlin.test.fail
22 
23 private const val DEFAULT_TIMEOUT_MS = 200L
24 
25 open class TestableNetworkStatsProviderBinder : NetworkStatsProviderStubCompat() {
26     sealed class CallbackType {
27         data class OnRequestStatsUpdate(val token: Int) : CallbackType()
28         data class OnSetAlert(val quotaBytes: Long) : CallbackType()
29         data class OnSetWarningAndLimit(
30             val iface: String,
31             val warningBytes: Long,
32             val limitBytes: Long
33         ) : CallbackType()
34     }
35 
36     private val history = ArrayTrackRecord<CallbackType>().ReadHead()
37 
onRequestStatsUpdatenull38     override fun onRequestStatsUpdate(token: Int) {
39         history.add(CallbackType.OnRequestStatsUpdate(token))
40     }
41 
onSetAlertnull42     override fun onSetAlert(quotaBytes: Long) {
43         history.add(CallbackType.OnSetAlert(quotaBytes))
44     }
45 
onSetWarningAndLimitnull46     override fun onSetWarningAndLimit(iface: String, warningBytes: Long, limitBytes: Long) {
47         history.add(CallbackType.OnSetWarningAndLimit(iface, warningBytes, limitBytes))
48     }
49 
expectOnRequestStatsUpdatenull50     fun expectOnRequestStatsUpdate(token: Int) {
51         assertEquals(CallbackType.OnRequestStatsUpdate(token), history.poll(DEFAULT_TIMEOUT_MS))
52     }
53 
expectOnSetWarningAndLimitnull54     fun expectOnSetWarningAndLimit(iface: String, warningBytes: Long, limitBytes: Long) {
55         assertEquals(CallbackType.OnSetWarningAndLimit(iface, warningBytes, limitBytes),
56                 history.poll(DEFAULT_TIMEOUT_MS))
57     }
58 
expectOnSetAlertnull59     fun expectOnSetAlert(quotaBytes: Long) {
60         assertEquals(CallbackType.OnSetAlert(quotaBytes), history.poll(DEFAULT_TIMEOUT_MS))
61     }
62 
63     @JvmOverloads
assertNoCallbacknull64     fun assertNoCallback(timeout: Long = DEFAULT_TIMEOUT_MS) {
65         val cb = history.poll(timeout)
66         cb?.let { fail("Expected no callback but got $cb") }
67     }
68 }
69