summaryrefslogtreecommitdiffstats
path: root/tests/wifitests/src/com/android/server/wifi/WifiQualifiedNetworkSelectorTest.java
blob: 1726e7d3292fe6fc436f068743c2cdfa101aca41 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
/*
 * Copyright (C) 2015 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License
 */

package com.android.server.wifi;

import static com.android.server.wifi.WifiConfigurationTestUtil.SECURITY_EAP;
import static com.android.server.wifi.WifiConfigurationTestUtil.SECURITY_NONE;
import static com.android.server.wifi.WifiConfigurationTestUtil.SECURITY_PSK;
import static com.android.server.wifi.WifiConfigurationTestUtil.generateWifiConfig;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertSame;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyBoolean;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.validateMockitoUsage;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import android.content.Context;
import android.content.res.Resources;
import android.net.NetworkScoreManager;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiEnterpriseConfig;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiSsid;
import android.os.SystemClock;
import android.test.suitebuilder.annotation.SmallTest;
import android.util.LocalLog;

import com.android.internal.R;
import com.android.server.wifi.MockAnswerUtil.AnswerWithArguments;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Unit tests for {@link com.android.server.wifi.WifiQualifiedNetworkSelector}.
 */
@SmallTest
public class WifiQualifiedNetworkSelectorTest {

    @Before
    public void setUp() throws Exception {
        mResource = getResource();
        mScoreManager = getNetworkScoreManager();
        mScoreCache = getScoreCache();
        mContext = getContext();
        mWifiConfigManager = getWifiConfigManager();
        mWifiInfo = getWifiInfo();
        mLocalLog = getLocalLog();

        mWifiQualifiedNetworkSelector = new WifiQualifiedNetworkSelector(mWifiConfigManager,
                mContext, mWifiInfo, mClock);
        mWifiQualifiedNetworkSelector.enableVerboseLogging(1);
        mWifiQualifiedNetworkSelector.setUserPreferredBand(1);
        mWifiQualifiedNetworkSelector.setWifiNetworkScoreCache(mScoreCache);
        when(mClock.elapsedRealtime()).thenReturn(SystemClock.elapsedRealtime());
    }

    @After
    public void cleanup() {
        validateMockitoUsage();
    }

    private WifiQualifiedNetworkSelector mWifiQualifiedNetworkSelector = null;
    private WifiConfigManager mWifiConfigManager = null;
    private Context mContext;
    private Resources mResource;
    private NetworkScoreManager mScoreManager;
    private WifiNetworkScoreCache mScoreCache;
    private WifiInfo mWifiInfo;
    private LocalLog mLocalLog;
    private Clock mClock = mock(Clock.class);
    private static final String[] DEFAULT_SSIDS = {"\"test1\"", "\"test2\""};
    private static final String[] DEFAULT_BSSIDS = {"6c:f3:7f:ae:8c:f3", "6c:f3:7f:ae:8c:f4"};
    private static final String TAG = "QNS Unit Test";

    private List<ScanDetail> getScanDetails(String[] ssids, String[] bssids, int[] frequencies,
                                            String[] caps, int[] levels) {
        List<ScanDetail> scanDetailList = new ArrayList<ScanDetail>();
        long timeStamp = mClock.elapsedRealtime();
        for (int index = 0; index < ssids.length; index++) {
            ScanDetail scanDetail = new ScanDetail(WifiSsid.createFromAsciiEncoded(ssids[index]),
                    bssids[index], caps[index], levels[index], frequencies[index], timeStamp, 0);
            scanDetailList.add(scanDetail);
        }
        return scanDetailList;
    }

    Context getContext() {
        Context context = mock(Context.class);
        Resources resource = mock(Resources.class);

        when(context.getResources()).thenReturn(mResource);
        when(context.getSystemService(Context.NETWORK_SCORE_SERVICE)).thenReturn(mScoreManager);
        return context;
    }

    Resources getResource() {
        Resources resource = mock(Resources.class);

        when(resource.getInteger(R.integer.config_wifi_framework_SECURITY_AWARD)).thenReturn(80);
        when(resource.getInteger(R.integer.config_wifi_framework_RSSI_SCORE_OFFSET)).thenReturn(85);
        when(resource.getInteger(R.integer.config_wifi_framework_SAME_BSSID_AWARD)).thenReturn(24);
        when(resource.getInteger(R.integer.config_wifi_framework_LAST_SELECTION_AWARD))
                .thenReturn(480);
        when(resource.getInteger(R.integer.config_wifi_framework_PASSPOINT_SECURITY_AWARD))
                .thenReturn(40);
        when(resource.getInteger(R.integer.config_wifi_framework_SECURITY_AWARD)).thenReturn(80);
        when(resource.getInteger(R.integer.config_wifi_framework_RSSI_SCORE_SLOPE)).thenReturn(4);
        return resource;
    }

    NetworkScoreManager getNetworkScoreManager() {
        NetworkScoreManager networkScoreManager = mock(NetworkScoreManager.class);

        return networkScoreManager;
    }

    WifiNetworkScoreCache getScoreCache() {
        return mock(WifiNetworkScoreCache.class);
    }

    LocalLog getLocalLog() {
        return new LocalLog(0);
    }

    WifiInfo getWifiInfo() {
        WifiInfo wifiInfo = mock(WifiInfo.class);

        //simulate a disconnected state
        when(wifiInfo.is24GHz()).thenReturn(true);
        when(wifiInfo.is5GHz()).thenReturn(false);
        when(wifiInfo.getRssi()).thenReturn(-70);
        when(wifiInfo.getNetworkId()).thenReturn(WifiConfiguration.INVALID_NETWORK_ID);
        when(wifiInfo.getBSSID()).thenReturn(null);
        when(wifiInfo.getNetworkId()).thenReturn(-1);
        return wifiInfo;
    }

    WifiConfigManager getWifiConfigManager() {
        WifiConfigManager wifiConfigManager = mock(WifiConfigManager.class);
        wifiConfigManager.mThresholdSaturatedRssi24 = new AtomicInteger(
                WifiQualifiedNetworkSelector.RSSI_SATURATION_2G_BAND);
        wifiConfigManager.mBandAward5Ghz = new AtomicInteger(
                WifiQualifiedNetworkSelector.BAND_AWARD_5GHz);
        wifiConfigManager.mCurrentNetworkBoost = new AtomicInteger(
                WifiQualifiedNetworkSelector.SAME_NETWORK_AWARD);
        wifiConfigManager.mThresholdQualifiedRssi5 = new AtomicInteger(
                WifiQualifiedNetworkSelector.QUALIFIED_RSSI_5G_BAND);
        wifiConfigManager.mThresholdMinimumRssi24 = new AtomicInteger(
                WifiQualifiedNetworkSelector.MINIMUM_2G_ACCEPT_RSSI);
        wifiConfigManager.mThresholdMinimumRssi5 = new AtomicInteger(
                WifiQualifiedNetworkSelector.MINIMUM_5G_ACCEPT_RSSI);

        when(wifiConfigManager.getEnableAutoJoinWhenAssociated()).thenReturn(true);
        return wifiConfigManager;
    }

    /**
     * This API is used to generate multiple simulated saved configurations used for test
     *
     * @param ssid     array of SSID of saved configuration
     * @param security array  of securities of  saved configuration
     * @return generated new array of configurations based on input
     */
    private WifiConfiguration[] generateWifiConfigurations(String[] ssid, int[] security) {
        if (ssid == null || security == null || ssid.length != security.length
                || ssid.length == 0) {
            return null;
        }

        WifiConfiguration[] configs = new WifiConfiguration[ssid.length];
        for (int index = 0; index < ssid.length; index++) {
            configs[index] = generateWifiConfig(index, 0, ssid[index], false, true, null, null,
                    security[index]);
        }

        return configs;
    }

    /**
     * set configuration to a passpoint configuration
     *
     * @param config The configuration need to be set as a passipoint configuration
     */
    private void setConfigPasspoint(WifiConfiguration config) {
        config.FQDN = "android.qns.unitTest";
        config.providerFriendlyName = "android.qns.unitTest";
        WifiEnterpriseConfig enterpriseConfig = mock(WifiEnterpriseConfig.class);
        when(enterpriseConfig.getEapMethod()).thenReturn(WifiEnterpriseConfig.Eap.PEAP);

    }

    /**
     * add the Configurations to WifiConfigManager (WifiConfigureStore can take them out according
     * to the networkd ID)
     *
     * @param configs input configuration need to be added to WifiConfigureStore
     */
    private void prepareConfigStore(final WifiConfiguration[] configs) {
        when(mWifiConfigManager.getWifiConfiguration(anyInt()))
                .then(new AnswerWithArguments() {
                    public WifiConfiguration answer(int netId) {
                        if (netId >= 0 && netId < configs.length) {
                            return configs[netId];
                        } else {
                            return null;
                        }
                    }
                });
    }

    /**
     * Link scan results to the saved configurations.
     *
     * The shorter of the 2 input params will be used to loop over so the inputs don't
     * need to be of equal length. If there are more scan details then configs the remaining scan
     * details will be associated with a NULL config.
     *
     * @param configs     saved configurations
     * @param scanDetails come in scan results
     */
    private void scanResultLinkConfiguration(WifiConfiguration[] configs,
                                             List<ScanDetail> scanDetails) {
        if (scanDetails.size() <= configs.length) {
            for (int i = 0; i < scanDetails.size(); i++) {
                ScanDetail scanDetail = scanDetails.get(i);
                List<WifiConfiguration> associateWithScanResult = new ArrayList<>();
                associateWithScanResult.add(configs[i]);
                when(mWifiConfigManager.updateSavedNetworkWithNewScanDetail(eq(scanDetail),
                        anyBoolean())).thenReturn(associateWithScanResult);
            }
        } else {
            for (int i = 0; i < configs.length; i++) {
                ScanDetail scanDetail = scanDetails.get(i);
                List<WifiConfiguration> associateWithScanResult = new ArrayList<>();
                associateWithScanResult.add(configs[i]);
                when(mWifiConfigManager.updateSavedNetworkWithNewScanDetail(eq(scanDetail),
                        anyBoolean())).thenReturn(associateWithScanResult);
            }

            // associated the remaining scan details with a NULL config.
            for (int i = configs.length; i < scanDetails.size(); i++) {
                when(mWifiConfigManager.updateSavedNetworkWithNewScanDetail(eq(scanDetails.get(i)),
                        anyBoolean())).thenReturn(null);
            }
        }
    }

    private void configureScoreCache(List<ScanDetail> scanDetails, Integer[] scores,
            boolean[] meteredHints) {
        for (int i = 0; i < scanDetails.size(); i++) {
            ScanDetail scanDetail = scanDetails.get(i);
            Integer score = scores[i];
            ScanResult scanResult = scanDetail.getScanResult();
            if (score != null) {
                when(mScoreCache.isScoredNetwork(scanResult)).thenReturn(true);
                when(mScoreCache.hasScoreCurve(scanResult)).thenReturn(true);
                when(mScoreCache.getNetworkScore(eq(scanResult), anyBoolean())).thenReturn(score);
                when(mScoreCache.getNetworkScore(scanResult)).thenReturn(score);
            } else {
                when(mScoreCache.isScoredNetwork(scanResult)).thenReturn(false);
                when(mScoreCache.hasScoreCurve(scanResult)).thenReturn(false);
                when(mScoreCache.getNetworkScore(eq(scanResult), anyBoolean())).thenReturn(
                        WifiNetworkScoreCache.INVALID_NETWORK_SCORE);
                when(mScoreCache.getNetworkScore(scanResult)).thenReturn(
                        WifiNetworkScoreCache.INVALID_NETWORK_SCORE);
            }
            when(mScoreCache.getMeteredHint(scanResult)).thenReturn(meteredHints[i]);
        }
    }

    /**
     * verify whether the chosen configuration matched with the expected chosen scan result
     *
     * @param chosenScanResult the expected chosen scan result
     * @param candidate        the chosen configuration
     */
    private void verifySelectedResult(ScanResult chosenScanResult, WifiConfiguration candidate) {
        ScanResult candidateScan = candidate.getNetworkSelectionStatus().getCandidate();
        assertEquals("choose the wrong SSID", chosenScanResult.SSID, candidate.SSID);
        assertEquals("choose the wrong BSSID", chosenScanResult.BSSID, candidateScan.BSSID);
    }

    // QNS test under disconnected State

    /**
     * Case #1    choose 2GHz stronger RSSI test
     *
     * In this test. we simulate following scenario
     * WifiStateMachine is under disconnected state
     * Two networks test1, test2 are secured network
     * Both network are enabled, encrypted and at 2.4 GHz
     * test1 is with RSSI -70 test2 is with RSSI -60
     *
     * Expected behavior: test2 is chosen
     */
    @Test
    public void chooseNetworkDisconnected2GHighestRssi() {
        String[] ssids = DEFAULT_SSIDS;
        String[] bssids = DEFAULT_BSSIDS;
        int[] frequencies = {2437, 2417};
        String[] caps = {"[WPA2-EAP-CCMP][ESS]", "[WPA2-EAP-CCMP][ESS][ESS]"};
        int[] levels = {-70, -60};
        int[] security = {SECURITY_PSK, SECURITY_PSK};

        List<ScanDetail> scanDetails = getScanDetails(ssids, bssids, frequencies, caps, levels);

        WifiConfiguration[] savedConfigs = generateWifiConfigurations(ssids, security);
        prepareConfigStore(savedConfigs);

        final List<WifiConfiguration> savedNetwork = Arrays.asList(savedConfigs);
        when(mWifiConfigManager.getSavedNetworks()).thenReturn(savedNetwork);

        scanResultLinkConfiguration(savedConfigs, scanDetails);

        ScanResult chosenScanResult = scanDetails.get(scanDetails.size() - 1).getScanResult();

        WifiConfiguration candidate = mWifiQualifiedNetworkSelector.selectQualifiedNetwork(false,
                false, scanDetails, false, false, true, false);

        verifySelectedResult(chosenScanResult, candidate);
    }

    /**
     * Case #2    choose 5GHz Stronger RSSI Test
     *
     * In this test. we simulate following scenario
     * WifiStateMachine is under disconnected state
     * Two networks test1, test2 are secured network
     * Both network are enabled, encrypted and at 5 GHz
     * test1 is with RSSI -70 test2 is with RSSI -60
     *
     * Expected behavior: test2 is chosen
     */
    @Test
    public void chooseNetworkDisconnected5GHighestRssi() {
        String[] ssids = DEFAULT_SSIDS;
        String[] bssids = DEFAULT_BSSIDS;
        int[] frequencies = {5180, 5610};
        String[] caps = {"[WPA2-EAP-CCMP][ESS]", "[WPA2-EAP-CCMP][ESS][ESS]"};
        int[] levels = {-70, -60};
        int[] security = {SECURITY_PSK, SECURITY_PSK};

        List<ScanDetail> scanDetails = getScanDetails(ssids, bssids, frequencies, caps, levels);

        WifiConfiguration[] savedConfigs = generateWifiConfigurations(ssids, security);
        prepareConfigStore(savedConfigs);

        final List<WifiConfiguration> savedNetwork = Arrays.asList(savedConfigs);
        when(mWifiConfigManager.getSavedNetworks()).thenReturn(savedNetwork);
        scanResultLinkConfiguration(savedConfigs, scanDetails);

        ScanResult chosenScanResult = scanDetails.get(scanDetails.size() - 1).getScanResult();

        WifiConfiguration candidate = mWifiQualifiedNetworkSelector.selectQualifiedNetwork(false,
                false, scanDetails, false, false, true, false);

        verifySelectedResult(chosenScanResult, candidate);
    }

    /**
     * Case #3    5GHz over 2GHz bonus Test
     *
     * In this test. we simulate following scenario
     * WifiStateMachine is under disconnected state
     * Two networks test1, test2 are secured network
     * Both network are enabled
     * test1 is @ 2GHz with RSSI -60
     * test2 is @ 5Ghz with RSSI -65
     *
     * Expected behavior: test2 is chosen due to 5GHz bonus
     */
    @Test
    public void chooseNetworkDisconnect5GOver2GTest() {
        String[] ssids = DEFAULT_SSIDS;
        String[] bssids = DEFAULT_BSSIDS;
        int[] frequencies = {2437, 5180};
        String[] caps = {"[WPA2-EAP-CCMP][ESS]", "[WPA2-EAP-CCMP][ESS][ESS]"};
        int[] levels = {-60, -65};
        int[] security = {SECURITY_PSK, SECURITY_PSK};

        List<ScanDetail> scanDetails = getScanDetails(ssids, bssids, frequencies, caps, levels);
        WifiConfiguration[] savedConfigs = generateWifiConfigurations(ssids, security);
        prepareConfigStore(savedConfigs);

        final List<WifiConfiguration> savedNetwork = Arrays.asList(savedConfigs);
        when(mWifiConfigManager.getSavedNetworks()).thenReturn(savedNetwork);
        scanResultLinkConfiguration(savedConfigs, scanDetails);
        ScanResult chosenScanResult = scanDetails.get(scanDetails.size() - 1).getScanResult();

        WifiConfiguration candidate = mWifiQualifiedNetworkSelector.selectQualifiedNetwork(false,
                false, scanDetails, false, false, true, false);

        verifySelectedResult(chosenScanResult, candidate);
    }

    /**
     * Case #4    2GHz over 5GHz dur to 5GHz signal too weak test
     *
     * In this test. we simulate following scenario
     * WifiStateMachine is under disconnected state
     * Two networks test1, test2 are secured network
     * Both network are enabled
     * test1 is @ 2GHz with RSSI -60
     * test2 is @ 5Ghz with RSSI -75
     *
     * Expected behavior: test1 is chosen due to 5GHz signal is too weak (5GHz bonus can not
     * compensate)
     */
    @Test
    public void chooseNetworkDisconnect2GOver5GTest() {
        String[] ssids = DEFAULT_SSIDS;
        String[] bssids = DEFAULT_BSSIDS;
        int[] frequencies = {2437, 5180};
        String[] caps = {"[WPA2-EAP-CCMP][ESS]", "[WPA2-EAP-CCMP][ESS][ESS]"};
        int[] levels = {-60, -75};
        int[] security = {SECURITY_PSK, SECURITY_PSK};

        List<ScanDetail> scanDetails = getScanDetails(ssids, bssids, frequencies, caps, levels);
        WifiConfiguration[] savedConfigs = generateWifiConfigurations(ssids, security);
        prepareConfigStore(savedConfigs);

        final List<WifiConfiguration> savedNetwork = Arrays.asList(savedConfigs);
        when(mWifiConfigManager.getSavedNetworks()).thenReturn(savedNetwork);
        scanResultLinkConfiguration(savedConfigs, scanDetails);
        ScanResult chosenScanResult = scanDetails.get(0).getScanResult();

        WifiConfiguration candidate = mWifiQualifiedNetworkSelector.selectQualifiedNetwork(false,
                false, scanDetails, false, false, true, false);

        verifySelectedResult(chosenScanResult, candidate);
    }

    /**
     * Case #5    2GHz signal Saturation test
     *
     * In this test. we simulate following scenario
     * WifiStateMachine is under disconnected state
     * Two networks test1, test2 are secured network
     * Both network are enabled
     * test1 is @ 2GHz with RSSI -50
     * test2 is @ 5Ghz with RSSI -65
     *
     * Expected behavior: test2 is chosen. Although the RSSI delta here is 15 too, because 2GHz RSSI
     * saturates at -60, the real RSSI delta is only 5, which is less than 5GHz bonus
     */
    @Test
    public void chooseNetworkDisconnect2GRssiSaturationTest() {
        String[] ssids = DEFAULT_SSIDS;
        String[] bssids = DEFAULT_BSSIDS;
        int[] frequencies = {2437, 5180};
        String[] caps = {"[WPA2-EAP-CCMP][ESS]", "[WPA2-EAP-CCMP][ESS][ESS]"};
        int[] levels = {-50, -65};
        int[] security = {SECURITY_PSK, SECURITY_PSK};

        List<ScanDetail> scanDetails = getScanDetails(ssids, bssids, frequencies, caps, levels);
        WifiConfiguration[] savedConfigs = generateWifiConfigurations(ssids, security);
        prepareConfigStore(savedConfigs);

        final List<WifiConfiguration> savedNetwork = Arrays.asList(savedConfigs);
        when(mWifiConfigManager.getSavedNetworks()).thenReturn(savedNetwork);
        scanResultLinkConfiguration(savedConfigs, scanDetails);
        ScanResult chosenScanResult = scanDetails.get(scanDetails.size() - 1).getScanResult();

        WifiConfiguration candidate = mWifiQualifiedNetworkSelector.selectQualifiedNetwork(false,
                false, scanDetails, false, false, true, false);

        verifySelectedResult(chosenScanResult, candidate);
    }

    /**
     * Case #6    Minimum RSSI test
     *
     * In this test. we simulate following scenario
     * WifiStateMachine is under disconnected state
     * Two networks test1, test2 are secured network
     * Both network are enabled
     * test1 is @ 2GHz with RSSI -86
     * test2 is @ 5Ghz with RSSI -83
     *
     * Expected behavior: no QNS is made because both network are below the minimum threshold, null
     */
    @Test
    public void chooseNetworkMinimumRssiTest() {
        String[] ssids = DEFAULT_SSIDS;
        String[] bssids = DEFAULT_BSSIDS;
        int[] frequencies = {2437, 5180};
        String[] caps = {"[WPA2-EAP-CCMP][ESS]", "[WPA2-EAP-CCMP][ESS][ESS]"};
        int[] levels = {WifiQualifiedNetworkSelector.MINIMUM_2G_ACCEPT_RSSI - 1,
                WifiQualifiedNetworkSelector.MINIMUM_5G_ACCEPT_RSSI - 1};
        int[] security = {SECURITY_EAP, SECURITY_PSK};

        List<ScanDetail> scanDetails = getScanDetails(ssids, bssids, frequencies, caps, levels);
        WifiConfiguration[] savedConfigs = generateWifiConfigurations(ssids, security);
        prepareConfigStore(savedConfigs);

        final List<WifiConfiguration> savedNetwork = Arrays.asList(savedConfigs);
        when(mWifiConfigManager.getSavedNetworks()).thenReturn(savedNetwork);
        scanResultLinkConfiguration(savedConfigs, scanDetails);

        WifiConfiguration candidate = mWifiQualifiedNetworkSelector.selectQualifiedNetwork(false,
                false, scanDetails, false, false, true, false);

        assertEquals("choose the wrong SSID", null, candidate);
    }

    /**
     * Case #7    encrypted network over passpoint network
     *
     * In this test. we simulate following scenario
     * WifiStateMachine is under disconnected state
     * Two networks test1 is secured network, test2 are passpoint network
     * Both network are enabled and at 2.4 GHz. Both have RSSI of -70
     *
     * Expected behavior: test1 is chosen since secured network has higher priority than passpoint
     * network
     */
    @Test
    public void chooseNetworkSecurityOverPassPoint() {
        String[] ssids = DEFAULT_SSIDS;
        String[] bssids = DEFAULT_BSSIDS;
        int[] frequencies = {2437, 2437};
        String[] caps = {"[WPA2-EAP-CCMP][ESS]", "[ESS]"};
        int[] levels = {-70, -70};
        int[] security = {SECURITY_EAP, SECURITY_NONE};

        List<ScanDetail> scanDetails = getScanDetails(ssids, bssids, frequencies, caps, levels);
        WifiConfiguration[] savedConfigs = generateWifiConfigurations(ssids, security);
        setConfigPasspoint(savedConfigs[1]);
        prepareConfigStore(savedConfigs);

        final List<WifiConfiguration> savedNetwork = Arrays.asList(savedConfigs);
        when(mWifiConfigManager.getSavedNetworks()).thenReturn(savedNetwork);
        scanResultLinkConfiguration(savedConfigs, scanDetails);
        ScanResult chosenScanResult = scanDetails.get(0).getScanResult();

        WifiConfiguration candidate = mWifiQualifiedNetworkSelector.selectQualifiedNetwork(false,
                false, scanDetails, false, false, true, false);

        verifySelectedResult(chosenScanResult, candidate);
    }

    /**
     * Case #8    passpoint network over open network
     *
     * In this test. we simulate following scenario
     * WifiStateMachine is under disconnected state
     * Two networks test1 is passpoint network, test2 is open network
     * Both network are enabled and at 2.4 GHz. Both have RSSI of -70
     *
     * Expected behavior: test1 is chosen since passpoint network has higher priority than open
     * network
     */
    @Test
    public void chooseNetworkPasspointOverOpen() {
        String[] ssids = {"\"test1\"", "\"test2\""};
        String[] bssids = {"6c:f3:7f:ae:8c:f8", "6c:f3:7f:ae:8c:f4"};
        int[] frequencies = {2437, 2437};
        String[] caps = {"[WPA2-EAP-CCMP][ESS]", "[WPA2-EAP-CCMP][ESS][ESS]"};
        int[] levels = {-70, -70};
        int[] security = {SECURITY_NONE, SECURITY_NONE};

        List<ScanDetail> scanDetails = getScanDetails(ssids, bssids, frequencies, caps, levels);
        WifiConfiguration[] savedConfigs = generateWifiConfigurations(ssids, security);
        setConfigPasspoint(savedConfigs[0]);
        prepareConfigStore(savedConfigs);

        final List<WifiConfiguration> savedNetwork = Arrays.asList(savedConfigs);
        when(mWifiConfigManager.getSavedNetworks()).thenReturn(savedNetwork);
        scanResultLinkConfiguration(savedConfigs, scanDetails);
        ScanResult chosenScanResult = scanDetails.get(0).getScanResult();

        WifiConfiguration candidate = mWifiQualifiedNetworkSelector.selectQualifiedNetwork(false,
                false, scanDetails, false, false, true, false);

        verifySelectedResult(chosenScanResult, candidate);
    }

    /**
     * Case #9    secure network over open network
     *
     * In this test. we simulate following scenario
     * WifiStateMachine is under disconnected state
     * Two networks test1 is secure network, test2 is open network
     * Both network are enabled and at 2.4 GHz. Both have RSSI of -70
     *
     * Expected behavior: test1 is chosen since secured network has higher priority than open
     * network
     */
    @Test
    public void chooseNetworkSecureOverOpen() {
        String[] ssids = DEFAULT_SSIDS;
        String[] bssids = DEFAULT_BSSIDS;
        int[] frequencies = {2437, 2437};
        String[] caps = {"[WPA2-EAP-CCMP][ESS]", "[WPA2-EAP-CCMP][ESS][ESS]"};
        int[] levels = {-70, -70};
        int[] security = {SECURITY_PSK, SECURITY_NONE};

        List<ScanDetail> scanDetails = getScanDetails(ssids, bssids, frequencies, caps, levels);
        WifiConfiguration[] savedConfigs = generateWifiConfigurations(ssids, security);
        prepareConfigStore(savedConfigs);

        final List<WifiConfiguration> savedNetwork = Arrays.asList(savedConfigs);
        when(mWifiConfigManager.getSavedNetworks()).thenReturn(savedNetwork);
        scanResultLinkConfiguration(savedConfigs, scanDetails);
        ScanResult chosenScanResult = scanDetails.get(0).getScanResult();

        WifiConfiguration candidate = mWifiQualifiedNetworkSelector.selectQualifiedNetwork(false,
                false, scanDetails, false, false, true, false);
        verifySelectedResult(chosenScanResult, candidate);
    }

    /**
     * Case #10    first time user select a network
     *
     * In this test. we simulate following scenario
     * There are three saved networks: test1, test2 and test3. Now user select the network test3
     * check test3 has been saved in test1's and test2's ConnectChoice
     *
     * Expected behavior: test1's and test2's ConnectChoice should be test3, test3's ConnectChoice
     * should be null
     */
    @Test
    public void userSelectsNetworkForFirstTime() {
        String[] ssids = {"\"test1\"", "\"test2\"", "\"test3\""};
        int[] security = {SECURITY_PSK, SECURITY_PSK, SECURITY_NONE};

        final WifiConfiguration[] configs = generateWifiConfigurations(ssids, security);
        prepareConfigStore(configs);
        when(mWifiConfigManager.getSavedNetworks()).thenReturn(Arrays.asList(configs));
        for (WifiConfiguration network : configs) {
            WifiConfiguration.NetworkSelectionStatus status = network.getNetworkSelectionStatus();
            status.setSeenInLastQualifiedNetworkSelection(true);
        }

        mWifiQualifiedNetworkSelector.userSelectNetwork(configs.length - 1, true);
        String key = configs[configs.length - 1].configKey();
        for (int index = 0; index < configs.length; index++) {
            WifiConfiguration config = configs[index];
            WifiConfiguration.NetworkSelectionStatus status = config.getNetworkSelectionStatus();
            if (index == configs.length - 1) {
                assertEquals("User selected network should not have prefernce over it", null,
                        status.getConnectChoice());
            } else {
                assertEquals("Wrong user preference", key, status.getConnectChoice());
            }
        }
    }

    /**
     * Case #11    choose user selected network
     *
     * In this test, we simulate following scenario:
     * WifiStateMachine is under disconnected state
     * There are three networks: test1, test2, test3 and test3 is the user preference
     * All three networks are enabled
     * test1 is @ 2.4GHz with RSSI -50 PSK
     * test2 is @ 5Ghz with RSSI -65 PSK
     * test3 is @ 2.4GHz with RSSI -55 open
     *
     * Expected behavior: test3 is chosen since it is user selected network. It overcome all other
     * priorities
     */
    @Test
    public void chooseUserPreferredNetwork() {
        String[] ssids = {"\"test1\"", "\"test2\"", "\"test3\""};
        int[] security = {SECURITY_PSK, SECURITY_PSK, SECURITY_NONE};

        final WifiConfiguration[] configs = generateWifiConfigurations(ssids, security);
        prepareConfigStore(configs);
        for (WifiConfiguration network : configs) {
            WifiConfiguration.NetworkSelectionStatus status = network.getNetworkSelectionStatus();
            status.setSeenInLastQualifiedNetworkSelection(true);
        }

        when(mWifiConfigManager.getSavedNetworks()).thenReturn(Arrays.asList(configs));

        //set user preference
        mWifiQualifiedNetworkSelector.userSelectNetwork(ssids.length - 1, true);
        //Generate mocked recent scan results
        String[] bssids = {"6c:f3:7f:ae:8c:f3", "6c:f3:7f:ae:8c:f4", "6c:f3:7f:ae:8c:f5"};
        int[] frequencies = {2437, 5180, 2437};
        String[] caps = {"[WPA2-EAP-CCMP][ESS]", "[WPA2-EAP-CCMP][ESS][ESS]", "NONE"};
        int[] levels = {-50, -65, -55};

        List<ScanDetail> scanDetails = getScanDetails(ssids, bssids, frequencies, caps, levels);
        scanResultLinkConfiguration(configs, scanDetails);

        ScanResult chosenScanResult = scanDetails.get(scanDetails.size() - 1).getScanResult();
        when(mWifiConfigManager.getWifiConfiguration(configs[2].configKey()))
                .thenReturn(configs[2]);

        WifiConfiguration candidate = mWifiQualifiedNetworkSelector.selectQualifiedNetwork(false,
                false, scanDetails, false, false, true, false);
        verifySelectedResult(chosenScanResult, candidate);
    }

    /**
     * Case #12    enable a blacklisted BSSID
     *
     * In this test, we simulate following scenario:
     * For two Aps, BSSIDA and BSSIDB. Disable BSSIDA, then check whether BSSIDA is disabled and
     * BSSIDB is enabled. Then enable BSSIDA, check whether both BSSIDs are enabled.
     */
    @Test
    public void enableBssidTest() {
        String bssidA = "6c:f3:7f:ae:8c:f3";
        String bssidB = "6c:f3:7f:ae:8c:f4";
        //check by default these two BSSIDs should be enabled
        assertEquals("bssidA should be enabled by default",
                mWifiQualifiedNetworkSelector.isBssidDisabled(bssidA), false);
        assertEquals("bssidB should be enabled by default",
                mWifiQualifiedNetworkSelector.isBssidDisabled(bssidB), false);

        //disable bssidA 3 times, check whether A is dsiabled and B is still enabled
        mWifiQualifiedNetworkSelector.enableBssidForQualityNetworkSelection(bssidA, false);
        assertEquals("bssidA should be disabled",
                mWifiQualifiedNetworkSelector.isBssidDisabled(bssidA), false);
        mWifiQualifiedNetworkSelector.enableBssidForQualityNetworkSelection(bssidA, false);
        assertEquals("bssidA should be disabled",
                mWifiQualifiedNetworkSelector.isBssidDisabled(bssidA), false);
        mWifiQualifiedNetworkSelector.enableBssidForQualityNetworkSelection(bssidA, false);
        assertEquals("bssidA should be disabled",
                mWifiQualifiedNetworkSelector.isBssidDisabled(bssidA), true);
        assertEquals("bssidB should still be enabled",
                mWifiQualifiedNetworkSelector.isBssidDisabled(bssidB), false);

        //re-enable bssidA, check whether A is dsiabled and B is still enabled
        mWifiQualifiedNetworkSelector.enableBssidForQualityNetworkSelection(bssidA, true);
        assertEquals("bssidA should be enabled by default",
                mWifiQualifiedNetworkSelector.isBssidDisabled(bssidA), false);
        assertEquals("bssidB should be enabled by default",
                mWifiQualifiedNetworkSelector.isBssidDisabled(bssidB), false);

        //make sure illegal input will not cause crash
        mWifiQualifiedNetworkSelector.enableBssidForQualityNetworkSelection(null, false);
        mWifiQualifiedNetworkSelector.enableBssidForQualityNetworkSelection(null, true);
    }

    /**
     * Case #13    do not choose the BSSID has been disabled
     *
     * In this test. we simulate following scenario:
     * WifiStateMachine is under disconnected state
     * Two networks test1, test2 are secured network and found in scan results
     * Both network are enabled
     * test1 is @ 2GHz with RSSI -65
     * test2 is @ 5Ghz with RSSI -50
     * test2's BSSID is disabled
     *
     * expected return test1 since test2's BSSID has been disabled
     */
    @Test
    public void networkChooseWithOneBssidDisabled() {
        String[] ssids = DEFAULT_SSIDS;
        String[] bssids = DEFAULT_BSSIDS;
        int[] frequencies = {2437, 5180};
        String[] caps = {"[WPA2-EAP-CCMP][ESS]", "[WPA2-EAP-CCMP][ESS][ESS]"};
        int[] levels = {-65, -50};
        int[] security = {SECURITY_PSK, SECURITY_PSK};

        List<ScanDetail> scanDetails = getScanDetails(ssids, bssids, frequencies, caps, levels);
        WifiConfiguration[] savedConfigs = generateWifiConfigurations(ssids, security);
        prepareConfigStore(savedConfigs);

        final List<WifiConfiguration> savedNetwork = Arrays.asList(savedConfigs);
        when(mWifiConfigManager.getSavedNetworks()).thenReturn(savedNetwork);
        scanResultLinkConfiguration(savedConfigs, scanDetails);
        ScanResult chosenScanResult = scanDetails.get(0).getScanResult();

        mWifiQualifiedNetworkSelector.enableBssidForQualityNetworkSelection(bssids[1], false);
        mWifiQualifiedNetworkSelector.enableBssidForQualityNetworkSelection(bssids[1], false);
        mWifiQualifiedNetworkSelector.enableBssidForQualityNetworkSelection(bssids[1], false);
        WifiConfiguration candidate = mWifiQualifiedNetworkSelector.selectQualifiedNetwork(false,
                false, scanDetails, false, false, true, false);

        verifySelectedResult(chosenScanResult, candidate);
    }

    /**
     * Case #14    re-choose the disabled BSSID after it is re-enabled
     *
     * In this test. we simulate following scenario:
     * WifiStateMachine is under disconnected state
     * Two networks test1, test2 are secured network and found in scan results
     * Both network are enabled
     * test1 is @ 2GHz with RSSI -65
     * test2 is @ 5Ghz with RSSI -50
     * test2's BSSID is disabled
     *
     * expected return test2 since test2's BSSID has been enabled again
     */
    @Test
    public void networkChooseWithOneBssidReenaabled() {
        String[] ssids = DEFAULT_SSIDS;
        String[] bssids = DEFAULT_BSSIDS;
        int[] frequencies = {2437, 5180};
        String[] caps = {"[WPA2-EAP-CCMP][ESS]", "[WPA2-EAP-CCMP][ESS][ESS]"};
        int[] levels = {-65, -50};
        int[] security = {SECURITY_PSK, SECURITY_PSK};

        List<ScanDetail> scanDetails = getScanDetails(ssids, bssids, frequencies, caps, levels);
        WifiConfiguration[] savedConfigs = generateWifiConfigurations(ssids, security);
        prepareConfigStore(savedConfigs);

        final List<WifiConfiguration> savedNetwork = Arrays.asList(savedConfigs);
        when(mWifiConfigManager.getSavedNetworks()).thenReturn(savedNetwork);
        scanResultLinkConfiguration(savedConfigs, scanDetails);
        ScanResult chosenScanResult = scanDetails.get(1).getScanResult();

        mWifiQualifiedNetworkSelector.enableBssidForQualityNetworkSelection(bssids[1], false);
        mWifiQualifiedNetworkSelector.enableBssidForQualityNetworkSelection(bssids[1], false);
        mWifiQualifiedNetworkSelector.enableBssidForQualityNetworkSelection(bssids[1], false);
        //re-enable it
        mWifiQualifiedNetworkSelector.enableBssidForQualityNetworkSelection(bssids[1], true);
        WifiConfiguration candidate = mWifiQualifiedNetworkSelector.selectQualifiedNetwork(false,
                false, scanDetails, false, false, true, false);

        verifySelectedResult(chosenScanResult, candidate);
    }

    /**
     * Case #15    re-choose the disabled BSSID after its disability has expired
     *
     * In this test. we simulate following scenario:
     * WifiStateMachine is under disconnected state
     * Two networks test1, test2 are secured network and found in scan results
     * Both network are enabled
     * test1 is @ 2GHz with RSSI -65
     * test2 is @ 5Ghz with RSSI -50
     * test2's BSSID is disabled
     *
     * expected return test2 since test2's BSSID has been enabled again
     */
    @Test
    public void networkChooseWithOneBssidDisableExpire() {
        String[] ssids = {"\"test1\"", "\"test2\"", "\"test3\""};
        String[] bssids = {"6c:f3:7f:ae:8c:f3", "6c:f3:7f:ae:8c:f4", "6c:f3:7f:ae:8c:f5"};
        int[] frequencies = {2437, 5180, 5180};
        String[] caps = {"[WPA2-EAP-CCMP][ESS]", "[WPA2-EAP-CCMP][ESS][ESS]",
                "[WPA2-EAP-CCMP][ESS][ESS]"};
        int[] levels = {-65, -50, -60};
        int[] security = {SECURITY_PSK, SECURITY_PSK, SECURITY_PSK};

        List<ScanDetail> scanDetails = getScanDetails(ssids, bssids, frequencies, caps, levels);
        WifiConfiguration[] savedConfigs = generateWifiConfigurations(ssids, security);
        prepareConfigStore(savedConfigs);

        final List<WifiConfiguration> savedNetwork = Arrays.asList(savedConfigs);
        when(mWifiConfigManager.getSavedNetworks()).thenReturn(savedNetwork);
        scanResultLinkConfiguration(savedConfigs, scanDetails);
        ScanResult chosenScanResult = scanDetails.get(1).getScanResult();

        for (int index = 0; index < WifiQualifiedNetworkSelector.BSSID_BLACKLIST_THRESHOLD;
                index++) {
            mWifiQualifiedNetworkSelector.enableBssidForQualityNetworkSelection(bssids[1], false);
            mWifiQualifiedNetworkSelector.enableBssidForQualityNetworkSelection(bssids[2], false);
        }

        //re-enable it
        when(mClock.elapsedRealtime()).thenReturn(SystemClock.elapsedRealtime()
                + WifiQualifiedNetworkSelector.BSSID_BLACKLIST_EXPIRE_TIME);
        WifiConfiguration candidate = mWifiQualifiedNetworkSelector.selectQualifiedNetwork(false,
                false, scanDetails, false, false, true, false);

        verifySelectedResult(chosenScanResult, candidate);
    }
    /**
     * Case #16    do not choose the SSID has been disabled
     *
     * In this test. we simulate following scenario:
     * WifiStateMachine is under disconnected state
     * Two networks test1, test2 are secured network and found in scan results
     * Both network are enabled
     * test1 is @ 2GHz with RSSI -65
     * test2 is @ 5Ghz with RSSI -50
     * test2's SSID is disabled
     *
     * expected return test1 since test2's SSID has been disabled
     */
    @Test
    public void networkChooseWithOneSsidDisabled() {
        String[] ssids = DEFAULT_SSIDS;
        String[] bssids = DEFAULT_BSSIDS;
        int[] frequencies = {2437, 5180};
        String[] caps = {"[WPA2-EAP-CCMP][ESS]", "[WPA2-EAP-CCMP][ESS][ESS]"};
        int[] levels = {-65, -50};
        int[] security = {SECURITY_PSK, SECURITY_PSK};

        List<ScanDetail> scanDetails = getScanDetails(ssids, bssids, frequencies, caps, levels);
        WifiConfiguration[] savedConfigs = generateWifiConfigurations(ssids, security);
        prepareConfigStore(savedConfigs);

        final List<WifiConfiguration> savedNetwork = Arrays.asList(savedConfigs);
        when(mWifiConfigManager.getSavedNetworks()).thenReturn(savedNetwork);
        scanResultLinkConfiguration(savedConfigs, scanDetails);
        ScanResult chosenScanResult = scanDetails.get(0).getScanResult();

        when(mWifiConfigManager.tryEnableQualifiedNetwork(anyInt())).thenReturn(true);
        savedConfigs[1].getNetworkSelectionStatus().setNetworkSelectionStatus(
                WifiConfiguration.NetworkSelectionStatus.NETWORK_SELECTION_TEMPORARY_DISABLED);
        WifiConfiguration candidate = mWifiQualifiedNetworkSelector.selectQualifiedNetwork(false,
                false, scanDetails, false, false, true, false);

        verifySelectedResult(chosenScanResult, candidate);
    }

    /**
     * Case #17    do not make QNS is link is bouncing now
     *
     * In this test. we simulate following scenario:
     * WifiStateMachine is under disconnected state and currently is under link bouncing
     * Two networks test1, test2 are secured network and found in scan results
     * Both network are enabled
     * test1 is @ 2GHz with RSSI -50
     * test2 is @ 5Ghz with RSSI -50
     *
     * expected return null
     */
    @Test
    public void noQNSWhenLinkBouncingDisconnected() {
        String[] ssids = DEFAULT_SSIDS;
        String[] bssids = DEFAULT_BSSIDS;
        int[] frequencies = {2437, 5180};
        String[] caps = {"[WPA2-EAP-CCMP][ESS]", "[WPA2-EAP-CCMP][ESS][ESS]"};
        int[] levels = {WifiQualifiedNetworkSelector.MINIMUM_2G_ACCEPT_RSSI - 1,
                WifiQualifiedNetworkSelector.MINIMUM_5G_ACCEPT_RSSI - 1};
        int[] security = {SECURITY_PSK, SECURITY_PSK};

        List<ScanDetail> scanDetails = getScanDetails(ssids, bssids, frequencies, caps, levels);
        WifiConfiguration[] savedConfigs = generateWifiConfigurations(ssids, security);
        prepareConfigStore(savedConfigs);

        final List<WifiConfiguration> savedNetwork = Arrays.asList(savedConfigs);
        when(mWifiConfigManager.getSavedNetworks()).thenReturn(savedNetwork);
        scanResultLinkConfiguration(savedConfigs, scanDetails);

        WifiConfiguration candidate = mWifiQualifiedNetworkSelector.selectQualifiedNetwork(false,
                false, scanDetails, true, false, true, false);

        assertEquals("choose the wrong network", null, candidate);
    }

    /**
     * Case #18    QNS with very short gap
     *
     * In this test. we simulate following scenario:
     * WifiStateMachine is under disconnected state
     * If last QNS is made in less than MINIMUM_QUALIFIED_NETWORK_SELECTION_INTERVAL, we
     * still should make new QNS since it is disconnected now
     *
     * expect return test1 because of band bonus
     */
    @Test
    public void networkSelectionInShortGap() {
        String[] ssids = DEFAULT_SSIDS;
        String[] bssids = DEFAULT_BSSIDS;
        int[] frequencies = {2437, 5180};
        String[] caps = {"[WPA2-EAP-CCMP][ESS]", "[WPA2-EAP-CCMP][ESS][ESS]"};
        int[] levels = {-50, -65};
        int[] security = {SECURITY_PSK, SECURITY_PSK};

        List<ScanDetail> scanDetails = getScanDetails(ssids, bssids, frequencies, caps, levels);
        WifiConfiguration[] savedConfigs = generateWifiConfigurations(ssids, security);
        prepareConfigStore(savedConfigs);

        final List<WifiConfiguration> savedNetwork = Arrays.asList(savedConfigs);
        when(mWifiConfigManager.getSavedNetworks()).thenReturn(savedNetwork);
        scanResultLinkConfiguration(savedConfigs, scanDetails);
        //first QNS
        mWifiQualifiedNetworkSelector.selectQualifiedNetwork(false, false, scanDetails, false,
                false, true, false);
        //immediately second QNS
        WifiConfiguration candidate = mWifiQualifiedNetworkSelector.selectQualifiedNetwork(false,
                false, scanDetails, false, false, true, false);
        ScanResult chosenScanResult = scanDetails.get(1).getScanResult();

        verifySelectedResult(chosenScanResult, candidate);
    }

    //Unit test for Connected State

    /**
     * Case #19    no QNS with very short gap when connected
     * In this test. we simulate following scenario:
     * WifiStateMachine is under connected state and test2 is connected
     * When WifiStateMachine is already in connected state, if last QNS is made in less than
     * MINIMUM_QUALIFIED_NETWORK_SELECTION_INTERVAL, no new QNS should be made
     *
     * expect return NULL
     */
    @Test
    public void noNetworkSelectionDueToShortGap() {
        String[] ssids = DEFAULT_SSIDS;
        String[] bssids = DEFAULT_BSSIDS;
        int[] frequencies = {2437, 5180};
        String[] caps = {"[WPA2-EAP-CCMP][ESS]", "[WPA2-EAP-CCMP][ESS][ESS]"};
        int[] levels = {-50, -65};
        int[] security = {SECURITY_PSK, SECURITY_PSK};

        List<ScanDetail> scanDetails = getScanDetails(ssids, bssids, frequencies, caps, levels);
        WifiConfiguration[] savedConfigs = generateWifiConfigurations(ssids, security);
        prepareConfigStore(savedConfigs);

        final List<WifiConfiguration> savedNetwork = Arrays.asList(savedConfigs);
        when(mWifiConfigManager.getSavedNetworks()).thenReturn(savedNetwork);
        scanResultLinkConfiguration(savedConfigs, scanDetails);
        //first QNS
        mWifiQualifiedNetworkSelector.selectQualifiedNetwork(false, false, scanDetails, false,
                false, true, false);
        //immediately second QNS
        WifiConfiguration candidate = mWifiQualifiedNetworkSelector.selectQualifiedNetwork(false,
                false, scanDetails, false, true, false, false);
        ScanResult chosenScanResult = scanDetails.get(1).getScanResult();
        assertEquals("choose the wrong BSSID", null, candidate);
    }

    /**
     * Case #20    force QNS with very short gap under connection
     * In this test. we simulate following scenario:
     * WifiStateMachine is under connected state and test2 is connected
     * When WifiStateMachine is already in connected state, if last QNS is made in less than
     * MINIMUM_QUALIFIED_NETWORK_SELECTION_INTERVAL, no new QNS should be made. However, if we force
     * to make new QNS, QNS still will be made
     *
     * expect return test2 since it is the current connected one (bonus)
     */
    @Test
    public void forceNetworkSelectionInShortGap() {
        String[] ssids = DEFAULT_SSIDS;
        String[] bssids = DEFAULT_BSSIDS;
        int[] frequencies = {2437, 5180};
        String[] caps = {"[WPA2-EAP-CCMP][ESS]", "[WPA2-EAP-CCMP][ESS][ESS]"};
        int[] levels = {-50, -65};
        int[] security = {SECURITY_PSK, SECURITY_PSK};

        List<ScanDetail> scanDetails = getScanDetails(ssids, bssids, frequencies, caps, levels);
        WifiConfiguration[] savedConfigs = generateWifiConfigurations(ssids, security);
        prepareConfigStore(savedConfigs);

        final List<WifiConfiguration> savedNetwork = Arrays.asList(savedConfigs);
        when(mWifiConfigManager.getSavedNetworks()).thenReturn(savedNetwork);
        scanResultLinkConfiguration(savedConfigs, scanDetails);
        //first QNS
        mWifiQualifiedNetworkSelector.selectQualifiedNetwork(false, false, scanDetails, false,
                false, true, false);
        //immediately second QNS
        WifiConfiguration candidate = mWifiQualifiedNetworkSelector.selectQualifiedNetwork(true,
                false, scanDetails, false, true, false, false);
        ScanResult chosenScanResult = scanDetails.get(1).getScanResult();

        verifySelectedResult(chosenScanResult, candidate);
    }

    /**
     * Case #21    no QNS when connected and user do not allow switch when connected
     *
     * In this test. we simulate following scenario:
     * WifiStateMachine is under connected state and test2 is connected
     * if user does not allow switch network when connected, do not make new QNS when connected
     *
     * expect return NULL
     */
    @Test
    public void noNewNetworkSelectionDuetoUserDisableSwitchWhenConnected() {
        String[] ssids = DEFAULT_SSIDS;
        String[] bssids = DEFAULT_BSSIDS;
        int[] frequencies = {2437, 5180};
        String[] caps = {"[WPA2-EAP-CCMP][ESS]", "[WPA2-EAP-CCMP][ESS][ESS]"};
        int[] levels = {-50, -65};
        int[] security = {SECURITY_PSK, SECURITY_PSK};

        List<ScanDetail> scanDetails = getScanDetails(ssids, bssids, frequencies, caps, levels);
        WifiConfiguration[] savedConfigs = generateWifiConfigurations(ssids, security);
        prepareConfigStore(savedConfigs);

        final List<WifiConfiguration> savedNetwork = Arrays.asList(savedConfigs);
        when(mWifiConfigManager.getSavedNetworks()).thenReturn(savedNetwork);
        scanResultLinkConfiguration(savedConfigs, scanDetails);

        WifiConfiguration candidate = mWifiQualifiedNetworkSelector.selectQualifiedNetwork(false,
                false, scanDetails, false, true, false, false);
        assertEquals("choose the wrong BSSID", null, candidate);
        assertEquals("Should receive zero filteredScanDetails", 0,
                mWifiQualifiedNetworkSelector.getFilteredScanDetails().size());
    }

    /**
     * Case #22    no new QNS if current network is qualified already
     *
     * In this test. we simulate following scenario:
     * WifiStateMachine is under connected state and test2 is connected
     * If current connected network is Qualified already, do not make new QNS
     * simulated current connected network as:
     * 5GHz, RSSI = WifiQualifiedNetworkSelector.QUALIFIED_RSSI_5G_BAND, secured
     *
     * expected return null
     */
    @Test
    public void noNewQNSCurrentNetworkQualified() {
        String[] ssids = DEFAULT_SSIDS;
        String[] bssids = DEFAULT_BSSIDS;
        int[] frequencies = {2437, 5180};
        String[] caps = {"[WPA2-EAP-CCMP][ESS]", "[WPA2-EAP-CCMP][ESS][ESS]"};
        int[] levels = {-65, WifiQualifiedNetworkSelector.QUALIFIED_RSSI_5G_BAND};
        int[] security = {SECURITY_PSK, SECURITY_PSK};

        List<ScanDetail> scanDetails = getScanDetails(ssids, bssids, frequencies, caps, levels);
        WifiConfiguration[] savedConfigs = generateWifiConfigurations(ssids, security);
        prepareConfigStore(savedConfigs);

        final List<WifiConfiguration> savedNetwork = Arrays.asList(savedConfigs);
        when(mWifiConfigManager.getSavedNetworks()).thenReturn(savedNetwork);
        scanResultLinkConfiguration(savedConfigs, scanDetails);

        //first time, connect to test2 due to 5GHz bonus
        mWifiQualifiedNetworkSelector.selectQualifiedNetwork(false, false, scanDetails, false,
                false, true, false);
        when(mWifiInfo.getNetworkId()).thenReturn(1);
        when(mWifiInfo.getBSSID()).thenReturn(bssids[1]);
        when(mWifiInfo.is24GHz()).thenReturn(false);
        when(mWifiConfigManager.getEnableAutoJoinWhenAssociated()).thenReturn(true);
        when(mClock.elapsedRealtime()).thenReturn(SystemClock.elapsedRealtime() + 11 * 1000);

        levels[0] = -50; // if there is QNS, test1 will be chosen
        scanDetails = getScanDetails(ssids, bssids, frequencies, caps, levels);
        scanResultLinkConfiguration(savedConfigs, scanDetails);

        WifiConfiguration candidate = mWifiQualifiedNetworkSelector.selectQualifiedNetwork(false,
                false, scanDetails, false, true, false, false);
        assertEquals("choose the wrong BSSID", null, candidate);
    }

    /**
     * Case #23    No new QNS when link bouncing when connected
     *
     * In this test. we simulate following scenario:
     * WifiStateMachine is under connected state and test2 is connected
     * no new QNS when link is bouncing
     *
     * expected return null
     */
    @Test
    public void noNewQNSLinkBouncing() {
        String[] ssids = DEFAULT_SSIDS;
        String[] bssids = DEFAULT_BSSIDS;
        int[] frequencies = {2437, 5180};
        String[] caps = {"[WPA2-EAP-CCMP][ESS]", "[WPA2-EAP-CCMP][ESS][ESS]"};
        int[] levels = {-70, -75};
        int[] security = {SECURITY_PSK, SECURITY_PSK};

        List<ScanDetail> scanDetails = getScanDetails(ssids, bssids, frequencies, caps, levels);
        WifiConfiguration[] savedConfigs = generateWifiConfigurations(ssids, security);
        prepareConfigStore(savedConfigs);

        final List<WifiConfiguration> savedNetwork = Arrays.asList(savedConfigs);
        when(mWifiConfigManager.getSavedNetworks()).thenReturn(savedNetwork);
        scanResultLinkConfiguration(savedConfigs, scanDetails);

        //first connect to test2 due to 5GHz bonus
        mWifiQualifiedNetworkSelector.selectQualifiedNetwork(false, false, scanDetails, false,
                false, true, false);
        when(mWifiInfo.getNetworkId()).thenReturn(1);
        when(mWifiInfo.getBSSID()).thenReturn(bssids[1]);
        when(mWifiInfo.is24GHz()).thenReturn(false);
        when(mClock.elapsedRealtime()).thenReturn(SystemClock.elapsedRealtime() + 11 * 1000);
        when(mWifiConfigManager.getEnableAutoJoinWhenAssociated()).thenReturn(true);

        WifiConfiguration candidate = mWifiQualifiedNetworkSelector.selectQualifiedNetwork(false,
                false, scanDetails, true, true, false, false);
        assertEquals("choose the wrong BSSID", null, candidate);
    }

    /**
     * Case #24    Qualified network need to be on 5GHz
     *
     * In this test. we simulate following scenario:
     * WifiStateMachine is under connected state and connected to test2
     * if current connected network is not 5GHz, then it is not qualified. We should make new QNS
     *
     * expected result: return test1
     */
    @Test
    public void currentNetworkNotQualifiedDueToBandMismatch() {
        String[] ssids = DEFAULT_SSIDS;
        String[] bssids = DEFAULT_BSSIDS;
        int[] frequencies = {2437, 2437};
        String[] caps = {"[WPA2-EAP-CCMP][ESS]", "[WPA2-EAP-CCMP][ESS][ESS]"};
        int[] levels = {-50, -65};
        int[] security = {SECURITY_PSK, SECURITY_PSK};

        List<ScanDetail> scanDetails = getScanDetails(ssids, bssids, frequencies, caps, levels);
        WifiConfiguration[] savedConfigs = generateWifiConfigurations(ssids, security);
        prepareConfigStore(savedConfigs);

        final List<WifiConfiguration> savedNetwork = Arrays.asList(savedConfigs);
        when(mWifiConfigManager.getSavedNetworks()).thenReturn(savedNetwork);
        scanResultLinkConfiguration(savedConfigs, scanDetails);
        when(mWifiInfo.getNetworkId()).thenReturn(0);
        when(mWifiInfo.getBSSID()).thenReturn(bssids[0]);
        when(mWifiInfo.is24GHz()).thenReturn(true);
        //connect to config2 first
        mWifiQualifiedNetworkSelector.selectQualifiedNetwork(false, false, scanDetails, false,
                false, true, false);

        when(mClock.elapsedRealtime()).thenReturn(SystemClock.elapsedRealtime() + 11 * 1000);
        when(mWifiConfigManager.getEnableAutoJoinWhenAssociated()).thenReturn(true);

        ScanResult chosenScanResult = scanDetails.get(0).getScanResult();
        WifiConfiguration candidate = mWifiQualifiedNetworkSelector.selectQualifiedNetwork(false,
                false, scanDetails, false, true, false, false);
        verifySelectedResult(chosenScanResult, candidate);
    }

    /**
     * Case #25    Qualified network need to be secured
     *
     * In this test. we simulate following scenario:
     * WifiStateMachine is under connected state and current connects to test2
     * if current connected network is open network, then it is not qualified. We should make new
     * QNS
     *
     * expected result: return test1 since test1 has higher RSSI
     */
    @Test
    public void currentNetworkNotQualifiedDueToOpenNetwork() {
        String[] ssids = DEFAULT_SSIDS;
        String[] bssids = DEFAULT_BSSIDS;
        int[] frequencies = {5400, 5400};
        String[] caps = {"[ESS]", "[ESS]"};
        int[] levels = {-70, -65};
        int[] security = {SECURITY_NONE, SECURITY_NONE};

        List<ScanDetail> scanDetails = getScanDetails(ssids, bssids, frequencies, caps, levels);
        WifiConfiguration[] savedConfigs = generateWifiConfigurations(ssids, security);
        prepareConfigStore(savedConfigs);

        final List<WifiConfiguration> savedNetwork = Arrays.asList(savedConfigs);
        when(mWifiConfigManager.getSavedNetworks()).thenReturn(savedNetwork);
        scanResultLinkConfiguration(savedConfigs, scanDetails);

        //first connect to test2 because of RSSI
        mWifiQualifiedNetworkSelector.selectQualifiedNetwork(false, false, scanDetails, false,
                false, true, false);
        when(mWifiInfo.getNetworkId()).thenReturn(1);
        when(mWifiInfo.getBSSID()).thenReturn(bssids[1]);
        when(mWifiInfo.is24GHz()).thenReturn(false);
        when(mWifiInfo.is5GHz()).thenReturn(true);
        when(mWifiConfigManager.isOpenNetwork(savedConfigs[1])).thenReturn(true);
        when(mClock.elapsedRealtime()).thenReturn(SystemClock.elapsedRealtime() + 11 * 1000);
        when(mWifiConfigManager.getEnableAutoJoinWhenAssociated()).thenReturn(true);
        levels[0] = -60;
        scanDetails = getScanDetails(ssids, bssids, frequencies, caps, levels);
        scanResultLinkConfiguration(savedConfigs, scanDetails);

        ScanResult chosenScanResult = scanDetails.get(0).getScanResult();
        WifiConfiguration candidate = mWifiQualifiedNetworkSelector.selectQualifiedNetwork(false,
                false, scanDetails, false, true, false, false);
        verifySelectedResult(chosenScanResult, candidate);
    }

    /**
     * Case #26    ephemeral network can not be qualified network
     *
     * In this test. we simulate following scenario:
     * WifiStateMachine is under connected state and current connected to test2
     * if current connected network is ephemeral network, then it is not qualified. We should make
     * new QNS
     *
     * expected result: return test1 (since test2 is ephemeral)
     */
    @Test
    public void currentNetworkNotQualifiedDueToEphemeral() {
        String[] ssids = DEFAULT_SSIDS;
        String[] bssids = DEFAULT_BSSIDS;
        int[] frequencies = {5200, 5200};
        String[] caps = {"[WPA2-EAP-CCMP][ESS]", "[WPA2-EAP-CCMP][ESS][ESS]"};
        int[] levels = {-100, -50};
        int[] security = {SECURITY_PSK, SECURITY_PSK};

        List<ScanDetail> scanDetails = getScanDetails(ssids, bssids, frequencies, caps, levels);
        WifiConfiguration[] savedConfigs = generateWifiConfigurations(ssids, security);
        savedConfigs[1].ephemeral = true;
        prepareConfigStore(savedConfigs);

        final List<WifiConfiguration> savedNetwork = Arrays.asList(savedConfigs);
        when(mWifiConfigManager.getSavedNetworks()).thenReturn(savedNetwork);
        scanResultLinkConfiguration(savedConfigs, scanDetails);

        //first connect to test2 since test1's RSSI is negligible
        mWifiQualifiedNetworkSelector.selectQualifiedNetwork(false, false, scanDetails, false,
                false, true, false);
        when(mWifiInfo.getNetworkId()).thenReturn(1);
        when(mWifiInfo.getBSSID()).thenReturn(bssids[1]);
        when(mWifiInfo.is24GHz()).thenReturn(false);

        levels[0] = -70;
        scanDetails = getScanDetails(ssids, bssids, frequencies, caps, levels);
        scanResultLinkConfiguration(savedConfigs, scanDetails);
        when(mWifiConfigManager.getEnableAutoJoinWhenAssociated()).thenReturn(true);
        when(mClock.elapsedRealtime()).thenReturn(SystemClock.elapsedRealtime() + 11 * 1000);

        ScanResult chosenScanResult = scanDetails.get(0).getScanResult();
        WifiConfiguration candidate = mWifiQualifiedNetworkSelector.selectQualifiedNetwork(false,
                false, scanDetails, false, true, false, false);
        verifySelectedResult(chosenScanResult, candidate);
    }

    /**
     * Case #27    low signal network can not be Qualified network (5GHz)
     *
     * In this test. we simulate following scenario:
     * WifiStateMachine is under connected state and current connected to test2
     * if current connected network's rssi is too low, then it is not qualified. We should
     * make new QNS
     *
     * expected result: return test1
     */
    @Test
    public void currentNetworkNotQualifiedDueToLow5GRssi() {
        String[] ssids = DEFAULT_SSIDS;
        String[] bssids = DEFAULT_BSSIDS;
        int[] frequencies = {5200, 5200};
        String[] caps = {"[WPA2-EAP-CCMP][ESS]", "[WPA2-EAP-CCMP][ESS][ESS]"};
        int[] levels = {-80, WifiQualifiedNetworkSelector.QUALIFIED_RSSI_5G_BAND - 1};
        int[] security = {SECURITY_PSK, SECURITY_PSK};

        List<ScanDetail> scanDetails = getScanDetails(ssids, bssids, frequencies, caps, levels);
        WifiConfiguration[] savedConfigs = generateWifiConfigurations(ssids, security);
        prepareConfigStore(savedConfigs);

        final List<WifiConfiguration> savedNetwork = Arrays.asList(savedConfigs);
        when(mWifiConfigManager.getSavedNetworks()).thenReturn(savedNetwork);
        scanResultLinkConfiguration(savedConfigs, scanDetails);

        mWifiQualifiedNetworkSelector.selectQualifiedNetwork(false, false, scanDetails, false,
                false, true, false);
        when(mWifiInfo.getNetworkId()).thenReturn(1);
        when(mWifiInfo.getBSSID()).thenReturn(bssids[1]);
        when(mWifiInfo.getRssi()).thenReturn(levels[1]);
        when(mWifiInfo.is24GHz()).thenReturn(false);
        when(mWifiInfo.is5GHz()).thenReturn(true);

        when(mWifiConfigManager.getEnableAutoJoinWhenAssociated()).thenReturn(true);
        when(mClock.elapsedRealtime()).thenReturn(SystemClock.elapsedRealtime() + 11 * 1000);
        levels[0] = -60;
        scanDetails = getScanDetails(ssids, bssids, frequencies, caps, levels);
        scanResultLinkConfiguration(savedConfigs, scanDetails);
        ScanResult chosenScanResult = scanDetails.get(0).getScanResult();

        WifiConfiguration candidate = mWifiQualifiedNetworkSelector.selectQualifiedNetwork(false,
                false, scanDetails, false, true, false, false);
        verifySelectedResult(chosenScanResult, candidate);
    }

    /**
     * Case #28    low signal network can not be Qualified network (2.4GHz)
     *
     * In this test. we simulate following scenario:
     * WifiStateMachine is under connected state and current connected to test2
     * if current connected network's rssi is too low, then it is not qualified. We should
     * make new QNS
     *
     * expected result: return test1
     */
    @Test
    public void currentNetworkNotQualifiedDueToLow2GRssi() {
        String[] ssids = DEFAULT_SSIDS;
        String[] bssids = DEFAULT_BSSIDS;
        int[] frequencies = {2437, 2437};
        String[] caps = {"[WPA2-EAP-CCMP][ESS]", "[WPA2-EAP-CCMP][ESS][ESS]"};
        int[] levels = {-100, WifiQualifiedNetworkSelector.QUALIFIED_RSSI_24G_BAND - 1};
        int[] security = {SECURITY_PSK, SECURITY_PSK};

        List<ScanDetail> scanDetails = getScanDetails(ssids, bssids, frequencies, caps, levels);
        WifiConfiguration[] savedConfigs = generateWifiConfigurations(ssids, security);
        prepareConfigStore(savedConfigs);
        final List<WifiConfiguration> savedNetwork = Arrays.asList(savedConfigs);
        when(mWifiConfigManager.getSavedNetworks()).thenReturn(savedNetwork);
        scanResultLinkConfiguration(savedConfigs, scanDetails);

        mWifiQualifiedNetworkSelector.selectQualifiedNetwork(false, false, scanDetails, false,
                false, true, false);

        when(mWifiInfo.getNetworkId()).thenReturn(1);
        when(mWifiInfo.getBSSID()).thenReturn(bssids[1]);
        when(mWifiInfo.getRssi()).thenReturn(levels[1]);
        when(mWifiInfo.is24GHz()).thenReturn(false);
        when(mWifiInfo.is5GHz()).thenReturn(true);

        when(mWifiConfigManager.getEnableAutoJoinWhenAssociated()).thenReturn(true);
        levels[0] = -60;
        scanDetails = getScanDetails(ssids, bssids, frequencies, caps, levels);
        when(mClock.elapsedRealtime()).thenReturn(SystemClock.elapsedRealtime() + 11 * 1000);
        scanResultLinkConfiguration(savedConfigs, scanDetails);

        ScanResult chosenScanResult = scanDetails.get(0).getScanResult();
        WifiConfiguration candidate = mWifiQualifiedNetworkSelector.selectQualifiedNetwork(false,
                false, scanDetails, false, true, false, false);
        verifySelectedResult(chosenScanResult, candidate);
    }

    /**
     * Case #29    Choose current network due to current network bonus
     *
     * In this test. we simulate following scenario:
     * WifiStateMachine is under connected state and current connected to test2
     * To connect to a network which is not linked to current connected network, unless this network
     * is more than 10 db higher than current network, we should not switch. So although test2 has a
     * lower signal, we still choose test2
     *
     * expected result: return test2
     */
    @Test
    public void currentNetworkStayDueToSameNetworkBonus() {
        String[] ssids = DEFAULT_SSIDS;
        String[] bssids = DEFAULT_BSSIDS;
        int[] frequencies = {2437, 2437};
        String[] caps = {"[WPA2-EAP-CCMP][ESS]", "[WPA2-EAP-CCMP][ESS][ESS]"};
        int[] levels = {-100, -80};
        int[] security = {SECURITY_PSK, SECURITY_PSK};

        List<ScanDetail> scanDetails = getScanDetails(ssids, bssids, frequencies, caps, levels);
        WifiConfiguration[] savedConfigs = generateWifiConfigurations(ssids, security);
        prepareConfigStore(savedConfigs);

        final List<WifiConfiguration> savedNetwork = Arrays.asList(savedConfigs);
        when(mWifiConfigManager.getSavedNetworks()).thenReturn(savedNetwork);
        scanResultLinkConfiguration(savedConfigs, scanDetails);

        mWifiQualifiedNetworkSelector.selectQualifiedNetwork(false, false, scanDetails, false,
                false, true, false);
        when(mWifiInfo.getNetworkId()).thenReturn(1);
        when(mWifiInfo.getBSSID()).thenReturn(bssids[1]);
        when(mWifiInfo.is24GHz()).thenReturn(true);

        when(mWifiConfigManager.getEnableAutoJoinWhenAssociated()).thenReturn(true);
        levels[0] = -80 + WifiQualifiedNetworkSelector.SAME_BSSID_AWARD / 4
                + WifiQualifiedNetworkSelector.SAME_NETWORK_AWARD / 4 - 1;
        scanDetails = getScanDetails(ssids, bssids, frequencies, caps, levels);
        when(mClock.elapsedRealtime()).thenReturn(SystemClock.elapsedRealtime() + 11 * 1000);
        scanResultLinkConfiguration(savedConfigs, scanDetails);

        ScanResult chosenScanResult = scanDetails.get(1).getScanResult();
        WifiConfiguration candidate = mWifiQualifiedNetworkSelector.selectQualifiedNetwork(false,
                false, scanDetails, false, true, false, false);
        verifySelectedResult(chosenScanResult, candidate);
    }

    /**
     * Case #30    choose another network due to current network's signal is too low
     *
     * In this test. we simulate following scenario:
     * WifiStateMachine is under connected state and current connected to test2
     * To connect to a network which is not linked to current connected network, if this network
     * is more than 10 db higher than current network, we should switch
     *
     * expected new result: return test1
     */
    @Test
    public void switchNetworkStayDueToCurrentNetworkRssiLow() {
        String[] ssids = DEFAULT_SSIDS;
        String[] bssids = DEFAULT_BSSIDS;
        int[] frequencies = {2437, 2437};
        String[] caps = {"[WPA2-EAP-CCMP][ESS]", "[WPA2-EAP-CCMP][ESS][ESS]"};
        int[] levels = {-100, -80};
        int[] security = {SECURITY_PSK, SECURITY_PSK};

        List<ScanDetail> scanDetails = getScanDetails(ssids, bssids, frequencies, caps, levels);
        WifiConfiguration[] savedConfigs = generateWifiConfigurations(ssids, security);
        prepareConfigStore(savedConfigs);

        final List<WifiConfiguration> savedNetwork = Arrays.asList(savedConfigs);
        when(mWifiConfigManager.getSavedNetworks()).thenReturn(savedNetwork);
        scanResultLinkConfiguration(savedConfigs, scanDetails);
        mWifiQualifiedNetworkSelector.selectQualifiedNetwork(false, false, scanDetails, false,
                false, true, false);

        when(mWifiInfo.getNetworkId()).thenReturn(1);
        when(mWifiInfo.getBSSID()).thenReturn(bssids[1]);
        when(mWifiInfo.is24GHz()).thenReturn(true);

        when(mWifiConfigManager.getEnableAutoJoinWhenAssociated()).thenReturn(true);
        levels[0] = -80 + WifiQualifiedNetworkSelector.SAME_BSSID_AWARD / 4
                + WifiQualifiedNetworkSelector.SAME_NETWORK_AWARD / 4 + 1;
        scanDetails = getScanDetails(ssids, bssids, frequencies, caps, levels);
        when(mClock.elapsedRealtime()).thenReturn(SystemClock.elapsedRealtime() + 11 * 1000);
        scanResultLinkConfiguration(savedConfigs, scanDetails);

        ScanResult chosenScanResult = scanDetails.get(0).getScanResult();
        WifiConfiguration candidate = mWifiQualifiedNetworkSelector.selectQualifiedNetwork(false,
                false, scanDetails, false, true, false, false);
        verifySelectedResult(chosenScanResult, candidate);
    }

    /**
     * Case #31    Choose current BSSID due to current BSSID bonus
     *
     * In this test. we simulate following scenario:
     * WifiStateMachine is under connected state and current connected to test2
     * Linked network will be treated as same network. To connect to a network which is linked to
     * current connected network, unless this network is more than 6 db higher than current network,
     * we should not switch AP and stick to current BSSID
     *
     * expected result: return test2
     */
    @Test
    public void currentBssidStayDueToSameBSSIDBonus() {
        String[] ssids = DEFAULT_SSIDS;
        String[] bssids = DEFAULT_BSSIDS;
        int[] frequencies = {2437, 2437};
        String[] caps = {"[WPA2-EAP-CCMP][ESS]", "[WPA2-EAP-CCMP][ESS][ESS]"};
        int[] levels = {-100, -80};
        int[] security = {SECURITY_PSK, SECURITY_PSK};

        List<ScanDetail> scanDetails = getScanDetails(ssids, bssids, frequencies, caps, levels);
        WifiConfiguration[] savedConfigs = generateWifiConfigurations(ssids, security);
        //link two configuration
        savedConfigs[0].linkedConfigurations = new HashMap<String, Integer>();
        savedConfigs[1].linkedConfigurations = new HashMap<String, Integer>();
        savedConfigs[0].linkedConfigurations.put(savedConfigs[1].configKey(), 1);
        savedConfigs[1].linkedConfigurations.put(savedConfigs[0].configKey(), 1);
        prepareConfigStore(savedConfigs);

        final List<WifiConfiguration> savedNetwork = Arrays.asList(savedConfigs);
        when(mWifiConfigManager.getSavedNetworks()).thenReturn(savedNetwork);
        scanResultLinkConfiguration(savedConfigs, scanDetails);
        mWifiQualifiedNetworkSelector.selectQualifiedNetwork(false, false, scanDetails, false,
                false, true, false);

        when(mWifiInfo.getNetworkId()).thenReturn(1);
        when(mWifiInfo.getBSSID()).thenReturn(bssids[1]);
        when(mWifiInfo.is24GHz()).thenReturn(true);

        when(mWifiConfigManager.getEnableAutoJoinWhenAssociated()).thenReturn(true);
        levels[0] = -80 + WifiQualifiedNetworkSelector.SAME_NETWORK_AWARD / 4 - 1;
        scanDetails = getScanDetails(ssids, bssids, frequencies, caps, levels);
        when(mClock.elapsedRealtime()).thenReturn(SystemClock.elapsedRealtime() + 11 * 1000);
        scanResultLinkConfiguration(savedConfigs, scanDetails);

        ScanResult chosenScanResult = scanDetails.get(1).getScanResult();
        WifiConfiguration candidate = mWifiQualifiedNetworkSelector.selectQualifiedNetwork(false,
                false, scanDetails, false, true, false, false);
        verifySelectedResult(chosenScanResult, candidate);
    }

    /**
     * Case #32    Choose another BSSID due to current BSSID's rssi is too low
     *
     * In this test. we simulate following scenario:
     * WifiStateMachine is under connected state and current connected to test2
     * Linked network will be treated as same network. To connect to a network which is linked to
     * current connected network, unless this network is more than 6 db higher than current network,
     * we should not switch AP and stick to current BSSID
     *
     * expected result: return test2
     */
    @Test
    public void swithBssidDueToLowRssi() {
        String[] ssids = DEFAULT_SSIDS;
        String[] bssids = DEFAULT_BSSIDS;
        int[] frequencies = {2437, 2437};
        String[] caps = {"[WPA2-EAP-CCMP][ESS]", "[WPA2-EAP-CCMP][ESS][ESS]"};
        int[] levels = {-100, -80};
        int[] security = {SECURITY_PSK, SECURITY_PSK};

        List<ScanDetail> scanDetails = getScanDetails(ssids, bssids, frequencies, caps, levels);
        WifiConfiguration[] savedConfigs = generateWifiConfigurations(ssids, security);
        //link two configuration
        savedConfigs[0].linkedConfigurations = new HashMap<String, Integer>();
        savedConfigs[1].linkedConfigurations = new HashMap<String, Integer>();
        savedConfigs[0].linkedConfigurations.put(savedConfigs[1].configKey(), 1);
        savedConfigs[1].linkedConfigurations.put(savedConfigs[0].configKey(), 1);
        prepareConfigStore(savedConfigs);

        final List<WifiConfiguration> savedNetwork = Arrays.asList(savedConfigs);
        when(mWifiConfigManager.getSavedNetworks()).thenReturn(savedNetwork);
        scanResultLinkConfiguration(savedConfigs, scanDetails);
        mWifiQualifiedNetworkSelector.selectQualifiedNetwork(false, false, scanDetails, false,
                false, true, false);

        when(mWifiInfo.getNetworkId()).thenReturn(1);
        when(mWifiInfo.getBSSID()).thenReturn(bssids[1]);
        when(mWifiInfo.is24GHz()).thenReturn(true);

        when(mWifiConfigManager.getEnableAutoJoinWhenAssociated()).thenReturn(true);
        levels[0] = -80 + WifiQualifiedNetworkSelector.SAME_BSSID_AWARD / 4 + 1;
        scanDetails = getScanDetails(ssids, bssids, frequencies, caps, levels);
        when(mClock.elapsedRealtime()).thenReturn(SystemClock.elapsedRealtime() + 11 * 1000);
        scanResultLinkConfiguration(savedConfigs, scanDetails);

        ScanResult chosenScanResult = scanDetails.get(0).getScanResult();
        WifiConfiguration candidate = mWifiQualifiedNetworkSelector.selectQualifiedNetwork(false,
                false, scanDetails, false, true, false, false);
        verifySelectedResult(chosenScanResult, candidate);
    }

    /**
     * Case #33  Choose an ephemeral network with a good score because no saved networks
     *           are available.
     *
     * In this test. we simulate following scenario:
     * WifiStateMachine is not connected to any network.
     * selectQualifiedNetwork() is called with 2 scan results, test1 and test2.
     * test1 is an enterprise network w/o a score.
     * test2 is an open network with a good score. Additionally it's a metered network.
     * isUntrustedConnectionsAllowed is set to true.
     *
     * expected result: return test2 with meteredHint set to True.
     */
    @Test
    public void selectQualifiedNetworkChoosesEphemeral() {
        String[] ssids = DEFAULT_SSIDS;
        String[] bssids = DEFAULT_BSSIDS;
        int[] frequencies = {5200, 5200};
        String[] caps = {"[WPA2-EAP-CCMP][ESS]", "[ESS]"};
        int[] levels = {-70, -70};
        Integer[] scores = {null, 120};
        boolean[] meteredHints = {false, true};

        List<ScanDetail> scanDetails = getScanDetails(ssids, bssids, frequencies, caps, levels);
        configureScoreCache(scanDetails, scores, meteredHints);

        // No saved networks.
        when(mWifiConfigManager.updateSavedNetworkWithNewScanDetail(any(ScanDetail.class),
                anyBoolean())).thenReturn(null);

        WifiConfiguration unTrustedNetworkCandidate = mock(WifiConfiguration.class);
        // Setup the config as an invalid candidate. This is done to workaround a Mockito issue.
        // Basically Mockito is unable to mock package-private methods in classes loaded from a
        // different Jar (like all of the framework code) which results in the actual saveNetwork()
        // method being invoked in this case. Because the config is invalid it quickly returns.
        unTrustedNetworkCandidate.SSID = null;
        unTrustedNetworkCandidate.networkId = WifiConfiguration.INVALID_NETWORK_ID;
        ScanResult untrustedScanResult = scanDetails.get(1).getScanResult();
        when(mWifiConfigManager
                .wifiConfigurationFromScanResult(untrustedScanResult))
                .thenReturn(unTrustedNetworkCandidate);

        WifiConfiguration.NetworkSelectionStatus selectionStatus =
                mock(WifiConfiguration.NetworkSelectionStatus.class);
        when(unTrustedNetworkCandidate.getNetworkSelectionStatus()).thenReturn(selectionStatus);
        when(selectionStatus.getCandidate()).thenReturn(untrustedScanResult);

        WifiConfiguration candidate = mWifiQualifiedNetworkSelector.selectQualifiedNetwork(
                false /* forceSelectNetwork */,
                true /* isUntrustedConnectionsAllowed */,
                scanDetails,
                false, /* isLinkDebouncing */
                false, /* isConnected */
                true, /* isDisconnected */
                false /* isSupplicantTransient */);
        verify(selectionStatus).setCandidate(untrustedScanResult);
        assertSame(unTrustedNetworkCandidate, candidate);
        assertEquals(meteredHints[1], candidate.meteredHint);
    }

    /**
     * Case #34    Test Filtering of potential candidate scanDetails (Untrusted allowed)
     *
     * In this test. we simulate following scenario
     * WifiStateMachine is under disconnected state
     * test1 is @ 2GHz with RSSI -60
     * test2 is @ 5Ghz with RSSI -86, (below minimum threshold)
     * test3 is @ 5Ghz with RSSI -50, however it has no associated saved config
     * test4 is @ 2Ghz with RSSI -62, no associated config, but is Ephemeral
     *
     * Expected behavior: test1 is chosen due to 5GHz signal is too weak (5GHz bonus can not
     * compensate).
     * test1 & test4's scanDetails are returned by 'getFilteredScanDetail()'
     */
    @Test
    public void testGetFilteredScanDetailsReturnsOnlyConsideredScanDetails_untrustedAllowed() {
        String[] ssids = {"\"test1\"", "\"test2\"", "\"test3\"", "\"test4\""};
        String[] bssids = {"6c:f3:7f:ae:8c:f3", "6c:f3:7f:ae:8c:f4", "de:ad:ba:b1:e5:55",
                "c0:ff:ee:ee:e3:ee"};
        int[] frequencies = {2437, 5180, 5180, 2437};
        String[] caps = {"[WPA2-EAP-CCMP][ESS]", "[WPA2-EAP-CCMP][ESS]", "[WPA2-EAP-CCMP][ESS]",
                "[WPA2-EAP-CCMP][ESS]"};
        int[] levels = {-60, -86, -50, -62};
        int[] security = {SECURITY_PSK, SECURITY_PSK, SECURITY_PSK, SECURITY_PSK};
        boolean[] meteredHints = {false, false, false, true};
        Integer[] scores = {null, null, null, 120};

        //Create all 4 scanDetails
        List<ScanDetail> scanDetails = getScanDetails(ssids, bssids, frequencies, caps, levels);

        //Setup NetworkScoreCache for detecting ephemeral networks ("test4")
        configureScoreCache(scanDetails, scores, meteredHints);
        WifiConfiguration unTrustedNetworkCandidate = mock(WifiConfiguration.class);
        unTrustedNetworkCandidate.SSID = null;
        unTrustedNetworkCandidate.networkId = WifiConfiguration.INVALID_NETWORK_ID;
        ScanResult untrustedScanResult = scanDetails.get(3).getScanResult();
        when(mWifiConfigManager
                .wifiConfigurationFromScanResult(untrustedScanResult))
                .thenReturn(unTrustedNetworkCandidate);
        WifiConfiguration.NetworkSelectionStatus selectionStatus =
                        mock(WifiConfiguration.NetworkSelectionStatus.class);
        when(unTrustedNetworkCandidate.getNetworkSelectionStatus()).thenReturn(selectionStatus);

        //Set up associated configs for test1 & test2
        WifiConfiguration[] savedConfigs = generateWifiConfigurations(
                Arrays.copyOfRange(ssids, 0, 2), Arrays.copyOfRange(security, 0, 2));
        prepareConfigStore(savedConfigs);
        List<ScanDetail> savedScanDetails = new ArrayList<ScanDetail>(scanDetails.subList(0, 2));
        final List<WifiConfiguration> savedNetwork = Arrays.asList(savedConfigs);
        when(mWifiConfigManager.getSavedNetworks()).thenReturn(savedNetwork);
        scanResultLinkConfiguration(savedConfigs, savedScanDetails);

        //Force mock ConfigManager to return null (and not an empty list) for "test3" & "test4"
        when(mWifiConfigManager.updateSavedNetworkWithNewScanDetail(eq(scanDetails.get(2)),
                anyBoolean())).thenReturn(null);
        when(mWifiConfigManager.updateSavedNetworkWithNewScanDetail(eq(scanDetails.get(3)),
                anyBoolean())).thenReturn(null);

        ScanResult chosenScanResult = scanDetails.get(0).getScanResult();

        WifiConfiguration candidate = mWifiQualifiedNetworkSelector.selectQualifiedNetwork(
                false /* forceSelectNetwork */,
                true /* isUntrustedConnectionsAllowed */,
                scanDetails,
                false, /* isLinkDebouncing */
                false, /* isConnected */
                true, /* isDisconnected */
                false /* isSupplicantTransient */);

        verifySelectedResult(chosenScanResult, candidate);
        //Verify two scanDetails returned in the filteredScanDetails
        assertEquals(2, mWifiQualifiedNetworkSelector.getFilteredScanDetails().size());
        assertEquals(mWifiQualifiedNetworkSelector.getFilteredScanDetails().get(0).first.toString(),
                scanDetails.get(0).toString());
        assertEquals(mWifiQualifiedNetworkSelector.getFilteredScanDetails().get(1).first.toString(),
                scanDetails.get(3).toString());
    }


    /**
     * Case #35    Test Filtering of potential candidate scanDetails (Untrusted disallowed)
     *
     * In this test. we simulate following scenario
     * WifiStateMachine is under disconnected state
     * test1 is @ 2GHz with RSSI -60
     * test2 is @ 5Ghz with RSSI -86, (below minimum threshold)
     * test3 is @ 5Ghz with RSSI -50, however it has no associated saved config
     * test4 is @ 2Ghz with RSSI -62, no associated config, but is Ephemeral
     *
     * Expected behavior: test1 is chosen due to 5GHz signal is too weak (5GHz bonus can not
     * compensate).
     * test1 & test4's scanDetails are returned by 'getFilteredScanDetail()'
     */
    @Test
    public void testGetFilteredScanDetailsReturnsOnlyConsideredScanDetails_untrustedDisallowed() {
        String[] ssids = {"\"test1\"", "\"test2\"", "\"test3\"", "\"test4\""};
        String[] bssids = {"6c:f3:7f:ae:8c:f3", "6c:f3:7f:ae:8c:f4", "de:ad:ba:b1:e5:55",
                "c0:ff:ee:ee:e3:ee"};
        int[] frequencies = {2437, 5180, 5180, 2437};
        String[] caps = {"[WPA2-EAP-CCMP][ESS]", "[WPA2-EAP-CCMP][ESS]", "[WPA2-EAP-CCMP][ESS]",
                "[WPA2-EAP-CCMP][ESS]"};
        int[] levels = {-60, -86, -50, -62};
        int[] security = {SECURITY_PSK, SECURITY_PSK, SECURITY_PSK, SECURITY_PSK};
        boolean[] meteredHints = {false, false, false, true};
        Integer[] scores = {null, null, null, 120};

        //Create all 4 scanDetails
        List<ScanDetail> scanDetails = getScanDetails(ssids, bssids, frequencies, caps, levels);

        //Setup NetworkScoreCache for detecting ephemeral networks ("test4")
        configureScoreCache(scanDetails, scores, meteredHints);
        WifiConfiguration unTrustedNetworkCandidate = mock(WifiConfiguration.class);
        unTrustedNetworkCandidate.SSID = null;
        unTrustedNetworkCandidate.networkId = WifiConfiguration.INVALID_NETWORK_ID;
        ScanResult untrustedScanResult = scanDetails.get(3).getScanResult();
        when(mWifiConfigManager
                .wifiConfigurationFromScanResult(untrustedScanResult))
                .thenReturn(unTrustedNetworkCandidate);
        WifiConfiguration.NetworkSelectionStatus selectionStatus =
                        mock(WifiConfiguration.NetworkSelectionStatus.class);
        when(unTrustedNetworkCandidate.getNetworkSelectionStatus()).thenReturn(selectionStatus);

        //Set up associated configs for test1 & test2
        WifiConfiguration[] savedConfigs = generateWifiConfigurations(
                Arrays.copyOfRange(ssids, 0, 2), Arrays.copyOfRange(security, 0, 2));
        prepareConfigStore(savedConfigs);
        List<ScanDetail> savedScanDetails = new ArrayList<ScanDetail>(scanDetails.subList(0, 2));
        final List<WifiConfiguration> savedNetwork = Arrays.asList(savedConfigs);
        when(mWifiConfigManager.getSavedNetworks()).thenReturn(savedNetwork);
        scanResultLinkConfiguration(savedConfigs, savedScanDetails);

        //Force mock ConfigManager to return null (and not an empty list) for "test3" & "test4"
        when(mWifiConfigManager.updateSavedNetworkWithNewScanDetail(eq(scanDetails.get(2)),
                anyBoolean())).thenReturn(null);
        when(mWifiConfigManager.updateSavedNetworkWithNewScanDetail(eq(scanDetails.get(3)),
                anyBoolean())).thenReturn(null);

        ScanResult chosenScanResult = scanDetails.get(0).getScanResult();

        WifiConfiguration candidate = mWifiQualifiedNetworkSelector.selectQualifiedNetwork(
                false /* forceSelectNetwork */,
                false /* isUntrustedConnectionsAllowed */,
                scanDetails,
                false, /* isLinkDebouncing */
                false, /* isConnected */
                true, /* isDisconnected */
                false /* isSupplicantTransient */);

        verifySelectedResult(chosenScanResult, candidate);
        //Verify two scanDetails returned in the filteredScanDetails
        assertEquals(1, mWifiQualifiedNetworkSelector.getFilteredScanDetails().size());
        assertEquals(mWifiQualifiedNetworkSelector.getFilteredScanDetails().get(0).first.toString(),
                scanDetails.get(0).toString());
    }

    /**
     * Case #36  Ignore an ephemeral network if it was previously deleted.
     *
     * In this test. we simulate following scenario:
     * WifiStateMachine is not connected to any network.
     * selectQualifiedNetwork() is called with 2 scan results, test1 and test2.
     * test1 is an open network with a low score. Additionally it's a metered network.
     * test2 is an open network with a good score but was previously deleted.
     * isUntrustedConnectionsAllowed is set to true.
     *
     * expected result: return test1 with meteredHint set to True.
     */
    @Test
    public void selectQualifiedNetworkDoesNotChooseDeletedEphemeral() {
        String[] ssids = DEFAULT_SSIDS;
        String[] bssids = DEFAULT_BSSIDS;
        int[] frequencies = {5200, 5200};
        String[] caps = {"[WPA2-EAP-CCMP][ESS]", "[ESS]"};
        int[] levels = {-70, -70};
        Integer[] scores = {20, 120};
        boolean[] meteredHints = {true, false};

        List<ScanDetail> scanDetails = getScanDetails(ssids, bssids, frequencies, caps, levels);
        configureScoreCache(scanDetails, scores, meteredHints);

        // No saved networks.
        when(mWifiConfigManager.updateSavedNetworkWithNewScanDetail(any(ScanDetail.class),
                anyBoolean())).thenReturn(null);

        WifiConfiguration unTrustedNetworkCandidate = mock(WifiConfiguration.class);
        // Setup the config as an invalid candidate. This is done to workaround a Mockito issue.
        // Basically Mockito is unable to mock package-private methods in classes loaded from a
        // different Jar (like all of the framework code) which results in the actual saveNetwork()
        // method being invoked in this case. Because the config is invalid it quickly returns.
        unTrustedNetworkCandidate.SSID = null;
        unTrustedNetworkCandidate.networkId = WifiConfiguration.INVALID_NETWORK_ID;
        ScanResult untrustedScanResult = scanDetails.get(0).getScanResult();
        when(mWifiConfigManager
                .wifiConfigurationFromScanResult(untrustedScanResult))
                .thenReturn(unTrustedNetworkCandidate);

        // The second scan result is for an ephemeral network which was previously deleted
        when(mWifiConfigManager
                .wasEphemeralNetworkDeleted(scanDetails.get(0).getScanResult().SSID))
                .thenReturn(false);
        when(mWifiConfigManager
                .wasEphemeralNetworkDeleted(scanDetails.get(1).getScanResult().SSID))
                .thenReturn(true);

        WifiConfiguration.NetworkSelectionStatus selectionStatus =
                mock(WifiConfiguration.NetworkSelectionStatus.class);
        when(unTrustedNetworkCandidate.getNetworkSelectionStatus()).thenReturn(selectionStatus);
        when(selectionStatus.getCandidate()).thenReturn(untrustedScanResult);

        WifiConfiguration candidate = mWifiQualifiedNetworkSelector.selectQualifiedNetwork(
                false /* forceSelectNetwork */,
                true /* isUntrustedConnectionsAllowed */,
                scanDetails,
                false, /* isLinkDebouncing */
                false, /* isConnected */
                true, /* isDisconnected */
                false /* isSupplicantTransient */);
        verify(selectionStatus).setCandidate(untrustedScanResult);
        assertSame(candidate, unTrustedNetworkCandidate);
        assertEquals(meteredHints[0], candidate.meteredHint);
    }

    /**
     * Case #37  Choose the saved config that doesn't qualify for external scoring.
     *
     * In this test. we simulate following scenario:
     * WifiStateMachine is not connected to any network.
     * selectQualifiedNetwork() is called with 2 scan results, test1 and test2.
     * test1 is a saved network.
     * test2 is a saved network with useExternalScores set to true and a very high score.
     *
     * expected result: return test1 because saved networks that don't request external scoring
     *                  have a higher priority.
     */
    @Test
    public void selectQualifiedNetworkPrefersSavedWithoutExternalScores() {
        String[] ssids = DEFAULT_SSIDS;
        String[] bssids = DEFAULT_BSSIDS;
        int[] frequencies = {5200, 5200};
        String[] caps = {"[WPA2-EAP-CCMP][ESS]", "[ESS]"};
        int[] security = {SECURITY_PSK, SECURITY_PSK};
        int[] levels = {-70, -70};
        Integer[] scores = {null, 120};
        boolean[] meteredHints = {false, true};

        List<ScanDetail> scanDetails = getScanDetails(ssids, bssids, frequencies, caps, levels);
        configureScoreCache(scanDetails, scores, meteredHints);

        WifiConfiguration[] savedConfigs = generateWifiConfigurations(DEFAULT_SSIDS, security);
        savedConfigs[1].useExternalScores = true; // test2 is set to use external scores.
        prepareConfigStore(savedConfigs);
        when(mWifiConfigManager.getSavedNetworks()).thenReturn(Arrays.asList(savedConfigs));
        scanResultLinkConfiguration(savedConfigs, scanDetails);

        WifiConfiguration candidate = mWifiQualifiedNetworkSelector.selectQualifiedNetwork(
                false /* forceSelectNetwork */,
                false /* isUntrustedConnectionsAllowed */,
                scanDetails,
                false, /* isLinkDebouncing */
                false, /* isConnected */
                true, /* isDisconnected */
                false /* isSupplicantTransient */);
        verifySelectedResult(scanDetails.get(0).getScanResult(), candidate);
        assertSame(candidate, savedConfigs[0]);
    }

    /**
     * Case #38  Choose the saved config that does qualify for external scoring when other saved
     *           networks are not available.
     *
     * In this test. we simulate following scenario:
     * WifiStateMachine is not connected to any network.
     * selectQualifiedNetwork() is called with 2 scan results, test1 and test2.
     * test1 is a saved network with useExternalScores set to true and a very high score.
     * test2 is a saved network but not in range (not included in the scan results).
     *
     * expected result: return test1 because there are no better saved networks within range.
     */
    @Test
    public void selectQualifiedNetworkSelectsSavedWithExternalScores() {
        String[] ssids = {"\"test1\""};
        String[] bssids = {"6c:f3:7f:ae:8c:f3"};
        int[] frequencies = {5200};
        String[] caps = {"[WPA2-EAP-CCMP][ESS]"};
        int[] security = {SECURITY_PSK, SECURITY_PSK};
        int[] levels = {-70};
        Integer[] scores = {120};
        boolean[] meteredHints = {false};

        // Scan details only contains 1 ssid, test1.
        List<ScanDetail> scanDetails = getScanDetails(ssids, bssids, frequencies, caps, levels);
        configureScoreCache(scanDetails, scores, meteredHints);

        // The saved config contains 2 ssids, test1 & test2.
        WifiConfiguration[] savedConfigs = generateWifiConfigurations(DEFAULT_SSIDS, security);
        savedConfigs[0].useExternalScores = true; // test1 is set to use external scores.
        prepareConfigStore(savedConfigs);
        when(mWifiConfigManager.getSavedNetworks()).thenReturn(Arrays.asList(savedConfigs));
        scanResultLinkConfiguration(savedConfigs, scanDetails);

        WifiConfiguration candidate = mWifiQualifiedNetworkSelector.selectQualifiedNetwork(
                false /* forceSelectNetwork */,
                false /* isUntrustedConnectionsAllowed */,
                scanDetails,
                false, /* isLinkDebouncing */
                false, /* isConnected */
                true, /* isDisconnected */
                false /* isSupplicantTransient */);
        verifySelectedResult(scanDetails.get(0).getScanResult(), candidate);
        assertSame(candidate, savedConfigs[0]);
    }

    /**
     * Case #39  Choose the saved config that does qualify for external scoring over the
     *           untrusted network with the same score.
     *
     * In this test. we simulate following scenario:
     * WifiStateMachine is not connected to any network.
     * selectQualifiedNetwork() is called with 2 scan results, test1 and test2.
     * test1 is a saved network with useExternalScores set to true and the same score as test1.
     * test2 is NOT saved network but in range with a good external score.
     *
     * expected result: return test1 because the tie goes to the saved network.
     */
    @Test
    public void selectQualifiedNetworkPrefersSavedWithExternalScoresOverUntrusted() {
        String[] ssids = DEFAULT_SSIDS;
        String[] bssids = DEFAULT_BSSIDS;
        int[] frequencies = {5200, 5200};
        String[] caps = {"[WPA2-EAP-CCMP][ESS]", "[ESS]"};
        int[] security = {SECURITY_PSK, SECURITY_PSK};
        int[] levels = {-70, -70};
        Integer[] scores = {120, 120};
        boolean[] meteredHints = {false, true};

        // Both networks are in the scan results.
        List<ScanDetail> scanDetails = getScanDetails(ssids, bssids, frequencies, caps, levels);
        configureScoreCache(scanDetails, scores, meteredHints);

        // Set up the associated configs only for test1
        WifiConfiguration[] savedConfigs = generateWifiConfigurations(
                Arrays.copyOfRange(ssids, 0, 1), Arrays.copyOfRange(security, 0, 1));
        savedConfigs[0].useExternalScores = true; // test1 is set to use external scores.
        prepareConfigStore(savedConfigs);
        when(mWifiConfigManager.getSavedNetworks()).thenReturn(Arrays.asList(savedConfigs));
        scanResultLinkConfiguration(savedConfigs, scanDetails);
        WifiConfiguration unTrustedNetworkCandidate = mock(WifiConfiguration.class);
        when(mWifiConfigManager
                .wifiConfigurationFromScanResult(scanDetails.get(1).getScanResult()))
                .thenReturn(unTrustedNetworkCandidate);

        WifiConfiguration candidate = mWifiQualifiedNetworkSelector.selectQualifiedNetwork(
                false /* forceSelectNetwork */,
                true /* isUntrustedConnectionsAllowed */,
                scanDetails,
                false, /* isLinkDebouncing */
                false, /* isConnected */
                true, /* isDisconnected */
                false /* isSupplicantTransient */);
        verifySelectedResult(scanDetails.get(0).getScanResult(), candidate);
        assertSame(candidate, savedConfigs[0]);
    }

    /**
     * Case #40  Choose the ephemeral config over the saved config that does qualify for external
     *           scoring because the untrusted network has a higher score.
     *
     * In this test. we simulate following scenario:
     * WifiStateMachine is not connected to any network.
     * selectQualifiedNetwork() is called with 2 scan results, test1 and test2.
     * test1 is a saved network with useExternalScores set to true and a low score.
     * test2 is NOT saved network but in range with a good external score.
     *
     * expected result: return test2 because it has a better score.
     */
    @Test
    public void selectQualifiedNetworkPrefersUntrustedOverScoredSaved() {
        String[] ssids = DEFAULT_SSIDS;
        String[] bssids = DEFAULT_BSSIDS;
        int[] frequencies = {5200, 5200};
        String[] caps = {"[WPA2-EAP-CCMP][ESS]", "[ESS]"};
        int[] security = {SECURITY_PSK, SECURITY_PSK};
        int[] levels = {-70, -70};
        Integer[] scores = {10, 120};
        boolean[] meteredHints = {false, true};

        // Both networks are in the scan results.
        List<ScanDetail> scanDetails = getScanDetails(ssids, bssids, frequencies, caps, levels);
        configureScoreCache(scanDetails, scores, meteredHints);

        // Set up the associated configs only for test1
        WifiConfiguration[] savedConfigs = generateWifiConfigurations(
                Arrays.copyOfRange(ssids, 0, 1), Arrays.copyOfRange(security, 0, 1));
        savedConfigs[0].useExternalScores = true; // test1 is set to use external scores.
        prepareConfigStore(savedConfigs);
        when(mWifiConfigManager.getSavedNetworks()).thenReturn(Arrays.asList(savedConfigs));
        scanResultLinkConfiguration(savedConfigs, scanDetails);
        WifiConfiguration unTrustedNetworkCandidate = mock(WifiConfiguration.class);
        unTrustedNetworkCandidate.SSID = null;
        unTrustedNetworkCandidate.networkId = WifiConfiguration.INVALID_NETWORK_ID;
        ScanResult untrustedScanResult = scanDetails.get(1).getScanResult();
        when(mWifiConfigManager
                .wifiConfigurationFromScanResult(untrustedScanResult))
                .thenReturn(unTrustedNetworkCandidate);
        WifiConfiguration.NetworkSelectionStatus selectionStatus =
                mock(WifiConfiguration.NetworkSelectionStatus.class);
        when(unTrustedNetworkCandidate.getNetworkSelectionStatus()).thenReturn(selectionStatus);
        when(selectionStatus.getCandidate()).thenReturn(untrustedScanResult);

        WifiConfiguration candidate = mWifiQualifiedNetworkSelector.selectQualifiedNetwork(
                false /* forceSelectNetwork */,
                true /* isUntrustedConnectionsAllowed */,
                scanDetails,
                false, /* isLinkDebouncing */
                false, /* isConnected */
                true, /* isDisconnected */
                false /* isSupplicantTransient */);
        verify(selectionStatus).setCandidate(untrustedScanResult);
        assertSame(unTrustedNetworkCandidate, candidate);
    }

    /**
     * Case #41 Ensure the ExternalScoreEvaluator correctly selects the untrusted network.
     *
     * In this test. we simulate following scenario:
     * The ExternalScoreEvaluator is asked to evaluate 1 untrusted network and 1 saved network.
     * The untrusted network has the higher score.
     *
     * expected result: The untrusted network is determined to be the best network.
     */
    @Test
    public void externalScoreEvaluator_untrustedIsBest() {
        WifiQualifiedNetworkSelector.ExternalScoreEvaluator evaluator =
                new WifiQualifiedNetworkSelector.ExternalScoreEvaluator(mLocalLog, true);
        ScanResult untrustedScanResult = new ScanResult();
        int untrustedScore = 100;
        evaluator.evalUntrustedCandidate(untrustedScore, untrustedScanResult);

        ScanResult savedScanResult = new ScanResult();
        int savedScore = 50;
        WifiConfiguration savedConfig = new WifiConfiguration();
        evaluator.evalSavedCandidate(savedScore, savedConfig, savedScanResult);
        assertEquals(WifiQualifiedNetworkSelector.ExternalScoreEvaluator
                .BestCandidateType.UNTRUSTED_NETWORK, evaluator.getBestCandidateType());
        assertEquals(untrustedScore, evaluator.getHighScore());
        assertSame(untrustedScanResult, evaluator.getScanResultCandidate());
    }

    /**
     * Case #42 Ensure the ExternalScoreEvaluator correctly selects the saved network.
     *
     * In this test. we simulate following scenario:
     * The ExternalScoreEvaluator is asked to evaluate 1 untrusted network and 1 saved network.
     * The saved network has the higher score.
     *
     * expected result: The saved network is determined to be the best network.
     */
    @Test
    public void externalScoreEvaluator_savedIsBest() {
        WifiQualifiedNetworkSelector.ExternalScoreEvaluator evaluator =
                new WifiQualifiedNetworkSelector.ExternalScoreEvaluator(mLocalLog, true);
        ScanResult untrustedScanResult = new ScanResult();
        int untrustedScore = 50;
        evaluator.evalUntrustedCandidate(untrustedScore, untrustedScanResult);

        ScanResult savedScanResult = new ScanResult();
        int savedScore = 100;
        WifiConfiguration savedConfig = new WifiConfiguration();
        evaluator.evalSavedCandidate(savedScore, savedConfig, savedScanResult);
        assertEquals(WifiQualifiedNetworkSelector.ExternalScoreEvaluator
                .BestCandidateType.SAVED_NETWORK, evaluator.getBestCandidateType());
        assertEquals(savedScore, evaluator.getHighScore());
        assertSame(savedScanResult, evaluator.getScanResultCandidate());
    }

    /**
     * Case #43 Ensure the ExternalScoreEvaluator correctly selects the saved network if a
     *          tie occurs.
     *
     * In this test. we simulate following scenario:
     * The ExternalScoreEvaluator is asked to evaluate 1 untrusted network and 1 saved network.
     * Both networks have the same score.
     *
     * expected result: The saved network is determined to be the best network.
     */
    @Test
    public void externalScoreEvaluator_tieScores() {
        WifiQualifiedNetworkSelector.ExternalScoreEvaluator evaluator =
                new WifiQualifiedNetworkSelector.ExternalScoreEvaluator(mLocalLog, true);
        ScanResult untrustedScanResult = new ScanResult();
        int untrustedScore = 100;
        evaluator.evalUntrustedCandidate(untrustedScore, untrustedScanResult);

        ScanResult savedScanResult = new ScanResult();
        int savedScore = 100;
        WifiConfiguration savedConfig = new WifiConfiguration();
        evaluator.evalSavedCandidate(savedScore, savedConfig, savedScanResult);
        assertEquals(WifiQualifiedNetworkSelector.ExternalScoreEvaluator
                .BestCandidateType.SAVED_NETWORK, evaluator.getBestCandidateType());
        assertEquals(savedScore, evaluator.getHighScore());
        assertSame(savedScanResult, evaluator.getScanResultCandidate());
    }

    /**
     * Case #44 Ensure the ExternalScoreEvaluator correctly selects the saved network out of
     *          multiple options.
     *
     * In this test. we simulate following scenario:
     * The ExternalScoreEvaluator is asked to evaluate 2 untrusted networks and 2 saved networks.
     * The high scores are equal and the low scores differ.
     *
     * expected result: The saved network is determined to be the best network.
     */
    @Test
    public void externalScoreEvaluator_multipleScores() {
        WifiQualifiedNetworkSelector.ExternalScoreEvaluator evaluator =
                new WifiQualifiedNetworkSelector.ExternalScoreEvaluator(mLocalLog, true);
        ScanResult untrustedScanResult = new ScanResult();
        int untrustedScore = 100;
        evaluator.evalUntrustedCandidate(untrustedScore, untrustedScanResult);
        evaluator.evalUntrustedCandidate(80, new ScanResult());

        ScanResult savedScanResult = new ScanResult();
        int savedScore = 100;
        WifiConfiguration savedConfig = new WifiConfiguration();
        evaluator.evalSavedCandidate(savedScore, savedConfig, savedScanResult);
        evaluator.evalSavedCandidate(90, new WifiConfiguration(), new ScanResult());
        assertEquals(WifiQualifiedNetworkSelector.ExternalScoreEvaluator
                .BestCandidateType.SAVED_NETWORK, evaluator.getBestCandidateType());
        assertEquals(savedScore, evaluator.getHighScore());
        assertSame(savedScanResult, evaluator.getScanResultCandidate());
    }

    /**
     * Case #45 Ensure the ExternalScoreEvaluator correctly handles NULL score inputs.
     *
     * In this test we simulate following scenario:
     * The ExternalScoreEvaluator is asked to evaluate both types of candidates with NULL scores.
     *
     * expected result: No crashes. The best candidate type is returned as NONE.
     */
    @Test
    public void externalScoreEvaluator_nullScores() {
        WifiQualifiedNetworkSelector.ExternalScoreEvaluator evaluator =
                new WifiQualifiedNetworkSelector.ExternalScoreEvaluator(mLocalLog, true);
        evaluator.evalUntrustedCandidate(null, new ScanResult());
        assertEquals(WifiQualifiedNetworkSelector.ExternalScoreEvaluator
                .BestCandidateType.NONE, evaluator.getBestCandidateType());
        evaluator.evalSavedCandidate(null, new WifiConfiguration(), new ScanResult());
        assertEquals(WifiQualifiedNetworkSelector.ExternalScoreEvaluator
                .BestCandidateType.NONE, evaluator.getBestCandidateType());
    }

    /**
     * Case #46   Choose 2.4GHz BSSID with stronger RSSI value over
     *            5GHz BSSID with weaker RSSI value
     *
     * In this test. we simulate following scenario:
     * Two APs are found in scan results
     * BSSID1 is @ 5GHz with RSSI -82
     * BSSID2 is @ 2Ghz with RSSI -72
     * These two BSSIDs get exactly the same QNS score
     *
     * expect BSSID2 to be chosen as it has stronger RSSI value
     */
    @Test
    public void chooseStrongerRssiOver5GHz() {
        String[] ssids = {"\"test1\"", "\"test1\""};
        String[] bssids = {"6c:f3:7f:ae:8c:f3", "6c:f3:7f:ae:8c:f4"};
        int[] frequencies = {5220, 2437};
        String[] caps = {"[ESS]", "[ESS]"};
        int[] levels = {-82, -72};
        int[] security = {SECURITY_NONE, SECURITY_NONE};

        List<ScanDetail> scanDetails = getScanDetails(ssids, bssids, frequencies, caps, levels);
        WifiConfiguration[] savedConfigs = generateWifiConfigurations(ssids, security);
        prepareConfigStore(savedConfigs);

        final List<WifiConfiguration> savedNetwork = Arrays.asList(savedConfigs);
        when(mWifiConfigManager.getSavedNetworks()).thenReturn(savedNetwork);
        scanResultLinkConfiguration(savedConfigs, scanDetails);

        ScanResult chosenScanResult = scanDetails.get(1).getScanResult();

        WifiConfiguration candidate = mWifiQualifiedNetworkSelector.selectQualifiedNetwork(false,
                false, scanDetails, false, false, true, false);

        verifySelectedResult(chosenScanResult, candidate);
    }

    /**
     * Case #47   Choose the currently connected BSSID after a firmware initiated roaming.
     *
     * In this test. we simulate following scenario:
     * Two APs are found in scan results
     * BSSID1 is @ 2.4GHz with RSSI -78
     * BSSID2 is @ 2.4Ghz with RSSI -77
     * BSSID2 is chosen because of stronger RSSI. Then firmware initiates
     * a roaming to BSSID1. QNS now selects BSSID1 because of the bonus for currently
     * connected network even if BSSID 2 has slightly stronger signal strengh.
     *
     * expect BSSID2 to be chosen after firmware roaming
     */
    @Test
    public void chooseCurrentlyConnectedBssid() {
        String[] ssids = {"\"test1\"", "\"test1\""};
        String[] bssids = {"6c:f3:7f:ae:8c:f3", "6c:f3:7f:ae:8c:f4"};
        int[] frequencies = {2437, 2437};
        String[] caps = {"[ESS]", "[ESS]"};
        int[] levels = {-78, -77};
        int[] security = {SECURITY_NONE, SECURITY_NONE};

        List<ScanDetail> scanDetails = getScanDetails(ssids, bssids, frequencies, caps, levels);
        WifiConfiguration[] savedConfigs = generateWifiConfigurations(ssids, security);
        prepareConfigStore(savedConfigs);

        final List<WifiConfiguration> savedNetwork = Arrays.asList(savedConfigs);
        when(mWifiConfigManager.getSavedNetworks()).thenReturn(savedNetwork);
        scanResultLinkConfiguration(savedConfigs, scanDetails);

        // Choose BSSID2 as it has stronger RSSI
        ScanResult chosenScanResult = scanDetails.get(1).getScanResult();
        WifiConfiguration candidate = mWifiQualifiedNetworkSelector.selectQualifiedNetwork(false,
                false, scanDetails, false, false, true, false);
        verifySelectedResult(chosenScanResult, candidate);
        when(mWifiInfo.getBSSID()).thenReturn(bssids[1]);
        when(mWifiConfigManager.getEnableAutoJoinWhenAssociated()).thenReturn(true);

        // Choose BSSID2 as it has stronger RSSI and it is the currently connected BSSID
        chosenScanResult = scanDetails.get(1).getScanResult();
        candidate = mWifiQualifiedNetworkSelector.selectQualifiedNetwork(true,
                false, scanDetails, false, true, false, false);
        verifySelectedResult(chosenScanResult, candidate);

        // Pretend firmware roamed the device to BSSID1
        when(mWifiInfo.getBSSID()).thenReturn(bssids[0]);

        // Choose BSSID1 as it is the currently connected BSSID even if BSSID2 has slightly
        // higher RSSI value.
        chosenScanResult = scanDetails.get(0).getScanResult();
        candidate = mWifiQualifiedNetworkSelector.selectQualifiedNetwork(true,
                false, scanDetails, false, true, false, false);
        verifySelectedResult(chosenScanResult, candidate);
    }
}