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.testutils 18 19 import android.net.NetworkCapabilities 20 import android.net.NetworkProvider 21 import android.net.NetworkRequest 22 import android.util.Log 23 import com.android.net.module.util.ArrayTrackRecord 24 import kotlin.test.fail 25 26 class TestableNetworkOfferCallback(val timeoutMs: Long, private val noCallbackTimeoutMs: Long) 27 : NetworkProvider.NetworkOfferCallback { 28 private val TAG = this::class.simpleName 29 val history = ArrayTrackRecord<CallbackEntry>().newReadHead() 30 31 sealed class CallbackEntry { 32 data class OnNetworkNeeded(val request: NetworkRequest) : CallbackEntry() 33 data class OnNetworkUnneeded(val request: NetworkRequest) : CallbackEntry() 34 } 35 36 /** 37 * Called by the system when a network for this offer is needed to satisfy some 38 * networking request. 39 */ onNetworkNeedednull40 override fun onNetworkNeeded(request: NetworkRequest) { 41 Log.d(TAG, "onNetworkNeeded $request") 42 history.add(CallbackEntry.OnNetworkNeeded(request)) 43 } 44 45 /** 46 * Called by the system when this offer is no longer valuable for this request. 47 */ onNetworkUnneedednull48 override fun onNetworkUnneeded(request: NetworkRequest) { 49 Log.d(TAG, "onNetworkUnneeded $request") 50 history.add(CallbackEntry.OnNetworkUnneeded(request)) 51 } 52 expectCallbackThatnull53 inline fun <reified T : CallbackEntry> expectCallbackThat( 54 crossinline predicate: (T) -> Boolean 55 ) { 56 val event = history.poll(timeoutMs) 57 ?: fail("Did not receive callback after ${timeoutMs}ms") 58 if (event !is T || !predicate(event)) fail("Received unexpected callback $event") 59 } 60 expectOnNetworkNeedednull61 fun expectOnNetworkNeeded(capabilities: NetworkCapabilities) = 62 expectCallbackThat<CallbackEntry.OnNetworkNeeded> { 63 it.request.canBeSatisfiedBy(capabilities) 64 } 65 expectOnNetworkUnneedednull66 fun expectOnNetworkUnneeded(capabilities: NetworkCapabilities) = 67 expectCallbackThat<CallbackEntry.OnNetworkUnneeded> { 68 it.request.canBeSatisfiedBy(capabilities) 69 } 70 assertNoCallbacknull71 fun assertNoCallback() { 72 val cb = history.poll(noCallbackTimeoutMs) 73 if (null != cb) fail("Expected no callback but got $cb") 74 } 75 }