WifiConfigManagerTest.java revision 0ce3ad57f3ce7fcfab17930e8cd48e6da57006fb
1/*
2 * Copyright (C) 2016 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.server.wifi;
18
19import static org.junit.Assert.*;
20import static org.mockito.Mockito.*;
21
22import android.app.Application;
23import android.app.test.MockAnswerUtil.AnswerWithArguments;
24import android.content.Context;
25import android.content.Intent;
26import android.content.pm.ApplicationInfo;
27import android.content.pm.PackageManager;
28import android.content.pm.UserInfo;
29import android.net.IpConfiguration;
30import android.net.wifi.ScanResult;
31import android.net.wifi.WifiConfiguration;
32import android.net.wifi.WifiConfiguration.NetworkSelectionStatus;
33import android.net.wifi.WifiEnterpriseConfig;
34import android.net.wifi.WifiManager;
35import android.net.wifi.WifiScanner;
36import android.net.wifi.WifiSsid;
37import android.os.UserHandle;
38import android.os.UserManager;
39import android.telephony.TelephonyManager;
40import android.test.suitebuilder.annotation.SmallTest;
41import android.text.TextUtils;
42
43import com.android.internal.R;
44import com.android.server.wifi.WifiConfigStoreLegacy.WifiConfigStoreDataLegacy;
45
46import org.junit.After;
47import org.junit.Before;
48import org.junit.Test;
49import org.mockito.ArgumentCaptor;
50import org.mockito.InOrder;
51import org.mockito.Mock;
52import org.mockito.MockitoAnnotations;
53
54import java.util.ArrayList;
55import java.util.Arrays;
56import java.util.HashSet;
57import java.util.List;
58import java.util.Set;
59
60/**
61 * Unit tests for {@link com.android.server.wifi.WifiConfigManager}.
62 */
63@SmallTest
64public class WifiConfigManagerTest {
65
66    private static final String TEST_BSSID = "0a:08:5c:67:89:00";
67    private static final long TEST_WALLCLOCK_CREATION_TIME_MILLIS = 9845637;
68    private static final long TEST_WALLCLOCK_UPDATE_TIME_MILLIS = 75455637;
69    private static final long TEST_ELAPSED_UPDATE_NETWORK_SELECTION_TIME_MILLIS = 29457631;
70    private static final int TEST_CREATOR_UID = 5;
71    private static final int TEST_UPDATE_UID = 4;
72    private static final int TEST_SYSUI_UID = 56;
73    private static final int TEST_DEFAULT_USER = UserHandle.USER_SYSTEM;
74    private static final int TEST_MAX_NUM_ACTIVE_CHANNELS_FOR_PARTIAL_SCAN = 5;
75    private static final Integer[] TEST_FREQ_LIST = {2400, 2450, 5150, 5175, 5650};
76    private static final String TEST_CREATOR_NAME = "com.wificonfigmanagerNew.creator";
77    private static final String TEST_UPDATE_NAME = "com.wificonfigmanagerNew.update";
78    private static final String TEST_DEFAULT_GW_MAC_ADDRESS = "0f:67:ad:ef:09:34";
79
80    @Mock private Context mContext;
81    @Mock private FrameworkFacade mFrameworkFacade;
82    @Mock private Clock mClock;
83    @Mock private UserManager mUserManager;
84    @Mock private TelephonyManager mTelephonyManager;
85    @Mock private WifiKeyStore mWifiKeyStore;
86    @Mock private WifiConfigStore mWifiConfigStore;
87    @Mock private WifiConfigStoreLegacy mWifiConfigStoreLegacy;
88    @Mock private PackageManager mPackageManager;
89
90    private MockResources mResources;
91    private InOrder mContextConfigStoreMockOrder;
92    private WifiConfigManager mWifiConfigManager;
93
94    /**
95     * Setup the mocks and an instance of WifiConfigManager before each test.
96     */
97    @Before
98    public void setUp() throws Exception {
99        MockitoAnnotations.initMocks(this);
100
101        // Set up the inorder for verifications. This is needed to verify that the broadcasts,
102        // store writes for network updates followed by network additions are in the expected order.
103        mContextConfigStoreMockOrder = inOrder(mContext, mWifiConfigStore);
104
105        // Set up the package name stuff & permission override.
106        when(mContext.getPackageManager()).thenReturn(mPackageManager);
107        mResources = new MockResources();
108        mResources.setBoolean(
109                R.bool.config_wifi_only_link_same_credential_configurations, true);
110        mResources.setInteger(
111                R.integer.config_wifi_framework_associated_partial_scan_max_num_active_channels,
112                TEST_MAX_NUM_ACTIVE_CHANNELS_FOR_PARTIAL_SCAN);
113        when(mContext.getResources()).thenReturn(mResources);
114
115        // Setup UserManager profiles for the default user.
116        setupUserProfiles(TEST_DEFAULT_USER);
117
118        doAnswer(new AnswerWithArguments() {
119            public String answer(int uid) throws Exception {
120                if (uid == TEST_CREATOR_UID) {
121                    return TEST_CREATOR_NAME;
122                } else if (uid == TEST_UPDATE_UID) {
123                    return TEST_UPDATE_NAME;
124                } else if (uid == TEST_SYSUI_UID) {
125                    return WifiConfigManager.SYSUI_PACKAGE_NAME;
126                }
127                fail("Unexpected UID: " + uid);
128                return "";
129            }
130        }).when(mPackageManager).getNameForUid(anyInt());
131        doAnswer(new AnswerWithArguments() {
132            public int answer(String packageName, int flags, int userId) throws Exception {
133                if (packageName.equals(WifiConfigManager.SYSUI_PACKAGE_NAME)) {
134                    return TEST_SYSUI_UID;
135                } else {
136                    return 0;
137                }
138            }
139        }).when(mPackageManager).getPackageUidAsUser(anyString(), anyInt(), anyInt());
140
141        // Both the UID's in the test have the configuration override permission granted by
142        // default. This maybe modified for particular tests if needed.
143        doAnswer(new AnswerWithArguments() {
144            public int answer(String permName, int uid) throws Exception {
145                if (uid == TEST_CREATOR_UID || uid == TEST_UPDATE_UID) {
146                    return PackageManager.PERMISSION_GRANTED;
147                }
148                return PackageManager.PERMISSION_DENIED;
149            }
150        }).when(mFrameworkFacade).checkUidPermission(anyString(), anyInt());
151
152        when(mWifiKeyStore
153                .updateNetworkKeys(any(WifiConfiguration.class), any(WifiConfiguration.class)))
154                .thenReturn(true);
155
156        when(mWifiConfigStore.areStoresPresent()).thenReturn(true);
157
158        createWifiConfigManager();
159    }
160
161    /**
162     * Called after each test
163     */
164    @After
165    public void cleanup() {
166        validateMockitoUsage();
167    }
168
169    /**
170     * Verifies the addition of a single network using
171     * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)}
172     */
173    @Test
174    public void testAddSingleOpenNetwork() {
175        WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
176        List<WifiConfiguration> networks = new ArrayList<>();
177        networks.add(openNetwork);
178
179        verifyAddNetworkToWifiConfigManager(openNetwork);
180
181        List<WifiConfiguration> retrievedNetworks =
182                mWifiConfigManager.getConfiguredNetworksWithPasswords();
183        WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate(
184                networks, retrievedNetworks);
185        // Ensure that the newly added network is disabled.
186        assertEquals(WifiConfiguration.Status.DISABLED, retrievedNetworks.get(0).status);
187    }
188
189    /**
190     * Verifies the modification of a single network using
191     * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)}
192     */
193    @Test
194    public void testUpdateSingleOpenNetwork() {
195        WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
196        List<WifiConfiguration> networks = new ArrayList<>();
197        networks.add(openNetwork);
198
199        verifyAddNetworkToWifiConfigManager(openNetwork);
200
201        // Now change BSSID for the network.
202        assertAndSetNetworkBSSID(openNetwork, TEST_BSSID);
203        verifyUpdateNetworkToWifiConfigManagerWithoutIpChange(openNetwork);
204
205        // Now verify that the modification has been effective.
206        List<WifiConfiguration> retrievedNetworks =
207                mWifiConfigManager.getConfiguredNetworksWithPasswords();
208        WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate(
209                networks, retrievedNetworks);
210    }
211
212    /**
213     * Verifies the addition of a single ephemeral network using
214     * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} and verifies that
215     * the {@link WifiConfigManager#getSavedNetworks()} does not return this network.
216     */
217    @Test
218    public void testAddSingleEphemeralNetwork() {
219        WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
220        openNetwork.ephemeral = true;
221        List<WifiConfiguration> networks = new ArrayList<>();
222        networks.add(openNetwork);
223
224        verifyAddEphemeralNetworkToWifiConfigManager(openNetwork);
225
226        List<WifiConfiguration> retrievedNetworks =
227                mWifiConfigManager.getConfiguredNetworksWithPasswords();
228        WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate(
229                networks, retrievedNetworks);
230
231        // Ensure that this is not returned in the saved network list.
232        assertTrue(mWifiConfigManager.getSavedNetworks().isEmpty());
233    }
234
235    /**
236     * Verifies that the modification of a single open network using
237     * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} with a UID which
238     * has no permission to modify the network fails.
239     */
240    @Test
241    public void testUpdateSingleOpenNetworkFailedDueToPermissionDenied() throws Exception {
242        WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
243        List<WifiConfiguration> networks = new ArrayList<>();
244        networks.add(openNetwork);
245
246        verifyAddNetworkToWifiConfigManager(openNetwork);
247
248        // Now change BSSID of the network.
249        assertAndSetNetworkBSSID(openNetwork, TEST_BSSID);
250
251        // Deny permission for |UPDATE_UID|.
252        doAnswer(new AnswerWithArguments() {
253            public int answer(String permName, int uid) throws Exception {
254                if (uid == TEST_CREATOR_UID) {
255                    return PackageManager.PERMISSION_GRANTED;
256                }
257                return PackageManager.PERMISSION_DENIED;
258            }
259        }).when(mFrameworkFacade).checkUidPermission(anyString(), anyInt());
260
261        // Update the same configuration and ensure that the operation failed.
262        NetworkUpdateResult result = updateNetworkToWifiConfigManager(openNetwork);
263        assertTrue(result.getNetworkId() == WifiConfiguration.INVALID_NETWORK_ID);
264    }
265
266    /**
267     * Verifies that the modification of a single open network using
268     * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} with the creator UID
269     * should always succeed.
270     */
271    @Test
272    public void testUpdateSingleOpenNetworkSuccessWithCreatorUID() throws Exception {
273        WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
274        List<WifiConfiguration> networks = new ArrayList<>();
275        networks.add(openNetwork);
276
277        verifyAddNetworkToWifiConfigManager(openNetwork);
278
279        // Now change BSSID of the network.
280        assertAndSetNetworkBSSID(openNetwork, TEST_BSSID);
281
282        // Deny permission for all UIDs.
283        doAnswer(new AnswerWithArguments() {
284            public int answer(String permName, int uid) throws Exception {
285                return PackageManager.PERMISSION_DENIED;
286            }
287        }).when(mFrameworkFacade).checkUidPermission(anyString(), anyInt());
288
289        // Update the same configuration using the creator UID.
290        NetworkUpdateResult result =
291                mWifiConfigManager.addOrUpdateNetwork(openNetwork, TEST_CREATOR_UID);
292        assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID);
293
294        // Now verify that the modification has been effective.
295        List<WifiConfiguration> retrievedNetworks =
296                mWifiConfigManager.getConfiguredNetworksWithPasswords();
297        WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate(
298                networks, retrievedNetworks);
299    }
300
301    /**
302     * Verifies the addition of a single PSK network using
303     * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} and verifies that
304     * {@link WifiConfigManager#getSavedNetworks()} masks the password.
305     */
306    @Test
307    public void testAddSinglePskNetwork() {
308        WifiConfiguration pskNetwork = WifiConfigurationTestUtil.createPskNetwork();
309        List<WifiConfiguration> networks = new ArrayList<>();
310        networks.add(pskNetwork);
311
312        verifyAddNetworkToWifiConfigManager(pskNetwork);
313
314        List<WifiConfiguration> retrievedNetworks =
315                mWifiConfigManager.getConfiguredNetworksWithPasswords();
316        WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate(
317                networks, retrievedNetworks);
318
319        List<WifiConfiguration> retrievedSavedNetworks = mWifiConfigManager.getSavedNetworks();
320        assertEquals(retrievedSavedNetworks.size(), 1);
321        assertEquals(retrievedSavedNetworks.get(0).configKey(), pskNetwork.configKey());
322        assertPasswordsMaskedInWifiConfiguration(retrievedSavedNetworks.get(0));
323    }
324
325    /**
326     * Verifies the addition of a single WEP network using
327     * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} and verifies that
328     * {@link WifiConfigManager#getSavedNetworks()} masks the password.
329     */
330    @Test
331    public void testAddSingleWepNetwork() {
332        WifiConfiguration wepNetwork = WifiConfigurationTestUtil.createWepNetwork();
333        List<WifiConfiguration> networks = new ArrayList<>();
334        networks.add(wepNetwork);
335
336        verifyAddNetworkToWifiConfigManager(wepNetwork);
337
338        List<WifiConfiguration> retrievedNetworks =
339                mWifiConfigManager.getConfiguredNetworksWithPasswords();
340        WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate(
341                networks, retrievedNetworks);
342
343        List<WifiConfiguration> retrievedSavedNetworks = mWifiConfigManager.getSavedNetworks();
344        assertEquals(retrievedSavedNetworks.size(), 1);
345        assertEquals(retrievedSavedNetworks.get(0).configKey(), wepNetwork.configKey());
346        assertPasswordsMaskedInWifiConfiguration(retrievedSavedNetworks.get(0));
347    }
348
349    /**
350     * Verifies the modification of an IpConfiguration using
351     * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)}
352     */
353    @Test
354    public void testUpdateIpConfiguration() {
355        WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
356        List<WifiConfiguration> networks = new ArrayList<>();
357        networks.add(openNetwork);
358
359        verifyAddNetworkToWifiConfigManager(openNetwork);
360
361        // Now change BSSID of the network.
362        assertAndSetNetworkBSSID(openNetwork, TEST_BSSID);
363
364        // Update the same configuration and ensure that the IP configuration change flags
365        // are not set.
366        verifyUpdateNetworkToWifiConfigManagerWithoutIpChange(openNetwork);
367
368        // Change the IpConfiguration now and ensure that the IP configuration flags are set now.
369        assertAndSetNetworkIpConfiguration(
370                openNetwork,
371                WifiConfigurationTestUtil.createStaticIpConfigurationWithStaticProxy());
372        verifyUpdateNetworkToWifiConfigManagerWithIpChange(openNetwork);
373
374        // Now verify that all the modifications have been effective.
375        List<WifiConfiguration> retrievedNetworks =
376                mWifiConfigManager.getConfiguredNetworksWithPasswords();
377        WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate(
378                networks, retrievedNetworks);
379    }
380
381    /**
382     * Verifies the removal of a single network using
383     * {@link WifiConfigManager#removeNetwork(int)}
384     */
385    @Test
386    public void testRemoveSingleOpenNetwork() {
387        WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
388        List<WifiConfiguration> networks = new ArrayList<>();
389        networks.add(openNetwork);
390
391        verifyAddNetworkToWifiConfigManager(openNetwork);
392
393        verifyRemoveNetworkFromWifiConfigManager(openNetwork);
394
395        // Ensure that configured network list is empty now.
396        assertTrue(mWifiConfigManager.getConfiguredNetworks().isEmpty());
397    }
398
399    /**
400     * Verifies the addition & update of multiple networks using
401     * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} and the
402     * removal of networks using
403     * {@link WifiConfigManager#removeNetwork(int)}
404     */
405    @Test
406    public void testAddUpdateRemoveMultipleNetworks() {
407        List<WifiConfiguration> networks = new ArrayList<>();
408        WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
409        WifiConfiguration pskNetwork = WifiConfigurationTestUtil.createPskNetwork();
410        WifiConfiguration wepNetwork = WifiConfigurationTestUtil.createWepNetwork();
411        networks.add(openNetwork);
412        networks.add(pskNetwork);
413        networks.add(wepNetwork);
414
415        verifyAddNetworkToWifiConfigManager(openNetwork);
416        verifyAddNetworkToWifiConfigManager(pskNetwork);
417        verifyAddNetworkToWifiConfigManager(wepNetwork);
418
419        // Now verify that all the additions has been effective.
420        List<WifiConfiguration> retrievedNetworks =
421                mWifiConfigManager.getConfiguredNetworksWithPasswords();
422        WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate(
423                networks, retrievedNetworks);
424
425        // Modify all the 3 configurations and update it to WifiConfigManager.
426        assertAndSetNetworkBSSID(openNetwork, TEST_BSSID);
427        assertAndSetNetworkBSSID(pskNetwork, TEST_BSSID);
428        assertAndSetNetworkIpConfiguration(
429                wepNetwork,
430                WifiConfigurationTestUtil.createStaticIpConfigurationWithPacProxy());
431
432        verifyUpdateNetworkToWifiConfigManagerWithoutIpChange(openNetwork);
433        verifyUpdateNetworkToWifiConfigManagerWithoutIpChange(pskNetwork);
434        verifyUpdateNetworkToWifiConfigManagerWithIpChange(wepNetwork);
435        // Now verify that all the modifications has been effective.
436        retrievedNetworks = mWifiConfigManager.getConfiguredNetworksWithPasswords();
437        WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate(
438                networks, retrievedNetworks);
439
440        // Now remove all 3 networks.
441        verifyRemoveNetworkFromWifiConfigManager(openNetwork);
442        verifyRemoveNetworkFromWifiConfigManager(pskNetwork);
443        verifyRemoveNetworkFromWifiConfigManager(wepNetwork);
444
445        // Ensure that configured network list is empty now.
446        assertTrue(mWifiConfigManager.getConfiguredNetworks().isEmpty());
447    }
448
449    /**
450     * Verifies the update of network status using
451     * {@link WifiConfigManager#updateNetworkSelectionStatus(int, int)}.
452     */
453    @Test
454    public void testNetworkSelectionStatus() {
455        WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
456
457        NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(openNetwork);
458
459        // First set it to enabled.
460        verifyUpdateNetworkSelectionStatus(
461                result.getNetworkId(), NetworkSelectionStatus.NETWORK_SELECTION_ENABLE, 0);
462
463        // Now set it to temporarily disabled. The threshold for association rejection is 5, so
464        // disable it 5 times to actually mark it temporarily disabled.
465        int assocRejectReason = NetworkSelectionStatus.DISABLED_ASSOCIATION_REJECTION;
466        int assocRejectThreshold =
467                WifiConfigManager.NETWORK_SELECTION_DISABLE_THRESHOLD[assocRejectReason];
468        for (int i = 1; i <= assocRejectThreshold; i++) {
469            verifyUpdateNetworkSelectionStatus(result.getNetworkId(), assocRejectReason, i);
470        }
471
472        // Now set it to permanently disabled.
473        verifyUpdateNetworkSelectionStatus(
474                result.getNetworkId(), NetworkSelectionStatus.DISABLED_BY_WIFI_MANAGER, 0);
475
476        // Now set it back to enabled.
477        verifyUpdateNetworkSelectionStatus(
478                result.getNetworkId(), NetworkSelectionStatus.NETWORK_SELECTION_ENABLE, 0);
479    }
480
481    /**
482     * Verifies the update of network status using
483     * {@link WifiConfigManager#updateNetworkSelectionStatus(int, int)} and ensures that
484     * enabling a network clears out all the temporary disable counters.
485     */
486    @Test
487    public void testNetworkSelectionStatusEnableClearsDisableCounters() {
488        WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
489
490        NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(openNetwork);
491
492        // First set it to enabled.
493        verifyUpdateNetworkSelectionStatus(
494                result.getNetworkId(), NetworkSelectionStatus.NETWORK_SELECTION_ENABLE, 0);
495
496        // Now set it to temporarily disabled 2 times for 2 different reasons.
497        verifyUpdateNetworkSelectionStatus(
498                result.getNetworkId(), NetworkSelectionStatus.DISABLED_ASSOCIATION_REJECTION, 1);
499        verifyUpdateNetworkSelectionStatus(
500                result.getNetworkId(), NetworkSelectionStatus.DISABLED_ASSOCIATION_REJECTION, 2);
501        verifyUpdateNetworkSelectionStatus(
502                result.getNetworkId(), NetworkSelectionStatus.DISABLED_AUTHENTICATION_FAILURE, 1);
503        verifyUpdateNetworkSelectionStatus(
504                result.getNetworkId(), NetworkSelectionStatus.DISABLED_AUTHENTICATION_FAILURE, 2);
505
506        // Now set it back to enabled.
507        verifyUpdateNetworkSelectionStatus(
508                result.getNetworkId(), NetworkSelectionStatus.NETWORK_SELECTION_ENABLE, 0);
509
510        // Ensure that the counters have all been reset now.
511        verifyUpdateNetworkSelectionStatus(
512                result.getNetworkId(), NetworkSelectionStatus.DISABLED_ASSOCIATION_REJECTION, 1);
513        verifyUpdateNetworkSelectionStatus(
514                result.getNetworkId(), NetworkSelectionStatus.DISABLED_AUTHENTICATION_FAILURE, 1);
515    }
516
517    /**
518     * Verifies the enabling of temporarily disabled network using
519     * {@link WifiConfigManager#tryEnableNetwork(int)}.
520     */
521    @Test
522    public void testTryEnableNetwork() {
523        WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
524
525        NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(openNetwork);
526
527        // First set it to enabled.
528        verifyUpdateNetworkSelectionStatus(
529                result.getNetworkId(), NetworkSelectionStatus.NETWORK_SELECTION_ENABLE, 0);
530
531        // Now set it to temporarily disabled. The threshold for association rejection is 5, so
532        // disable it 5 times to actually mark it temporarily disabled.
533        int assocRejectReason = NetworkSelectionStatus.DISABLED_ASSOCIATION_REJECTION;
534        int assocRejectThreshold =
535                WifiConfigManager.NETWORK_SELECTION_DISABLE_THRESHOLD[assocRejectReason];
536        for (int i = 1; i <= assocRejectThreshold; i++) {
537            verifyUpdateNetworkSelectionStatus(result.getNetworkId(), assocRejectReason, i);
538        }
539
540        // Now let's try enabling this network without changing the time, this should fail and the
541        // status remains temporarily disabled.
542        assertFalse(mWifiConfigManager.tryEnableNetwork(result.getNetworkId()));
543        NetworkSelectionStatus retrievedStatus =
544                mWifiConfigManager.getConfiguredNetwork(result.getNetworkId())
545                        .getNetworkSelectionStatus();
546        assertTrue(retrievedStatus.isNetworkTemporaryDisabled());
547
548        // Now advance time by the timeout for association rejection and ensure that the network
549        // is now enabled.
550        int assocRejectTimeout =
551                WifiConfigManager.NETWORK_SELECTION_DISABLE_TIMEOUT_MS[assocRejectReason];
552        when(mClock.getElapsedSinceBootMillis())
553                .thenReturn(TEST_ELAPSED_UPDATE_NETWORK_SELECTION_TIME_MILLIS + assocRejectTimeout);
554
555        assertTrue(mWifiConfigManager.tryEnableNetwork(result.getNetworkId()));
556        retrievedStatus =
557                mWifiConfigManager.getConfiguredNetwork(result.getNetworkId())
558                        .getNetworkSelectionStatus();
559        assertTrue(retrievedStatus.isNetworkEnabled());
560    }
561
562    /**
563     * Verifies the enabling of network using
564     * {@link WifiConfigManager#enableNetwork(int, boolean, int)} and
565     * {@link WifiConfigManager#disableNetwork(int, int)}.
566     */
567    @Test
568    public void testEnableDisableNetwork() {
569        WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
570
571        NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(openNetwork);
572
573        assertTrue(mWifiConfigManager.enableNetwork(
574                result.getNetworkId(), false, TEST_CREATOR_UID));
575        WifiConfiguration retrievedNetwork =
576                mWifiConfigManager.getConfiguredNetwork(result.getNetworkId());
577        NetworkSelectionStatus retrievedStatus = retrievedNetwork.getNetworkSelectionStatus();
578        assertTrue(retrievedStatus.isNetworkEnabled());
579        verifyUpdateNetworkStatus(retrievedNetwork, WifiConfiguration.Status.ENABLED);
580
581        // Now set it disabled.
582        assertTrue(mWifiConfigManager.disableNetwork(result.getNetworkId(), TEST_CREATOR_UID));
583        retrievedNetwork = mWifiConfigManager.getConfiguredNetwork(result.getNetworkId());
584        retrievedStatus = retrievedNetwork.getNetworkSelectionStatus();
585        assertTrue(retrievedStatus.isNetworkPermanentlyDisabled());
586        verifyUpdateNetworkStatus(retrievedNetwork, WifiConfiguration.Status.DISABLED);
587    }
588
589    /**
590     * Verifies the enabling of network using
591     * {@link WifiConfigManager#enableNetwork(int, boolean, int)} with a UID which
592     * has no permission to modify the network fails..
593     */
594    @Test
595    public void testEnableDisableNetworkFailedDueToPermissionDenied() throws Exception {
596        WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
597
598        NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(openNetwork);
599
600        assertTrue(mWifiConfigManager.enableNetwork(
601                result.getNetworkId(), false, TEST_CREATOR_UID));
602        WifiConfiguration retrievedNetwork =
603                mWifiConfigManager.getConfiguredNetwork(result.getNetworkId());
604        NetworkSelectionStatus retrievedStatus = retrievedNetwork.getNetworkSelectionStatus();
605        assertTrue(retrievedStatus.isNetworkEnabled());
606        verifyUpdateNetworkStatus(retrievedNetwork, WifiConfiguration.Status.ENABLED);
607
608        // Deny permission for |UPDATE_UID|.
609        doAnswer(new AnswerWithArguments() {
610            public int answer(String permName, int uid) throws Exception {
611                if (uid == TEST_CREATOR_UID) {
612                    return PackageManager.PERMISSION_GRANTED;
613                }
614                return PackageManager.PERMISSION_DENIED;
615            }
616        }).when(mFrameworkFacade).checkUidPermission(anyString(), anyInt());
617
618        // Now try to set it disabled with |TEST_UPDATE_UID|, it should fail and the network
619        // should remain enabled.
620        assertFalse(mWifiConfigManager.disableNetwork(result.getNetworkId(), TEST_UPDATE_UID));
621        retrievedStatus =
622                mWifiConfigManager.getConfiguredNetwork(result.getNetworkId())
623                        .getNetworkSelectionStatus();
624        assertTrue(retrievedStatus.isNetworkEnabled());
625        assertEquals(WifiConfiguration.Status.ENABLED, retrievedNetwork.status);
626    }
627
628    /**
629     * Verifies the updation of network's connectUid using
630     * {@link WifiConfigManager#checkAndUpdateLastConnectUid(int, int)}.
631     */
632    @Test
633    public void testUpdateLastConnectUid() throws Exception {
634        WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
635
636        NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(openNetwork);
637
638        assertTrue(
639                mWifiConfigManager.checkAndUpdateLastConnectUid(
640                        result.getNetworkId(), TEST_CREATOR_UID));
641        WifiConfiguration retrievedNetwork =
642                mWifiConfigManager.getConfiguredNetwork(result.getNetworkId());
643        assertEquals(TEST_CREATOR_UID, retrievedNetwork.lastConnectUid);
644
645        // Deny permission for |UPDATE_UID|.
646        doAnswer(new AnswerWithArguments() {
647            public int answer(String permName, int uid) throws Exception {
648                if (uid == TEST_CREATOR_UID) {
649                    return PackageManager.PERMISSION_GRANTED;
650                }
651                return PackageManager.PERMISSION_DENIED;
652            }
653        }).when(mFrameworkFacade).checkUidPermission(anyString(), anyInt());
654
655        // Now try to update the last connect UID with |TEST_UPDATE_UID|, it should fail and
656        // the lastConnectUid should remain the same.
657        assertFalse(
658                mWifiConfigManager.checkAndUpdateLastConnectUid(
659                        result.getNetworkId(), TEST_UPDATE_UID));
660        retrievedNetwork = mWifiConfigManager.getConfiguredNetwork(result.getNetworkId());
661        assertEquals(TEST_CREATOR_UID, retrievedNetwork.lastConnectUid);
662    }
663
664    /**
665     * Verifies that any configuration update attempt with an null config is gracefully
666     * handled.
667     * This invokes {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)}.
668     */
669    @Test
670    public void testAddOrUpdateNetworkWithNullConfig() {
671        NetworkUpdateResult result = mWifiConfigManager.addOrUpdateNetwork(null, TEST_CREATOR_UID);
672        assertFalse(result.isSuccess());
673    }
674
675    /**
676     * Verifies that any configuration removal attempt with an invalid networkID is gracefully
677     * handled.
678     * This invokes {@link WifiConfigManager#removeNetwork(int)}.
679     */
680    @Test
681    public void testRemoveNetworkWithInvalidNetworkId() {
682        WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
683
684        verifyAddNetworkToWifiConfigManager(openNetwork);
685
686        // Change the networkID to an invalid one.
687        openNetwork.networkId++;
688        assertFalse(mWifiConfigManager.removeNetwork(openNetwork.networkId, TEST_CREATOR_UID));
689    }
690
691    /**
692     * Verifies that any configuration update attempt with an invalid networkID is gracefully
693     * handled.
694     * This invokes {@link WifiConfigManager#enableNetwork(int, boolean, int)},
695     * {@link WifiConfigManager#disableNetwork(int, int)},
696     * {@link WifiConfigManager#updateNetworkSelectionStatus(int, int)} and
697     * {@link WifiConfigManager#checkAndUpdateLastConnectUid(int, int)}.
698     */
699    @Test
700    public void testChangeConfigurationWithInvalidNetworkId() {
701        WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
702
703        NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(openNetwork);
704
705        assertFalse(mWifiConfigManager.enableNetwork(
706                result.getNetworkId() + 1, false, TEST_CREATOR_UID));
707        assertFalse(mWifiConfigManager.disableNetwork(result.getNetworkId() + 1, TEST_CREATOR_UID));
708        assertFalse(mWifiConfigManager.updateNetworkSelectionStatus(
709                result.getNetworkId() + 1, NetworkSelectionStatus.DISABLED_BY_WIFI_MANAGER));
710        assertFalse(mWifiConfigManager.checkAndUpdateLastConnectUid(
711                result.getNetworkId() + 1, TEST_CREATOR_UID));
712    }
713
714    /**
715     * Verifies multiple modification of a single network using
716     * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)}.
717     * This test is basically checking if the apps can reset some of the fields of the config after
718     * addition. The fields being reset in this test are the |preSharedKey| and |wepKeys|.
719     * 1. Create an open network initially.
720     * 2. Modify the added network config to a WEP network config with all the 4 keys set.
721     * 3. Modify the added network config to a WEP network config with only 1 key set.
722     * 4. Modify the added network config to a PSK network config.
723     */
724    @Test
725    public void testMultipleUpdatesSingleNetwork() {
726        WifiConfiguration network = WifiConfigurationTestUtil.createOpenNetwork();
727        verifyAddNetworkToWifiConfigManager(network);
728
729        // Now add |wepKeys| to the network. We don't need to update the |allowedKeyManagement|
730        // fields for open to WEP conversion.
731        String[] wepKeys =
732                Arrays.copyOf(WifiConfigurationTestUtil.TEST_WEP_KEYS,
733                        WifiConfigurationTestUtil.TEST_WEP_KEYS.length);
734        int wepTxKeyIdx = WifiConfigurationTestUtil.TEST_WEP_TX_KEY_INDEX;
735        assertAndSetNetworkWepKeysAndTxIndex(network, wepKeys, wepTxKeyIdx);
736
737        verifyUpdateNetworkToWifiConfigManagerWithoutIpChange(network);
738        WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate(
739                network, mWifiConfigManager.getConfiguredNetworkWithPassword(network.networkId));
740
741        // Now empty out 3 of the |wepKeys[]| and ensure that those keys have been reset correctly.
742        for (int i = 1; i < network.wepKeys.length; i++) {
743            wepKeys[i] = "";
744        }
745        wepTxKeyIdx = 0;
746        assertAndSetNetworkWepKeysAndTxIndex(network, wepKeys, wepTxKeyIdx);
747
748        verifyUpdateNetworkToWifiConfigManagerWithoutIpChange(network);
749        WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate(
750                network, mWifiConfigManager.getConfiguredNetworkWithPassword(network.networkId));
751
752        // Now change the config to a PSK network config by resetting the remaining |wepKey[0]|
753        // field and setting the |preSharedKey| and |allowedKeyManagement| fields.
754        wepKeys[0] = "";
755        wepTxKeyIdx = -1;
756        assertAndSetNetworkWepKeysAndTxIndex(network, wepKeys, wepTxKeyIdx);
757        network.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
758        assertAndSetNetworkPreSharedKey(network, WifiConfigurationTestUtil.TEST_PSK);
759
760        verifyUpdateNetworkToWifiConfigManagerWithoutIpChange(network);
761        WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate(
762                network, mWifiConfigManager.getConfiguredNetworkWithPassword(network.networkId));
763    }
764
765    /**
766     * Verifies the modification of a WifiEnteriseConfig using
767     * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)}.
768     */
769    @Test
770    public void testUpdateWifiEnterpriseConfig() {
771        WifiConfiguration network = WifiConfigurationTestUtil.createEapNetwork();
772        verifyAddNetworkToWifiConfigManager(network);
773
774        // Set the |password| field in WifiEnterpriseConfig and modify the config to PEAP/GTC.
775        network.enterpriseConfig =
776                WifiConfigurationTestUtil.createPEAPWifiEnterpriseConfigWithGTCPhase2();
777        assertAndSetNetworkEnterprisePassword(network, "test");
778
779        verifyUpdateNetworkToWifiConfigManagerWithoutIpChange(network);
780        WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate(
781                network, mWifiConfigManager.getConfiguredNetworkWithPassword(network.networkId));
782
783        // Reset the |password| field in WifiEnterpriseConfig and modify the config to TLS/None.
784        network.enterpriseConfig.setEapMethod(WifiEnterpriseConfig.Eap.TLS);
785        network.enterpriseConfig.setPhase2Method(WifiEnterpriseConfig.Phase2.NONE);
786        assertAndSetNetworkEnterprisePassword(network, "");
787
788        verifyUpdateNetworkToWifiConfigManagerWithoutIpChange(network);
789        WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate(
790                network, mWifiConfigManager.getConfiguredNetworkWithPassword(network.networkId));
791    }
792
793    /**
794     * Verifies the modification of a single network using
795     * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} by passing in nulls
796     * in all the publicly exposed fields.
797     */
798    @Test
799    public void testUpdateSingleNetworkWithNullValues() {
800        WifiConfiguration network = WifiConfigurationTestUtil.createEapNetwork();
801        verifyAddNetworkToWifiConfigManager(network);
802
803        // Save a copy of the original network for comparison.
804        WifiConfiguration originalNetwork = new WifiConfiguration(network);
805
806        // Now set all the public fields to null and try updating the network.
807        network.allowedAuthAlgorithms = null;
808        network.allowedProtocols = null;
809        network.allowedKeyManagement = null;
810        network.allowedPairwiseCiphers = null;
811        network.allowedGroupCiphers = null;
812        network.setIpConfiguration(null);
813        network.enterpriseConfig = null;
814
815        verifyUpdateNetworkToWifiConfigManagerWithoutIpChange(network);
816
817        // Copy over the updated debug params to the original network config before comparison.
818        originalNetwork.lastUpdateUid = network.lastUpdateUid;
819        originalNetwork.lastUpdateName = network.lastUpdateName;
820        originalNetwork.updateTime = network.updateTime;
821
822        // Now verify that there was no change to the network configurations.
823        WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate(
824                originalNetwork,
825                mWifiConfigManager.getConfiguredNetworkWithPassword(originalNetwork.networkId));
826    }
827
828    /**
829     * Verifies that the modification of a single network using
830     * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} does not modify
831     * existing configuration if there is a failure.
832     */
833    @Test
834    public void testUpdateSingleNetworkFailureDoesNotModifyOriginal() {
835        WifiConfiguration network = WifiConfigurationTestUtil.createEapNetwork();
836        network.enterpriseConfig =
837                WifiConfigurationTestUtil.createPEAPWifiEnterpriseConfigWithGTCPhase2();
838        verifyAddNetworkToWifiConfigManager(network);
839
840        // Save a copy of the original network for comparison.
841        WifiConfiguration originalNetwork = new WifiConfiguration(network);
842
843        // Now modify the network's EAP method.
844        network.enterpriseConfig =
845                WifiConfigurationTestUtil.createTLSWifiEnterpriseConfigWithNonePhase2();
846
847        // Fail this update because of cert installation failure.
848        when(mWifiKeyStore
849                .updateNetworkKeys(any(WifiConfiguration.class), any(WifiConfiguration.class)))
850                .thenReturn(false);
851        NetworkUpdateResult result =
852                mWifiConfigManager.addOrUpdateNetwork(network, TEST_UPDATE_UID);
853        assertTrue(result.getNetworkId() == WifiConfiguration.INVALID_NETWORK_ID);
854
855        // Now verify that there was no change to the network configurations.
856        WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate(
857                originalNetwork,
858                mWifiConfigManager.getConfiguredNetworkWithPassword(originalNetwork.networkId));
859    }
860
861    /**
862     * Verifies the matching of networks with different encryption types with the
863     * corresponding scan detail using
864     * {@link WifiConfigManager#getSavedNetworkForScanDetailAndCache(ScanDetail)}.
865     * The test also verifies that the provided scan detail was cached,
866     */
867    @Test
868    public void testMatchScanDetailToNetworksAndCache() {
869        // Create networks of different types and ensure that they're all matched using
870        // the corresponding ScanDetail correctly.
871        verifyAddSingleNetworkAndMatchScanDetailToNetworkAndCache(
872                WifiConfigurationTestUtil.createOpenNetwork());
873        verifyAddSingleNetworkAndMatchScanDetailToNetworkAndCache(
874                WifiConfigurationTestUtil.createWepNetwork());
875        verifyAddSingleNetworkAndMatchScanDetailToNetworkAndCache(
876                WifiConfigurationTestUtil.createPskNetwork());
877        verifyAddSingleNetworkAndMatchScanDetailToNetworkAndCache(
878                WifiConfigurationTestUtil.createEapNetwork());
879    }
880
881    /**
882     * Verifies that scan details with wrong SSID/authentication types are not matched using
883     * {@link WifiConfigManager#getSavedNetworkForScanDetailAndCache(ScanDetail)}
884     * to the added networks.
885     */
886    @Test
887    public void testNoMatchScanDetailToNetwork() {
888        // First create networks of different types.
889        WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
890        WifiConfiguration wepNetwork = WifiConfigurationTestUtil.createWepNetwork();
891        WifiConfiguration pskNetwork = WifiConfigurationTestUtil.createPskNetwork();
892        WifiConfiguration eapNetwork = WifiConfigurationTestUtil.createEapNetwork();
893
894        // Now add them to WifiConfigManager.
895        verifyAddNetworkToWifiConfigManager(openNetwork);
896        verifyAddNetworkToWifiConfigManager(wepNetwork);
897        verifyAddNetworkToWifiConfigManager(pskNetwork);
898        verifyAddNetworkToWifiConfigManager(eapNetwork);
899
900        // Now create dummy scan detail corresponding to the networks.
901        ScanDetail openNetworkScanDetail = createScanDetailForNetwork(openNetwork);
902        ScanDetail wepNetworkScanDetail = createScanDetailForNetwork(wepNetwork);
903        ScanDetail pskNetworkScanDetail = createScanDetailForNetwork(pskNetwork);
904        ScanDetail eapNetworkScanDetail = createScanDetailForNetwork(eapNetwork);
905
906        // Now mix and match parameters from different scan details.
907        openNetworkScanDetail.getScanResult().SSID =
908                wepNetworkScanDetail.getScanResult().SSID;
909        wepNetworkScanDetail.getScanResult().capabilities =
910                pskNetworkScanDetail.getScanResult().capabilities;
911        pskNetworkScanDetail.getScanResult().capabilities =
912                eapNetworkScanDetail.getScanResult().capabilities;
913        eapNetworkScanDetail.getScanResult().capabilities =
914                openNetworkScanDetail.getScanResult().capabilities;
915
916        // Try to lookup a saved network using the modified scan details. All of these should fail.
917        assertNull(mWifiConfigManager.getSavedNetworkForScanDetailAndCache(openNetworkScanDetail));
918        assertNull(mWifiConfigManager.getSavedNetworkForScanDetailAndCache(wepNetworkScanDetail));
919        assertNull(mWifiConfigManager.getSavedNetworkForScanDetailAndCache(pskNetworkScanDetail));
920        assertNull(mWifiConfigManager.getSavedNetworkForScanDetailAndCache(eapNetworkScanDetail));
921
922        // All the cache's should be empty as well.
923        assertNull(mWifiConfigManager.getScanDetailCacheForNetwork(openNetwork.networkId));
924        assertNull(mWifiConfigManager.getScanDetailCacheForNetwork(wepNetwork.networkId));
925        assertNull(mWifiConfigManager.getScanDetailCacheForNetwork(pskNetwork.networkId));
926        assertNull(mWifiConfigManager.getScanDetailCacheForNetwork(eapNetwork.networkId));
927    }
928
929    /**
930     * Verifies that scan detail cache is trimmed down when the size of the cache for a network
931     * exceeds {@link WifiConfigManager#SCAN_CACHE_ENTRIES_MAX_SIZE}.
932     */
933    @Test
934    public void testScanDetailCacheTrimForNetwork() {
935        // Add a single network.
936        WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
937        verifyAddNetworkToWifiConfigManager(openNetwork);
938
939        ScanDetailCache scanDetailCache;
940        String testBssidPrefix = "00:a5:b8:c9:45:";
941
942        // Modify |BSSID| field in the scan result and add copies of scan detail
943        // |SCAN_CACHE_ENTRIES_MAX_SIZE| times.
944        int scanDetailNum = 1;
945        for (; scanDetailNum <= WifiConfigManager.SCAN_CACHE_ENTRIES_MAX_SIZE; scanDetailNum++) {
946            // Create dummy scan detail caches with different BSSID for the network.
947            ScanDetail scanDetail =
948                    createScanDetailForNetwork(
949                            openNetwork, String.format("%s%02x", testBssidPrefix, scanDetailNum));
950            assertNotNull(
951                    mWifiConfigManager.getSavedNetworkForScanDetailAndCache(scanDetail));
952
953            // The size of scan detail cache should keep growing until it hits
954            // |SCAN_CACHE_ENTRIES_MAX_SIZE|.
955            scanDetailCache =
956                    mWifiConfigManager.getScanDetailCacheForNetwork(openNetwork.networkId);
957            assertEquals(scanDetailNum, scanDetailCache.size());
958        }
959
960        // Now add the |SCAN_CACHE_ENTRIES_MAX_SIZE + 1| entry. This should trigger the trim.
961        ScanDetail scanDetail =
962                createScanDetailForNetwork(
963                        openNetwork, String.format("%s%02x", testBssidPrefix, scanDetailNum));
964        assertNotNull(mWifiConfigManager.getSavedNetworkForScanDetailAndCache(scanDetail));
965
966        // Retrieve the scan detail cache and ensure that the size was trimmed down to
967        // |SCAN_CACHE_ENTRIES_TRIM_SIZE + 1|. The "+1" is to account for the new entry that
968        // was added after the trim.
969        scanDetailCache = mWifiConfigManager.getScanDetailCacheForNetwork(openNetwork.networkId);
970        assertEquals(WifiConfigManager.SCAN_CACHE_ENTRIES_TRIM_SIZE + 1, scanDetailCache.size());
971    }
972
973    /**
974     * Verifies that hasEverConnected is false for a newly added network.
975     */
976    @Test
977    public void testAddNetworkHasEverConnectedFalse() {
978        verifyAddNetworkHasEverConnectedFalse(WifiConfigurationTestUtil.createOpenNetwork());
979    }
980
981    /**
982     * Verifies that hasEverConnected is false for a newly added network even when new config has
983     * mistakenly set HasEverConnected to true.
984     */
985    @Test
986    public void testAddNetworkOverridesHasEverConnectedWhenTrueInNewConfig() {
987        WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
988        openNetwork.getNetworkSelectionStatus().setHasEverConnected(true);
989        verifyAddNetworkHasEverConnectedFalse(openNetwork);
990    }
991
992    /**
993     * Verify that the |HasEverConnected| is set when
994     * {@link WifiConfigManager#updateNetworkAfterConnect(int)} is invoked.
995     */
996    @Test
997    public void testUpdateConfigAfterConnect() {
998        WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
999        verifyAddNetworkHasEverConnectedFalse(openNetwork);
1000        verifyUpdateNetworkAfterConnectHasEverConnectedTrue(openNetwork.networkId);
1001    }
1002
1003    /**
1004     * Verifies that hasEverConnected is cleared when a network config |preSharedKey| is updated.
1005     */
1006    @Test
1007    public void testUpdatePreSharedKeyClearsHasEverConnected() {
1008        WifiConfiguration pskNetwork = WifiConfigurationTestUtil.createPskNetwork();
1009        verifyAddNetworkHasEverConnectedFalse(pskNetwork);
1010        verifyUpdateNetworkAfterConnectHasEverConnectedTrue(pskNetwork.networkId);
1011
1012        // Now update the same network with a different psk.
1013        assertFalse(pskNetwork.preSharedKey.equals("newpassword"));
1014        pskNetwork.preSharedKey = "newpassword";
1015        verifyUpdateNetworkWithCredentialChangeHasEverConnectedFalse(pskNetwork);
1016    }
1017
1018    /**
1019     * Verifies that hasEverConnected is cleared when a network config |wepKeys| is updated.
1020     */
1021    @Test
1022    public void testUpdateWepKeysClearsHasEverConnected() {
1023        WifiConfiguration wepNetwork = WifiConfigurationTestUtil.createWepNetwork();
1024        verifyAddNetworkHasEverConnectedFalse(wepNetwork);
1025        verifyUpdateNetworkAfterConnectHasEverConnectedTrue(wepNetwork.networkId);
1026
1027        // Now update the same network with a different wep.
1028        assertFalse(wepNetwork.wepKeys[0].equals("newpassword"));
1029        wepNetwork.wepKeys[0] = "newpassword";
1030        verifyUpdateNetworkWithCredentialChangeHasEverConnectedFalse(wepNetwork);
1031    }
1032
1033    /**
1034     * Verifies that hasEverConnected is cleared when a network config |wepTxKeyIndex| is updated.
1035     */
1036    @Test
1037    public void testUpdateWepTxKeyClearsHasEverConnected() {
1038        WifiConfiguration wepNetwork = WifiConfigurationTestUtil.createWepNetwork();
1039        verifyAddNetworkHasEverConnectedFalse(wepNetwork);
1040        verifyUpdateNetworkAfterConnectHasEverConnectedTrue(wepNetwork.networkId);
1041
1042        // Now update the same network with a different wep.
1043        assertFalse(wepNetwork.wepTxKeyIndex == 3);
1044        wepNetwork.wepTxKeyIndex = 3;
1045        verifyUpdateNetworkWithCredentialChangeHasEverConnectedFalse(wepNetwork);
1046    }
1047
1048    /**
1049     * Verifies that hasEverConnected is cleared when a network config |allowedKeyManagement| is
1050     * updated.
1051     */
1052    @Test
1053    public void testUpdateAllowedKeyManagementClearsHasEverConnected() {
1054        WifiConfiguration pskNetwork = WifiConfigurationTestUtil.createPskNetwork();
1055        verifyAddNetworkHasEverConnectedFalse(pskNetwork);
1056        verifyUpdateNetworkAfterConnectHasEverConnectedTrue(pskNetwork.networkId);
1057
1058        assertFalse(pskNetwork.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.IEEE8021X));
1059        pskNetwork.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.IEEE8021X);
1060        verifyUpdateNetworkWithCredentialChangeHasEverConnectedFalse(pskNetwork);
1061    }
1062
1063    /**
1064     * Verifies that hasEverConnected is cleared when a network config |allowedProtocol| is
1065     * updated.
1066     */
1067    @Test
1068    public void testUpdateProtocolsClearsHasEverConnected() {
1069        WifiConfiguration pskNetwork = WifiConfigurationTestUtil.createPskNetwork();
1070        verifyAddNetworkHasEverConnectedFalse(pskNetwork);
1071        verifyUpdateNetworkAfterConnectHasEverConnectedTrue(pskNetwork.networkId);
1072
1073        assertFalse(pskNetwork.allowedProtocols.get(WifiConfiguration.Protocol.OSEN));
1074        pskNetwork.allowedProtocols.set(WifiConfiguration.Protocol.OSEN);
1075        verifyUpdateNetworkWithCredentialChangeHasEverConnectedFalse(pskNetwork);
1076    }
1077
1078    /**
1079     * Verifies that hasEverConnected is cleared when a network config |allowedAuthAlgorithms| is
1080     * updated.
1081     */
1082    @Test
1083    public void testUpdateAllowedAuthAlgorithmsClearsHasEverConnected() {
1084        WifiConfiguration pskNetwork = WifiConfigurationTestUtil.createPskNetwork();
1085        verifyAddNetworkHasEverConnectedFalse(pskNetwork);
1086        verifyUpdateNetworkAfterConnectHasEverConnectedTrue(pskNetwork.networkId);
1087
1088        assertFalse(pskNetwork.allowedAuthAlgorithms.get(WifiConfiguration.AuthAlgorithm.LEAP));
1089        pskNetwork.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.LEAP);
1090        verifyUpdateNetworkWithCredentialChangeHasEverConnectedFalse(pskNetwork);
1091    }
1092
1093    /**
1094     * Verifies that hasEverConnected is cleared when a network config |allowedPairwiseCiphers| is
1095     * updated.
1096     */
1097    @Test
1098    public void testUpdateAllowedPairwiseCiphersClearsHasEverConnected() {
1099        WifiConfiguration pskNetwork = WifiConfigurationTestUtil.createPskNetwork();
1100        verifyAddNetworkHasEverConnectedFalse(pskNetwork);
1101        verifyUpdateNetworkAfterConnectHasEverConnectedTrue(pskNetwork.networkId);
1102
1103        assertFalse(pskNetwork.allowedPairwiseCiphers.get(WifiConfiguration.PairwiseCipher.NONE));
1104        pskNetwork.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.NONE);
1105        verifyUpdateNetworkWithCredentialChangeHasEverConnectedFalse(pskNetwork);
1106    }
1107
1108    /**
1109     * Verifies that hasEverConnected is cleared when a network config |allowedGroup| is
1110     * updated.
1111     */
1112    @Test
1113    public void testUpdateAllowedGroupCiphersClearsHasEverConnected() {
1114        WifiConfiguration pskNetwork = WifiConfigurationTestUtil.createPskNetwork();
1115        verifyAddNetworkHasEverConnectedFalse(pskNetwork);
1116        verifyUpdateNetworkAfterConnectHasEverConnectedTrue(pskNetwork.networkId);
1117
1118        assertTrue(pskNetwork.allowedGroupCiphers.get(WifiConfiguration.GroupCipher.WEP104));
1119        pskNetwork.allowedGroupCiphers.clear(WifiConfiguration.GroupCipher.WEP104);
1120        verifyUpdateNetworkWithCredentialChangeHasEverConnectedFalse(pskNetwork);
1121    }
1122
1123    /**
1124     * Verifies that hasEverConnected is cleared when a network config |hiddenSSID| is
1125     * updated.
1126     */
1127    @Test
1128    public void testUpdateHiddenSSIDClearsHasEverConnected() {
1129        WifiConfiguration pskNetwork = WifiConfigurationTestUtil.createPskNetwork();
1130        verifyAddNetworkHasEverConnectedFalse(pskNetwork);
1131        verifyUpdateNetworkAfterConnectHasEverConnectedTrue(pskNetwork.networkId);
1132
1133        assertFalse(pskNetwork.hiddenSSID);
1134        pskNetwork.hiddenSSID = true;
1135        verifyUpdateNetworkWithCredentialChangeHasEverConnectedFalse(pskNetwork);
1136    }
1137
1138    /**
1139     * Verifies that hasEverConnected is not cleared when a network config |requirePMF| is
1140     * updated.
1141     */
1142    @Test
1143    public void testUpdateRequirePMFDoesNotClearHasEverConnected() {
1144        WifiConfiguration pskNetwork = WifiConfigurationTestUtil.createPskNetwork();
1145        verifyAddNetworkHasEverConnectedFalse(pskNetwork);
1146        verifyUpdateNetworkAfterConnectHasEverConnectedTrue(pskNetwork.networkId);
1147
1148        assertFalse(pskNetwork.requirePMF);
1149        pskNetwork.requirePMF = true;
1150
1151        NetworkUpdateResult result =
1152                verifyUpdateNetworkToWifiConfigManagerWithoutIpChange(pskNetwork);
1153        WifiConfiguration retrievedNetwork =
1154                mWifiConfigManager.getConfiguredNetwork(result.getNetworkId());
1155        assertTrue("Updating network non-credentials config should not clear hasEverConnected.",
1156                retrievedNetwork.getNetworkSelectionStatus().getHasEverConnected());
1157    }
1158
1159    /**
1160     * Verifies that hasEverConnected is cleared when a network config |enterpriseConfig| is
1161     * updated.
1162     */
1163    @Test
1164    public void testUpdateEnterpriseConfigClearsHasEverConnected() {
1165        WifiConfiguration eapNetwork = WifiConfigurationTestUtil.createEapNetwork();
1166        eapNetwork.enterpriseConfig =
1167                WifiConfigurationTestUtil.createPEAPWifiEnterpriseConfigWithGTCPhase2();
1168        verifyAddNetworkHasEverConnectedFalse(eapNetwork);
1169        verifyUpdateNetworkAfterConnectHasEverConnectedTrue(eapNetwork.networkId);
1170
1171        assertFalse(eapNetwork.enterpriseConfig.getEapMethod() == WifiEnterpriseConfig.Eap.TLS);
1172        eapNetwork.enterpriseConfig.setEapMethod(WifiEnterpriseConfig.Eap.TLS);
1173        verifyUpdateNetworkWithCredentialChangeHasEverConnectedFalse(eapNetwork);
1174    }
1175
1176    /**
1177     * Verifies the ordering of network list generated using
1178     * {@link WifiConfigManager#retrievePnoNetworkList()}.
1179     */
1180    @Test
1181    public void testRetrievePnoList() {
1182        // Create and add 3 networks.
1183        WifiConfiguration network1 = WifiConfigurationTestUtil.createEapNetwork();
1184        WifiConfiguration network2 = WifiConfigurationTestUtil.createPskNetwork();
1185        WifiConfiguration network3 = WifiConfigurationTestUtil.createOpenHiddenNetwork();
1186        verifyAddNetworkToWifiConfigManager(network1);
1187        verifyAddNetworkToWifiConfigManager(network2);
1188        verifyAddNetworkToWifiConfigManager(network3);
1189
1190        // Enable all of them.
1191        assertTrue(mWifiConfigManager.enableNetwork(network1.networkId, false, TEST_CREATOR_UID));
1192        assertTrue(mWifiConfigManager.enableNetwork(network2.networkId, false, TEST_CREATOR_UID));
1193        assertTrue(mWifiConfigManager.enableNetwork(network3.networkId, false, TEST_CREATOR_UID));
1194
1195        // Now set scan results in 2 of them to set the corresponding
1196        // {@link NetworkSelectionStatus#mSeenInLastQualifiedNetworkSelection} field.
1197        assertTrue(mWifiConfigManager.setNetworkCandidateScanResult(
1198                network1.networkId, createScanDetailForNetwork(network1).getScanResult(), 54));
1199        assertTrue(mWifiConfigManager.setNetworkCandidateScanResult(
1200                network3.networkId, createScanDetailForNetwork(network3).getScanResult(), 54));
1201
1202        // Now increment |network3|'s association count. This should ensure that this network
1203        // is preferred over |network1|.
1204        assertTrue(mWifiConfigManager.updateNetworkAfterConnect(network3.networkId));
1205
1206        // Retrieve the Pno network list & verify the order of the networks returned.
1207        List<WifiScanner.PnoSettings.PnoNetwork> pnoNetworks =
1208                mWifiConfigManager.retrievePnoNetworkList();
1209        assertEquals(3, pnoNetworks.size());
1210        assertEquals(network3.SSID, pnoNetworks.get(0).ssid);
1211        assertEquals(network1.SSID, pnoNetworks.get(1).ssid);
1212        assertEquals(network2.SSID, pnoNetworks.get(2).ssid);
1213
1214        // Now permanently disable |network3|. This should remove network 3 from the list.
1215        assertTrue(mWifiConfigManager.disableNetwork(network3.networkId, TEST_CREATOR_UID));
1216
1217        // Retrieve the Pno network list again & verify the order of the networks returned.
1218        pnoNetworks = mWifiConfigManager.retrievePnoNetworkList();
1219        assertEquals(2, pnoNetworks.size());
1220        assertEquals(network1.SSID, pnoNetworks.get(0).ssid);
1221        assertEquals(network2.SSID, pnoNetworks.get(1).ssid);
1222    }
1223
1224    /**
1225     * Verifies the linking of networks when they have the same default GW Mac address in
1226     * {@link WifiConfigManager#getOrCreateScanDetailCacheForNetwork(WifiConfiguration)}.
1227     */
1228    @Test
1229    public void testNetworkLinkUsingGwMacAddress() {
1230        WifiConfiguration network1 = WifiConfigurationTestUtil.createPskNetwork();
1231        WifiConfiguration network2 = WifiConfigurationTestUtil.createPskNetwork();
1232        WifiConfiguration network3 = WifiConfigurationTestUtil.createPskNetwork();
1233        verifyAddNetworkToWifiConfigManager(network1);
1234        verifyAddNetworkToWifiConfigManager(network2);
1235        verifyAddNetworkToWifiConfigManager(network3);
1236
1237        // Set the same default GW mac address for all of the networks.
1238        assertTrue(mWifiConfigManager.setNetworkDefaultGwMacAddress(
1239                network1.networkId, TEST_DEFAULT_GW_MAC_ADDRESS));
1240        assertTrue(mWifiConfigManager.setNetworkDefaultGwMacAddress(
1241                network2.networkId, TEST_DEFAULT_GW_MAC_ADDRESS));
1242        assertTrue(mWifiConfigManager.setNetworkDefaultGwMacAddress(
1243                network3.networkId, TEST_DEFAULT_GW_MAC_ADDRESS));
1244
1245        // Now create dummy scan detail corresponding to the networks.
1246        ScanDetail networkScanDetail1 = createScanDetailForNetwork(network1);
1247        ScanDetail networkScanDetail2 = createScanDetailForNetwork(network2);
1248        ScanDetail networkScanDetail3 = createScanDetailForNetwork(network3);
1249
1250        // Now save all these scan details corresponding to each of this network and expect
1251        // all of these networks to be linked with each other.
1252        assertNotNull(mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail1));
1253        assertNotNull(mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail2));
1254        assertNotNull(mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail3));
1255
1256        List<WifiConfiguration> retrievedNetworks =
1257                mWifiConfigManager.getConfiguredNetworks();
1258        for (WifiConfiguration network : retrievedNetworks) {
1259            assertEquals(2, network.linkedConfigurations.size());
1260            for (WifiConfiguration otherNetwork : retrievedNetworks) {
1261                if (otherNetwork == network) {
1262                    continue;
1263                }
1264                assertNotNull(network.linkedConfigurations.get(otherNetwork.configKey()));
1265            }
1266        }
1267    }
1268
1269    /**
1270     * Verifies the linking of networks when they have scan results with same first 16 ASCII of
1271     * bssid in
1272     * {@link WifiConfigManager#getOrCreateScanDetailCacheForNetwork(WifiConfiguration)}.
1273     */
1274    @Test
1275    public void testNetworkLinkUsingBSSIDMatch() {
1276        WifiConfiguration network1 = WifiConfigurationTestUtil.createPskNetwork();
1277        WifiConfiguration network2 = WifiConfigurationTestUtil.createPskNetwork();
1278        WifiConfiguration network3 = WifiConfigurationTestUtil.createPskNetwork();
1279        verifyAddNetworkToWifiConfigManager(network1);
1280        verifyAddNetworkToWifiConfigManager(network2);
1281        verifyAddNetworkToWifiConfigManager(network3);
1282
1283        // Create scan results with bssid which is different in only the last char.
1284        ScanDetail networkScanDetail1 = createScanDetailForNetwork(network1, "af:89:56:34:56:67");
1285        ScanDetail networkScanDetail2 = createScanDetailForNetwork(network2, "af:89:56:34:56:68");
1286        ScanDetail networkScanDetail3 = createScanDetailForNetwork(network3, "af:89:56:34:56:69");
1287
1288        // Now save all these scan details corresponding to each of this network and expect
1289        // all of these networks to be linked with each other.
1290        assertNotNull(mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail1));
1291        assertNotNull(mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail2));
1292        assertNotNull(mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail3));
1293
1294        List<WifiConfiguration> retrievedNetworks =
1295                mWifiConfigManager.getConfiguredNetworks();
1296        for (WifiConfiguration network : retrievedNetworks) {
1297            assertEquals(2, network.linkedConfigurations.size());
1298            for (WifiConfiguration otherNetwork : retrievedNetworks) {
1299                if (otherNetwork == network) {
1300                    continue;
1301                }
1302                assertNotNull(network.linkedConfigurations.get(otherNetwork.configKey()));
1303            }
1304        }
1305    }
1306
1307    /**
1308     * Verifies the linking of networks does not happen for non WPA networks when they have scan
1309     * results with same first 16 ASCII of bssid in
1310     * {@link WifiConfigManager#getOrCreateScanDetailCacheForNetwork(WifiConfiguration)}.
1311     */
1312    @Test
1313    public void testNoNetworkLinkUsingBSSIDMatchForNonWpaNetworks() {
1314        WifiConfiguration network1 = WifiConfigurationTestUtil.createOpenNetwork();
1315        WifiConfiguration network2 = WifiConfigurationTestUtil.createPskNetwork();
1316        verifyAddNetworkToWifiConfigManager(network1);
1317        verifyAddNetworkToWifiConfigManager(network2);
1318
1319        // Create scan results with bssid which is different in only the last char.
1320        ScanDetail networkScanDetail1 = createScanDetailForNetwork(network1, "af:89:56:34:56:67");
1321        ScanDetail networkScanDetail2 = createScanDetailForNetwork(network2, "af:89:56:34:56:68");
1322
1323        assertNotNull(mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail1));
1324        assertNotNull(mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail2));
1325
1326        List<WifiConfiguration> retrievedNetworks =
1327                mWifiConfigManager.getConfiguredNetworks();
1328        for (WifiConfiguration network : retrievedNetworks) {
1329            assertNull(network.linkedConfigurations);
1330        }
1331    }
1332
1333    /**
1334     * Verifies the linking of networks does not happen for networks with more than
1335     * {@link WifiConfigManager#LINK_CONFIGURATION_MAX_SCAN_CACHE_ENTRIES} scan
1336     * results with same first 16 ASCII of bssid in
1337     * {@link WifiConfigManager#getOrCreateScanDetailCacheForNetwork(WifiConfiguration)}.
1338     */
1339    @Test
1340    public void testNoNetworkLinkUsingBSSIDMatchForNetworksWithHighScanDetailCacheSize() {
1341        WifiConfiguration network1 = WifiConfigurationTestUtil.createPskNetwork();
1342        WifiConfiguration network2 = WifiConfigurationTestUtil.createPskNetwork();
1343        verifyAddNetworkToWifiConfigManager(network1);
1344        verifyAddNetworkToWifiConfigManager(network2);
1345
1346        // Create 7 scan results with bssid which is different in only the last char.
1347        String test_bssid_base = "af:89:56:34:56:6";
1348        int scan_result_num = 0;
1349        for (; scan_result_num < WifiConfigManager.LINK_CONFIGURATION_MAX_SCAN_CACHE_ENTRIES + 1;
1350             scan_result_num++) {
1351            ScanDetail networkScanDetail =
1352                    createScanDetailForNetwork(
1353                            network1, test_bssid_base + Integer.toString(scan_result_num));
1354            assertNotNull(
1355                    mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail));
1356        }
1357
1358        // Now add 1 scan result to the other network with bssid which is different in only the
1359        // last char.
1360        ScanDetail networkScanDetail2 =
1361                createScanDetailForNetwork(
1362                        network2, test_bssid_base + Integer.toString(scan_result_num++));
1363        assertNotNull(mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail2));
1364
1365        List<WifiConfiguration> retrievedNetworks =
1366                mWifiConfigManager.getConfiguredNetworks();
1367        for (WifiConfiguration network : retrievedNetworks) {
1368            assertNull(network.linkedConfigurations);
1369        }
1370    }
1371
1372    /**
1373     * Verifies the linking of networks when they have scan results with same first 16 ASCII of
1374     * bssid in {@link WifiConfigManager#getOrCreateScanDetailCacheForNetwork(WifiConfiguration)}
1375     * and then subsequently delinked when the networks have default gateway set which do not match.
1376     */
1377    @Test
1378    public void testNetworkLinkUsingBSSIDMatchAndThenUnlinkDueToGwMacAddress() {
1379        WifiConfiguration network1 = WifiConfigurationTestUtil.createPskNetwork();
1380        WifiConfiguration network2 = WifiConfigurationTestUtil.createPskNetwork();
1381        verifyAddNetworkToWifiConfigManager(network1);
1382        verifyAddNetworkToWifiConfigManager(network2);
1383
1384        // Create scan results with bssid which is different in only the last char.
1385        ScanDetail networkScanDetail1 = createScanDetailForNetwork(network1, "af:89:56:34:56:67");
1386        ScanDetail networkScanDetail2 = createScanDetailForNetwork(network2, "af:89:56:34:56:68");
1387
1388        // Now save all these scan details corresponding to each of this network and expect
1389        // all of these networks to be linked with each other.
1390        assertNotNull(mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail1));
1391        assertNotNull(mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail2));
1392
1393        List<WifiConfiguration> retrievedNetworks =
1394                mWifiConfigManager.getConfiguredNetworks();
1395        for (WifiConfiguration network : retrievedNetworks) {
1396            assertEquals(1, network.linkedConfigurations.size());
1397            for (WifiConfiguration otherNetwork : retrievedNetworks) {
1398                if (otherNetwork == network) {
1399                    continue;
1400                }
1401                assertNotNull(network.linkedConfigurations.get(otherNetwork.configKey()));
1402            }
1403        }
1404
1405        // Now Set different GW mac address for both the networks and ensure they're unlinked.
1406        assertTrue(mWifiConfigManager.setNetworkDefaultGwMacAddress(
1407                network1.networkId, "de:ad:fe:45:23:34"));
1408        assertTrue(mWifiConfigManager.setNetworkDefaultGwMacAddress(
1409                network2.networkId, "ad:de:fe:45:23:34"));
1410
1411        // Add some dummy scan results again to re-evaluate the linking of networks.
1412        assertNotNull(mWifiConfigManager.getSavedNetworkForScanDetailAndCache(
1413                createScanDetailForNetwork(network1, "af:89:56:34:45:67")));
1414        assertNotNull(mWifiConfigManager.getSavedNetworkForScanDetailAndCache(
1415                createScanDetailForNetwork(network1, "af:89:56:34:45:68")));
1416
1417        retrievedNetworks = mWifiConfigManager.getConfiguredNetworks();
1418        for (WifiConfiguration network : retrievedNetworks) {
1419            assertNull(network.linkedConfigurations);
1420        }
1421    }
1422
1423    /*
1424     * Verifies the creation of channel list using
1425     * {@link WifiConfigManager#fetchChannelSetForNetworkForPartialScan(int, long)}.
1426     */
1427    @Test
1428    public void testFetchChannelSetForNetwork() {
1429        WifiConfiguration network = WifiConfigurationTestUtil.createPskNetwork();
1430        verifyAddNetworkToWifiConfigManager(network);
1431
1432        // Create 5 scan results with different bssid's & frequencies.
1433        String test_bssid_base = "af:89:56:34:56:6";
1434        for (int i = 0; i < TEST_FREQ_LIST.length; i++) {
1435            ScanDetail networkScanDetail =
1436                    createScanDetailForNetwork(
1437                            network, test_bssid_base + Integer.toString(i), 0, TEST_FREQ_LIST[i]);
1438            assertNotNull(
1439                    mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail));
1440
1441        }
1442        assertEquals(new HashSet<Integer>(Arrays.asList(TEST_FREQ_LIST)),
1443                mWifiConfigManager.fetchChannelSetForNetworkForPartialScan(network.networkId, 1));
1444    }
1445
1446    /**
1447     * Verifies the creation of channel list using
1448     * {@link WifiConfigManager#fetchChannelSetForNetworkForPartialScan(int, long)} and ensures
1449     * that scan results which have a timestamp  beyond the provided age are not used in the
1450     * channel list.
1451     */
1452    @Test
1453    public void testFetchChannelSetForNetworkIgnoresStaleScanResults() {
1454        WifiConfiguration network = WifiConfigurationTestUtil.createPskNetwork();
1455        verifyAddNetworkToWifiConfigManager(network);
1456
1457        long wallClockBase = 0;
1458        // Create 5 scan results with different bssid's & frequencies.
1459        String test_bssid_base = "af:89:56:34:56:6";
1460        for (int i = 0; i < TEST_FREQ_LIST.length; i++) {
1461            // Increment the seen value in the scan results for each of them.
1462            when(mClock.getWallClockMillis()).thenReturn(wallClockBase + i);
1463            ScanDetail networkScanDetail =
1464                    createScanDetailForNetwork(
1465                            network, test_bssid_base + Integer.toString(i), 0, TEST_FREQ_LIST[i]);
1466            assertNotNull(
1467                    mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail));
1468
1469        }
1470        int ageInMillis = 4;
1471        // Now fetch only scan results which are 4 millis stale. This should ignore the first
1472        // scan result.
1473        assertEquals(
1474                new HashSet<>(Arrays.asList(
1475                        Arrays.copyOfRange(
1476                                TEST_FREQ_LIST,
1477                                TEST_FREQ_LIST.length - ageInMillis, TEST_FREQ_LIST.length))),
1478                mWifiConfigManager.fetchChannelSetForNetworkForPartialScan(
1479                        network.networkId, ageInMillis));
1480    }
1481
1482    /**
1483     * Verifies the creation of channel list using
1484     * {@link WifiConfigManager#fetchChannelSetForNetworkForPartialScan(int, long)} and ensures
1485     * that the list size does not exceed the max configured for the device.
1486     */
1487    @Test
1488    public void testFetchChannelSetForNetworkIsLimitedToConfiguredSize() {
1489        // Need to recreate the WifiConfigManager instance for this test to modify the config
1490        // value which is read only in the constructor.
1491        int maxListSize = 3;
1492        mResources.setInteger(
1493                R.integer.config_wifi_framework_associated_partial_scan_max_num_active_channels,
1494                maxListSize);
1495        createWifiConfigManager();
1496
1497        WifiConfiguration network = WifiConfigurationTestUtil.createPskNetwork();
1498        verifyAddNetworkToWifiConfigManager(network);
1499
1500        // Create 5 scan results with different bssid's & frequencies.
1501        String test_bssid_base = "af:89:56:34:56:6";
1502        for (int i = 0; i < TEST_FREQ_LIST.length; i++) {
1503            ScanDetail networkScanDetail =
1504                    createScanDetailForNetwork(
1505                            network, test_bssid_base + Integer.toString(i), 0, TEST_FREQ_LIST[i]);
1506            assertNotNull(
1507                    mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail));
1508
1509        }
1510        // Ensure that the fetched list size is limited.
1511        assertEquals(maxListSize,
1512                mWifiConfigManager.fetchChannelSetForNetworkForPartialScan(
1513                        network.networkId, 1).size());
1514    }
1515
1516    /**
1517     * Verifies the creation of channel list using
1518     * {@link WifiConfigManager#fetchChannelSetForNetworkForPartialScan(int, long)} and ensures
1519     * that scan results from linked networks are used in the channel list.
1520     */
1521    @Test
1522    public void testFetchChannelSetForNetworkIncludesLinkedNetworks() {
1523        WifiConfiguration network1 = WifiConfigurationTestUtil.createPskNetwork();
1524        WifiConfiguration network2 = WifiConfigurationTestUtil.createPskNetwork();
1525        verifyAddNetworkToWifiConfigManager(network1);
1526        verifyAddNetworkToWifiConfigManager(network2);
1527
1528        String test_bssid_base = "af:89:56:34:56:6";
1529        int TEST_FREQ_LISTIdx = 0;
1530        // Create 3 scan results with different bssid's & frequencies for network 1.
1531        for (; TEST_FREQ_LISTIdx < TEST_FREQ_LIST.length / 2; TEST_FREQ_LISTIdx++) {
1532            ScanDetail networkScanDetail =
1533                    createScanDetailForNetwork(
1534                            network1, test_bssid_base + Integer.toString(TEST_FREQ_LISTIdx), 0,
1535                            TEST_FREQ_LIST[TEST_FREQ_LISTIdx]);
1536            assertNotNull(
1537                    mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail));
1538
1539        }
1540        // Create 3 scan results with different bssid's & frequencies for network 2.
1541        for (; TEST_FREQ_LISTIdx < TEST_FREQ_LIST.length; TEST_FREQ_LISTIdx++) {
1542            ScanDetail networkScanDetail =
1543                    createScanDetailForNetwork(
1544                            network2, test_bssid_base + Integer.toString(TEST_FREQ_LISTIdx), 0,
1545                            TEST_FREQ_LIST[TEST_FREQ_LISTIdx]);
1546            assertNotNull(
1547                    mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail));
1548        }
1549
1550        // Link the 2 configurations together using the GwMacAddress.
1551        assertTrue(mWifiConfigManager.setNetworkDefaultGwMacAddress(
1552                network1.networkId, TEST_DEFAULT_GW_MAC_ADDRESS));
1553        assertTrue(mWifiConfigManager.setNetworkDefaultGwMacAddress(
1554                network2.networkId, TEST_DEFAULT_GW_MAC_ADDRESS));
1555
1556        // The channel list fetched should include scan results from both the linked networks.
1557        assertEquals(new HashSet<Integer>(Arrays.asList(TEST_FREQ_LIST)),
1558                mWifiConfigManager.fetchChannelSetForNetworkForPartialScan(network1.networkId, 1));
1559        assertEquals(new HashSet<Integer>(Arrays.asList(TEST_FREQ_LIST)),
1560                mWifiConfigManager.fetchChannelSetForNetworkForPartialScan(network2.networkId, 1));
1561    }
1562
1563    /**
1564     * Verifies the creation of channel list using
1565     * {@link WifiConfigManager#fetchChannelSetForNetworkForPartialScan(int, long)} and ensures
1566     * that scan results from linked networks are used in the channel list and that the list size
1567     * does not exceed the max configured for the device.
1568     */
1569    @Test
1570    public void testFetchChannelSetForNetworkIncludesLinkedNetworksIsLimitedToConfiguredSize() {
1571        // Need to recreate the WifiConfigManager instance for this test to modify the config
1572        // value which is read only in the constructor.
1573        int maxListSize = 3;
1574        mResources.setInteger(
1575                R.integer.config_wifi_framework_associated_partial_scan_max_num_active_channels,
1576                maxListSize);
1577
1578        createWifiConfigManager();
1579        WifiConfiguration network1 = WifiConfigurationTestUtil.createPskNetwork();
1580        WifiConfiguration network2 = WifiConfigurationTestUtil.createPskNetwork();
1581        verifyAddNetworkToWifiConfigManager(network1);
1582        verifyAddNetworkToWifiConfigManager(network2);
1583
1584        String test_bssid_base = "af:89:56:34:56:6";
1585        int TEST_FREQ_LISTIdx = 0;
1586        // Create 3 scan results with different bssid's & frequencies for network 1.
1587        for (; TEST_FREQ_LISTIdx < TEST_FREQ_LIST.length / 2; TEST_FREQ_LISTIdx++) {
1588            ScanDetail networkScanDetail =
1589                    createScanDetailForNetwork(
1590                            network1, test_bssid_base + Integer.toString(TEST_FREQ_LISTIdx), 0,
1591                            TEST_FREQ_LIST[TEST_FREQ_LISTIdx]);
1592            assertNotNull(
1593                    mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail));
1594
1595        }
1596        // Create 3 scan results with different bssid's & frequencies for network 2.
1597        for (; TEST_FREQ_LISTIdx < TEST_FREQ_LIST.length; TEST_FREQ_LISTIdx++) {
1598            ScanDetail networkScanDetail =
1599                    createScanDetailForNetwork(
1600                            network2, test_bssid_base + Integer.toString(TEST_FREQ_LISTIdx), 0,
1601                            TEST_FREQ_LIST[TEST_FREQ_LISTIdx]);
1602            assertNotNull(
1603                    mWifiConfigManager.getSavedNetworkForScanDetailAndCache(networkScanDetail));
1604        }
1605
1606        // Link the 2 configurations together using the GwMacAddress.
1607        assertTrue(mWifiConfigManager.setNetworkDefaultGwMacAddress(
1608                network1.networkId, TEST_DEFAULT_GW_MAC_ADDRESS));
1609        assertTrue(mWifiConfigManager.setNetworkDefaultGwMacAddress(
1610                network2.networkId, TEST_DEFAULT_GW_MAC_ADDRESS));
1611
1612        // Ensure that the fetched list size is limited.
1613        assertEquals(maxListSize,
1614                mWifiConfigManager.fetchChannelSetForNetworkForPartialScan(
1615                        network1.networkId, 1).size());
1616        assertEquals(maxListSize,
1617                mWifiConfigManager.fetchChannelSetForNetworkForPartialScan(
1618                        network2.networkId, 1).size());
1619    }
1620
1621    /**
1622     * Verifies the foreground user switch using {@link WifiConfigManager#handleUserSwitch(int)}
1623     * and ensures that any non current user private networks are moved to shared store file.
1624     */
1625    @Test
1626    public void testHandleUserSwitchPushesOtherPrivateNetworksToSharedStore() throws Exception {
1627        int user1 = TEST_DEFAULT_USER;
1628        int user2 = TEST_DEFAULT_USER + 1;
1629        setupUserProfiles(user2);
1630
1631        int appId = 674;
1632
1633        // Create 3 networks. 1 for user1, 1 for user2 and 1 shared.
1634        final WifiConfiguration user1Network = WifiConfigurationTestUtil.createPskNetwork();
1635        user1Network.shared = false;
1636        user1Network.creatorUid = UserHandle.getUid(user1, appId);
1637        final WifiConfiguration user2Network = WifiConfigurationTestUtil.createPskNetwork();
1638        user2Network.shared = false;
1639        user2Network.creatorUid = UserHandle.getUid(user2, appId);
1640        final WifiConfiguration sharedNetwork = WifiConfigurationTestUtil.createPskNetwork();
1641
1642        // Set up the store data first that is loaded.
1643        List<WifiConfiguration> sharedNetworks = new ArrayList<WifiConfiguration>() {
1644            {
1645                add(sharedNetwork);
1646                add(user2Network);
1647            }
1648        };
1649        List<WifiConfiguration> userNetworks = new ArrayList<WifiConfiguration>() {
1650            {
1651                add(user1Network);
1652            }
1653        };
1654        WifiConfigStoreData loadStoreData =
1655                new WifiConfigStoreData(sharedNetworks, userNetworks, new HashSet<String>());
1656        when(mWifiConfigStore.read()).thenReturn(loadStoreData);
1657
1658        // Now switch the user to user2
1659        mWifiConfigManager.handleUserSwitch(user2);
1660
1661        // Set the expected network list before comparing. user1Network should be in shared data.
1662        // Note: In the real world, user1Network will no longer be visible now because it should
1663        // already be in user1's private store file. But, we're purposefully exposing it
1664        // via |loadStoreData| to test if other user's private networks are pushed to shared store.
1665        List<WifiConfiguration> expectedSharedNetworks = new ArrayList<WifiConfiguration>() {
1666            {
1667                add(sharedNetwork);
1668                add(user1Network);
1669            }
1670        };
1671        List<WifiConfiguration> expectedUserNetworks = new ArrayList<WifiConfiguration>() {
1672            {
1673                add(user2Network);
1674            }
1675        };
1676        // Capture the written data for the old user and ensure that it was empty.
1677        WifiConfigStoreData writtenStoreData = captureWriteStoreData();
1678        assertTrue(writtenStoreData.getConfigurations().isEmpty());
1679
1680        // Now capture the next written data and ensure that user1Network is now in shared data.
1681        writtenStoreData = captureWriteStoreData();
1682        WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate(
1683                expectedSharedNetworks, writtenStoreData.getSharedConfigurations());
1684        WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate(
1685                expectedUserNetworks, writtenStoreData.getUserConfigurations());
1686    }
1687
1688    /**
1689     * Verifies the foreground user switch using {@link WifiConfigManager#handleUserSwitch(int)}
1690     * and {@link WifiConfigManager#handleUserUnlock(int)} and ensures that the new store is
1691     * read immediately if the user is unlocked during the switch.
1692     */
1693    @Test
1694    public void testHandleUserSwitchWhenUnlocked() throws Exception {
1695        int user1 = TEST_DEFAULT_USER;
1696        int user2 = TEST_DEFAULT_USER + 1;
1697        setupUserProfiles(user2);
1698
1699        when(mWifiConfigStore.read()).thenReturn(
1700                new WifiConfigStoreData(
1701                        new ArrayList<WifiConfiguration>(), new ArrayList<WifiConfiguration>(),
1702                        new HashSet<String>()));
1703
1704        // user2 is unlocked and switched to foreground.
1705        when(mUserManager.isUserUnlockingOrUnlocked(user2)).thenReturn(true);
1706        mWifiConfigManager.handleUserSwitch(user2);
1707        // Ensure that the read was invoked.
1708        mContextConfigStoreMockOrder.verify(mWifiConfigStore).read();
1709    }
1710
1711    /**
1712     * Verifies the foreground user switch using {@link WifiConfigManager#handleUserSwitch(int)}
1713     * and {@link WifiConfigManager#handleUserUnlock(int)} and ensures that the new store is not
1714     * read until the user is unlocked.
1715     */
1716    public void testHandleUserSwitchWhenLocked() throws Exception {
1717        int user1 = TEST_DEFAULT_USER;
1718        int user2 = TEST_DEFAULT_USER + 1;
1719        setupUserProfiles(user2);
1720
1721        // user2 is locked and switched to foreground.
1722        when(mUserManager.isUserUnlockingOrUnlocked(user2)).thenReturn(false);
1723        mWifiConfigManager.handleUserSwitch(user2);
1724
1725        // Ensure that the read was not invoked.
1726        mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).read();
1727
1728        // Now try unlocking some other user (user1), this should be ignored.
1729        mWifiConfigManager.handleUserUnlock(user1);
1730        mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).read();
1731
1732        when(mWifiConfigStore.read()).thenReturn(
1733                new WifiConfigStoreData(
1734                        new ArrayList<WifiConfiguration>(), new ArrayList<WifiConfiguration>(),
1735                        new HashSet<String>()));
1736
1737        // Unlock the user2 and ensure that we read the data now.
1738        mWifiConfigManager.handleUserUnlock(user2);
1739        mContextConfigStoreMockOrder.verify(mWifiConfigStore).read();
1740    }
1741
1742    /**
1743     * Verifies that the foreground user stop using {@link WifiConfigManager#handleUserStop(int)}
1744     * and ensures that the store is written only when the foreground user is stopped.
1745     */
1746    @Test
1747    public void testHandleUserStop() throws Exception {
1748        int user1 = TEST_DEFAULT_USER;
1749        int user2 = TEST_DEFAULT_USER + 1;
1750        setupUserProfiles(user2);
1751
1752        // Try stopping background user2 first, this should not do anything.
1753        when(mUserManager.isUserUnlockingOrUnlocked(user2)).thenReturn(false);
1754        mWifiConfigManager.handleUserStop(user2);
1755        mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).read();
1756
1757        // Now try stopping the foreground user1, this should trigger a write to store.
1758        mWifiConfigManager.handleUserStop(user1);
1759        mContextConfigStoreMockOrder.verify(mWifiConfigStore, never()).read();
1760        mContextConfigStoreMockOrder.verify(mWifiConfigStore).write(
1761                anyBoolean(), any(WifiConfigStoreData.class));
1762    }
1763
1764    /**
1765     * Verifies the private network addition using
1766     * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)}
1767     * by a non foreground user is rejected.
1768     */
1769    @Test
1770    public void testAddNetworkUsingBackgroundUserUId() throws Exception {
1771        int user2 = TEST_DEFAULT_USER + 1;
1772        setupUserProfiles(user2);
1773
1774        int creatorUid = UserHandle.getUid(user2, 674);
1775
1776        // Create a network for user2 try adding it. This should be rejected.
1777        final WifiConfiguration user2Network = WifiConfigurationTestUtil.createPskNetwork();
1778        NetworkUpdateResult result =
1779                mWifiConfigManager.addOrUpdateNetwork(user2Network, creatorUid);
1780        assertFalse(result.isSuccess());
1781    }
1782
1783    /**
1784     * Verifies the private network addition using
1785     * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)}
1786     * by SysUI is always accepted.
1787     */
1788    @Test
1789    public void testAddNetworkUsingSysUiUid() throws Exception {
1790        // Set up the user profiles stuff. Needed for |WifiConfigurationUtil.isVisibleToAnyProfile|
1791        int user2 = TEST_DEFAULT_USER + 1;
1792        setupUserProfiles(user2);
1793
1794        when(mUserManager.isUserUnlockingOrUnlocked(user2)).thenReturn(false);
1795        mWifiConfigManager.handleUserSwitch(user2);
1796
1797        // Create a network for user2 try adding it. This should be rejected.
1798        final WifiConfiguration user2Network = WifiConfigurationTestUtil.createPskNetwork();
1799        NetworkUpdateResult result =
1800                mWifiConfigManager.addOrUpdateNetwork(user2Network, TEST_SYSUI_UID);
1801        assertTrue(result.isSuccess());
1802    }
1803
1804    /**
1805     * Verifies the loading of networks using {@link WifiConfigManager#loadFromStore()} attempts
1806     * to migrate data from legacy stores when the new store files are absent.
1807     */
1808    @Test
1809    public void testMigrationFromLegacyStore() throws Exception {
1810        // Create the store data to be returned from legacy stores.
1811        List<WifiConfiguration> networks = new ArrayList<>();
1812        networks.add(WifiConfigurationTestUtil.createPskNetwork());
1813        networks.add(WifiConfigurationTestUtil.createEapNetwork());
1814        networks.add(WifiConfigurationTestUtil.createWepNetwork());
1815        String deletedEphemeralSSID = "EphemeralSSID";
1816        Set<String> deletedEphermalSSIDs = new HashSet<>(Arrays.asList(deletedEphemeralSSID));
1817        WifiConfigStoreDataLegacy storeData =
1818                new WifiConfigStoreDataLegacy(networks, deletedEphermalSSIDs);
1819
1820        // New store files not present, so migrate from the old store.
1821        when(mWifiConfigStore.areStoresPresent()).thenReturn(false);
1822        when(mWifiConfigStoreLegacy.areStoresPresent()).thenReturn(true);
1823        when(mWifiConfigStoreLegacy.read()).thenReturn(storeData);
1824
1825        // Now trigger a load from store. This should populate the in memory list with all the
1826        // networks above from the legacy store.
1827        mWifiConfigManager.loadFromStore();
1828
1829        verify(mWifiConfigStore, never()).read();
1830        verify(mWifiConfigStoreLegacy).read();
1831
1832        List<WifiConfiguration> retrievedNetworks =
1833                mWifiConfigManager.getConfiguredNetworksWithPasswords();
1834        WifiConfigurationTestUtil.assertConfigurationsEqualForConfigManagerAddOrUpdate(
1835                networks, retrievedNetworks);
1836        assertTrue(mWifiConfigManager.wasEphemeralNetworkDeleted(deletedEphemeralSSID));
1837    }
1838
1839    /**
1840     * Verifies the loading of networks using {@link WifiConfigManager#loadFromStore()} does
1841     * not attempt to read from any of the stores (new or legacy) when the store files are
1842     * not present.
1843     */
1844    @Test
1845    public void testFreshInstallDoesNotLoadFromStore() throws Exception {
1846        // New store files not present, so migrate from the old store.
1847        when(mWifiConfigStore.areStoresPresent()).thenReturn(false);
1848        when(mWifiConfigStoreLegacy.areStoresPresent()).thenReturn(false);
1849
1850        // Now trigger a load from store. This should populate the in memory list with all the
1851        // networks above.
1852        mWifiConfigManager.loadFromStore();
1853
1854        verify(mWifiConfigStore, never()).read();
1855        verify(mWifiConfigStoreLegacy, never()).read();
1856
1857        assertTrue(mWifiConfigManager.getConfiguredNetworksWithPasswords().isEmpty());
1858    }
1859
1860    /**
1861     * Verifies that the last user selected network parameter is set when
1862     * {@link WifiConfigManager#enableNetwork(int, boolean, int)} with disableOthers flag is set
1863     * to true and cleared when either {@link WifiConfigManager#disableNetwork(int, int)} or
1864     * {@link WifiConfigManager#removeNetwork(int, int)} is invoked using the same network ID.
1865     */
1866    @Test
1867    public void testLastSelectedNetwork() throws Exception {
1868        WifiConfiguration openNetwork = WifiConfigurationTestUtil.createOpenNetwork();
1869        NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(openNetwork);
1870
1871        when(mClock.getElapsedSinceBootMillis()).thenReturn(67L);
1872        assertTrue(mWifiConfigManager.enableNetwork(
1873                result.getNetworkId(), true, TEST_CREATOR_UID));
1874        assertEquals(result.getNetworkId(), mWifiConfigManager.getLastSelectedNetwork());
1875        assertEquals(67, mWifiConfigManager.getLastSelectedTimeStamp());
1876
1877        // Now disable the network and ensure that the last selected flag is cleared.
1878        assertTrue(mWifiConfigManager.disableNetwork(result.getNetworkId(), TEST_CREATOR_UID));
1879        assertEquals(
1880                WifiConfiguration.INVALID_NETWORK_ID, mWifiConfigManager.getLastSelectedNetwork());
1881
1882        // Enable it again and remove the network to ensure that the last selected flag was cleared.
1883        assertTrue(mWifiConfigManager.enableNetwork(
1884                result.getNetworkId(), true, TEST_CREATOR_UID));
1885        assertEquals(result.getNetworkId(), mWifiConfigManager.getLastSelectedNetwork());
1886        assertEquals(openNetwork.configKey(), mWifiConfigManager.getLastSelectedNetworkConfigKey());
1887
1888        assertTrue(mWifiConfigManager.removeNetwork(result.getNetworkId(), TEST_CREATOR_UID));
1889        assertEquals(
1890                WifiConfiguration.INVALID_NETWORK_ID, mWifiConfigManager.getLastSelectedNetwork());
1891    }
1892
1893    /**
1894     * Verifies that all the networks for the provided app is removed when
1895     * {@link WifiConfigManager#removeNetworksForApp(ApplicationInfo)} is invoked.
1896     */
1897    @Test
1898    public void testRemoveNetworksForApp() throws Exception {
1899        verifyAddNetworkToWifiConfigManager(WifiConfigurationTestUtil.createOpenNetwork());
1900        verifyAddNetworkToWifiConfigManager(WifiConfigurationTestUtil.createPskNetwork());
1901        verifyAddNetworkToWifiConfigManager(WifiConfigurationTestUtil.createWepNetwork());
1902
1903        assertFalse(mWifiConfigManager.getConfiguredNetworks().isEmpty());
1904
1905        ApplicationInfo app = new ApplicationInfo();
1906        app.uid = TEST_CREATOR_UID;
1907        app.packageName = TEST_CREATOR_NAME;
1908        assertTrue(mWifiConfigManager.removeNetworksForApp(app));
1909
1910        // Ensure all the networks are removed now.
1911        assertTrue(mWifiConfigManager.getConfiguredNetworks().isEmpty());
1912    }
1913
1914    /**
1915     * Verifies that all the networks for the provided user is removed when
1916     * {@link WifiConfigManager#removeNetworksForUser(int)} is invoked.
1917     */
1918    @Test
1919    public void testRemoveNetworksForUser() throws Exception {
1920        verifyAddNetworkToWifiConfigManager(WifiConfigurationTestUtil.createOpenNetwork());
1921        verifyAddNetworkToWifiConfigManager(WifiConfigurationTestUtil.createPskNetwork());
1922        verifyAddNetworkToWifiConfigManager(WifiConfigurationTestUtil.createWepNetwork());
1923
1924        assertFalse(mWifiConfigManager.getConfiguredNetworks().isEmpty());
1925
1926        assertTrue(mWifiConfigManager.removeNetworksForUser(TEST_DEFAULT_USER));
1927
1928        // Ensure all the networks are removed now.
1929        assertTrue(mWifiConfigManager.getConfiguredNetworks().isEmpty());
1930    }
1931
1932    /**
1933     * Verifies that the connect choice is removed from all networks when
1934     * {@link WifiConfigManager#removeNetwork(int, int)} is invoked.
1935     */
1936    @Test
1937    public void testRemoveNetworkRemovesConnectChoice() throws Exception {
1938        WifiConfiguration network1 = WifiConfigurationTestUtil.createOpenNetwork();
1939        WifiConfiguration network2 = WifiConfigurationTestUtil.createPskNetwork();
1940        WifiConfiguration network3 = WifiConfigurationTestUtil.createPskNetwork();
1941        verifyAddNetworkToWifiConfigManager(network1);
1942        verifyAddNetworkToWifiConfigManager(network2);
1943        verifyAddNetworkToWifiConfigManager(network3);
1944
1945        // Set connect choice of network 2 over network 1.
1946        assertTrue(
1947                mWifiConfigManager.setNetworkConnectChoice(
1948                        network1.networkId, network2.configKey(), 78L));
1949
1950        WifiConfiguration retrievedNetwork =
1951                mWifiConfigManager.getConfiguredNetwork(network1.networkId);
1952        assertEquals(
1953                network2.configKey(),
1954                retrievedNetwork.getNetworkSelectionStatus().getConnectChoice());
1955
1956        // Remove network 3 and ensure that the connect choice on network 1 is not removed.
1957        assertTrue(mWifiConfigManager.removeNetwork(network3.networkId, TEST_CREATOR_UID));
1958        retrievedNetwork = mWifiConfigManager.getConfiguredNetwork(network1.networkId);
1959        assertEquals(
1960                network2.configKey(),
1961                retrievedNetwork.getNetworkSelectionStatus().getConnectChoice());
1962
1963        // Now remove network 2 and ensure that the connect choice on network 1 is removed..
1964        assertTrue(mWifiConfigManager.removeNetwork(network2.networkId, TEST_CREATOR_UID));
1965        retrievedNetwork = mWifiConfigManager.getConfiguredNetwork(network1.networkId);
1966        assertNotEquals(
1967                network2.configKey(),
1968                retrievedNetwork.getNetworkSelectionStatus().getConnectChoice());
1969    }
1970
1971    /**
1972     * Verifies that the modification of a single network using
1973     * {@link WifiConfigManager#addOrUpdateNetwork(WifiConfiguration, int)} and ensures that any
1974     * updates to the network config in
1975     * {@link WifiKeyStore#updateNetworkKeys(WifiConfiguration, WifiConfiguration)} is reflected
1976     * in the internal database.
1977     */
1978    @Test
1979    public void testUpdateSingleNetworkWithKeysUpdate() {
1980        WifiConfiguration network = WifiConfigurationTestUtil.createEapNetwork();
1981        network.enterpriseConfig =
1982                WifiConfigurationTestUtil.createPEAPWifiEnterpriseConfigWithGTCPhase2();
1983        verifyAddNetworkToWifiConfigManager(network);
1984
1985        // Now verify that network configurations match before we make any change.
1986        WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate(
1987                network,
1988                mWifiConfigManager.getConfiguredNetworkWithPassword(network.networkId));
1989
1990        // Modify the network ca_cert field in updateNetworkKeys method during a network
1991        // config update.
1992        final String newCaCertAlias = "test";
1993        assertNotEquals(newCaCertAlias, network.enterpriseConfig.getCaCertificateAlias());
1994
1995        doAnswer(new AnswerWithArguments() {
1996            public boolean answer(WifiConfiguration newConfig, WifiConfiguration existingConfig) {
1997                newConfig.enterpriseConfig.setCaCertificateAlias(newCaCertAlias);
1998                return true;
1999            }
2000        }).when(mWifiKeyStore).updateNetworkKeys(
2001                any(WifiConfiguration.class), any(WifiConfiguration.class));
2002
2003        verifyUpdateNetworkToWifiConfigManagerWithoutIpChange(network);
2004
2005        // Now verify that the keys update is reflected in the configuration fetched from internal
2006        // db.
2007        network.enterpriseConfig.setCaCertificateAlias(newCaCertAlias);
2008        WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate(
2009                network,
2010                mWifiConfigManager.getConfiguredNetworkWithPassword(network.networkId));
2011    }
2012
2013    private void createWifiConfigManager() {
2014        mWifiConfigManager =
2015                new WifiConfigManager(
2016                        mContext, mFrameworkFacade, mClock, mUserManager, mTelephonyManager,
2017                        mWifiKeyStore, mWifiConfigStore, mWifiConfigStoreLegacy);
2018        mWifiConfigManager.enableVerboseLogging(1);
2019    }
2020
2021    /**
2022     * This method sets defaults in the provided WifiConfiguration object if not set
2023     * so that it can be used for comparison with the configuration retrieved from
2024     * WifiConfigManager.
2025     */
2026    private void setDefaults(WifiConfiguration configuration) {
2027        if (configuration.allowedAuthAlgorithms.isEmpty()) {
2028            configuration.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
2029        }
2030        if (configuration.allowedProtocols.isEmpty()) {
2031            configuration.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
2032            configuration.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
2033        }
2034        if (configuration.allowedKeyManagement.isEmpty()) {
2035            configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
2036            configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_EAP);
2037        }
2038        if (configuration.allowedPairwiseCiphers.isEmpty()) {
2039            configuration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP);
2040            configuration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP);
2041        }
2042        if (configuration.allowedGroupCiphers.isEmpty()) {
2043            configuration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
2044            configuration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
2045            configuration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
2046            configuration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
2047        }
2048        if (configuration.getIpAssignment() == IpConfiguration.IpAssignment.UNASSIGNED) {
2049            configuration.setIpAssignment(IpConfiguration.IpAssignment.DHCP);
2050        }
2051        if (configuration.getProxySettings() == IpConfiguration.ProxySettings.UNASSIGNED) {
2052            configuration.setProxySettings(IpConfiguration.ProxySettings.NONE);
2053        }
2054        configuration.status = WifiConfiguration.Status.DISABLED;
2055        configuration.getNetworkSelectionStatus().setNetworkSelectionStatus(
2056                NetworkSelectionStatus.NETWORK_SELECTION_PERMANENTLY_DISABLED);
2057    }
2058
2059    /**
2060     * Modifies the provided configuration with creator uid, package name
2061     * and time.
2062     */
2063    private void setCreationDebugParams(WifiConfiguration configuration) {
2064        configuration.creatorUid = configuration.lastUpdateUid = TEST_CREATOR_UID;
2065        configuration.creatorName = configuration.lastUpdateName = TEST_CREATOR_NAME;
2066        configuration.creationTime = configuration.updateTime =
2067                WifiConfigManager.createDebugTimeStampString(
2068                        TEST_WALLCLOCK_CREATION_TIME_MILLIS);
2069    }
2070
2071    /**
2072     * Modifies the provided configuration with update uid, package name
2073     * and time.
2074     */
2075    private void setUpdateDebugParams(WifiConfiguration configuration) {
2076        configuration.lastUpdateUid = TEST_UPDATE_UID;
2077        configuration.lastUpdateName = TEST_UPDATE_NAME;
2078        configuration.updateTime =
2079                WifiConfigManager.createDebugTimeStampString(TEST_WALLCLOCK_UPDATE_TIME_MILLIS);
2080    }
2081
2082    private void assertNotEquals(Object expected, Object actual) {
2083        if (actual != null) {
2084            assertFalse(actual.equals(expected));
2085        } else {
2086            assertNotNull(expected);
2087        }
2088    }
2089
2090    /**
2091     * Modifies the provided WifiConfiguration with the specified bssid value. Also, asserts that
2092     * the existing |BSSID| field is not the same value as the one being set
2093     */
2094    private void assertAndSetNetworkBSSID(WifiConfiguration configuration, String bssid) {
2095        assertNotEquals(bssid, configuration.BSSID);
2096        configuration.BSSID = bssid;
2097    }
2098
2099    /**
2100     * Modifies the provided WifiConfiguration with the specified |IpConfiguration| object. Also,
2101     * asserts that the existing |mIpConfiguration| field is not the same value as the one being set
2102     */
2103    private void assertAndSetNetworkIpConfiguration(
2104            WifiConfiguration configuration, IpConfiguration ipConfiguration) {
2105        assertNotEquals(ipConfiguration, configuration.getIpConfiguration());
2106        configuration.setIpConfiguration(ipConfiguration);
2107    }
2108
2109    /**
2110     * Modifies the provided WifiConfiguration with the specified |wepKeys| value and
2111     * |wepTxKeyIndex|.
2112     */
2113    private void assertAndSetNetworkWepKeysAndTxIndex(
2114            WifiConfiguration configuration, String[] wepKeys, int wepTxKeyIdx) {
2115        assertNotEquals(wepKeys, configuration.wepKeys);
2116        assertNotEquals(wepTxKeyIdx, configuration.wepTxKeyIndex);
2117        configuration.wepKeys = Arrays.copyOf(wepKeys, wepKeys.length);
2118        configuration.wepTxKeyIndex = wepTxKeyIdx;
2119    }
2120
2121    /**
2122     * Modifies the provided WifiConfiguration with the specified |preSharedKey| value.
2123     */
2124    private void assertAndSetNetworkPreSharedKey(
2125            WifiConfiguration configuration, String preSharedKey) {
2126        assertNotEquals(preSharedKey, configuration.preSharedKey);
2127        configuration.preSharedKey = preSharedKey;
2128    }
2129
2130    /**
2131     * Modifies the provided WifiConfiguration with the specified enteprise |password| value.
2132     */
2133    private void assertAndSetNetworkEnterprisePassword(
2134            WifiConfiguration configuration, String password) {
2135        assertNotEquals(password, configuration.enterpriseConfig.getPassword());
2136        configuration.enterpriseConfig.setPassword(password);
2137    }
2138
2139    /**
2140     * Helper method to capture the store data written in WifiConfigStore.write() method.
2141     */
2142    private WifiConfigStoreData captureWriteStoreData() {
2143        try {
2144            ArgumentCaptor<WifiConfigStoreData> storeDataCaptor =
2145                    ArgumentCaptor.forClass(WifiConfigStoreData.class);
2146            mContextConfigStoreMockOrder.verify(mWifiConfigStore)
2147                    .write(anyBoolean(), storeDataCaptor.capture());
2148            return storeDataCaptor.getValue();
2149        } catch (Exception e) {
2150            fail("Exception encountered during write " + e);
2151        }
2152        return null;
2153    }
2154
2155    /**
2156     * Returns whether the provided network was in the store data or not.
2157     */
2158    private boolean isNetworkInConfigStoreData(WifiConfiguration configuration) {
2159        WifiConfigStoreData storeData = captureWriteStoreData();
2160        if (storeData == null) {
2161            return false;
2162        }
2163        boolean foundNetworkInStoreData = false;
2164        for (WifiConfiguration retrievedConfig : storeData.getConfigurations()) {
2165            if (retrievedConfig.configKey().equals(configuration.configKey())) {
2166                foundNetworkInStoreData = true;
2167            }
2168        }
2169        return foundNetworkInStoreData;
2170    }
2171
2172    /**
2173     * Verifies that the provided network was not present in the last config store write.
2174     */
2175    private void verifyNetworkNotInConfigStoreData(WifiConfiguration configuration) {
2176        assertFalse(isNetworkInConfigStoreData(configuration));
2177    }
2178
2179    /**
2180     * Verifies that the provided network was present in the last config store write.
2181     */
2182    private void verifyNetworkInConfigStoreData(WifiConfiguration configuration) {
2183        assertTrue(isNetworkInConfigStoreData(configuration));
2184    }
2185
2186    private void assertPasswordsMaskedInWifiConfiguration(WifiConfiguration configuration) {
2187        if (!TextUtils.isEmpty(configuration.preSharedKey)) {
2188            assertEquals(WifiConfigManager.PASSWORD_MASK, configuration.preSharedKey);
2189        }
2190        if (configuration.wepKeys != null) {
2191            for (int i = 0; i < configuration.wepKeys.length; i++) {
2192                if (!TextUtils.isEmpty(configuration.wepKeys[i])) {
2193                    assertEquals(WifiConfigManager.PASSWORD_MASK, configuration.wepKeys[i]);
2194                }
2195            }
2196        }
2197        if (!TextUtils.isEmpty(configuration.enterpriseConfig.getPassword())) {
2198            assertEquals(
2199                    WifiConfigManager.PASSWORD_MASK,
2200                    configuration.enterpriseConfig.getPassword());
2201        }
2202    }
2203
2204    /**
2205     * Verifies that the network was present in the network change broadcast and returns the
2206     * change reason.
2207     */
2208    private int verifyNetworkInBroadcastAndReturnReason(WifiConfiguration configuration) {
2209        ArgumentCaptor<Intent> intentCaptor = ArgumentCaptor.forClass(Intent.class);
2210        ArgumentCaptor<UserHandle> userHandleCaptor = ArgumentCaptor.forClass(UserHandle.class);
2211        mContextConfigStoreMockOrder.verify(mContext)
2212                .sendBroadcastAsUser(intentCaptor.capture(), userHandleCaptor.capture());
2213
2214        assertEquals(userHandleCaptor.getValue(), UserHandle.ALL);
2215        Intent intent = intentCaptor.getValue();
2216
2217        int changeReason = intent.getIntExtra(WifiManager.EXTRA_CHANGE_REASON, -1);
2218        WifiConfiguration retrievedConfig =
2219                (WifiConfiguration) intent.getExtra(WifiManager.EXTRA_WIFI_CONFIGURATION);
2220        assertEquals(retrievedConfig.configKey(), configuration.configKey());
2221
2222        // Verify that all the passwords are masked in the broadcast configuration.
2223        assertPasswordsMaskedInWifiConfiguration(retrievedConfig);
2224
2225        return changeReason;
2226    }
2227
2228    /**
2229     * Verifies that we sent out an add broadcast with the provided network.
2230     */
2231    private void verifyNetworkAddBroadcast(WifiConfiguration configuration) {
2232        assertEquals(
2233                verifyNetworkInBroadcastAndReturnReason(configuration),
2234                WifiManager.CHANGE_REASON_ADDED);
2235    }
2236
2237    /**
2238     * Verifies that we sent out an update broadcast with the provided network.
2239     */
2240    private void verifyNetworkUpdateBroadcast(WifiConfiguration configuration) {
2241        assertEquals(
2242                verifyNetworkInBroadcastAndReturnReason(configuration),
2243                WifiManager.CHANGE_REASON_CONFIG_CHANGE);
2244    }
2245
2246    /**
2247     * Verifies that we sent out a remove broadcast with the provided network.
2248     */
2249    private void verifyNetworkRemoveBroadcast(WifiConfiguration configuration) {
2250        assertEquals(
2251                verifyNetworkInBroadcastAndReturnReason(configuration),
2252                WifiManager.CHANGE_REASON_REMOVED);
2253    }
2254
2255    /**
2256     * Adds the provided configuration to WifiConfigManager and modifies the provided configuration
2257     * with creator/update uid, package name and time. This also sets defaults for fields not
2258     * populated.
2259     * These fields are populated internally by WifiConfigManager and hence we need
2260     * to modify the configuration before we compare the added network with the retrieved network.
2261     */
2262    private NetworkUpdateResult addNetworkToWifiConfigManager(WifiConfiguration configuration) {
2263        when(mClock.getWallClockMillis()).thenReturn(TEST_WALLCLOCK_CREATION_TIME_MILLIS);
2264        NetworkUpdateResult result =
2265                mWifiConfigManager.addOrUpdateNetwork(configuration, TEST_CREATOR_UID);
2266        setDefaults(configuration);
2267        setCreationDebugParams(configuration);
2268        configuration.networkId = result.getNetworkId();
2269        return result;
2270    }
2271
2272    /**
2273     * Add network to WifiConfigManager and ensure that it was successful.
2274     */
2275    private NetworkUpdateResult verifyAddNetworkToWifiConfigManager(
2276            WifiConfiguration configuration) {
2277        NetworkUpdateResult result = addNetworkToWifiConfigManager(configuration);
2278        assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID);
2279        assertTrue(result.isNewNetwork());
2280        assertTrue(result.hasIpChanged());
2281        assertTrue(result.hasProxyChanged());
2282
2283        verifyNetworkAddBroadcast(configuration);
2284        // Verify that the config store write was triggered with this new configuration.
2285        verifyNetworkInConfigStoreData(configuration);
2286        return result;
2287    }
2288
2289    /**
2290     * Add ephemeral network to WifiConfigManager and ensure that it was successful.
2291     */
2292    private NetworkUpdateResult verifyAddEphemeralNetworkToWifiConfigManager(
2293            WifiConfiguration configuration) {
2294        NetworkUpdateResult result = addNetworkToWifiConfigManager(configuration);
2295        assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID);
2296        assertTrue(result.isNewNetwork());
2297        assertTrue(result.hasIpChanged());
2298        assertTrue(result.hasProxyChanged());
2299
2300        verifyNetworkAddBroadcast(configuration);
2301        // Ephemeral networks should not be persisted.
2302        verifyNetworkNotInConfigStoreData(configuration);
2303        return result;
2304    }
2305
2306    /**
2307     * Updates the provided configuration to WifiConfigManager and modifies the provided
2308     * configuration with update uid, package name and time.
2309     * These fields are populated internally by WifiConfigManager and hence we need
2310     * to modify the configuration before we compare the added network with the retrieved network.
2311     */
2312    private NetworkUpdateResult updateNetworkToWifiConfigManager(WifiConfiguration configuration) {
2313        when(mClock.getWallClockMillis()).thenReturn(TEST_WALLCLOCK_UPDATE_TIME_MILLIS);
2314        NetworkUpdateResult result =
2315                mWifiConfigManager.addOrUpdateNetwork(configuration, TEST_UPDATE_UID);
2316        setUpdateDebugParams(configuration);
2317        return result;
2318    }
2319
2320    /**
2321     * Update network to WifiConfigManager config change and ensure that it was successful.
2322     */
2323    private NetworkUpdateResult verifyUpdateNetworkToWifiConfigManager(
2324            WifiConfiguration configuration) {
2325        NetworkUpdateResult result = updateNetworkToWifiConfigManager(configuration);
2326        assertTrue(result.getNetworkId() != WifiConfiguration.INVALID_NETWORK_ID);
2327        assertFalse(result.isNewNetwork());
2328
2329        verifyNetworkUpdateBroadcast(configuration);
2330        // Verify that the config store write was triggered with this new configuration.
2331        verifyNetworkInConfigStoreData(configuration);
2332        return result;
2333    }
2334
2335    /**
2336     * Update network to WifiConfigManager without IP config change and ensure that it was
2337     * successful.
2338     */
2339    private NetworkUpdateResult verifyUpdateNetworkToWifiConfigManagerWithoutIpChange(
2340            WifiConfiguration configuration) {
2341        NetworkUpdateResult result = verifyUpdateNetworkToWifiConfigManager(configuration);
2342        assertFalse(result.hasIpChanged());
2343        assertFalse(result.hasProxyChanged());
2344        return result;
2345    }
2346
2347    /**
2348     * Update network to WifiConfigManager with IP config change and ensure that it was
2349     * successful.
2350     */
2351    private NetworkUpdateResult verifyUpdateNetworkToWifiConfigManagerWithIpChange(
2352            WifiConfiguration configuration) {
2353        NetworkUpdateResult result = verifyUpdateNetworkToWifiConfigManager(configuration);
2354        assertTrue(result.hasIpChanged());
2355        assertTrue(result.hasProxyChanged());
2356        return result;
2357    }
2358
2359    /**
2360     * Removes network from WifiConfigManager and ensure that it was successful.
2361     */
2362    private void verifyRemoveNetworkFromWifiConfigManager(
2363            WifiConfiguration configuration) {
2364        assertTrue(mWifiConfigManager.removeNetwork(configuration.networkId, TEST_CREATOR_UID));
2365
2366        verifyNetworkRemoveBroadcast(configuration);
2367        // Verify if the config store write was triggered without this new configuration.
2368        verifyNetworkNotInConfigStoreData(configuration);
2369    }
2370
2371    /**
2372     * Verifies the provided network's public status and ensures that the network change broadcast
2373     * has been sent out.
2374     */
2375    private void verifyUpdateNetworkStatus(WifiConfiguration configuration, int status) {
2376        assertEquals(status, configuration.status);
2377        verifyNetworkUpdateBroadcast(configuration);
2378    }
2379
2380    /**
2381     * Verifies the network's selection status update.
2382     *
2383     * For temporarily disabled reasons, the method ensures that the status has changed only if
2384     * disable reason counter has exceeded the threshold.
2385     *
2386     * For permanently disabled/enabled reasons, the method ensures that the public status has
2387     * changed and the network change broadcast has been sent out.
2388     */
2389    private void verifyUpdateNetworkSelectionStatus(
2390            int networkId, int reason, int temporaryDisableReasonCounter) {
2391        when(mClock.getElapsedSinceBootMillis())
2392                .thenReturn(TEST_ELAPSED_UPDATE_NETWORK_SELECTION_TIME_MILLIS);
2393
2394        // Fetch the current status of the network before we try to update the status.
2395        WifiConfiguration retrievedNetwork = mWifiConfigManager.getConfiguredNetwork(networkId);
2396        NetworkSelectionStatus currentStatus = retrievedNetwork.getNetworkSelectionStatus();
2397        int currentDisableReason = currentStatus.getNetworkSelectionDisableReason();
2398
2399        // First set the status to the provided reason.
2400        assertTrue(mWifiConfigManager.updateNetworkSelectionStatus(networkId, reason));
2401
2402        // Now fetch the network configuration and verify the new status of the network.
2403        retrievedNetwork = mWifiConfigManager.getConfiguredNetwork(networkId);
2404
2405        NetworkSelectionStatus retrievedStatus = retrievedNetwork.getNetworkSelectionStatus();
2406        int retrievedDisableReason = retrievedStatus.getNetworkSelectionDisableReason();
2407        long retrievedDisableTime = retrievedStatus.getDisableTime();
2408        int retrievedDisableReasonCounter = retrievedStatus.getDisableReasonCounter(reason);
2409        int disableReasonThreshold =
2410                WifiConfigManager.NETWORK_SELECTION_DISABLE_THRESHOLD[reason];
2411
2412        if (reason == NetworkSelectionStatus.NETWORK_SELECTION_ENABLE) {
2413            assertEquals(reason, retrievedDisableReason);
2414            assertTrue(retrievedStatus.isNetworkEnabled());
2415            assertEquals(
2416                    NetworkSelectionStatus.INVALID_NETWORK_SELECTION_DISABLE_TIMESTAMP,
2417                    retrievedDisableTime);
2418            verifyUpdateNetworkStatus(retrievedNetwork, WifiConfiguration.Status.ENABLED);
2419        } else if (reason < NetworkSelectionStatus.DISABLED_TLS_VERSION_MISMATCH) {
2420            // For temporarily disabled networks, we need to ensure that the current status remains
2421            // until the threshold is crossed.
2422            assertEquals(temporaryDisableReasonCounter, retrievedDisableReasonCounter);
2423            if (retrievedDisableReasonCounter < disableReasonThreshold) {
2424                assertEquals(currentDisableReason, retrievedDisableReason);
2425                assertEquals(
2426                        currentStatus.getNetworkSelectionStatus(),
2427                        retrievedStatus.getNetworkSelectionStatus());
2428            } else {
2429                assertEquals(reason, retrievedDisableReason);
2430                assertTrue(retrievedStatus.isNetworkTemporaryDisabled());
2431                assertEquals(
2432                        TEST_ELAPSED_UPDATE_NETWORK_SELECTION_TIME_MILLIS, retrievedDisableTime);
2433            }
2434        } else if (reason < NetworkSelectionStatus.NETWORK_SELECTION_DISABLED_MAX) {
2435            assertEquals(reason, retrievedDisableReason);
2436            assertTrue(retrievedStatus.isNetworkPermanentlyDisabled());
2437            assertEquals(
2438                    NetworkSelectionStatus.INVALID_NETWORK_SELECTION_DISABLE_TIMESTAMP,
2439                    retrievedDisableTime);
2440            verifyUpdateNetworkStatus(retrievedNetwork, WifiConfiguration.Status.DISABLED);
2441        }
2442    }
2443
2444    /**
2445     * Creates a scan detail corresponding to the provided network and given BSSID, level &frequency
2446     * values.
2447     */
2448    private ScanDetail createScanDetailForNetwork(
2449            WifiConfiguration configuration, String bssid, int level, int frequency) {
2450        String caps;
2451        if (configuration.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.WPA_PSK)) {
2452            caps = "[WPA2-PSK-CCMP]";
2453        } else if (configuration.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.WPA_EAP)
2454                || configuration.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.IEEE8021X)) {
2455            caps = "[WPA2-EAP-CCMP]";
2456        } else if (configuration.allowedKeyManagement.get(WifiConfiguration.KeyMgmt.NONE)
2457                && WifiConfigurationUtil.hasAnyValidWepKey(configuration.wepKeys)) {
2458            caps = "[WEP]";
2459        } else {
2460            caps = "[]";
2461        }
2462        WifiSsid ssid = WifiSsid.createFromAsciiEncoded(configuration.getPrintableSsid());
2463        // Fill in 0's in the fields we don't care about.
2464        return new ScanDetail(
2465                ssid, bssid, caps, level, frequency, mClock.getUptimeSinceBootMillis(),
2466                mClock.getWallClockMillis());
2467    }
2468
2469    /**
2470     * Creates a scan detail corresponding to the provided network and BSSID value.
2471     */
2472    private ScanDetail createScanDetailForNetwork(WifiConfiguration configuration, String bssid) {
2473        return createScanDetailForNetwork(configuration, bssid, 0, 0);
2474    }
2475
2476    /**
2477     * Creates a scan detail corresponding to the provided network and fixed BSSID value.
2478     */
2479    private ScanDetail createScanDetailForNetwork(WifiConfiguration configuration) {
2480        return createScanDetailForNetwork(configuration, TEST_BSSID);
2481    }
2482
2483    /**
2484     * Adds the provided network and then creates a scan detail corresponding to the network. The
2485     * method then creates a ScanDetail corresponding to the network and ensures that the network
2486     * is properly matched using
2487     * {@link WifiConfigManager#getSavedNetworkForScanDetailAndCache(ScanDetail)} and also
2488     * verifies that the provided scan detail was cached,
2489     */
2490    private void verifyAddSingleNetworkAndMatchScanDetailToNetworkAndCache(
2491            WifiConfiguration network) {
2492        // First add the provided network.
2493        verifyAddNetworkToWifiConfigManager(network);
2494
2495        // Now create a dummy scan detail corresponding to the network.
2496        ScanDetail scanDetail = createScanDetailForNetwork(network);
2497        ScanResult scanResult = scanDetail.getScanResult();
2498
2499        WifiConfiguration retrievedNetwork =
2500                mWifiConfigManager.getSavedNetworkForScanDetailAndCache(scanDetail);
2501        // Retrieve the network with password data for comparison.
2502        retrievedNetwork =
2503                mWifiConfigManager.getConfiguredNetworkWithPassword(retrievedNetwork.networkId);
2504
2505        WifiConfigurationTestUtil.assertConfigurationEqualForConfigManagerAddOrUpdate(
2506                network, retrievedNetwork);
2507
2508        // Now retrieve the scan detail cache and ensure that the new scan detail is in cache.
2509        ScanDetailCache retrievedScanDetailCache =
2510                mWifiConfigManager.getScanDetailCacheForNetwork(network.networkId);
2511        assertEquals(1, retrievedScanDetailCache.size());
2512        ScanResult retrievedScanResult = retrievedScanDetailCache.get(scanResult.BSSID);
2513
2514        ScanTestUtil.assertScanResultEquals(scanResult, retrievedScanResult);
2515    }
2516
2517    /**
2518     * Adds a new network and verifies that the |HasEverConnected| flag is set to false.
2519     */
2520    private void verifyAddNetworkHasEverConnectedFalse(WifiConfiguration network) {
2521        NetworkUpdateResult result = verifyAddNetworkToWifiConfigManager(network);
2522        WifiConfiguration retrievedNetwork =
2523                mWifiConfigManager.getConfiguredNetwork(result.getNetworkId());
2524        assertFalse("Adding a new network should not have hasEverConnected set to true.",
2525                retrievedNetwork.getNetworkSelectionStatus().getHasEverConnected());
2526    }
2527
2528    /**
2529     * Updates an existing network with some credential change and verifies that the
2530     * |HasEverConnected| flag is set to false.
2531     */
2532    private void verifyUpdateNetworkWithCredentialChangeHasEverConnectedFalse(
2533            WifiConfiguration network) {
2534        NetworkUpdateResult result = verifyUpdateNetworkToWifiConfigManagerWithoutIpChange(network);
2535        WifiConfiguration retrievedNetwork =
2536                mWifiConfigManager.getConfiguredNetwork(result.getNetworkId());
2537        assertFalse("Updating network credentials config should clear hasEverConnected.",
2538                retrievedNetwork.getNetworkSelectionStatus().getHasEverConnected());
2539    }
2540
2541    /**
2542     * Updates an existing network after connection using
2543     * {@link WifiConfigManager#updateNetworkAfterConnect(int)} and asserts that the
2544     * |HasEverConnected| flag is set to true.
2545     */
2546    private void verifyUpdateNetworkAfterConnectHasEverConnectedTrue(int networkId) {
2547        assertTrue(mWifiConfigManager.updateNetworkAfterConnect(networkId));
2548        WifiConfiguration retrievedNetwork = mWifiConfigManager.getConfiguredNetwork(networkId);
2549        assertTrue("hasEverConnected expected to be true after connection.",
2550                retrievedNetwork.getNetworkSelectionStatus().getHasEverConnected());
2551    }
2552
2553    /**
2554     * Sets up a user profiles for WifiConfigManager testing.
2555     *
2556     * @param userId Id of the user.
2557     */
2558    private void setupUserProfiles(int userId) {
2559        final UserInfo userInfo =
2560                new UserInfo(userId, Integer.toString(userId), UserInfo.FLAG_PRIMARY);
2561        List<UserInfo> userProfiles = Arrays.asList(userInfo);
2562        when(mUserManager.getProfiles(userId)).thenReturn(userProfiles);
2563        when(mUserManager.isUserUnlockingOrUnlocked(userId)).thenReturn(true);
2564    }
2565
2566}
2567