Move the connectivity tests to frameworks/base/tests/net.

This will give us a good place to put all the networking tests.

Fix: 31479480
Test: adb  shell am instrument -w -e notClass com.android.server.connectivity.tethering.TetherInterfaceStateMachineTest 'com.android.frameworks.tests.net/android.support.test.runner.AndroidJUnitRunner'  # PASS

(cherry picked from commit 5a7c486d70)

Change-Id: I993eeaa5dec001c39389023f355f506129b356e7
This commit is contained in:
Lorenzo Colitti
2016-10-28 12:48:36 +09:00
parent ae5c443943
commit ebc2b946ee
7 changed files with 149 additions and 3080 deletions

View File

@@ -70,6 +70,7 @@ import android.provider.Settings;
import android.test.AndroidTestCase; import android.test.AndroidTestCase;
import android.test.FlakyTest; import android.test.FlakyTest;
import android.test.mock.MockContentResolver; import android.test.mock.MockContentResolver;
import android.test.suitebuilder.annotation.LargeTest;
import android.test.suitebuilder.annotation.SmallTest; import android.test.suitebuilder.annotation.SmallTest;
import android.util.Log; import android.util.Log;
import android.util.LogPrinter; import android.util.LogPrinter;
@@ -90,7 +91,6 @@ import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.BooleanSupplier;
/** /**
* Tests for {@link ConnectivityService}. * Tests for {@link ConnectivityService}.
@@ -195,7 +195,6 @@ public class ConnectivityServiceTest extends AndroidTestCase {
} }
// Tests that IdleableHandlerThread works as expected. // Tests that IdleableHandlerThread works as expected.
@SmallTest
public void testIdleableHandlerThread() { public void testIdleableHandlerThread() {
final int attempts = 50; // Causes the test to take about 200ms on bullhead-eng. final int attempts = 50; // Causes the test to take about 200ms on bullhead-eng.
@@ -220,7 +219,6 @@ public class ConnectivityServiceTest extends AndroidTestCase {
} }
} }
@SmallTest
@FlakyTest(tolerance = 3) @FlakyTest(tolerance = 3)
public void testNotWaitingForIdleCausesRaceConditions() { public void testNotWaitingForIdleCausesRaceConditions() {
// Bring up a network that we can use to send messages to ConnectivityService. // Bring up a network that we can use to send messages to ConnectivityService.
@@ -624,7 +622,7 @@ public class ConnectivityServiceTest extends AndroidTestCase {
} }
private class WrappedAvoidBadWifiTracker extends AvoidBadWifiTracker { private class WrappedAvoidBadWifiTracker extends AvoidBadWifiTracker {
public volatile boolean configRestrictsAvoidBadWifi; public boolean configRestrictsAvoidBadWifi;
public WrappedAvoidBadWifiTracker(Context c, Handler h, Runnable r) { public WrappedAvoidBadWifiTracker(Context c, Handler h, Runnable r) {
super(c, h, r); super(c, h, r);
@@ -729,7 +727,10 @@ public class ConnectivityServiceTest extends AndroidTestCase {
static private void waitFor(Criteria criteria) { static private void waitFor(Criteria criteria) {
int delays = 0; int delays = 0;
while (!criteria.get()) { while (!criteria.get()) {
sleepFor(50); try {
Thread.sleep(50);
} catch (InterruptedException e) {
}
if (++delays == 10) fail(); if (++delays == 10) fail();
} }
} }
@@ -841,7 +842,7 @@ public class ConnectivityServiceTest extends AndroidTestCase {
return cv; return cv;
} }
@SmallTest @LargeTest
public void testLingering() throws Exception { public void testLingering() throws Exception {
verifyNoNetwork(); verifyNoNetwork();
mCellNetworkAgent = new MockNetworkAgent(TRANSPORT_CELLULAR); mCellNetworkAgent = new MockNetworkAgent(TRANSPORT_CELLULAR);
@@ -881,7 +882,7 @@ public class ConnectivityServiceTest extends AndroidTestCase {
verifyNoNetwork(); verifyNoNetwork();
} }
@SmallTest @LargeTest
public void testValidatedCellularOutscoresUnvalidatedWiFi() throws Exception { public void testValidatedCellularOutscoresUnvalidatedWiFi() throws Exception {
// Test bringing up unvalidated WiFi // Test bringing up unvalidated WiFi
mWiFiNetworkAgent = new MockNetworkAgent(TRANSPORT_WIFI); mWiFiNetworkAgent = new MockNetworkAgent(TRANSPORT_WIFI);
@@ -916,7 +917,7 @@ public class ConnectivityServiceTest extends AndroidTestCase {
verifyNoNetwork(); verifyNoNetwork();
} }
@SmallTest @LargeTest
public void testUnvalidatedWifiOutscoresUnvalidatedCellular() throws Exception { public void testUnvalidatedWifiOutscoresUnvalidatedCellular() throws Exception {
// Test bringing up unvalidated cellular. // Test bringing up unvalidated cellular.
mCellNetworkAgent = new MockNetworkAgent(TRANSPORT_CELLULAR); mCellNetworkAgent = new MockNetworkAgent(TRANSPORT_CELLULAR);
@@ -942,7 +943,7 @@ public class ConnectivityServiceTest extends AndroidTestCase {
verifyNoNetwork(); verifyNoNetwork();
} }
@SmallTest @LargeTest
public void testUnlingeringDoesNotValidate() throws Exception { public void testUnlingeringDoesNotValidate() throws Exception {
// Test bringing up unvalidated WiFi. // Test bringing up unvalidated WiFi.
mWiFiNetworkAgent = new MockNetworkAgent(TRANSPORT_WIFI); mWiFiNetworkAgent = new MockNetworkAgent(TRANSPORT_WIFI);
@@ -970,7 +971,7 @@ public class ConnectivityServiceTest extends AndroidTestCase {
NET_CAPABILITY_VALIDATED)); NET_CAPABILITY_VALIDATED));
} }
@SmallTest @LargeTest
public void testCellularOutscoresWeakWifi() throws Exception { public void testCellularOutscoresWeakWifi() throws Exception {
// Test bringing up validated cellular. // Test bringing up validated cellular.
mCellNetworkAgent = new MockNetworkAgent(TRANSPORT_CELLULAR); mCellNetworkAgent = new MockNetworkAgent(TRANSPORT_CELLULAR);
@@ -996,7 +997,7 @@ public class ConnectivityServiceTest extends AndroidTestCase {
verifyActiveNetwork(TRANSPORT_WIFI); verifyActiveNetwork(TRANSPORT_WIFI);
} }
@SmallTest @LargeTest
public void testReapingNetwork() throws Exception { public void testReapingNetwork() throws Exception {
// Test bringing up WiFi without NET_CAPABILITY_INTERNET. // Test bringing up WiFi without NET_CAPABILITY_INTERNET.
// Expect it to be torn down immediately because it satisfies no requests. // Expect it to be torn down immediately because it satisfies no requests.
@@ -1029,7 +1030,7 @@ public class ConnectivityServiceTest extends AndroidTestCase {
waitFor(cv); waitFor(cv);
} }
@SmallTest @LargeTest
public void testCellularFallback() throws Exception { public void testCellularFallback() throws Exception {
// Test bringing up validated cellular. // Test bringing up validated cellular.
mCellNetworkAgent = new MockNetworkAgent(TRANSPORT_CELLULAR); mCellNetworkAgent = new MockNetworkAgent(TRANSPORT_CELLULAR);
@@ -1067,7 +1068,7 @@ public class ConnectivityServiceTest extends AndroidTestCase {
verifyActiveNetwork(TRANSPORT_WIFI); verifyActiveNetwork(TRANSPORT_WIFI);
} }
@SmallTest @LargeTest
public void testWiFiFallback() throws Exception { public void testWiFiFallback() throws Exception {
// Test bringing up unvalidated WiFi. // Test bringing up unvalidated WiFi.
mWiFiNetworkAgent = new MockNetworkAgent(TRANSPORT_WIFI); mWiFiNetworkAgent = new MockNetworkAgent(TRANSPORT_WIFI);
@@ -1103,6 +1104,29 @@ public class ConnectivityServiceTest extends AndroidTestCase {
UNAVAILABLE UNAVAILABLE
} }
private static class CallbackInfo {
public final CallbackState state;
public final Network network;
public final Object arg;
public CallbackInfo(CallbackState s, Network n, Object o) {
state = s; network = n; arg = o;
}
public String toString() {
return String.format("%s (%s)", state, network);
}
@Override
public boolean equals(Object o) {
if (!(o instanceof CallbackInfo)) return false;
// Ignore timeMs, since it's unpredictable.
CallbackInfo other = (CallbackInfo) o;
return (state == other.state) && Objects.equals(network, other.network);
}
@Override
public int hashCode() {
return Objects.hash(state, network);
}
}
/** /**
* Utility NetworkCallback for testing. The caller must explicitly test for all the callbacks * Utility NetworkCallback for testing. The caller must explicitly test for all the callbacks
* this class receives, by calling expectCallback() exactly once each time a callback is * this class receives, by calling expectCallback() exactly once each time a callback is
@@ -1114,21 +1138,6 @@ public class ConnectivityServiceTest extends AndroidTestCase {
// the linger timeout. // the linger timeout.
private final static int TIMEOUT_MS = 50; private final static int TIMEOUT_MS = 50;
private class CallbackInfo {
public final CallbackState state;
public final Network network;
public Object arg;
public CallbackInfo(CallbackState s, Network n, Object o) {
state = s; network = n; arg = o;
}
public String toString() { return String.format("%s (%s)", state, network); }
public boolean equals(Object o) {
if (!(o instanceof CallbackInfo)) return false;
// Ignore timeMs, since it's unpredictable.
CallbackInfo other = (CallbackInfo) o;
return state == other.state && Objects.equals(network, other.network);
}
}
private final LinkedBlockingQueue<CallbackInfo> mCallbacks = new LinkedBlockingQueue<>(); private final LinkedBlockingQueue<CallbackInfo> mCallbacks = new LinkedBlockingQueue<>();
protected void setLastCallback(CallbackState state, Network network, Object o) { protected void setLastCallback(CallbackState state, Network network, Object o) {
@@ -1155,17 +1164,24 @@ public class ConnectivityServiceTest extends AndroidTestCase {
setLastCallback(CallbackState.LOST, network, null); setLastCallback(CallbackState.LOST, network, null);
} }
CallbackInfo nextCallback(int timeoutMs) {
CallbackInfo cb = null;
try {
cb = mCallbacks.poll(timeoutMs, TimeUnit.MILLISECONDS);
} catch (InterruptedException e) {
}
if (cb == null) {
// LinkedBlockingQueue.poll() returns null if it timeouts.
fail("Did not receive callback after " + timeoutMs + "ms");
}
return cb;
}
void expectCallback(CallbackState state, MockNetworkAgent mockAgent, int timeoutMs) { void expectCallback(CallbackState state, MockNetworkAgent mockAgent, int timeoutMs) {
CallbackInfo expected = new CallbackInfo( CallbackInfo expected = new CallbackInfo(
state, (mockAgent != null) ? mockAgent.getNetwork() : null, 0); state, (mockAgent != null) ? mockAgent.getNetwork() : null, 0);
CallbackInfo actual; CallbackInfo actual = nextCallback(timeoutMs);
try { assertEquals("Unexpected callback:", expected, actual);
actual = mCallbacks.poll(timeoutMs, TimeUnit.MILLISECONDS);
assertEquals("Unexpected callback:", expected, actual);
} catch (InterruptedException e) {
fail("Did not receive expected " + expected + " after " + TIMEOUT_MS + "ms");
actual = null; // Or the compiler can't tell it's never used uninitialized.
}
if (state == CallbackState.LOSING) { if (state == CallbackState.LOSING) {
String msg = String.format( String msg = String.format(
"Invalid linger time value %d, must be between %d and %d", "Invalid linger time value %d, must be between %d and %d",
@@ -1194,7 +1210,7 @@ public class ConnectivityServiceTest extends AndroidTestCase {
} }
} }
@SmallTest @LargeTest
public void testStateChangeNetworkCallbacks() throws Exception { public void testStateChangeNetworkCallbacks() throws Exception {
final TestNetworkCallback genericNetworkCallback = new TestNetworkCallback(); final TestNetworkCallback genericNetworkCallback = new TestNetworkCallback();
final TestNetworkCallback wifiNetworkCallback = new TestNetworkCallback(); final TestNetworkCallback wifiNetworkCallback = new TestNetworkCallback();
@@ -1577,7 +1593,7 @@ public class ConnectivityServiceTest extends AndroidTestCase {
handlerThread.quit(); handlerThread.quit();
} }
@SmallTest @LargeTest
public void testNetworkFactoryRequests() throws Exception { public void testNetworkFactoryRequests() throws Exception {
tryNetworkFactoryRequests(NET_CAPABILITY_MMS); tryNetworkFactoryRequests(NET_CAPABILITY_MMS);
tryNetworkFactoryRequests(NET_CAPABILITY_SUPL); tryNetworkFactoryRequests(NET_CAPABILITY_SUPL);
@@ -1597,7 +1613,7 @@ public class ConnectivityServiceTest extends AndroidTestCase {
// Skipping VALIDATED and CAPTIVE_PORTAL as they're disallowed. // Skipping VALIDATED and CAPTIVE_PORTAL as they're disallowed.
} }
@SmallTest @LargeTest
public void testNoMutableNetworkRequests() throws Exception { public void testNoMutableNetworkRequests() throws Exception {
PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, new Intent("a"), 0); PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, new Intent("a"), 0);
NetworkRequest.Builder builder = new NetworkRequest.Builder(); NetworkRequest.Builder builder = new NetworkRequest.Builder();
@@ -1622,7 +1638,7 @@ public class ConnectivityServiceTest extends AndroidTestCase {
} catch (IllegalArgumentException expected) {} } catch (IllegalArgumentException expected) {}
} }
@SmallTest @LargeTest
public void testMMSonWiFi() throws Exception { public void testMMSonWiFi() throws Exception {
// Test bringing up cellular without MMS NetworkRequest gets reaped // Test bringing up cellular without MMS NetworkRequest gets reaped
mCellNetworkAgent = new MockNetworkAgent(TRANSPORT_CELLULAR); mCellNetworkAgent = new MockNetworkAgent(TRANSPORT_CELLULAR);
@@ -1657,7 +1673,7 @@ public class ConnectivityServiceTest extends AndroidTestCase {
verifyActiveNetwork(TRANSPORT_WIFI); verifyActiveNetwork(TRANSPORT_WIFI);
} }
@SmallTest @LargeTest
public void testMMSonCell() throws Exception { public void testMMSonCell() throws Exception {
// Test bringing up cellular without MMS // Test bringing up cellular without MMS
mCellNetworkAgent = new MockNetworkAgent(TRANSPORT_CELLULAR); mCellNetworkAgent = new MockNetworkAgent(TRANSPORT_CELLULAR);
@@ -1683,7 +1699,7 @@ public class ConnectivityServiceTest extends AndroidTestCase {
verifyActiveNetwork(TRANSPORT_CELLULAR); verifyActiveNetwork(TRANSPORT_CELLULAR);
} }
@SmallTest @LargeTest
public void testCaptivePortal() { public void testCaptivePortal() {
final TestNetworkCallback captivePortalCallback = new TestNetworkCallback(); final TestNetworkCallback captivePortalCallback = new TestNetworkCallback();
final NetworkRequest captivePortalRequest = new NetworkRequest.Builder() final NetworkRequest captivePortalRequest = new NetworkRequest.Builder()
@@ -1732,7 +1748,7 @@ public class ConnectivityServiceTest extends AndroidTestCase {
validatedCallback.expectCallback(CallbackState.LOST, mWiFiNetworkAgent); validatedCallback.expectCallback(CallbackState.LOST, mWiFiNetworkAgent);
} }
@SmallTest @LargeTest
public void testAvoidOrIgnoreCaptivePortals() { public void testAvoidOrIgnoreCaptivePortals() {
final TestNetworkCallback captivePortalCallback = new TestNetworkCallback(); final TestNetworkCallback captivePortalCallback = new TestNetworkCallback();
final NetworkRequest captivePortalRequest = new NetworkRequest.Builder() final NetworkRequest captivePortalRequest = new NetworkRequest.Builder()
@@ -1803,7 +1819,7 @@ public class ConnectivityServiceTest extends AndroidTestCase {
execptionCalled); execptionCalled);
} }
@SmallTest @LargeTest
public void testRegisterDefaultNetworkCallback() throws Exception { public void testRegisterDefaultNetworkCallback() throws Exception {
final TestNetworkCallback defaultNetworkCallback = new TestNetworkCallback(); final TestNetworkCallback defaultNetworkCallback = new TestNetworkCallback();
mCm.registerDefaultNetworkCallback(defaultNetworkCallback); mCm.registerDefaultNetworkCallback(defaultNetworkCallback);
@@ -1864,7 +1880,7 @@ public class ConnectivityServiceTest extends AndroidTestCase {
} }
} }
@SmallTest @LargeTest
public void testRequestCallbackUpdates() throws Exception { public void testRequestCallbackUpdates() throws Exception {
// File a network request for mobile. // File a network request for mobile.
final TestNetworkCallback cellNetworkCallback = new TestRequestUpdateCallback(); final TestNetworkCallback cellNetworkCallback = new TestRequestUpdateCallback();
@@ -1999,7 +2015,6 @@ public class ConnectivityServiceTest extends AndroidTestCase {
@SmallTest @SmallTest
public void testRequestBenchmark() throws Exception { public void testRequestBenchmark() throws Exception {
// TODO: turn this unit test into a real benchmarking test.
// Benchmarks connecting and switching performance in the presence of a large number of // Benchmarks connecting and switching performance in the presence of a large number of
// NetworkRequests. // NetworkRequests.
// 1. File NUM_REQUESTS requests. // 1. File NUM_REQUESTS requests.
@@ -2013,80 +2028,61 @@ public class ConnectivityServiceTest extends AndroidTestCase {
final CountDownLatch availableLatch = new CountDownLatch(NUM_REQUESTS); final CountDownLatch availableLatch = new CountDownLatch(NUM_REQUESTS);
final CountDownLatch losingLatch = new CountDownLatch(NUM_REQUESTS); final CountDownLatch losingLatch = new CountDownLatch(NUM_REQUESTS);
final int REGISTER_TIME_LIMIT_MS = 100;
long startTime = System.currentTimeMillis();
for (int i = 0; i < NUM_REQUESTS; i++) { for (int i = 0; i < NUM_REQUESTS; i++) {
callbacks[i] = new NetworkCallback() { callbacks[i] = new NetworkCallback() {
@Override public void onAvailable(Network n) { availableLatch.countDown(); } @Override public void onAvailable(Network n) { availableLatch.countDown(); }
@Override public void onLosing(Network n, int t) { losingLatch.countDown(); } @Override public void onLosing(Network n, int t) { losingLatch.countDown(); }
}; };
mCm.registerNetworkCallback(request, callbacks[i]);
} }
long timeTaken = System.currentTimeMillis() - startTime;
String msg = String.format("Register %d callbacks: %dms, acceptable %dms",
NUM_REQUESTS, timeTaken, REGISTER_TIME_LIMIT_MS);
Log.d(TAG, msg);
assertTrue(msg, timeTaken < REGISTER_TIME_LIMIT_MS);
final int REGISTER_TIME_LIMIT_MS = 180; final int CONNECT_TIME_LIMIT_MS = 30;
assertTimeLimit("Registering callbacks", REGISTER_TIME_LIMIT_MS, () -> {
for (NetworkCallback cb : callbacks) {
mCm.registerNetworkCallback(request, cb);
}
});
final int CONNECT_TIME_LIMIT_MS = 40;
mCellNetworkAgent = new MockNetworkAgent(TRANSPORT_CELLULAR); mCellNetworkAgent = new MockNetworkAgent(TRANSPORT_CELLULAR);
// Don't request that the network validate, because otherwise connect() will block until // Don't request that the network validate, because otherwise connect() will block until
// the network gets NET_CAPABILITY_VALIDATED, after all the callbacks below have fired, // the network gets NET_CAPABILITY_VALIDATED, after all the callbacks below have fired,
// and we won't actually measure anything. // and we won't actually measure anything.
mCellNetworkAgent.connect(false); mCellNetworkAgent.connect(false);
startTime = System.currentTimeMillis();
long onAvailableDispatchingDuration = durationOf(() -> { if (!availableLatch.await(CONNECT_TIME_LIMIT_MS, TimeUnit.MILLISECONDS)) {
if (!awaitLatch(availableLatch, CONNECT_TIME_LIMIT_MS)) { fail(String.format("Only dispatched %d/%d onAvailable callbacks in %dms",
fail(String.format("Only dispatched %d/%d onAvailable callbacks in %dms", NUM_REQUESTS - availableLatch.getCount(), NUM_REQUESTS,
NUM_REQUESTS - availableLatch.getCount(), NUM_REQUESTS, CONNECT_TIME_LIMIT_MS));
CONNECT_TIME_LIMIT_MS)); }
} timeTaken = System.currentTimeMillis() - startTime;
});
Log.d(TAG, String.format("Connect, %d callbacks: %dms, acceptable %dms", Log.d(TAG, String.format("Connect, %d callbacks: %dms, acceptable %dms",
NUM_REQUESTS, onAvailableDispatchingDuration, CONNECT_TIME_LIMIT_MS)); NUM_REQUESTS, timeTaken, CONNECT_TIME_LIMIT_MS));
final int SWITCH_TIME_LIMIT_MS = 40; final int SWITCH_TIME_LIMIT_MS = 30;
mWiFiNetworkAgent = new MockNetworkAgent(TRANSPORT_WIFI); mWiFiNetworkAgent = new MockNetworkAgent(TRANSPORT_WIFI);
// Give wifi a high enough score that we'll linger cell when wifi comes up. // Give wifi a high enough score that we'll linger cell when wifi comes up.
mWiFiNetworkAgent.adjustScore(40); mWiFiNetworkAgent.adjustScore(40);
mWiFiNetworkAgent.connect(false); mWiFiNetworkAgent.connect(false);
startTime = System.currentTimeMillis();
long onLostDispatchingDuration = durationOf(() -> { if (!losingLatch.await(SWITCH_TIME_LIMIT_MS, TimeUnit.MILLISECONDS)) {
if (!awaitLatch(losingLatch, SWITCH_TIME_LIMIT_MS)) { fail(String.format("Only dispatched %d/%d onLosing callbacks in %dms",
fail(String.format("Only dispatched %d/%d onLosing callbacks in %dms", NUM_REQUESTS - losingLatch.getCount(), NUM_REQUESTS, SWITCH_TIME_LIMIT_MS));
NUM_REQUESTS - losingLatch.getCount(), NUM_REQUESTS, SWITCH_TIME_LIMIT_MS)); }
} timeTaken = System.currentTimeMillis() - startTime;
});
Log.d(TAG, String.format("Linger, %d callbacks: %dms, acceptable %dms", Log.d(TAG, String.format("Linger, %d callbacks: %dms, acceptable %dms",
NUM_REQUESTS, onLostDispatchingDuration, SWITCH_TIME_LIMIT_MS)); NUM_REQUESTS, timeTaken, SWITCH_TIME_LIMIT_MS));
final int UNREGISTER_TIME_LIMIT_MS = 10; final int UNREGISTER_TIME_LIMIT_MS = 10;
assertTimeLimit("Unregistering callbacks", UNREGISTER_TIME_LIMIT_MS, () -> { startTime = System.currentTimeMillis();
for (NetworkCallback cb : callbacks) { for (int i = 0; i < NUM_REQUESTS; i++) {
mCm.unregisterNetworkCallback(cb); mCm.unregisterNetworkCallback(callbacks[i]);
} }
}); timeTaken = System.currentTimeMillis() - startTime;
} msg = String.format("Unregister %d callbacks: %dms, acceptable %dms",
NUM_REQUESTS, timeTaken, UNREGISTER_TIME_LIMIT_MS);
private long durationOf(Runnable fn) {
long startTime = SystemClock.elapsedRealtime();
fn.run();
return SystemClock.elapsedRealtime() - startTime;
}
private void assertTimeLimit(String descr, long timeLimit, Runnable fn) {
long timeTaken = durationOf(fn);
String msg = String.format("%s: took %dms, limit was %dms", descr, timeTaken, timeLimit);
Log.d(TAG, msg); Log.d(TAG, msg);
assertTrue(msg, timeTaken <= timeLimit); assertTrue(msg, timeTaken < UNREGISTER_TIME_LIMIT_MS);
}
private boolean awaitLatch(CountDownLatch l, long timeoutMs) {
try {
if (l.await(timeoutMs, TimeUnit.MILLISECONDS)) {
return true;
}
} catch (InterruptedException e) {}
return false;
} }
@SmallTest @SmallTest
@@ -2167,7 +2163,7 @@ public class ConnectivityServiceTest extends AndroidTestCase {
tracker.reevaluate(); tracker.reevaluate();
mService.waitForIdle(); mService.waitForIdle();
String msg = String.format("config=false, setting=%s", values[i]); String msg = String.format("config=false, setting=%s", values[i]);
assertEventuallyTrue(() -> mService.avoidBadWifi(), 50); assertTrue(msg, mService.avoidBadWifi());
assertFalse(msg, tracker.shouldNotifyWifiUnvalidated()); assertFalse(msg, tracker.shouldNotifyWifiUnvalidated());
} }
@@ -2176,19 +2172,19 @@ public class ConnectivityServiceTest extends AndroidTestCase {
Settings.Global.putInt(cr, settingName, 0); Settings.Global.putInt(cr, settingName, 0);
tracker.reevaluate(); tracker.reevaluate();
mService.waitForIdle(); mService.waitForIdle();
assertEventuallyTrue(() -> !mService.avoidBadWifi(), 50); assertFalse(mService.avoidBadWifi());
assertFalse(tracker.shouldNotifyWifiUnvalidated()); assertFalse(tracker.shouldNotifyWifiUnvalidated());
Settings.Global.putInt(cr, settingName, 1); Settings.Global.putInt(cr, settingName, 1);
tracker.reevaluate(); tracker.reevaluate();
mService.waitForIdle(); mService.waitForIdle();
assertEventuallyTrue(() -> mService.avoidBadWifi(), 50); assertTrue(mService.avoidBadWifi());
assertFalse(tracker.shouldNotifyWifiUnvalidated()); assertFalse(tracker.shouldNotifyWifiUnvalidated());
Settings.Global.putString(cr, settingName, null); Settings.Global.putString(cr, settingName, null);
tracker.reevaluate(); tracker.reevaluate();
mService.waitForIdle(); mService.waitForIdle();
assertEventuallyTrue(() -> !mService.avoidBadWifi(), 50); assertFalse(mService.avoidBadWifi());
assertTrue(tracker.shouldNotifyWifiUnvalidated()); assertTrue(tracker.shouldNotifyWifiUnvalidated());
} }
@@ -2331,30 +2327,10 @@ public class ConnectivityServiceTest extends AndroidTestCase {
networkCallback.expectCallback(CallbackState.AVAILABLE, mWiFiNetworkAgent); networkCallback.expectCallback(CallbackState.AVAILABLE, mWiFiNetworkAgent);
// pass timeout and validate that UNAVAILABLE is not called // pass timeout and validate that UNAVAILABLE is not called
sleepFor(15); try {
networkCallback.assertNoCallback(); Thread.sleep(15);
} } catch (InterruptedException e) {
}
/**
* Validate that a satisfied network request followed by a disconnected (lost) network does
* not trigger onUnavailable() once the time-out period expires.
*/
@SmallTest
public void testSatisfiedThenLostNetworkRequestDoesNotTriggerOnUnavailable() {
NetworkRequest nr = new NetworkRequest.Builder().addTransportType(
NetworkCapabilities.TRANSPORT_WIFI).build();
final TestNetworkCallback networkCallback = new TestNetworkCallback();
mCm.requestNetwork(nr, networkCallback, 500);
mWiFiNetworkAgent = new MockNetworkAgent(TRANSPORT_WIFI);
mWiFiNetworkAgent.connect(false);
networkCallback.expectCallback(CallbackState.AVAILABLE, mWiFiNetworkAgent);
sleepFor(20);
mWiFiNetworkAgent.disconnect();
networkCallback.expectCallback(CallbackState.LOST, mWiFiNetworkAgent);
// pass timeout and validate that UNAVAILABLE is not called
sleepFor(600);
networkCallback.assertNoCallback(); networkCallback.assertNoCallback();
} }
@@ -2396,7 +2372,10 @@ public class ConnectivityServiceTest extends AndroidTestCase {
// pass timeout and validate that no callbacks // pass timeout and validate that no callbacks
// Note: doesn't validate that nothing called from CS since even if called the CM already // Note: doesn't validate that nothing called from CS since even if called the CM already
// unregisters the callback and won't pass it through! // unregisters the callback and won't pass it through!
sleepFor(15); try {
Thread.sleep(15);
} catch (InterruptedException e) {
}
networkCallback.assertNoCallback(); networkCallback.assertNoCallback();
// create a network satisfying request - validate that request not triggered // create a network satisfying request - validate that request not triggered
@@ -2405,17 +2384,6 @@ public class ConnectivityServiceTest extends AndroidTestCase {
networkCallback.assertNoCallback(); networkCallback.assertNoCallback();
} }
public void assertEventuallyTrue(BooleanSupplier fn, long maxWaitingTimeMs) throws Exception {
long start = SystemClock.elapsedRealtime();
while (SystemClock.elapsedRealtime() <= start + maxWaitingTimeMs) {
if (fn.getAsBoolean()) {
return;
}
Thread.sleep(10);
}
assertTrue(fn.getAsBoolean());
}
private static class TestKeepaliveCallback extends PacketKeepaliveCallback { private static class TestKeepaliveCallback extends PacketKeepaliveCallback {
public static enum CallbackType { ON_STARTED, ON_STOPPED, ON_ERROR }; public static enum CallbackType { ON_STARTED, ON_STOPPED, ON_ERROR };
@@ -2505,7 +2473,6 @@ public class ConnectivityServiceTest extends AndroidTestCase {
return mWiFiNetworkAgent.getNetwork(); return mWiFiNetworkAgent.getNetwork();
} }
@SmallTest
public void testPacketKeepalives() throws Exception { public void testPacketKeepalives() throws Exception {
InetAddress myIPv4 = InetAddress.getByName("192.0.2.129"); InetAddress myIPv4 = InetAddress.getByName("192.0.2.129");
InetAddress notMyIPv4 = InetAddress.getByName("192.0.2.35"); InetAddress notMyIPv4 = InetAddress.getByName("192.0.2.35");
@@ -2821,13 +2788,4 @@ public class ConnectivityServiceTest extends AndroidTestCase {
mCm.unregisterNetworkCallback(pendingIntent); mCm.unregisterNetworkCallback(pendingIntent);
} }
} }
/* test utilities */
static private void sleepFor(int ms) {
try {
Thread.sleep(ms);
} catch (InterruptedException e) {
}
}
} }

View File

@@ -71,8 +71,7 @@ public class IpConnectivityEventBuilderTest extends TestCase {
" transport_types: 3", " transport_types: 3",
" >", " >",
" time_ms: 1", " time_ms: 1",
">", ">");
"version: 2");
verifySerialization(want, ev); verifySerialization(want, ev);
} }
@@ -94,8 +93,7 @@ public class IpConnectivityEventBuilderTest extends TestCase {
" state_transition: \"SomeState\"", " state_transition: \"SomeState\"",
" >", " >",
" time_ms: 1", " time_ms: 1",
">", ">");
"version: 2");
verifySerialization(want, ev); verifySerialization(want, ev);
} }
@@ -116,8 +114,7 @@ public class IpConnectivityEventBuilderTest extends TestCase {
" state_transition: \"\"", " state_transition: \"\"",
" >", " >",
" time_ms: 1", " time_ms: 1",
">", ">");
"version: 2");
verifySerialization(want, ev); verifySerialization(want, ev);
} }
@@ -163,8 +160,7 @@ public class IpConnectivityEventBuilderTest extends TestCase {
" return_codes: 178", " return_codes: 178",
" >", " >",
" time_ms: 1", " time_ms: 1",
">", ">");
"version: 2");
verifySerialization(want, ev); verifySerialization(want, ev);
} }
@@ -185,8 +181,7 @@ public class IpConnectivityEventBuilderTest extends TestCase {
" latency_ms: 5678", " latency_ms: 5678",
" >", " >",
" time_ms: 1", " time_ms: 1",
">", ">");
"version: 2");
verifySerialization(want, ev); verifySerialization(want, ev);
} }
@@ -205,8 +200,7 @@ public class IpConnectivityEventBuilderTest extends TestCase {
" if_name: \"wlan0\"", " if_name: \"wlan0\"",
" >", " >",
" time_ms: 1", " time_ms: 1",
">", ">");
"version: 2");
verifySerialization(want, ev); verifySerialization(want, ev);
} }
@@ -229,8 +223,7 @@ public class IpConnectivityEventBuilderTest extends TestCase {
" >", " >",
" >", " >",
" time_ms: 1", " time_ms: 1",
">", ">");
"version: 2");
verifySerialization(want, ev); verifySerialization(want, ev);
} }
@@ -255,8 +248,7 @@ public class IpConnectivityEventBuilderTest extends TestCase {
" probe_result: 204", " probe_result: 204",
" probe_type: 1", " probe_type: 1",
" >", " >",
">", ">");
"version: 2");
verifySerialization(want, ev); verifySerialization(want, ev);
} }
@@ -282,8 +274,7 @@ public class IpConnectivityEventBuilderTest extends TestCase {
" program_length: 2048", " program_length: 2048",
" >", " >",
" time_ms: 1", " time_ms: 1",
">", ">");
"version: 2");
verifySerialization(want, ev); verifySerialization(want, ev);
} }
@@ -314,8 +305,7 @@ public class IpConnectivityEventBuilderTest extends TestCase {
" zero_lifetime_ras: 1", " zero_lifetime_ras: 1",
" >", " >",
" time_ms: 1", " time_ms: 1",
">", ">");
"version: 2");
verifySerialization(want, ev); verifySerialization(want, ev);
} }
@@ -342,8 +332,7 @@ public class IpConnectivityEventBuilderTest extends TestCase {
" router_lifetime: 2000", " router_lifetime: 2000",
" >", " >",
" time_ms: 1", " time_ms: 1",
">", ">");
"version: 2");
verifySerialization(want, ev); verifySerialization(want, ev);
} }

View File

@@ -19,7 +19,6 @@ package com.android.server.connectivity;
import android.content.Context; import android.content.Context;
import android.net.ConnectivityMetricsEvent; import android.net.ConnectivityMetricsEvent;
import android.net.IIpConnectivityMetrics; import android.net.IIpConnectivityMetrics;
import android.net.metrics.ApfProgramEvent;
import android.net.metrics.ApfStats; import android.net.metrics.ApfStats;
import android.net.metrics.DefaultNetworkEvent; import android.net.metrics.DefaultNetworkEvent;
import android.net.metrics.DhcpClientEvent; import android.net.metrics.DhcpClientEvent;
@@ -58,7 +57,7 @@ public class IpConnectivityMetricsTest extends TestCase {
public void setUp() { public void setUp() {
MockitoAnnotations.initMocks(this); MockitoAnnotations.initMocks(this);
mService = new IpConnectivityMetrics(mCtx, (ctx) -> 2000); mService = new IpConnectivityMetrics(mCtx);
} }
public void testLoggingEvents() throws Exception { public void testLoggingEvents() throws Exception {
@@ -113,27 +112,6 @@ public class IpConnectivityMetricsTest extends TestCase {
assertEquals("", output3); assertEquals("", output3);
} }
public void testRateLimiting() {
final IpConnectivityLog logger = new IpConnectivityLog(mService.impl);
final ApfProgramEvent ev = new ApfProgramEvent(0, 0, 0, 0, 0);
final long fakeTimestamp = 1;
int attempt = 100; // More than burst quota, but less than buffer size.
for (int i = 0; i < attempt; i++) {
logger.log(ev);
}
String output1 = getdump("flush");
assertFalse("".equals(output1));
for (int i = 0; i < attempt; i++) {
assertFalse("expected event to be dropped", logger.log(fakeTimestamp, ev));
}
String output2 = getdump("flush");
assertEquals("", output2);
}
public void testEndToEndLogging() { public void testEndToEndLogging() {
IpConnectivityLog logger = new IpConnectivityLog(mService.impl); IpConnectivityLog logger = new IpConnectivityLog(mService.impl);
@@ -226,8 +204,7 @@ public class IpConnectivityMetricsTest extends TestCase {
" router_lifetime: 2000", " router_lifetime: 2000",
" >", " >",
" time_ms: 700", " time_ms: 700",
">", ">");
"version: 2");
verifySerialization(want, getdump("flush")); verifySerialization(want, getdump("flush"));
} }

View File

@@ -24,7 +24,6 @@ import android.net.Network;
import android.net.NetworkCapabilities; import android.net.NetworkCapabilities;
import android.net.NetworkInfo; import android.net.NetworkInfo;
import android.net.NetworkMisc; import android.net.NetworkMisc;
import android.test.suitebuilder.annotation.SmallTest;
import android.text.format.DateUtils; import android.text.format.DateUtils;
import com.android.internal.R; import com.android.internal.R;
import com.android.server.ConnectivityService; import com.android.server.ConnectivityService;
@@ -71,7 +70,6 @@ public class LingerMonitorTest extends TestCase {
mMonitor = new TestableLingerMonitor(mCtx, mNotifier, HIGH_DAILY_LIMIT, HIGH_RATE_LIMIT); mMonitor = new TestableLingerMonitor(mCtx, mNotifier, HIGH_DAILY_LIMIT, HIGH_RATE_LIMIT);
} }
@SmallTest
public void testTransitions() { public void testTransitions() {
setNotificationSwitch(transition(WIFI, CELLULAR)); setNotificationSwitch(transition(WIFI, CELLULAR));
NetworkAgentInfo nai1 = wifiNai(100); NetworkAgentInfo nai1 = wifiNai(100);
@@ -81,7 +79,6 @@ public class LingerMonitorTest extends TestCase {
assertFalse(mMonitor.isNotificationEnabled(nai2, nai1)); assertFalse(mMonitor.isNotificationEnabled(nai2, nai1));
} }
@SmallTest
public void testNotificationOnLinger() { public void testNotificationOnLinger() {
setNotificationSwitch(transition(WIFI, CELLULAR)); setNotificationSwitch(transition(WIFI, CELLULAR));
setNotificationType(LingerMonitor.NOTIFY_TYPE_NOTIFICATION); setNotificationType(LingerMonitor.NOTIFY_TYPE_NOTIFICATION);
@@ -92,7 +89,6 @@ public class LingerMonitorTest extends TestCase {
verifyNotification(from, to); verifyNotification(from, to);
} }
@SmallTest
public void testToastOnLinger() { public void testToastOnLinger() {
setNotificationSwitch(transition(WIFI, CELLULAR)); setNotificationSwitch(transition(WIFI, CELLULAR));
setNotificationType(LingerMonitor.NOTIFY_TYPE_TOAST); setNotificationType(LingerMonitor.NOTIFY_TYPE_TOAST);
@@ -103,7 +99,6 @@ public class LingerMonitorTest extends TestCase {
verifyToast(from, to); verifyToast(from, to);
} }
@SmallTest
public void testNotificationClearedAfterDisconnect() { public void testNotificationClearedAfterDisconnect() {
setNotificationSwitch(transition(WIFI, CELLULAR)); setNotificationSwitch(transition(WIFI, CELLULAR));
setNotificationType(LingerMonitor.NOTIFY_TYPE_NOTIFICATION); setNotificationType(LingerMonitor.NOTIFY_TYPE_NOTIFICATION);
@@ -117,7 +112,6 @@ public class LingerMonitorTest extends TestCase {
verify(mNotifier, times(1)).clearNotification(100); verify(mNotifier, times(1)).clearNotification(100);
} }
@SmallTest
public void testNotificationClearedAfterSwitchingBack() { public void testNotificationClearedAfterSwitchingBack() {
setNotificationSwitch(transition(WIFI, CELLULAR)); setNotificationSwitch(transition(WIFI, CELLULAR));
setNotificationType(LingerMonitor.NOTIFY_TYPE_NOTIFICATION); setNotificationType(LingerMonitor.NOTIFY_TYPE_NOTIFICATION);
@@ -131,7 +125,6 @@ public class LingerMonitorTest extends TestCase {
verify(mNotifier, times(1)).clearNotification(100); verify(mNotifier, times(1)).clearNotification(100);
} }
@SmallTest
public void testUniqueToast() { public void testUniqueToast() {
setNotificationSwitch(transition(WIFI, CELLULAR)); setNotificationSwitch(transition(WIFI, CELLULAR));
setNotificationType(LingerMonitor.NOTIFY_TYPE_TOAST); setNotificationType(LingerMonitor.NOTIFY_TYPE_TOAST);
@@ -149,7 +142,6 @@ public class LingerMonitorTest extends TestCase {
verifyNoNotifications(); verifyNoNotifications();
} }
@SmallTest
public void testMultipleNotifications() { public void testMultipleNotifications() {
setNotificationSwitch(transition(WIFI, CELLULAR)); setNotificationSwitch(transition(WIFI, CELLULAR));
setNotificationType(LingerMonitor.NOTIFY_TYPE_NOTIFICATION); setNotificationType(LingerMonitor.NOTIFY_TYPE_NOTIFICATION);
@@ -168,7 +160,6 @@ public class LingerMonitorTest extends TestCase {
verifyNotification(wifi2, cell); verifyNotification(wifi2, cell);
} }
@SmallTest
public void testRateLimiting() throws InterruptedException { public void testRateLimiting() throws InterruptedException {
mMonitor = new TestableLingerMonitor(mCtx, mNotifier, HIGH_DAILY_LIMIT, LOW_RATE_LIMIT); mMonitor = new TestableLingerMonitor(mCtx, mNotifier, HIGH_DAILY_LIMIT, LOW_RATE_LIMIT);
@@ -194,7 +185,6 @@ public class LingerMonitorTest extends TestCase {
verifyNoNotifications(); verifyNoNotifications();
} }
@SmallTest
public void testDailyLimiting() throws InterruptedException { public void testDailyLimiting() throws InterruptedException {
mMonitor = new TestableLingerMonitor(mCtx, mNotifier, LOW_DAILY_LIMIT, HIGH_RATE_LIMIT); mMonitor = new TestableLingerMonitor(mCtx, mNotifier, LOW_DAILY_LIMIT, HIGH_RATE_LIMIT);
@@ -221,7 +211,6 @@ public class LingerMonitorTest extends TestCase {
verifyNoNotifications(); verifyNoNotifications();
} }
@SmallTest
public void testUniqueNotification() { public void testUniqueNotification() {
setNotificationSwitch(transition(WIFI, CELLULAR)); setNotificationSwitch(transition(WIFI, CELLULAR));
setNotificationType(LingerMonitor.NOTIFY_TYPE_NOTIFICATION); setNotificationType(LingerMonitor.NOTIFY_TYPE_NOTIFICATION);
@@ -238,7 +227,6 @@ public class LingerMonitorTest extends TestCase {
verifyNotification(from, to); verifyNotification(from, to);
} }
@SmallTest
public void testIgnoreNeverValidatedNetworks() { public void testIgnoreNeverValidatedNetworks() {
setNotificationType(LingerMonitor.NOTIFY_TYPE_TOAST); setNotificationType(LingerMonitor.NOTIFY_TYPE_TOAST);
setNotificationSwitch(transition(WIFI, CELLULAR)); setNotificationSwitch(transition(WIFI, CELLULAR));
@@ -250,7 +238,6 @@ public class LingerMonitorTest extends TestCase {
verifyNoNotifications(); verifyNoNotifications();
} }
@SmallTest
public void testIgnoreCurrentlyValidatedNetworks() { public void testIgnoreCurrentlyValidatedNetworks() {
setNotificationType(LingerMonitor.NOTIFY_TYPE_TOAST); setNotificationType(LingerMonitor.NOTIFY_TYPE_TOAST);
setNotificationSwitch(transition(WIFI, CELLULAR)); setNotificationSwitch(transition(WIFI, CELLULAR));
@@ -262,7 +249,6 @@ public class LingerMonitorTest extends TestCase {
verifyNoNotifications(); verifyNoNotifications();
} }
@SmallTest
public void testNoNotificationType() { public void testNoNotificationType() {
setNotificationType(LingerMonitor.NOTIFY_TYPE_TOAST); setNotificationType(LingerMonitor.NOTIFY_TYPE_TOAST);
setNotificationSwitch(); setNotificationSwitch();
@@ -273,7 +259,6 @@ public class LingerMonitorTest extends TestCase {
verifyNoNotifications(); verifyNoNotifications();
} }
@SmallTest
public void testNoTransitionToNotify() { public void testNoTransitionToNotify() {
setNotificationType(LingerMonitor.NOTIFY_TYPE_NONE); setNotificationType(LingerMonitor.NOTIFY_TYPE_NONE);
setNotificationSwitch(transition(WIFI, CELLULAR)); setNotificationSwitch(transition(WIFI, CELLULAR));
@@ -284,7 +269,6 @@ public class LingerMonitorTest extends TestCase {
verifyNoNotifications(); verifyNoNotifications();
} }
@SmallTest
public void testDifferentTransitionToNotify() { public void testDifferentTransitionToNotify() {
setNotificationType(LingerMonitor.NOTIFY_TYPE_TOAST); setNotificationType(LingerMonitor.NOTIFY_TYPE_TOAST);
setNotificationSwitch(transition(CELLULAR, WIFI)); setNotificationSwitch(transition(CELLULAR, WIFI));

View File

@@ -22,8 +22,6 @@ import android.net.Network;
import android.net.metrics.DnsEvent; import android.net.metrics.DnsEvent;
import android.net.metrics.INetdEventListener; import android.net.metrics.INetdEventListener;
import android.net.metrics.IpConnectivityLog; import android.net.metrics.IpConnectivityLog;
import android.os.RemoteException;
import android.test.suitebuilder.annotation.SmallTest;
import junit.framework.TestCase; import junit.framework.TestCase;
import org.junit.Before; import org.junit.Before;
@@ -84,7 +82,6 @@ public class NetdEventListenerServiceTest extends TestCase {
verify(mCm, times(1)).registerNetworkCallback(any(), mCallbackCaptor.capture()); verify(mCm, times(1)).registerNetworkCallback(any(), mCallbackCaptor.capture());
} }
@SmallTest
public void testOneBatch() throws Exception { public void testOneBatch() throws Exception {
log(105, LATENCIES); log(105, LATENCIES);
log(106, Arrays.copyOf(LATENCIES, BATCH_SIZE - 1)); // one lookup short of a batch event log(106, Arrays.copyOf(LATENCIES, BATCH_SIZE - 1)); // one lookup short of a batch event
@@ -99,7 +96,6 @@ public class NetdEventListenerServiceTest extends TestCase {
new DnsEvent(106, EVENT_TYPES, RETURN_CODES, LATENCIES)); new DnsEvent(106, EVENT_TYPES, RETURN_CODES, LATENCIES));
} }
@SmallTest
public void testSeveralBatches() throws Exception { public void testSeveralBatches() throws Exception {
log(105, LATENCIES); log(105, LATENCIES);
log(106, LATENCIES); log(106, LATENCIES);
@@ -113,7 +109,6 @@ public class NetdEventListenerServiceTest extends TestCase {
new DnsEvent(107, EVENT_TYPES, RETURN_CODES, LATENCIES)); new DnsEvent(107, EVENT_TYPES, RETURN_CODES, LATENCIES));
} }
@SmallTest
public void testBatchAndNetworkLost() throws Exception { public void testBatchAndNetworkLost() throws Exception {
byte[] eventTypes = Arrays.copyOf(EVENT_TYPES, 20); byte[] eventTypes = Arrays.copyOf(EVENT_TYPES, 20);
byte[] returnCodes = Arrays.copyOf(RETURN_CODES, 20); byte[] returnCodes = Arrays.copyOf(RETURN_CODES, 20);
@@ -130,7 +125,6 @@ public class NetdEventListenerServiceTest extends TestCase {
new DnsEvent(105, EVENT_TYPES, RETURN_CODES, LATENCIES)); new DnsEvent(105, EVENT_TYPES, RETURN_CODES, LATENCIES));
} }
@SmallTest
public void testConcurrentBatchesAndDumps() throws Exception { public void testConcurrentBatchesAndDumps() throws Exception {
final long stop = System.currentTimeMillis() + 100; final long stop = System.currentTimeMillis() + 100;
final PrintWriter pw = new PrintWriter(new FileOutputStream("/dev/null")); final PrintWriter pw = new PrintWriter(new FileOutputStream("/dev/null"));
@@ -152,7 +146,6 @@ public class NetdEventListenerServiceTest extends TestCase {
new DnsEvent(107, EVENT_TYPES, RETURN_CODES, LATENCIES)); new DnsEvent(107, EVENT_TYPES, RETURN_CODES, LATENCIES));
} }
@SmallTest
public void testConcurrentBatchesAndNetworkLoss() throws Exception { public void testConcurrentBatchesAndNetworkLoss() throws Exception {
logAsync(105, LATENCIES); logAsync(105, LATENCIES);
Thread.sleep(10L); Thread.sleep(10L);
@@ -164,13 +157,9 @@ public class NetdEventListenerServiceTest extends TestCase {
} }
void log(int netId, int[] latencies) { void log(int netId, int[] latencies) {
try { for (int l : latencies) {
for (int l : latencies) { mNetdEventListenerService.onDnsEvent(netId, EVENT_TYPE, RETURN_CODE, l, null, null, 0,
mNetdEventListenerService.onDnsEvent(netId, EVENT_TYPE, RETURN_CODE, l, null, null, 0);
0, 0);
}
} catch (RemoteException re) {
throw re.rethrowFromSystemServer();
} }
} }

View File

@@ -25,11 +25,9 @@ import static org.mockito.Mockito.*;
import android.annotation.UserIdInt; import android.annotation.UserIdInt;
import android.app.AppOpsManager; import android.app.AppOpsManager;
import android.app.NotificationManager;
import android.content.Context; import android.content.Context;
import android.content.pm.PackageManager; import android.content.pm.PackageManager;
import android.content.pm.UserInfo; import android.content.pm.UserInfo;
import android.net.NetworkInfo.DetailedState;
import android.net.UidRange; import android.net.UidRange;
import android.os.INetworkManagementService; import android.os.INetworkManagementService;
import android.os.Looper; import android.os.Looper;
@@ -45,8 +43,6 @@ import java.util.Arrays;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
import org.mockito.Mock; import org.mockito.Mock;
import org.mockito.MockitoAnnotations; import org.mockito.MockitoAnnotations;
@@ -92,18 +88,14 @@ public class VpnTest extends AndroidTestCase {
@Mock private PackageManager mPackageManager; @Mock private PackageManager mPackageManager;
@Mock private INetworkManagementService mNetService; @Mock private INetworkManagementService mNetService;
@Mock private AppOpsManager mAppOps; @Mock private AppOpsManager mAppOps;
@Mock private NotificationManager mNotificationManager;
@Override @Override
public void setUp() throws Exception { public void setUp() throws Exception {
MockitoAnnotations.initMocks(this); MockitoAnnotations.initMocks(this);
when(mContext.getPackageManager()).thenReturn(mPackageManager); when(mContext.getPackageManager()).thenReturn(mPackageManager);
setMockedPackages(mPackages); setMockedPackages(mPackages);
when(mContext.getPackageName()).thenReturn(Vpn.class.getPackage().getName());
when(mContext.getSystemService(eq(Context.USER_SERVICE))).thenReturn(mUserManager); when(mContext.getSystemService(eq(Context.USER_SERVICE))).thenReturn(mUserManager);
when(mContext.getSystemService(eq(Context.APP_OPS_SERVICE))).thenReturn(mAppOps); when(mContext.getSystemService(eq(Context.APP_OPS_SERVICE))).thenReturn(mAppOps);
when(mContext.getSystemService(eq(Context.NOTIFICATION_SERVICE)))
.thenReturn(mNotificationManager);
doNothing().when(mNetService).registerObserver(any()); doNothing().when(mNetService).registerObserver(any());
} }
@@ -111,7 +103,7 @@ public class VpnTest extends AndroidTestCase {
public void testRestrictedProfilesAreAddedToVpn() { public void testRestrictedProfilesAreAddedToVpn() {
setMockedUsers(primaryUser, secondaryUser, restrictedProfileA, restrictedProfileB); setMockedUsers(primaryUser, secondaryUser, restrictedProfileA, restrictedProfileB);
final Vpn vpn = spyVpn(primaryUser.id); final Vpn vpn = new MockVpn(primaryUser.id);
final Set<UidRange> ranges = vpn.createUserAndRestrictedProfilesRanges(primaryUser.id, final Set<UidRange> ranges = vpn.createUserAndRestrictedProfilesRanges(primaryUser.id,
null, null); null, null);
@@ -125,7 +117,7 @@ public class VpnTest extends AndroidTestCase {
public void testManagedProfilesAreNotAddedToVpn() { public void testManagedProfilesAreNotAddedToVpn() {
setMockedUsers(primaryUser, managedProfileA); setMockedUsers(primaryUser, managedProfileA);
final Vpn vpn = spyVpn(primaryUser.id); final Vpn vpn = new MockVpn(primaryUser.id);
final Set<UidRange> ranges = vpn.createUserAndRestrictedProfilesRanges(primaryUser.id, final Set<UidRange> ranges = vpn.createUserAndRestrictedProfilesRanges(primaryUser.id,
null, null); null, null);
@@ -138,7 +130,7 @@ public class VpnTest extends AndroidTestCase {
public void testAddUserToVpnOnlyAddsOneUser() { public void testAddUserToVpnOnlyAddsOneUser() {
setMockedUsers(primaryUser, restrictedProfileA, managedProfileA); setMockedUsers(primaryUser, restrictedProfileA, managedProfileA);
final Vpn vpn = spyVpn(primaryUser.id); final Vpn vpn = new MockVpn(primaryUser.id);
final Set<UidRange> ranges = new ArraySet<>(); final Set<UidRange> ranges = new ArraySet<>();
vpn.addUserToRanges(ranges, primaryUser.id, null, null); vpn.addUserToRanges(ranges, primaryUser.id, null, null);
@@ -149,7 +141,7 @@ public class VpnTest extends AndroidTestCase {
@SmallTest @SmallTest
public void testUidWhiteAndBlacklist() throws Exception { public void testUidWhiteAndBlacklist() throws Exception {
final Vpn vpn = spyVpn(primaryUser.id); final Vpn vpn = new MockVpn(primaryUser.id);
final UidRange user = UidRange.createForUser(primaryUser.id); final UidRange user = UidRange.createForUser(primaryUser.id);
final String[] packages = {PKGS[0], PKGS[1], PKGS[2]}; final String[] packages = {PKGS[0], PKGS[1], PKGS[2]};
@@ -174,15 +166,15 @@ public class VpnTest extends AndroidTestCase {
@SmallTest @SmallTest
public void testLockdownChangingPackage() throws Exception { public void testLockdownChangingPackage() throws Exception {
final Vpn vpn = spyVpn(primaryUser.id); final MockVpn vpn = new MockVpn(primaryUser.id);
final UidRange user = UidRange.createForUser(primaryUser.id); final UidRange user = UidRange.createForUser(primaryUser.id);
// Default state. // Default state.
assertUnblocked(vpn, user.start + PKG_UIDS[0], user.start + PKG_UIDS[1], user.start + PKG_UIDS[2], user.start + PKG_UIDS[3]); vpn.assertUnblocked(user.start + PKG_UIDS[0], user.start + PKG_UIDS[1], user.start + PKG_UIDS[2], user.start + PKG_UIDS[3]);
// Set always-on without lockdown. // Set always-on without lockdown.
assertTrue(vpn.setAlwaysOnPackage(PKGS[1], false)); assertTrue(vpn.setAlwaysOnPackage(PKGS[1], false));
assertUnblocked(vpn, user.start + PKG_UIDS[0], user.start + PKG_UIDS[1], user.start + PKG_UIDS[2], user.start + PKG_UIDS[3]); vpn.assertUnblocked(user.start + PKG_UIDS[0], user.start + PKG_UIDS[1], user.start + PKG_UIDS[2], user.start + PKG_UIDS[3]);
// Set always-on with lockdown. // Set always-on with lockdown.
assertTrue(vpn.setAlwaysOnPackage(PKGS[1], true)); assertTrue(vpn.setAlwaysOnPackage(PKGS[1], true));
@@ -190,8 +182,8 @@ public class VpnTest extends AndroidTestCase {
new UidRange(user.start, user.start + PKG_UIDS[1] - 1), new UidRange(user.start, user.start + PKG_UIDS[1] - 1),
new UidRange(user.start + PKG_UIDS[1] + 1, user.stop) new UidRange(user.start + PKG_UIDS[1] + 1, user.stop)
})); }));
assertBlocked(vpn, user.start + PKG_UIDS[0], user.start + PKG_UIDS[2], user.start + PKG_UIDS[3]); vpn.assertBlocked(user.start + PKG_UIDS[0], user.start + PKG_UIDS[2], user.start + PKG_UIDS[3]);
assertUnblocked(vpn, user.start + PKG_UIDS[1]); vpn.assertUnblocked(user.start + PKG_UIDS[1]);
// Switch to another app. // Switch to another app.
assertTrue(vpn.setAlwaysOnPackage(PKGS[3], true)); assertTrue(vpn.setAlwaysOnPackage(PKGS[3], true));
@@ -203,13 +195,13 @@ public class VpnTest extends AndroidTestCase {
new UidRange(user.start, user.start + PKG_UIDS[3] - 1), new UidRange(user.start, user.start + PKG_UIDS[3] - 1),
new UidRange(user.start + PKG_UIDS[3] + 1, user.stop) new UidRange(user.start + PKG_UIDS[3] + 1, user.stop)
})); }));
assertBlocked(vpn, user.start + PKG_UIDS[0], user.start + PKG_UIDS[1], user.start + PKG_UIDS[2]); vpn.assertBlocked(user.start + PKG_UIDS[0], user.start + PKG_UIDS[1], user.start + PKG_UIDS[2]);
assertUnblocked(vpn, user.start + PKG_UIDS[3]); vpn.assertUnblocked(user.start + PKG_UIDS[3]);
} }
@SmallTest @SmallTest
public void testLockdownAddingAProfile() throws Exception { public void testLockdownAddingAProfile() throws Exception {
final Vpn vpn = spyVpn(primaryUser.id); final MockVpn vpn = new MockVpn(primaryUser.id);
setMockedUsers(primaryUser); setMockedUsers(primaryUser);
// Make a copy of the restricted profile, as we're going to mark it deleted halfway through. // Make a copy of the restricted profile, as we're going to mark it deleted halfway through.
@@ -228,7 +220,7 @@ public class VpnTest extends AndroidTestCase {
})); }));
// Verify restricted user isn't affected at first. // Verify restricted user isn't affected at first.
assertUnblocked(vpn, profile.start + PKG_UIDS[0]); vpn.assertUnblocked(profile.start + PKG_UIDS[0]);
// Add the restricted user. // Add the restricted user.
setMockedUsers(primaryUser, tempProfile); setMockedUsers(primaryUser, tempProfile);
@@ -247,53 +239,24 @@ public class VpnTest extends AndroidTestCase {
})); }));
} }
@SmallTest
public void testNotificationShownForAlwaysOnApp() {
final Vpn vpn = spyVpn(primaryUser.id);
final InOrder order = inOrder(vpn);
setMockedUsers(primaryUser);
// Don't show a notification for regular disconnected states.
vpn.updateState(DetailedState.DISCONNECTED, TAG);
order.verify(vpn).updateAlwaysOnNotificationInternal(false);
// Start showing a notification for disconnected once always-on.
vpn.setAlwaysOnPackage(PKGS[0], false);
order.verify(vpn).updateAlwaysOnNotificationInternal(true);
// Stop showing the notification once connected.
vpn.updateState(DetailedState.CONNECTED, TAG);
order.verify(vpn).updateAlwaysOnNotificationInternal(false);
// Show the notification if we disconnect again.
vpn.updateState(DetailedState.DISCONNECTED, TAG);
order.verify(vpn).updateAlwaysOnNotificationInternal(true);
// Notification should be cleared after unsetting always-on package.
vpn.setAlwaysOnPackage(null, false);
order.verify(vpn).updateAlwaysOnNotificationInternal(false);
}
/** /**
* Mock some methods of vpn object. * A subclass of {@link Vpn} with some of the fields pre-mocked.
*/ */
private Vpn spyVpn(@UserIdInt int userId) { private class MockVpn extends Vpn {
final Vpn vpn = spy(new Vpn(Looper.myLooper(), mContext, mNetService, userId)); public MockVpn(@UserIdInt int userId) {
super(Looper.myLooper(), mContext, mNetService, userId);
// Block calls to the NotificationManager or PendingIntent#getActivity.
doNothing().when(vpn).updateAlwaysOnNotificationInternal(anyBoolean());
return vpn;
}
private static void assertBlocked(Vpn vpn, int... uids) {
for (int uid : uids) {
assertTrue("Uid " + uid + " should be blocked", vpn.isBlockingUid(uid));
} }
}
private static void assertUnblocked(Vpn vpn, int... uids) { public void assertBlocked(int... uids) {
for (int uid : uids) { for (int uid : uids) {
assertFalse("Uid " + uid + " should not be blocked", vpn.isBlockingUid(uid)); assertTrue("Uid " + uid + " should be blocked", isBlockingUid(uid));
}
}
public void assertUnblocked(int... uids) {
for (int uid : uids) {
assertFalse("Uid " + uid + " should not be blocked", isBlockingUid(uid));
}
} }
} }