M7350v1_en_gpl

This commit is contained in:
T
2024-09-09 08:52:07 +00:00
commit f9cc65cfda
65988 changed files with 26357421 additions and 0 deletions
@@ -0,0 +1,30 @@
# 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.
LOCAL_PATH:= $(call my-dir)
include $(CLEAR_VARS)
# We only want this apk build for tests.
LOCAL_MODULE_TAGS := tests
LOCAL_JAVA_LIBRARIES := android.test.runner
# Include all test java files.
LOCAL_SRC_FILES := $(call all-java-files-under, src)
LOCAL_PACKAGE_NAME := ConnectivityManagerTest
LOCAL_CERTIFICATE := platform
include $(BUILD_PACKAGE)
@@ -0,0 +1,76 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- 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 name must be unique so suffix with "tests" so package loader doesn't ignore us -->
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.android.connectivitymanagertest"
android:sharedUserId="com.android.uid.test">
<!-- We add an application tag here just so that we can indicate that
this package needs to link against the android.test library,
which is needed when building test cases. -->
<application>
<uses-library android:name="android.test.runner" />
<activity android:name="ConnectivityManagerTestActivity"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<!--
This declares that this app uses the instrumentation test runner targeting
the package of connectivitymanagertest. To run the tests use the command:
"adb shell am instrument -e ssid <SSID> -w
com.android.connectivitymanagertest/.ConnectivityManagerTestRunner",
the access point <SSID> should be an open AP.
-->
<instrumentation android:name=".ConnectivityManagerTestRunner"
android:targetPackage="com.android.connectivitymanagertest"
android:label="Test runner for Connectivity Manager Tests"
/>
<!--
To run the unit tests use the command:
"adb shell am instrument -w
com.android.connectivitymanagertest/.ConnectivityManagerUnitTestRunner"
-->
<instrumentation android:name=".ConnectivityManagerUnitTestRunner"
android:targetPackage="com.android.connectivitymanagertest"
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" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
<uses-permission android:name="android.permission.WRITE_SETTINGS" />
<uses-permission android:name="android.permission.WRITE_SECURE_SETTINGS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.DEVICE_POWER" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</manifest>
@@ -0,0 +1,35 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<accesspoint>
<ssid>opennet</ssid>
<security>NONE</security>
</accesspoint>
<accesspoint>
<ssid>GoogleGuest</ssid>
<security>NONE</security>
</accesspoint>
<accesspoint>
<ssid>securenetdhcp</ssid>
<security>PSK</security>
<password>androidwifi</password>
</accesspoint>
<accesspoint>
<ssid>securenetstatic</ssid>
<security>PSK</security>
<password>androidwifi</password>
<ip>192.168.14.2</ip>
<gateway>192.168.14.1</gateway>
<netmask>255.255.255.0</netmask>
<dns1>192.168.14.1</dns1>
<dns2>192.168.1.9</dns2>
</accesspoint>
<accesspoint>
<ssid>botnet</ssid>
<security>EAP</security>
<eap>PEAP</eap>
<phase2>MSCHAPV2</phase2>
<identity>donut</identity>
<password>android</password>
</accesspoint>
</resources>
@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="app_name">ConnectivityManagerTest</string>
</resources>
@@ -0,0 +1,354 @@
/*
* 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 javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiConfiguration.AuthAlgorithm;
import android.net.wifi.WifiConfiguration.KeyMgmt;
import android.net.DhcpInfo;
import java.io.InputStream;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
/**
* Help class to process configurations of access points saved in an XML file.
* The configurations of an access point is included in tag
* <accesspoint></accesspoint>. The supported configuration includes: ssid,
* security, eap, phase2, identity, password, anonymousidentity, cacert, usercert,
* in which each is included in the corresponding tags. Static IP setting is also supported.
* Tags that can be used include: ip, gateway, netmask, dns1, dns2. All access points have to be
* enclosed in tags of <resources></resources>.
*
* The following is a sample configuration file for an access point using EAP-PEAP with MSCHAP2.
* <resources>
* <accesspoint>
* <ssid>testnet</ssid>
* <security>EAP</security>
* <eap>PEAP</eap>
* <phase2>MSCHAP2</phase2>
* <identity>donut</identity</identity>
* <password>abcdefgh</password>
* </accesspoint>
* </resources>
*
* Note:ssid and security have to be the first two tags
* for static ip setting, tag "ip" should be listed before other fields: dns, gateway, netmask.
*/
public class AccessPointParserHelper {
private static final String KEYSTORE_SPACE = "keystore://";
private static final String TAG = "AccessPointParserHelper";
static final int NONE = 0;
static final int WEP = 1;
static final int PSK = 2;
static final int EAP = 3;
List<WifiConfiguration> networks = new ArrayList<WifiConfiguration>();
HashMap<String, DhcpInfo> ssidToDhcpInfoHM = new HashMap<String, DhcpInfo>();
private int getSecurityType (String security) {
if (security.equalsIgnoreCase("NONE")) {
return NONE;
} else if (security.equalsIgnoreCase("WEP")) {
return WEP;
} else if (security.equalsIgnoreCase("PSK")) {
return PSK;
} else if (security.equalsIgnoreCase("EAP")) {
return EAP;
} else {
return -1;
}
}
private boolean validateEapValue(String value) {
if (value.equalsIgnoreCase("PEAP") ||
value.equalsIgnoreCase("TLS") ||
value.equalsIgnoreCase("TTLS")) {
return true;
} else {
return false;
}
}
private static int stringToIpAddr(String addrString) throws UnknownHostException {
try {
String[] parts = addrString.split("\\.");
if (parts.length != 4) {
throw new UnknownHostException(addrString);
}
int a = Integer.parseInt(parts[0]) ;
int b = Integer.parseInt(parts[1]) << 8;
int c = Integer.parseInt(parts[2]) << 16;
int d = Integer.parseInt(parts[3]) << 24;
return a | b | c | d;
} catch (NumberFormatException ex) {
throw new UnknownHostException(addrString);
}
}
DefaultHandler mHandler = new DefaultHandler() {
boolean ssid = false;
boolean security = false;
boolean password = false;
boolean ip = false;
boolean netmask = false;
boolean gateway = false;
boolean dns1 = false;
boolean dns2 = false;
boolean eap = false;
boolean phase2 = false;
boolean identity = false;
boolean anonymousidentity = false;
boolean cacert = false;
boolean usercert = false;
WifiConfiguration config = null;
int securityType = NONE;
DhcpInfo mDhcpInfo = null;
@Override
public void startElement(String uri, String localName, String tagName,
Attributes attributes) throws SAXException {
if (tagName.equalsIgnoreCase("accesspoint")) {
config = new WifiConfiguration();
}
if (tagName.equalsIgnoreCase("ssid")) {
ssid = true;
}
if (tagName.equalsIgnoreCase("security")) {
security = true;
}
if (tagName.equalsIgnoreCase("password")) {
password = true;
}
if (tagName.equalsIgnoreCase("eap")) {
eap = true;
}
if (tagName.equalsIgnoreCase("phase2")) {
phase2 = true;
}
if (tagName.equalsIgnoreCase("identity")) {
identity = true;
}
if (tagName.equalsIgnoreCase("anonymousidentity")) {
anonymousidentity = true;
}
if (tagName.equalsIgnoreCase("cacert")) {
cacert = true;
}
if (tagName.equalsIgnoreCase("usercert")) {
usercert = true;
}
if (tagName.equalsIgnoreCase("ip")) {
ip = true;
mDhcpInfo = new DhcpInfo();
}
if (tagName.equalsIgnoreCase("gateway")) {
gateway = true;
}
if (tagName.equalsIgnoreCase("netmask")) {
netmask = true;
}
if (tagName.equalsIgnoreCase("dns1")) {
dns1 = true;
}
if (tagName.equalsIgnoreCase("dns2")) {
dns2 = true;
}
}
@Override
public void endElement(String uri, String localName, String tagName) throws SAXException {
if (tagName.equalsIgnoreCase("accesspoint")) {
networks.add(config);
if (mDhcpInfo != null) {
ssidToDhcpInfoHM.put(config.SSID, mDhcpInfo);
mDhcpInfo = null;
}
}
}
@Override
public void characters(char ch[], int start, int length) throws SAXException {
if (ssid) {
config.SSID = new String(ch, start, length);
ssid = false;
}
if (security) {
String securityStr = (new String(ch, start, length)).toUpperCase();
securityType = getSecurityType(securityStr);
switch (securityType) {
case NONE:
config.allowedKeyManagement.set(KeyMgmt.NONE);
break;
case WEP:
config.allowedKeyManagement.set(KeyMgmt.NONE);
config.allowedAuthAlgorithms.set(AuthAlgorithm.OPEN);
config.allowedAuthAlgorithms.set(AuthAlgorithm.SHARED);
break;
case PSK:
config.allowedKeyManagement.set(KeyMgmt.WPA_PSK);
break;
case EAP:
config.allowedKeyManagement.set(KeyMgmt.WPA_EAP);
config.allowedKeyManagement.set(KeyMgmt.IEEE8021X);
// Initialize other fields.
config.phase2.setValue("");
config.ca_cert.setValue("");
config.client_cert.setValue("");
config.private_key.setValue("");
config.identity.setValue("");
config.anonymous_identity.setValue("");
break;
default:
throw new SAXException();
}
security = false;
}
if (password) {
String passwordStr = new String(ch, start, length);
int len = passwordStr.length();
if (len == 0) {
throw new SAXException();
}
if (securityType == WEP) {
if ((len == 10 || len == 26 || len == 58) &&
passwordStr.matches("[0-9A-Fa-f]*")) {
config.wepKeys[0] = passwordStr;
} else {
config.wepKeys[0] = '"' + passwordStr + '"';
}
} else if (securityType == PSK) {
if (passwordStr.matches("[0-9A-Fa-f]{64}")) {
config.preSharedKey = passwordStr;
} else {
config.preSharedKey = '"' + passwordStr + '"';
}
} else if (securityType == EAP) {
config.password.setValue(passwordStr);
} else {
throw new SAXException();
}
password = false;
}
if (eap) {
String eapValue = new String(ch, start, length);
if (!validateEapValue(eapValue)) {
throw new SAXException();
}
config.eap.setValue(eapValue);
eap = false;
}
if (phase2) {
String phase2Value = new String(ch, start, length);
config.phase2.setValue("auth=" + phase2Value);
phase2 = false;
}
if (identity) {
String identityValue = new String(ch, start, length);
config.identity.setValue(identityValue);
identity = false;
}
if (anonymousidentity) {
String anonyId = new String(ch, start, length);
config.anonymous_identity.setValue(anonyId);
anonymousidentity = false;
}
if (cacert) {
String cacertValue = new String(ch, start, length);
// need to install the credentail to "keystore://"
config.ca_cert.setValue(KEYSTORE_SPACE);
cacert = false;
}
if (usercert) {
String usercertValue = new String(ch, start, length);
config.client_cert.setValue(KEYSTORE_SPACE);
usercert = false;
}
if (ip) {
try {
mDhcpInfo.ipAddress = stringToIpAddr(new String(ch, start, length));
} catch (UnknownHostException e) {
throw new SAXException();
}
ip = false;
}
if (gateway) {
try {
mDhcpInfo.gateway = stringToIpAddr(new String(ch, start, length));
} catch (UnknownHostException e) {
throw new SAXException();
}
gateway = false;
}
if (netmask) {
try {
mDhcpInfo.netmask = stringToIpAddr(new String(ch, start, length));
} catch (UnknownHostException e) {
throw new SAXException();
}
netmask = false;
}
if (dns1) {
try {
mDhcpInfo.dns1 = stringToIpAddr(new String(ch, start, length));
} catch (UnknownHostException e) {
throw new SAXException();
}
dns1 = false;
}
if (dns2) {
try {
mDhcpInfo.dns2 = stringToIpAddr(new String(ch, start, length));
} catch (UnknownHostException e) {
throw new SAXException();
}
dns2 = false;
}
}
};
/**
* Process the InputStream in
* @param in is the InputStream that can be used for XML parsing
* @throws Exception
*/
public AccessPointParserHelper(InputStream in) throws Exception {
SAXParserFactory factory = SAXParserFactory.newInstance();
SAXParser saxParser = factory.newSAXParser();
saxParser.parse(in, mHandler);
}
public List<WifiConfiguration> getNetworkConfigurations() throws Exception {
return networks;
}
public HashMap<String, DhcpInfo> getSsidToDhcpInfoHashMap() {
return ssidToDhcpInfoHM;
}
}
@@ -0,0 +1,102 @@
/*
* 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 com.android.connectivitymanagertest.stress.WifiApStress;
import com.android.connectivitymanagertest.stress.WifiStressTest;
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 {
public int mSoftapIterations = 100;
public int mScanIterations = 100;
public int mReconnectIterations = 100;
public int mSleepTime = 30 * 1000; // default sleep time is 30 seconds
public String mReconnectSsid = "securenetdhcp";
public String mReconnectPassword = "androidwifi";
@Override
public TestSuite getAllTests() {
TestSuite suite = new InstrumentationTestSuite(this);
suite.addTestSuite(WifiApStress.class);
suite.addTestSuite(WifiStressTest.class);
return suite;
}
@Override
public ClassLoader getLoader() {
return ConnectivityManagerTestRunner.class.getClassLoader();
}
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
String valueStr = (String) icicle.get("softap_iterations");
if (valueStr != null) {
int iteration = Integer.parseInt(valueStr);
if (iteration > 0) {
mSoftapIterations = iteration;
}
}
String scanIterationStr = (String) icicle.get("scan_iterations");
if (scanIterationStr != null) {
int scanIteration = Integer.parseInt(scanIterationStr);
if (scanIteration > 0) {
mScanIterations = scanIteration;
}
}
String ssidStr= (String) icicle.get("reconnect_ssid");
if (ssidStr != null) {
mReconnectSsid = ssidStr;
}
String passwordStr = (String) icicle.get("reconnect_password");
if (passwordStr != null) {
mReconnectPassword = passwordStr;
}
String reconnectStr = (String) icicle.get("reconnect_iterations");
if (reconnectStr != null) {
int iteration = Integer.parseInt(reconnectStr);
if (iteration > 0) {
mReconnectIterations = iteration;
}
}
String sleepTimeStr = (String) icicle.get("sleep_time");
if (sleepTimeStr != null) {
int sleepTime = Integer.parseInt(sleepTimeStr);
if (sleepTime > 0) {
mSleepTime = 1000 * sleepTime;
}
}
}
}
@@ -0,0 +1,756 @@
/*
* 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 com.android.connectivitymanagertest.R;
import android.app.Activity;
import android.content.Context;
import android.content.res.Resources;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.IPowerManager;
import android.os.PowerManager;
import android.os.ServiceManager;
import android.os.SystemClock;
import android.provider.Settings;
import android.util.Log;
import android.view.KeyEvent;
import java.io.IOException;
import java.io.InputStream;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import android.widget.LinearLayout;
import android.net.ConnectivityManager;
import android.net.DhcpInfo;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
import android.net.wifi.SupplicantState;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration.KeyMgmt;
/**
* An activity registered with connectivity manager broadcast
* provides network connectivity information and
* can be used to set device states: Cellular, Wifi, Airplane mode.
*/
public class ConnectivityManagerTestActivity extends Activity {
public static final String LOG_TAG = "ConnectivityManagerTestActivity";
public static final int WAIT_FOR_SCAN_RESULT = 10 * 1000; //10 seconds
public static final int WIFI_SCAN_TIMEOUT = 50 * 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;
private AccessPointParserHelper mParseHelper = null;
public boolean scanResultAvailable = false;
/*
* Track network connectivity information
*/
public State mState;
public NetworkInfo mNetworkInfo;
public NetworkInfo mOtherNetworkInfo;
public boolean mIsFailOver;
public String mReason;
public boolean mScanResultIsAvailable = false;
public ConnectivityManager mCM;
public Object wifiObject = new Object();
public Object connectivityObject = new Object();
public int mWifiState;
public NetworkInfo mWifiNetworkInfo;
public String mBssid;
public String mPowerSsid = "opennet"; //Default power SSID
private Context mContext;
/*
* Control Wifi States
*/
public WifiManager mWifiManager;
/*
* Verify connectivity state
*/
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.
*/
private class ConnectivityReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
log("ConnectivityReceiver: onReceive() is called with " + intent);
String action = intent.getAction();
if (!action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Log.v("ConnectivityReceiver", "onReceive() called with " + intent);
return;
}
boolean noConnectivity =
intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
if (noConnectivity) {
mState = State.DISCONNECTED;
} else {
mState = State.CONNECTED;
}
mNetworkInfo = (NetworkInfo)
intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
mOtherNetworkInfo = (NetworkInfo)
intent.getParcelableExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO);
mReason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON);
mIsFailOver = intent.getBooleanExtra(ConnectivityManager.EXTRA_IS_FAILOVER, false);
log("mNetworkInfo: " + mNetworkInfo.toString());
if (mOtherNetworkInfo != null) {
log("mOtherNetworkInfo: " + mOtherNetworkInfo.toString());
}
recordNetworkState(mNetworkInfo.getType(), mNetworkInfo.getState());
if (mOtherNetworkInfo != null) {
recordNetworkState(mOtherNetworkInfo.getType(), mOtherNetworkInfo.getState());
}
notifyNetworkConnectivityChange();
}
}
private class WifiReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
Log.v("WifiReceiver", "onReceive() is calleld with " + intent);
if (action.equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
notifyScanResult();
} else if (action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
mWifiNetworkInfo =
(NetworkInfo) intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
log("mWifiNetworkInfo: " + mWifiNetworkInfo.toString());
if (mWifiNetworkInfo.getState() == State.CONNECTED) {
mBssid = intent.getStringExtra(WifiManager.EXTRA_BSSID);
}
notifyWifiState();
} else if (action.equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
mWifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE,
WifiManager.WIFI_STATE_UNKNOWN);
log("mWifiState: " + mWifiState);
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;
}
}
}
public ConnectivityManagerTestActivity() {
mState = State.UNKNOWN;
scanResultAvailable = false;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
log("onCreate, inst=" + Integer.toHexString(hashCode()));
// Create a simple layout
LinearLayout contentView = new LinearLayout(this);
contentView.setOrientation(LinearLayout.VERTICAL);
setContentView(contentView);
setTitle("ConnectivityManagerTestActivity");
// register a connectivity receiver for CONNECTIVITY_ACTION;
mConnectivityReceiver = new ConnectivityReceiver();
registerReceiver(mConnectivityReceiver,
new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
mWifiReceiver = new WifiReceiver();
IntentFilter mIntentFilter = new IntentFilter();
mIntentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
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
mCM = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
// Get an instance of WifiManager
mWifiManager =(WifiManager)getSystemService(Context.WIFI_SERVICE);
initializeNetworkStates();
if (mWifiManager.isWifiEnabled()) {
log("Clear Wifi before we start the test.");
removeConfiguredNetworksAndDisableWifi();
}
mWifiRegexs = mCM.getTetherableWifiRegexs();
}
public List<WifiConfiguration> loadNetworkConfigurations() throws Exception {
InputStream in = getAssets().open(ACCESS_POINT_FILE);
mParseHelper = new AccessPointParserHelper(in);
return mParseHelper.getNetworkConfigurations();
}
public HashMap<String, DhcpInfo> getDhcpInfo() throws Exception{
if (mParseHelper == null) {
InputStream in = getAssets().open(ACCESS_POINT_FILE);
mParseHelper = new AccessPointParserHelper(in);
}
return mParseHelper.getSsidToDhcpInfoHashMap();
}
private void printNetConfig(String[] configuration) {
for (int i = 0; i < configuration.length; i++) {
if (i == 0) {
log("SSID: " + configuration[0]);
} else {
log(" " + configuration[i]);
}
}
}
// for each network type, initialize network states to UNKNOWN, and no verification flag is set
public void initializeNetworkStates() {
for (int networkType = NUM_NETWORK_TYPES - 1; networkType >=0; networkType--) {
connectivityState[networkType] = new NetworkState();
log("Initialize network state for " + networkType + ": " +
connectivityState[networkType].toString());
}
}
// deposit a network state
public void recordNetworkState(int networkType, State networkState) {
log("record network state for network " + networkType +
", state is " + networkState);
connectivityState[networkType].recordState(networkState);
}
// set the state transition criteria
public void setStateTransitionCriteria(int networkType, State initState,
int transitionDir, State targetState) {
connectivityState[networkType].setStateTransitionCriteria(
initState, transitionDir, targetState);
}
// Validate the states recorded
public boolean validateNetworkStates(int networkType) {
log("validate network state for " + networkType + ": ");
return connectivityState[networkType].validateStateTransition();
}
// return result from network state validation
public String getTransitionFailureReason(int networkType) {
log("get network state transition failure reason for " + networkType + ": " +
connectivityState[networkType].toString());
return connectivityState[networkType].getReason();
}
private void notifyNetworkConnectivityChange() {
synchronized(connectivityObject) {
log("notify network connectivity changed");
connectivityObject.notifyAll();
}
}
private void notifyScanResult() {
synchronized (this) {
log("notify that scan results are available");
scanResultAvailable = true;
this.notify();
}
}
private void notifyWifiState() {
synchronized (wifiObject) {
log("notify wifi state changed");
wifiObject.notify();
}
}
private void notifyWifiAPState() {
synchronized (this) {
log("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("str: " + str +"tethRex: " + tethRex);
if (str.matches(tethRex)) {
wifiTethered = true;
}
}
}
for (Object obj: errored) {
String str = (String)obj;
for (String tethRex: mWifiRegexs) {
log("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("mWifiTetherResult: " + mWifiTetherResult);
this.notify();
}
}
// Wait for network connectivity state: CONNECTING, CONNECTED, SUSPENDED,
// DISCONNECTING, DISCONNECTED, UNKNOWN
public boolean waitForNetworkState(int networkType, State expectedState, long timeout) {
long startTime = System.currentTimeMillis();
while (true) {
if ((System.currentTimeMillis() - startTime) > timeout) {
if (mCM.getNetworkInfo(networkType).getState() != expectedState) {
return false;
} else {
// the broadcast has been sent out. the state has been changed.
log("networktype: " + networkType + " state: " +
mCM.getNetworkInfo(networkType));
return true;
}
}
log("Wait for the connectivity state for network: " + networkType +
" to be " + expectedState.toString());
synchronized (connectivityObject) {
try {
connectivityObject.wait(SHORT_TIMEOUT);
} catch (InterruptedException e) {
e.printStackTrace();
}
if ((mNetworkInfo.getType() != networkType) ||
(mNetworkInfo.getState() != expectedState)) {
log("network state for " + mNetworkInfo.getType() +
"is: " + mNetworkInfo.getState());
continue;
}
return true;
}
}
}
// Wait for Wifi state: WIFI_STATE_DISABLED, WIFI_STATE_DISABLING, WIFI_STATE_ENABLED,
// WIFI_STATE_ENALBING, WIFI_STATE_UNKNOWN
public boolean waitForWifiState(int expectedState, long timeout) {
long startTime = System.currentTimeMillis();
while (true) {
if ((System.currentTimeMillis() - startTime) > timeout) {
if (mWifiState != expectedState) {
return false;
} else {
return true;
}
}
log("Wait for wifi state to be: " + expectedState);
synchronized (wifiObject) {
try {
wifiObject.wait(SHORT_TIMEOUT);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (mWifiState != expectedState) {
log("Wifi state is: " + mWifiState);
continue;
}
return true;
}
}
}
// 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("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("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("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);
}
// Return true if device is currently connected to Wifi
public boolean isConnectedToWifi() {
return (mNetworkInfo.getType() == ConnectivityManager.TYPE_WIFI);
}
public boolean enableWifi() {
return mWifiManager.setWifiEnabled(true);
}
// Turn screen off
public void turnScreenOff() {
log("Turn screen off");
PowerManager pm =
(PowerManager) getSystemService(Context.POWER_SERVICE);
pm.goToSleep(SystemClock.uptimeMillis() + 100);
}
// Turn screen on
public void turnScreenOn() {
log("Turn screen on");
IPowerManager mPowerManagerService = IPowerManager.Stub.asInterface(
ServiceManager.getService("power"));;
try {
mPowerManagerService.userActivityWithForce(SystemClock.uptimeMillis(), false, true);
} catch (Exception e) {
log(e.toString());
}
}
/**
* @param pingServerList a list of servers that can be used for ping test, can be null
* @return true if the ping test is successful, false otherwise.
*/
public boolean pingTest(String[] pingServerList) {
boolean result = false;
String[] hostList = {"www.google.com", "www.yahoo.com",
"www.bing.com", "www.facebook.com", "www.ask.com"};
if (pingServerList != null) {
hostList = pingServerList;
}
try {
// assume the chance that all servers are down is very small
for (int i = 0; i < hostList.length; i++ ) {
String host = hostList[i];
log("Start ping test, ping " + host);
Process p = Runtime.getRuntime().exec("ping -c 10 -w 100 " + host);
int status = p.waitFor();
if (status == 0) {
// if any of the ping test is successful, return true
result = true;
break;
} else {
result = false;
log("ping " + host + " failed.");
}
}
} catch (UnknownHostException e) {
log("Ping test Fail: Unknown Host");
} catch (IOException e) {
log("Ping test Fail: IOException");
} catch (InterruptedException e) {
log("Ping test Fail: InterruptedException");
}
log("return");
return result;
}
/**
* Associate the device to given SSID
* If the device is already associated with a WiFi, disconnect and forget it,
* We don't verify whether the connection is successful or not, leave this to the test
*/
public boolean connectToWifi(String knownSSID) {
WifiConfiguration config = new WifiConfiguration();
config.SSID = knownSSID;
config.allowedKeyManagement.set(KeyMgmt.NONE);
return connectToWifiWithConfiguration(config);
}
/**
* Connect to Wi-Fi with the given configuration. Note the SSID in the configuration
* is pure string, we need to convert it to quoted string.
* @param config
* @return
*/
public boolean connectToWifiWithConfiguration(WifiConfiguration config) {
String ssid = config.SSID;
config.SSID = convertToQuotedString(ssid);
//If Wifi is not enabled, enable it
if (!mWifiManager.isWifiEnabled()) {
log("Wifi is not enabled, enable it");
mWifiManager.setWifiEnabled(true);
}
List<ScanResult> netList = mWifiManager.getScanResults();
if (netList == null) {
log("scan results are null");
// if no scan results are available, start active scan
mWifiManager.startScanActive();
mScanResultIsAvailable = false;
long startTime = System.currentTimeMillis();
while (!mScanResultIsAvailable) {
if ((System.currentTimeMillis() - startTime) > WIFI_SCAN_TIMEOUT) {
return false;
}
// wait for the scan results to be available
synchronized (this) {
// wait for the scan result to be available
try {
this.wait(WAIT_FOR_SCAN_RESULT);
} catch (InterruptedException e) {
e.printStackTrace();
}
if ((mWifiManager.getScanResults() == null) ||
(mWifiManager.getScanResults().size() <= 0)) {
continue;
}
mScanResultIsAvailable = true;
}
}
}
netList = mWifiManager.getScanResults();
for (int i = 0; i < netList.size(); i++) {
ScanResult sr= netList.get(i);
if (sr.SSID.equals(ssid)) {
log("found " + ssid + " in the scan result list");
int networkId = mWifiManager.addNetwork(config);
// Connect to network by disabling others.
mWifiManager.enableNetwork(networkId, true);
mWifiManager.saveConfiguration();
mWifiManager.reconnect();
break;
}
}
List<WifiConfiguration> netConfList = mWifiManager.getConfiguredNetworks();
if (netConfList.size() <= 0) {
log(ssid + " is not available");
return false;
}
return true;
}
/*
* Disconnect from the current AP and remove configured networks.
*/
public boolean disconnectAP() {
if (mWifiManager.isWifiEnabled()) {
//remove the current network Id
WifiInfo curWifi = mWifiManager.getConnectionInfo();
if (curWifi == null) {
return false;
}
int curNetworkId = curWifi.getNetworkId();
mWifiManager.removeNetwork(curNetworkId);
mWifiManager.saveConfiguration();
// remove other saved networks
List<WifiConfiguration> netConfList = mWifiManager.getConfiguredNetworks();
if (netConfList != null) {
log("remove configured network ids");
for (int i = 0; i < netConfList.size(); i++) {
WifiConfiguration conf = new WifiConfiguration();
conf = netConfList.get(i);
mWifiManager.removeNetwork(conf.networkId);
}
}
}
mWifiManager.saveConfiguration();
return true;
}
/**
* Disable Wifi
* @return true if Wifi is disabled successfully
*/
public boolean disableWifi() {
return mWifiManager.setWifiEnabled(false);
}
/**
* Remove configured networks and disable wifi
*/
public boolean removeConfiguredNetworksAndDisableWifi() {
if (!disconnectAP()) {
return false;
}
// Disable Wifi
if (!mWifiManager.setWifiEnabled(false)) {
return false;
}
// Wait for the actions to be completed
try {
Thread.sleep(5*1000);
} catch (InterruptedException e) {}
return true;
}
/**
* Set airplane mode
*/
public void setAirplaneMode(Context context, boolean enableAM) {
//set the airplane mode
Settings.System.putInt(context.getContentResolver(), Settings.System.AIRPLANE_MODE_ON,
enableAM ? 1 : 0);
// Post the intent
Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
intent.putExtra("state", enableAM);
context.sendBroadcast(intent);
}
protected static String convertToQuotedString(String string) {
return "\"" + string + "\"";
}
@Override
protected void onDestroy() {
super.onDestroy();
//Unregister receiver
if (mConnectivityReceiver != null) {
unregisterReceiver(mConnectivityReceiver);
}
if (mWifiReceiver != null) {
unregisterReceiver(mWifiReceiver);
}
log("onDestroy, inst=" + Integer.toHexString(hashCode()));
}
@Override
public void onStart() {
super.onStart();
mContext = this;
Bundle bundle = this.getIntent().getExtras();
if (bundle != null){
mPowerSsid = bundle.getString("power_ssid");
}
}
//A thread to set the device into airplane mode then turn on wifi.
Thread setDeviceWifiAndAirplaneThread = new Thread(new Runnable() {
public void run() {
setAirplaneMode(mContext, true);
connectToWifi(mPowerSsid);
}
});
//A thread to set the device into wifi
Thread setDeviceInWifiOnlyThread = new Thread(new Runnable() {
public void run() {
connectToWifi(mPowerSsid);
}
});
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
//This is a tricky way for the scripted monkey to
//set the device in wifi and wifi in airplane mode.
case KeyEvent.KEYCODE_1:
setDeviceWifiAndAirplaneThread.start();
break;
case KeyEvent.KEYCODE_2:
setDeviceInWifiOnlyThread.start();
break;
}
return super.onKeyDown(keyCode, event);
}
private void log(String message) {
Log.v(LOG_TAG, message);
}
}
@@ -0,0 +1,61 @@
/*
* 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.functional.ConnectivityManagerMobileTest;
import com.android.connectivitymanagertest.functional.WifiConnectionTest;
import junit.framework.TestSuite;
/**
* Instrumentation Test Runner for all connectivity manager tests.
*
* To run the connectivity manager tests:
*
* adb shell am instrument -e ssid <ssid> \
* -w com.android.connectivitymanagertest/.ConnectivityManagerTestRunner
*/
public class ConnectivityManagerTestRunner extends InstrumentationTestRunner {
@Override
public TestSuite getAllTests() {
TestSuite suite = new InstrumentationTestSuite(this);
suite.addTestSuite(ConnectivityManagerMobileTest.class);
suite.addTestSuite(WifiConnectionTest.class);
return suite;
}
@Override
public ClassLoader getLoader() {
return ConnectivityManagerTestRunner.class.getClassLoader();
}
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
String testSSID = (String) icicle.get("ssid");
if (testSSID != null) {
TEST_SSID = testSSID;
}
}
public String TEST_SSID = null;
}
@@ -0,0 +1,47 @@
/*
* 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.unit.WifiSoftAPTest;
import junit.framework.TestSuite;
/**
* Instrumentation Test Runner for all unit tests
*
* adb shell am instrument \
* -w com.android.connectivitymanagertest/.ConnectivityManagerUnitTestRunner
*/
public class ConnectivityManagerUnitTestRunner extends InstrumentationTestRunner {
@Override
public TestSuite getAllTests() {
TestSuite suite = new InstrumentationTestSuite(this);
suite.addTestSuite(WifiSoftAPTest.class);
return suite;
}
@Override
public ClassLoader getLoader() {
return ConnectivityManagerUnitTestRunner.class.getClassLoader();
}
}
@@ -0,0 +1,193 @@
/*
* 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.net.NetworkInfo.State;
import android.util.Log;
import java.util.List;
import java.util.ArrayList;
public class NetworkState {
public static final int TO_DISCONNECTION = 0; // transition to disconnection
public static final int TO_CONNECTION = 1; // transition to connection
public static final int DO_NOTHING = -1; // no state change
private final String LOG_TAG = "NetworkState";
private List<State> mStateDepository;
private State mTransitionTarget;
private int mTransitionDirection;
private String mReason = null; // record mReason of state transition failure
public NetworkState() {
mStateDepository = new ArrayList<State>();
mTransitionDirection = DO_NOTHING;
mTransitionTarget = State.UNKNOWN;
}
public NetworkState(State currentState) {
mStateDepository = new ArrayList<State>();
mStateDepository.add(currentState);
mTransitionDirection = DO_NOTHING;
mTransitionTarget = State.UNKNOWN;
}
// Reinitialize the network state
public void resetNetworkState() {
mStateDepository.clear();
mTransitionDirection = DO_NOTHING;
mTransitionTarget = State.UNKNOWN;
}
// set the transition criteria, transitionDir could be:
// DO_NOTHING, TO_CONNECTION, TO_DISCONNECTION
public void setStateTransitionCriteria(State initState, int transitionDir, State targetState) {
if (!mStateDepository.isEmpty()) {
mStateDepository.clear();
}
mStateDepository.add(initState);
mTransitionDirection = transitionDir;
mTransitionTarget = targetState;
Log.v(LOG_TAG, "setStateTransitionCriteria: " + printStates());
}
public void recordState(State currentState) {
mStateDepository.add(currentState);
}
// Verify state transition
public boolean validateStateTransition() {
Log.v(LOG_TAG, "print state depository: " + printStates());
if (mTransitionDirection == DO_NOTHING) {
if (mStateDepository.isEmpty()) {
Log.v(LOG_TAG, "no state is recorded");
mReason = "no state is recorded.";
return false;
} else if (mStateDepository.size() > 1) {
Log.v(LOG_TAG, "no broadcast is expected, " +
"instead broadcast is probably received");
mReason = "no broadcast is expected, instead broadcast is probably received";
return false;
} else if (mStateDepository.get(0) != mTransitionTarget) {
Log.v(LOG_TAG, mTransitionTarget + " is expected, but it is " +
mStateDepository.get(0));
mReason = mTransitionTarget + " is expected, but it is " + mStateDepository.get(0);
return false;
}
return true;
} else if (mTransitionDirection == TO_CONNECTION) {
Log.v(LOG_TAG, "transition to CONNECTED");
return transitToConnection();
} else {
Log.v(LOG_TAG, "transition to DISCONNECTED");
return transitToDisconnection();
}
}
/*
* Transition from CONNECTED -> DISCONNECTED:
* CONNECTED->DISCONNECTING->DISCONNECTED
* return false if any state transition is not valid and save a message in mReason
*/
public boolean transitToDisconnection () {
mReason = "states: " + printStates();
if (mStateDepository.get(0) != State.CONNECTED) {
mReason += " initial state should be CONNECTED, but it is " +
mStateDepository.get(0) + ".";
return false;
}
State lastState = mStateDepository.get(mStateDepository.size() - 1);
if ( lastState != mTransitionTarget) {
mReason += " the last state should be DISCONNECTED, but it is " + lastState;
return false;
}
for (int i = 1; i < mStateDepository.size() - 1; i++) {
State preState = mStateDepository.get(i-1);
State curState = mStateDepository.get(i);
if ((preState == State.CONNECTED) && ((curState == State.DISCONNECTING) ||
(curState == State.DISCONNECTED))) {
continue;
} else if ((preState == State.DISCONNECTING) && (curState == State.DISCONNECTED)) {
continue;
} else if ((preState == State.DISCONNECTED) && (curState == State.DISCONNECTED)) {
continue;
} else {
mReason += " Transition state from " + preState.toString() + " to " +
curState.toString() + " is not valid.";
return false;
}
}
return true;
}
// DISCONNECTED->CONNECTING->CONNECTED
public boolean transitToConnection() {
mReason = "states: " + printStates();
if (mStateDepository.get(0) != State.DISCONNECTED) {
mReason += " initial state should be DISCONNECTED, but it is " +
mStateDepository.get(0) + ".";
return false;
}
State lastState = mStateDepository.get(mStateDepository.size() - 1);
if ( lastState != mTransitionTarget) {
mReason += "The last state should be " + mTransitionTarget + ", but it is " + lastState;
return false;
}
for (int i = 1; i < mStateDepository.size(); i++) {
State preState = mStateDepository.get(i-1);
State curState = mStateDepository.get(i);
if ((preState == State.DISCONNECTED) && ((curState == State.CONNECTING) ||
(curState == State.CONNECTED) || (curState == State.DISCONNECTED))) {
continue;
} else if ((preState == State.CONNECTING) && (curState == State.CONNECTED)) {
continue;
} else if ((preState == State.CONNECTED) && (curState == State.CONNECTED)) {
continue;
} else {
mReason += " Transition state from " + preState.toString() + " to " +
curState.toString() + " is not valid.";
return false;
}
}
return true;
}
public List<State> getTransitionStates() {
return mStateDepository;
}
// return state failure mReason
public String getReason() {
return mReason;
}
public String printStates() {
StringBuilder stateBuilder = new StringBuilder("");
for (int i = 0; i < mStateDepository.size(); i++) {
stateBuilder.append(" ").append(mStateDepository.get(i).toString()).append("->");
}
return stateBuilder.toString();
}
@Override
public String toString() {
StringBuilder builder = new StringBuilder(" ");
builder.append("mTransitionDirection: ").append(Integer.toString(mTransitionDirection)).
append("; ").append("states:").
append(printStates()).append("; ");
return builder.toString();
}
}
@@ -0,0 +1,487 @@
/*
* 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.functional;
import com.android.connectivitymanagertest.ConnectivityManagerTestActivity;
import android.content.Intent;
import android.content.Context;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.app.Instrumentation;
import android.os.Handler;
import android.os.Message;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
import android.net.NetworkInfo.DetailedState;
import android.net.wifi.WifiManager;
import android.test.suitebuilder.annotation.LargeTest;
import android.test.ActivityInstrumentationTestCase2;
import com.android.connectivitymanagertest.ConnectivityManagerTestRunner;
import com.android.connectivitymanagertest.NetworkState;
import android.util.Log;
public class ConnectivityManagerMobileTest
extends ActivityInstrumentationTestCase2<ConnectivityManagerTestActivity> {
private static final String LOG_TAG = "ConnectivityManagerMobileTest";
private static final String PKG_NAME = "com.android.connectivitymanagertest";
private String TEST_ACCESS_POINT;
private ConnectivityManagerTestActivity cmActivity;
private WakeLock wl;
public ConnectivityManagerMobileTest() {
super(PKG_NAME, ConnectivityManagerTestActivity.class);
}
@Override
public void setUp() throws Exception {
super.setUp();
cmActivity = getActivity();
ConnectivityManagerTestRunner mRunner =
(ConnectivityManagerTestRunner)getInstrumentation();
TEST_ACCESS_POINT = mRunner.TEST_SSID;
PowerManager pm = (PowerManager)getInstrumentation().
getContext().getSystemService(Context.POWER_SERVICE);
wl = pm.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "CMWakeLock");
wl.acquire();
// Each test case will start with cellular connection
if (!cmActivity.waitForNetworkState(ConnectivityManager.TYPE_MOBILE, State.CONNECTED,
ConnectivityManagerTestActivity.LONG_TIMEOUT)) {
// Note: When the test fails in setUp(), tearDown is not called. In that case,
// the activity is destroyed which blocks the next test at "getActivity()".
// tearDown() is called hear to avoid that situation.
tearDown();
fail("Device is not connected to Mobile, setUp failed");
}
}
@Override
public void tearDown() throws Exception {
cmActivity.finish();
Log.v(LOG_TAG, "tear down ConnectivityManagerTestActivity");
wl.release();
cmActivity.removeConfiguredNetworksAndDisableWifi();
super.tearDown();
}
// help function to verify 3G connection
public void verifyCellularConnection() {
NetworkInfo extraNetInfo = cmActivity.mCM.getActiveNetworkInfo();
assertEquals("network type is not MOBILE", ConnectivityManager.TYPE_MOBILE,
extraNetInfo.getType());
assertTrue("not connected to cellular network", extraNetInfo.isConnected());
assertTrue("no data connection", cmActivity.mState.equals(State.CONNECTED));
}
// Test case 1: Test enabling Wifi without associating with any AP
@LargeTest
public void test3GToWifiNotification() {
// To avoid UNKNOWN state when device boots up
cmActivity.enableWifi();
try {
Thread.sleep(2 * ConnectivityManagerTestActivity.SHORT_TIMEOUT);
} catch (Exception e) {
Log.v(LOG_TAG, "exception: " + e.toString());
}
cmActivity.disableWifi();
// As Wifi stays in DISCONNECTED, the connectivity manager will not broadcast
// any network connectivity event for Wifi
NetworkInfo networkInfo = cmActivity.mCM.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
cmActivity.setStateTransitionCriteria(ConnectivityManager.TYPE_MOBILE, networkInfo.getState(),
NetworkState.DO_NOTHING, State.CONNECTED);
networkInfo = cmActivity.mCM.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
cmActivity.setStateTransitionCriteria(ConnectivityManager.TYPE_WIFI, networkInfo.getState(),
NetworkState.DO_NOTHING, State.DISCONNECTED);
// Eanble Wifi
cmActivity.enableWifi();
try {
Thread.sleep(2 * ConnectivityManagerTestActivity.SHORT_TIMEOUT);
} catch (Exception e) {
Log.v(LOG_TAG, "exception: " + e.toString());
}
// validate state and broadcast
if (!cmActivity.validateNetworkStates(ConnectivityManager.TYPE_WIFI)) {
Log.v(LOG_TAG, "the state for WIFI is changed");
Log.v(LOG_TAG, "reason: " +
cmActivity.getTransitionFailureReason(ConnectivityManager.TYPE_WIFI));
assertTrue("state validation fail", false);
}
if (!cmActivity.validateNetworkStates(ConnectivityManager.TYPE_MOBILE)) {
Log.v(LOG_TAG, "the state for MOBILE is changed");
Log.v(LOG_TAG, "reason: " +
cmActivity.getTransitionFailureReason(ConnectivityManager.TYPE_MOBILE));
assertTrue("state validation fail", false);
}
// Verify that the device is still connected to MOBILE
verifyCellularConnection();
}
// Test case 2: test connection to a given AP
@LargeTest
public void testConnectToWifi() {
assertNotNull("SSID is null", TEST_ACCESS_POINT);
//Prepare for connectivity verification
NetworkInfo networkInfo = cmActivity.mCM.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
cmActivity.setStateTransitionCriteria(ConnectivityManager.TYPE_MOBILE, networkInfo.getState(),
NetworkState.TO_DISCONNECTION, State.DISCONNECTED);
networkInfo = cmActivity.mCM.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
cmActivity.setStateTransitionCriteria(ConnectivityManager.TYPE_WIFI, networkInfo.getState(),
NetworkState.TO_CONNECTION, State.CONNECTED);
// Enable Wifi and connect to a test access point
assertTrue("failed to connect to " + TEST_ACCESS_POINT,
cmActivity.connectToWifi(TEST_ACCESS_POINT));
assertTrue(cmActivity.waitForWifiState(WifiManager.WIFI_STATE_ENABLED,
ConnectivityManagerTestActivity.LONG_TIMEOUT));
Log.v(LOG_TAG, "wifi state is enabled");
assertTrue(cmActivity.waitForNetworkState(ConnectivityManager.TYPE_WIFI, State.CONNECTED,
ConnectivityManagerTestActivity.LONG_TIMEOUT));
assertTrue(cmActivity.waitForNetworkState(ConnectivityManager.TYPE_MOBILE, State.DISCONNECTED,
ConnectivityManagerTestActivity.LONG_TIMEOUT));
// validate states
if (!cmActivity.validateNetworkStates(ConnectivityManager.TYPE_WIFI)) {
Log.v(LOG_TAG, "Wifi state transition validation failed.");
Log.v(LOG_TAG, "reason: " +
cmActivity.getTransitionFailureReason(ConnectivityManager.TYPE_WIFI));
assertTrue(false);
}
if (!cmActivity.validateNetworkStates(ConnectivityManager.TYPE_MOBILE)) {
Log.v(LOG_TAG, "Mobile state transition validation failed.");
Log.v(LOG_TAG, "reason: " +
cmActivity.getTransitionFailureReason(ConnectivityManager.TYPE_MOBILE));
assertTrue(false);
}
}
// Test case 3: connect to Wifi with known AP
@LargeTest
public void testConnectToWifWithKnownAP() {
assertNotNull("SSID is null", TEST_ACCESS_POINT);
// Connect to TEST_ACCESS_POINT
assertTrue("failed to connect to " + TEST_ACCESS_POINT,
cmActivity.connectToWifi(TEST_ACCESS_POINT));
assertTrue(cmActivity.waitForWifiState(WifiManager.WIFI_STATE_ENABLED,
ConnectivityManagerTestActivity.LONG_TIMEOUT));
assertTrue(cmActivity.waitForNetworkState(ConnectivityManager.TYPE_WIFI, State.CONNECTED,
ConnectivityManagerTestActivity.LONG_TIMEOUT));
try {
Thread.sleep(ConnectivityManagerTestActivity.SHORT_TIMEOUT);
} catch (Exception e) {
Log.v(LOG_TAG, "exception: " + e.toString());
}
// Disable Wifi
Log.v(LOG_TAG, "Disable Wifi");
if (!cmActivity.disableWifi()) {
Log.v(LOG_TAG, "disable Wifi failed");
return;
}
// Wait for the Wifi state to be DISABLED
assertTrue(cmActivity.waitForWifiState(WifiManager.WIFI_STATE_DISABLED,
ConnectivityManagerTestActivity.LONG_TIMEOUT));
assertTrue(cmActivity.waitForNetworkState(ConnectivityManager.TYPE_WIFI, State.DISCONNECTED,
ConnectivityManagerTestActivity.LONG_TIMEOUT));
assertTrue(cmActivity.waitForNetworkState(ConnectivityManager.TYPE_MOBILE, State.CONNECTED,
ConnectivityManagerTestActivity.LONG_TIMEOUT));
//Prepare for connectivity state verification
NetworkInfo networkInfo = cmActivity.mCM.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
cmActivity.setStateTransitionCriteria(ConnectivityManager.TYPE_MOBILE,
networkInfo.getState(), NetworkState.DO_NOTHING,
State.DISCONNECTED);
networkInfo = cmActivity.mCM.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
cmActivity.setStateTransitionCriteria(ConnectivityManager.TYPE_WIFI, networkInfo.getState(),
NetworkState.TO_CONNECTION, State.CONNECTED);
// Enable Wifi again
Log.v(LOG_TAG, "Enable Wifi again");
cmActivity.enableWifi();
// Wait for Wifi to be connected and mobile to be disconnected
assertTrue(cmActivity.waitForNetworkState(ConnectivityManager.TYPE_WIFI, State.CONNECTED,
ConnectivityManagerTestActivity.LONG_TIMEOUT));
assertTrue(cmActivity.waitForNetworkState(ConnectivityManager.TYPE_MOBILE, State.DISCONNECTED,
ConnectivityManagerTestActivity.LONG_TIMEOUT));
// validate wifi states
if (!cmActivity.validateNetworkStates(ConnectivityManager.TYPE_WIFI)) {
Log.v(LOG_TAG, "Wifi state transition validation failed.");
Log.v(LOG_TAG, "reason: " +
cmActivity.getTransitionFailureReason(ConnectivityManager.TYPE_WIFI));
assertTrue(false);
}
}
// Test case 4: test disconnect Wifi
@LargeTest
public void testDisconnectWifi() {
assertNotNull("SSID is null", TEST_ACCESS_POINT);
// connect to Wifi
assertTrue("failed to connect to " + TEST_ACCESS_POINT,
cmActivity.connectToWifi(TEST_ACCESS_POINT));
assertTrue(cmActivity.waitForNetworkState(ConnectivityManager.TYPE_WIFI, State.CONNECTED,
ConnectivityManagerTestActivity.LONG_TIMEOUT));
// Wait for a few seconds to avoid the state that both Mobile and Wifi is connected
try {
Thread.sleep(ConnectivityManagerTestActivity.SHORT_TIMEOUT);
} catch (Exception e) {
Log.v(LOG_TAG, "exception: " + e.toString());
}
NetworkInfo networkInfo = cmActivity.mCM.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
cmActivity.setStateTransitionCriteria(ConnectivityManager.TYPE_MOBILE,
networkInfo.getState(),
NetworkState.TO_CONNECTION,
State.CONNECTED);
networkInfo = cmActivity.mCM.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
cmActivity.setStateTransitionCriteria(ConnectivityManager.TYPE_WIFI, networkInfo.getState(),
NetworkState.TO_DISCONNECTION, State.DISCONNECTED);
// clear Wifi
cmActivity.removeConfiguredNetworksAndDisableWifi();
assertTrue(cmActivity.waitForNetworkState(ConnectivityManager.TYPE_WIFI, State.DISCONNECTED,
ConnectivityManagerTestActivity.LONG_TIMEOUT));
assertTrue(cmActivity.waitForNetworkState(ConnectivityManager.TYPE_MOBILE, State.CONNECTED,
ConnectivityManagerTestActivity.LONG_TIMEOUT));
// validate states
if (!cmActivity.validateNetworkStates(ConnectivityManager.TYPE_WIFI)) {
Log.v(LOG_TAG, "Wifi state transition validation failed.");
Log.v(LOG_TAG, "reason: " +
cmActivity.getTransitionFailureReason(ConnectivityManager.TYPE_WIFI));
assertTrue(false);
}
if (!cmActivity.validateNetworkStates(ConnectivityManager.TYPE_MOBILE)) {
Log.v(LOG_TAG, "Mobile state transition validation failed.");
Log.v(LOG_TAG, "reason: " +
cmActivity.getTransitionFailureReason(ConnectivityManager.TYPE_MOBILE));
assertTrue(false);
}
}
// Test case 5: test connectivity from 3G to airplane mode, then to 3G again
@LargeTest
public void testDataConnectionWith3GToAmTo3G() {
//Prepare for state verification
NetworkInfo networkInfo = cmActivity.mCM.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
cmActivity.setStateTransitionCriteria(ConnectivityManager.TYPE_MOBILE,
networkInfo.getState(),
NetworkState.TO_DISCONNECTION,
State.DISCONNECTED);
networkInfo = cmActivity.mCM.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
assertEquals(State.DISCONNECTED, networkInfo.getState());
cmActivity.setStateTransitionCriteria(ConnectivityManager.TYPE_WIFI, networkInfo.getState(),
NetworkState.DO_NOTHING, State.DISCONNECTED);
// Enable airplane mode
cmActivity.setAirplaneMode(getInstrumentation().getContext(), true);
try {
Thread.sleep(ConnectivityManagerTestActivity.SHORT_TIMEOUT);
} catch (Exception e) {
Log.v(LOG_TAG, "exception: " + e.toString());
}
// Validate the state transition
if (!cmActivity.validateNetworkStates(ConnectivityManager.TYPE_WIFI)) {
Log.v(LOG_TAG, "Wifi state transition validation failed.");
Log.v(LOG_TAG, "reason: " +
cmActivity.getTransitionFailureReason(ConnectivityManager.TYPE_WIFI));
assertTrue(false);
}
if (!cmActivity.validateNetworkStates(ConnectivityManager.TYPE_MOBILE)) {
Log.v(LOG_TAG, "Mobile state transition validation failed.");
Log.v(LOG_TAG, "reason: " +
cmActivity.getTransitionFailureReason(ConnectivityManager.TYPE_MOBILE));
assertTrue(false);
}
// reset state recorder
networkInfo = cmActivity.mCM.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
cmActivity.setStateTransitionCriteria(ConnectivityManager.TYPE_MOBILE,
networkInfo.getState(),
NetworkState.TO_CONNECTION,
State.CONNECTED);
networkInfo = cmActivity.mCM.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
cmActivity.setStateTransitionCriteria(ConnectivityManager.TYPE_WIFI, networkInfo.getState(),
NetworkState.DO_NOTHING, State.DISCONNECTED);
// disable airplane mode
cmActivity.setAirplaneMode(getInstrumentation().getContext(), false);
assertTrue(cmActivity.waitForNetworkState(ConnectivityManager.TYPE_MOBILE, State.CONNECTED,
ConnectivityManagerTestActivity.LONG_TIMEOUT));
// Validate the state transition
if (!cmActivity.validateNetworkStates(ConnectivityManager.TYPE_MOBILE)) {
Log.v(LOG_TAG, "Mobile state transition validation failed.");
Log.v(LOG_TAG, "reason: " +
cmActivity.getTransitionFailureReason(ConnectivityManager.TYPE_MOBILE));
assertTrue(false);
}
if (!cmActivity.validateNetworkStates(ConnectivityManager.TYPE_WIFI)) {
Log.v(LOG_TAG, "Wifi state transition validation failed.");
Log.v(LOG_TAG, "reason: " +
cmActivity.getTransitionFailureReason(ConnectivityManager.TYPE_WIFI));
assertTrue(false);
}
}
// Test case 6: test connectivity with airplane mode Wifi connected
@LargeTest
public void testDataConnectionOverAMWithWifi() {
assertNotNull("SSID is null", TEST_ACCESS_POINT);
// Eanble airplane mode
cmActivity.setAirplaneMode(getInstrumentation().getContext(), true);
assertTrue(cmActivity.waitForNetworkState(ConnectivityManager.TYPE_MOBILE, State.DISCONNECTED,
ConnectivityManagerTestActivity.LONG_TIMEOUT));
NetworkInfo networkInfo = cmActivity.mCM.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
cmActivity.setStateTransitionCriteria(ConnectivityManager.TYPE_MOBILE,
networkInfo.getState(),
NetworkState.DO_NOTHING,
State.DISCONNECTED);
networkInfo = cmActivity.mCM.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
cmActivity.setStateTransitionCriteria(ConnectivityManager.TYPE_WIFI, networkInfo.getState(),
NetworkState.TO_CONNECTION, State.CONNECTED);
// Connect to Wifi
assertTrue("failed to connect to " + TEST_ACCESS_POINT,
cmActivity.connectToWifi(TEST_ACCESS_POINT));
assertTrue(cmActivity.waitForNetworkState(ConnectivityManager.TYPE_WIFI, State.CONNECTED,
ConnectivityManagerTestActivity.LONG_TIMEOUT));
// validate state and broadcast
if (!cmActivity.validateNetworkStates(ConnectivityManager.TYPE_WIFI)) {
Log.v(LOG_TAG, "state validate for Wifi failed");
Log.v(LOG_TAG, "reason: " +
cmActivity.getTransitionFailureReason(ConnectivityManager.TYPE_WIFI));
assertTrue("State validation failed", false);
}
if (!cmActivity.validateNetworkStates(ConnectivityManager.TYPE_MOBILE)) {
Log.v(LOG_TAG, "state validation for Mobile failed");
Log.v(LOG_TAG, "reason: " +
cmActivity.getTransitionFailureReason(ConnectivityManager.TYPE_MOBILE));
assertTrue("state validation failed", false);
}
cmActivity.setAirplaneMode(getInstrumentation().getContext(), false);
}
// Test case 7: test connectivity while transit from Wifi->AM->Wifi
@LargeTest
public void testDataConnectionWithWifiToAMToWifi () {
// Connect to TEST_ACCESS_POINT
assertNotNull("SSID is null", TEST_ACCESS_POINT);
// Connect to Wifi
assertTrue("failed to connect to " + TEST_ACCESS_POINT,
cmActivity.connectToWifi(TEST_ACCESS_POINT));
assertTrue(cmActivity.waitForNetworkState(ConnectivityManager.TYPE_WIFI, State.CONNECTED,
ConnectivityManagerTestActivity.LONG_TIMEOUT));
try {
Thread.sleep(ConnectivityManagerTestActivity.SHORT_TIMEOUT);
} catch (Exception e) {
Log.v(LOG_TAG, "exception: " + e.toString());
}
// Enable airplane mode without clearing Wifi
cmActivity.setAirplaneMode(getInstrumentation().getContext(), true);
assertTrue(cmActivity.waitForNetworkState(ConnectivityManager.TYPE_WIFI, State.DISCONNECTED,
ConnectivityManagerTestActivity.LONG_TIMEOUT));
try {
Thread.sleep(ConnectivityManagerTestActivity.SHORT_TIMEOUT);
} catch (Exception e) {
Log.v(LOG_TAG, "exception: " + e.toString());
}
// Prepare for state validation
NetworkInfo networkInfo = cmActivity.mCM.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
assertEquals(State.DISCONNECTED, networkInfo.getState());
cmActivity.setStateTransitionCriteria(ConnectivityManager.TYPE_WIFI,
networkInfo.getState(), NetworkState.TO_CONNECTION, State.CONNECTED);
// Disable airplane mode
cmActivity.setAirplaneMode(getInstrumentation().getContext(), false);
assertTrue(cmActivity.waitForNetworkState(ConnectivityManager.TYPE_WIFI, State.CONNECTED,
ConnectivityManagerTestActivity.LONG_TIMEOUT));
assertTrue(cmActivity.waitForNetworkState(ConnectivityManager.TYPE_MOBILE, State.DISCONNECTED,
ConnectivityManagerTestActivity.LONG_TIMEOUT));
// validate the state transition
if (!cmActivity.validateNetworkStates(ConnectivityManager.TYPE_WIFI)) {
Log.v(LOG_TAG, "Wifi state transition validation failed.");
Log.v(LOG_TAG, "reason: " +
cmActivity.getTransitionFailureReason(ConnectivityManager.TYPE_WIFI));
assertTrue(false);
}
}
// Test case 8: test wifi state change while connecting/disconnecting to/from an AP
@LargeTest
public void testWifiStateChange () {
assertNotNull("SSID is null", TEST_ACCESS_POINT);
//Connect to TEST_ACCESS_POINT
assertTrue("failed to connect to " + TEST_ACCESS_POINT,
cmActivity.connectToWifi(TEST_ACCESS_POINT));
assertTrue(cmActivity.waitForWifiState(WifiManager.WIFI_STATE_ENABLED,
ConnectivityManagerTestActivity.LONG_TIMEOUT));
assertTrue(cmActivity.waitForNetworkState(ConnectivityManager.TYPE_WIFI, State.CONNECTED,
ConnectivityManagerTestActivity.LONG_TIMEOUT));
assertNotNull("Not associated with any AP",
cmActivity.mWifiManager.getConnectionInfo().getBSSID());
try {
Thread.sleep(ConnectivityManagerTestActivity.SHORT_TIMEOUT);
} catch (Exception e) {
Log.v(LOG_TAG, "exception: " + e.toString());
}
// Disconnect from the current AP
Log.v(LOG_TAG, "disconnect from the AP");
if (!cmActivity.disconnectAP()) {
Log.v(LOG_TAG, "failed to disconnect from " + TEST_ACCESS_POINT);
}
// Verify the connectivity state for Wifi is DISCONNECTED
assertTrue(cmActivity.waitForNetworkState(ConnectivityManager.TYPE_WIFI, State.DISCONNECTED,
ConnectivityManagerTestActivity.LONG_TIMEOUT));
if (!cmActivity.disableWifi()) {
Log.v(LOG_TAG, "disable Wifi failed");
return;
}
assertTrue(cmActivity.waitForWifiState(WifiManager.WIFI_STATE_DISABLED,
ConnectivityManagerTestActivity.LONG_TIMEOUT));
}
}
@@ -0,0 +1,256 @@
/*
* 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.functional;
import com.android.connectivitymanagertest.ConnectivityManagerStressTestRunner;
import com.android.connectivitymanagertest.ConnectivityManagerTestActivity;
import com.android.connectivitymanagertest.ConnectivityManagerTestRunner;
import com.android.connectivitymanagertest.NetworkState;
import android.R;
import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.Context;
import android.content.res.Resources;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiConfiguration.Status;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.net.ConnectivityManager;
import android.net.DhcpInfo;
import android.net.NetworkInfo;
import android.net.NetworkInfo.State;
import android.provider.Settings;
import android.test.suitebuilder.annotation.LargeTest;
import android.test.ActivityInstrumentationTestCase2;
import android.util.Log;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map.Entry;
import java.util.Set;
/**
* Test Wi-Fi connection with different configuration
* To run this tests:
* adb shell am instrument -e class
* com.android.connectivitymanagertest.functional.WifiConnectionTest
* -w com.android.connectivitymanagertest/.ConnectivityManagerTestRunner
*/
public class WifiConnectionTest
extends ActivityInstrumentationTestCase2<ConnectivityManagerTestActivity> {
private static final String TAG = "WifiConnectionTest";
private static final boolean DEBUG = false;
private List<WifiConfiguration> networks = new ArrayList<WifiConfiguration>();
private ConnectivityManagerTestActivity mAct;
private HashMap<String, DhcpInfo> hm = null;
private ConnectivityManagerTestRunner mRunner;
private ContentResolver cr;
private Set<WifiConfiguration> enabledNetworks = null;
private WifiManager mWifiManager = null;
public WifiConnectionTest() {
super(ConnectivityManagerTestActivity.class);
}
@Override
public void setUp() throws Exception {
super.setUp();
log("before we launch the test activity, we preserve all the configured networks.");
mRunner = ((ConnectivityManagerTestRunner)getInstrumentation());
mWifiManager = (WifiManager) mRunner.getContext().getSystemService(Context.WIFI_SERVICE);
enabledNetworks = getEnabledNetworks(mWifiManager.getConfiguredNetworks());
mAct = getActivity();
cr = mRunner.getContext().getContentResolver();
networks = mAct.loadNetworkConfigurations();
hm = mAct.getDhcpInfo();
if (DEBUG) {
printNetworkConfigurations();
printDhcpInfo();
}
// enable Wifi and verify wpa_supplicant is started
assertTrue("enable Wifi failed", mAct.enableWifi());
sleep(2 * ConnectivityManagerTestActivity.SHORT_TIMEOUT,
"interrupted while waiting for WPA_SUPPLICANT to start");
WifiInfo mConnection = mAct.mWifiManager.getConnectionInfo();
assertNotNull(mConnection);
assertTrue("wpa_supplicant is not started ", mAct.mWifiManager.pingSupplicant());
}
private void printNetworkConfigurations() {
log("==== print network configurations parsed from XML file ====");
log("number of access points: " + networks.size());
for (WifiConfiguration config : networks) {
log(config.toString());
}
}
private void printDhcpInfo() {
if (hm == null) {
return;
} else {
Set<Entry<String, DhcpInfo>> set = hm.entrySet();
for (Entry<String, DhcpInfo> me: set) {
log("SSID: " + me.getKey());
DhcpInfo dhcp = me.getValue();
log("IP: " + intToIpString(dhcp.ipAddress));
log("gateway: " + intToIpString(dhcp.gateway));
log("Netmask: " + intToIpString(dhcp.netmask));
log("DNS1: " + intToIpString(dhcp.dns1));
log("DNS2: " + intToIpString(dhcp.dns2));
}
}
}
@Override
public void tearDown() throws Exception {
log("tear down");
mAct.removeConfiguredNetworksAndDisableWifi();
reEnableNetworks(enabledNetworks);
mWifiManager.saveConfiguration();
super.tearDown();
}
private Set<WifiConfiguration> getEnabledNetworks(List<WifiConfiguration> configuredNetworks) {
Set<WifiConfiguration> networks = new HashSet<WifiConfiguration>();
for (WifiConfiguration wifiConfig : configuredNetworks) {
if (wifiConfig.status == Status.ENABLED || wifiConfig.status == Status.CURRENT) {
networks.add(wifiConfig);
log("remembering enabled network " + wifiConfig.SSID +
" status is " + wifiConfig.status);
}
}
return networks;
}
private void reEnableNetworks(Set<WifiConfiguration> enabledWifiConfig) {
if (!mWifiManager.isWifiEnabled()) {
log("reEnableNetworks: enable Wifi");
mWifiManager.setWifiEnabled(true);
sleep(ConnectivityManagerTestActivity.SHORT_TIMEOUT,
"interruped while waiting for wifi to be enabled");
}
for (WifiConfiguration wifiConfig : enabledWifiConfig) {
log("recover wifi configuration: " + wifiConfig.toString());
int netId = mWifiManager.addNetwork(wifiConfig);
if (wifiConfig.status == Status.CURRENT) {
mWifiManager.enableNetwork(netId, true);
mWifiManager.reconnect();
sleep(ConnectivityManagerTestActivity.SHORT_TIMEOUT,
String.format("interruped while connecting to %s", wifiConfig.SSID));
log("re-connecting to network " + wifiConfig.SSID);
}
}
List<WifiConfiguration> wifiConfigurations = mWifiManager.getConfiguredNetworks();
for (WifiConfiguration wifiConfig: wifiConfigurations) {
if (wifiConfig.status == Status.DISABLED) {
mWifiManager.enableNetwork(wifiConfig.networkId, false);
}
}
}
private String intToIpString(int i) {
return ((i & 0xFF) + "." +
((i >> 8) & 0xFF) + "." +
((i >> 16) & 0xFF) + "." +
((i >> 24) & 0xFF));
}
private void sleep(long sometime, String errorMsg) {
try {
Thread.sleep(sometime);
} catch (InterruptedException e) {
fail(errorMsg);
}
}
private void log(String message) {
Log.v(TAG, message);
}
/**
* Connect to the provided Wi-Fi network
* @param config is the network configuration
* @return true if the connection is successful.
*/
private void connectToWifi(WifiConfiguration config) {
// step 1: connect to the test access point
boolean isStaticIP = false;
if (hm.containsKey(config.SSID)) {
DhcpInfo dhcpInfo = hm.get(config.SSID);
if (dhcpInfo != null) {
isStaticIP = true;
// set the system settings:
Settings.System.putInt(cr,Settings.System.WIFI_USE_STATIC_IP, 1);
Settings.System.putString(cr, Settings.System.WIFI_STATIC_IP,
intToIpString(dhcpInfo.ipAddress));
Settings.System.putString(cr, Settings.System.WIFI_STATIC_GATEWAY,
intToIpString(dhcpInfo.gateway));
Settings.System.putString(cr, Settings.System.WIFI_STATIC_NETMASK,
intToIpString(dhcpInfo.netmask));
Settings.System.putString(cr, Settings.System.WIFI_STATIC_DNS1,
intToIpString(dhcpInfo.dns1));
Settings.System.putString(cr, Settings.System.WIFI_STATIC_DNS2,
intToIpString(dhcpInfo.dns2));
}
}
assertTrue("failed to connect to " + config.SSID,
mAct.connectToWifiWithConfiguration(config));
// step 2: verify Wifi state and network state;
assertTrue(mAct.waitForWifiState(WifiManager.WIFI_STATE_ENABLED,
ConnectivityManagerTestActivity.SHORT_TIMEOUT));
// 802.1x requires long time for connection.
assertTrue(mAct.waitForNetworkState(ConnectivityManager.TYPE_WIFI,
State.CONNECTED, 2 * ConnectivityManagerTestActivity.LONG_TIMEOUT));
// step 3: verify the current connected network is the given SSID
assertNotNull("Wifi connection returns null", mAct.mWifiManager.getConnectionInfo());
if (DEBUG) {
log("config.SSID = " + config.SSID);
log("mAct.mWifiManager.getConnectionInfo.getSSID()" +
mAct.mWifiManager.getConnectionInfo().getSSID());
}
assertTrue(config.SSID.contains(mAct.mWifiManager.getConnectionInfo().getSSID()));
if (isStaticIP) {
Settings.System.putInt(cr, Settings.System.WIFI_USE_STATIC_IP, 0);
Settings.System.putString(cr, Settings.System.WIFI_STATIC_IP, "");
Settings.System.putString(cr, Settings.System.WIFI_STATIC_GATEWAY, "");
Settings.System.putString(cr, Settings.System.WIFI_STATIC_NETMASK, "");
Settings.System.putString(cr, Settings.System.WIFI_STATIC_DNS1, "");
Settings.System.putString(cr, Settings.System.WIFI_STATIC_DNS2, "");
}
}
@LargeTest
public void testWifiConnections() {
for (int i = 0; i < networks.size(); i++) {
String ssid = networks.get(i).SSID;
log("-- START Wi-Fi connection test for SSID: " + ssid + " --");
connectToWifi(networks.get(i));
sleep(2 * ConnectivityManagerTestActivity.SHORT_TIMEOUT,
String.format("Interrupted while connecting to ", ssid));
log("-- END Wi-Fi connection test for SSID: " + ssid + " --");
}
}
}
@@ -0,0 +1,122 @@
/*
* 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 android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiConfiguration.KeyMgmt;
import android.net.wifi.WifiConfiguration.AuthAlgorithm;
import android.net.wifi.WifiManager;
import android.os.Environment;
import android.test.ActivityInstrumentationTestCase2;
import android.test.suitebuilder.annotation.LargeTest;
import android.util.Log;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
/**
* Stress the wifi driver as access point.
*/
public class WifiApStress
extends ActivityInstrumentationTestCase2<ConnectivityManagerTestActivity> {
private final static String TAG = "WifiApStress";
private static String NETWORK_ID = "AndroidAPTest";
private static String PASSWD = "androidwifi";
private final static String OUTPUT_FILE = "WifiStressTestOutput.txt";
private ConnectivityManagerTestActivity mAct;
private int iterations;
private BufferedWriter mOutputWriter = null;
private int mLastIteration = 0;
public WifiApStress() {
super(ConnectivityManagerTestActivity.class);
}
@Override
public void setUp() throws Exception {
super.setUp();
mAct = getActivity();
ConnectivityManagerStressTestRunner mRunner =
(ConnectivityManagerStressTestRunner)getInstrumentation();
iterations = mRunner.mSoftapIterations;
mAct.turnScreenOn();
}
@Override
public void tearDown() throws Exception {
// write the total number of iterations into output file
mOutputWriter = new BufferedWriter(new FileWriter(new File(
Environment.getExternalStorageDirectory(), OUTPUT_FILE)));
mOutputWriter.write(String.format("iteration %d out of %d\n", mLastIteration, iterations));
mOutputWriter.flush();
mOutputWriter.close();
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();
}
int i;
for (i = 0; i < iterations; i++) {
Log.v(TAG, "iteration: " + i);
mLastIteration = i;
// enable Wifi tethering
assertTrue(mAct.mWifiManager.setWifiApEnabled(config, true));
// Wait for wifi ap state to be ENABLED
assertTrue(mAct.waitForWifiAPState(WifiManager.WIFI_AP_STATE_ENABLED,
ConnectivityManagerTestActivity.LONG_TIMEOUT));
// Wait for wifi tethering result
assertEquals(ConnectivityManagerTestActivity.SUCCESS,
mAct.waitForTetherStateChange(2*ConnectivityManagerTestActivity.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("no uplink data connection after Wi-Fi tethering", mAct.pingTest(null));
// Disable soft AP
assertTrue(mAct.mWifiManager.setWifiApEnabled(config, false));
// Wait for 30 seconds until Wi-Fi tethering is stopped
try {
Thread.sleep(30 * 1000);
Log.v(TAG, "wait for Wi-Fi tethering to be disabled.");
} catch (Exception e) {
fail("thread in sleep is interrupted");
}
assertFalse("Wi-Fi AP disable failed", mAct.mWifiManager.isWifiApEnabled());
}
if (i == iterations) {
mLastIteration = iterations;
}
}
}
@@ -0,0 +1,285 @@
/*
* 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 android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo.State;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiConfiguration.KeyMgmt;
import android.net.wifi.WifiManager;
import android.os.Environment;
import android.os.PowerManager;
import android.provider.Settings;
import android.test.ActivityInstrumentationTestCase2;
import android.test.suitebuilder.annotation.LargeTest;
import android.util.Log;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.List;
/**
* Stress Wi-Fi connection, scanning and reconnection after sleep.
*
* To run this stress test suite, type
* adb shell am instrument -e class com.android.connectivitymanagertest.stress.WifiStressTest
* -w com.android.connectivitymanagertest/.ConnectivityManagerStressTestRunner
*/
public class WifiStressTest
extends ActivityInstrumentationTestCase2<ConnectivityManagerTestActivity> {
private final static String TAG = "WifiStressTest";
/**
* Wi-Fi idle time for default sleep policy
*/
private final static long WIFI_IDLE_MS = 60 * 1000;
/**
* The delay for Wi-Fi to get into idle, after screen off + WIFI_IDEL_MS + WIFI_IDLE_DELAY
* the Wi-Fi should be in idle mode and device should be in cellular mode.
*/
private final static long WIFI_IDLE_DELAY = 3 * 1000;
private final static String OUTPUT_FILE = "WifiStressTestOutput.txt";
private ConnectivityManagerTestActivity mAct;
private int mReconnectIterations;
private int mWifiSleepTime;
private int mScanIterations;
private String mSsid;
private String mPassword;
private ConnectivityManagerStressTestRunner mRunner;
private BufferedWriter mOutputWriter = null;
public WifiStressTest() {
super(ConnectivityManagerTestActivity.class);
}
@Override
public void setUp() throws Exception {
super.setUp();
mAct = getActivity();
mRunner = (ConnectivityManagerStressTestRunner) getInstrumentation();
mReconnectIterations = mRunner.mReconnectIterations;
mSsid = mRunner.mReconnectSsid;
mPassword = mRunner.mReconnectPassword;
mScanIterations = mRunner.mScanIterations;
mWifiSleepTime = mRunner.mSleepTime;
mOutputWriter = new BufferedWriter(new FileWriter(new File(
Environment.getExternalStorageDirectory(), OUTPUT_FILE), true));
if (!mAct.mWifiManager.isWifiEnabled()) {
if (!mAct.enableWifi()) {
tearDown();
fail("enable wifi failed.");
}
sleep(ConnectivityManagerTestActivity.SHORT_TIMEOUT,
"Interruped while waiting for wifi on");
}
}
@Override
public void tearDown() throws Exception {
log("tearDown()");
if (mOutputWriter != null) {
mOutputWriter.close();
}
super.tearDown();
}
private void writeOutput(String s) {
log("write message: " + s);
if (mOutputWriter == null) {
log("no writer attached to file " + OUTPUT_FILE);
return;
}
try {
mOutputWriter.write(s + "\n");
mOutputWriter.flush();
} catch (IOException e) {
log("failed to write output.");
}
}
public void log(String message) {
Log.v(TAG, message);
}
private void sleep(long sometime, String errorMsg) {
try {
Thread.sleep(sometime);
} catch (InterruptedException e) {
fail(errorMsg);
}
}
/**
* Stress Wifi Scanning
* TODO: test the scanning quality for each frequency band
*/
@LargeTest
public void testWifiScanning() {
int scanTimeSum = 0;
int i;
int ssidAppearInScanResultsCount = 0; // count times of given ssid appear in scan results.
for (i = 0; i < mScanIterations; i++) {
log("testWifiScanning: iteration: " + i);
int averageScanTime = 0;
if (i > 0) {
averageScanTime = scanTimeSum/i;
}
writeOutput(String.format("iteration %d out of %d",
i, mScanIterations));
writeOutput(String.format("average scanning time is %d", averageScanTime));
writeOutput(String.format("ssid appear %d out of %d scan iterations",
ssidAppearInScanResultsCount, i));
long startTime = System.currentTimeMillis();
mAct.scanResultAvailable = false;
assertTrue("start scan failed", mAct.mWifiManager.startScanActive());
while (true) {
if ((System.currentTimeMillis() - startTime) >
ConnectivityManagerTestActivity.WIFI_SCAN_TIMEOUT) {
fail("Wifi scanning takes more than " +
ConnectivityManagerTestActivity.WIFI_SCAN_TIMEOUT + " ms");
}
synchronized(mAct) {
try {
mAct.wait(ConnectivityManagerTestActivity.WAIT_FOR_SCAN_RESULT);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (mAct.scanResultAvailable) {
long scanTime = (System.currentTimeMillis() - startTime);
scanTimeSum += scanTime;
break;
}
}
}
if ((mAct.mWifiManager.getScanResults() == null) ||
(mAct.mWifiManager.getScanResults().size() <= 0)) {
fail("Scan results are empty ");
}
List<ScanResult> netList = mAct.mWifiManager.getScanResults();
if (netList != null) {
log("size of scan result list: " + netList.size());
for (int s = 0; s < netList.size(); s++) {
ScanResult sr= netList.get(s);
log(String.format("scan result for %s is: %s", sr.SSID, sr.toString()));
log(String.format("signal level for %s is %d ", sr.SSID, sr.level));
if (sr.SSID.equals(mSsid)) {
ssidAppearInScanResultsCount += 1;
log("Number of times " + mSsid + " appear in the scan list: " +
ssidAppearInScanResultsCount);
break;
}
}
}
}
if (i == mScanIterations) {
writeOutput(String.format("iteration %d out of %d",
i, mScanIterations));
writeOutput(String.format("average scanning time is %d", scanTimeSum/mScanIterations));
writeOutput(String.format("ssid appear %d out of %d scan iterations",
ssidAppearInScanResultsCount, mScanIterations));
}
}
// Stress Wifi reconnection to secure net after sleep
@LargeTest
public void testWifiReconnectionAfterSleep() {
int value = Settings.System.getInt(mRunner.getContext().getContentResolver(),
Settings.System.WIFI_SLEEP_POLICY, -1);
if (value < 0) {
Settings.System.putInt(mRunner.getContext().getContentResolver(),
Settings.System.WIFI_SLEEP_POLICY, Settings.System.WIFI_SLEEP_POLICY_DEFAULT);
log("set wifi sleep policy to default value");
}
Settings.Secure.putLong(mRunner.getContext().getContentResolver(),
Settings.Secure.WIFI_IDLE_MS, WIFI_IDLE_MS);
// Connect to a Wi-Fi network
WifiConfiguration config = new WifiConfiguration();
config.SSID = mSsid;
config.allowedKeyManagement.set(KeyMgmt.WPA_PSK);
if (mPassword.matches("[0-9A-Fa-f]{64}")) {
config.preSharedKey = mPassword;
} else {
config.preSharedKey = '"' + mPassword + '"';
}
assertTrue("Failed to connect to Wi-Fi network: " + mSsid,
mAct.connectToWifiWithConfiguration(config));
assertTrue(mAct.waitForWifiState(WifiManager.WIFI_STATE_ENABLED,
ConnectivityManagerTestActivity.SHORT_TIMEOUT));
assertTrue(mAct.waitForNetworkState(ConnectivityManager.TYPE_WIFI, State.CONNECTED,
ConnectivityManagerTestActivity.LONG_TIMEOUT));
// Run ping test to verify the data connection
assertTrue("Wi-Fi is connected, but no data connection.", mAct.pingTest(null));
int i;
for (i = 0; i < mReconnectIterations; i++) {
// 1. Put device into sleep mode
// 2. Wait for the device to sleep for sometime, verify wi-fi is off and mobile is on.
// 3. Maintain the sleep mode for some time,
// 4. Verify the Wi-Fi is still off, and data is on
// 5. Wake up the device, verify Wi-Fi is enabled and connected.
writeOutput(String.format("iteration %d out of %d",
i, mReconnectIterations));
log("iteration: " + i);
mAct.turnScreenOff();
PowerManager pm =
(PowerManager)mRunner.getContext().getSystemService(Context.POWER_SERVICE);
assertFalse(pm.isScreenOn());
sleep(WIFI_IDLE_MS, "Interruped while wait for wifi to be idle");
assertTrue("Wait for Wi-Fi to idle timeout",
mAct.waitForNetworkState(ConnectivityManager.TYPE_WIFI, State.DISCONNECTED,
6 * ConnectivityManagerTestActivity.SHORT_TIMEOUT));
// use long timeout as the pppd startup may take several retries.
assertTrue("Wait for cellular connection timeout",
mAct.waitForNetworkState(ConnectivityManager.TYPE_MOBILE, State.CONNECTED,
ConnectivityManagerTestActivity.LONG_TIMEOUT));
sleep(mWifiSleepTime + WIFI_IDLE_DELAY, "Interrupted while device is in sleep mode");
// Verify the wi-fi is still off and data connection is on
assertEquals("Wi-Fi is reconnected", State.DISCONNECTED,
mAct.mCM.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState());
assertEquals("Cellular connection is down", State.CONNECTED,
mAct.mCM.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState());
assertTrue("Mobile is connected, but no data connection.", mAct.pingTest(null));
// Turn screen on again
mAct.turnScreenOn();
assertTrue("Wait for Wi-Fi enable timeout after wake up",
mAct.waitForWifiState(WifiManager.WIFI_STATE_ENABLED,
ConnectivityManagerTestActivity.SHORT_TIMEOUT));
assertTrue("Wait for Wi-Fi connection timeout after wake up",
mAct.waitForNetworkState(ConnectivityManager.TYPE_WIFI, State.CONNECTED,
ConnectivityManagerTestActivity.LONG_TIMEOUT));
assertTrue("Reconnect to Wi-Fi network, but no data connection.", mAct.pingTest(null));
}
if (i == mReconnectIterations) {
writeOutput(String.format("iteration %d out of %d",
i, mReconnectIterations));
}
}
}
@@ -0,0 +1,86 @@
/*
* 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.unit;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.Context;
import android.app.Instrumentation;
import android.os.Handler;
import android.os.Message;
import android.net.ConnectivityManager;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiConfiguration.KeyMgmt;
import android.test.suitebuilder.annotation.LargeTest;
import android.test.AndroidTestCase;
import java.util.ArrayList;
import android.util.Log;
/**
* Test Wifi soft AP configuration
*/
public class WifiSoftAPTest extends AndroidTestCase {
private WifiManager mWifiManager;
private WifiConfiguration mWifiConfig = null;
private final String TAG = "WifiSoftAPTest";
private final int DURATION = 10000;
@Override
protected void setUp() throws Exception {
super.setUp();
mWifiManager = (WifiManager) getContext().getSystemService(Context.WIFI_SERVICE);
assertNotNull(mWifiManager);
assertTrue(mWifiManager.setWifiApEnabled(null, true));
mWifiConfig = mWifiManager.getWifiApConfiguration();
if (mWifiConfig != null) {
Log.v(TAG, "mWifiConfig is " + mWifiConfig.toString());
} else {
Log.v(TAG, "mWifiConfig is null.");
}
}
@Override
protected void tearDown() throws Exception {
Log.v(TAG, "turn off wifi tethering");
mWifiManager.setWifiApEnabled(null, false);
super.tearDown();
}
// Test case 1: Test the soft AP SSID with letters
@LargeTest
public void testApSsidWithAlphabet() {
WifiConfiguration config = new WifiConfiguration();
config.SSID = "abcdefghijklmnopqrstuvwxyz";
config.allowedKeyManagement.set(KeyMgmt.NONE);
mWifiConfig = config;
assertTrue(mWifiManager.setWifiApEnabled(mWifiConfig, true));
try {
Thread.sleep(DURATION);
} catch (InterruptedException e) {
Log.v(TAG, "exception " + e.getStackTrace());
assertFalse(true);
}
assertNotNull(mWifiManager.getWifiApConfiguration());
assertEquals("wifi AP state is not enabled", WifiManager.WIFI_AP_STATE_ENABLED,
mWifiManager.getWifiApState());
}
}