WifiConnectionTest.java revision fddbe98cca2c5ab301337cc5e20e8b25a779822a
1/*
2 * Copyright (C) 2010, The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 *      http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.connectivitymanagertest.functional;
18
19import com.android.connectivitymanagertest.ConnectivityManagerStressTestRunner;
20import com.android.connectivitymanagertest.ConnectivityManagerTestActivity;
21import com.android.connectivitymanagertest.ConnectivityManagerTestRunner;
22import com.android.connectivitymanagertest.NetworkState;
23
24import android.R;
25import android.app.Activity;
26import android.content.ContentResolver;
27import android.content.Intent;
28import android.content.Context;
29import android.content.res.Resources;
30import android.net.wifi.WifiConfiguration;
31import android.net.wifi.WifiConfiguration.Status;
32import android.net.wifi.WifiInfo;
33import android.net.wifi.WifiManager;
34import android.net.ConnectivityManager;
35import android.net.DhcpInfo;
36import android.net.NetworkInfo;
37import android.net.NetworkInfo.State;
38import android.provider.Settings;
39
40import android.test.suitebuilder.annotation.LargeTest;
41import android.test.ActivityInstrumentationTestCase2;
42import android.util.Log;
43
44import java.util.ArrayList;
45import java.util.HashMap;
46import java.util.HashSet;
47import java.util.List;
48import java.util.Map.Entry;
49import java.util.Set;
50
51/**
52 * Test Wi-Fi connection with different configuration
53 * To run this tests:
54 *     adb shell am instrument -e class
55 *          com.android.connectivitymanagertest.functional.WifiConnectionTest
56 *          -w com.android.connectivitymanagertest/.ConnectivityManagerTestRunner
57 */
58public class WifiConnectionTest
59    extends ActivityInstrumentationTestCase2<ConnectivityManagerTestActivity> {
60    private static final String TAG = "WifiConnectionTest";
61    private static final boolean DEBUG = false;
62    private List<WifiConfiguration> networks = new ArrayList<WifiConfiguration>();
63    private ConnectivityManagerTestActivity mAct;
64    private HashMap<String, DhcpInfo> hm = null;
65    private ConnectivityManagerTestRunner mRunner;
66    private ContentResolver cr;
67    private Set<WifiConfiguration> enabledNetworks = null;
68    private WifiManager mWifiManager = null;
69
70    public WifiConnectionTest() {
71        super(ConnectivityManagerTestActivity.class);
72    }
73
74    @Override
75    public void setUp() throws Exception {
76        super.setUp();
77        log("before we launch the test activity, we preserve all the configured networks.");
78        mRunner = ((ConnectivityManagerTestRunner)getInstrumentation());
79        mWifiManager = (WifiManager) mRunner.getContext().getSystemService(Context.WIFI_SERVICE);
80        enabledNetworks = getEnabledNetworks(mWifiManager.getConfiguredNetworks());
81
82        mAct = getActivity();
83        cr = mRunner.getContext().getContentResolver();
84        networks = mAct.loadNetworkConfigurations();
85        hm = mAct.getDhcpInfo();
86        if (DEBUG) {
87            printNetworkConfigurations();
88            printDhcpInfo();
89        }
90
91        // enable Wifi and verify wpa_supplicant is started
92        assertTrue("enable Wifi failed", mAct.enableWifi());
93        sleep(2 * ConnectivityManagerTestActivity.SHORT_TIMEOUT,
94                "interrupted while waiting for WPA_SUPPLICANT to start");
95        WifiInfo mConnection = mAct.mWifiManager.getConnectionInfo();
96        assertNotNull(mConnection);
97        assertTrue("wpa_supplicant is not started ", mAct.mWifiManager.pingSupplicant());
98    }
99
100    private void printNetworkConfigurations() {
101        log("==== print network configurations parsed from XML file ====");
102        log("number of access points: " + networks.size());
103        for (WifiConfiguration config : networks) {
104            log(config.toString());
105        }
106    }
107
108    private void printDhcpInfo() {
109        if (hm == null) {
110            return;
111        } else {
112            Set<Entry<String, DhcpInfo>> set = hm.entrySet();
113            for (Entry<String, DhcpInfo> me: set) {
114               log("SSID: " + me.getKey());
115               DhcpInfo dhcp = me.getValue();
116               log("IP: " + intToIpString(dhcp.ipAddress));
117               log("gateway: " + intToIpString(dhcp.gateway));
118               log("Netmask: " + intToIpString(dhcp.netmask));
119               log("DNS1: " + intToIpString(dhcp.dns1));
120               log("DNS2: " + intToIpString(dhcp.dns2));
121            }
122        }
123    }
124
125    @Override
126    public void tearDown() throws Exception {
127        log("tear down");
128        mAct.removeConfiguredNetworksAndDisableWifi();
129        reEnableNetworks(enabledNetworks);
130        mWifiManager.saveConfiguration();
131        super.tearDown();
132    }
133
134    private Set<WifiConfiguration> getEnabledNetworks(List<WifiConfiguration> configuredNetworks) {
135        Set<WifiConfiguration> networks = new HashSet<WifiConfiguration>();
136        for (WifiConfiguration wifiConfig : configuredNetworks) {
137            if (wifiConfig.status == Status.ENABLED || wifiConfig.status == Status.CURRENT) {
138                networks.add(wifiConfig);
139                log("remembering enabled network " + wifiConfig.SSID +
140                        " status is " + wifiConfig.status);
141            }
142        }
143        return networks;
144    }
145
146    private void reEnableNetworks(Set<WifiConfiguration> enabledWifiConfig) {
147        if (!mWifiManager.isWifiEnabled()) {
148            log("reEnableNetworks: enable Wifi");
149            mWifiManager.setWifiEnabled(true);
150            sleep(ConnectivityManagerTestActivity.SHORT_TIMEOUT,
151                    "interruped while waiting for wifi to be enabled");
152        }
153        for (WifiConfiguration wifiConfig : enabledWifiConfig) {
154            log("recover wifi configuration: " + wifiConfig.toString());
155            int netId = mWifiManager.addNetwork(wifiConfig);
156            if (wifiConfig.status == Status.CURRENT) {
157                mWifiManager.enableNetwork(netId, true);
158                mWifiManager.reconnect();
159                sleep(ConnectivityManagerTestActivity.SHORT_TIMEOUT,
160                        String.format("interruped while connecting to %s", wifiConfig.SSID));
161                log("re-connecting to network " + wifiConfig.SSID);
162            }
163        }
164        List<WifiConfiguration> wifiConfigurations = mWifiManager.getConfiguredNetworks();
165        for (WifiConfiguration wifiConfig: wifiConfigurations) {
166            if (wifiConfig.status == Status.DISABLED) {
167                mWifiManager.enableNetwork(wifiConfig.networkId, false);
168            }
169        }
170    }
171
172    private String intToIpString(int i) {
173        return ((i & 0xFF) + "." +
174                ((i >> 8) & 0xFF) + "." +
175                ((i >> 16) & 0xFF) + "." +
176                ((i >> 24) & 0xFF));
177    }
178
179    private void sleep(long sometime, String errorMsg) {
180        try {
181            Thread.sleep(sometime);
182        } catch (InterruptedException e) {
183            fail(errorMsg);
184        }
185    }
186
187    private void log(String message) {
188        Log.v(TAG, message);
189    }
190    /**
191     * Connect to the provided Wi-Fi network
192     * @param config is the network configuration
193     * @return true if the connection is successful.
194     */
195    private void connectToWifi(WifiConfiguration config) {
196        // step 1: connect to the test access point
197        boolean isStaticIP = false;
198        if (hm.containsKey(config.SSID)) {
199            DhcpInfo dhcpInfo = hm.get(config.SSID);
200            if (dhcpInfo != null) {
201                isStaticIP = true;
202                // set the system settings:
203                Settings.System.putInt(cr,Settings.System.WIFI_USE_STATIC_IP, 1);
204                Settings.System.putString(cr, Settings.System.WIFI_STATIC_IP,
205                        intToIpString(dhcpInfo.ipAddress));
206                Settings.System.putString(cr, Settings.System.WIFI_STATIC_GATEWAY,
207                        intToIpString(dhcpInfo.gateway));
208                Settings.System.putString(cr, Settings.System.WIFI_STATIC_NETMASK,
209                        intToIpString(dhcpInfo.netmask));
210                Settings.System.putString(cr, Settings.System.WIFI_STATIC_DNS1,
211                        intToIpString(dhcpInfo.dns1));
212                Settings.System.putString(cr, Settings.System.WIFI_STATIC_DNS2,
213                        intToIpString(dhcpInfo.dns2));
214            }
215        }
216
217        assertTrue("failed to connect to " + config.SSID,
218                mAct.connectToWifiWithConfiguration(config));
219
220        // step 2: verify Wifi state and network state;
221        assertTrue(mAct.waitForWifiState(WifiManager.WIFI_STATE_ENABLED,
222                ConnectivityManagerTestActivity.SHORT_TIMEOUT));
223        // 802.1x requires long time for connection.
224        assertTrue(mAct.waitForNetworkState(ConnectivityManager.TYPE_WIFI,
225                State.CONNECTED, 2 * ConnectivityManagerTestActivity.LONG_TIMEOUT));
226
227        // step 3: verify the current connected network is the given SSID
228        assertNotNull("Wifi connection returns null", mAct.mWifiManager.getConnectionInfo());
229        if (DEBUG) {
230            log("config.SSID = " + config.SSID);
231            log("mAct.mWifiManager.getConnectionInfo.getSSID()" +
232                    mAct.mWifiManager.getConnectionInfo().getSSID());
233        }
234        assertTrue(config.SSID.contains(mAct.mWifiManager.getConnectionInfo().getSSID()));
235        if (isStaticIP) {
236            Settings.System.putInt(cr, Settings.System.WIFI_USE_STATIC_IP, 0);
237            Settings.System.putString(cr, Settings.System.WIFI_STATIC_IP, "");
238            Settings.System.putString(cr, Settings.System.WIFI_STATIC_GATEWAY, "");
239            Settings.System.putString(cr, Settings.System.WIFI_STATIC_NETMASK, "");
240            Settings.System.putString(cr, Settings.System.WIFI_STATIC_DNS1, "");
241            Settings.System.putString(cr, Settings.System.WIFI_STATIC_DNS2, "");
242        }
243    }
244
245    @LargeTest
246    public void testWifiConnections() {
247        for (int i = 0; i < networks.size(); i++) {
248            String ssid = networks.get(i).SSID;
249            log("-- START Wi-Fi connection test for SSID: " + ssid + " --");
250            connectToWifi(networks.get(i));
251            sleep(2 * ConnectivityManagerTestActivity.SHORT_TIMEOUT,
252                    String.format("Interrupted while connecting to ", ssid));
253            log("-- END Wi-Fi connection test for SSID: " + ssid + " --");
254        }
255    }
256}
257