Clean up connectivity tests.
Change-Id: I407cb78aecb43aa8413835a25b4558241d69fd2e
diff --git a/core/tests/ConnectivityManagerTest/assets/accesspoints.xml b/core/tests/ConnectivityManagerTest/assets/accesspoints.xml
deleted file mode 100644
index ce6eebc..0000000
--- a/core/tests/ConnectivityManagerTest/assets/accesspoints.xml
+++ /dev/null
@@ -1,40 +0,0 @@
-<?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>
- <networkprefixlength>24</networkprefixlength>
- <dns1>192.168.14.1</dns1>
- <dns2>192.168.1.9</dns2>
- </accesspoint>
-<!-- TODO: This AP is outdated and only supports 2.4GHz.
- Need to switch to a new dual-band AP.
- Enable this test case again once the configuration is completed.
- bug#: 9470594
- <accesspoint>
- <ssid>botnet</ssid>
- <security>EAP</security>
- <eap>PEAP</eap>
- <phase2>MSCHAPV2</phase2>
- <identity>donut</identity>
- <password>android</password>
- </accesspoint>
--->
-</resources>
-
diff --git a/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/AccessPointParserHelper.java b/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/AccessPointParserHelper.java
deleted file mode 100644
index 1222c8b..0000000
--- a/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/AccessPointParserHelper.java
+++ /dev/null
@@ -1,373 +0,0 @@
-/*
- * 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.IpConfiguration.IpAssignment;
-import android.net.IpConfiguration.ProxySettings;
-import android.net.LinkAddress;
-import android.net.RouteInfo;
-import android.net.StaticIpConfiguration;
-import android.net.wifi.WifiConfiguration;
-import android.net.wifi.WifiConfiguration.AuthAlgorithm;
-import android.net.wifi.WifiConfiguration.KeyMgmt;
-import android.net.wifi.WifiEnterpriseConfig;
-
-import java.io.InputStream;
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-import java.util.ArrayList;
-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, networkprefixlength, 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,
- * networkprefixlength.
- */
-public class 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>();
-
- 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;
- }
- }
-
- DefaultHandler mHandler = new DefaultHandler() {
-
- boolean ssid = false;
- boolean security = false;
- boolean password = false;
- boolean ip = false;
- boolean gateway = false;
- boolean networkprefix = 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;
- StaticIpConfiguration mStaticIpConfiguration = null;
- InetAddress mInetAddr = 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")) {
- mStaticIpConfiguration = new StaticIpConfiguration();
- ip = true;
- }
- if (tagName.equalsIgnoreCase("gateway")) {
- gateway = true;
- }
- if (tagName.equalsIgnoreCase("networkprefixlength")) {
- networkprefix = 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")) {
- if (mStaticIpConfiguration != null) {
- config.setIpAssignment(IpAssignment.STATIC);
- config.setStaticIpConfiguration(mStaticIpConfiguration);
- } else {
- config.setIpAssignment(IpAssignment.DHCP);
- }
- config.setProxySettings(ProxySettings.NONE);
- networks.add(config);
- mStaticIpConfiguration = 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.enterpriseConfig.setPhase2Method(WifiEnterpriseConfig.Phase2.NONE);
- config.enterpriseConfig.setCaCertificateAlias("");
- config.enterpriseConfig.setClientCertificateAlias("");
- config.enterpriseConfig.setIdentity("");
- config.enterpriseConfig.setAnonymousIdentity("");
- 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.enterpriseConfig.setPassword(passwordStr);
- } else {
- throw new SAXException();
- }
- password = false;
- }
- if (eap) {
- String eapValue = new String(ch, start, length);
- if (!validateEapValue(eapValue)) {
- throw new SAXException();
- }
- if (eapValue.equals("TLS")) {
- config.enterpriseConfig.setEapMethod(WifiEnterpriseConfig.Eap.TLS);
- } else if (eapValue.equals("TTLS")) {
- config.enterpriseConfig.setEapMethod(WifiEnterpriseConfig.Eap.TTLS);
- } else if (eapValue.equals("PEAP")) {
- config.enterpriseConfig.setEapMethod(WifiEnterpriseConfig.Eap.PEAP);
- }
- eap = false;
- }
- if (phase2) {
- String phase2Value = new String(ch, start, length);
- if (phase2Value.equals("PAP")) {
- config.enterpriseConfig.setPhase2Method(WifiEnterpriseConfig.Phase2.PAP);
- } else if (phase2Value.equals("MSCHAP")) {
- config.enterpriseConfig.setPhase2Method(WifiEnterpriseConfig.Phase2.MSCHAP);
- } else if (phase2Value.equals("MSCHAPV2")) {
- config.enterpriseConfig.setPhase2Method(WifiEnterpriseConfig.Phase2.MSCHAPV2);
- } else if (phase2Value.equals("GTC")) {
- config.enterpriseConfig.setPhase2Method(WifiEnterpriseConfig.Phase2.GTC);
- }
- phase2 = false;
- }
- if (identity) {
- String identityValue = new String(ch, start, length);
- config.enterpriseConfig.setIdentity(identityValue);
- identity = false;
- }
- if (anonymousidentity) {
- String anonyId = new String(ch, start, length);
- config.enterpriseConfig.setAnonymousIdentity(anonyId);
- anonymousidentity = false;
- }
- if (cacert) {
- String cacertValue = new String(ch, start, length);
- config.enterpriseConfig.setCaCertificateAlias(cacertValue);
- cacert = false;
- }
- if (usercert) {
- String usercertValue = new String(ch, start, length);
- config.enterpriseConfig.setClientCertificateAlias(usercertValue);
- usercert = false;
- }
- if (ip) {
- try {
- String ipAddr = new String(ch, start, length);
- if (!InetAddress.isNumeric(ipAddr)) {
- throw new SAXException();
- }
- mInetAddr = InetAddress.getByName(ipAddr);
- } catch (UnknownHostException e) {
- throw new SAXException();
- }
- ip = false;
- }
- if (gateway) {
- try {
- String gwAddr = new String(ch, start, length);
- if (!InetAddress.isNumeric(gwAddr)) {
- throw new SAXException();
- }
- mStaticIpConfiguration.gateway = InetAddress.getByName(gwAddr);
- } catch (UnknownHostException e) {
- throw new SAXException();
- }
- gateway = false;
- }
- if (networkprefix) {
- try {
- int nwPrefixLength = Integer.parseInt(new String(ch, start, length));
- if ((nwPrefixLength < 0) || (nwPrefixLength > 32)) {
- throw new SAXException();
- }
- mStaticIpConfiguration.ipAddress = new LinkAddress(mInetAddr, nwPrefixLength);
- } catch (NumberFormatException e) {
- throw new SAXException();
- }
- networkprefix = false;
- }
- if (dns1) {
- try {
- String dnsAddr = new String(ch, start, length);
- if (!InetAddress.isNumeric(dnsAddr)) {
- throw new SAXException();
- }
- mStaticIpConfiguration.dnsServers.add(InetAddress.getByName(dnsAddr));
- } catch (UnknownHostException e) {
- throw new SAXException();
- }
- dns1 = false;
- }
- if (dns2) {
- try {
- String dnsAddr = new String(ch, start, length);
- if (!InetAddress.isNumeric(dnsAddr)) {
- throw new SAXException();
- }
- mStaticIpConfiguration.dnsServers.add(InetAddress.getByName(dnsAddr));
- } 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;
- }
-}
diff --git a/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/ConnectivityManagerTestBase.java b/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/ConnectivityManagerTestBase.java
index 0f9d8e9..a3c5351 100644
--- a/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/ConnectivityManagerTestBase.java
+++ b/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/ConnectivityManagerTestBase.java
@@ -26,7 +26,6 @@
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.PowerManager;
import android.os.SystemClock;
@@ -35,10 +34,8 @@
import android.view.KeyEvent;
import java.io.IOException;
-import java.io.InputStream;
import java.net.UnknownHostException;
import java.util.List;
-import java.util.regex.Pattern;
/**
@@ -52,8 +49,6 @@
*/
public class ConnectivityManagerTestBase extends InstrumentationTestCase {
- private static final String LOG_TAG = "ConnectivityManagerTestBase";
- private static final String ACCESS_POINT_FILE = "accesspoints.xml";
private static final String PING_IP_ADDR = "8.8.8.8";
protected static final int WAIT_FOR_SCAN_RESULT = 10 * 1000; //10 seconds
@@ -69,9 +64,10 @@
protected static final int FAILURE = 1;
protected static final int INIT = -1;
+ protected final String mLogTag;
+
private ConnectivityReceiver mConnectivityReceiver = null;
private WifiReceiver mWifiReceiver = null;
- private AccessPointParserHelper mParseHelper = null;
private long mLastConnectivityChangeTime = -1;
protected ConnectivityManager mCm;
@@ -82,6 +78,11 @@
/* Control Wifi States */
public WifiManager mWifiManager;
+ public ConnectivityManagerTestBase(String logTag) {
+ super();
+ mLogTag = logTag;
+ }
+
protected long getLastConnectivityChangeTime() {
return mLastConnectivityChangeTime;
}
@@ -94,7 +95,7 @@
@Override
public void onReceive(Context context, Intent intent) {
mLastConnectivityChangeTime = SystemClock.uptimeMillis();
- log("ConnectivityReceiver: " + intent);
+ logv("ConnectivityReceiver: " + intent);
String action = intent.getAction();
if (!action.equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
Log.v("ConnectivityReceiver", "onReceive() called with " + intent);
@@ -108,7 +109,7 @@
String action = intent.getAction();
Log.v("WifiReceiver", "onReceive() is calleld with " + intent);
if (action.equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
- log("scan results are available");
+ logv("scan results are available");
synchronized (mWifiScanResultLock) {
mLastScanResult = mWifiManager.getScanResults();
mWifiScanResultLock.notifyAll();
@@ -130,7 +131,7 @@
if (mWifiManager.isWifiApEnabled()) {
// if soft AP is enabled, disable it
mWifiManager.setWifiApEnabled(null, false);
- log("Disable soft ap");
+ logv("Disable soft ap");
}
// register a connectivity receiver for CONNECTIVITY_ACTION;
@@ -148,32 +149,25 @@
mIntentFilter.addAction(ConnectivityManager.ACTION_TETHER_STATE_CHANGED);
mContext.registerReceiver(mWifiReceiver, mIntentFilter);
- log("Clear Wifi before we start the test.");
+ logv("Clear Wifi before we start the test.");
removeConfiguredNetworksAndDisableWifi();
}
- protected List<WifiConfiguration> loadNetworkConfigurations() throws Exception {
- InputStream in = mContext.getAssets().open(ACCESS_POINT_FILE);
- mParseHelper = new AccessPointParserHelper(in);
- return mParseHelper.getNetworkConfigurations();
- }
-
// wait for network connectivity state: CONNECTING, CONNECTED, SUSPENDED, DISCONNECTING,
// DISCONNECTED, UNKNOWN
protected boolean waitForNetworkState(int networkType, State expectedState, long timeout) {
long startTime = SystemClock.uptimeMillis();
while (true) {
NetworkInfo ni = mCm.getNetworkInfo(networkType);
- String niString = ni == null ? "null" : ni.toString();
if (ni != null && expectedState.equals(ni.getState())) {
- log("waitForNetworkState success: " + niString);
+ logv("waitForNetworkState success: %s", ni);
return true;
}
if ((SystemClock.uptimeMillis() - startTime) > timeout) {
- log("waitForNetworkState timeout: " + niString);
+ logv("waitForNetworkState timeout: %s", ni);
return false;
}
- log("waitForNetworkState interim: " + niString);
+ logv("waitForNetworkState interim: %s", ni);
SystemClock.sleep(SHORT_TIMEOUT);
}
}
@@ -185,16 +179,14 @@
while (true) {
int state = mWifiManager.getWifiState();
if (state == expectedState) {
- log("waitForWifiState success: state=" + state);
+ logv("waitForWifiState success: state=" + state);
return true;
}
if ((SystemClock.uptimeMillis() - startTime) > timeout) {
- log(String.format("waitForWifiState timeout: expected=%d, actual=%d",
- expectedState, state));
+ logv("waitForWifiState timeout: expected=%d, actual=%d", expectedState, state);
return false;
}
- log(String.format("waitForWifiState interim: expected=%d, actual=%d",
- expectedState, state));
+ logv("waitForWifiState interim: expected=%d, actual=%d", expectedState, state);
SystemClock.sleep(SHORT_TIMEOUT);
}
}
@@ -206,15 +198,15 @@
while (true) {
int state = mWifiManager.getWifiApState();
if (state == expectedState) {
- log("waitForWifiAPState success: state=" + state);
+ logv("waitForWifiAPState success: state=" + state);
return true;
}
if ((SystemClock.uptimeMillis() - startTime) > timeout) {
- log(String.format("waitForWifiAPState timeout: expected=%d, actual=%d",
+ logv(String.format("waitForWifiAPState timeout: expected=%d, actual=%d",
expectedState, state));
return false;
}
- log(String.format("waitForWifiAPState interim: expected=%d, actual=%d",
+ logv(String.format("waitForWifiAPState interim: expected=%d, actual=%d",
expectedState, state));
SystemClock.sleep(SHORT_TIMEOUT);
}
@@ -269,7 +261,7 @@
// Turn screen off
protected void turnScreenOff() {
- log("Turn screen off");
+ logv("Turn screen off");
PowerManager pm =
(PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
pm.goToSleep(SystemClock.uptimeMillis());
@@ -277,7 +269,7 @@
// Turn screen on
protected void turnScreenOn() {
- log("Turn screen on");
+ logv("Turn screen on");
PowerManager pm =
(PowerManager) mContext.getSystemService(Context.POWER_SERVICE);
pm.wakeUp(SystemClock.uptimeMillis());
@@ -305,7 +297,7 @@
// 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);
+ logv("Start ping test, ping " + host);
Process p = Runtime.getRuntime().exec("ping -c 10 -w 100 " + host);
int status = p.waitFor();
if (status == 0) {
@@ -314,11 +306,11 @@
}
}
} catch (UnknownHostException e) {
- log("Ping test Fail: Unknown Host");
+ logv("Ping test Fail: Unknown Host");
} catch (IOException e) {
- log("Ping test Fail: IOException");
+ logv("Ping test Fail: IOException");
} catch (InterruptedException e) {
- log("Ping test Fail: InterruptedException");
+ logv("Ping test Fail: InterruptedException");
}
}
// ping test timeout
@@ -331,29 +323,22 @@
* We don't verify whether the connection is successful or not, leave this to the test
*/
protected boolean connectToWifi(String knownSSID) {
- WifiConfiguration config = new WifiConfiguration();
- config.SSID = knownSSID;
- config.allowedKeyManagement.set(KeyMgmt.NONE);
+ WifiConfiguration config = WifiConfigurationHelper.createOpenConfig(knownSSID);
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
*/
protected 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");
+ logv("Wifi is not enabled, enable it");
mWifiManager.setWifiEnabled(true);
// wait for the wifi state change before start scanning.
if (!waitForWifiState(WifiManager.WIFI_STATE_ENABLED, LONG_TIMEOUT)) {
- log("wait for WIFI_STATE_ENABLED failed");
+ logv("wait for WIFI_STATE_ENABLED failed");
return false;
}
}
@@ -361,10 +346,13 @@
// Save network configuration and connect to network without scanning
mWifiManager.connect(config,
new WifiManager.ActionListener() {
+ @Override
public void onSuccess() {
}
+
+ @Override
public void onFailure(int reason) {
- log("connect failure " + reason);
+ logv("connect failure " + reason);
}
});
return true;
@@ -376,25 +364,28 @@
protected boolean disconnectAP() {
// remove saved networks
if (!mWifiManager.isWifiEnabled()) {
- log("Enabled wifi before remove configured networks");
+ logv("Enabled wifi before remove configured networks");
mWifiManager.setWifiEnabled(true);
SystemClock.sleep(SHORT_TIMEOUT);
}
List<WifiConfiguration> wifiConfigList = mWifiManager.getConfiguredNetworks();
if (wifiConfigList == null) {
- log("no configuration list is null");
+ logv("no configuration list is null");
return true;
}
- log("size of wifiConfigList: " + wifiConfigList.size());
+ logv("size of wifiConfigList: " + wifiConfigList.size());
for (WifiConfiguration wifiConfig: wifiConfigList) {
- log("remove wifi configuration: " + wifiConfig.networkId);
+ logv("remove wifi configuration: " + wifiConfig.networkId);
int netId = wifiConfig.networkId;
mWifiManager.forget(netId, new WifiManager.ActionListener() {
+ @Override
public void onSuccess() {
}
+
+ @Override
public void onFailure(int reason) {
- log("Failed to forget " + reason);
+ logv("Failed to forget " + reason);
}
});
}
@@ -431,15 +422,14 @@
long startTime = SystemClock.uptimeMillis();
while (true) {
NetworkInfo ni = mCm.getActiveNetworkInfo();
- String niString = ni == null ? "null" : ni.toString();
if (ni != null && ni.isConnected()) {
return true;
}
if ((SystemClock.uptimeMillis() - startTime) > timeout) {
- log("waitForActiveNetworkConnection timeout: " + niString);
+ logv("waitForActiveNetworkConnection timeout: %s", ni);
return false;
}
- log("waitForActiveNetworkConnection interim: " + niString);
+ logv("waitForActiveNetworkConnection interim: %s", ni);
SystemClock.sleep(SHORT_TIMEOUT);
}
}
@@ -451,12 +441,11 @@
if (ni == null) {
return true;
}
- String niString = ni.toString();
if ((SystemClock.uptimeMillis() - startTime) > timeout) {
- log("waitForActiveNetworkConnection timeout: " + niString);
+ logv("waitForActiveNetworkConnection timeout: %s", ni);
return false;
}
- log("waitForActiveNetworkConnection interim: " + niString);
+ logv("waitForActiveNetworkConnection interim: %s", ni);
SystemClock.sleep(SHORT_TIMEOUT);
}
}
@@ -467,12 +456,9 @@
try {
Process proc = Runtime.getRuntime().exec(new String[]{
"/system/bin/ping", "-W", "30", "-c", "1", PING_IP_ADDR});
- int exitCode = proc.waitFor();
- return exitCode == 0;
- } catch (InterruptedException ie) {
- Log.e(LOG_TAG, "InterruptedException while waiting for ping");
- } catch (IOException ioe) {
- Log.e(LOG_TAG, "IOException during ping", ioe);
+ return proc.waitFor() == 0;
+ } catch (InterruptedException | IOException e) {
+ Log.e(mLogTag, "Ping failed", e);
}
return false;
}
@@ -489,8 +475,8 @@
super.tearDown();
}
- private void log(String message) {
- Log.v(LOG_TAG, message);
+ protected void logv(String format, Object... args) {
+ Log.v(mLogTag, String.format(format, args));
}
/**
@@ -506,22 +492,10 @@
// step 2: verify Wifi state and network state;
assertTrue("wifi state not connected with " + config.SSID,
waitForNetworkState(ConnectivityManager.TYPE_WIFI,
- State.CONNECTED, LONG_TIMEOUT));
+ State.CONNECTED, WIFI_CONNECTION_TIMEOUT));
// step 3: verify the current connected network is the given SSID
assertNotNull("no active wifi info", mWifiManager.getConnectionInfo());
assertEquals("SSID mismatch", config.SSID, mWifiManager.getConnectionInfo().getSSID());
}
-
- /**
- * checks if the input is a hexadecimal string of given length
- *
- * @param input string to be checked
- * @param length required length of the string
- * @return
- */
- protected static boolean isHex(String input, int length) {
- Pattern p = Pattern.compile(String.format("[0-9A-Fa-f]{%d}", length));
- return p.matcher(input).matches();
- }
}
diff --git a/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/WifiConfigurationHelper.java b/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/WifiConfigurationHelper.java
new file mode 100644
index 0000000..f0a8367
--- /dev/null
+++ b/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/WifiConfigurationHelper.java
@@ -0,0 +1,364 @@
+/*
+ * 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.IpConfiguration.IpAssignment;
+import android.net.IpConfiguration.ProxySettings;
+import android.net.LinkAddress;
+import android.net.StaticIpConfiguration;
+import android.net.wifi.WifiConfiguration;
+import android.net.wifi.WifiConfiguration.AuthAlgorithm;
+import android.net.wifi.WifiConfiguration.KeyMgmt;
+import android.net.wifi.WifiEnterpriseConfig;
+
+import org.json.JSONArray;
+import org.json.JSONException;
+import org.json.JSONObject;
+
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Helper for dealing with creating {@link WifiConfiguration} objects.
+ */
+public class WifiConfigurationHelper {
+ private static final int NONE = 0;
+ private static final int WEP = 1;
+ private static final int PSK = 2;
+ private static final int EAP = 3;
+
+ /**
+ * Private constructor since this a static class.
+ */
+ private WifiConfigurationHelper() {}
+
+ /**
+ * Create a {@link WifiConfiguration} for an open network
+ *
+ * @param ssid The SSID of the wifi network
+ * @return The {@link WifiConfiguration}
+ */
+ public static WifiConfiguration createOpenConfig(String ssid) {
+ WifiConfiguration config = createGenericConfig(ssid);
+
+ config.allowedKeyManagement.set(KeyMgmt.NONE);
+ return config;
+ }
+
+ /**
+ * Create a {@link WifiConfiguration} for a WEP secured network
+ *
+ * @param ssid The SSID of the wifi network
+ * @param password Either a 10, 26, or 58 character hex string or the plain text password
+ * @return The {@link WifiConfiguration}
+ */
+ public static WifiConfiguration createWepConfig(String ssid, String password) {
+ WifiConfiguration config = createGenericConfig(ssid);
+
+ if (isHex(password, 10) || isHex(password, 26) || isHex(password, 58)) {
+ config.wepKeys[0] = password;
+ } else {
+ config.wepKeys[0] = quotedString(password);
+ }
+
+ config.allowedKeyManagement.set(KeyMgmt.NONE);
+ config.allowedAuthAlgorithms.set(AuthAlgorithm.OPEN);
+ config.allowedAuthAlgorithms.set(AuthAlgorithm.SHARED);
+ return config;
+ }
+
+ /**
+ * Create a {@link WifiConfiguration} for a PSK secured network
+ *
+ * @param ssid The SSID of the wifi network
+ * @param password Either a 64 character hex string or the plain text password
+ * @return The {@link WifiConfiguration}
+ */
+ public static WifiConfiguration createPskConfig(String ssid, String password) {
+ WifiConfiguration config = createGenericConfig(ssid);
+
+ if (isHex(password, 64)) {
+ config.preSharedKey = password;
+ } else {
+ config.preSharedKey = quotedString(password);
+ }
+ config.allowedKeyManagement.set(KeyMgmt.WPA_PSK);
+ return config;
+ }
+
+ /**
+ * Create a {@link WifiConfiguration} for an EAP secured network
+ *
+ * @param ssid The SSID of the wifi network
+ * @param password The password
+ * @param eapMethod The EAP method
+ * @param phase2 The phase 2 method or null
+ * @param identity The identity or null
+ * @param anonymousIdentity The anonymous identity or null
+ * @param caCert The CA certificate or null
+ * @param clientCert The client certificate or null
+ * @return The {@link WifiConfiguration}
+ */
+ public static WifiConfiguration createEapConfig(String ssid, String password, int eapMethod,
+ Integer phase2, String identity, String anonymousIdentity, String caCert,
+ String clientCert) {
+ WifiConfiguration config = new WifiConfiguration();
+ config.SSID = quotedString(ssid);
+
+ config.allowedKeyManagement.set(KeyMgmt.WPA_EAP);
+ config.allowedKeyManagement.set(KeyMgmt.IEEE8021X);
+
+ // Set defaults
+ if (phase2 == null) phase2 = WifiEnterpriseConfig.Phase2.NONE;
+ if (identity == null) identity = "";
+ if (anonymousIdentity == null) anonymousIdentity = "";
+ if (caCert == null) caCert = "";
+ if (clientCert == null) clientCert = "";
+
+ config.enterpriseConfig.setPassword(password);
+ config.enterpriseConfig.setEapMethod(eapMethod);
+ config.enterpriseConfig.setPhase2Method(phase2);
+ config.enterpriseConfig.setIdentity(identity);
+ config.enterpriseConfig.setAnonymousIdentity(anonymousIdentity);
+ config.enterpriseConfig.setCaCertificateAlias(caCert);
+ config.enterpriseConfig.setClientCertificateAlias(clientCert);
+ return config;
+ }
+
+ /**
+ * Create a generic {@link WifiConfiguration} used by the other create methods.
+ */
+ private static WifiConfiguration createGenericConfig(String ssid) {
+ WifiConfiguration config = new WifiConfiguration();
+ config.SSID = quotedString(ssid);
+ config.setIpAssignment(IpAssignment.DHCP);
+ config.setProxySettings(ProxySettings.NONE);
+ return config;
+ }
+
+ /**
+ * Parse a JSON string for WiFi configurations stored as a JSON string.
+ * <p>
+ * This json string should be a list of dictionaries, with each dictionary containing a single
+ * wifi configuration. The wifi configuration requires the fields "ssid" and "security" with
+ * security being one of NONE, WEP, PSK, or EAP. If WEP, PSK, or EAP are selected, the field
+ * "password" must also be provided. If EAP is selected, then the fiels "eap", "phase2",
+ * "identity", "ananymous_identity", "ca_cert", and "client_cert" are also required. Lastly,
+ * static IP settings are also supported. If the field "ip" is set, then the fields "gateway",
+ * "prefix_length", "dns1", and "dns2" are required.
+ * </p>
+ * @throws IllegalArgumentException if the input string was not valid JSON or if any mandatory
+ * fields are missing.
+ */
+ public static List<WifiConfiguration> parseJson(String in) {
+ try {
+ JSONArray jsonConfigs = new JSONArray(in);
+ List<WifiConfiguration> wifiConfigs = new ArrayList<>(jsonConfigs.length());
+
+ for (int i = 0; i < jsonConfigs.length(); i++) {
+ JSONObject jsonConfig = jsonConfigs.getJSONObject(i);
+
+ wifiConfigs.add(getWifiConfiguration(jsonConfig));
+ }
+ return wifiConfigs;
+ } catch (JSONException e) {
+ throw new IllegalArgumentException(e);
+ }
+ }
+
+ /**
+ * Parse a {@link JSONObject} and return the wifi configuration.
+ *
+ * @throws IllegalArgumentException if any mandatory fields are missing.
+ */
+ private static WifiConfiguration getWifiConfiguration(JSONObject jsonConfig)
+ throws JSONException {
+ String ssid = jsonConfig.getString("ssid");
+ String password = null;
+ WifiConfiguration config;
+
+ int securityType = getSecurityType(jsonConfig.getString("security"));
+ switch (securityType) {
+ case NONE:
+ config = createOpenConfig(ssid);
+ break;
+ case WEP:
+ password = jsonConfig.getString("password");
+ config = createWepConfig(ssid, password);
+ break;
+ case PSK:
+ password = jsonConfig.getString("password");
+ config = createPskConfig(ssid, password);
+ break;
+ case EAP:
+ password = jsonConfig.getString("password");
+ int eapMethod = getEapMethod(jsonConfig.getString("eap"));
+ Integer phase2 = null;
+ if (jsonConfig.has("phase2")) {
+ phase2 = getPhase2(jsonConfig.getString("phase2"));
+ }
+ String identity = null;
+ if (jsonConfig.has("identity")) {
+ identity = jsonConfig.getString("identity");
+ }
+ String anonymousIdentity = null;
+ if (jsonConfig.has("anonymous_identity")) {
+ anonymousIdentity = jsonConfig.getString("anonymous_identity");
+ }
+ String caCert = null;
+ if (jsonConfig.has("ca_cert")) {
+ caCert = (jsonConfig.getString("ca_cert"));
+ }
+ String clientCert = null;
+ if (jsonConfig.has("client_cert")) {
+ clientCert = jsonConfig.getString("client_cert");
+ }
+ config = createEapConfig(ssid, password, eapMethod, phase2, identity,
+ anonymousIdentity, caCert, clientCert);
+ break;
+ default:
+ // Should never reach here as getSecurityType will already throw an exception
+ throw new IllegalArgumentException();
+ }
+
+ if (jsonConfig.has("ip")) {
+ StaticIpConfiguration staticIpConfig = new StaticIpConfiguration();
+
+ InetAddress ipAddress = getInetAddress(jsonConfig.getString("ip"));
+ int prefixLength = getPrefixLength(jsonConfig.getInt("prefix_length"));
+ staticIpConfig.ipAddress = new LinkAddress(ipAddress, prefixLength);
+ staticIpConfig.gateway = getInetAddress(jsonConfig.getString("gateway"));
+ staticIpConfig.dnsServers.add(getInetAddress(jsonConfig.getString("dns1")));
+ staticIpConfig.dnsServers.add(getInetAddress(jsonConfig.getString("dns2")));
+
+ config.setIpAssignment(IpAssignment.STATIC);
+ config.setStaticIpConfiguration(staticIpConfig);
+ } else {
+ config.setIpAssignment(IpAssignment.DHCP);
+ }
+
+ config.setProxySettings(ProxySettings.NONE);
+ return config;
+ }
+
+ private static String quotedString(String s) {
+ return String.format("\"%s\"", s);
+ }
+
+ /**
+ * Get the security type from a string.
+ *
+ * @throws IllegalArgumentException if the string is not a supported security type.
+ */
+ private static int getSecurityType(String security) {
+ if ("NONE".equalsIgnoreCase(security)) {
+ return NONE;
+ }
+ if ("WEP".equalsIgnoreCase(security)) {
+ return WEP;
+ }
+ if ("PSK".equalsIgnoreCase(security)) {
+ return PSK;
+ }
+ if ("EAP".equalsIgnoreCase(security)) {
+ return EAP;
+ }
+ throw new IllegalArgumentException("Security type must be one of NONE, WEP, PSK, or EAP");
+ }
+
+ /**
+ * Get the EAP method from a string.
+ *
+ * @throws IllegalArgumentException if the string is not a supported EAP method.
+ */
+ private static int getEapMethod(String eapMethod) {
+ if ("TLS".equalsIgnoreCase(eapMethod)) {
+ return WifiEnterpriseConfig.Eap.TLS;
+ }
+ if ("TTLS".equalsIgnoreCase(eapMethod)) {
+ return WifiEnterpriseConfig.Eap.TTLS;
+ }
+ if ("PEAP".equalsIgnoreCase(eapMethod)) {
+ return WifiEnterpriseConfig.Eap.PEAP;
+ }
+ throw new IllegalArgumentException("EAP method must be one of TLS, TTLS, or PEAP");
+ }
+
+ /**
+ * Get the phase 2 method from a string.
+ *
+ * @throws IllegalArgumentException if the string is not a supported phase 2 method.
+ */
+ private static int getPhase2(String phase2) {
+ if ("PAP".equalsIgnoreCase(phase2)) {
+ return WifiEnterpriseConfig.Phase2.PAP;
+ }
+ if ("MSCHAP".equalsIgnoreCase(phase2)) {
+ return WifiEnterpriseConfig.Phase2.MSCHAP;
+ }
+ if ("MSCHAPV2".equalsIgnoreCase(phase2)) {
+ return WifiEnterpriseConfig.Phase2.MSCHAPV2;
+ }
+ if ("GTC".equalsIgnoreCase(phase2)) {
+ return WifiEnterpriseConfig.Phase2.GTC;
+ }
+ throw new IllegalArgumentException("Phase2 must be one of PAP, MSCHAP, MSCHAPV2, or GTC");
+ }
+
+ /**
+ * Get an {@link InetAddress} from a string
+ *
+ * @throws IllegalArgumentException if the string is not a valid IP address.
+ */
+ private static InetAddress getInetAddress(String ipAddress) {
+ if (!InetAddress.isNumeric(ipAddress)) {
+ throw new IllegalArgumentException(
+ String.format("IP address %s is not numeric", ipAddress));
+ }
+
+ try {
+ return InetAddress.getByName(ipAddress);
+ } catch (UnknownHostException e) {
+ throw new IllegalArgumentException(
+ String.format("IP address %s could not be resolved", ipAddress));
+ }
+ }
+
+ /**
+ * Get the prefix length from an int.
+ *
+ * @throws IllegalArgumentException if the prefix length is less than 0 or greater than 32.
+ */
+ private static int getPrefixLength(int prefixLength) {
+ if (prefixLength < 0 || prefixLength > 32) {
+ throw new IllegalArgumentException("Prefix length cannot be less than 0 or more than 32");
+ }
+ return prefixLength;
+ }
+
+ /**
+ * Utility method to check if a given string is a hexadecimal string of given length
+ */
+ public static boolean isHex(String input, int length) {
+ if (input == null || length < 0) {
+ return false;
+ }
+ return input.matches(String.format("[0-9A-Fa-f]{%d}", length));
+ }
+}
diff --git a/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/functional/ConnectivityManagerMobileTest.java b/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/functional/ConnectivityManagerMobileTest.java
index 01995c7..b280106 100644
--- a/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/functional/ConnectivityManagerMobileTest.java
+++ b/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/functional/ConnectivityManagerMobileTest.java
@@ -23,14 +23,15 @@
import android.os.SystemClock;
import android.provider.Settings;
import android.test.suitebuilder.annotation.LargeTest;
-import android.util.Log;
import com.android.connectivitymanagertest.ConnectivityManagerTestBase;
import com.android.connectivitymanagertest.ConnectivityManagerTestRunner;
-public class ConnectivityManagerMobileTest extends
- ConnectivityManagerTestBase {
- private static final String TAG = "ConnectivityManagerMobileTest";
+public class ConnectivityManagerMobileTest extends ConnectivityManagerTestBase {
+
+ public ConnectivityManagerMobileTest() {
+ super(ConnectivityManagerMobileTest.class.getSimpleName());
+ }
private String mTestAccessPoint;
private boolean mWifiOnlyFlag;
@@ -46,7 +47,7 @@
// Each test case will start with cellular connection
if (Settings.Global.getInt(getInstrumentation().getContext().getContentResolver(),
Settings.Global.AIRPLANE_MODE_ON) == 1) {
- log("airplane is not disabled, disable it.");
+ logv("airplane is not disabled, disable it.");
mCm.setAirplaneMode(false);
}
@@ -77,16 +78,14 @@
assertTrue("not connected to cellular network", extraNetInfo.isConnected());
}
- private void log(String message) {
- Log.v(TAG, message);
- }
+
// Test case 1: Test enabling Wifi without associating with any AP, no broadcast on network
// event should be expected.
@LargeTest
public void test3GToWifiNotification() {
if (mWifiOnlyFlag) {
- Log.v(TAG, getName() + " is excluded for wifi-only test");
+ logv(getName() + " is excluded for wifi-only test");
return;
}
@@ -225,7 +224,7 @@
@LargeTest
public void testDataConnectionWith3GToAmTo3G() {
if (mWifiOnlyFlag) {
- Log.v(TAG, getName() + " is excluded for wifi-only test");
+ logv(getName() + " is excluded for wifi-only test");
return;
}
// disable wifi
diff --git a/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/functional/WifiAssociationTest.java b/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/functional/WifiAssociationTest.java
index eb75b0d..c2b80dc 100644
--- a/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/functional/WifiAssociationTest.java
+++ b/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/functional/WifiAssociationTest.java
@@ -21,16 +21,15 @@
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiConfiguration.AuthAlgorithm;
import android.net.wifi.WifiConfiguration.GroupCipher;
-import android.net.wifi.WifiConfiguration.KeyMgmt;
import android.net.wifi.WifiConfiguration.PairwiseCipher;
import android.net.wifi.WifiConfiguration.Protocol;
import android.net.wifi.WifiInfo;
import android.os.Bundle;
import android.test.suitebuilder.annotation.LargeTest;
-import android.util.Log;
import com.android.connectivitymanagertest.ConnectivityManagerTestBase;
import com.android.connectivitymanagertest.WifiAssociationTestRunner;
+import com.android.connectivitymanagertest.WifiConfigurationHelper;
/**
* Test Wi-Fi connection with different configuration
@@ -40,7 +39,6 @@
* -w com.android.connectivitymanagertest/.WifiAssociationTestRunner"
*/
public class WifiAssociationTest extends ConnectivityManagerTestBase {
- private static final String TAG = "WifiAssociationTest";
private String mSsid = null;
private String mPassword = null;
private String mSecurityType = null;
@@ -51,6 +49,10 @@
OPEN, WEP64, WEP128, WPA_TKIP, WPA2_AES
}
+ public WifiAssociationTest() {
+ super(WifiAssociationTest.class.getSimpleName());
+ }
+
@Override
protected void setUp() throws Exception {
super.setUp();
@@ -77,90 +79,58 @@
private void validateFrequencyBand() {
if (mFrequencyBand != null) {
int currentFreq = mWifiManager.getFrequencyBand();
- Log.v(TAG, "read frequency band: " + currentFreq);
+ logv("read frequency band: " + currentFreq);
assertEquals("specified frequency band does not match operational band of WifiManager",
currentFreq, mBand);
}
}
- private void log(String message) {
- Log.v(TAG, message);
- }
-
@LargeTest
public void testWifiAssociation() {
assertNotNull("no test ssid", mSsid);
- WifiConfiguration config = new WifiConfiguration();
- config.SSID = mSsid;
+ WifiConfiguration config = null;
SECURITY_TYPE security = SECURITY_TYPE.valueOf(mSecurityType);
- log("Security type is " + security.toString());
+ logv("Security type is " + security.toString());
switch (security) {
// set network configurations
case OPEN:
- config.allowedKeyManagement.set(KeyMgmt.NONE);
+ config = WifiConfigurationHelper.createOpenConfig(mSsid);
break;
case WEP64:
assertNotNull("password is empty", mPassword);
- config.allowedKeyManagement.set(KeyMgmt.NONE);
- config.allowedAuthAlgorithms.set(AuthAlgorithm.OPEN);
- config.allowedAuthAlgorithms.set(AuthAlgorithm.SHARED);
+ // always use hex pair for WEP-40
+ assertTrue(WifiConfigurationHelper.isHex(mPassword, 10));
+ config = WifiConfigurationHelper.createWepConfig(mSsid, mPassword);
config.allowedGroupCiphers.set(GroupCipher.WEP40);
- if (mPassword != null) {
- // always use hex pair for WEP-40
- if (isHex(mPassword, 10)) {
- config.wepKeys[0] = mPassword;
- } else {
- fail("password should be 10-character hex");
- }
- }
break;
case WEP128:
assertNotNull("password is empty", mPassword);
- config.allowedKeyManagement.set(KeyMgmt.NONE);
- config.allowedAuthAlgorithms.set(AuthAlgorithm.OPEN);
- config.allowedAuthAlgorithms.set(AuthAlgorithm.SHARED);
+ // always use hex pair for WEP-104
+ assertTrue(WifiConfigurationHelper.isHex(mPassword, 26));
+ config = WifiConfigurationHelper.createWepConfig(mSsid, mPassword);
config.allowedGroupCiphers.set(GroupCipher.WEP104);
- if (mPassword != null) {
- // always use hex pair for WEP-104
- if (isHex(mPassword, 26)) {
- config.wepKeys[0] = mPassword;
- } else {
- fail("password should be 26-character hex");
- }
- }
break;
case WPA_TKIP:
assertNotNull("password is empty", mPassword);
- config.allowedKeyManagement.set(KeyMgmt.WPA_PSK);
+ config = WifiConfigurationHelper.createPskConfig(mSsid, mPassword);
config.allowedAuthAlgorithms.set(AuthAlgorithm.OPEN);
config.allowedProtocols.set(Protocol.WPA);
config.allowedPairwiseCiphers.set(PairwiseCipher.TKIP);
config.allowedGroupCiphers.set(GroupCipher.TKIP);
- if (isHex(mPassword, 64)) {
- config.preSharedKey = mPassword;
- } else {
- config.preSharedKey = '"' + mPassword + '"';
- }
break;
case WPA2_AES:
assertNotNull("password is empty", mPassword);
- config.allowedKeyManagement.set(KeyMgmt.WPA_PSK);
+ config = WifiConfigurationHelper.createPskConfig(mSsid, mPassword);
config.allowedAuthAlgorithms.set(AuthAlgorithm.OPEN);
config.allowedProtocols.set(Protocol.RSN);
config.allowedPairwiseCiphers.set(PairwiseCipher.CCMP);
config.allowedGroupCiphers.set(GroupCipher.CCMP);
- config.allowedProtocols.set(Protocol.RSN);
- if (isHex(mPassword, 64)) {
- config.preSharedKey = mPassword;
- } else {
- config.preSharedKey = '"' + mPassword + '"';
- }
break;
default:
fail("Not a valid security type: " + mSecurityType);
break;
}
- Log.v(TAG, "network config: " + config.toString());
+ logv("network config: %s", config.toString());
connectToWifi(config);
// verify that connection actually works
assertTrue("no network connectivity at end of test", checkNetworkConnectivity());
diff --git a/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/functional/WifiConnectionTest.java b/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/functional/WifiConnectionTest.java
index 740ffb8..b37daa3 100644
--- a/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/functional/WifiConnectionTest.java
+++ b/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/functional/WifiConnectionTest.java
@@ -16,54 +16,38 @@
package com.android.connectivitymanagertest.functional;
-import android.net.ConnectivityManager;
-import android.net.NetworkInfo.State;
import android.net.wifi.WifiConfiguration;
-import android.net.wifi.WifiInfo;
+import android.os.SystemClock;
import android.test.suitebuilder.annotation.LargeTest;
-import android.util.Log;
import com.android.connectivitymanagertest.ConnectivityManagerTestBase;
+import com.android.connectivitymanagertest.WifiConfigurationHelper;
-import java.util.ArrayList;
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.FileReader;
+import java.io.IOException;
import java.util.List;
/**
* 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
+ * adb shell am instrument \
+ * -e class com.android.connectivitymanagertest.functional.WifiConnectionTest \
+ * -w com.android.connectivitymanagertest/.ConnectivityManagerTestRunner
*/
-public class WifiConnectionTest
- extends ConnectivityManagerTestBase {
- private static final String TAG = "WifiConnectionTest";
- private static final boolean DEBUG = false;
- private List<WifiConfiguration> mNetworks = new ArrayList<WifiConfiguration>();
+public class WifiConnectionTest extends ConnectivityManagerTestBase {
+ private static final String WIFI_CONFIG_FILE = "/data/wifi_configs.json";
+ private static final long PAUSE_DURATION_MS = 60 * 1000;
+
+ public WifiConnectionTest() {
+ super(WifiConnectionTest.class.getSimpleName());
+ }
@Override
public void setUp() throws Exception {
super.setUp();
- mNetworks = loadNetworkConfigurations();
- if (DEBUG) {
- printNetworkConfigurations();
- }
-
- // enable wifi and verify wpa_supplicant is started
- assertTrue("enable Wifi failed", enableWifi());
- assertTrue("wifi not connected", waitForNetworkState(
- ConnectivityManager.TYPE_WIFI, State.CONNECTED, LONG_TIMEOUT));
- WifiInfo wi = mWifiManager.getConnectionInfo();
- assertNotNull("no active wifi info", wi);
- assertTrue("failed to ping wpa_supplicant ", mWifiManager.pingSupplicant());
- }
-
- private void printNetworkConfigurations() {
- log("==== print network configurations parsed from XML file ====");
- log("number of access points: " + mNetworks.size());
- for (WifiConfiguration config : mNetworks) {
- log(config.toString());
- }
+ assertTrue("Failed to enable wifi", enableWifi());
}
@Override
@@ -72,25 +56,67 @@
super.tearDown();
}
- private void log(String message) {
- Log.v(TAG, message);
- }
-
@LargeTest
public void testWifiConnections() {
- for (int i = 0; i < mNetworks.size(); i++) {
- String ssid = mNetworks.get(i).SSID;
- log("-- START Wi-Fi connection test to : " + ssid + " --");
- connectToWifi(mNetworks.get(i));
- // verify that connection actually works
- assertTrue("no network connectivity at end of test", checkNetworkConnectivity());
- log("-- END Wi-Fi connection test to " + ssid + " -- ");
- log("pausing for 1 minute");
- try {
- Thread.sleep(60 * 1000);
- } catch (InterruptedException e) {
- // ignore
+ List<WifiConfiguration> wifiConfigs = loadConfigurations();
+
+ printWifiConfigurations(wifiConfigs);
+
+ assertFalse("No configurations to test against", wifiConfigs.isEmpty());
+
+ boolean shouldPause = false;
+ for (WifiConfiguration config : wifiConfigs) {
+ if (shouldPause) {
+ logv("Pausing for %d seconds", PAUSE_DURATION_MS / 1000);
+ SystemClock.sleep(PAUSE_DURATION_MS);
}
+ logv("Start wifi connection test to: %s", config.SSID);
+ connectToWifi(config);
+
+ // verify that connection actually works
+ assertTrue("No connectivity at end of test", checkNetworkConnectivity());
+
+ // Disconnect and remove the network
+ assertTrue("Unable to remove network", disconnectAP());
+ logv("End wifi connection test to: %s", config.SSID);
+
+ shouldPause = true;
+ }
+ }
+
+ /**
+ * Load the configuration file from the root of the data partition
+ */
+ private List<WifiConfiguration> loadConfigurations() {
+ BufferedReader reader = null;
+ try {
+ reader = new BufferedReader(new FileReader(new File(WIFI_CONFIG_FILE)));
+ StringBuffer jsonBuffer = new StringBuffer();
+ String line;
+ while ((line = reader.readLine()) != null) {
+ jsonBuffer.append(line);
+ }
+ return WifiConfigurationHelper.parseJson(jsonBuffer.toString());
+ } catch (IllegalArgumentException | IOException e) {
+ throw new AssertionError("Error parsing file", e);
+ } finally {
+ if (reader != null) {
+ try {
+ reader.close();
+ } catch (IOException e) {
+ // Ignore
+ }
+ }
+ }
+ }
+
+ /**
+ * Print the wifi configurations to test against.
+ */
+ private void printWifiConfigurations(List<WifiConfiguration> wifiConfigs) {
+ logv("Wifi configurations to be tested");
+ for (WifiConfiguration config : wifiConfigs) {
+ logv(config.toString());
}
}
}
diff --git a/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/stress/WifiApStress.java b/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/stress/WifiApStress.java
index aead65b..41f01e6 100644
--- a/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/stress/WifiApStress.java
+++ b/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/stress/WifiApStress.java
@@ -17,16 +17,15 @@
package com.android.connectivitymanagertest.stress;
-import com.android.connectivitymanagertest.ConnectivityManagerStressTestRunner;
-import com.android.connectivitymanagertest.ConnectivityManagerTestBase;
-
import android.net.wifi.WifiConfiguration;
-import android.net.wifi.WifiConfiguration.KeyMgmt;
import android.net.wifi.WifiConfiguration.AuthAlgorithm;
+import android.net.wifi.WifiConfiguration.KeyMgmt;
import android.net.wifi.WifiManager;
import android.os.Environment;
import android.test.suitebuilder.annotation.LargeTest;
-import android.util.Log;
+
+import com.android.connectivitymanagertest.ConnectivityManagerStressTestRunner;
+import com.android.connectivitymanagertest.ConnectivityManagerTestBase;
import java.io.BufferedWriter;
import java.io.File;
@@ -35,9 +34,7 @@
/**
* Stress test setting up device as wifi hotspot
*/
-public class WifiApStress
- extends ConnectivityManagerTestBase {
- private final static String TAG = "WifiApStress";
+public class WifiApStress extends ConnectivityManagerTestBase {
private static String NETWORK_ID = "AndroidAPTest";
private static String PASSWD = "androidwifi";
private final static String OUTPUT_FILE = "WifiStressTestOutput.txt";
@@ -46,6 +43,10 @@
private int mLastIteration = 0;
private boolean mWifiOnlyFlag;
+ public WifiApStress() {
+ super(WifiApStress.class.getSimpleName());
+ }
+
@Override
protected void setUp() throws Exception {
super.setUp();
@@ -71,7 +72,7 @@
@LargeTest
public void testWifiHotSpot() {
if (mWifiOnlyFlag) {
- Log.v(TAG, this.getName() + " is excluded for wi-fi only test");
+ logv(getName() + " is excluded for wi-fi only test");
return;
}
WifiConfiguration config = new WifiConfiguration();
@@ -95,7 +96,7 @@
}
int i;
for (i = 0; i < mTotalIterations; i++) {
- Log.v(TAG, "iteration: " + i);
+ logv("iteration: " + i);
mLastIteration = i;
// enable Wifi tethering
assertTrue("failed to enable wifi hotspot",
diff --git a/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/stress/WifiStressTest.java b/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/stress/WifiStressTest.java
index 6ef4f06..fbd4669 100644
--- a/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/stress/WifiStressTest.java
+++ b/core/tests/ConnectivityManagerTest/src/com/android/connectivitymanagertest/stress/WifiStressTest.java
@@ -19,13 +19,10 @@
import android.app.Activity;
import android.content.Context;
import android.net.ConnectivityManager;
-import android.net.IpConfiguration.IpAssignment;
-import android.net.IpConfiguration.ProxySettings;
import android.net.NetworkInfo;
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.Bundle;
import android.os.Environment;
@@ -37,6 +34,7 @@
import com.android.connectivitymanagertest.ConnectivityManagerStressTestRunner;
import com.android.connectivitymanagertest.ConnectivityManagerTestBase;
+import com.android.connectivitymanagertest.WifiConfigurationHelper;
import java.io.BufferedWriter;
import java.io.File;
@@ -52,8 +50,6 @@
* -w com.android.connectivitymanagertest/.ConnectivityManagerStressTestRunner
*/
public class WifiStressTest extends ConnectivityManagerTestBase {
- private final static String TAG = "WifiStressTest";
-
private final static long SCREEN_OFF_TIMER = 500; //500ms
/**
* Wi-Fi idle time for default sleep policy
@@ -78,6 +74,10 @@
private BufferedWriter mOutputWriter = null;
private boolean mWifiOnlyFlag;
+ public WifiStressTest() {
+ super(WifiStressTest.class.getSimpleName());
+ }
+
@Override
protected void setUp() throws Exception {
super.setUp();
@@ -89,14 +89,14 @@
mScanIterations = mRunner.getScanIterations();
mWifiSleepTime = mRunner.getSleepTime();
mWifiOnlyFlag = mRunner.isWifiOnly();
- log(String.format("mReconnectIterations(%d), mSsid(%s), mPassword(%s),"
+ logv(String.format("mReconnectIterations(%d), mSsid(%s), mPassword(%s),"
+ "mScanIterations(%d), mWifiSleepTime(%d)", mReconnectIterations, mSsid,
mPassword, mScanIterations, mWifiSleepTime));
mOutputWriter = new BufferedWriter(new FileWriter(new File(
Environment.getExternalStorageDirectory(), OUTPUT_FILE), true));
turnScreenOn();
if (!mWifiManager.isWifiEnabled()) {
- log("Enable wi-fi before stress tests.");
+ logv("Enable wi-fi before stress tests.");
if (!enableWifi()) {
tearDown();
fail("enable wifi failed.");
@@ -107,7 +107,7 @@
@Override
protected void tearDown() throws Exception {
- log("tearDown()");
+ logv("tearDown()");
if (mOutputWriter != null) {
mOutputWriter.close();
}
@@ -115,23 +115,19 @@
}
private void writeOutput(String s) {
- log("write message: " + s);
+ logv("write message: " + s);
if (mOutputWriter == null) {
- log("no writer attached to file " + OUTPUT_FILE);
+ logv("no writer attached to file " + OUTPUT_FILE);
return;
}
try {
mOutputWriter.write(s + "\n");
mOutputWriter.flush();
} catch (IOException e) {
- log("failed to write output.");
+ logv("failed to write output.");
}
}
- public void log(String message) {
- Log.v(TAG, message);
- }
-
private void sleep(long sometime, String errorMsg) {
try {
Thread.sleep(sometime);
@@ -149,7 +145,7 @@
long scanTimeSum = 0, i, averageScanTime = -1;
int ssidAppearInScanResultsCount = 0; // count times of given ssid appear in scan results.
for (i = 1; i <= mScanIterations; i++) {
- log("testWifiScanning: iteration: " + i);
+ logv("testWifiScanning: iteration: " + i);
averageScanTime = scanTimeSum / i;
writeOutput(String.format("iteration %d out of %d", i, mScanIterations));
writeOutput(String.format("average scanning time is %d", averageScanTime));
@@ -173,9 +169,9 @@
if (scanResultLocal == null || scanResultLocal.isEmpty()) {
fail("Scan results are empty ");
}
- log("size of scan result list: " + scanResultLocal.size());
+ logv("size of scan result list: " + scanResultLocal.size());
for (ScanResult sr : scanResultLocal) {
- log(String.format("scan result: " + sr.toString()));
+ logv(String.format("scan result: " + sr.toString()));
if (mSsid.equals(sr.SSID)) {
ssidAppearInScanResultsCount += 1;
break;
@@ -208,21 +204,12 @@
Settings.Global.putLong(mRunner.getContext().getContentResolver(),
Settings.Global.WIFI_IDLE_MS, WIFI_IDLE_MS);
- // Connect to a Wi-Fi network
- WifiConfiguration config = new WifiConfiguration();
- config.SSID = mSsid;
- if (mPassword != null) {
- config.allowedKeyManagement.set(KeyMgmt.WPA_PSK);
- if (isHex(mPassword, 64)) {
- config.preSharedKey = mPassword;
- } else {
- config.preSharedKey = '"' + mPassword + '"';
- }
+ WifiConfiguration config;
+ if (mPassword == null) {
+ config = WifiConfigurationHelper.createOpenConfig(mSsid);
} else {
- config.allowedKeyManagement.set(KeyMgmt.NONE);
+ config = WifiConfigurationHelper.createPskConfig(mSsid, mPassword);
}
- config.setIpAssignment(IpAssignment.DHCP);
- config.setProxySettings(ProxySettings.NONE);
assertTrue("Failed to connect to Wi-Fi network: " + mSsid,
connectToWifiWithConfiguration(config));
@@ -240,7 +227,7 @@
// 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);
+ logv("iteration: " + i);
turnScreenOff();
// Use clock time since boot for intervals.
long start = SystemClock.uptimeMillis();
@@ -271,7 +258,7 @@
if (mWifiOnlyFlag) {
NetworkInfo ni = mCm.getActiveNetworkInfo();
if (ni != null) {
- Log.e(TAG, "has active network while in wifi sleep: " + ni.toString());
+ Log.e(mLogTag, "has active network while in wifi sleep: " + ni.toString());
fail("active network detected");
}
} else {
@@ -292,7 +279,7 @@
long connectionTime = SystemClock.uptimeMillis() - startTime;
sum += connectionTime;
avgReconnectTime = sum / i;
- log("average reconnection time is: " + avgReconnectTime);
+ logv("average reconnection time is: " + avgReconnectTime);
assertTrue("Reconnect to Wi-Fi network, but no data connection.", pingTest(null));
}