From 484c4219d9f974e168bc66779c2f125d9aee6ab5 Mon Sep 17 00:00:00 2001 From: Chalard Jean Date: Thu, 20 Jun 2019 16:01:19 +0900 Subject: [PATCH] Simplify Exception expressions in CSTest Test: CSTest Change-Id: Ie9b9fc334b85836bf156bda71e54e8d30885b82a --- .../server/ConnectivityServiceTest.java | 278 ++++++++---------- 1 file changed, 119 insertions(+), 159 deletions(-) diff --git a/tests/net/java/com/android/server/ConnectivityServiceTest.java b/tests/net/java/com/android/server/ConnectivityServiceTest.java index 5dcbba6fb5..7dd2bbfe52 100644 --- a/tests/net/java/com/android/server/ConnectivityServiceTest.java +++ b/tests/net/java/com/android/server/ConnectivityServiceTest.java @@ -71,6 +71,7 @@ import static android.net.RouteInfo.RTN_UNREACHABLE; import static com.android.testutils.ConcurrentUtilsKt.await; import static com.android.testutils.ConcurrentUtilsKt.durationOf; +import static com.android.testutils.ExceptionUtils.ignoreExceptions; import static com.android.testutils.HandlerUtilsKt.waitForIdleSerialExecutor; import static com.android.testutils.MiscAssertsKt.assertContainsExactly; import static com.android.testutils.MiscAssertsKt.assertEmpty; @@ -205,8 +206,8 @@ import com.android.server.connectivity.Tethering; import com.android.server.connectivity.Vpn; import com.android.server.net.NetworkPinner; import com.android.server.net.NetworkPolicyManagerInternal; +import com.android.testutils.ExceptionUtils; import com.android.testutils.HandlerUtilsKt; -import com.android.testutils.ThrowingConsumer; import org.junit.After; import org.junit.Before; @@ -227,7 +228,6 @@ import java.net.Inet6Address; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.Socket; -import java.net.UnknownHostException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -417,7 +417,7 @@ public class ConnectivityServiceTest { } @Test - public void testWaitForIdle() { + public void testWaitForIdle() throws Exception { final int attempts = 50; // Causes the test to take about 200ms on bullhead-eng. // Tests that waitForIdle returns immediately if the service is already idle. @@ -444,7 +444,7 @@ public class ConnectivityServiceTest { // This test has an inherent race condition in it, and cannot be enabled for continuous testing // or presubmit tests. It is kept for manual runs and documentation purposes. @Ignore - public void verifyThatNotWaitingForIdleCausesRaceConditions() { + public void verifyThatNotWaitingForIdleCausesRaceConditions() throws Exception { // Bring up a network that we can use to send messages to ConnectivityService. ConditionVariable cv = waitForConnectivityBroadcasts(1); mWiFiNetworkAgent = new MockNetworkAgent(TRANSPORT_WIFI); @@ -524,11 +524,11 @@ public class ConnectivityServiceTest { mNmValidationRedirectUrl = null; } - MockNetworkAgent(int transport) { + MockNetworkAgent(int transport) throws Exception { this(transport, new LinkProperties()); } - MockNetworkAgent(int transport, LinkProperties linkProperties) { + MockNetworkAgent(int transport, LinkProperties linkProperties) throws Exception { final int type = transportToLegacyType(transport); final String typeName = ConnectivityManager.getNetworkTypeName(type); mNetworkInfo = new NetworkInfo(type, 0, typeName, "Mock"); @@ -559,16 +559,12 @@ public class ConnectivityServiceTest { mNetworkMonitor = mock(INetworkMonitor.class); final Answer validateAnswer = inv -> { - new Thread(this::onValidationRequested).start(); + new Thread(ignoreExceptions(this::onValidationRequested)).start(); return null; }; - try { - doAnswer(validateAnswer).when(mNetworkMonitor).notifyNetworkConnected(any(), any()); - doAnswer(validateAnswer).when(mNetworkMonitor).forceReevaluation(anyInt()); - } catch (RemoteException e) { - fail(e.getMessage()); - } + doAnswer(validateAnswer).when(mNetworkMonitor).notifyNetworkConnected(any(), any()); + doAnswer(validateAnswer).when(mNetworkMonitor).forceReevaluation(anyInt()); final ArgumentCaptor nmNetworkCaptor = ArgumentCaptor.forClass(Network.class); final ArgumentCaptor nmCbCaptor = @@ -623,35 +619,27 @@ public class ConnectivityServiceTest { assertEquals(mNetworkAgent.netId, nmNetworkCaptor.getValue().netId); mNmCallbacks = nmCbCaptor.getValue(); - try { - mNmCallbacks.onNetworkMonitorCreated(mNetworkMonitor); - } catch (RemoteException e) { - fail(e.getMessage()); - } + mNmCallbacks.onNetworkMonitorCreated(mNetworkMonitor); // Waits for the NetworkAgent to be registered, which includes the creation of the // NetworkMonitor. waitForIdle(); } - private void onValidationRequested() { - try { - if (mNmProvNotificationRequested - && ((mNmValidationResult & NETWORK_VALIDATION_RESULT_VALID) != 0)) { - mNmCallbacks.hideProvisioningNotification(); - mNmProvNotificationRequested = false; - } + private void onValidationRequested() throws Exception { + if (mNmProvNotificationRequested + && ((mNmValidationResult & NETWORK_VALIDATION_RESULT_VALID) != 0)) { + mNmCallbacks.hideProvisioningNotification(); + mNmProvNotificationRequested = false; + } - mNmCallbacks.notifyNetworkTested( - mNmValidationResult, mNmValidationRedirectUrl); + mNmCallbacks.notifyNetworkTested( + mNmValidationResult, mNmValidationRedirectUrl); - if (mNmValidationRedirectUrl != null) { - mNmCallbacks.showProvisioningNotification( - "test_provisioning_notif_action", "com.android.test.package"); - mNmProvNotificationRequested = true; - } - } catch (RemoteException e) { - fail(e.getMessage()); + if (mNmValidationRedirectUrl != null) { + mNmCallbacks.showProvisioningNotification( + "test_provisioning_notif_action", "com.android.test.package"); + mNmProvNotificationRequested = true; } } @@ -1249,18 +1237,13 @@ public class ConnectivityServiceTest { waitForIdle(TIMEOUT_MS); } - public void setUidRulesChanged(int uidRules) { - try { - mPolicyListener.onUidRulesChanged(Process.myUid(), uidRules); - } catch (RemoteException ignored) { - } + public void setUidRulesChanged(int uidRules) throws RemoteException { + mPolicyListener.onUidRulesChanged(Process.myUid(), uidRules); } - public void setRestrictBackgroundChanged(boolean restrictBackground) { - try { - mPolicyListener.onRestrictBackgroundChanged(restrictBackground); - } catch (RemoteException ignored) { - } + public void setRestrictBackgroundChanged(boolean restrictBackground) + throws RemoteException { + mPolicyListener.onRestrictBackgroundChanged(restrictBackground); } } @@ -1815,12 +1798,9 @@ public class ConnectivityServiceTest { return mLastAvailableNetwork; } - CallbackInfo nextCallback(int timeoutMs) { + CallbackInfo nextCallback(int timeoutMs) throws InterruptedException { CallbackInfo cb = null; - try { - cb = mCallbacks.poll(timeoutMs, TimeUnit.MILLISECONDS); - } catch (InterruptedException e) { - } + cb = mCallbacks.poll(timeoutMs, TimeUnit.MILLISECONDS); if (cb == null) { // LinkedBlockingQueue.poll() returns null if it timeouts. fail("Did not receive callback after " + timeoutMs + "ms"); @@ -1828,7 +1808,8 @@ public class ConnectivityServiceTest { return cb; } - CallbackInfo expectCallback(CallbackState state, MockNetworkAgent agent, int timeoutMs) { + CallbackInfo expectCallback(CallbackState state, MockNetworkAgent agent, int timeoutMs) + throws Exception { final Network expectedNetwork = (agent != null) ? agent.getNetwork() : null; CallbackInfo expected = new CallbackInfo(state, expectedNetwork, 0); CallbackInfo actual = nextCallback(timeoutMs); @@ -1845,15 +1826,16 @@ public class ConnectivityServiceTest { return actual; } - CallbackInfo expectCallback(CallbackState state, MockNetworkAgent agent) { + CallbackInfo expectCallback(CallbackState state, MockNetworkAgent agent) throws Exception { return expectCallback(state, agent, TEST_CALLBACK_TIMEOUT_MS); } - CallbackInfo expectCallbackLike(Predicate fn) { + CallbackInfo expectCallbackLike(Predicate fn) throws Exception { return expectCallbackLike(fn, TEST_CALLBACK_TIMEOUT_MS); } - CallbackInfo expectCallbackLike(Predicate fn, int timeoutMs) { + CallbackInfo expectCallbackLike(Predicate fn, int timeoutMs) + throws Exception { int timeLeft = timeoutMs; while (timeLeft > 0) { long start = SystemClock.elapsedRealtime(); @@ -1879,7 +1861,7 @@ public class ConnectivityServiceTest { // onCapabilitiesChanged callback. // @param timeoutMs how long to wait for the callbacks. void expectAvailableCallbacks(MockNetworkAgent agent, boolean expectSuspended, - boolean expectValidated, boolean expectBlocked, int timeoutMs) { + boolean expectValidated, boolean expectBlocked, int timeoutMs) throws Exception { expectCallback(CallbackState.AVAILABLE, agent, timeoutMs); if (expectSuspended) { expectCallback(CallbackState.SUSPENDED, agent, timeoutMs); @@ -1894,23 +1876,26 @@ public class ConnectivityServiceTest { } // Expects the available callbacks (validated), plus onSuspended. - void expectAvailableAndSuspendedCallbacks(MockNetworkAgent agent, boolean expectValidated) { + void expectAvailableAndSuspendedCallbacks(MockNetworkAgent agent, boolean expectValidated) + throws Exception { expectAvailableCallbacks(agent, true, expectValidated, false, TEST_CALLBACK_TIMEOUT_MS); } - void expectAvailableCallbacksValidated(MockNetworkAgent agent) { + void expectAvailableCallbacksValidated(MockNetworkAgent agent) + throws Exception { expectAvailableCallbacks(agent, false, true, false, TEST_CALLBACK_TIMEOUT_MS); } - void expectAvailableCallbacksValidatedAndBlocked(MockNetworkAgent agent) { + void expectAvailableCallbacksValidatedAndBlocked(MockNetworkAgent agent) throws Exception { expectAvailableCallbacks(agent, false, true, true, TEST_CALLBACK_TIMEOUT_MS); } - void expectAvailableCallbacksUnvalidated(MockNetworkAgent agent) { + void expectAvailableCallbacksUnvalidated(MockNetworkAgent agent) throws Exception { expectAvailableCallbacks(agent, false, false, false, TEST_CALLBACK_TIMEOUT_MS); } - void expectAvailableCallbacksUnvalidatedAndBlocked(MockNetworkAgent agent) { + void expectAvailableCallbacksUnvalidatedAndBlocked(MockNetworkAgent agent) + throws Exception { expectAvailableCallbacks(agent, false, false, true, TEST_CALLBACK_TIMEOUT_MS); } @@ -1918,7 +1903,7 @@ public class ConnectivityServiceTest { // VALIDATED capability), plus another onCapabilitiesChanged which is identical to the // one we just sent. // TODO: this is likely a bug. Fix it and remove this method. - void expectAvailableDoubleValidatedCallbacks(MockNetworkAgent agent) { + void expectAvailableDoubleValidatedCallbacks(MockNetworkAgent agent) throws Exception { expectCallback(CallbackState.AVAILABLE, agent, TEST_CALLBACK_TIMEOUT_MS); NetworkCapabilities nc1 = expectCapabilitiesWith(NET_CAPABILITY_VALIDATED, agent); expectCallback(CallbackState.LINK_PROPERTIES, agent, TEST_CALLBACK_TIMEOUT_MS); @@ -1932,48 +1917,53 @@ public class ConnectivityServiceTest { // Expects the available callbacks where the onCapabilitiesChanged must not have validated, // then expects another onCapabilitiesChanged that has the validated bit set. This is used // when a network connects and satisfies a callback, and then immediately validates. - void expectAvailableThenValidatedCallbacks(MockNetworkAgent agent) { + void expectAvailableThenValidatedCallbacks(MockNetworkAgent agent) throws Exception { expectAvailableCallbacksUnvalidated(agent); expectCapabilitiesWith(NET_CAPABILITY_VALIDATED, agent); } - NetworkCapabilities expectCapabilitiesWith(int capability, MockNetworkAgent agent) { + NetworkCapabilities expectCapabilitiesWith(int capability, MockNetworkAgent agent) + throws Exception { return expectCapabilitiesWith(capability, agent, TEST_CALLBACK_TIMEOUT_MS); } NetworkCapabilities expectCapabilitiesWith(int capability, MockNetworkAgent agent, - int timeoutMs) { + int timeoutMs) throws Exception { CallbackInfo cbi = expectCallback(CallbackState.NETWORK_CAPABILITIES, agent, timeoutMs); NetworkCapabilities nc = (NetworkCapabilities) cbi.arg; assertTrue(nc.hasCapability(capability)); return nc; } - NetworkCapabilities expectCapabilitiesWithout(int capability, MockNetworkAgent agent) { + NetworkCapabilities expectCapabilitiesWithout(int capability, MockNetworkAgent agent) + throws Exception { return expectCapabilitiesWithout(capability, agent, TEST_CALLBACK_TIMEOUT_MS); } NetworkCapabilities expectCapabilitiesWithout(int capability, MockNetworkAgent agent, - int timeoutMs) { + int timeoutMs) throws Exception { CallbackInfo cbi = expectCallback(CallbackState.NETWORK_CAPABILITIES, agent, timeoutMs); NetworkCapabilities nc = (NetworkCapabilities) cbi.arg; assertFalse(nc.hasCapability(capability)); return nc; } - void expectCapabilitiesLike(Predicate fn, MockNetworkAgent agent) { + void expectCapabilitiesLike(Predicate fn, MockNetworkAgent agent) + throws Exception { CallbackInfo cbi = expectCallback(CallbackState.NETWORK_CAPABILITIES, agent); assertTrue("Received capabilities don't match expectations : " + cbi.arg, fn.test((NetworkCapabilities) cbi.arg)); } - void expectLinkPropertiesLike(Predicate fn, MockNetworkAgent agent) { + void expectLinkPropertiesLike(Predicate fn, MockNetworkAgent agent) + throws Exception { CallbackInfo cbi = expectCallback(CallbackState.LINK_PROPERTIES, agent); assertTrue("Received LinkProperties don't match expectations : " + cbi.arg, fn.test((LinkProperties) cbi.arg)); } - void expectBlockedStatusCallback(boolean expectBlocked, MockNetworkAgent agent) { + void expectBlockedStatusCallback(boolean expectBlocked, MockNetworkAgent agent) + throws Exception { CallbackInfo cbi = expectCallback(CallbackState.BLOCKED_STATUS, agent); boolean actualBlocked = (boolean) cbi.arg; assertEquals(expectBlocked, actualBlocked); @@ -2085,7 +2075,7 @@ public class ConnectivityServiceTest { } @Test - public void testMultipleLingering() { + public void testMultipleLingering() throws Exception { // This test would be flaky with the default 120ms timer: that is short enough that // lingered networks are torn down before assertions can be run. We don't want to mock the // lingering timer to keep the WakeupMessage logic realistic: this has already proven useful @@ -2340,7 +2330,7 @@ public class ConnectivityServiceTest { } @Test - public void testNetworkGoesIntoBackgroundAfterLinger() { + public void testNetworkGoesIntoBackgroundAfterLinger() throws Exception { setAlwaysOnNetworks(true); NetworkRequest request = new NetworkRequest.Builder() .clearCapabilities() @@ -2385,7 +2375,7 @@ public class ConnectivityServiceTest { } @Test - public void testExplicitlySelected() { + public void testExplicitlySelected() throws Exception { NetworkRequest request = new NetworkRequest.Builder() .clearCapabilities().addCapability(NET_CAPABILITY_INTERNET) .build(); @@ -2666,7 +2656,7 @@ public class ConnectivityServiceTest { } @Test - public void testPartialConnectivity() { + public void testPartialConnectivity() throws Exception { // Register network callback. NetworkRequest request = new NetworkRequest.Builder() .clearCapabilities().addCapability(NET_CAPABILITY_INTERNET) @@ -2699,11 +2689,7 @@ public class ConnectivityServiceTest { // If user accepts partial connectivity network, // NetworkMonitor#setAcceptPartialConnectivity() should be called too. waitForIdle(); - try { - verify(mWiFiNetworkAgent.mNetworkMonitor, times(1)).setAcceptPartialConnectivity(); - } catch (RemoteException e) { - fail(e.getMessage()); - } + verify(mWiFiNetworkAgent.mNetworkMonitor, times(1)).setAcceptPartialConnectivity(); // Need a trigger point to let NetworkMonitor tell ConnectivityService that network is // validated. mCm.reportNetworkConnectivity(mWiFiNetworkAgent.getNetwork(), true); @@ -2740,11 +2726,7 @@ public class ConnectivityServiceTest { // NetworkMonitor#setAcceptPartialConnectivity() will be called in // ConnectivityService#updateNetworkInfo(). waitForIdle(); - try { - verify(mWiFiNetworkAgent.mNetworkMonitor, times(1)).setAcceptPartialConnectivity(); - } catch (RemoteException e) { - fail(e.getMessage()); - } + verify(mWiFiNetworkAgent.mNetworkMonitor, times(1)).setAcceptPartialConnectivity(); callback.expectAvailableCallbacksUnvalidated(mWiFiNetworkAgent); callback.expectCallback(CallbackState.LOSING, mCellNetworkAgent); nc = callback.expectCapabilitiesWith(NET_CAPABILITY_VALIDATED, mWiFiNetworkAgent); @@ -2768,11 +2750,7 @@ public class ConnectivityServiceTest { // NetworkMonitor#setAcceptPartialConnectivity() will be called in // ConnectivityService#updateNetworkInfo(). waitForIdle(); - try { - verify(mWiFiNetworkAgent.mNetworkMonitor, times(1)).setAcceptPartialConnectivity(); - } catch (RemoteException e) { - fail(e.getMessage()); - } + verify(mWiFiNetworkAgent.mNetworkMonitor, times(1)).setAcceptPartialConnectivity(); callback.expectAvailableCallbacksUnvalidated(mWiFiNetworkAgent); callback.expectCallback(CallbackState.LOSING, mCellNetworkAgent); // TODO: If the user accepted partial connectivity, we shouldn't switch to wifi until @@ -2789,7 +2767,7 @@ public class ConnectivityServiceTest { } @Test - public void testCaptivePortalOnPartialConnectivity() throws RemoteException { + public void testCaptivePortalOnPartialConnectivity() throws Exception { final TestNetworkCallback captivePortalCallback = new TestNetworkCallback(); final NetworkRequest captivePortalRequest = new NetworkRequest.Builder() .addCapability(NET_CAPABILITY_CAPTIVE_PORTAL).build(); @@ -2838,7 +2816,7 @@ public class ConnectivityServiceTest { } @Test - public void testCaptivePortal() { + public void testCaptivePortal() throws Exception { final TestNetworkCallback captivePortalCallback = new TestNetworkCallback(); final NetworkRequest captivePortalRequest = new NetworkRequest.Builder() .addCapability(NET_CAPABILITY_CAPTIVE_PORTAL).build(); @@ -2890,7 +2868,7 @@ public class ConnectivityServiceTest { } @Test - public void testCaptivePortalApp() throws RemoteException { + public void testCaptivePortalApp() throws Exception { final TestNetworkCallback captivePortalCallback = new TestNetworkCallback(); final NetworkRequest captivePortalRequest = new NetworkRequest.Builder() .addCapability(NET_CAPABILITY_CAPTIVE_PORTAL).build(); @@ -2948,7 +2926,7 @@ public class ConnectivityServiceTest { } @Test - public void testAvoidOrIgnoreCaptivePortals() { + public void testAvoidOrIgnoreCaptivePortals() throws Exception { final TestNetworkCallback captivePortalCallback = new TestNetworkCallback(); final NetworkRequest captivePortalRequest = new NetworkRequest.Builder() .addCapability(NET_CAPABILITY_CAPTIVE_PORTAL).build(); @@ -2988,7 +2966,7 @@ public class ConnectivityServiceTest { * does work. */ @Test - public void testNetworkSpecifier() { + public void testNetworkSpecifier() throws Exception { // A NetworkSpecifier subclass that matches all networks but must not be visible to apps. class ConfidentialMatchAllNetworkSpecifier extends NetworkSpecifier implements Parcelable { @@ -3177,7 +3155,7 @@ public class ConnectivityServiceTest { } @Test - public void testNetworkSpecifierUidSpoofSecurityException() { + public void testNetworkSpecifierUidSpoofSecurityException() throws Exception { class UidAwareNetworkSpecifier extends NetworkSpecifier implements Parcelable { @Override public boolean satisfiedBy(NetworkSpecifier other) { @@ -3790,7 +3768,7 @@ public class ConnectivityServiceTest { * time-out period expires. */ @Test - public void testSatisfiedNetworkRequestDoesNotTriggerOnUnavailable() { + public void testSatisfiedNetworkRequestDoesNotTriggerOnUnavailable() throws Exception { NetworkRequest nr = new NetworkRequest.Builder().addTransportType( NetworkCapabilities.TRANSPORT_WIFI).build(); final TestNetworkCallback networkCallback = new TestNetworkCallback(); @@ -3810,7 +3788,7 @@ public class ConnectivityServiceTest { * not trigger onUnavailable() once the time-out period expires. */ @Test - public void testSatisfiedThenLostNetworkRequestDoesNotTriggerOnUnavailable() { + public void testSatisfiedThenLostNetworkRequestDoesNotTriggerOnUnavailable() throws Exception { NetworkRequest nr = new NetworkRequest.Builder().addTransportType( NetworkCapabilities.TRANSPORT_WIFI).build(); final TestNetworkCallback networkCallback = new TestNetworkCallback(); @@ -3833,7 +3811,7 @@ public class ConnectivityServiceTest { * (somehow) satisfied - the callback isn't called later. */ @Test - public void testTimedoutNetworkRequest() { + public void testTimedoutNetworkRequest() throws Exception { NetworkRequest nr = new NetworkRequest.Builder().addTransportType( NetworkCapabilities.TRANSPORT_WIFI).build(); final TestNetworkCallback networkCallback = new TestNetworkCallback(); @@ -3854,7 +3832,7 @@ public class ConnectivityServiceTest { * trigger the callback. */ @Test - public void testNoCallbackAfterUnregisteredNetworkRequest() { + public void testNoCallbackAfterUnregisteredNetworkRequest() throws Exception { NetworkRequest nr = new NetworkRequest.Builder().addTransportType( NetworkCapabilities.TRANSPORT_WIFI).build(); final TestNetworkCallback networkCallback = new TestNetworkCallback(); @@ -3946,7 +3924,7 @@ public class ConnectivityServiceTest { private static class TestKeepaliveCallback extends PacketKeepaliveCallback { - public static enum CallbackType { ON_STARTED, ON_STOPPED, ON_ERROR }; + public enum CallbackType { ON_STARTED, ON_STOPPED, ON_ERROR } private class CallbackValue { public CallbackType callbackType; @@ -3994,25 +3972,19 @@ public class ConnectivityServiceTest { mCallbacks.add(new CallbackValue(CallbackType.ON_ERROR, error)); } - private void expectCallback(CallbackValue callbackValue) { - try { - assertEquals( - callbackValue, - mCallbacks.poll(TIMEOUT_MS, TimeUnit.MILLISECONDS)); - } catch (InterruptedException e) { - fail(callbackValue.callbackType + " callback not seen after " + TIMEOUT_MS + " ms"); - } + private void expectCallback(CallbackValue callbackValue) throws InterruptedException { + assertEquals(callbackValue, mCallbacks.poll(TIMEOUT_MS, TimeUnit.MILLISECONDS)); } - public void expectStarted() { + public void expectStarted() throws Exception { expectCallback(new CallbackValue(CallbackType.ON_STARTED)); } - public void expectStopped() { + public void expectStopped() throws Exception { expectCallback(new CallbackValue(CallbackType.ON_STOPPED)); } - public void expectError(int error) { + public void expectError(int error) throws Exception { expectCallback(new CallbackValue(CallbackType.ON_ERROR, error)); } } @@ -4073,25 +4045,20 @@ public class ConnectivityServiceTest { mCallbacks.add(new CallbackValue(CallbackType.ON_ERROR, error)); } - private void expectCallback(CallbackValue callbackValue) { - try { - assertEquals( - callbackValue, - mCallbacks.poll(TIMEOUT_MS, TimeUnit.MILLISECONDS)); - } catch (InterruptedException e) { - fail(callbackValue.callbackType + " callback not seen after " + TIMEOUT_MS + " ms"); - } + private void expectCallback(CallbackValue callbackValue) throws InterruptedException { + assertEquals(callbackValue, mCallbacks.poll(TIMEOUT_MS, TimeUnit.MILLISECONDS)); + } - public void expectStarted() { + public void expectStarted() throws InterruptedException { expectCallback(new CallbackValue(CallbackType.ON_STARTED)); } - public void expectStopped() { + public void expectStopped() throws InterruptedException { expectCallback(new CallbackValue(CallbackType.ON_STOPPED)); } - public void expectError(int error) { + public void expectError(int error) throws InterruptedException { expectCallback(new CallbackValue(CallbackType.ON_ERROR, error)); } @@ -4102,7 +4069,7 @@ public class ConnectivityServiceTest { } } - private Network connectKeepaliveNetwork(LinkProperties lp) { + private Network connectKeepaliveNetwork(LinkProperties lp) throws Exception { // Ensure the network is disconnected before we do anything. if (mWiFiNetworkAgent != null) { assertNull(mCm.getNetworkCapabilities(mWiFiNetworkAgent.getNetwork())); @@ -4236,7 +4203,8 @@ public class ConnectivityServiceTest { } // Helper method to prepare the executor and run test - private void runTestWithSerialExecutors(ThrowingConsumer functor) throws Exception { + private void runTestWithSerialExecutors(ExceptionUtils.ThrowingConsumer functor) + throws Exception { final ExecutorService executorSingleThread = Executors.newSingleThreadExecutor(); final Executor executorInline = (Runnable r) -> r.run(); functor.accept(executorSingleThread); @@ -4554,7 +4522,7 @@ public class ConnectivityServiceTest { private static boolean isUdpPortInUse(int port) { try (DatagramSocket ignored = new DatagramSocket(port)) { return false; - } catch (IOException ignored) { + } catch (IOException alreadyInUse) { return true; } } @@ -4566,23 +4534,19 @@ public class ConnectivityServiceTest { } private static class TestNetworkPinner extends NetworkPinner { - public static boolean awaitPin(int timeoutMs) { + public static boolean awaitPin(int timeoutMs) throws InterruptedException { synchronized(sLock) { if (sNetwork == null) { - try { - sLock.wait(timeoutMs); - } catch (InterruptedException e) {} + sLock.wait(timeoutMs); } return sNetwork != null; } } - public static boolean awaitUnpin(int timeoutMs) { + public static boolean awaitUnpin(int timeoutMs) throws InterruptedException { synchronized(sLock) { if (sNetwork != null) { - try { - sLock.wait(timeoutMs); - } catch (InterruptedException e) {} + sLock.wait(timeoutMs); } return sNetwork == null; } @@ -4605,7 +4569,7 @@ public class ConnectivityServiceTest { } @Test - public void testNetworkPinner() { + public void testNetworkPinner() throws Exception { NetworkRequest wifiRequest = new NetworkRequest.Builder() .addTransportType(TRANSPORT_WIFI) .build(); @@ -4757,7 +4721,7 @@ public class ConnectivityServiceTest { } @Test - public void testNetworkInfoOfTypeNone() { + public void testNetworkInfoOfTypeNone() throws Exception { ConditionVariable broadcastCV = waitForConnectivityBroadcasts(1); verifyNoNetwork(); @@ -4818,7 +4782,7 @@ public class ConnectivityServiceTest { } @Test - public void testLinkPropertiesEnsuresDirectlyConnectedRoutes() { + public void testLinkPropertiesEnsuresDirectlyConnectedRoutes() throws Exception { final NetworkRequest networkRequest = new NetworkRequest.Builder() .addTransportType(TRANSPORT_WIFI).build(); final TestNetworkCallback networkCallback = new TestNetworkCallback(); @@ -5226,7 +5190,7 @@ public class ConnectivityServiceTest { } @Test - public void testVpnNetworkActive() { + public void testVpnNetworkActive() throws Exception { final int uid = Process.myUid(); final TestNetworkCallback genericNetworkCallback = new TestNetworkCallback(); @@ -5338,7 +5302,7 @@ public class ConnectivityServiceTest { } @Test - public void testVpnWithoutInternet() { + public void testVpnWithoutInternet() throws Exception { final int uid = Process.myUid(); final TestNetworkCallback defaultCallback = new TestNetworkCallback(); @@ -5368,7 +5332,7 @@ public class ConnectivityServiceTest { } @Test - public void testVpnWithInternet() { + public void testVpnWithInternet() throws Exception { final int uid = Process.myUid(); final TestNetworkCallback defaultCallback = new TestNetworkCallback(); @@ -5451,7 +5415,7 @@ public class ConnectivityServiceTest { } @Test - public void testVpnSetUnderlyingNetworks() { + public void testVpnSetUnderlyingNetworks() throws Exception { final int uid = Process.myUid(); final TestNetworkCallback vpnNetworkCallback = new TestNetworkCallback(); @@ -5549,7 +5513,7 @@ public class ConnectivityServiceTest { } @Test - public void testNullUnderlyingNetworks() { + public void testNullUnderlyingNetworks() throws Exception { final int uid = Process.myUid(); final TestNetworkCallback vpnNetworkCallback = new TestNetworkCallback(); @@ -5613,7 +5577,7 @@ public class ConnectivityServiceTest { } @Test - public void testIsActiveNetworkMeteredOverWifi() { + public void testIsActiveNetworkMeteredOverWifi() throws Exception { // Returns true by default when no network is available. assertTrue(mCm.isActiveNetworkMetered()); mWiFiNetworkAgent = new MockNetworkAgent(TRANSPORT_WIFI); @@ -5625,7 +5589,7 @@ public class ConnectivityServiceTest { } @Test - public void testIsActiveNetworkMeteredOverCell() { + public void testIsActiveNetworkMeteredOverCell() throws Exception { // Returns true by default when no network is available. assertTrue(mCm.isActiveNetworkMetered()); mCellNetworkAgent = new MockNetworkAgent(TRANSPORT_CELLULAR); @@ -5637,7 +5601,7 @@ public class ConnectivityServiceTest { } @Test - public void testIsActiveNetworkMeteredOverVpnTrackingPlatformDefault() { + public void testIsActiveNetworkMeteredOverVpnTrackingPlatformDefault() throws Exception { // Returns true by default when no network is available. assertTrue(mCm.isActiveNetworkMetered()); mCellNetworkAgent = new MockNetworkAgent(TRANSPORT_CELLULAR); @@ -5691,7 +5655,7 @@ public class ConnectivityServiceTest { } @Test - public void testIsActiveNetworkMeteredOverVpnSpecifyingUnderlyingNetworks() { + public void testIsActiveNetworkMeteredOverVpnSpecifyingUnderlyingNetworks() throws Exception { // Returns true by default when no network is available. assertTrue(mCm.isActiveNetworkMetered()); mCellNetworkAgent = new MockNetworkAgent(TRANSPORT_CELLULAR); @@ -5762,7 +5726,7 @@ public class ConnectivityServiceTest { } @Test - public void testIsActiveNetworkMeteredOverAlwaysMeteredVpn() { + public void testIsActiveNetworkMeteredOverAlwaysMeteredVpn() throws Exception { // Returns true by default when no network is available. assertTrue(mCm.isActiveNetworkMetered()); mWiFiNetworkAgent = new MockNetworkAgent(TRANSPORT_WIFI); @@ -5809,7 +5773,7 @@ public class ConnectivityServiceTest { } @Test - public void testNetworkBlockedStatus() { + public void testNetworkBlockedStatus() throws Exception { final TestNetworkCallback cellNetworkCallback = new TestNetworkCallback(); final NetworkRequest cellRequest = new NetworkRequest.Builder() .addTransportType(TRANSPORT_CELLULAR) @@ -5860,7 +5824,7 @@ public class ConnectivityServiceTest { } @Test - public void testNetworkBlockedStatusBeforeAndAfterConnect() { + public void testNetworkBlockedStatusBeforeAndAfterConnect() throws Exception { final TestNetworkCallback defaultCallback = new TestNetworkCallback(); mCm.registerDefaultNetworkCallback(defaultCallback); @@ -5929,7 +5893,7 @@ public class ConnectivityServiceTest { } @Test - public void testStackedLinkProperties() throws UnknownHostException, RemoteException { + public void testStackedLinkProperties() throws Exception { final LinkAddress myIpv4 = new LinkAddress("1.2.3.4/24"); final LinkAddress myIpv6 = new LinkAddress("2001:db8:1::1/64"); final String kNat64PrefixString = "2001:db8:64:64:64:64::"; @@ -6092,7 +6056,7 @@ public class ConnectivityServiceTest { } @Test - public void testDataActivityTracking() throws RemoteException { + public void testDataActivityTracking() throws Exception { final TestNetworkCallback networkCallback = new TestNetworkCallback(); final NetworkRequest networkRequest = new NetworkRequest.Builder() .addCapability(NET_CAPABILITY_INTERNET) @@ -6167,21 +6131,17 @@ public class ConnectivityServiceTest { mCm.unregisterNetworkCallback(networkCallback); } - private void verifyTcpBufferSizeChange(String tcpBufferSizes) { + private void verifyTcpBufferSizeChange(String tcpBufferSizes) throws Exception { String[] values = tcpBufferSizes.split(","); String rmemValues = String.join(" ", values[0], values[1], values[2]); String wmemValues = String.join(" ", values[3], values[4], values[5]); waitForIdle(); - try { - verify(mMockNetd, atLeastOnce()).setTcpRWmemorySize(rmemValues, wmemValues); - } catch (RemoteException e) { - fail("mMockNetd should never throw RemoteException"); - } + verify(mMockNetd, atLeastOnce()).setTcpRWmemorySize(rmemValues, wmemValues); reset(mMockNetd); } @Test - public void testTcpBufferReset() { + public void testTcpBufferReset() throws Exception { final String testTcpBufferSizes = "1,2,3,4,5,6"; mCellNetworkAgent = new MockNetworkAgent(TRANSPORT_CELLULAR); @@ -6198,7 +6158,7 @@ public class ConnectivityServiceTest { } @Test - public void testGetGlobalProxyForNetwork() { + public void testGetGlobalProxyForNetwork() throws Exception { final ProxyInfo testProxyInfo = ProxyInfo.buildDirectProxy("test", 8888); mWiFiNetworkAgent = new MockNetworkAgent(TRANSPORT_WIFI); final Network wifiNetwork = mWiFiNetworkAgent.getNetwork(); @@ -6207,7 +6167,7 @@ public class ConnectivityServiceTest { } @Test - public void testGetProxyForActiveNetwork() { + public void testGetProxyForActiveNetwork() throws Exception { final ProxyInfo testProxyInfo = ProxyInfo.buildDirectProxy("test", 8888); mWiFiNetworkAgent = new MockNetworkAgent(TRANSPORT_WIFI); mWiFiNetworkAgent.connect(true); @@ -6224,7 +6184,7 @@ public class ConnectivityServiceTest { } @Test - public void testGetProxyForVPN() { + public void testGetProxyForVPN() throws Exception { final ProxyInfo testProxyInfo = ProxyInfo.buildDirectProxy("test", 8888); // Set up a WiFi network with no proxy @@ -6410,7 +6370,7 @@ public class ConnectivityServiceTest { private MockNetworkAgent establishVpn(LinkProperties lp, int establishingUid, - Set vpnRange) { + Set vpnRange) throws Exception { final MockNetworkAgent vpnNetworkAgent = new MockNetworkAgent(TRANSPORT_VPN, lp); vpnNetworkAgent.getNetworkCapabilities().setEstablishingVpnAppUid(establishingUid); mMockVpn.setNetworkAgent(vpnNetworkAgent);