Increase test independence

If a test fails without unregistering an agent, other tests will
see their requests match the old agent. That means any test failing
will fail all subsequent tests, which is not very helpful.

Solve this by making sure the agents are unregistered before the
test ends. Also ensure the requests are unregistered.

Test: NetworkAgentTest
Change-Id: I2c167803d478d31fd85dc6e6e621f35d36c68fb4
This commit is contained in:
Chalard Jean
2020-04-12 21:34:11 +09:00
parent 2a22d65235
commit 01f3fd3d80

View File

@@ -67,6 +67,9 @@ class NetworkAgentTest {
private class Provider(context: Context, looper: Looper) :
NetworkProvider(context, looper, "NetworkAgentTest NetworkProvider")
private val agentsToCleanUp = mutableListOf<NetworkAgent>()
private val callbacksToCleanUp = mutableListOf<TestableNetworkCallback>()
@Before
fun setUp() {
instrumentation.getUiAutomation().adoptShellPermissionIdentity()
@@ -75,11 +78,13 @@ class NetworkAgentTest {
@After
fun tearDown() {
agentsToCleanUp.forEach { it.unregister() }
callbacksToCleanUp.forEach { mCM.unregisterNetworkCallback(it) }
mHandlerThread.quitSafely()
instrumentation.getUiAutomation().dropShellPermissionIdentity()
}
internal class TestableNetworkAgent(
private class TestableNetworkAgent(
looper: Looper,
nc: NetworkCapabilities,
lp: LinkProperties,
@@ -94,12 +99,10 @@ class NetworkAgentTest {
}
override fun onBandwidthUpdateRequested() {
super.onBandwidthUpdateRequested()
history.add(OnBandwidthUpdateRequested)
}
override fun onNetworkUnwanted() {
super.onNetworkUnwanted()
history.add(OnNetworkUnwanted)
}
@@ -109,6 +112,11 @@ class NetworkAgentTest {
}
}
private fun requestNetwork(request: NetworkRequest, callback: TestableNetworkCallback) {
mCM.requestNetwork(request, callback)
callbacksToCleanUp.add(callback)
}
private fun createNetworkAgent(): TestableNetworkAgent {
val nc = NetworkCapabilities().apply {
addTransportType(NetworkCapabilities.TRANSPORT_TEST)
@@ -120,7 +128,9 @@ class NetworkAgentTest {
}
val lp = LinkProperties()
val config = NetworkAgentConfig.Builder().build()
return TestableNetworkAgent(mHandlerThread.looper, nc, lp, config)
return TestableNetworkAgent(mHandlerThread.looper, nc, lp, config).also {
agentsToCleanUp.add(it)
}
}
private fun createConnectedNetworkAgent(): Pair<TestableNetworkAgent, TestableNetworkCallback> {
@@ -129,8 +139,9 @@ class NetworkAgentTest {
.addTransportType(NetworkCapabilities.TRANSPORT_TEST)
.build()
val callback = TestableNetworkCallback(timeoutMs = DEFAULT_TIMEOUT_MS)
mCM.requestNetwork(request, callback)
val agent = createNetworkAgent().also { it.register() }
requestNetwork(request, callback)
val agent = createNetworkAgent()
agent.register()
agent.markConnected()
return agent to callback
}