Tests for managed WiFi deleting on owner removal

Tests that removing a managed profile will also remove any network
information associated with that profile.

Bug: 19573610
Change-Id: Icf910728632ac3f8de0c03e8c12490dbac1c4155
diff --git a/common/device-side/util/src/com/android/compatibility/common/util/WifiConfigCreator.java b/common/device-side/util/src/com/android/compatibility/common/util/WifiConfigCreator.java
index 1cea80c..d01978a 100644
--- a/common/device-side/util/src/com/android/compatibility/common/util/WifiConfigCreator.java
+++ b/common/device-side/util/src/com/android/compatibility/common/util/WifiConfigCreator.java
@@ -28,11 +28,11 @@
  * A simple activity to create and manage wifi configurations.
  */
 public class WifiConfigCreator {
-    public static final String CREATE_WIFI_CONFIG_ACTION =
+    public static final String ACTION_CREATE_WIFI_CONFIG =
             "com.android.compatibility.common.util.CREATE_WIFI_CONFIG";
-    public static final String UPDATE_WIFI_CONFIG_ACTION =
+    public static final String ACTION_UPDATE_WIFI_CONFIG =
             "com.android.compatibility.common.util.UPDATE_WIFI_CONFIG";
-    public static final String REMOVE_WIFI_CONFIG_ACTION =
+    public static final String ACTION_REMOVE_WIFI_CONFIG =
             "com.android.compatibility.common.util.REMOVE_WIFI_CONFIG";
     public static final String EXTRA_NETID = "extra-netid";
     public static final String EXTRA_SSID = "extra-ssid";
diff --git a/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/WifiConfigLockdownTest.java b/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/WifiConfigLockdownTest.java
index ef1d8f7..1627961 100644
--- a/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/WifiConfigLockdownTest.java
+++ b/hostsidetests/devicepolicy/app/DeviceOwner/src/com/android/cts/deviceowner/WifiConfigLockdownTest.java
@@ -26,15 +26,15 @@
 
 import java.util.List;
 
-import static com.android.compatibility.common.util.WifiConfigCreator.CREATE_WIFI_CONFIG_ACTION;
+import static com.android.compatibility.common.util.WifiConfigCreator.ACTION_CREATE_WIFI_CONFIG;
 import static com.android.compatibility.common.util.WifiConfigCreator.EXTRA_NETID;
 import static com.android.compatibility.common.util.WifiConfigCreator.EXTRA_PASSWORD;
 import static com.android.compatibility.common.util.WifiConfigCreator.EXTRA_SECURITY_TYPE;
 import static com.android.compatibility.common.util.WifiConfigCreator.EXTRA_SSID;
-import static com.android.compatibility.common.util.WifiConfigCreator.REMOVE_WIFI_CONFIG_ACTION;
+import static com.android.compatibility.common.util.WifiConfigCreator.ACTION_REMOVE_WIFI_CONFIG;
 import static com.android.compatibility.common.util.WifiConfigCreator.SECURITY_TYPE_NONE;
 import static com.android.compatibility.common.util.WifiConfigCreator.SECURITY_TYPE_WPA;
-import static com.android.compatibility.common.util.WifiConfigCreator.UPDATE_WIFI_CONFIG_ACTION;
+import static com.android.compatibility.common.util.WifiConfigCreator.ACTION_UPDATE_WIFI_CONFIG;
 
 /**
  * Testing WiFi configuration lockdown by Device Owner
@@ -58,7 +58,7 @@
                 Settings.Global.WIFI_DEVICE_OWNER_CONFIGS_LOCKDOWN, "1");
         mConfigCreator.addNetwork(ORIGINAL_DEVICE_OWNER_SSID, true, SECURITY_TYPE_WPA,
                 ORIGINAL_PASSWORD);
-        startRegularActivity(CREATE_WIFI_CONFIG_ACTION, -1, ORIGINAL_REGULAR_SSID,
+        startRegularActivity(ACTION_CREATE_WIFI_CONFIG, -1, ORIGINAL_REGULAR_SSID,
                 SECURITY_TYPE_WPA, ORIGINAL_PASSWORD);
     }
 
@@ -116,7 +116,7 @@
         int updateCount = 0;
         for (WifiConfiguration config : configs) {
             if (areMatchingSsids(ORIGINAL_DEVICE_OWNER_SSID, config.SSID)) {
-                startRegularActivity(UPDATE_WIFI_CONFIG_ACTION, config.networkId,
+                startRegularActivity(ACTION_UPDATE_WIFI_CONFIG, config.networkId,
                         CHANGED_DEVICE_OWNER_SSID, SECURITY_TYPE_NONE, null);
                 ++updateCount;
             }
@@ -142,7 +142,7 @@
         int removeCount = 0;
         for (WifiConfiguration config : configs) {
             if (areMatchingSsids(ORIGINAL_DEVICE_OWNER_SSID, config.SSID)) {
-                startRegularActivity(REMOVE_WIFI_CONFIG_ACTION, config.networkId,
+                startRegularActivity(ACTION_REMOVE_WIFI_CONFIG, config.networkId,
                         null, SECURITY_TYPE_NONE, null);
                 ++removeCount;
             }
diff --git a/hostsidetests/devicepolicy/app/ManagedProfile/Android.mk b/hostsidetests/devicepolicy/app/ManagedProfile/Android.mk
index f4adb31..7b3fba3 100644
--- a/hostsidetests/devicepolicy/app/ManagedProfile/Android.mk
+++ b/hostsidetests/devicepolicy/app/ManagedProfile/Android.mk
@@ -26,7 +26,7 @@
 
 LOCAL_JAVA_LIBRARIES := android.test.runner cts-junit
 
-LOCAL_STATIC_JAVA_LIBRARIES = android-support-v4 ctstestrunner
+LOCAL_STATIC_JAVA_LIBRARIES = android-support-v4 ctstestrunner compatibility-device-util_v2
 
 LOCAL_SDK_VERSION := current
 
diff --git a/hostsidetests/devicepolicy/app/ManagedProfile/AndroidManifest.xml b/hostsidetests/devicepolicy/app/ManagedProfile/AndroidManifest.xml
index 31e4ad4..9bf7046 100644
--- a/hostsidetests/devicepolicy/app/ManagedProfile/AndroidManifest.xml
+++ b/hostsidetests/devicepolicy/app/ManagedProfile/AndroidManifest.xml
@@ -18,6 +18,7 @@
     package="com.android.cts.managedprofile">
 
     <uses-sdk android:minSdkVersion="20"/>
+    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
     <uses-permission android:name="android.permission.BLUETOOTH" />
     <uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
     <uses-permission android:name="android.permission.READ_CONTACTS" />
diff --git a/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/WifiTest.java b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/WifiTest.java
new file mode 100644
index 0000000..c4c02e8
--- /dev/null
+++ b/hostsidetests/devicepolicy/app/ManagedProfile/src/com/android/cts/managedprofile/WifiTest.java
@@ -0,0 +1,142 @@
+/*
+ * Copyright (C) 2015 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.managedprofile;
+
+import android.content.Context;
+import android.content.Intent;
+import android.net.wifi.WifiConfiguration;
+import android.net.wifi.WifiManager;
+import android.os.SystemClock;
+import android.test.AndroidTestCase;
+
+import java.util.concurrent.TimeUnit;
+
+import static com.android.compatibility.common.util.WifiConfigCreator.ACTION_CREATE_WIFI_CONFIG;
+import static com.android.compatibility.common.util.WifiConfigCreator.ACTION_REMOVE_WIFI_CONFIG;
+import static com.android.compatibility.common.util.WifiConfigCreator.EXTRA_NETID;
+import static com.android.compatibility.common.util.WifiConfigCreator.EXTRA_SSID;
+
+/**
+ * Driven by the host-side test: com.android.cts.devicepolicy.ManagedProfileTest
+ *
+ * Each of these tests can run independently but have side-effects. The side-effects are used as
+ * building blocks to test various cleanup routines, for example that networks belonging to one
+ * user are deleted
+ */
+public class WifiTest extends AndroidTestCase {
+    private static final String TAG = WifiTest.class.getSimpleName();
+
+    // Unique SSID to use for this test (max SSID length is 32)
+    private static final String NETWORK_SSID = "com.android.cts.xwde7ktvh8rmjuhr";
+
+    // Time duration to allow before assuming that a WiFi operation failed and ceasing to wait.
+    private static final long UPDATE_TIMEOUT_MS = TimeUnit.SECONDS.toMillis(30);
+    private static final long UPDATE_INTERVAL_MS = TimeUnit.SECONDS.toMillis(1);
+
+    // Shared WifiManager instance.
+    private WifiManager mWifiManager;
+
+    @Override
+    public void setUp() throws Exception {
+        super.setUp();
+        mWifiManager = (WifiManager) getContext().getSystemService(Context.WIFI_SERVICE);
+    }
+
+    /**
+     * Add a network through the WifiManager API. Verifies that the network was actually added.
+     *
+     * <p>Side effects:
+     * <ul>
+     *   <li>Network with SSID {@link WifiTest#NETWORK_SSID} is created.</li>
+     * </ul>
+     */
+    public void testAddWifiNetwork() throws Exception {
+        Intent intent = new Intent(ACTION_CREATE_WIFI_CONFIG);
+        intent.putExtra(EXTRA_SSID, NETWORK_SSID);
+        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+        getContext().startActivity(intent);
+
+        // Wait for configuration to appear in networks list.
+        assertTrue(awaitNetworkState(NETWORK_SSID, /* exists */ true));
+    }
+
+    /**
+     * Remove any network through the WifiManager API with a certain SSID. Verifies that the network
+     * was actually removed.
+     *
+     * <p>Side effects:
+     * <ul>
+     *   <li>If a network with SSID {@link WifiTest#NETWORK_SSID} exists, it will be deleted.</li>
+     * </ul>
+     */
+    public void testRemoveWifiNetworkIfExists() throws Exception {
+        WifiConfiguration config = getNetworkForSsid(NETWORK_SSID);
+
+        if (config != null && config.networkId != -1) {
+            Intent intent = new Intent(ACTION_REMOVE_WIFI_CONFIG);
+            intent.putExtra(EXTRA_NETID, config.networkId);
+            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
+            getContext().startActivity(intent);
+        }
+
+        assertTrue(awaitNetworkState(NETWORK_SSID, /* exists */ false));
+    }
+
+    /**
+     * Verify that no network exists with a certain SSID.
+     *
+     * <p>The SSID that will be checked for is {@link WifiTest#NETWORK_SSID}.
+     */
+    public void testWifiNetworkDoesNotExist() throws Exception {
+        assertTrue(awaitNetworkState(NETWORK_SSID, /* exists */ false));
+    }
+
+    /**
+     * Block until a network configuration with a certain SSID either exists or ceases to.
+     * Wait for up to {@link WifiTest#UPDATE_TIMEOUT_MS} milliseconds, in increments of
+     * {@link WifiTest#UPDATE_INTERVAL_MS}.
+     */
+    private boolean awaitNetworkState(String ssid, boolean exists) {
+        for (int probes = 0; probes * UPDATE_INTERVAL_MS <= UPDATE_TIMEOUT_MS; probes++) {
+            if (probes != 0) {
+                SystemClock.sleep(UPDATE_INTERVAL_MS);
+            }
+            if ((getNetworkForSsid(ssid) != null) == exists) {
+                return true;
+            }
+        }
+        return false;
+    }
+
+    /**
+     * Internal method to find an existing {@link WifiConfiguration} with the given SSID.
+     *
+     * @return A {@link WifiConfiguration} matching the specification, or {@code null} if no such
+     *         configuration exists.
+     */
+    private WifiConfiguration getNetworkForSsid(String ssid) {
+        if (!ssid.startsWith("\"")) {
+            ssid = '"' + ssid + '"';
+        }
+        for (WifiConfiguration config : mWifiManager.getConfiguredNetworks()) {
+            if (ssid.equals(config.SSID)) {
+                return config;
+            }
+        }
+        return null;
+    }
+}
diff --git a/hostsidetests/devicepolicy/app/WifiConfigCreator/src/com/android/cts/deviceowner/wificonfigcreator/WifiConfigCreatorActivity.java b/hostsidetests/devicepolicy/app/WifiConfigCreator/src/com/android/cts/deviceowner/wificonfigcreator/WifiConfigCreatorActivity.java
index 7958cb1..af31030 100644
--- a/hostsidetests/devicepolicy/app/WifiConfigCreator/src/com/android/cts/deviceowner/wificonfigcreator/WifiConfigCreatorActivity.java
+++ b/hostsidetests/devicepolicy/app/WifiConfigCreator/src/com/android/cts/deviceowner/wificonfigcreator/WifiConfigCreatorActivity.java
@@ -22,14 +22,14 @@
 import android.util.Log;
 
 import com.android.compatibility.common.util.WifiConfigCreator;
-import static com.android.compatibility.common.util.WifiConfigCreator.CREATE_WIFI_CONFIG_ACTION;
+import static com.android.compatibility.common.util.WifiConfigCreator.ACTION_CREATE_WIFI_CONFIG;
 import static com.android.compatibility.common.util.WifiConfigCreator.EXTRA_NETID;
 import static com.android.compatibility.common.util.WifiConfigCreator.EXTRA_PASSWORD;
 import static com.android.compatibility.common.util.WifiConfigCreator.EXTRA_SECURITY_TYPE;
 import static com.android.compatibility.common.util.WifiConfigCreator.EXTRA_SSID;
-import static com.android.compatibility.common.util.WifiConfigCreator.REMOVE_WIFI_CONFIG_ACTION;
+import static com.android.compatibility.common.util.WifiConfigCreator.ACTION_REMOVE_WIFI_CONFIG;
 import static com.android.compatibility.common.util.WifiConfigCreator.SECURITY_TYPE_NONE;
-import static com.android.compatibility.common.util.WifiConfigCreator.UPDATE_WIFI_CONFIG_ACTION;
+import static com.android.compatibility.common.util.WifiConfigCreator.ACTION_UPDATE_WIFI_CONFIG;
 
 /**
  * A simple activity to create and manage wifi configurations.
@@ -45,18 +45,18 @@
         try {
             Intent intent = getIntent();
             String action = intent.getAction();
-            if (CREATE_WIFI_CONFIG_ACTION.equals(action)) {
+            if (ACTION_CREATE_WIFI_CONFIG.equals(action)) {
                 String ssid = intent.getStringExtra(EXTRA_SSID);
                 int securityType = intent.getIntExtra(EXTRA_SECURITY_TYPE, SECURITY_TYPE_NONE);
                 String password = intent.getStringExtra(EXTRA_PASSWORD);
                 configCreator.addNetwork(ssid, false, securityType, password);
-            } else if (UPDATE_WIFI_CONFIG_ACTION.equals(action)) {
+            } else if (ACTION_UPDATE_WIFI_CONFIG.equals(action)) {
                 int netId = intent.getIntExtra(EXTRA_NETID, -1);
                 String ssid = intent.getStringExtra(EXTRA_SSID);
                 int securityType = intent.getIntExtra(EXTRA_SECURITY_TYPE, SECURITY_TYPE_NONE);
                 String password = intent.getStringExtra(EXTRA_PASSWORD);
                 configCreator.updateNetwork(netId, ssid, false, securityType, password);
-            } else if (REMOVE_WIFI_CONFIG_ACTION.equals(action)) {
+            } else if (ACTION_REMOVE_WIFI_CONFIG.equals(action)) {
                 int netId = intent.getIntExtra(EXTRA_NETID, -1);
                 if (netId != -1) {
                     configCreator.removeNetwork(netId);
diff --git a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/ManagedProfileTest.java b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/ManagedProfileTest.java
index 3f0805c..34cb3ba 100644
--- a/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/ManagedProfileTest.java
+++ b/hostsidetests/devicepolicy/src/com/android/cts/devicepolicy/ManagedProfileTest.java
@@ -42,11 +42,19 @@
     private static final String CERT_INSTALLER_PKG = "com.android.cts.certinstaller";
     private static final String CERT_INSTALLER_APK = "CtsCertInstallerApp.apk";
 
+    private static final String WIFI_CONFIG_CREATOR_PKG = "com.android.cts.wificonfigcreator";
+    private static final String WIFI_CONFIG_CREATOR_APK = "CtsWifiConfigCreator.apk";
+
     private static final String ADMIN_RECEIVER_TEST_CLASS =
             MANAGED_PROFILE_PKG + ".BaseManagedProfileTest$BasicAdminReceiver";
 
     private static final String FEATURE_BLUETOOTH = "android.hardware.bluetooth";
     private static final String FEATURE_CAMERA = "android.hardware.camera";
+    private static final String FEATURE_WIFI = "android.hardware.wifi";
+
+    private static final int USER_OWNER = 0;
+
+    // ID of the profile we'll create. This will always be a profile of USER_OWNER.
     private int mUserId;
 
     @Override
@@ -114,6 +122,29 @@
         }
     }
 
+    /**
+     * Verify that removing a managed profile will remove all networks owned by that profile.
+     */
+    public void testProfileWifiCleanup() throws Exception {
+        if (!mHasFeature || !hasDeviceFeature(FEATURE_WIFI)) {
+            return;
+        }
+        assertTrue("WiFi config already exists and could not be removed", runDeviceTestsAsUser(
+                MANAGED_PROFILE_PKG, ".WifiTest", "testRemoveWifiNetworkIfExists", USER_OWNER));
+        try {
+            installApp(WIFI_CONFIG_CREATOR_APK);
+            assertTrue("Failed to add WiFi config", runDeviceTestsAsUser(
+                    MANAGED_PROFILE_PKG, ".WifiTest", "testAddWifiNetwork", mUserId));
+
+            // Now delete the user - should undo the effect of testAddWifiNetwork.
+            removeUser(mUserId);
+            assertTrue("WiFi config not removed after deleting profile", runDeviceTestsAsUser(
+                    MANAGED_PROFILE_PKG, ".WifiTest", "testWifiNetworkDoesNotExist", USER_OWNER));
+        } finally {
+            getDevice().uninstallPackage(WIFI_CONFIG_CREATOR_APK);
+        }
+    }
+
     public void testCrossProfileIntentFilters() throws Exception {
         if (!mHasFeature) {
             return;