Asserts foreground apps always have network access.

BUG: 28473659
Change-Id: Iea6933a4630ff2e9c00a2d2e9e4a6f1a51de70f2
This commit is contained in:
Felipe Leme
2016-04-29 16:48:14 -07:00
parent aa2e8ea1d8
commit 6cd41f6d03
9 changed files with 188 additions and 71 deletions

View File

@@ -54,6 +54,8 @@ abstract class AbstractRestrictBackgroundNetworkTestCase extends Instrumentation
private static final String DYNAMIC_RECEIVER = "DynamicReceiver";
private static final String ACTION_GET_COUNTERS =
"com.android.cts.net.hostside.app2.action.GET_COUNTERS";
private static final String ACTION_GET_RESTRICT_BACKGROUND_STATUS =
"com.android.cts.net.hostside.app2.action.GET_RESTRICT_BACKGROUND_STATUS";
private static final String ACTION_CHECK_NETWORK =
"com.android.cts.net.hostside.app2.action.CHECK_NETWORK";
private static final String ACTION_RECEIVER_READY =
@@ -61,7 +63,6 @@ abstract class AbstractRestrictBackgroundNetworkTestCase extends Instrumentation
private static final String EXTRA_ACTION = "com.android.cts.net.hostside.app2.extra.ACTION";
private static final String EXTRA_RECEIVER_NAME =
"com.android.cts.net.hostside.app2.extra.RECEIVER_NAME";
private static final String RESULT_SEPARATOR = ";";
private static final String NETWORK_STATUS_SEPARATOR = "\\|";
private static final int SECOND_IN_MS = 1000;
private static final int NETWORK_TIMEOUT_MS = 15 * SECOND_IN_MS;
@@ -71,8 +72,6 @@ abstract class AbstractRestrictBackgroundNetworkTestCase extends Instrumentation
// Must be higher than NETWORK_TIMEOUT_MS
private static final int ORDERED_BROADCAST_TIMEOUT_MS = NETWORK_TIMEOUT_MS * 4;
private static final boolean ASSERT_NETWORK_INFO_STATE = false;
protected Context mContext;
protected Instrumentation mInstrumentation;
protected ConnectivityManager mCm;
@@ -159,27 +158,22 @@ abstract class AbstractRestrictBackgroundNetworkTestCase extends Instrumentation
return Integer.valueOf(resultData);
}
protected void assertRestrictBackgroundStatus(int expectedApiStatus) throws Exception {
assertBackgroundState(); // Sanity check.
final Intent intent = new Intent(ACTION_CHECK_NETWORK);
protected void assertRestrictBackgroundStatus(int expectedStatus) throws Exception {
final Intent intent = new Intent(ACTION_GET_RESTRICT_BACKGROUND_STATUS);
final String resultData = sendOrderedBroadcast(intent);
final String[] resultItems = resultData.split(RESULT_SEPARATOR);
final String actualApiStatus = toString(Integer.parseInt(resultItems[0]));
// First asserts the API returns the proper value...
assertEquals("wrong status", toString(expectedApiStatus), actualApiStatus);
//...then the actual network status in the background thread.
final String networkStatus = getNetworkStatus(resultItems);
assertNetworkStatus(expectedApiStatus != RESTRICT_BACKGROUND_STATUS_ENABLED, networkStatus);
assertNotNull("timeout waiting for ordered broadcast result", resultData);
final String actualStatus = toString(Integer.parseInt(resultData));
assertEquals("wrong status", toString(expectedStatus), actualStatus);
}
protected void assertBackgroundNetworkAccess(boolean expectAllowed) throws Exception {
assertBackgroundState(); // Sanity check.
final Intent intent = new Intent(ACTION_CHECK_NETWORK);
final String resultData = sendOrderedBroadcast(intent);
final String[] resultItems = resultData.split(RESULT_SEPARATOR);
final String networkStatus = getNetworkStatus(resultItems);
assertNetworkStatus(expectAllowed, networkStatus);
assertNetworkAccess(expectAllowed);
}
protected void assertForegroundNetworkAccess() throws Exception {
assertForegroundState(); // Sanity check.
assertNetworkAccess(true);
}
protected final void assertBackgroundState() throws Exception {
@@ -189,6 +183,13 @@ abstract class AbstractRestrictBackgroundNetworkTestCase extends Instrumentation
assertTrue("App2 is not on background state: " + state, isBackground);
}
protected final void assertForegroundState() throws Exception {
final ProcessState state = getProcessStateByUid(mUid);
Log.v(TAG, "assertForegroundState(): status for app2 (" + mUid + "): " + state);
final boolean isForeground = !isBackground(state.state);
assertTrue("App2 is not on foreground state: " + state, isForeground);
}
protected final void assertForegroundServiceState() throws Exception {
final ProcessState state = getProcessStateByUid(mUid);
Log.v(TAG, "assertForegroundServiceState(): status for app2 (" + mUid + "): " + state);
@@ -203,39 +204,54 @@ abstract class AbstractRestrictBackgroundNetworkTestCase extends Instrumentation
return state >= PROCESS_STATE_FOREGROUND_SERVICE;
}
private String getNetworkStatus(String[] resultItems) {
return resultItems.length < 2 ? null : resultItems[1];
}
private void assertNetworkAccess(boolean expectAvailable) throws Exception {
final Intent intent = new Intent(ACTION_CHECK_NETWORK);
private void assertNetworkStatus(boolean expectAvailable, String status) throws Exception {
assertNotNull("timeout waiting for ordered broadcast", status);
// When the network info state change, it's possible the app still get the previous value,
// so we need to retry a couple times.
final int maxTries = 5;
String resultData = null;
for (int i = 1; i <= maxTries; i++) {
resultData = sendOrderedBroadcast(intent);
assertNotNull("timeout waiting for ordered broadcast", resultData);
// Network status format is described on MyBroadcastReceiver.checkNetworkStatus()
final String[] parts = status.split(NETWORK_STATUS_SEPARATOR);
assertEquals("Wrong network status: " + status, 5, parts.length); // Sanity check
final State state = State.valueOf(parts[0]);
final DetailedState detailedState = DetailedState.valueOf(parts[1]);
final boolean connected = Boolean.valueOf(parts[2]);
final String connectionCheckDetails = parts[3];
final String networkInfo = parts[4];
// Network status format is described on MyBroadcastReceiver.checkNetworkStatus()
final String[] parts = resultData.split(NETWORK_STATUS_SEPARATOR);
assertEquals("Wrong network status: " + resultData, 5, parts.length); // Sanity check
final State state = State.valueOf(parts[0]);
final DetailedState detailedState = DetailedState.valueOf(parts[1]);
final boolean connected = Boolean.valueOf(parts[2]);
final String connectionCheckDetails = parts[3];
final String networkInfo = parts[4];
if (expectAvailable) {
assertTrue("should be connected: " + connectionCheckDetails
+ " (network info: " + networkInfo + ")", connected);
if (ASSERT_NETWORK_INFO_STATE) {
assertEquals("wrong state for " + networkInfo, State.CONNECTED, state);
assertEquals("wrong detailed state for " + networkInfo,
DetailedState.CONNECTED, detailedState);
}
} else {
assertFalse("should not be connected: " + connectionCheckDetails
+ " (network info: " + networkInfo + ")", connected);
if (ASSERT_NETWORK_INFO_STATE) {
assertEquals("wrong state for " + networkInfo, State.DISCONNECTED, state);
assertEquals("wrong detailed state for " + networkInfo,
DetailedState.BLOCKED, detailedState);
if (expectAvailable) {
assertTrue("should be connected: " + connectionCheckDetails
+ " (network info: " + networkInfo + ")", connected);
if (state != State.CONNECTED) {
Log.d(TAG, "State (" + state + ") not set to CONNECTED on attempt #" + i
+ "; sleeping 1s before trying again");
Thread.sleep(SECOND_IN_MS);
} else {
assertEquals("wrong detailed state for " + networkInfo,
DetailedState.CONNECTED, detailedState);
return;
}
return;
} else {
assertFalse("should not be connected: " + connectionCheckDetails
+ " (network info: " + networkInfo + ")", connected);
if (state != State.DISCONNECTED) {
Log.d(TAG, "State (" + state + ") not set to DISCONNECTED on attempt #" + i
+ "; sleeping 1s before trying again");
Thread.sleep(SECOND_IN_MS);
} else {
assertEquals("wrong detailed state for " + networkInfo,
DetailedState.BLOCKED, detailedState);
return;
}
}
}
fail("Invalid state after " + maxTries + " attempts. Last data: " + resultData);
}
protected String executeShellCommand(String command) throws Exception {
@@ -479,6 +495,13 @@ abstract class AbstractRestrictBackgroundNetworkTestCase extends Instrumentation
"am startservice com.android.cts.net.hostside.app2/.MyForegroundService");
}
/**
* Launches an activity on app2 so its process is elevated to foreground status.
*/
protected void launchApp2Activity() throws Exception {
executeShellCommand("am start com.android.cts.net.hostside.app2/.MyActivity");
}
private String toString(int status) {
switch (status) {
case RESTRICT_BACKGROUND_STATUS_DISABLED:

View File

@@ -38,10 +38,15 @@ public class BatterySaverModeNonMeteredTest extends AbstractRestrictBackgroundNe
public void testBackgroundNetworkAccess_enabled() throws Exception {
setPowerSaveMode(true);
assertBackgroundNetworkAccess(false);
// Make sure app is allowed if running a foreground service.
startForegroundService();
assertForegroundServiceState();
assertBackgroundNetworkAccess(true);
// Should always have access when running on foreground
launchApp2Activity();
assertForegroundNetworkAccess();
}
public void testBackgroundNetworkAccess_whitelisted() throws Exception {
@@ -51,10 +56,18 @@ public class BatterySaverModeNonMeteredTest extends AbstractRestrictBackgroundNe
assertBackgroundNetworkAccess(true);
removePowerSaveModeWhitelist(TEST_APP2_PKG);
assertBackgroundNetworkAccess(false);
// Should always have access when running on foreground
launchApp2Activity();
assertForegroundNetworkAccess();
}
public void testBackgroundNetworkAccess_disabled() throws Exception {
setPowerSaveMode(false);
assertBackgroundNetworkAccess(true);
// Should always have access when running on foreground
launchApp2Activity();
assertForegroundNetworkAccess();
}
}

View File

@@ -49,6 +49,10 @@ public class BatterySaverModeTest extends AbstractRestrictBackgroundNetworkTestC
startForegroundService();
assertForegroundServiceState();
assertBackgroundNetworkAccess(true);
// Should always have access when running on foreground
launchApp2Activity();
assertForegroundNetworkAccess();
}
public void testBackgroundNetworkAccess_whitelisted() throws Exception {
@@ -58,10 +62,18 @@ public class BatterySaverModeTest extends AbstractRestrictBackgroundNetworkTestC
assertBackgroundNetworkAccess(true);
removePowerSaveModeWhitelist(TEST_APP2_PKG);
assertBackgroundNetworkAccess(false);
// Should always have access when running on foreground
launchApp2Activity();
assertForegroundNetworkAccess();
}
public void testBackgroundNetworkAccess_disabled() throws Exception {
setPowerSaveMode(false);
assertBackgroundNetworkAccess(true);
// Should always have access when running on foreground
launchApp2Activity();
assertForegroundNetworkAccess();
}
}

View File

@@ -58,12 +58,16 @@ public class DataSaverModeTest extends AbstractRestrictBackgroundNetworkTestCase
public void testGetRestrictBackgroundStatus_disabled() throws Exception {
removeRestrictBackgroundWhitelist(mUid);
assertRestrictBackgroundChangedReceived(0);
assertRestrictBackgroundStatus(RESTRICT_BACKGROUND_STATUS_DISABLED);
assertDataSaverStatusOnBackground(RESTRICT_BACKGROUND_STATUS_DISABLED);
// Sanity check: make sure status is always disabled, never whitelisted
addRestrictBackgroundWhitelist(mUid);
assertRestrictBackgroundChangedReceived(0);
assertRestrictBackgroundStatus(RESTRICT_BACKGROUND_STATUS_DISABLED);
assertDataSaverStatusOnBackground(RESTRICT_BACKGROUND_STATUS_DISABLED);
// Should always have access when running on foreground
launchApp2Activity();
assertForegroundNetworkAccess();
}
public void testGetRestrictBackgroundStatus_whitelisted() throws Exception {
@@ -72,49 +76,64 @@ public class DataSaverModeTest extends AbstractRestrictBackgroundNetworkTestCase
addRestrictBackgroundWhitelist(mUid);
assertRestrictBackgroundChangedReceived(2);
assertRestrictBackgroundStatus(RESTRICT_BACKGROUND_STATUS_WHITELISTED);
assertDataSaverStatusOnBackground(RESTRICT_BACKGROUND_STATUS_WHITELISTED);
removeRestrictBackgroundWhitelist(mUid);
assertRestrictBackgroundChangedReceived(3);
assertRestrictBackgroundStatus(RESTRICT_BACKGROUND_STATUS_ENABLED);
}
// Should always have access when running on foreground
launchApp2Activity();
assertForegroundNetworkAccess();
}
public void testGetRestrictBackgroundStatus_enabled() throws Exception {
setRestrictBackground(true);
assertRestrictBackgroundChangedReceived(1);
assertRestrictBackgroundStatus(RESTRICT_BACKGROUND_STATUS_ENABLED);
assertDataSaverStatusOnBackground(RESTRICT_BACKGROUND_STATUS_ENABLED);
removeRestrictBackgroundWhitelist(mUid);
assertRestrictBackgroundChangedReceived(1);
assertRestrictBackgroundStatus(RESTRICT_BACKGROUND_STATUS_ENABLED);
assertDataSaverStatusOnBackground(RESTRICT_BACKGROUND_STATUS_ENABLED);
// Make sure app is allowed if running a foreground service.
assertBackgroundNetworkAccess(false);
startForegroundService();
assertForegroundServiceState();
assertBackgroundNetworkAccess(true);
// Should always have access when running on foreground
launchApp2Activity();
assertForegroundNetworkAccess();
}
public void testGetRestrictBackgroundStatus_blacklisted() throws Exception {
addRestrictBackgroundBlacklist(mUid);
assertRestrictBackgroundChangedReceived(1);
assertRestrictBackgroundStatus(RESTRICT_BACKGROUND_STATUS_ENABLED);
assertDataSaverStatusOnBackground(RESTRICT_BACKGROUND_STATUS_ENABLED);
// Make sure blacklist prevails over whitelist.
setRestrictBackground(true);
assertRestrictBackgroundChangedReceived(2);
assertRestrictBackgroundStatus(RESTRICT_BACKGROUND_STATUS_ENABLED);
assertDataSaverStatusOnBackground(RESTRICT_BACKGROUND_STATUS_ENABLED);
addRestrictBackgroundWhitelist(mUid);
assertRestrictBackgroundChangedReceived(3);
assertRestrictBackgroundStatus(RESTRICT_BACKGROUND_STATUS_ENABLED);
assertDataSaverStatusOnBackground(RESTRICT_BACKGROUND_STATUS_ENABLED);
// Check status after removing blacklist.
removeRestrictBackgroundBlacklist(mUid);
assertRestrictBackgroundChangedReceived(4);
assertRestrictBackgroundStatus(RESTRICT_BACKGROUND_STATUS_WHITELISTED);
assertDataSaverStatusOnBackground(RESTRICT_BACKGROUND_STATUS_WHITELISTED);
setRestrictBackground(false);
assertRestrictBackgroundChangedReceived(5);
assertRestrictBackgroundStatus(RESTRICT_BACKGROUND_STATUS_DISABLED);
assertDataSaverStatusOnBackground(RESTRICT_BACKGROUND_STATUS_DISABLED);
// Should always have access when running on foreground
addRestrictBackgroundBlacklist(mUid);
assertRestrictBackgroundChangedReceived(6);
assertDataSaverStatusOnBackground(RESTRICT_BACKGROUND_STATUS_ENABLED);
launchApp2Activity();
assertForegroundNetworkAccess();
}
public void testGetRestrictBackgroundStatus_requiredWhitelistedPackages() throws Exception {
@@ -136,4 +155,9 @@ public class DataSaverModeTest extends AbstractRestrictBackgroundNetworkTestCase
fail(error.toString());
}
}
private void assertDataSaverStatusOnBackground(int expectedStatus) throws Exception {
assertRestrictBackgroundStatus(expectedStatus);
assertBackgroundNetworkAccess(expectedStatus != RESTRICT_BACKGROUND_STATUS_ENABLED);
}
}

View File

@@ -31,6 +31,7 @@
test app.
-->
<application>
<activity android:name=".MyActivity" android:exported="true"/>
<service android:name=".MyService" android:exported="true"/>
<service android:name=".MyForegroundService" android:exported="true"/>
@@ -38,6 +39,7 @@
<intent-filter>
<action android:name="android.net.conn.RESTRICT_BACKGROUND_CHANGED" />
<action android:name="com.android.cts.net.hostside.app2.action.GET_COUNTERS" />
<action android:name="com.android.cts.net.hostside.app2.action.GET_RESTRICT_BACKGROUND_STATUS" />
<action android:name="com.android.cts.net.hostside.app2.action.CHECK_NETWORK" />
</intent-filter>
</receiver>

View File

@@ -28,6 +28,8 @@ public final class Common {
static final String DYNAMIC_RECEIVER = "DynamicReceiver";
static final String ACTION_GET_COUNTERS =
"com.android.cts.net.hostside.app2.action.GET_COUNTERS";
static final String ACTION_GET_RESTRICT_BACKGROUND_STATUS =
"com.android.cts.net.hostside.app2.action.GET_RESTRICT_BACKGROUND_STATUS";
static final String ACTION_CHECK_NETWORK =
"com.android.cts.net.hostside.app2.action.CHECK_NETWORK";
static final String ACTION_RECEIVER_READY =

View File

@@ -0,0 +1,38 @@
/*
* Copyright (C) 2016 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.cts.net.hostside.app2;
import static com.android.cts.net.hostside.app2.Common.TAG;
import android.app.Activity;
import android.util.Log;
/**
* Activity used to bring process to foreground.
*/
public class MyActivity extends Activity {
@Override
protected void onStart() {
super.onStart();
Log.d(TAG, "MyActivity.onStart()");
}
@Override
protected void onDestroy() {
Log.d(TAG, "MyActivity.onDestroy()");
super.onDestroy();
}
}

View File

@@ -19,6 +19,7 @@ package com.android.cts.net.hostside.app2;
import static android.net.ConnectivityManager.ACTION_RESTRICT_BACKGROUND_CHANGED;
import static com.android.cts.net.hostside.app2.Common.ACTION_CHECK_NETWORK;
import static com.android.cts.net.hostside.app2.Common.ACTION_GET_COUNTERS;
import static com.android.cts.net.hostside.app2.Common.ACTION_GET_RESTRICT_BACKGROUND_STATUS;
import static com.android.cts.net.hostside.app2.Common.ACTION_RECEIVER_READY;
import static com.android.cts.net.hostside.app2.Common.EXTRA_ACTION;
import static com.android.cts.net.hostside.app2.Common.EXTRA_RECEIVER_NAME;
@@ -73,6 +74,9 @@ public class MyBroadcastReceiver extends BroadcastReceiver {
case ACTION_GET_COUNTERS:
setResultDataFromCounter(context, intent);
break;
case ACTION_GET_RESTRICT_BACKGROUND_STATUS:
getRestrictBackgroundStatus(context, intent);
break;
case ACTION_CHECK_NETWORK:
checkNetwork(context, intent);
break;
@@ -101,31 +105,30 @@ public class MyBroadcastReceiver extends BroadcastReceiver {
return value;
}
private void getRestrictBackgroundStatus(Context context, Intent intent) {
final ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
final int apiStatus = cm.getRestrictBackgroundStatus();
Log.d(TAG, "getRestrictBackgroundStatus: returning " + apiStatus);
setResultData(Integer.toString(apiStatus));
}
private void checkNetwork(final Context context, Intent intent) {
final ConnectivityManager cm = (ConnectivityManager) context
.getSystemService(Context.CONNECTIVITY_SERVICE);
final StringBuilder data = new StringBuilder();
final int apiStatus = cm.getRestrictBackgroundStatus();
String netStatus;
String netStatus = null;
try {
netStatus = checkNetworkStatus(context, cm);
} catch (InterruptedException e) {
Log.e(TAG, "Timeout checking network status");
setResultData(null);
return;
}
data.append(apiStatus).append(RESULT_SEPARATOR);
if (netStatus != null) {
data.append(netStatus);
}
Log.d(TAG, "checkNetwork: returning " + data);
setResultData(data.toString());
Log.d(TAG, "checkNetwork(): returning " + netStatus);
setResultData(netStatus);
}
private static final String NETWORK_STATUS_TEMPLATE = "%s|%s|%s|%s|%s";
/**
* Checks whether the network is available and return a string which can then be send as a
* result data for the ordered broadcast.

View File

@@ -111,7 +111,7 @@ public class HostsideRestrictBackgroundNetworkTests extends HostsideNetworkTestC
"testBackgroundNetworkAccess_disabled");
}
public void testBatterySaverModeNonMeteredt_whitelisted() throws Exception {
public void testBatterySaverModeNonMetered_whitelisted() throws Exception {
runDeviceTests(TEST_PKG, TEST_PKG + ".BatterySaverModeNonMeteredTest",
"testBackgroundNetworkAccess_whitelisted");
}