diff --git a/staticlibs/testutils/devicetests/com/android/testutils/CarrierConfigRule.kt b/staticlibs/testutils/devicetests/com/android/testutils/CarrierConfigRule.kt new file mode 100644 index 0000000000..a93ae3e1e6 --- /dev/null +++ b/staticlibs/testutils/devicetests/com/android/testutils/CarrierConfigRule.kt @@ -0,0 +1,127 @@ +/* + * Copyright (C) 2025 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.android.testutils.com.android.testutils + +import android.Manifest.permission.MODIFY_PHONE_STATE +import android.Manifest.permission.READ_PHONE_STATE +import android.os.PersistableBundle +import android.telephony.CarrierConfigManager +import android.util.Log +import androidx.test.platform.app.InstrumentationRegistry +import com.android.modules.utils.build.SdkLevel.isAtLeastU +import com.android.testutils.runAsShell +import com.android.testutils.tryTest +import kotlin.test.assertNotNull +import org.junit.rules.TestRule +import org.junit.runner.Description +import org.junit.runners.model.Statement + +private val TAG = CarrierConfigRule::class.simpleName + +/** + * A [TestRule] that helps set [CarrierConfigManager] overrides for tests and clean up the test + * configuration automatically on teardown. + */ +class CarrierConfigRule : TestRule { + private val ccm by lazy { InstrumentationRegistry.getInstrumentation().context.getSystemService( + CarrierConfigManager::class.java + ) } + + // Map of (subId) -> (original values of overridden settings) + private val originalConfigs = mutableMapOf() + + override fun apply(base: Statement, description: Description): Statement { + return CarrierConfigStatement(base, description) + } + + private inner class CarrierConfigStatement( + private val base: Statement, + private val description: Description + ) : Statement() { + override fun evaluate() { + tryTest { + base.evaluate() + } cleanup { + cleanUpNow() + } + } + } + + /** + * Add carrier config overrides with the specified configuration. + * + * The overrides will automatically be cleaned up when the test case finishes. + */ + fun addConfigOverrides(subId: Int, config: PersistableBundle) { + val originalConfig = originalConfigs.computeIfAbsent(subId) { PersistableBundle() } + val overrideKeys = config.keySet() + val previousValues = runAsShell(READ_PHONE_STATE) { + ccm.getConfigForSubIdCompat(subId, overrideKeys) + } + // If a key is already in the originalConfig, keep the oldest original overrides + originalConfig.keySet().forEach { + previousValues.remove(it) + } + originalConfig.putAll(previousValues) + + runAsShell(MODIFY_PHONE_STATE) { + ccm.overrideConfig(subId, config) + } + } + + /** + * Cleanup overrides that were added by the test case. + * + * This will be called automatically on test teardown, so it does not need to be called by the + * test case unless cleaning up earlier is required. + */ + fun cleanUpNow() { + runAsShell(MODIFY_PHONE_STATE) { + originalConfigs.forEach { (subId, config) -> + try { + // Do not use overrideConfig with null, as it would reset configs that may + // have been set by target preparers such as + // ConnectivityTestTargetPreparer / CarrierConfigSetupTest. + ccm.overrideConfig(subId, config) + } catch (e: Throwable) { + Log.e(TAG, "Error resetting carrier config for subId $subId") + } + } + originalConfigs.clear() + } + } +} + +private fun CarrierConfigManager.getConfigForSubIdCompat( + subId: Int, + keys: Set +): PersistableBundle { + return if (isAtLeastU()) { + // This method is U+ + getConfigForSubId(subId, *keys.toTypedArray()) + } else { + @Suppress("DEPRECATION") + val config = assertNotNull(getConfigForSubId(subId)) + val allKeys = config.keySet().toList() + allKeys.forEach { + if (!keys.contains(it)) { + config.remove(it) + } + } + config + } +} diff --git a/tests/cts/net/src/android/net/cts/ConnectivityDiagnosticsManagerTest.java b/tests/cts/net/src/android/net/cts/ConnectivityDiagnosticsManagerTest.java index ceb48d45ef..faaadeeb43 100644 --- a/tests/cts/net/src/android/net/cts/ConnectivityDiagnosticsManagerTest.java +++ b/tests/cts/net/src/android/net/cts/ConnectivityDiagnosticsManagerTest.java @@ -88,9 +88,11 @@ import com.android.modules.utils.build.SdkLevel; import com.android.net.module.util.ArrayTrackRecord; import com.android.testutils.DevSdkIgnoreRule.IgnoreUpTo; import com.android.testutils.DevSdkIgnoreRunner; +import com.android.testutils.com.android.testutils.CarrierConfigRule; import org.junit.After; import org.junit.Before; +import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; @@ -110,6 +112,9 @@ import java.util.concurrent.TimeUnit; public class ConnectivityDiagnosticsManagerTest { private static final String TAG = ConnectivityDiagnosticsManagerTest.class.getSimpleName(); + @Rule + public final CarrierConfigRule mCarrierConfigRule = new CarrierConfigRule(); + private static final int CALLBACK_TIMEOUT_MILLIS = 5000; private static final int NO_CALLBACK_INVOKED_TIMEOUT = 500; private static final long TIMESTAMP = 123456789L; @@ -264,9 +269,6 @@ public class ConnectivityDiagnosticsManagerTest { doBroadcastCarrierConfigsAndVerifyOnConnectivityReportAvailable( subId, carrierConfigReceiver, testNetworkCallback); }, () -> { - runWithShellPermissionIdentity( - () -> mCarrierConfigManager.overrideConfig(subId, null), - android.Manifest.permission.MODIFY_PHONE_STATE); mConnectivityManager.unregisterNetworkCallback(testNetworkCallback); mContext.unregisterReceiver(carrierConfigReceiver); }); @@ -291,9 +293,9 @@ public class ConnectivityDiagnosticsManagerTest { CarrierConfigManager.KEY_CARRIER_CERTIFICATE_STRING_ARRAY, new String[] {getCertHashForThisPackage()}); + mCarrierConfigRule.addConfigOverrides(subId, carrierConfigs); runWithShellPermissionIdentity( () -> { - mCarrierConfigManager.overrideConfig(subId, carrierConfigs); mCarrierConfigManager.notifyConfigChangedForSubId(subId); }, android.Manifest.permission.MODIFY_PHONE_STATE); diff --git a/tests/cts/net/src/android/net/cts/NetworkAgentTest.kt b/tests/cts/net/src/android/net/cts/NetworkAgentTest.kt index 815c3a5483..286e08cb9e 100644 --- a/tests/cts/net/src/android/net/cts/NetworkAgentTest.kt +++ b/tests/cts/net/src/android/net/cts/NetworkAgentTest.kt @@ -117,13 +117,13 @@ import com.android.testutils.CompatUtil import com.android.testutils.ConnectivityModuleTest import com.android.testutils.DevSdkIgnoreRule.IgnoreUpTo import com.android.testutils.DevSdkIgnoreRunner +import com.android.testutils.PollPacketReader import com.android.testutils.RecorderCallback.CallbackEntry.Available import com.android.testutils.RecorderCallback.CallbackEntry.BlockedStatus import com.android.testutils.RecorderCallback.CallbackEntry.CapabilitiesChanged import com.android.testutils.RecorderCallback.CallbackEntry.LinkPropertiesChanged import com.android.testutils.RecorderCallback.CallbackEntry.Losing import com.android.testutils.RecorderCallback.CallbackEntry.Lost -import com.android.testutils.PollPacketReader import com.android.testutils.TestableNetworkAgent import com.android.testutils.TestableNetworkAgent.CallbackEntry.OnAddKeepalivePacketFilter import com.android.testutils.TestableNetworkAgent.CallbackEntry.OnAutomaticReconnectDisabled @@ -140,6 +140,7 @@ import com.android.testutils.TestableNetworkAgent.CallbackEntry.OnUnregisterQosC import com.android.testutils.TestableNetworkAgent.CallbackEntry.OnValidationStatus import com.android.testutils.TestableNetworkCallback import com.android.testutils.assertThrows +import com.android.testutils.com.android.testutils.CarrierConfigRule import com.android.testutils.runAsShell import com.android.testutils.tryTest import com.android.testutils.waitForIdle @@ -149,8 +150,8 @@ import java.net.DatagramSocket import java.net.InetAddress import java.net.InetSocketAddress import java.net.Socket -import java.security.MessageDigest import java.nio.ByteBuffer +import java.security.MessageDigest import java.time.Duration import java.util.Arrays import java.util.Random @@ -167,6 +168,7 @@ import kotlin.test.fail import org.junit.After import org.junit.Assume.assumeTrue import org.junit.Before +import org.junit.Rule import org.junit.Test import org.junit.runner.RunWith import org.mockito.ArgumentMatchers.any @@ -178,10 +180,12 @@ import org.mockito.Mockito.timeout import org.mockito.Mockito.verify private const val TAG = "NetworkAgentTest" + // This test doesn't really have a constraint on how fast the methods should return. If it's // going to fail, it will simply wait forever, so setting a high timeout lowers the flake ratio // without affecting the run time of successful runs. Thus, set a very high timeout. private const val DEFAULT_TIMEOUT_MS = 5000L + // When waiting for a NetworkCallback to determine there was no timeout, waiting is the // only possible thing (the relevant handler is the one in the real ConnectivityService, // and then there is the Binder call), so have a short timeout for this as it will be @@ -223,6 +227,9 @@ private const val SHOULD_CREATE_NETWORKS_IMMEDIATELY = false @IgnoreUpTo(Build.VERSION_CODES.R) @RunWith(DevSdkIgnoreRunner::class) class NetworkAgentTest { + @get:Rule + val carrierConfigRule = CarrierConfigRule() + private val LOCAL_IPV4_ADDRESS = InetAddresses.parseNumericAddress("192.0.2.1") private val REMOTE_IPV4_ADDRESS = InetAddresses.parseNumericAddress("192.0.2.2") @@ -378,8 +385,12 @@ class NetworkAgentTest { // Ensure this NetworkAgent is never unneeded by filing a request with its specifier. requestNetwork(makeTestNetworkRequest(specifier), callback) val nc = makeTestNetworkCapabilities(specifier, transports) - val agent = createNetworkAgent(context, initialConfig = initialConfig, initialLp = lp, - initialNc = nc) + val agent = createNetworkAgent( + context, + initialConfig = initialConfig, + initialLp = lp, + initialNc = nc + ) agent.setTeardownDelayMillis(0) // Connect the agent and verify initial status callbacks. agent.register() @@ -414,7 +425,8 @@ class NetworkAgentTest { private fun createTunInterface(addrs: Collection = emptyList()): TestNetworkInterface = realContext.getSystemService( - TestNetworkManager::class.java)!!.createTunInterface(addrs).also { + TestNetworkManager::class.java + )!!.createTunInterface(addrs).also { ifacesToCleanUp.add(it) } @@ -546,9 +558,12 @@ class NetworkAgentTest { @Test fun testSocketKeepalive(): Unit = createNetworkAgentWithFakeCS().let { agent -> val packet = NattKeepalivePacketData( - LOCAL_IPV4_ADDRESS /* srcAddress */, 1234 /* srcPort */, - REMOTE_IPV4_ADDRESS /* dstAddress */, 4567 /* dstPort */, - ByteArray(100 /* size */)) + LOCAL_IPV4_ADDRESS /* srcAddress */, + 1234 /* srcPort */, + REMOTE_IPV4_ADDRESS /* dstAddress */, + 4567 /* dstPort */, + ByteArray(100 /* size */) + ) val slot = 4 val interval = 37 @@ -653,8 +668,13 @@ class NetworkAgentTest { uid: Int, expectUidsPresent: Boolean ) { - doTestAllowedUids(intArrayOf(transport), uid, expectUidsPresent, - specifier = null, transportInfo = null) + doTestAllowedUids( + intArrayOf(transport), + uid, + expectUidsPresent, + specifier = null, + transportInfo = null + ) } private fun doTestAllowedUidsWithSubId( @@ -689,15 +709,16 @@ class NetworkAgentTest { private fun setHoldCarrierPrivilege(hold: Boolean, subId: Int) { fun getCertHash(): String { - val pkgInfo = realContext.packageManager.getPackageInfo(realContext.opPackageName, - PackageManager.GET_SIGNATURES) + val pkgInfo = realContext.packageManager.getPackageInfo( + realContext.opPackageName, + PackageManager.GET_SIGNATURES + ) val digest = MessageDigest.getInstance("SHA-256") val certHash = digest.digest(pkgInfo.signatures!![0]!!.toByteArray()) return UiccUtil.bytesToHexString(certHash)!! } val tm = realContext.getSystemService(TelephonyManager::class.java)!! - val ccm = realContext.getSystemService(CarrierConfigManager::class.java)!! val cv = ConditionVariable() val cpb = PrivilegeWaiterCallback(cv) @@ -717,16 +738,13 @@ class NetworkAgentTest { return@tryTest } cv.close() - runAsShell(MODIFY_PHONE_STATE) { - val carrierConfigs = if (hold) { - PersistableBundle().also { - it.putStringArray(CarrierConfigManager.KEY_CARRIER_CERTIFICATE_STRING_ARRAY, - arrayOf(getCertHash())) - } - } else { - null - } - ccm.overrideConfig(subId, carrierConfigs) + if (hold) { + carrierConfigRule.addConfigOverrides(subId, PersistableBundle().also { + it.putStringArray(CarrierConfigManager.KEY_CARRIER_CERTIFICATE_STRING_ARRAY, + arrayOf(getCertHash())) + }) + } else { + carrierConfigRule.cleanUpNow() } assertTrue(cv.block(DEFAULT_TIMEOUT_MS), "Can't change carrier privilege") } cleanup { @@ -799,14 +817,19 @@ class NetworkAgentTest { val uid = try { realContext.packageManager.getApplicationInfo(servicePackage, 0).uid } catch (e: PackageManager.NameNotFoundException) { - fail("$servicePackage could not be installed, please check the SuiteApkInstaller" + - " installed CtsCarrierServicePackage.apk", e) + fail( + "$servicePackage could not be installed, please check the SuiteApkInstaller" + + " installed CtsCarrierServicePackage.apk", + e + ) } val tm = realContext.getSystemService(TelephonyManager::class.java)!! val defaultSubId = SubscriptionManager.getDefaultSubscriptionId() - assertTrue(defaultSubId != SubscriptionManager.INVALID_SUBSCRIPTION_ID, - "getDefaultSubscriptionId returns INVALID_SUBSCRIPTION_ID") + assertTrue( + defaultSubId != SubscriptionManager.INVALID_SUBSCRIPTION_ID, + "getDefaultSubscriptionId returns INVALID_SUBSCRIPTION_ID" + ) tryTest { // This process is not the carrier service UID, so allowedUids should be ignored in all // the following cases. @@ -910,8 +933,10 @@ class NetworkAgentTest { // If using the int ranking, agent1 must be upgraded to a better score so that there is // no ambiguity when agent2 connects that agent1 is still better. If using policy // ranking, this is not necessary. - agent1.sendNetworkScore(NetworkScore.Builder().setLegacyInt(BETTER_NETWORK_SCORE) - .build()) + agent1.sendNetworkScore( + NetworkScore.Builder().setLegacyInt(BETTER_NETWORK_SCORE) + .build() + ) // Connect the second agent. val (agent2, _) = createConnectedNetworkAgent() @@ -920,10 +945,12 @@ class NetworkAgentTest { // virtue of already satisfying the request. callback.assertNoCallback(NO_CALLBACK_TIMEOUT) // Now downgrade the score and expect the callback now prefers agent2 - agent1.sendNetworkScore(NetworkScore.Builder() + agent1.sendNetworkScore( + NetworkScore.Builder() .setLegacyInt(WORSE_NETWORK_SCORE) .setExiting(true) - .build()) + .build() + ) callback.expect(agent2.network!!) // tearDown() will unregister the requests and agents @@ -968,16 +995,20 @@ class NetworkAgentTest { // Check that the default network's transport is propagated to the VPN. var vpnNc = mCM.getNetworkCapabilities(agent.network!!) assertNotNull(vpnNc) - assertEquals(VpnManager.TYPE_VPN_SERVICE, - (vpnNc.transportInfo as VpnTransportInfo).type) + assertEquals( + VpnManager.TYPE_VPN_SERVICE, + (vpnNc.transportInfo as VpnTransportInfo).type + ) assertEquals(mySessionId, (vpnNc.transportInfo as VpnTransportInfo).sessionId) val testAndVpn = intArrayOf(TRANSPORT_TEST, TRANSPORT_VPN) assertTrue(vpnNc.hasAllTransports(testAndVpn)) assertFalse(vpnNc.hasCapability(NET_CAPABILITY_NOT_VPN)) - assertTrue(vpnNc.hasAllTransports(defaultNetworkTransports), - "VPN transports ${Arrays.toString(vpnNc.transportTypes)}" + - " lacking transports from ${Arrays.toString(defaultNetworkTransports)}") + assertTrue( + vpnNc.hasAllTransports(defaultNetworkTransports), + "VPN transports ${Arrays.toString(vpnNc.transportTypes)}" + + " lacking transports from ${Arrays.toString(defaultNetworkTransports)}" + ) // Check that when no underlying networks are announced the underlying transport disappears. agent.setUnderlyingNetworks(listOf()) @@ -999,9 +1030,11 @@ class NetworkAgentTest { // underlying networks, and because not congested, not roaming, and not suspended are the // default anyway. It's still useful as an extra check though. vpnNc = mCM.getNetworkCapabilities(agent.network!!)!! - for (cap in listOf(NET_CAPABILITY_NOT_CONGESTED, - NET_CAPABILITY_NOT_ROAMING, - NET_CAPABILITY_NOT_SUSPENDED)) { + for (cap in listOf( + NET_CAPABILITY_NOT_CONGESTED, + NET_CAPABILITY_NOT_ROAMING, + NET_CAPABILITY_NOT_SUSPENDED + )) { val capStr = valueToString(NetworkCapabilities::class.java, "NET_CAPABILITY_", cap) if (defaultNetworkCapabilities.hasCapability(cap) && !vpnNc.hasCapability(cap)) { fail("$capStr not propagated from underlying: $defaultNetworkCapabilities") @@ -1026,13 +1059,15 @@ class NetworkAgentTest { doReturn(mockCm).`when`(mockContext).getSystemService(Context.CONNECTIVITY_SERVICE) val agent = createNetworkAgent(mockContext) agent.register() - verify(mockCm).registerNetworkAgent(any(), - argThat { it.detailedState == NetworkInfo.DetailedState.CONNECTING }, - any(LinkProperties::class.java), - any(NetworkCapabilities::class.java), - any(NetworkScore::class.java), - any(NetworkAgentConfig::class.java), - eq(NetworkProvider.ID_NONE)) + verify(mockCm).registerNetworkAgent( + any(), + argThat { it.detailedState == NetworkInfo.DetailedState.CONNECTING }, + any(LinkProperties::class.java), + any(NetworkCapabilities::class.java), + any(NetworkScore::class.java), + any(NetworkAgentConfig::class.java), + eq(NetworkProvider.ID_NONE) + ) } @Test @@ -1079,8 +1114,10 @@ class NetworkAgentTest { @Test fun testValidationStatus() = createNetworkAgentWithFakeCS().let { agent -> val uri = Uri.parse("http://www.google.com") - mFakeConnectivityService.agent.onValidationStatusChanged(VALID_NETWORK, - uri.toString()) + mFakeConnectivityService.agent.onValidationStatusChanged( + VALID_NETWORK, + uri.toString() + ) agent.expectCallback().let { assertEquals(it.status, VALID_NETWORK) assertEquals(it.uri, uri) @@ -1155,7 +1192,8 @@ class NetworkAgentTest { } assertFailsWith { agentWeaker.setLingerDuration(Duration.ofMillis( - NetworkAgent.MIN_LINGER_TIMER_MS.toLong() - 1)) + NetworkAgent.MIN_LINGER_TIMER_MS.toLong() - 1 + )) } // Verify valid linger timer can be set, but it should not take effect since the network // is still needed. @@ -1165,11 +1203,14 @@ class NetworkAgentTest { agentWeaker.setLingerDuration(Duration.ofMillis(NetworkAgent.MIN_LINGER_TIMER_MS.toLong())) // Make a listener which can observe agentWeaker lost later. val callbackWeaker = TestableNetworkCallback(timeoutMs = DEFAULT_TIMEOUT_MS) - registerNetworkCallback(NetworkRequest.Builder() + registerNetworkCallback( + NetworkRequest.Builder() .clearCapabilities() .addTransportType(TRANSPORT_TEST) .setNetworkSpecifier(CompatUtil.makeEthernetNetworkSpecifier(specifierWeaker)) - .build(), callbackWeaker) + .build(), + callbackWeaker + ) callbackWeaker.expectAvailableCallbacks(agentWeaker.network!!) // Connect the agentStronger with a score better than agentWeaker. Verify the callback for @@ -1186,8 +1227,10 @@ class NetworkAgentTest { val expectedRemainingLingerDuration = lingerStart + NetworkAgent.MIN_LINGER_TIMER_MS.toLong() - SystemClock.elapsedRealtime() // If the available callback is too late. The remaining duration will be reduced. - assertTrue(expectedRemainingLingerDuration > 0, - "expected remaining linger duration is $expectedRemainingLingerDuration") + assertTrue( + expectedRemainingLingerDuration > 0, + "expected remaining linger duration is $expectedRemainingLingerDuration" + ) callbackWeaker.assertNoCallback(expectedRemainingLingerDuration) callbackWeaker.expect(agentWeaker.network!!) } @@ -1205,20 +1248,24 @@ class NetworkAgentTest { assertEquals(imsi, testNetworkSnapshot!!.subscriberId) } - @Test - @IgnoreUpTo(Build.VERSION_CODES.R) // TODO: Refactor helper functions to util class and move this test case to // {@link android.net.cts.ConnectivityManagerTest}. + @Test + @IgnoreUpTo(Build.VERSION_CODES.R) fun testRegisterBestMatchingNetworkCallback() { // Register best matching network callback with additional condition that will be // exercised later. This assumes the test network agent has NOT_VCN_MANAGED in it and // does not have NET_CAPABILITY_TEMPORARILY_NOT_METERED. val bestMatchingCb = TestableNetworkCallback(timeoutMs = DEFAULT_TIMEOUT_MS) - registerBestMatchingNetworkCallback(NetworkRequest.Builder() + registerBestMatchingNetworkCallback( + NetworkRequest.Builder() .clearCapabilities() .addTransportType(TRANSPORT_TEST) .addCapability(NET_CAPABILITY_NOT_VCN_MANAGED) - .build(), bestMatchingCb, mHandlerThread.threadHandler) + .build(), + bestMatchingCb, + mHandlerThread.threadHandler + ) val (agent1, _) = createConnectedNetworkAgent(specifier = "AGENT-1") bestMatchingCb.expectAvailableThenValidatedCallbacks(agent1.network!!) @@ -1296,8 +1343,10 @@ class NetworkAgentTest { } fun assertNoCallback() { - assertNull(history.poll(NO_CALLBACK_TIMEOUT), - "Callback received") + assertNull( + history.poll(NO_CALLBACK_TIMEOUT), + "Callback received" + ) } } @@ -1312,7 +1361,8 @@ class NetworkAgentTest { private fun setupForQosDatagram() = setupForQosCallbackTest { agent: TestableNetworkAgent -> DatagramSocket( - InetSocketAddress(InetAddress.getLoopbackAddress(), 0)) + InetSocketAddress(InetAddress.getLoopbackAddress(), 0) + ) .also { assertNotNull(agent.network?.bindSocket(it)) } } @@ -1345,7 +1395,8 @@ class NetworkAgentTest { assertFailsWith( "The same callback cannot be " + - "registered more than once without first being unregistered") { + "registered more than once without first being unregistered" + ) { mCM.registerQosCallback(info, executor, qosCallback) } } finally { @@ -1438,8 +1489,10 @@ class NetworkAgentTest { qosCallback.expectCallback() // Check that onError is coming through correctly - agent.sendQosCallbackError(callbackId, - QosCallbackException.EX_TYPE_FILTER_NOT_SUPPORTED) + agent.sendQosCallbackError( + callbackId, + QosCallbackException.EX_TYPE_FILTER_NOT_SUPPORTED + ) qosCallback.expectCallback { it.ex.cause is UnsupportedOperationException } @@ -1534,13 +1587,20 @@ class NetworkAgentTest { val remoteAddresses = ArrayList() remoteAddresses.add(InetSocketAddress(REMOTE_ADDRESS, 80)) return EpsBearerQosSessionAttributes( - qci, 2, 3, 4, 5, - remoteAddresses + qci, + 2, + 3, + 4, + 5, + remoteAddresses ) } - fun sendAndExpectUdpPacket(net: Network, - reader: PollPacketReader, iface: TestNetworkInterface) { + fun sendAndExpectUdpPacket( + net: Network, + reader: PollPacketReader, + iface: TestNetworkInterface + ) { val s = Os.socket(AF_INET6, SOCK_DGRAM, 0) net.bindSocket(s) val content = ByteArray(16) @@ -1553,8 +1613,11 @@ class NetworkAgentTest { it[IPV6_PROTOCOL_OFFSET].toInt() == IPPROTO_UDP && Arrays.equals(content, it.copyOfRange(udpStart, udpStart + content.size)) } - assertNotNull(match, "Did not receive matching packet on ${iface.interfaceName} " + - " after ${DEFAULT_TIMEOUT_MS}ms") + assertNotNull( + match, + "Did not receive matching packet on ${iface.interfaceName} " + + " after ${DEFAULT_TIMEOUT_MS}ms" + ) } fun createInterfaceAndReader(): Triple { @@ -1750,8 +1813,10 @@ class NetworkAgentTest { assertNotNull(wifiSpecifier) assertTrue(wifiSpecifier is EthernetNetworkSpecifier) - val wifiNc = makeTestNetworkCapabilities(wifiSpecifier.interfaceName, - intArrayOf(TRANSPORT_WIFI)) + val wifiNc = makeTestNetworkCapabilities( + wifiSpecifier.interfaceName, + intArrayOf(TRANSPORT_WIFI) + ) wifiAgent.sendNetworkCapabilities(wifiNc) val wifiLp = mCM.getLinkProperties(wifiNetwork)!! val newRoute = RouteInfo(IpPrefix("192.0.2.42/24")) @@ -1822,8 +1887,12 @@ class NetworkAgentTest { val nc = makeTestNetworkCapabilities(ifName, transports).also { if (transports.contains(TRANSPORT_VPN)) { val sessionId = "NetworkAgentTest-${Process.myPid()}" - it.setTransportInfo(VpnTransportInfo(VpnManager.TYPE_VPN_PLATFORM, sessionId, - /*bypassable=*/ false, /*longLivedTcpConnectionsExpensive=*/ false)) + it.setTransportInfo(VpnTransportInfo( + VpnManager.TYPE_VPN_PLATFORM, + sessionId, + /*bypassable=*/ false, + /*longLivedTcpConnectionsExpensive=*/ false + )) it.underlyingNetworks = listOf() } } @@ -1868,9 +1937,11 @@ class NetworkAgentTest { listenCallback.expect(network) requestCallback.expect(network) { it.caps.hasCapability( - NET_CAPABILITY_TEMPORARILY_NOT_METERED) } + NET_CAPABILITY_TEMPORARILY_NOT_METERED + ) } listenCallback.expect(network) { it.caps.hasCapability( - NET_CAPABILITY_TEMPORARILY_NOT_METERED) } + NET_CAPABILITY_TEMPORARILY_NOT_METERED + ) } requestCallback.expect(network) { it.lp.equals(lp) } listenCallback.expect(network) { it.lp.equals(lp) } @@ -1896,7 +1967,8 @@ class NetworkAgentTest { fun testNativeNetworkCreation_PhysicalNetwork() { doTestNativeNetworkCreation( expectCreatedImmediately = SHOULD_CREATE_NETWORKS_IMMEDIATELY, - intArrayOf(TRANSPORT_CELLULAR)) + intArrayOf(TRANSPORT_CELLULAR) + ) } @Test diff --git a/tests/cts/tethering/src/android/tethering/cts/TetheringManagerTest.java b/tests/cts/tethering/src/android/tethering/cts/TetheringManagerTest.java index 2420026942..d103f75d01 100644 --- a/tests/cts/tethering/src/android/tethering/cts/TetheringManagerTest.java +++ b/tests/cts/tethering/src/android/tethering/cts/TetheringManagerTest.java @@ -88,9 +88,11 @@ import androidx.test.runner.AndroidJUnit4; import com.android.modules.utils.build.SdkLevel; import com.android.net.flags.Flags; import com.android.testutils.ParcelUtils; +import com.android.testutils.com.android.testutils.CarrierConfigRule; import org.junit.After; import org.junit.Before; +import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; @@ -106,6 +108,8 @@ import java.util.function.Consumer; @RunWith(AndroidJUnit4.class) public class TetheringManagerTest { + @Rule + public final CarrierConfigRule mCarrierConfigRule = new CarrierConfigRule(); private Context mContext; @@ -551,22 +555,13 @@ public class TetheringManagerTest { // Override carrier config to ignore entitlement check. final PersistableBundle bundle = new PersistableBundle(); bundle.putBoolean(CarrierConfigManager.KEY_REQUIRE_ENTITLEMENT_CHECKS_BOOL, false); - overrideCarrierConfig(bundle); + mCarrierConfigRule.addConfigOverrides( + SubscriptionManager.getDefaultSubscriptionId(), bundle); // Verify that requestLatestTetheringEntitlementResult() can get entitlement // result TETHER_ERROR_NO_ERROR due to provisioning bypassed. assertEntitlementResult(listener -> mTM.requestLatestTetheringEntitlementResult( TETHERING_WIFI, false, c -> c.run(), listener), TETHER_ERROR_NO_ERROR); - - // Reset carrier config. - overrideCarrierConfig(null); - } - - private void overrideCarrierConfig(PersistableBundle bundle) { - final CarrierConfigManager configManager = (CarrierConfigManager) mContext - .getSystemService(Context.CARRIER_CONFIG_SERVICE); - final int subId = SubscriptionManager.getDefaultSubscriptionId(); - runAsShell(MODIFY_PHONE_STATE, () -> configManager.overrideConfig(subId, bundle)); } private boolean isTetheringApnRequired() {