Merge "Fix kotlin nullable errors in Connectivity tests" into main

This commit is contained in:
Colin Cross
2023-08-22 04:13:01 +00:00
committed by Gerrit Code Review
17 changed files with 44 additions and 83 deletions

View File

@@ -50,9 +50,9 @@ class KeepalivePacketDataTest {
// Add for test because constructor of KeepalivePacketData is protected.
private inner class TestKeepalivePacketData(
srcAddress: InetAddress? = TEST_SRC_ADDRV4,
srcAddress: InetAddress = TEST_SRC_ADDRV4,
srcPort: Int = TEST_SRC_PORT,
dstAddress: InetAddress? = TEST_DST_ADDRV4,
dstAddress: InetAddress = TEST_DST_ADDRV4,
dstPort: Int = TEST_DST_PORT,
data: ByteArray = TESTBYTES
) : KeepalivePacketData(srcAddress, srcPort, dstAddress, dstPort, data)
@@ -62,20 +62,6 @@ class KeepalivePacketDataTest {
fun testConstructor() {
var data: TestKeepalivePacketData
try {
data = TestKeepalivePacketData(srcAddress = null)
fail("Null src address should cause exception")
} catch (e: InvalidPacketException) {
assertEquals(e.error, ERROR_INVALID_IP_ADDRESS)
}
try {
data = TestKeepalivePacketData(dstAddress = null)
fail("Null dst address should cause exception")
} catch (e: InvalidPacketException) {
assertEquals(e.error, ERROR_INVALID_IP_ADDRESS)
}
try {
data = TestKeepalivePacketData(dstAddress = TEST_ADDRV6)
fail("Ip family mismatched should cause exception")
@@ -117,4 +103,4 @@ class KeepalivePacketDataTest {
@Test
@IgnoreUpTo(Build.VERSION_CODES.Q)
fun testPacket() = assertTrue(Arrays.equals(TESTBYTES, TestKeepalivePacketData().packet))
}
}

View File

@@ -67,7 +67,7 @@ private val PROVIDER_NAME = "NetworkProviderTest"
class NetworkProviderTest {
@Rule @JvmField
val mIgnoreRule = DevSdkIgnoreRule()
private val mCm = context.getSystemService(ConnectivityManager::class.java)
private val mCm = context.getSystemService(ConnectivityManager::class.java)!!
private val mHandlerThread = HandlerThread("${javaClass.simpleName} handler thread")
@Before

View File

@@ -95,7 +95,7 @@ private fun <T> CompletableFuture<T>.assertGet(timeoutMs: Long, message: String)
@RunWith(AndroidJUnit4::class)
class CaptivePortalTest {
private val context: android.content.Context by lazy { getInstrumentation().context }
private val cm by lazy { context.getSystemService(ConnectivityManager::class.java) }
private val cm by lazy { context.getSystemService(ConnectivityManager::class.java)!! }
private val pm by lazy { context.packageManager }
private val utils by lazy { CtsNetUtils(context) }

View File

@@ -125,7 +125,7 @@ class DscpPolicyTest {
private val TEST_TARGET_MAC_ADDR = MacAddress.fromString("12:34:56:78:9a:bc")
private val realContext = InstrumentationRegistry.getContext()
private val cm = realContext.getSystemService(ConnectivityManager::class.java)
private val cm = realContext.getSystemService(ConnectivityManager::class.java)!!
private val agentsToCleanUp = mutableListOf<NetworkAgent>()
private val callbacksToCleanUp = mutableListOf<TestableNetworkCallback>()
@@ -160,7 +160,7 @@ class DscpPolicyTest {
assumeTrue(kernelIsAtLeast(5, 15))
runAsShell(MANAGE_TEST_NETWORKS) {
val tnm = realContext.getSystemService(TestNetworkManager::class.java)
val tnm = realContext.getSystemService(TestNetworkManager::class.java)!!
// Only statically configure the IPv4 address; for IPv6, use the SLAAC generated
// address.
@@ -306,7 +306,7 @@ class DscpPolicyTest {
val socket = Os.socket(if (sendV6) AF_INET6 else AF_INET, SOCK_DGRAM or SOCK_NONBLOCK,
IPPROTO_UDP)
agent.network.bindSocket(socket)
checkNotNull(agent.network).bindSocket(socket)
val originalPacket = testPacket.readAsArray()
Os.sendto(socket, originalPacket, 0 /* bytesOffset */, originalPacket.size, 0 /* flags */,

View File

@@ -135,8 +135,8 @@ private val STATIC_IP_CONFIGURATION = IpConfiguration.Builder()
class EthernetManagerTest {
private val context by lazy { InstrumentationRegistry.getInstrumentation().context }
private val em by lazy { context.getSystemService(EthernetManager::class.java) }
private val cm by lazy { context.getSystemService(ConnectivityManager::class.java) }
private val em by lazy { context.getSystemService(EthernetManager::class.java)!! }
private val cm by lazy { context.getSystemService(ConnectivityManager::class.java)!! }
private val handler by lazy { Handler(Looper.getMainLooper()) }
private val ifaceListener = EthernetStateListener()
@@ -160,7 +160,7 @@ class EthernetManagerTest {
init {
tnm = runAsShell(MANAGE_TEST_NETWORKS) {
context.getSystemService(TestNetworkManager::class.java)
context.getSystemService(TestNetworkManager::class.java)!!
}
tapInterface = runAsShell(MANAGE_TEST_NETWORKS) {
// Configuring a tun/tap interface always enables the carrier. If hasCarrier is

View File

@@ -257,7 +257,7 @@ class NetworkAgentTest {
callback: TestableNetworkCallback,
handler: Handler
) {
mCM!!.registerBestMatchingNetworkCallback(request, callback, handler)
mCM.registerBestMatchingNetworkCallback(request, callback, handler)
callbacksToCleanUp.add(callback)
}
@@ -394,8 +394,8 @@ class NetworkAgentTest {
.setLegacyExtraInfo(legacyExtraInfo).build()
val (agent, callback) = createConnectedNetworkAgent(initialConfig = config)
val networkInfo = mCM.getNetworkInfo(agent.network)
assertEquals(subtypeLTE, networkInfo.getSubtype())
assertEquals(subtypeNameLTE, networkInfo.getSubtypeName())
assertEquals(subtypeLTE, networkInfo?.getSubtype())
assertEquals(subtypeNameLTE, networkInfo?.getSubtypeName())
assertEquals(legacyExtraInfo, config.getLegacyExtraInfo())
}
@@ -417,8 +417,8 @@ class NetworkAgentTest {
val nc = NetworkCapabilities(agent.nc)
nc.addCapability(NET_CAPABILITY_NOT_METERED)
agent.sendNetworkCapabilities(nc)
callback.expectCaps(agent.network) { it.hasCapability(NET_CAPABILITY_NOT_METERED) }
val networkInfo = mCM.getNetworkInfo(agent.network)
callback.expectCaps(agent.network!!) { it.hasCapability(NET_CAPABILITY_NOT_METERED) }
val networkInfo = mCM.getNetworkInfo(agent.network!!)!!
assertEquals(subtypeUMTS, networkInfo.getSubtype())
assertEquals(subtypeNameUMTS, networkInfo.getSubtypeName())
}
@@ -631,6 +631,7 @@ class NetworkAgentTest {
val defaultNetwork = mCM.activeNetwork
assertNotNull(defaultNetwork)
val defaultNetworkCapabilities = mCM.getNetworkCapabilities(defaultNetwork)
assertNotNull(defaultNetworkCapabilities)
val defaultNetworkTransports = defaultNetworkCapabilities.transportTypes
val agent = createNetworkAgent(initialNc = nc)
@@ -671,7 +672,7 @@ class NetworkAgentTest {
// This is not very accurate because the test does not control the capabilities of the
// 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!!)
vpnNc = mCM.getNetworkCapabilities(agent.network!!)!!
for (cap in listOf(NET_CAPABILITY_NOT_CONGESTED,
NET_CAPABILITY_NOT_ROAMING,
NET_CAPABILITY_NOT_SUSPENDED)) {
@@ -1041,8 +1042,8 @@ class NetworkAgentTest {
}
fun QosSocketInfo(agent: NetworkAgent, socket: Closeable) = when (socket) {
is Socket -> QosSocketInfo(agent.network, socket)
is DatagramSocket -> QosSocketInfo(agent.network, socket)
is Socket -> QosSocketInfo(checkNotNull(agent.network), socket)
is DatagramSocket -> QosSocketInfo(checkNotNull(agent.network), socket)
else -> fail("unexpected socket type")
}
@@ -1405,8 +1406,8 @@ class NetworkAgentTest {
val nc = makeTestNetworkCapabilities(ifName, transports).also {
if (transports.contains(TRANSPORT_VPN)) {
val sessionId = "NetworkAgentTest-${Process.myPid()}"
it.transportInfo = 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()
}
}

View File

@@ -104,13 +104,6 @@ class NetworkInfoTest {
NetworkInfo(ConnectivityManager.MAX_NETWORK_TYPE + 1,
TelephonyManager.NETWORK_TYPE_LTE, MOBILE_TYPE_NAME, LTE_SUBTYPE_NAME)
}
if (SdkLevel.isAtLeastT()) {
assertFailsWith<NullPointerException> { NetworkInfo(null) }
} else {
// Doesn't immediately crash on S-
NetworkInfo(null)
}
}
@Test
@@ -133,21 +126,11 @@ class NetworkInfoTest {
constructor.isAccessible = true
val incorrectDetailedState = constructor.newInstance("any", 200) as DetailedState
if (SdkLevel.isAtLeastT()) {
assertFailsWith<NullPointerException> {
NetworkInfo(null)
}
assertFailsWith<NullPointerException> {
networkInfo.setDetailedState(null, "reason", "extraInfo")
}
// This actually throws ArrayOutOfBoundsException because of the implementation of
// EnumMap, but that's an implementation detail so accept any crash.
assertFails {
networkInfo.setDetailedState(incorrectDetailedState, "reason", "extraInfo")
}
} else {
// Doesn't immediately crash on S-
NetworkInfo(null)
networkInfo.setDetailedState(null, "reason", "extraInfo")
}
}
}
}

View File

@@ -67,7 +67,7 @@ private fun score(exiting: Boolean = false, primary: Boolean = false) =
@RunWith(DevSdkIgnoreRunner::class)
class NetworkScoreTest {
private val TAG = javaClass.simpleName
private val mCm = testContext.getSystemService(ConnectivityManager::class.java)
private val mCm = testContext.getSystemService(ConnectivityManager::class.java)!!
private val mHandlerThread = HandlerThread("$TAG handler thread")
private val mHandler by lazy { Handler(mHandlerThread.looper) }
private val agentsToCleanUp = Collections.synchronizedList(mutableListOf<NetworkAgent>())
@@ -111,7 +111,7 @@ class NetworkScoreTest {
// made for ConnectivityServiceTest.
// TODO : have TestNetworkCallback work for NetworkAgent too and remove this class.
private class AgentWrapper(val agent: NetworkAgent) : HasNetwork {
override val network = agent.network
override val network = checkNotNull(agent.network)
fun sendNetworkScore(s: NetworkScore) = agent.sendNetworkScore(s)
}

View File

@@ -159,9 +159,9 @@ class NsdManagerTest {
val ignoreRule = DevSdkIgnoreRule()
private val context by lazy { InstrumentationRegistry.getInstrumentation().context }
private val nsdManager by lazy { context.getSystemService(NsdManager::class.java) }
private val nsdManager by lazy { context.getSystemService(NsdManager::class.java)!! }
private val cm by lazy { context.getSystemService(ConnectivityManager::class.java) }
private val cm by lazy { context.getSystemService(ConnectivityManager::class.java)!! }
private val serviceName = "NsdTest%09d".format(Random().nextInt(1_000_000_000))
private val serviceType = "_nmt%09d._tcp".format(Random().nextInt(1_000_000_000))
private val handlerThread = HandlerThread(NsdManagerTest::class.java.simpleName)
@@ -397,7 +397,7 @@ class NsdManagerTest {
}
private fun createTestNetwork(): TestTapNetwork {
val tnm = context.getSystemService(TestNetworkManager::class.java)
val tnm = context.getSystemService(TestNetworkManager::class.java)!!
val iface = tnm.createTapInterface()
val cb = TestableNetworkCallback()
val testNetworkSpecifier = TestNetworkSpecifier(iface.interfaceName)

View File

@@ -70,7 +70,7 @@ class ProxyTest {
private fun getDefaultProxy(): ProxyInfo? {
return InstrumentationRegistry.getInstrumentation().context
.getSystemService(ConnectivityManager::class.java)
.getSystemService(ConnectivityManager::class.java)!!
.getDefaultProxy()
}
@@ -100,4 +100,4 @@ class ProxyTest {
Proxy.setHttpProxyConfiguration(original)
}
}
}
}

View File

@@ -56,6 +56,7 @@ import com.android.server.connectivity.ProxyTracker
import com.android.testutils.RecorderCallback.CallbackEntry.LinkPropertiesChanged
import com.android.testutils.TestableNetworkCallback
import kotlin.test.assertEquals
import kotlin.test.assertNotNull
import kotlin.test.assertTrue
import kotlin.test.fail
import org.junit.After
@@ -291,6 +292,7 @@ class ConnectivityServiceIntegrationTest {
val capportData = testCb.expect<LinkPropertiesChanged>(na, TEST_TIMEOUT_MS) {
it.lp.captivePortalData != null
}.lp.captivePortalData
assertNotNull(capportData)
assertTrue(capportData.isCaptive)
assertEquals(Uri.parse("https://login.capport.android.com"), capportData.userPortalUrl)
assertEquals(Uri.parse("https://venueinfo.capport.android.com"), capportData.venueInfoUrl)

View File

@@ -20,9 +20,9 @@ import android.os.Parcel
import android.os.Parcelable
data class HttpResponse(
val requestUrl: String,
val requestUrl: String?,
val responseCode: Int,
val content: String = "",
val content: String? = "",
val redirectUrl: String? = null
) : Parcelable {
constructor(p: Parcel): this(p.readString(), p.readInt(), p.readString(), p.readString())
@@ -46,4 +46,4 @@ data class HttpResponse(
override fun createFromParcel(source: Parcel) = HttpResponse(source)
override fun newArray(size: Int) = arrayOfNulls<HttpResponse?>(size)
}
}
}

View File

@@ -70,7 +70,7 @@ class NetworkStackInstrumentationService : Service() {
* request is seen, the test will fail.
*/
override fun addHttpResponse(response: HttpResponse) {
httpResponses.getValue(response.requestUrl).add(response)
httpResponses.getValue(checkNotNull(response.requestUrl)).add(response)
}
/**
@@ -81,4 +81,4 @@ class NetworkStackInstrumentationService : Service() {
return ArrayList(httpRequestUrls)
}
}
}
}

View File

@@ -69,7 +69,8 @@ class TestNetworkStackService : Service() {
url: URL,
private val response: HttpResponse
) : HttpURLConnection(url) {
private val responseBytes = response.content.toByteArray(StandardCharsets.UTF_8)
private val responseBytes = checkNotNull(response.content)
.toByteArray(StandardCharsets.UTF_8)
override fun getResponseCode() = response.responseCode
override fun getContentLengthLong() = responseBytes.size.toLong()
override fun getHeaderField(field: String): String? {

View File

@@ -218,18 +218,6 @@ class NetworkTemplateTest {
templateNullWifiKey.assertDoesNotMatch(identWifiNullKey)
}
@DevSdkIgnoreRule.IgnoreAfter(Build.VERSION_CODES.TIRAMISU)
@Test
fun testBuildTemplateMobileAll_nullSubscriberId() {
val templateMobileAllWithNullImsi = buildTemplateMobileAll(null)
val setWithNull = HashSet<String?>().apply {
add(null)
}
val templateFromBuilder = NetworkTemplate.Builder(MATCH_MOBILE).setMeteredness(METERED_YES)
.setSubscriberIds(setWithNull).build()
assertEquals(templateFromBuilder, templateMobileAllWithNullImsi)
}
@Test
fun testMobileMatches() {
val templateMobileImsi1 = buildTemplateMobileAll(TEST_IMSI1)

View File

@@ -74,7 +74,7 @@ class FullScoreTest {
private val TAG = this::class.simpleName
private var wtfHandler: Log.TerribleFailureHandler? = null
private lateinit var wtfHandler: Log.TerribleFailureHandler
@Before
fun setUp() {

View File

@@ -59,12 +59,12 @@ class MdnsPacketTest {
}
assertEquals(InetAddresses.parseNumericAddress("192.0.2.123"),
(packet.authorityRecords[0] as MdnsInetAddressRecord).inet4Address)
(packet.authorityRecords[0] as MdnsInetAddressRecord).inet4Address!!)
assertEquals(InetAddresses.parseNumericAddress("2001:db8::123"),
(packet.authorityRecords[1] as MdnsInetAddressRecord).inet6Address)
(packet.authorityRecords[1] as MdnsInetAddressRecord).inet6Address!!)
assertEquals(InetAddresses.parseNumericAddress("2001:db8::456"),
(packet.authorityRecords[2] as MdnsInetAddressRecord).inet6Address)
(packet.authorityRecords[2] as MdnsInetAddressRecord).inet6Address!!)
assertEquals(InetAddresses.parseNumericAddress("2001:db8::789"),
(packet.authorityRecords[3] as MdnsInetAddressRecord).inet6Address)
(packet.authorityRecords[3] as MdnsInetAddressRecord).inet6Address!!)
}
}