am 5df8c155: Merge "Add Wifi Tethering stress test" into gingerbread

* commit '5df8c155872833647ac56951ab90bd26a9af9480':
  Add Wifi Tethering stress test
diff --git a/core/tests/ConnectivityManagerTest/AndroidManifest.xml b/core/tests/ConnectivityManagerTest/AndroidManifest.xml
index d298d40..b116bea 100644
--- a/core/tests/ConnectivityManagerTest/AndroidManifest.xml
+++ b/core/tests/ConnectivityManagerTest/AndroidManifest.xml
@@ -53,6 +53,15 @@
         android.label="Test runner for unit tests"
     />
 
+    <!-- run stress test suite:
+      "adb shell am instrument -e stressnum <200> -w
+      com.android.connectivitymanagertest/.ConnectivityManagerStressTestRunner"
+    -->
+    <instrumentation android:name=".ConnectivityManagerStressTestRunner"
+        android:targetPackage="com.android.connectivitymanagertest"
+        android:label="Test runner for Connectivity Manager Stress Tests"
+    />
+
     <uses-permission android:name="android.permission.INTERNET" />
     <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
diff --git a/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/ConnectivityManagerStressTestRunner.java b/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/ConnectivityManagerStressTestRunner.java
new file mode 100644
index 0000000..47f208a
--- /dev/null
+++ b/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/ConnectivityManagerStressTestRunner.java
@@ -0,0 +1,62 @@
+/*
+ * Copyright (C) 2010, 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.connectivitymanagertest;
+
+import android.os.Bundle;
+import android.test.InstrumentationTestRunner;
+import android.test.InstrumentationTestSuite;
+import android.util.Log;
+import com.android.connectivitymanagertest.stress.WifiApStress;
+
+import junit.framework.TestSuite;
+
+/**
+ * Instrumentation Test Runner for all stress tests
+ *
+ * To run the stress tests:
+ *
+ * adb shell am instrument -e stressnum <stress times> \
+ *     -w com.android.connectivitymanagertest/.ConnectivityManagerStressTestRunner
+ */
+
+public class ConnectivityManagerStressTestRunner extends InstrumentationTestRunner {
+    @Override
+    public TestSuite getAllTests() {
+        TestSuite suite = new InstrumentationTestSuite(this);
+        suite.addTestSuite(WifiApStress.class);
+        return suite;
+    }
+
+    @Override
+    public ClassLoader getLoader() {
+        return ConnectivityManagerTestRunner.class.getClassLoader();
+    }
+
+    @Override
+    public void onCreate(Bundle icicle) {
+        super.onCreate(icicle);
+        String stressValue = (String) icicle.get("stressnum");
+        if (stressValue != null) {
+            int iteration = Integer.parseInt(stressValue);
+            if (iteration > 0) {
+                numStress = iteration;
+            }
+        }
+    }
+
+    public int numStress = 100;
+}
diff --git a/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/ConnectivityManagerTestActivity.java b/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/ConnectivityManagerTestActivity.java
index 7c46e7a..37b9f52 100644
--- a/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/ConnectivityManagerTestActivity.java
+++ b/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/ConnectivityManagerTestActivity.java
@@ -55,6 +55,9 @@
     public static final int WIFI_SCAN_TIMEOUT = 20 * 1000;
     public static final int SHORT_TIMEOUT = 5 * 1000;
     public static final long LONG_TIMEOUT = 50 * 1000;
+    public static final int SUCCESS = 0;  // for Wifi tethering state change
+    public static final int FAILURE = 1;
+    public static final int INIT = -1;
     private static final String ACCESS_POINT_FILE = "accesspoints.xml";
     public ConnectivityReceiver mConnectivityReceiver = null;
     public WifiReceiver mWifiReceiver = null;
@@ -87,6 +90,10 @@
     public static final int NUM_NETWORK_TYPES = ConnectivityManager.MAX_NETWORK_TYPE + 1;
     NetworkState[] connectivityState = new NetworkState[NUM_NETWORK_TYPES];
 
+    // For wifi tethering tests
+    private String[] mWifiRegexs;
+    public int mWifiTetherResult = INIT;    // -1 is initialization state
+
     /**
      * A wrapper of a broadcast receiver which provides network connectivity information
      * for all kinds of network: wifi, mobile, etc.
@@ -150,6 +157,16 @@
                 mWifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE,
                                                 WifiManager.WIFI_STATE_UNKNOWN);
                 notifyWifiState();
+            } else if (action.equals(WifiManager.WIFI_AP_STATE_CHANGED_ACTION)) {
+                notifyWifiAPState();
+            } else if (action.equals(ConnectivityManager.ACTION_TETHER_STATE_CHANGED)) {
+                ArrayList<String> available = intent.getStringArrayListExtra(
+                        ConnectivityManager.EXTRA_AVAILABLE_TETHER);
+                ArrayList<String> active = intent.getStringArrayListExtra(
+                        ConnectivityManager.EXTRA_ACTIVE_TETHER);
+                ArrayList<String> errored = intent.getStringArrayListExtra(
+                        ConnectivityManager.EXTRA_ERRORED_TETHER);
+                updateTetherState(available.toArray(), active.toArray(), errored.toArray());
             }
             else {
                 return;
@@ -184,6 +201,8 @@
         mIntentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
         mIntentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
         mIntentFilter.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
+        mIntentFilter.addAction(WifiManager.WIFI_AP_STATE_CHANGED_ACTION);
+        mIntentFilter.addAction(ConnectivityManager.ACTION_TETHER_STATE_CHANGED);
         registerReceiver(mWifiReceiver, mIntentFilter);
 
         // Get an instance of ConnectivityManager
@@ -196,6 +215,7 @@
             Log.v(LOG_TAG, "Clear Wifi before we start the test.");
             removeConfiguredNetworksAndDisableWifi();
         }
+        mWifiRegexs = mCM.getTetherableWifiRegexs();
      }
 
     public List<WifiConfiguration> loadNetworkConfigurations() throws Exception {
@@ -263,13 +283,57 @@
         }
     }
 
-    public void notifyWifiState() {
+    private void notifyWifiState() {
         synchronized (wifiObject) {
             Log.v(LOG_TAG, "notify wifi state changed");
             wifiObject.notify();
         }
     }
 
+    private void notifyWifiAPState() {
+        synchronized (this) {
+            Log.v(LOG_TAG, "notify wifi AP state changed");
+            this.notify();
+        }
+    }
+
+    // Update wifi tethering state
+    private void updateTetherState(Object[] available, Object[] tethered, Object[] errored) {
+        boolean wifiTethered = false;
+        boolean wifiErrored = false;
+
+        synchronized (this) {
+            for (Object obj: tethered) {
+                String str = (String)obj;
+                for (String tethRex: mWifiRegexs) {
+                    Log.v(LOG_TAG, "str: " + str +"tethRex: " + tethRex);
+                    if (str.matches(tethRex)) {
+                        wifiTethered = true;
+                    }
+                }
+            }
+
+            for (Object obj: errored) {
+                String str = (String)obj;
+                for (String tethRex: mWifiRegexs) {
+                    Log.v(LOG_TAG, "error: str: " + str +"tethRex: " + tethRex);
+                    if (str.matches(tethRex)) {
+                        wifiErrored = true;
+                    }
+                }
+            }
+
+            if (wifiTethered) {
+                mWifiTetherResult = SUCCESS;   // wifi tethering is successful
+            } else if (wifiErrored) {
+                mWifiTetherResult = FAILURE;   // wifi tethering failed
+            }
+            Log.v(LOG_TAG, "mWifiTetherResult: " + mWifiTetherResult);
+            this.notify();
+        }
+    }
+
+
     // Wait for network connectivity state: CONNECTING, CONNECTED, SUSPENDED,
     //                                      DISCONNECTING, DISCONNECTED, UNKNOWN
     public boolean waitForNetworkState(int networkType, State expectedState, long timeout) {
@@ -332,6 +396,62 @@
         }
     }
 
+    // Wait for Wifi AP state: WIFI_AP_STATE_DISABLED, WIFI_AP_STATE_DISABLING,
+    //                         WIFI_AP_STATE_ENABLED, WIFI_STATE_ENALBING, WIFI_STATE_UNKNOWN
+    public boolean waitForWifiAPState(int expectedState, long timeout) {
+        long startTime = System.currentTimeMillis();
+        while (true) {
+            if ((System.currentTimeMillis() - startTime) > timeout) {
+                if (mWifiManager.getWifiApState() != expectedState) {
+                    return false;
+                } else {
+                    return true;
+                }
+            }
+            Log.v(LOG_TAG, "Wait for wifi AP state to be: " + expectedState);
+            synchronized (wifiObject) {
+                try {
+                    wifiObject.wait(SHORT_TIMEOUT);
+                } catch (InterruptedException e) {
+                    e.printStackTrace();
+                }
+                if (mWifiManager.getWifiApState() != expectedState) {
+                    Log.v(LOG_TAG, "Wifi state is: " + mWifiManager.getWifiApState());
+                    continue;
+                }
+                return true;
+            }
+        }
+    }
+
+    /**
+     * Wait for the wifi tethering result:
+     * @param timeout is the maximum waiting time
+     * @return SUCCESS if tethering result is successful
+     *         FAILURE if tethering result returns error.
+     */
+    public int waitForTetherStateChange(long timeout) {
+        long startTime = System.currentTimeMillis();
+        while (true) {
+            if ((System.currentTimeMillis() - startTime) > timeout) {
+                return mWifiTetherResult;
+            }
+            Log.v(LOG_TAG, "Wait for wifi tethering result.");
+            synchronized (this) {
+                try {
+                    this.wait(SHORT_TIMEOUT);
+                } catch (InterruptedException e) {
+                    e.printStackTrace();
+                }
+                if (mWifiTetherResult == INIT ) {
+                    continue;
+                } else {
+                    return mWifiTetherResult;
+                }
+            }
+        }
+    }
+
     // Return true if device is currently connected to mobile network
     public boolean isConnectedToMobile() {
         return (mNetworkInfo.getType() == ConnectivityManager.TYPE_MOBILE);
diff --git a/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/stress/WifiApStress.java b/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/stress/WifiApStress.java
new file mode 100644
index 0000000..cc53ddc
--- /dev/null
+++ b/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/stress/WifiApStress.java
@@ -0,0 +1,89 @@
+/*
+ * Copyright (C) 2010, 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.connectivitymanagertest.stress;
+
+
+import com.android.connectivitymanagertest.ConnectivityManagerStressTestRunner;
+import com.android.connectivitymanagertest.ConnectivityManagerTestActivity;
+import com.android.connectivitymanagertest.ConnectivityManagerTestRunner;
+
+import android.net.wifi.WifiConfiguration;
+import android.net.wifi.WifiConfiguration.KeyMgmt;
+import android.net.wifi.WifiConfiguration.AuthAlgorithm;
+import android.test.ActivityInstrumentationTestCase2;
+import android.test.suitebuilder.annotation.LargeTest;
+import android.util.Log;
+
+/**
+ * Stress the wifi driver as access point.
+ */
+public class WifiApStress
+    extends ActivityInstrumentationTestCase2<ConnectivityManagerTestActivity> {
+    private final static String TAG = "WifiApStress";
+    private ConnectivityManagerTestActivity mAct;
+    private static String NETWORK_ID = "AndroidAPTest";
+    private static String PASSWD = "androidwifi";
+    private int max_num;
+
+    public WifiApStress() {
+        super(ConnectivityManagerTestActivity.class);
+    }
+
+    @Override
+    public void setUp() throws Exception {
+        super.setUp();
+        mAct = getActivity();
+        max_num = ((ConnectivityManagerStressTestRunner)getInstrumentation()).numStress;
+    }
+
+    @Override
+    public void tearDown() throws Exception {
+        super.tearDown();
+    }
+
+    @LargeTest
+    public void testWifiHotSpot() {
+        WifiConfiguration config = new WifiConfiguration();
+        config.SSID = NETWORK_ID;
+        config.allowedKeyManagement.set(KeyMgmt.WPA_PSK);
+        config.allowedAuthAlgorithms.set(AuthAlgorithm.OPEN);
+        config.preSharedKey = PASSWD;
+
+        // If Wifi is enabled, disable it
+        if (mAct.mWifiManager.isWifiEnabled()) {
+            mAct.disableWifi();
+        }
+        for (int i = 0; i < max_num; i++) {
+            Log.v(TAG, "iteration: " + i);
+            // enable Wifi tethering
+            assertTrue(mAct.mWifiManager.setWifiApEnabled(config, true));
+            // Wait for wifi ap state to be ENABLED
+            assertTrue(mAct.waitForWifiAPState(mAct.mWifiManager.WIFI_AP_STATE_ENABLED,
+                    mAct.LONG_TIMEOUT));
+            // Wait for wifi tethering result
+            assertEquals(mAct.SUCCESS, mAct.waitForTetherStateChange(2*mAct.SHORT_TIMEOUT));
+            // Allow the wifi tethering to be enabled for 10 seconds
+            try {
+                Thread.sleep(2 * ConnectivityManagerTestActivity.SHORT_TIMEOUT);
+            } catch (Exception e) {
+                fail("thread in sleep is interrupted");
+            }
+            assertTrue(mAct.mWifiManager.setWifiApEnabled(config, false));
+        }
+    }
+
+}