Merge "DO NOT MERGE: Merge Oreo MR1 into master"

This commit is contained in:
Xin Li
2017-12-06 23:18:30 +00:00
committed by Gerrit Code Review
12 changed files with 185 additions and 36 deletions

View File

@@ -26,7 +26,7 @@ LOCAL_JAVA_LIBRARIES := cts-tradefed tradefed
LOCAL_CTS_TEST_PACKAGE := android.net.hostsidenetwork LOCAL_CTS_TEST_PACKAGE := android.net.hostsidenetwork
# Tag this module as a cts test artifact # Tag this module as a cts test artifact
LOCAL_COMPATIBILITY_SUITE := cts general-tests LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
include $(BUILD_CTS_HOST_JAVA_LIBRARY) include $(BUILD_CTS_HOST_JAVA_LIBRARY)

View File

@@ -15,6 +15,7 @@
--> -->
<configuration description="Config for CTS net host test cases"> <configuration description="Config for CTS net host test cases">
<option name="config-descriptor:metadata" key="component" value="networking" /> <option name="config-descriptor:metadata" key="component" value="networking" />
<target_preparer class="com.android.cts.net.NetPolicyTestsPreparer" />
<test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" > <test class="com.android.compatibility.common.tradefed.testtype.JarHostTest" >
<option name="jar" value="CtsHostsideNetworkTests.jar" /> <option name="jar" value="CtsHostsideNetworkTests.jar" />
<option name="runtime-hint" value="3m56s" /> <option name="runtime-hint" value="3m56s" />

View File

@@ -31,6 +31,6 @@ LOCAL_PROGUARD_ENABLED := disabled
LOCAL_DEX_PREOPT := false LOCAL_DEX_PREOPT := false
# Tag this module as a cts test artifact # Tag this module as a cts test artifact
LOCAL_COMPATIBILITY_SUITE := cts general-tests LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
include $(BUILD_CTS_SUPPORT_PACKAGE) include $(BUILD_CTS_SUPPORT_PACKAGE)

View File

@@ -21,6 +21,8 @@
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/> <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/> <uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name="android.permission.INTERNET"/> <uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" />
<application> <application>
<uses-library android:name="android.test.runner" /> <uses-library android:name="android.test.runner" />

View File

@@ -27,12 +27,12 @@ import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import android.app.Instrumentation; import android.app.Instrumentation;
import android.app.NotificationManager;
import android.content.BroadcastReceiver; import android.content.BroadcastReceiver;
import android.content.ComponentName; import android.content.ComponentName;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.IntentFilter; import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager; import android.net.ConnectivityManager;
import android.net.NetworkInfo; import android.net.NetworkInfo;
import android.net.NetworkInfo.DetailedState; import android.net.NetworkInfo.DetailedState;
@@ -42,6 +42,7 @@ import android.os.BatteryManager;
import android.os.Binder; import android.os.Binder;
import android.os.Bundle; import android.os.Bundle;
import android.os.SystemClock; import android.os.SystemClock;
import android.provider.Settings;
import android.service.notification.NotificationListenerService; import android.service.notification.NotificationListenerService;
import android.test.InstrumentationTestCase; import android.test.InstrumentationTestCase;
import android.text.TextUtils; import android.text.TextUtils;
@@ -116,6 +117,7 @@ abstract class AbstractRestrictBackgroundNetworkTestCase extends Instrumentation
private MyServiceClient mServiceClient; private MyServiceClient mServiceClient;
private String mDeviceIdleConstantsSetting; private String mDeviceIdleConstantsSetting;
private boolean mSupported; private boolean mSupported;
private boolean mIsLocationOn;
@Override @Override
protected void setUp() throws Exception { protected void setUp() throws Exception {
@@ -130,20 +132,49 @@ abstract class AbstractRestrictBackgroundNetworkTestCase extends Instrumentation
mServiceClient = new MyServiceClient(mContext); mServiceClient = new MyServiceClient(mContext);
mServiceClient.bind(); mServiceClient.bind();
mDeviceIdleConstantsSetting = "device_idle_constants"; mDeviceIdleConstantsSetting = "device_idle_constants";
mIsLocationOn = isLocationOn();
if (!mIsLocationOn) {
enableLocation();
}
mSupported = setUpActiveNetworkMeteringState(); mSupported = setUpActiveNetworkMeteringState();
Log.i(TAG, "Apps status on " + getName() + ":\n" Log.i(TAG, "Apps status on " + getName() + ":\n"
+ "\ttest app: uid=" + mMyUid + ", state=" + getProcessStateByUid(mMyUid) + "\n" + "\ttest app: uid=" + mMyUid + ", state=" + getProcessStateByUid(mMyUid) + "\n"
+ "\tapp2: uid=" + mUid + ", state=" + getProcessStateByUid(mUid)); + "\tapp2: uid=" + mUid + ", state=" + getProcessStateByUid(mUid));
executeShellCommand("settings get global app_idle_constants");
} }
@Override @Override
protected void tearDown() throws Exception { protected void tearDown() throws Exception {
if (!mIsLocationOn) {
disableLocation();
}
mServiceClient.unbind(); mServiceClient.unbind();
super.tearDown(); super.tearDown();
} }
private void enableLocation() throws Exception {
Settings.Secure.putInt(mContext.getContentResolver(), Settings.Secure.LOCATION_MODE,
Settings.Secure.LOCATION_MODE_SENSORS_ONLY);
assertEquals(Settings.Secure.LOCATION_MODE_SENSORS_ONLY,
Settings.Secure.getInt(mContext.getContentResolver(),
Settings.Secure.LOCATION_MODE));
}
private void disableLocation() throws Exception {
Settings.Secure.putInt(mContext.getContentResolver(), Settings.Secure.LOCATION_MODE,
Settings.Secure.LOCATION_MODE_OFF);
assertEquals(Settings.Secure.LOCATION_MODE_OFF,
Settings.Secure.getInt(mContext.getContentResolver(),
Settings.Secure.LOCATION_MODE));
}
private boolean isLocationOn() throws Exception {
return Settings.Secure.getInt(mContext.getContentResolver(),
Settings.Secure.LOCATION_MODE) != Settings.Secure.LOCATION_MODE_OFF;
}
protected int getUid(String packageName) throws Exception { protected int getUid(String packageName) throws Exception {
return mContext.getPackageManager().getPackageUid(packageName, 0); return mContext.getPackageManager().getPackageUid(packageName, 0);
} }
@@ -353,14 +384,47 @@ abstract class AbstractRestrictBackgroundNetworkTestCase extends Instrumentation
Log.w(TAG, "Network status didn't match for expectAvailable=" + expectAvailable Log.w(TAG, "Network status didn't match for expectAvailable=" + expectAvailable
+ " on attempt #" + i + ": " + error + "\n" + " on attempt #" + i + ": " + error + "\n"
+ "Sleeping " + timeoutMs + "ms before trying again"); + "Sleeping " + timeoutMs + "ms before trying again");
SystemClock.sleep(timeoutMs); // No sleep after the last turn
if (i < maxTries) {
SystemClock.sleep(timeoutMs);
}
// Exponential back-off. // Exponential back-off.
timeoutMs = Math.min(timeoutMs*2, NETWORK_TIMEOUT_MS); timeoutMs = Math.min(timeoutMs*2, NETWORK_TIMEOUT_MS);
} }
dumpOnFailure();
fail("Invalid state for expectAvailable=" + expectAvailable + " after " + maxTries fail("Invalid state for expectAvailable=" + expectAvailable + " after " + maxTries
+ " attempts.\nLast error: " + error); + " attempts.\nLast error: " + error);
} }
private void dumpOnFailure() throws Exception {
dumpAllNetworkRules();
Log.d(TAG, "Usagestats dump: " + getUsageStatsDump());
executeShellCommand("settings get global app_idle_constants");
}
private void dumpAllNetworkRules() throws Exception {
final String networkManagementDump = runShellCommand(mInstrumentation,
"dumpsys network_management").trim();
final String networkPolicyDump = runShellCommand(mInstrumentation,
"dumpsys netpolicy").trim();
TextUtils.SimpleStringSplitter splitter = new TextUtils.SimpleStringSplitter('\n');
splitter.setString(networkManagementDump);
String next;
Log.d(TAG, ">>> Begin network_management dump");
while (splitter.hasNext()) {
next = splitter.next();
Log.d(TAG, next);
}
Log.d(TAG, "<<< End network_management dump");
splitter.setString(networkPolicyDump);
Log.d(TAG, ">>> Begin netpolicy dump");
while (splitter.hasNext()) {
next = splitter.next();
Log.d(TAG, next);
}
Log.d(TAG, "<<< End netpolicy dump");
}
/** /**
* Checks whether the network is available as expected. * Checks whether the network is available as expected.
* *
@@ -558,11 +622,15 @@ abstract class AbstractRestrictBackgroundNetworkTestCase extends Instrumentation
NetworkInfo info = null; NetworkInfo info = null;
for (int i = 1; i <= maxTries; i++) { for (int i = 1; i <= maxTries; i++) {
info = mCm.getActiveNetworkInfo(); info = mCm.getActiveNetworkInfo();
if (info != null) { if (info == null) {
Log.v(TAG, "No active network info on attempt #" + i
+ "; sleeping 1s before polling again");
} else if (mCm.isActiveNetworkMetered() != expected) {
Log.v(TAG, "Wrong metered status for active network " + info + "; expected="
+ expected + "; sleeping 1s before polling again");
} else {
break; break;
} }
Log.v(TAG, "No active network info on attempt #" + i
+ "; sleeping 1s before polling again");
Thread.sleep(SECOND_IN_MS); Thread.sleep(SECOND_IN_MS);
} }
assertNotNull("No active network after " + maxTries + " attempts", info); assertNotNull("No active network after " + maxTries + " attempts", info);
@@ -801,16 +869,8 @@ abstract class AbstractRestrictBackgroundNetworkTestCase extends Instrumentation
protected void setAppIdle(boolean enabled) throws Exception { protected void setAppIdle(boolean enabled) throws Exception {
Log.i(TAG, "Setting app idle to " + enabled); Log.i(TAG, "Setting app idle to " + enabled);
final String beforeStats = getUsageStatsDump();
executeSilentShellCommand("am set-inactive " + TEST_APP2_PKG + " " + enabled ); executeSilentShellCommand("am set-inactive " + TEST_APP2_PKG + " " + enabled );
try { assertAppIdle(enabled); // Sanity check
assertAppIdle(enabled); // Sanity check
} catch (Throwable e) {
final String afterStats = getUsageStatsDump();
Log.d(TAG, "UsageStats before:\n" + beforeStats);
Log.d(TAG, "UsageStats after:\n" + afterStats);
throw e;
}
} }
private String getUsageStatsDump() throws Exception { private String getUsageStatsDump() throws Exception {
@@ -825,7 +885,7 @@ abstract class AbstractRestrictBackgroundNetworkTestCase extends Instrumentation
&& !str.contains(TEST_PKG) && !str.contains(TEST_APP2_PKG)) { && !str.contains(TEST_PKG) && !str.contains(TEST_APP2_PKG)) {
continue; continue;
} }
if (str.contains("config=")) { if (str.trim().startsWith("config=") || str.trim().startsWith("time=")) {
continue; continue;
} }
sb.append(str).append('\n'); sb.append(str).append('\n');
@@ -834,7 +894,13 @@ abstract class AbstractRestrictBackgroundNetworkTestCase extends Instrumentation
} }
protected void assertAppIdle(boolean enabled) throws Exception { protected void assertAppIdle(boolean enabled) throws Exception {
assertDelayedShellCommand("am get-inactive " + TEST_APP2_PKG, 15, 2, "Idle=" + enabled); try {
assertDelayedShellCommand("am get-inactive " + TEST_APP2_PKG, 15, 2, "Idle=" + enabled);
} catch (Throwable e) {
Log.d(TAG, "UsageStats dump:\n" + getUsageStatsDump());
executeShellCommand("settings get global app_idle_constants");
throw e;
}
} }
/** /**
@@ -868,19 +934,12 @@ abstract class AbstractRestrictBackgroundNetworkTestCase extends Instrumentation
* notification actions right after the notification is sent. * notification actions right after the notification is sent.
*/ */
protected void registerNotificationListenerService() throws Exception { protected void registerNotificationListenerService() throws Exception {
final StringBuilder listeners = new StringBuilder(getNotificationListenerServices()); executeShellCommand("cmd notification allow_listener "
if (listeners.length() > 0) { + MyNotificationListenerService.getId());
listeners.append(":"); final NotificationManager nm = mContext.getSystemService(NotificationManager.class);
} final ComponentName listenerComponent = MyNotificationListenerService.getComponentName();
listeners.append(MyNotificationListenerService.getId()); assertTrue(listenerComponent + " has not been granted access",
executeShellCommand("settings put secure enabled_notification_listeners " + listeners); nm.isNotificationListenerAccessGranted(listenerComponent));
final String newListeners = getNotificationListenerServices();
assertEquals("Failed to set 'enabled_notification_listeners'",
listeners.toString(), newListeners);
}
private String getNotificationListenerServices() throws Exception {
return executeShellCommand("settings get secure enabled_notification_listeners");
} }
protected void setPendingIntentWhitelistDuration(int durationMs) throws Exception { protected void setPendingIntentWhitelistDuration(int durationMs) throws Exception {
@@ -916,10 +975,12 @@ abstract class AbstractRestrictBackgroundNetworkTestCase extends Instrumentation
// App didn't come to foreground when the activity is started, so try again. // App didn't come to foreground when the activity is started, so try again.
assertForegroundNetworkAccess(); assertForegroundNetworkAccess();
} else { } else {
dumpOnFailure();
fail("Network is not available for app2 (" + mUid + "): " + errors[0]); fail("Network is not available for app2 (" + mUid + "): " + errors[0]);
} }
} }
} else { } else {
dumpOnFailure();
fail("Timed out waiting for network availability status from app2 (" + mUid + ")"); fail("Timed out waiting for network availability status from app2 (" + mUid + ")");
} }
} else { } else {

View File

@@ -19,6 +19,7 @@ import android.app.Notification;
import android.app.PendingIntent; import android.app.PendingIntent;
import android.app.PendingIntent.CanceledException; import android.app.PendingIntent.CanceledException;
import android.app.RemoteInput; import android.app.RemoteInput;
import android.content.ComponentName;
import android.os.Bundle; import android.os.Bundle;
import android.service.notification.NotificationListenerService; import android.service.notification.NotificationListenerService;
import android.service.notification.StatusBarNotification; import android.service.notification.StatusBarNotification;
@@ -74,6 +75,11 @@ public class MyNotificationListenerService extends NotificationListenerService {
MyNotificationListenerService.class.getName()); MyNotificationListenerService.class.getName());
} }
static ComponentName getComponentName() {
return new ComponentName(MyNotificationListenerService.class.getPackage().getName(),
MyNotificationListenerService.class.getName());
}
private static final class PendingIntentSender { private static final class PendingIntentSender {
private PendingIntent mSentIntent = null; private PendingIntent mSentIntent = null;
private String mReason = null; private String mReason = null;

View File

@@ -30,6 +30,6 @@ LOCAL_PROGUARD_ENABLED := disabled
LOCAL_DEX_PREOPT := false LOCAL_DEX_PREOPT := false
# Tag this module as a cts test artifact # Tag this module as a cts test artifact
LOCAL_COMPATIBILITY_SUITE := cts general-tests LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
include $(BUILD_CTS_SUPPORT_PACKAGE) include $(BUILD_CTS_SUPPORT_PACKAGE)

View File

@@ -0,0 +1,75 @@
/*
* Copyright (C) 2017 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;
import com.android.tradefed.build.IBuildInfo;
import com.android.tradefed.device.DeviceNotAvailableException;
import com.android.tradefed.device.ITestDevice;
import com.android.tradefed.log.LogUtil;
import com.android.tradefed.targetprep.ITargetCleaner;
import com.android.tradefed.targetprep.ITargetPreparer;
public class NetPolicyTestsPreparer implements ITargetPreparer, ITargetCleaner {
private final static String KEY_PAROLE_DURATION = "parole_duration";
private final static String DESIRED_PAROLE_DURATION = "0";
private boolean mAppIdleConstsUpdated;
private String mOriginalAppIdleConsts;
@Override
public void setUp(ITestDevice device, IBuildInfo buildInfo) throws DeviceNotAvailableException {
updateParoleDuration(device);
LogUtil.CLog.d("Original app_idle_constants: " + mOriginalAppIdleConsts);
}
@Override
public void tearDown(ITestDevice device, IBuildInfo buildInfo, Throwable throwable)
throws DeviceNotAvailableException {
if (mAppIdleConstsUpdated) {
executeCmd(device, "settings put global app_idle_constants " + mOriginalAppIdleConsts);
}
}
/**
* Updates parole_duration with the desired value.
*/
private void updateParoleDuration(ITestDevice device) throws DeviceNotAvailableException {
mOriginalAppIdleConsts = executeCmd(device, "settings get global app_idle_constants");
String newAppIdleConstants;
final String newConstant = KEY_PAROLE_DURATION + "=" + DESIRED_PAROLE_DURATION;
if (mOriginalAppIdleConsts == null || "null".equals(mOriginalAppIdleConsts)) {
// app_idle_constants is initially empty, so just assign the desired value.
newAppIdleConstants = newConstant;
} else if (mOriginalAppIdleConsts.contains(KEY_PAROLE_DURATION)) {
// app_idle_constants contains parole_duration, so replace it with the desired value.
newAppIdleConstants = mOriginalAppIdleConsts.replaceAll(
KEY_PAROLE_DURATION + "=\\d+", newConstant);
} else {
// app_idle_constants didn't have parole_duration, so append the desired value.
newAppIdleConstants = mOriginalAppIdleConsts + "," + newConstant;
}
executeCmd(device, "settings put global app_idle_constants " + newAppIdleConstants);
mAppIdleConstsUpdated = true;
}
private String executeCmd(ITestDevice device, String cmd)
throws DeviceNotAvailableException {
final String output = device.executeShellCommand(cmd).trim();
LogUtil.CLog.d("Output for '%s': %s", cmd, output);
return output;
}
}

View File

@@ -47,7 +47,7 @@ LOCAL_STATIC_JAVA_LIBRARIES := \
#LOCAL_SDK_VERSION := current #LOCAL_SDK_VERSION := current
# Tag this module as a cts test artifact # Tag this module as a cts test artifact
LOCAL_COMPATIBILITY_SUITE := cts general-tests LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
include $(BUILD_CTS_PACKAGE) include $(BUILD_CTS_PACKAGE)

View File

@@ -31,7 +31,7 @@ LOCAL_PACKAGE_NAME := CtsNetTestAppForApi23
LOCAL_SDK_VERSION := 23 LOCAL_SDK_VERSION := 23
# Tag this module as a cts test artifact # Tag this module as a cts test artifact
LOCAL_COMPATIBILITY_SUITE := cts general-tests LOCAL_COMPATIBILITY_SUITE := cts vts general-tests
include $(BUILD_CTS_PACKAGE) include $(BUILD_CTS_PACKAGE)

View File

@@ -36,7 +36,7 @@ LOCAL_STATIC_LIBRARIES := \
LOCAL_CTS_TEST_PACKAGE := android.net.native LOCAL_CTS_TEST_PACKAGE := android.net.native
# Tag this module as a cts test artifact # Tag this module as a cts test artifact
LOCAL_COMPATIBILITY_SUITE := cts LOCAL_COMPATIBILITY_SUITE := cts vts
LOCAL_CFLAGS := -Werror -Wall LOCAL_CFLAGS := -Werror -Wall

View File

@@ -77,6 +77,10 @@ public class WifiManagerTest extends AndroidTestCase {
private static final String SSID2 = "\"WifiManagerTestModified\""; private static final String SSID2 = "\"WifiManagerTestModified\"";
private static final String PROXY_TEST_SSID = "SomeProxyAp"; private static final String PROXY_TEST_SSID = "SomeProxyAp";
private static final String ADD_NETWORK_EXCEPTION_SUBSTR = "addNetwork"; private static final String ADD_NETWORK_EXCEPTION_SUBSTR = "addNetwork";
// A full single scan duration is about 6-7 seconds if country code is set
// to US. If country code is set to world mode (00), we would expect a scan
// duration of roughly 8 seconds. So we set scan timeout as 9 seconds here.
private static final int SCAN_TIMEOUT_MSEC = 9000;
private static final int TIMEOUT_MSEC = 6000; private static final int TIMEOUT_MSEC = 6000;
private static final int WAIT_MSEC = 60; private static final int WAIT_MSEC = 60;
private static final int DURATION = 10000; private static final int DURATION = 10000;
@@ -202,7 +206,7 @@ public class WifiManagerTest extends AndroidTestCase {
mMySync.expectedState = STATE_SCANNING; mMySync.expectedState = STATE_SCANNING;
mScanResults = null; mScanResults = null;
assertTrue(mWifiManager.startScan()); assertTrue(mWifiManager.startScan());
long timeout = System.currentTimeMillis() + TIMEOUT_MSEC; long timeout = System.currentTimeMillis() + SCAN_TIMEOUT_MSEC;
while (System.currentTimeMillis() < timeout && mMySync.expectedState == STATE_SCANNING) while (System.currentTimeMillis() < timeout && mMySync.expectedState == STATE_SCANNING)
mMySync.wait(WAIT_MSEC); mMySync.wait(WAIT_MSEC);
} }