1 /* 2 * Copyright (C) 2024 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.Manifest.permission.MANAGE_TEST_NETWORKS 20 import android.content.Context 21 import android.net.TestNetworkInterface 22 import android.net.TestNetworkManager 23 import org.junit.rules.TestRule 24 import org.junit.runner.Description 25 import org.junit.runners.model.Statement 26 27 class AutoCloseTestInterfaceRule( 28 private val context: Context, 29 ) : TestRule { <lambda>null30 private val tnm = runAsShell(MANAGE_TEST_NETWORKS) { 31 context.getSystemService(TestNetworkManager::class.java)!! 32 } 33 private val ifaces = ArrayList<TestNetworkInterface>() 34 createTapInterfacenull35 fun createTapInterface(): TestNetworkInterface { 36 return runAsShell(MANAGE_TEST_NETWORKS) { 37 tnm.createTapInterface() 38 }.also { 39 ifaces.add(it) 40 } 41 } 42 closeAllInterfacesnull43 private fun closeAllInterfaces() { 44 // TODO: wait on RTM_DELLINK before proceeding. 45 for (iface in ifaces) { 46 // ParcelFileDescriptor prevents the fd from being double closed. 47 iface.getFileDescriptor().close() 48 } 49 } 50 51 private inner class AutoCloseTestInterfaceRuleStatement( 52 private val base: Statement, 53 private val description: Description 54 ) : Statement() { evaluatenull55 override fun evaluate() { 56 tryTest { 57 base.evaluate() 58 } cleanup { 59 closeAllInterfaces() 60 } 61 } 62 } 63 applynull64 override fun apply(base: Statement, description: Description): Statement { 65 return AutoCloseTestInterfaceRuleStatement(base, description) 66 } 67 } 68