summaryrefslogtreecommitdiffstats
path: root/tests/wifitests/src/com/android/server/wifi/scanner/WifiScanningServiceTest.java
blob: e7962f5080c2746c179437a99fa2737eeb1a0ee4 (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
 /*
 * Copyright (C) 2016 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.scanner;

import static com.android.server.wifi.ScanTestUtil.*;

import static org.junit.Assert.*;
import static org.mockito.Mockito.*;

import android.app.test.MockAnswerUtil.AnswerWithArguments;
import android.app.test.TestAlarmManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiScanner;
import android.os.Binder;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.RemoteException;
import android.os.UserHandle;
import android.os.WorkSource;
import android.os.test.TestLooper;
import android.test.suitebuilder.annotation.SmallTest;
import android.util.Pair;

import com.android.internal.app.IBatteryStats;
import com.android.internal.util.AsyncChannel;
import com.android.internal.util.Protocol;
import com.android.internal.util.test.BidirectionalAsyncChannel;
import com.android.server.wifi.Clock;
import com.android.server.wifi.FakeWifiLog;
import com.android.server.wifi.FrameworkFacade;
import com.android.server.wifi.ScanResults;
import com.android.server.wifi.TestUtil;
import com.android.server.wifi.WifiInjector;
import com.android.server.wifi.WifiMetrics;
import com.android.server.wifi.WifiNative;
import com.android.server.wifi.nano.WifiMetricsProto;
import com.android.server.wifi.util.WifiAsyncChannel;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.InOrder;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import org.mockito.Spy;
import org.mockito.compat.CapturingMatcher;

import java.io.FileDescriptor;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.regex.Pattern;

/**
 * Unit tests for {@link com.android.server.wifi.scanner.WifiScanningServiceImpl}.
 */
@SmallTest
public class WifiScanningServiceTest {
    public static final String TAG = "WifiScanningServiceTest";

    private static final int TEST_MAX_SCAN_BUCKETS_IN_CAPABILITIES = 8;

    @Mock Context mContext;
    TestAlarmManager mAlarmManager;
    @Mock WifiScannerImpl mWifiScannerImpl;
    @Mock WifiScannerImpl.WifiScannerImplFactory mWifiScannerImplFactory;
    @Mock IBatteryStats mBatteryStats;
    @Mock WifiInjector mWifiInjector;
    @Mock FrameworkFacade mFrameworkFacade;
    @Mock Clock mClock;
    @Spy FakeWifiLog mLog;
    WifiMetrics mWifiMetrics;
    TestLooper mLooper;
    WifiScanningServiceImpl mWifiScanningServiceImpl;


    @Before
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);

        mAlarmManager = new TestAlarmManager();
        when(mContext.getSystemService(Context.ALARM_SERVICE))
                .thenReturn(mAlarmManager.getAlarmManager());
        mWifiMetrics = new WifiMetrics(mClock);

        ChannelHelper channelHelper = new PresetKnownBandsChannelHelper(
                new int[]{2400, 2450},
                new int[]{5150, 5175},
                new int[]{5600, 5650, 5660});

        mLooper = new TestLooper();
        when(mWifiScannerImplFactory
                .create(any(), any(), any()))
                .thenReturn(mWifiScannerImpl);
        when(mWifiScannerImpl.getChannelHelper()).thenReturn(channelHelper);
        when(mWifiInjector.getWifiMetrics()).thenReturn(mWifiMetrics);
        when(mWifiInjector.makeLog(anyString())).thenReturn(mLog);
        WifiAsyncChannel mWifiAsyncChannel = new WifiAsyncChannel("ScanningServiceTest");
        mWifiAsyncChannel.setWifiLog(mLog);
        when(mFrameworkFacade.makeWifiAsyncChannel(anyString())).thenReturn(mWifiAsyncChannel);
        when(mWifiInjector.getFrameworkFacade()).thenReturn(mFrameworkFacade);
        mWifiScanningServiceImpl = new WifiScanningServiceImpl(mContext, mLooper.getLooper(),
                mWifiScannerImplFactory, mBatteryStats, mWifiInjector);
    }

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

    /**
     * Internal BroadcastReceiver that WifiScanningServiceImpl uses to listen for broadcasts
     * this is initialized by calling startServiceAndLoadDriver
     */
    BroadcastReceiver mBroadcastReceiver;

    private WifiScanner.ScanSettings generateValidScanSettings() {
        return createRequest(WifiScanner.WIFI_BAND_BOTH, 30000, 0, 20,
                WifiScanner.REPORT_EVENT_AFTER_EACH_SCAN);
    }

    private BidirectionalAsyncChannel connectChannel(Handler handler) {
        BidirectionalAsyncChannel controlChannel = new BidirectionalAsyncChannel();
        controlChannel.connect(mLooper.getLooper(), mWifiScanningServiceImpl.getMessenger(),
                handler);
        mLooper.dispatchAll();
        controlChannel.assertConnected();
        return controlChannel;
    }

    private static Message verifyHandleMessageAndGetMessage(InOrder order, Handler handler) {
        ArgumentCaptor<Message> messageCaptor = ArgumentCaptor.forClass(Message.class);
        order.verify(handler).handleMessage(messageCaptor.capture());
        return messageCaptor.getValue();
    }

    private static Message verifyHandleMessageAndGetMessage(InOrder order, Handler handler,
            final int what) {
        CapturingMatcher<Message> messageMatcher = new CapturingMatcher<Message>() {
            public boolean matchesObject(Object argument) {
                Message message = (Message) argument;
                return message.what == what;
            }
        };
        order.verify(handler).handleMessage(argThat(messageMatcher));
        return messageMatcher.getLastValue();
    }

    private static void verifyScanResultsReceived(InOrder order, Handler handler, int listenerId,
            WifiScanner.ScanData... expected) {
        Message scanResultMessage = verifyHandleMessageAndGetMessage(order, handler,
                WifiScanner.CMD_SCAN_RESULT);
        assertScanResultsMessage(listenerId, expected, scanResultMessage);
    }

    private static void assertScanResultsMessage(int listenerId, WifiScanner.ScanData[] expected,
            Message scanResultMessage) {
        assertEquals("what", WifiScanner.CMD_SCAN_RESULT, scanResultMessage.what);
        assertEquals("listenerId", listenerId, scanResultMessage.arg2);
        assertScanDatasEquals(expected,
                ((WifiScanner.ParcelableScanData) scanResultMessage.obj).getResults());
    }

    private static void verifySingleScanCompletedReceived(InOrder order, Handler handler,
            int listenerId) {
        Message completedMessage = verifyHandleMessageAndGetMessage(order, handler,
                WifiScanner.CMD_SINGLE_SCAN_COMPLETED);
        assertSingleScanCompletedMessage(listenerId, completedMessage);
    }

    private static void assertSingleScanCompletedMessage(int listenerId, Message completedMessage) {
        assertEquals("what", WifiScanner.CMD_SINGLE_SCAN_COMPLETED, completedMessage.what);
        assertEquals("listenerId", listenerId, completedMessage.arg2);
    }

    private static void sendBackgroundScanRequest(BidirectionalAsyncChannel controlChannel,
            int scanRequestId, WifiScanner.ScanSettings settings, WorkSource workSource) {
        Bundle scanParams = new Bundle();
        scanParams.putParcelable(WifiScanner.SCAN_PARAMS_SCAN_SETTINGS_KEY, settings);
        scanParams.putParcelable(WifiScanner.SCAN_PARAMS_WORK_SOURCE_KEY, workSource);
        controlChannel.sendMessage(Message.obtain(null, WifiScanner.CMD_START_BACKGROUND_SCAN, 0,
                        scanRequestId, scanParams));
    }

    private static void sendSingleScanRequest(BidirectionalAsyncChannel controlChannel,
            int scanRequestId, WifiScanner.ScanSettings settings, WorkSource workSource) {
        Bundle scanParams = new Bundle();
        scanParams.putParcelable(WifiScanner.SCAN_PARAMS_SCAN_SETTINGS_KEY, settings);
        scanParams.putParcelable(WifiScanner.SCAN_PARAMS_WORK_SOURCE_KEY, workSource);
        controlChannel.sendMessage(Message.obtain(null, WifiScanner.CMD_START_SINGLE_SCAN, 0,
                        scanRequestId, scanParams));
    }

    private static void registerScanListener(BidirectionalAsyncChannel controlChannel,
            int listenerRequestId) {
        controlChannel.sendMessage(Message.obtain(null, WifiScanner.CMD_REGISTER_SCAN_LISTENER, 0,
                        listenerRequestId, null));
    }

    private static void deregisterScanListener(BidirectionalAsyncChannel controlChannel,
            int listenerRequestId) {
        controlChannel.sendMessage(Message.obtain(null, WifiScanner.CMD_DEREGISTER_SCAN_LISTENER, 0,
                        listenerRequestId, null));
    }

    private static void verifySuccessfulResponse(InOrder order, Handler handler, int arg2) {
        Message response = verifyHandleMessageAndGetMessage(order, handler);
        assertSuccessfulResponse(arg2, response);
    }

    private static void assertSuccessfulResponse(int arg2, Message response) {
        if (response.what == WifiScanner.CMD_OP_FAILED) {
            WifiScanner.OperationResult result = (WifiScanner.OperationResult) response.obj;
            fail("response indicates failure, reason=" + result.reason
                    + ", description=" + result.description);
        } else {
            assertEquals("response.what", WifiScanner.CMD_OP_SUCCEEDED, response.what);
            assertEquals("response.arg2", arg2, response.arg2);
        }
    }

    /**
     * If multiple results are expected for a single hardware scan then the order that they are
     * dispatched is dependant on the order which they are iterated through internally. This
     * function validates that the order is either one way or the other. A scan listener can
     * optionally be provided as well and will be checked after the after the single scan requests.
     */
    private static void verifyMultipleSingleScanResults(InOrder handlerOrder, Handler handler,
            int requestId1, ScanResults results1, int requestId2, ScanResults results2,
            int listenerRequestId, ScanResults listenerResults) {
        ArgumentCaptor<Message> messageCaptor = ArgumentCaptor.forClass(Message.class);
        handlerOrder.verify(handler, times(listenerResults == null ? 4 : 5))
                .handleMessage(messageCaptor.capture());
        int firstListenerId = messageCaptor.getAllValues().get(0).arg2;
        assertTrue(firstListenerId + " was neither " + requestId2 + " nor " + requestId1,
                firstListenerId == requestId2 || firstListenerId == requestId1);
        if (firstListenerId == requestId2) {
            assertScanResultsMessage(requestId2,
                    new WifiScanner.ScanData[] {results2.getScanData()},
                    messageCaptor.getAllValues().get(0));
            assertSingleScanCompletedMessage(requestId2, messageCaptor.getAllValues().get(1));
            assertScanResultsMessage(requestId1,
                    new WifiScanner.ScanData[] {results1.getScanData()},
                    messageCaptor.getAllValues().get(2));
            assertSingleScanCompletedMessage(requestId1, messageCaptor.getAllValues().get(3));
            if (listenerResults != null) {
                assertScanResultsMessage(listenerRequestId,
                        new WifiScanner.ScanData[] {listenerResults.getScanData()},
                        messageCaptor.getAllValues().get(4));
            }
        } else {
            assertScanResultsMessage(requestId1,
                    new WifiScanner.ScanData[] {results1.getScanData()},
                    messageCaptor.getAllValues().get(0));
            assertSingleScanCompletedMessage(requestId1, messageCaptor.getAllValues().get(1));
            assertScanResultsMessage(requestId2,
                    new WifiScanner.ScanData[] {results2.getScanData()},
                    messageCaptor.getAllValues().get(2));
            assertSingleScanCompletedMessage(requestId2, messageCaptor.getAllValues().get(3));
            if (listenerResults != null) {
                assertScanResultsMessage(listenerRequestId,
                        new WifiScanner.ScanData[] {listenerResults.getScanData()},
                        messageCaptor.getAllValues().get(4));
            }
        }
    }

    private static void verifyMultipleSingleScanResults(InOrder handlerOrder, Handler handler,
            int requestId1, ScanResults results1, int requestId2, ScanResults results2) {
        verifyMultipleSingleScanResults(handlerOrder, handler, requestId1, results1, requestId2,
                results2, -1, null);
    }

    private static void verifyFailedResponse(InOrder order, Handler handler, int arg2,
            int expectedErrorReason, String expectedErrorDescription) {
        Message response = verifyHandleMessageAndGetMessage(order, handler);
        assertFailedResponse(arg2, expectedErrorReason, expectedErrorDescription, response);
    }

    private static void assertFailedResponse(int arg2, int expectedErrorReason,
            String expectedErrorDescription, Message response) {
        if (response.what == WifiScanner.CMD_OP_SUCCEEDED) {
            fail("response indicates success");
        } else {
            assertEquals("response.what", WifiScanner.CMD_OP_FAILED, response.what);
            assertEquals("response.arg2", arg2, response.arg2);
            WifiScanner.OperationResult result = (WifiScanner.OperationResult) response.obj;
            assertEquals("response.obj.reason",
                    expectedErrorReason, result.reason);
            assertEquals("response.obj.description",
                    expectedErrorDescription, result.description);
        }
    }

    private WifiNative.ScanEventHandler verifyStartSingleScan(InOrder order,
            WifiNative.ScanSettings expected) {
        ArgumentCaptor<WifiNative.ScanSettings> scanSettingsCaptor =
                ArgumentCaptor.forClass(WifiNative.ScanSettings.class);
        ArgumentCaptor<WifiNative.ScanEventHandler> scanEventHandlerCaptor =
                ArgumentCaptor.forClass(WifiNative.ScanEventHandler.class);
        order.verify(mWifiScannerImpl).startSingleScan(scanSettingsCaptor.capture(),
                scanEventHandlerCaptor.capture());
        assertNativeScanSettingsEquals(expected, scanSettingsCaptor.getValue());
        return scanEventHandlerCaptor.getValue();
    }

    private WifiNative.ScanEventHandler verifyStartBackgroundScan(InOrder order,
            WifiNative.ScanSettings expected) {
        ArgumentCaptor<WifiNative.ScanSettings> scanSettingsCaptor =
                ArgumentCaptor.forClass(WifiNative.ScanSettings.class);
        ArgumentCaptor<WifiNative.ScanEventHandler> scanEventHandlerCaptor =
                ArgumentCaptor.forClass(WifiNative.ScanEventHandler.class);
        order.verify(mWifiScannerImpl).startBatchedScan(scanSettingsCaptor.capture(),
                scanEventHandlerCaptor.capture());
        assertNativeScanSettingsEquals(expected, scanSettingsCaptor.getValue());
        return scanEventHandlerCaptor.getValue();
    }

    private static final int MAX_AP_PER_SCAN = 16;
    private void startServiceAndLoadDriver() {
        mWifiScanningServiceImpl.startService();
        setupAndLoadDriver(TEST_MAX_SCAN_BUCKETS_IN_CAPABILITIES);
    }

    private void setupAndLoadDriver(int max_scan_buckets) {
        when(mWifiScannerImpl.getScanCapabilities(any(WifiNative.ScanCapabilities.class)))
                .thenAnswer(new AnswerWithArguments() {
                        public boolean answer(WifiNative.ScanCapabilities capabilities) {
                            capabilities.max_scan_cache_size = Integer.MAX_VALUE;
                            capabilities.max_scan_buckets = max_scan_buckets;
                            capabilities.max_ap_cache_per_scan = MAX_AP_PER_SCAN;
                            capabilities.max_rssi_sample_size = 8;
                            capabilities.max_scan_reporting_threshold = 10;
                            capabilities.max_hotlist_bssids = 0;
                            capabilities.max_significant_wifi_change_aps = 0;
                            return true;
                        }
                    });
        ArgumentCaptor<BroadcastReceiver> broadcastReceiverCaptor =
                ArgumentCaptor.forClass(BroadcastReceiver.class);
        verify(mContext)
                .registerReceiver(broadcastReceiverCaptor.capture(), any(IntentFilter.class));
        mBroadcastReceiver = broadcastReceiverCaptor.getValue();
        TestUtil.sendWifiScanAvailable(broadcastReceiverCaptor.getValue(), mContext,
                WifiManager.WIFI_STATE_ENABLED);
        mLooper.dispatchAll();
    }

    private String dumpService() {
        StringWriter stringWriter = new StringWriter();
        mWifiScanningServiceImpl.dump(new FileDescriptor(), new PrintWriter(stringWriter),
                new String[0]);
        return stringWriter.toString();
    }

    private void assertDumpContainsRequestLog(String type, int id) {
        String serviceDump = dumpService();
        Pattern logLineRegex = Pattern.compile("^.+" + type
                + ": ClientInfo\\[uid=\\d+,android\\.os\\.Messenger@[a-f0-9]+\\],Id=" + id
                + ".*$", Pattern.MULTILINE);
        assertTrue("dump did not contain log with type=" + type + ", id=" + id +
                ": " + serviceDump + "\n",
                logLineRegex.matcher(serviceDump).find());
    }

    private void assertDumpContainsCallbackLog(String callback, int id, String extra) {
        String serviceDump = dumpService();
        String extraPattern = extra == null ? "" : "," + extra;
        Pattern logLineRegex = Pattern.compile("^.+" + callback
                + ": ClientInfo\\[uid=\\d+,android\\.os\\.Messenger@[a-f0-9]+\\],Id=" + id
                + extraPattern + "$", Pattern.MULTILINE);
        assertTrue("dump did not contain callback log with callback=" + callback + ", id=" + id +
                ", extra=" + extra + ": " + serviceDump + "\n",
                logLineRegex.matcher(serviceDump).find());
    }

    @Test
    public void construct() throws Exception {
        verifyNoMoreInteractions(mWifiScannerImpl, mWifiScannerImpl,
                mWifiScannerImplFactory, mBatteryStats);
        dumpService(); // make sure this succeeds
    }

    @Test
    public void startService() throws Exception {
        mWifiScanningServiceImpl.startService();
        mWifiScanningServiceImpl.setWifiHandlerLogForTest(mLog);
        verifyNoMoreInteractions(mWifiScannerImplFactory);

        Handler handler = mock(Handler.class);
        BidirectionalAsyncChannel controlChannel = connectChannel(handler);
        InOrder order = inOrder(handler);
        sendBackgroundScanRequest(controlChannel, 122, generateValidScanSettings(), null);
        mLooper.dispatchAll();
        verifyFailedResponse(order, handler, 122, WifiScanner.REASON_UNSPECIFIED, "not available");
    }

    @Test
    public void disconnectClientBeforeWifiEnabled() throws Exception {
        mWifiScanningServiceImpl.startService();
        mWifiScanningServiceImpl.setWifiHandlerLogForTest(mLog);
        BidirectionalAsyncChannel controlChannel = connectChannel(mock(Handler.class));
        mLooper.dispatchAll();

        controlChannel.disconnect();
        mLooper.dispatchAll();
    }

    @Test
    public void loadDriver() throws Exception {
        startServiceAndLoadDriver();
        mWifiScanningServiceImpl.setWifiHandlerLogForTest(mLog);
        verify(mWifiScannerImplFactory, times(1))
                .create(any(), any(), any());

        Handler handler = mock(Handler.class);
        BidirectionalAsyncChannel controlChannel = connectChannel(handler);
        InOrder order = inOrder(handler);
        when(mWifiScannerImpl.startBatchedScan(any(WifiNative.ScanSettings.class),
                        any(WifiNative.ScanEventHandler.class))).thenReturn(true);
        sendBackgroundScanRequest(controlChannel, 192, generateValidScanSettings(), null);
        mLooper.dispatchAll();
        verifySuccessfulResponse(order, handler, 192);
        assertDumpContainsRequestLog("addBackgroundScanRequest", 192);
    }

    @Test
    public void disconnectClientAfterStartingWifi() throws Exception {
        mWifiScanningServiceImpl.startService();
        mWifiScanningServiceImpl.setWifiHandlerLogForTest(mLog);
        BidirectionalAsyncChannel controlChannel = connectChannel(mock(Handler.class));
        mLooper.dispatchAll();

        setupAndLoadDriver(TEST_MAX_SCAN_BUCKETS_IN_CAPABILITIES);

        controlChannel.disconnect();
        mLooper.dispatchAll();
    }

    @Test
    public void connectAndDisconnectClientAfterStartingWifi() throws Exception {
        startServiceAndLoadDriver();
        mWifiScanningServiceImpl.setWifiHandlerLogForTest(mLog);

        BidirectionalAsyncChannel controlChannel = connectChannel(mock(Handler.class));
        mLooper.dispatchAll();
        controlChannel.disconnect();
        mLooper.dispatchAll();
    }

    @Test
    public void sendInvalidCommand() throws Exception {
        startServiceAndLoadDriver();
        mWifiScanningServiceImpl.setWifiHandlerLogForTest(mLog);

        Handler handler = mock(Handler.class);
        BidirectionalAsyncChannel controlChannel = connectChannel(handler);
        InOrder order = inOrder(handler, mWifiScannerImpl);
        controlChannel.sendMessage(Message.obtain(null, Protocol.BASE_WIFI_MANAGER));
        mLooper.dispatchAll();
        verifyFailedResponse(order, handler, 0, WifiScanner.REASON_INVALID_REQUEST,
                "Invalid request");
    }

    @Test
    public void rejectBackgroundScanRequestWhenHalReturnsInvalidCapabilities() throws Exception {
        mWifiScanningServiceImpl.startService();
        mWifiScanningServiceImpl.setWifiHandlerLogForTest(mLog);

        setupAndLoadDriver(0);

        Handler handler = mock(Handler.class);
        BidirectionalAsyncChannel controlChannel = connectChannel(handler);
        InOrder order = inOrder(handler);
        sendBackgroundScanRequest(controlChannel, 122, generateValidScanSettings(), null);
        mLooper.dispatchAll();
        verifyFailedResponse(order, handler, 122, WifiScanner.REASON_UNSPECIFIED, "not available");
    }

    private void doSuccessfulSingleScan(WifiScanner.ScanSettings requestSettings,
            WifiNative.ScanSettings nativeSettings, ScanResults results) throws RemoteException {
        int requestId = 12;
        WorkSource workSource = new WorkSource(2292);
        startServiceAndLoadDriver();
        mWifiScanningServiceImpl.setWifiHandlerLogForTest(mLog);

        Handler handler = mock(Handler.class);
        BidirectionalAsyncChannel controlChannel = connectChannel(handler);
        InOrder order = inOrder(handler, mWifiScannerImpl);

        when(mWifiScannerImpl.startSingleScan(any(WifiNative.ScanSettings.class),
                        any(WifiNative.ScanEventHandler.class))).thenReturn(true);

        sendSingleScanRequest(controlChannel, requestId, requestSettings, workSource);

        mLooper.dispatchAll();
        WifiNative.ScanEventHandler eventHandler = verifyStartSingleScan(order, nativeSettings);
        verifySuccessfulResponse(order, handler, requestId);
        verify(mBatteryStats).noteWifiScanStartedFromSource(eq(workSource));

        when(mWifiScannerImpl.getLatestSingleScanResults())
                .thenReturn(results.getRawScanData());
        eventHandler.onScanStatus(WifiNative.WIFI_SCAN_RESULTS_AVAILABLE);

        mLooper.dispatchAll();
        verifyScanResultsReceived(order, handler, requestId, results.getScanData());
        verifySingleScanCompletedReceived(order, handler, requestId);
        verify(mContext).sendBroadcastAsUser(any(Intent.class), eq(UserHandle.ALL));
        verifyNoMoreInteractions(handler);
        verify(mBatteryStats).noteWifiScanStoppedFromSource(eq(workSource));
        assertDumpContainsRequestLog("addSingleScanRequest", requestId);
        assertDumpContainsCallbackLog("singleScanResults", requestId,
                "results=" + results.getScanData().getResults().length);
    }

    /**
     * Do a single scan for a band and verify that it is successful.
     */
    @Test
    public void sendSingleScanBandRequest() throws Exception {
        WifiScanner.ScanSettings requestSettings = createRequest(WifiScanner.WIFI_BAND_BOTH_WITH_DFS,
                0, 0, 20, WifiScanner.REPORT_EVENT_AFTER_EACH_SCAN);
        doSuccessfulSingleScan(requestSettings, computeSingleScanNativeSettings(requestSettings),
                ScanResults.create(0, true, 2400, 5150, 5175));
    }

    /**
     * Do a single scan for a list of channels and verify that it is successful.
     */
    @Test
    public void sendSingleScanChannelsRequest() throws Exception {
        WifiScanner.ScanSettings requestSettings = createRequest(channelsToSpec(2400, 5150, 5175),
                0, 0, 20, WifiScanner.REPORT_EVENT_AFTER_EACH_SCAN);
        doSuccessfulSingleScan(requestSettings, computeSingleScanNativeSettings(requestSettings),
                ScanResults.create(0, 2400, 5150, 5175));
    }

    /**
     * Do a single scan for a list of all channels and verify that it is successful.
     */
    @Test
    public void sendSingleScanAllChannelsRequest() throws Exception {
        WifiScanner.ScanSettings requestSettings = createRequest(
                channelsToSpec(2400, 2450, 5150, 5175, 5600, 5650, 5660),
                0, 0, 20, WifiScanner.REPORT_EVENT_AFTER_EACH_SCAN);
        doSuccessfulSingleScan(requestSettings, computeSingleScanNativeSettings(requestSettings),
                ScanResults.create(0, true, 2400, 5150, 5175));
    }

    /**
     * Do a single scan with no results and verify that it is successful.
     */
    @Test
    public void sendSingleScanRequestWithNoResults() throws Exception {
        WifiScanner.ScanSettings requestSettings = createRequest(WifiScanner.WIFI_BAND_BOTH, 0,
                0, 20, WifiScanner.REPORT_EVENT_AFTER_EACH_SCAN);
        doSuccessfulSingleScan(requestSettings, computeSingleScanNativeSettings(requestSettings),
                ScanResults.create(0, new int[0]));
    }

    /**
     * Do a single scan with results that do not match the requested scan and verify that it is
     * still successful (and returns no results).
     */
    @Test
    public void sendSingleScanRequestWithBadRawResults() throws Exception {
        WifiScanner.ScanSettings requestSettings = createRequest(WifiScanner.WIFI_BAND_24_GHZ, 0,
                0, 20, WifiScanner.REPORT_EVENT_AFTER_EACH_SCAN);
        // Create a set of scan results that has results not matching the request settings, but is
        // limited to zero results for the expected results.
        ScanResults results = ScanResults.createOverflowing(0, 0,
                ScanResults.generateNativeResults(0, 5150, 5171));
        doSuccessfulSingleScan(requestSettings, computeSingleScanNativeSettings(requestSettings),
                results);
    }

    /**
     * Do a single scan, which the hardware fails to start, and verify that a failure response is
     * delivered.
     */
    @Test
    public void sendSingleScanRequestWhichFailsToStart() throws Exception {
        WifiScanner.ScanSettings requestSettings = createRequest(WifiScanner.WIFI_BAND_BOTH, 0,
                0, 20, WifiScanner.REPORT_EVENT_AFTER_EACH_SCAN);
        int requestId = 33;

        startServiceAndLoadDriver();
        mWifiScanningServiceImpl.setWifiHandlerLogForTest(mLog);

        Handler handler = mock(Handler.class);
        BidirectionalAsyncChannel controlChannel = connectChannel(handler);
        InOrder order = inOrder(handler, mWifiScannerImpl);

        // scan fails
        when(mWifiScannerImpl.startSingleScan(any(WifiNative.ScanSettings.class),
                        any(WifiNative.ScanEventHandler.class))).thenReturn(false);

        sendSingleScanRequest(controlChannel, requestId, requestSettings, null);

        mLooper.dispatchAll();
        // Scan is successfully queue, but then fails to execute
        ArgumentCaptor<Message> messageCaptor = ArgumentCaptor.forClass(Message.class);
        order.verify(handler, times(2)).handleMessage(messageCaptor.capture());
        assertSuccessfulResponse(requestId, messageCaptor.getAllValues().get(0));
        assertFailedResponse(requestId, WifiScanner.REASON_UNSPECIFIED,
                "Failed to start single scan", messageCaptor.getAllValues().get(1));
        verifyNoMoreInteractions(mBatteryStats);

        assertEquals(mWifiMetrics.getOneshotScanCount(), 1);
        assertEquals(mWifiMetrics.getScanReturnEntry(WifiMetricsProto.WifiLog.SCAN_UNKNOWN), 1);
        assertDumpContainsRequestLog("addSingleScanRequest", requestId);
    }

    /**
     * Do a single scan, which successfully starts, but fails partway through and verify that a
     * failure response is delivered.
     */
    @Test
    public void sendSingleScanRequestWhichFailsAfterStart() throws Exception {
        WifiScanner.ScanSettings requestSettings = createRequest(WifiScanner.WIFI_BAND_BOTH, 0,
                0, 20, WifiScanner.REPORT_EVENT_AFTER_EACH_SCAN);
        int requestId = 33;
        WorkSource workSource = new WorkSource(Binder.getCallingUid()); // don't explicitly set

        startServiceAndLoadDriver();
        mWifiScanningServiceImpl.setWifiHandlerLogForTest(mLog);

        Handler handler = mock(Handler.class);
        BidirectionalAsyncChannel controlChannel = connectChannel(handler);
        InOrder order = inOrder(handler, mWifiScannerImpl);

        // successful start
        when(mWifiScannerImpl.startSingleScan(any(WifiNative.ScanSettings.class),
                        any(WifiNative.ScanEventHandler.class))).thenReturn(true);

        sendSingleScanRequest(controlChannel, requestId, requestSettings, null);

        // Scan is successfully queue
        mLooper.dispatchAll();
        WifiNative.ScanEventHandler eventHandler =
                verifyStartSingleScan(order, computeSingleScanNativeSettings(requestSettings));
        verifySuccessfulResponse(order, handler, requestId);
        verify(mBatteryStats).noteWifiScanStartedFromSource(eq(workSource));

        // but then fails to execute
        eventHandler.onScanStatus(WifiNative.WIFI_SCAN_FAILED);
        mLooper.dispatchAll();
        verifyFailedResponse(order, handler, requestId,
                WifiScanner.REASON_UNSPECIFIED, "Scan failed");
        assertDumpContainsCallbackLog("singleScanFailed", requestId,
                "reason=" + WifiScanner.REASON_UNSPECIFIED + ", Scan failed");
        assertEquals(mWifiMetrics.getOneshotScanCount(), 1);
        assertEquals(mWifiMetrics.getScanReturnEntry(WifiMetricsProto.WifiLog.SCAN_UNKNOWN), 1);
        verify(mBatteryStats).noteWifiScanStoppedFromSource(eq(workSource));
        verify(mContext).sendBroadcastAsUser(any(Intent.class), eq(UserHandle.ALL));
    }

    /**
     * Send a single scan request and then disable Wi-Fi before it completes
     */
    @Test
    public void sendSingleScanRequestThenDisableWifi() {
        WifiScanner.ScanSettings requestSettings = createRequest(channelsToSpec(2400), 0,
                0, 20, WifiScanner.REPORT_EVENT_AFTER_EACH_SCAN);
        int requestId = 2293;

        startServiceAndLoadDriver();
        mWifiScanningServiceImpl.setWifiHandlerLogForTest(mLog);

        when(mWifiScannerImpl.startSingleScan(any(WifiNative.ScanSettings.class),
                        any(WifiNative.ScanEventHandler.class))).thenReturn(true);

        Handler handler = mock(Handler.class);
        BidirectionalAsyncChannel controlChannel = connectChannel(handler);
        InOrder order = inOrder(handler, mWifiScannerImpl);

        // Run scan 1
        sendSingleScanRequest(controlChannel, requestId, requestSettings, null);
        mLooper.dispatchAll();
        verifySuccessfulResponse(order, handler, requestId);

        // disable wifi
        TestUtil.sendWifiScanAvailable(mBroadcastReceiver, mContext,
                WifiManager.WIFI_STATE_DISABLED);

        // validate failed response
        mLooper.dispatchAll();
        verifyFailedResponse(order, handler, requestId, WifiScanner.REASON_UNSPECIFIED,
                "Scan was interrupted");
        verifyNoMoreInteractions(handler);
    }

    /**
     * Send a single scan request, schedule a second pending scan and disable Wi-Fi before the first
     * scan completes.
     */
    @Test
    public void sendSingleScanAndPendingScanAndListenerThenDisableWifi() {
        WifiScanner.ScanSettings requestSettings1 = createRequest(channelsToSpec(2400), 0,
                0, 20, WifiScanner.REPORT_EVENT_AFTER_EACH_SCAN);
        int requestId1 = 2293;

        WifiScanner.ScanSettings requestSettings2 = createRequest(channelsToSpec(2450), 0,
                0, 20, WifiScanner.REPORT_EVENT_AFTER_EACH_SCAN);
        int requestId2 = 2294;

        int listenerRequestId = 2295;

        startServiceAndLoadDriver();
        mWifiScanningServiceImpl.setWifiHandlerLogForTest(mLog);

        when(mWifiScannerImpl.startSingleScan(any(WifiNative.ScanSettings.class),
                        any(WifiNative.ScanEventHandler.class))).thenReturn(true);

        Handler handler = mock(Handler.class);
        BidirectionalAsyncChannel controlChannel = connectChannel(handler);
        InOrder order = inOrder(handler, mWifiScannerImpl);

        // Request scan 1
        sendSingleScanRequest(controlChannel, requestId1, requestSettings1, null);
        mLooper.dispatchAll();
        verifySuccessfulResponse(order, handler, requestId1);

        // Request scan 2
        sendSingleScanRequest(controlChannel, requestId2, requestSettings2, null);
        mLooper.dispatchAll();
        verifySuccessfulResponse(order, handler, requestId2);

        // Setup scan listener
        registerScanListener(controlChannel, listenerRequestId);
        mLooper.dispatchAll();
        verifySuccessfulResponse(order, handler, listenerRequestId);

        // disable wifi
        TestUtil.sendWifiScanAvailable(mBroadcastReceiver, mContext,
                WifiManager.WIFI_STATE_DISABLED);

        // validate failed response
        mLooper.dispatchAll();
        ArgumentCaptor<Message> messageCaptor = ArgumentCaptor.forClass(Message.class);
        order.verify(handler, times(2)).handleMessage(messageCaptor.capture());
        assertFailedResponse(requestId1, WifiScanner.REASON_UNSPECIFIED,
                "Scan was interrupted", messageCaptor.getAllValues().get(0));
        assertFailedResponse(requestId2, WifiScanner.REASON_UNSPECIFIED,
                "Scan was interrupted", messageCaptor.getAllValues().get(1));
        // No additional callbacks for scan listener
        verifyNoMoreInteractions(handler);
    }

    /**
     * Send a single scan request and then a second one after the first completes.
     */
    @Test
    public void sendSingleScanRequestAfterPreviousCompletes() {
        WifiScanner.ScanSettings requestSettings1 = createRequest(channelsToSpec(2400), 0,
                0, 20, WifiScanner.REPORT_EVENT_AFTER_EACH_SCAN);
        int requestId1 = 12;
        ScanResults results1 = ScanResults.create(0, 2400);


        WifiScanner.ScanSettings requestSettings2 = createRequest(channelsToSpec(2450, 5175), 0,
                0, 20, WifiScanner.REPORT_EVENT_AFTER_EACH_SCAN);
        int requestId2 = 13;
        ScanResults results2 = ScanResults.create(0, 2450);


        startServiceAndLoadDriver();
        mWifiScanningServiceImpl.setWifiHandlerLogForTest(mLog);

        when(mWifiScannerImpl.startSingleScan(any(WifiNative.ScanSettings.class),
                        any(WifiNative.ScanEventHandler.class))).thenReturn(true);

        Handler handler = mock(Handler.class);
        BidirectionalAsyncChannel controlChannel = connectChannel(handler);
        InOrder order = inOrder(handler, mWifiScannerImpl, mContext);

        // Run scan 1
        sendSingleScanRequest(controlChannel, requestId1, requestSettings1, null);

        mLooper.dispatchAll();
        WifiNative.ScanEventHandler eventHandler1 = verifyStartSingleScan(order,
                computeSingleScanNativeSettings(requestSettings1));
        verifySuccessfulResponse(order, handler, requestId1);

        // dispatch scan 1 results
        when(mWifiScannerImpl.getLatestSingleScanResults())
                .thenReturn(results1.getScanData());
        eventHandler1.onScanStatus(WifiNative.WIFI_SCAN_RESULTS_AVAILABLE);

        mLooper.dispatchAll();
        // Note: The order of the following verification calls looks out of order if you compare to
        // the source code of WifiScanningServiceImpl WifiSingleScanStateMachine.reportScanResults.
        // This is due to the fact that verifyScanResultsReceived and
        // verifySingleScanCompletedReceived require an additional call to handle the message that
        // is created in reportScanResults.  This handling is done in the two verify*Received calls
        // that is run AFTER the reportScanResults method in WifiScanningServiceImpl completes.
        order.verify(mContext).sendBroadcastAsUser(any(Intent.class), eq(UserHandle.ALL));
        verifyScanResultsReceived(order, handler, requestId1, results1.getScanData());
        verifySingleScanCompletedReceived(order, handler, requestId1);

        // Run scan 2
        sendSingleScanRequest(controlChannel, requestId2, requestSettings2, null);

        mLooper.dispatchAll();
        WifiNative.ScanEventHandler eventHandler2 = verifyStartSingleScan(order,
                computeSingleScanNativeSettings(requestSettings2));
        verifySuccessfulResponse(order, handler, requestId2);

        // dispatch scan 2 results
        when(mWifiScannerImpl.getLatestSingleScanResults())
                .thenReturn(results2.getScanData());
        eventHandler2.onScanStatus(WifiNative.WIFI_SCAN_RESULTS_AVAILABLE);

        mLooper.dispatchAll();
        order.verify(mContext).sendBroadcastAsUser(any(Intent.class), eq(UserHandle.ALL));
        verifyScanResultsReceived(order, handler, requestId2, results2.getScanData());
        verifySingleScanCompletedReceived(order, handler, requestId2);
    }

    /**
     * Send a single scan request and then a second one not satisfied by the first before the first
     * completes. Verify that both are scheduled and succeed.
     */
    @Test
    public void sendSingleScanRequestWhilePreviousScanRunning() {
        WifiScanner.ScanSettings requestSettings1 = createRequest(channelsToSpec(2400), 0,
                0, 20, WifiScanner.REPORT_EVENT_AFTER_EACH_SCAN);
        int requestId1 = 12;
        ScanResults results1 = ScanResults.create(0, 2400);

        WifiScanner.ScanSettings requestSettings2 = createRequest(channelsToSpec(2450, 5175), 0,
                0, 20, WifiScanner.REPORT_EVENT_AFTER_EACH_SCAN);
        int requestId2 = 13;
        ScanResults results2 = ScanResults.create(0, 2450);


        startServiceAndLoadDriver();
        mWifiScanningServiceImpl.setWifiHandlerLogForTest(mLog);

        when(mWifiScannerImpl.startSingleScan(any(WifiNative.ScanSettings.class),
                        any(WifiNative.ScanEventHandler.class))).thenReturn(true);

        Handler handler = mock(Handler.class);
        BidirectionalAsyncChannel controlChannel = connectChannel(handler);
        InOrder handlerOrder = inOrder(handler);
        InOrder nativeOrder = inOrder(mWifiScannerImpl);

        // Run scan 1
        sendSingleScanRequest(controlChannel, requestId1, requestSettings1, null);

        mLooper.dispatchAll();
        WifiNative.ScanEventHandler eventHandler1 = verifyStartSingleScan(nativeOrder,
                computeSingleScanNativeSettings(requestSettings1));
        verifySuccessfulResponse(handlerOrder, handler, requestId1);

        // Queue scan 2 (will not run because previous is in progress)
        sendSingleScanRequest(controlChannel, requestId2, requestSettings2, null);
        mLooper.dispatchAll();
        verifySuccessfulResponse(handlerOrder, handler, requestId2);

        // dispatch scan 1 results
        when(mWifiScannerImpl.getLatestSingleScanResults())
                .thenReturn(results1.getScanData());
        eventHandler1.onScanStatus(WifiNative.WIFI_SCAN_RESULTS_AVAILABLE);

        mLooper.dispatchAll();
        verifyScanResultsReceived(handlerOrder, handler, requestId1, results1.getScanData());
        verifySingleScanCompletedReceived(handlerOrder, handler, requestId1);
        verify(mContext).sendBroadcastAsUser(any(Intent.class), eq(UserHandle.ALL));

        // now that the first scan completed we expect the second one to start
        WifiNative.ScanEventHandler eventHandler2 = verifyStartSingleScan(nativeOrder,
                computeSingleScanNativeSettings(requestSettings2));

        // dispatch scan 2 results
        when(mWifiScannerImpl.getLatestSingleScanResults())
                .thenReturn(results2.getScanData());
        eventHandler2.onScanStatus(WifiNative.WIFI_SCAN_RESULTS_AVAILABLE);

        mLooper.dispatchAll();
        verifyScanResultsReceived(handlerOrder, handler, requestId2, results2.getScanData());
        verifySingleScanCompletedReceived(handlerOrder, handler, requestId2);
        verify(mContext, times(2)).sendBroadcastAsUser(any(Intent.class), eq(UserHandle.ALL));
        assertEquals(mWifiMetrics.getOneshotScanCount(), 2);
        assertEquals(mWifiMetrics.getScanReturnEntry(WifiMetricsProto.WifiLog.SCAN_SUCCESS), 2);
    }


    /**
     * Send a single scan request and then two more before the first completes. Neither are
     * satisfied by the first scan. Verify that the first completes and the second two are merged.
     */
    @Test
    public void sendMultipleSingleScanRequestWhilePreviousScanRunning() throws RemoteException {
        WifiScanner.ScanSettings requestSettings1 = createRequest(channelsToSpec(2400), 0,
                0, 20, WifiScanner.REPORT_EVENT_AFTER_EACH_SCAN);
        int requestId1 = 12;
        WorkSource workSource1 = new WorkSource(1121);
        ScanResults results1 = ScanResults.create(0, 2400);

        WifiScanner.ScanSettings requestSettings2 = createRequest(channelsToSpec(2450, 5175), 0,
                0, 20, WifiScanner.REPORT_EVENT_AFTER_EACH_SCAN);
        int requestId2 = 13;
        WorkSource workSource2 = new WorkSource(Binder.getCallingUid()); // don't explicitly set
        ScanResults results2 = ScanResults.create(0, 2450, 5175, 2450);

        WifiScanner.ScanSettings requestSettings3 = createRequest(channelsToSpec(5150), 0,
                0, 20, WifiScanner.REPORT_EVENT_AFTER_EACH_SCAN);
        int requestId3 = 15;
        WorkSource workSource3 = new WorkSource(2292);
        ScanResults results3 = ScanResults.create(0, 5150, 5150, 5150, 5150);

        WifiNative.ScanSettings nativeSettings2and3 = createSingleScanNativeSettingsForChannels(
                WifiScanner.REPORT_EVENT_AFTER_EACH_SCAN, channelsToSpec(2450, 5175, 5150));
        ScanResults results2and3 = ScanResults.merge(results2, results3);
        WorkSource workSource2and3 = new WorkSource();
        workSource2and3.add(workSource2);
        workSource2and3.add(workSource3);


        startServiceAndLoadDriver();
        mWifiScanningServiceImpl.setWifiHandlerLogForTest(mLog);

        when(mWifiScannerImpl.startSingleScan(any(WifiNative.ScanSettings.class),
                        any(WifiNative.ScanEventHandler.class))).thenReturn(true);

        Handler handler = mock(Handler.class);
        BidirectionalAsyncChannel controlChannel = connectChannel(handler);
        InOrder handlerOrder = inOrder(handler);
        InOrder nativeOrder = inOrder(mWifiScannerImpl);

        // Run scan 1
        sendSingleScanRequest(controlChannel, requestId1, requestSettings1, workSource1);

        mLooper.dispatchAll();
        WifiNative.ScanEventHandler eventHandler1 = verifyStartSingleScan(nativeOrder,
                computeSingleScanNativeSettings(requestSettings1));
        verifySuccessfulResponse(handlerOrder, handler, requestId1);
        verify(mBatteryStats).noteWifiScanStartedFromSource(eq(workSource1));


        // Queue scan 2 (will not run because previous is in progress)
        // uses uid of calling process
        sendSingleScanRequest(controlChannel, requestId2, requestSettings2, null);
        mLooper.dispatchAll();
        verifySuccessfulResponse(handlerOrder, handler, requestId2);

        // Queue scan 3 (will not run because previous is in progress)
        sendSingleScanRequest(controlChannel, requestId3, requestSettings3, workSource3);
        mLooper.dispatchAll();
        verifySuccessfulResponse(handlerOrder, handler, requestId3);

        // dispatch scan 1 results
        when(mWifiScannerImpl.getLatestSingleScanResults())
                .thenReturn(results1.getScanData());
        eventHandler1.onScanStatus(WifiNative.WIFI_SCAN_RESULTS_AVAILABLE);

        mLooper.dispatchAll();
        verifyScanResultsReceived(handlerOrder, handler, requestId1, results1.getScanData());
        verifySingleScanCompletedReceived(handlerOrder, handler, requestId1);
        verify(mContext).sendBroadcastAsUser(any(Intent.class), eq(UserHandle.ALL));
        verify(mBatteryStats).noteWifiScanStoppedFromSource(eq(workSource1));
        verify(mBatteryStats).noteWifiScanStartedFromSource(eq(workSource2and3));

        // now that the first scan completed we expect the second and third ones to start
        WifiNative.ScanEventHandler eventHandler2and3 = verifyStartSingleScan(nativeOrder,
                nativeSettings2and3);

        // dispatch scan 2 and 3 results
        when(mWifiScannerImpl.getLatestSingleScanResults())
                .thenReturn(results2and3.getScanData());
        eventHandler2and3.onScanStatus(WifiNative.WIFI_SCAN_RESULTS_AVAILABLE);

        mLooper.dispatchAll();

        verifyMultipleSingleScanResults(handlerOrder, handler, requestId2, results2, requestId3,
                results3);
        assertEquals(mWifiMetrics.getOneshotScanCount(), 3);
        assertEquals(mWifiMetrics.getScanReturnEntry(WifiMetricsProto.WifiLog.SCAN_SUCCESS), 3);

        verify(mBatteryStats).noteWifiScanStoppedFromSource(eq(workSource2and3));

        assertDumpContainsRequestLog("addSingleScanRequest", requestId1);
        assertDumpContainsRequestLog("addSingleScanRequest", requestId2);
        assertDumpContainsRequestLog("addSingleScanRequest", requestId3);
        assertDumpContainsCallbackLog("singleScanResults", requestId1,
                "results=" + results1.getRawScanResults().length);
        assertDumpContainsCallbackLog("singleScanResults", requestId2,
                "results=" + results2.getRawScanResults().length);
        assertDumpContainsCallbackLog("singleScanResults", requestId3,
                "results=" + results3.getRawScanResults().length);
    }


    /**
     * Send a single scan request and then a second one satisfied by the first before the first
     * completes. Verify that only one scan is scheduled.
     */
    @Test
    public void sendSingleScanRequestWhilePreviousScanRunningAndMergeIntoFirstScan() {
        // Split by frequency to make it easier to determine which results each request is expecting
        ScanResults results24GHz = ScanResults.create(0, 2400, 2400, 2400, 2450);
        ScanResults results5GHz = ScanResults.create(0, 5150, 5150, 5175);
        ScanResults resultsBoth = ScanResults.merge(results24GHz, results5GHz);

        WifiScanner.ScanSettings requestSettings1 = createRequest(WifiScanner.WIFI_BAND_BOTH, 0,
                0, 20, WifiScanner.REPORT_EVENT_AFTER_EACH_SCAN);
        int requestId1 = 12;
        ScanResults results1 = resultsBoth;

        WifiScanner.ScanSettings requestSettings2 = createRequest(WifiScanner.WIFI_BAND_24_GHZ, 0,
                0, 20, WifiScanner.REPORT_EVENT_AFTER_EACH_SCAN);
        int requestId2 = 13;
        ScanResults results2 = results24GHz;


        startServiceAndLoadDriver();
        mWifiScanningServiceImpl.setWifiHandlerLogForTest(mLog);

        when(mWifiScannerImpl.startSingleScan(any(WifiNative.ScanSettings.class),
                        any(WifiNative.ScanEventHandler.class))).thenReturn(true);

        Handler handler = mock(Handler.class);
        BidirectionalAsyncChannel controlChannel = connectChannel(handler);
        InOrder handlerOrder = inOrder(handler);
        InOrder nativeOrder = inOrder(mWifiScannerImpl);

        // Run scan 1
        sendSingleScanRequest(controlChannel, requestId1, requestSettings1, null);

        mLooper.dispatchAll();
        WifiNative.ScanEventHandler eventHandler = verifyStartSingleScan(nativeOrder,
                computeSingleScanNativeSettings(requestSettings1));
        verifySuccessfulResponse(handlerOrder, handler, requestId1);

        // Queue scan 2 (will be folded into ongoing scan)
        sendSingleScanRequest(controlChannel, requestId2, requestSettings2, null);
        mLooper.dispatchAll();
        verifySuccessfulResponse(handlerOrder, handler, requestId2);

        // dispatch scan 1 results
        when(mWifiScannerImpl.getLatestSingleScanResults())
                .thenReturn(resultsBoth.getScanData());
        eventHandler.onScanStatus(WifiNative.WIFI_SCAN_RESULTS_AVAILABLE);

        mLooper.dispatchAll();
        verifyMultipleSingleScanResults(handlerOrder, handler, requestId1, results1, requestId2,
                results2);

        assertEquals(mWifiMetrics.getOneshotScanCount(), 2);
        assertEquals(mWifiMetrics.getScanReturnEntry(WifiMetricsProto.WifiLog.SCAN_SUCCESS), 2);
    }

    /**
     * Send a single scan request and then two more before the first completes, one of which is
     * satisfied by the first scan. Verify that the first two complete together the second scan is
     * just for the other scan.
     */
    @Test
    public void sendMultipleSingleScanRequestWhilePreviousScanRunningAndMergeOneIntoFirstScan()
          throws RemoteException {
        // Split by frequency to make it easier to determine which results each request is expecting
        ScanResults results2400 = ScanResults.create(0, 2400, 2400, 2400);
        ScanResults results2450 = ScanResults.create(0, 2450);
        ScanResults results1and3 = ScanResults.merge(results2400, results2450);

        WifiScanner.ScanSettings requestSettings1 = createRequest(channelsToSpec(2400, 2450), 0,
                0, 20, WifiScanner.REPORT_EVENT_AFTER_EACH_SCAN);
        int requestId1 = 12;
        WorkSource workSource1 = new WorkSource(1121);
        ScanResults results1 = results1and3;

        WifiScanner.ScanSettings requestSettings2 = createRequest(channelsToSpec(2450, 5175), 0,
                0, 20, WifiScanner.REPORT_EVENT_AFTER_EACH_SCAN);
        int requestId2 = 13;
        WorkSource workSource2 = new WorkSource(Binder.getCallingUid()); // don't explicitly set
        ScanResults results2 = ScanResults.create(0, 2450, 5175, 2450);

        WifiScanner.ScanSettings requestSettings3 = createRequest(channelsToSpec(2400), 0,
                0, 20, WifiScanner.REPORT_EVENT_AFTER_EACH_SCAN);
        int requestId3 = 15;
        WorkSource workSource3 = new WorkSource(2292);
        ScanResults results3 = results2400;

        startServiceAndLoadDriver();
        mWifiScanningServiceImpl.setWifiHandlerLogForTest(mLog);

        when(mWifiScannerImpl.startSingleScan(any(WifiNative.ScanSettings.class),
                        any(WifiNative.ScanEventHandler.class))).thenReturn(true);

        Handler handler = mock(Handler.class);
        BidirectionalAsyncChannel controlChannel = connectChannel(handler);
        InOrder handlerOrder = inOrder(handler);
        InOrder nativeOrder = inOrder(mWifiScannerImpl);

        // Run scan 1
        sendSingleScanRequest(controlChannel, requestId1, requestSettings1, workSource1);

        mLooper.dispatchAll();
        WifiNative.ScanEventHandler eventHandler1 = verifyStartSingleScan(nativeOrder,
                computeSingleScanNativeSettings(requestSettings1));
        verifySuccessfulResponse(handlerOrder, handler, requestId1);
        verify(mBatteryStats).noteWifiScanStartedFromSource(eq(workSource1));


        // Queue scan 2 (will not run because previous is in progress)
        // uses uid of calling process
        sendSingleScanRequest(controlChannel, requestId2, requestSettings2, null);
        mLooper.dispatchAll();
        verifySuccessfulResponse(handlerOrder, handler, requestId2);

        // Queue scan 3 (will be merged into the active scan)
        sendSingleScanRequest(controlChannel, requestId3, requestSettings3, workSource3);
        mLooper.dispatchAll();
        verifySuccessfulResponse(handlerOrder, handler, requestId3);

        // dispatch scan 1 results
        when(mWifiScannerImpl.getLatestSingleScanResults())
                .thenReturn(results1and3.getScanData());
        eventHandler1.onScanStatus(WifiNative.WIFI_SCAN_RESULTS_AVAILABLE);

        mLooper.dispatchAll();
        verifyMultipleSingleScanResults(handlerOrder, handler, requestId1, results1, requestId3,
                results3);
        // only the requests know at the beginning of the scan get blamed
        verify(mBatteryStats).noteWifiScanStoppedFromSource(eq(workSource1));
        verify(mBatteryStats).noteWifiScanStartedFromSource(eq(workSource2));

        // now that the first scan completed we expect the second and third ones to start
        WifiNative.ScanEventHandler eventHandler2 = verifyStartSingleScan(nativeOrder,
                computeSingleScanNativeSettings(requestSettings2));

        // dispatch scan 2 and 3 results
        when(mWifiScannerImpl.getLatestSingleScanResults())
                .thenReturn(results2.getScanData());
        eventHandler2.onScanStatus(WifiNative.WIFI_SCAN_RESULTS_AVAILABLE);

        mLooper.dispatchAll();

        verifyScanResultsReceived(handlerOrder, handler, requestId2, results2.getScanData());
        verifySingleScanCompletedReceived(handlerOrder, handler, requestId2);
        verify(mContext, times(2)).sendBroadcastAsUser(any(Intent.class), eq(UserHandle.ALL));
        assertEquals(mWifiMetrics.getOneshotScanCount(), 3);
        assertEquals(mWifiMetrics.getScanReturnEntry(WifiMetricsProto.WifiLog.SCAN_SUCCESS), 3);

        verify(mBatteryStats).noteWifiScanStoppedFromSource(eq(workSource2));

        assertDumpContainsRequestLog("addSingleScanRequest", requestId1);
        assertDumpContainsRequestLog("addSingleScanRequest", requestId2);
        assertDumpContainsRequestLog("addSingleScanRequest", requestId3);
        assertDumpContainsCallbackLog("singleScanResults", requestId1,
                "results=" + results1.getRawScanResults().length);
        assertDumpContainsCallbackLog("singleScanResults", requestId2,
                "results=" + results2.getRawScanResults().length);
        assertDumpContainsCallbackLog("singleScanResults", requestId3,
                "results=" + results3.getRawScanResults().length);
    }

    /**
     * Verify that WifiService provides a way to get the most recent SingleScan results.
     */
    @Test
    public void retrieveSingleScanResults() throws Exception {
        WifiScanner.ScanSettings requestSettings =
                createRequest(WifiScanner.WIFI_BAND_BOTH_WITH_DFS,
                              0, 0, 20, WifiScanner.REPORT_EVENT_AFTER_EACH_SCAN);
        ScanResults expectedResults = ScanResults.create(0, true, 2400, 5150, 5175);
        doSuccessfulSingleScan(requestSettings,
                               computeSingleScanNativeSettings(requestSettings),
                               expectedResults);
        Handler handler = mock(Handler.class);
        BidirectionalAsyncChannel controlChannel = connectChannel(handler);
        InOrder order = inOrder(handler, mWifiScannerImpl);

        controlChannel.sendMessage(
                Message.obtain(null, WifiScanner.CMD_GET_SINGLE_SCAN_RESULTS, 0));
        mLooper.dispatchAll();
        Message response = verifyHandleMessageAndGetMessage(order, handler);
        List<ScanResult> results = Arrays.asList(
                ((WifiScanner.ParcelableScanResults) response.obj).getResults());
        assertEquals(results.size(), expectedResults.getRawScanResults().length);

        // Make sure that we logged the scan results in the dump method.
        String serviceDump = dumpService();
        Pattern logLineRegex = Pattern.compile("Latest scan results:");
        assertTrue("dump did not contain Latest scan results: " + serviceDump + "\n",
                logLineRegex.matcher(serviceDump).find());
    }

    /**
     * Verify that WifiService provides a way to get the most recent SingleScan results even when
     * they are empty.
     */
    @Test
    public void retrieveSingleScanResultsEmpty() throws Exception {
        WifiScanner.ScanSettings requestSettings = createRequest(WifiScanner.WIFI_BAND_BOTH, 0,
                0, 20, WifiScanner.REPORT_EVENT_AFTER_EACH_SCAN);
        doSuccessfulSingleScan(requestSettings, computeSingleScanNativeSettings(requestSettings),
                ScanResults.create(0, new int[0]));

        Handler handler = mock(Handler.class);
        BidirectionalAsyncChannel controlChannel = connectChannel(handler);
        InOrder order = inOrder(handler, mWifiScannerImpl);

        controlChannel.sendMessage(
                Message.obtain(null, WifiScanner.CMD_GET_SINGLE_SCAN_RESULTS, 0));
        mLooper.dispatchAll();
        Message response = verifyHandleMessageAndGetMessage(order, handler);

        List<ScanResult> results = Arrays.asList(
                ((WifiScanner.ParcelableScanResults) response.obj).getResults());
        assertEquals(results.size(), 0);
    }

    /**
     * Verify that WifiService will return empty SingleScan results if a scan has not been
     * performed.
     */
    @Test
    public void retrieveSingleScanResultsBeforeAnySingleScans() throws Exception {
        startServiceAndLoadDriver();
        mWifiScanningServiceImpl.setWifiHandlerLogForTest(mLog);
        Handler handler = mock(Handler.class);
        BidirectionalAsyncChannel controlChannel = connectChannel(handler);
        InOrder order = inOrder(handler, mWifiScannerImpl);

        controlChannel.sendMessage(
                Message.obtain(null, WifiScanner.CMD_GET_SINGLE_SCAN_RESULTS, 0));
        mLooper.dispatchAll();
        Message response = verifyHandleMessageAndGetMessage(order, handler);

        List<ScanResult> results = Arrays.asList(
                ((WifiScanner.ParcelableScanResults) response.obj).getResults());
        assertEquals(results.size(), 0);
    }

    /**
     * Verify that the newest scan results are returned by WifiService.getSingleScanResults.
     */
    @Test
    public void retrieveMostRecentSingleScanResults() throws Exception {
        WifiScanner.ScanSettings requestSettings = createRequest(WifiScanner.WIFI_BAND_BOTH, 0,
                0, 20, WifiScanner.REPORT_EVENT_AFTER_EACH_SCAN);
        ScanResults expectedResults = ScanResults.create(0, true, 2400, 5150, 5175);
        doSuccessfulSingleScan(requestSettings,
                               computeSingleScanNativeSettings(requestSettings),
                               expectedResults);

        Handler handler = mock(Handler.class);
        BidirectionalAsyncChannel controlChannel = connectChannel(handler);
        InOrder order = inOrder(handler, mWifiScannerImpl);

        controlChannel.sendMessage(
                Message.obtain(null, WifiScanner.CMD_GET_SINGLE_SCAN_RESULTS, 0));
        mLooper.dispatchAll();
        Message response = verifyHandleMessageAndGetMessage(order, handler);

        List<ScanResult> results = Arrays.asList(
                ((WifiScanner.ParcelableScanResults) response.obj).getResults());
        assertEquals(results.size(), expectedResults.getRawScanResults().length);

        // now update with a new scan that only has one result
        int secondScanRequestId = 35;
        ScanResults expectedSingleResult = ScanResults.create(0, true, 5150);
        sendSingleScanRequest(controlChannel, secondScanRequestId, requestSettings, null);

        mLooper.dispatchAll();
        WifiNative.ScanEventHandler eventHandler = verifyStartSingleScan(order,
                computeSingleScanNativeSettings(requestSettings));
        verifySuccessfulResponse(order, handler, secondScanRequestId);

        // dispatch scan 2 results
        when(mWifiScannerImpl.getLatestSingleScanResults())
                .thenReturn(expectedSingleResult.getScanData());
        eventHandler.onScanStatus(WifiNative.WIFI_SCAN_RESULTS_AVAILABLE);

        mLooper.dispatchAll();
        verifyScanResultsReceived(order, handler, secondScanRequestId,
                expectedSingleResult.getScanData());
        verifySingleScanCompletedReceived(order, handler, secondScanRequestId);

        controlChannel.sendMessage(
                Message.obtain(null, WifiScanner.CMD_GET_SINGLE_SCAN_RESULTS, 0));
        mLooper.dispatchAll();
        Message response2 = verifyHandleMessageAndGetMessage(order, handler);

        List<ScanResult> results2 = Arrays.asList(
                ((WifiScanner.ParcelableScanResults) response2.obj).getResults());
        assertEquals(results2.size(), expectedSingleResult.getRawScanResults().length);
    }

    /**
     * Cached scan results should be cleared after the driver is unloaded.
     */
    @Test
    public void validateScanResultsClearedAfterDriverUnloaded() throws Exception {
        WifiScanner.ScanSettings requestSettings =
                createRequest(WifiScanner.WIFI_BAND_BOTH_WITH_DFS,
                              0, 0, 20, WifiScanner.REPORT_EVENT_AFTER_EACH_SCAN);
        ScanResults expectedResults = ScanResults.create(0, true, 2400, 5150, 5175);
        doSuccessfulSingleScan(requestSettings,
                               computeSingleScanNativeSettings(requestSettings),
                               expectedResults);
        Handler handler = mock(Handler.class);
        BidirectionalAsyncChannel controlChannel = connectChannel(handler);
        InOrder order = inOrder(handler, mWifiScannerImpl);

        controlChannel.sendMessage(
                Message.obtain(null, WifiScanner.CMD_GET_SINGLE_SCAN_RESULTS, 0));
        mLooper.dispatchAll();
        Message response = verifyHandleMessageAndGetMessage(order, handler);
        List<ScanResult> results = Arrays.asList(
                ((WifiScanner.ParcelableScanResults) response.obj).getResults());
        assertEquals(results.size(), expectedResults.getRawScanResults().length);

        // disable wifi
        TestUtil.sendWifiScanAvailable(mBroadcastReceiver,
                                       mContext,
                                       WifiManager.WIFI_STATE_DISABLED);
        // Now get scan results again. The returned list should be empty since we
        // clear the cache when exiting the DriverLoaded state.
        controlChannel.sendMessage(
                Message.obtain(null, WifiScanner.CMD_GET_SINGLE_SCAN_RESULTS, 0));
        mLooper.dispatchAll();
        Message response2 = verifyHandleMessageAndGetMessage(order, handler);
        List<ScanResult> results2 = Arrays.asList(
                ((WifiScanner.ParcelableScanResults) response2.obj).getResults());
        assertEquals(results2.size(), 0);
    }

    /**
     * Register a single scan listener and do a single scan
     */
    @Test
    public void registerScanListener() throws Exception {
        WifiScanner.ScanSettings requestSettings = createRequest(WifiScanner.WIFI_BAND_BOTH, 0,
                0, 20, WifiScanner.REPORT_EVENT_AFTER_EACH_SCAN);
        WifiNative.ScanSettings nativeSettings = computeSingleScanNativeSettings(requestSettings);
        ScanResults results = ScanResults.create(0, 2400, 5150, 5175);

        int requestId = 12;
        int listenerRequestId = 13;

        startServiceAndLoadDriver();
        mWifiScanningServiceImpl.setWifiHandlerLogForTest(mLog);

        Handler handler = mock(Handler.class);
        BidirectionalAsyncChannel controlChannel = connectChannel(handler);
        InOrder order = inOrder(handler, mWifiScannerImpl);

        when(mWifiScannerImpl.startSingleScan(any(WifiNative.ScanSettings.class),
                        any(WifiNative.ScanEventHandler.class))).thenReturn(true);

        registerScanListener(controlChannel, listenerRequestId);
        mLooper.dispatchAll();
        verifySuccessfulResponse(order, handler, listenerRequestId);

        sendSingleScanRequest(controlChannel, requestId, requestSettings, null);

        mLooper.dispatchAll();
        WifiNative.ScanEventHandler eventHandler = verifyStartSingleScan(order, nativeSettings);
        verifySuccessfulResponse(order, handler, requestId);

        when(mWifiScannerImpl.getLatestSingleScanResults())
                .thenReturn(results.getRawScanData());
        eventHandler.onScanStatus(WifiNative.WIFI_SCAN_RESULTS_AVAILABLE);

        mLooper.dispatchAll();
        verifyScanResultsReceived(order, handler, requestId, results.getScanData());
        verifySingleScanCompletedReceived(order, handler, requestId);
        verifyScanResultsReceived(order, handler, listenerRequestId, results.getScanData());
        verify(mContext).sendBroadcastAsUser(any(Intent.class), eq(UserHandle.ALL));
        verifyNoMoreInteractions(handler);

        assertDumpContainsRequestLog("registerScanListener", listenerRequestId);
        assertDumpContainsCallbackLog("singleScanResults", listenerRequestId,
                "results=" + results.getScanData().getResults().length);
    }

    /**
     * Register a single scan listener and do a single scan
     */
    @Test
    public void deregisterScanListener() throws Exception {
        WifiScanner.ScanSettings requestSettings = createRequest(WifiScanner.WIFI_BAND_BOTH, 0,
                0, 20, WifiScanner.REPORT_EVENT_AFTER_EACH_SCAN);
        WifiNative.ScanSettings nativeSettings = computeSingleScanNativeSettings(requestSettings);
        ScanResults results = ScanResults.create(0, 2400, 5150, 5175);

        int requestId = 12;
        int listenerRequestId = 13;

        startServiceAndLoadDriver();
        mWifiScanningServiceImpl.setWifiHandlerLogForTest(mLog);

        Handler handler = mock(Handler.class);
        BidirectionalAsyncChannel controlChannel = connectChannel(handler);
        InOrder order = inOrder(handler, mWifiScannerImpl);

        when(mWifiScannerImpl.startSingleScan(any(WifiNative.ScanSettings.class),
                        any(WifiNative.ScanEventHandler.class))).thenReturn(true);

        registerScanListener(controlChannel, listenerRequestId);
        mLooper.dispatchAll();
        verifySuccessfulResponse(order, handler, listenerRequestId);

        sendSingleScanRequest(controlChannel, requestId, requestSettings, null);

        mLooper.dispatchAll();
        WifiNative.ScanEventHandler eventHandler = verifyStartSingleScan(order, nativeSettings);
        verifySuccessfulResponse(order, handler, requestId);

        deregisterScanListener(controlChannel, listenerRequestId);
        mLooper.dispatchAll();

        when(mWifiScannerImpl.getLatestSingleScanResults())
                .thenReturn(results.getRawScanData());
        eventHandler.onScanStatus(WifiNative.WIFI_SCAN_RESULTS_AVAILABLE);

        mLooper.dispatchAll();
        verifyScanResultsReceived(order, handler, requestId, results.getScanData());
        verifySingleScanCompletedReceived(order, handler, requestId);
        verify(mContext).sendBroadcastAsUser(any(Intent.class), eq(UserHandle.ALL));
        verifyNoMoreInteractions(handler);

        assertDumpContainsRequestLog("registerScanListener", listenerRequestId);
        assertDumpContainsRequestLog("deregisterScanListener", listenerRequestId);
    }

    /**
     * Send a single scan request and then two more before the first completes. Neither are
     * satisfied by the first scan. Verify that the first completes and the second two are merged.
     */
    @Test
    public void scanListenerReceivesAllResults() throws RemoteException {
        WifiScanner.ScanSettings requestSettings1 = createRequest(channelsToSpec(2400), 0,
                0, 20, WifiScanner.REPORT_EVENT_AFTER_EACH_SCAN);
        int requestId1 = 12;
        ScanResults results1 = ScanResults.create(0, 2400);

        WifiScanner.ScanSettings requestSettings2 = createRequest(channelsToSpec(2450, 5175), 0,
                0, 20, WifiScanner.REPORT_EVENT_AFTER_EACH_SCAN);
        int requestId2 = 13;
        ScanResults results2 = ScanResults.create(0, 2450, 5175, 2450);

        WifiScanner.ScanSettings requestSettings3 = createRequest(channelsToSpec(5150), 0,
                0, 20, WifiScanner.REPORT_EVENT_AFTER_EACH_SCAN);
        int requestId3 = 15;
        ScanResults results3 = ScanResults.create(0, 5150, 5150, 5150, 5150);

        WifiNative.ScanSettings nativeSettings2and3 = createSingleScanNativeSettingsForChannels(
                WifiScanner.REPORT_EVENT_AFTER_EACH_SCAN, channelsToSpec(2450, 5175, 5150));
        ScanResults results2and3 = ScanResults.merge(results2, results3);

        int listenerRequestId = 13;


        startServiceAndLoadDriver();
        mWifiScanningServiceImpl.setWifiHandlerLogForTest(mLog);

        when(mWifiScannerImpl.startSingleScan(any(WifiNative.ScanSettings.class),
                        any(WifiNative.ScanEventHandler.class))).thenReturn(true);

        Handler handler = mock(Handler.class);
        BidirectionalAsyncChannel controlChannel = connectChannel(handler);
        InOrder handlerOrder = inOrder(handler);
        InOrder nativeOrder = inOrder(mWifiScannerImpl);

        // Run scan 1
        sendSingleScanRequest(controlChannel, requestId1, requestSettings1, null);

        mLooper.dispatchAll();
        WifiNative.ScanEventHandler eventHandler1 = verifyStartSingleScan(nativeOrder,
                computeSingleScanNativeSettings(requestSettings1));
        verifySuccessfulResponse(handlerOrder, handler, requestId1);


        // Queue scan 2 (will not run because previous is in progress)
        sendSingleScanRequest(controlChannel, requestId2, requestSettings2, null);
        mLooper.dispatchAll();
        verifySuccessfulResponse(handlerOrder, handler, requestId2);

        // Queue scan 3 (will not run because previous is in progress)
        sendSingleScanRequest(controlChannel, requestId3, requestSettings3, null);
        mLooper.dispatchAll();
        verifySuccessfulResponse(handlerOrder, handler, requestId3);

        // Register scan listener
        registerScanListener(controlChannel, listenerRequestId);
        mLooper.dispatchAll();
        verifySuccessfulResponse(handlerOrder, handler, listenerRequestId);

        // dispatch scan 1 results
        when(mWifiScannerImpl.getLatestSingleScanResults())
                .thenReturn(results1.getScanData());
        eventHandler1.onScanStatus(WifiNative.WIFI_SCAN_RESULTS_AVAILABLE);

        mLooper.dispatchAll();
        verifyScanResultsReceived(handlerOrder, handler, requestId1, results1.getScanData());
        verifySingleScanCompletedReceived(handlerOrder, handler, requestId1);
        verifyScanResultsReceived(handlerOrder, handler, listenerRequestId, results1.getScanData());
        verify(mContext).sendBroadcastAsUser(any(Intent.class), eq(UserHandle.ALL));

        // now that the first scan completed we expect the second and third ones to start
        WifiNative.ScanEventHandler eventHandler2and3 = verifyStartSingleScan(nativeOrder,
                nativeSettings2and3);

        // dispatch scan 2 and 3 results
        when(mWifiScannerImpl.getLatestSingleScanResults())
                .thenReturn(results2and3.getScanData());
        eventHandler2and3.onScanStatus(WifiNative.WIFI_SCAN_RESULTS_AVAILABLE);

        mLooper.dispatchAll();

        verifyMultipleSingleScanResults(handlerOrder, handler, requestId2, results2, requestId3,
                results3, listenerRequestId, results2and3);

        assertDumpContainsRequestLog("registerScanListener", listenerRequestId);
        assertDumpContainsCallbackLog("singleScanResults", listenerRequestId,
                "results=" + results1.getRawScanResults().length);
        assertDumpContainsCallbackLog("singleScanResults", listenerRequestId,
                "results=" + results2and3.getRawScanResults().length);
    }


    private void doSuccessfulBackgroundScan(WifiScanner.ScanSettings requestSettings,
            WifiNative.ScanSettings nativeSettings) {
        startServiceAndLoadDriver();
        mWifiScanningServiceImpl.setWifiHandlerLogForTest(mLog);

        Handler handler = mock(Handler.class);
        BidirectionalAsyncChannel controlChannel = connectChannel(handler);
        InOrder order = inOrder(handler, mWifiScannerImpl);

        when(mWifiScannerImpl.startBatchedScan(any(WifiNative.ScanSettings.class),
                        any(WifiNative.ScanEventHandler.class))).thenReturn(true);

        sendBackgroundScanRequest(controlChannel, 12, requestSettings, null);
        mLooper.dispatchAll();
        verifyStartBackgroundScan(order, nativeSettings);
        verifySuccessfulResponse(order, handler, 12);
        verifyNoMoreInteractions(handler);
        assertDumpContainsRequestLog("addBackgroundScanRequest", 12);
    }

    /**
     * Do a background scan for a band and verify that it is successful.
     */
    @Test
    public void sendBackgroundScanBandRequest() throws Exception {
        WifiScanner.ScanSettings requestSettings = createRequest(WifiScanner.WIFI_BAND_BOTH, 30000,
                0, 20, WifiScanner.REPORT_EVENT_AFTER_EACH_SCAN);
        WifiNative.ScanSettings nativeSettings = new NativeScanSettingsBuilder()
                .withBasePeriod(30000)
                .withMaxApPerScan(MAX_AP_PER_SCAN)
                .withMaxScansToCache(BackgroundScanScheduler.DEFAULT_MAX_SCANS_TO_BATCH)
                .addBucketWithBand(30000, WifiScanner.REPORT_EVENT_AFTER_EACH_SCAN,
                        WifiScanner.WIFI_BAND_BOTH)
                .build();
        doSuccessfulBackgroundScan(requestSettings, nativeSettings);
        assertEquals(mWifiMetrics.getBackgroundScanCount(), 1);
    }

    /**
     * Do a background scan for a list of channels and verify that it is successful.
     */
    @Test
    public void sendBackgroundScanChannelsRequest() throws Exception {
        WifiScanner.ScanSettings requestSettings = createRequest(channelsToSpec(5150), 30000,
                0, 20, WifiScanner.REPORT_EVENT_AFTER_EACH_SCAN);
        WifiNative.ScanSettings nativeSettings = new NativeScanSettingsBuilder()
                .withBasePeriod(30000)
                .withMaxApPerScan(MAX_AP_PER_SCAN)
                .withMaxScansToCache(BackgroundScanScheduler.DEFAULT_MAX_SCANS_TO_BATCH)
                .addBucketWithChannels(30000, WifiScanner.REPORT_EVENT_AFTER_EACH_SCAN, 5150)
                .build();
        doSuccessfulBackgroundScan(requestSettings, nativeSettings);
    }

    private Pair<WifiScanner.ScanSettings, WifiNative.ScanSettings> createScanSettingsForHwPno()
            throws Exception {
        WifiScanner.ScanSettings requestSettings = createRequest(
                channelsToSpec(0, 2400, 5150, 5175), 30000, 0, 20,
                WifiScanner.REPORT_EVENT_AFTER_EACH_SCAN);
        WifiNative.ScanSettings nativeSettings = new NativeScanSettingsBuilder()
                .withBasePeriod(30000)
                .withMaxApPerScan(MAX_AP_PER_SCAN)
                .withMaxScansToCache(BackgroundScanScheduler.DEFAULT_MAX_SCANS_TO_BATCH)
                .addBucketWithChannels(30000, WifiScanner.REPORT_EVENT_AFTER_EACH_SCAN,
                        0, 2400, 5150, 5175)
                .build();
        return Pair.create(requestSettings, nativeSettings);
    }

    private Pair<WifiScanner.ScanSettings, WifiNative.ScanSettings> createScanSettingsForSwPno()
            throws Exception {
        Pair<WifiScanner.ScanSettings, WifiNative.ScanSettings> settingsPair =
                createScanSettingsForHwPno();

        WifiScanner.ScanSettings requestSettings = settingsPair.first;
        WifiNative.ScanSettings nativeSettings = settingsPair.second;
        // reportEvents field is overridden for SW PNO
        for (int i = 0; i < nativeSettings.buckets.length; i++) {
            nativeSettings.buckets[i].report_events = WifiScanner.REPORT_EVENT_AFTER_EACH_SCAN
                    | WifiScanner.REPORT_EVENT_FULL_SCAN_RESULT;
        }
        return Pair.create(requestSettings, nativeSettings);
    }

    private Pair<WifiScanner.PnoSettings, WifiNative.PnoSettings> createPnoSettings(
            ScanResults results)
            throws Exception {
        WifiScanner.PnoSettings requestPnoSettings = new WifiScanner.PnoSettings();
        requestPnoSettings.networkList =
                new WifiScanner.PnoSettings.PnoNetwork[results.getRawScanResults().length];
        int i = 0;
        for (ScanResult scanResult : results.getRawScanResults()) {
            requestPnoSettings.networkList[i++] =
                    new WifiScanner.PnoSettings.PnoNetwork(scanResult.SSID);
        }

        WifiNative.PnoSettings nativePnoSettings = new WifiNative.PnoSettings();
        nativePnoSettings.min5GHzRssi = requestPnoSettings.min5GHzRssi;
        nativePnoSettings.min24GHzRssi = requestPnoSettings.min24GHzRssi;
        nativePnoSettings.initialScoreMax = requestPnoSettings.initialScoreMax;
        nativePnoSettings.currentConnectionBonus = requestPnoSettings.currentConnectionBonus;
        nativePnoSettings.sameNetworkBonus = requestPnoSettings.sameNetworkBonus;
        nativePnoSettings.secureBonus = requestPnoSettings.secureBonus;
        nativePnoSettings.band5GHzBonus = requestPnoSettings.band5GHzBonus;
        nativePnoSettings.isConnected = requestPnoSettings.isConnected;
        nativePnoSettings.networkList =
                new WifiNative.PnoNetwork[requestPnoSettings.networkList.length];
        for (i = 0; i < requestPnoSettings.networkList.length; i++) {
            nativePnoSettings.networkList[i] = new WifiNative.PnoNetwork();
            nativePnoSettings.networkList[i].ssid = requestPnoSettings.networkList[i].ssid;
            nativePnoSettings.networkList[i].flags = requestPnoSettings.networkList[i].flags;
            nativePnoSettings.networkList[i].auth_bit_field =
                    requestPnoSettings.networkList[i].authBitField;
        }
        return Pair.create(requestPnoSettings, nativePnoSettings);
    }

    private ScanResults createScanResultsForPno() {
        return ScanResults.create(0, 2400, 5150, 5175);
    }

    private ScanResults createScanResultsForPnoWithNoIE() {
        return ScanResults.createWithNoIE(0, 2400, 5150, 5175);
    }

    private WifiNative.PnoEventHandler verifyHwPno(InOrder order,
            WifiNative.PnoSettings expected) {
        ArgumentCaptor<WifiNative.PnoSettings> pnoSettingsCaptor =
                ArgumentCaptor.forClass(WifiNative.PnoSettings.class);
        ArgumentCaptor<WifiNative.PnoEventHandler> pnoEventHandlerCaptor =
                ArgumentCaptor.forClass(WifiNative.PnoEventHandler.class);
        order.verify(mWifiScannerImpl).setHwPnoList(pnoSettingsCaptor.capture(),
                pnoEventHandlerCaptor.capture());
        assertNativePnoSettingsEquals(expected, pnoSettingsCaptor.getValue());
        return pnoEventHandlerCaptor.getValue();
    }

    private void sendPnoScanRequest(BidirectionalAsyncChannel controlChannel,
            int scanRequestId, WifiScanner.ScanSettings scanSettings,
            WifiScanner.PnoSettings pnoSettings) {
        Bundle pnoParams = new Bundle();
        scanSettings.isPnoScan = true;
        pnoParams.putParcelable(WifiScanner.PNO_PARAMS_SCAN_SETTINGS_KEY, scanSettings);
        pnoParams.putParcelable(WifiScanner.PNO_PARAMS_PNO_SETTINGS_KEY, pnoSettings);
        controlChannel.sendMessage(Message.obtain(null, WifiScanner.CMD_START_PNO_SCAN, 0,
                scanRequestId, pnoParams));
    }

    private void assertPnoNetworkFoundMessage(int listenerId, ScanResult[] expected,
            Message networkFoundMessage) {
        assertEquals("what", WifiScanner.CMD_PNO_NETWORK_FOUND, networkFoundMessage.what);
        assertEquals("listenerId", listenerId, networkFoundMessage.arg2);
        assertScanResultsEquals(expected,
                ((WifiScanner.ParcelableScanResults) networkFoundMessage.obj).getResults());
    }

    private void verifyPnoNetworkFoundReceived(InOrder order, Handler handler, int listenerId,
            ScanResult[] expected) {
        Message scanResultMessage = verifyHandleMessageAndGetMessage(order, handler,
                WifiScanner.CMD_PNO_NETWORK_FOUND);
        assertPnoNetworkFoundMessage(listenerId, expected, scanResultMessage);
    }

    private void expectSuccessfulBackgroundScan(InOrder order,
            WifiNative.ScanSettings nativeSettings, ScanResults results) {
        when(mWifiScannerImpl.startBatchedScan(any(WifiNative.ScanSettings.class),
                any(WifiNative.ScanEventHandler.class))).thenReturn(true);
        mLooper.dispatchAll();
        WifiNative.ScanEventHandler eventHandler = verifyStartBackgroundScan(order, nativeSettings);
        WifiScanner.ScanData[] scanDatas = new WifiScanner.ScanData[1];
        scanDatas[0] = results.getScanData();
        for (ScanResult fullScanResult : results.getRawScanResults()) {
            eventHandler.onFullScanResult(fullScanResult, 0);
        }
        when(mWifiScannerImpl.getLatestBatchedScanResults(anyBoolean())).thenReturn(scanDatas);
        eventHandler.onScanStatus(WifiNative.WIFI_SCAN_RESULTS_AVAILABLE);
        mLooper.dispatchAll();
    }

    private void expectHwPnoScanWithNoBackgroundScan(InOrder order, Handler handler, int requestId,
            WifiNative.PnoSettings nativeSettings, ScanResults results) {
        when(mWifiScannerImpl.isHwPnoSupported(anyBoolean())).thenReturn(true);
        when(mWifiScannerImpl.shouldScheduleBackgroundScanForHwPno()).thenReturn(false);

        when(mWifiScannerImpl.setHwPnoList(any(WifiNative.PnoSettings.class),
                any(WifiNative.PnoEventHandler.class))).thenReturn(true);
        mLooper.dispatchAll();
        WifiNative.PnoEventHandler eventHandler = verifyHwPno(order, nativeSettings);
        verifySuccessfulResponse(order, handler, requestId);
        eventHandler.onPnoNetworkFound(results.getRawScanResults());
        mLooper.dispatchAll();
    }

    private void expectHwPnoScanWithBackgroundScan(InOrder order, Handler handler, int requestId,
            WifiNative.ScanSettings nativeScanSettings,
            WifiNative.PnoSettings nativePnoSettings, ScanResults results) {
        when(mWifiScannerImpl.isHwPnoSupported(anyBoolean())).thenReturn(true);
        when(mWifiScannerImpl.shouldScheduleBackgroundScanForHwPno()).thenReturn(true);

        when(mWifiScannerImpl.setHwPnoList(any(WifiNative.PnoSettings.class),
                any(WifiNative.PnoEventHandler.class))).thenReturn(true);
        when(mWifiScannerImpl.startBatchedScan(any(WifiNative.ScanSettings.class),
                any(WifiNative.ScanEventHandler.class))).thenReturn(true);
        mLooper.dispatchAll();
        WifiNative.PnoEventHandler eventHandler = verifyHwPno(order, nativePnoSettings);
        verifySuccessfulResponse(order, handler, requestId);
        verifyStartBackgroundScan(order, nativeScanSettings);
        eventHandler.onPnoNetworkFound(results.getRawScanResults());
        mLooper.dispatchAll();
    }

    private void expectHwPnoScanWithBackgroundScanWithNoIE(InOrder order, Handler handler,
            int requestId, WifiNative.ScanSettings nativeBackgroundScanSettings,
            WifiNative.ScanSettings nativeSingleScanSettings,
            WifiNative.PnoSettings nativePnoSettings, ScanResults results) {
        when(mWifiScannerImpl.startSingleScan(any(WifiNative.ScanSettings.class),
                any(WifiNative.ScanEventHandler.class))).thenReturn(true);

        expectHwPnoScanWithBackgroundScan(order, handler, requestId, nativeBackgroundScanSettings,
                nativePnoSettings, results);
        WifiNative.ScanEventHandler eventHandler =
                verifyStartSingleScan(order, nativeSingleScanSettings);
        when(mWifiScannerImpl.getLatestSingleScanResults()).thenReturn(results.getScanData());
        eventHandler.onScanStatus(WifiNative.WIFI_SCAN_RESULTS_AVAILABLE);
        mLooper.dispatchAll();
    }
    private void expectSwPnoScan(InOrder order, WifiNative.ScanSettings nativeScanSettings,
            ScanResults results) {
        when(mWifiScannerImpl.isHwPnoSupported(anyBoolean())).thenReturn(false);
        when(mWifiScannerImpl.shouldScheduleBackgroundScanForHwPno()).thenReturn(true);

        expectSuccessfulBackgroundScan(order, nativeScanSettings, results);
    }

    /**
     * Tests wificond PNO scan when the PNO scan results contain IE info. This ensures that the
     * PNO scan results are plumbed back to the client as a PNO network found event.
     */
    @Test
    public void testSuccessfulHwPnoScanWithNoBackgroundScan() throws Exception {
        startServiceAndLoadDriver();
        mWifiScanningServiceImpl.setWifiHandlerLogForTest(mLog);
        Handler handler = mock(Handler.class);
        BidirectionalAsyncChannel controlChannel = connectChannel(handler);
        InOrder order = inOrder(handler, mWifiScannerImpl);
        int requestId = 12;

        ScanResults scanResults = createScanResultsForPno();
        Pair<WifiScanner.ScanSettings, WifiNative.ScanSettings> scanSettings =
                createScanSettingsForHwPno();
        Pair<WifiScanner.PnoSettings, WifiNative.PnoSettings> pnoSettings =
                createPnoSettings(scanResults);

        sendPnoScanRequest(controlChannel, requestId, scanSettings.first, pnoSettings.first);
        expectHwPnoScanWithNoBackgroundScan(order, handler, requestId, pnoSettings.second,
                scanResults);
        verifyPnoNetworkFoundReceived(order, handler, requestId, scanResults.getRawScanResults());
    }

    /**
     * Tests Hal ePNO scan when the PNO scan results contain IE info. This ensures that the
     * PNO scan results are plumbed back to the client as a PNO network found event.
     */
    @Test
    public void testSuccessfulHwPnoScanWithBackgroundScan() throws Exception {
        startServiceAndLoadDriver();
        mWifiScanningServiceImpl.setWifiHandlerLogForTest(mLog);
        Handler handler = mock(Handler.class);
        BidirectionalAsyncChannel controlChannel = connectChannel(handler);
        InOrder order = inOrder(handler, mWifiScannerImpl);
        int requestId = 12;

        ScanResults scanResults = createScanResultsForPno();
        Pair<WifiScanner.ScanSettings, WifiNative.ScanSettings> scanSettings =
                createScanSettingsForHwPno();
        Pair<WifiScanner.PnoSettings, WifiNative.PnoSettings> pnoSettings =
                createPnoSettings(scanResults);

        sendPnoScanRequest(controlChannel, requestId, scanSettings.first, pnoSettings.first);
        expectHwPnoScanWithBackgroundScan(order, handler, requestId, scanSettings.second,
                pnoSettings.second, scanResults);
        verifyPnoNetworkFoundReceived(order, handler, requestId, scanResults.getRawScanResults());
    }

    /**
     * Tests Hal ePNO scan when the PNO scan results don't contain IE info. This ensures that the
     * single scan results are plumbed back to the client as a PNO network found event.
     */
    @Test
    public void testSuccessfulHwPnoScanWithBackgroundScanWithNoIE() throws Exception {
        startServiceAndLoadDriver();
        mWifiScanningServiceImpl.setWifiHandlerLogForTest(mLog);
        Handler handler = mock(Handler.class);
        BidirectionalAsyncChannel controlChannel = connectChannel(handler);
        InOrder order = inOrder(handler, mWifiScannerImpl);
        int requestId = 12;

        ScanResults scanResults = createScanResultsForPnoWithNoIE();
        Pair<WifiScanner.ScanSettings, WifiNative.ScanSettings> scanSettings =
                createScanSettingsForHwPno();
        Pair<WifiScanner.PnoSettings, WifiNative.PnoSettings> pnoSettings =
                createPnoSettings(scanResults);

        sendPnoScanRequest(controlChannel, requestId, scanSettings.first, pnoSettings.first);
        expectHwPnoScanWithBackgroundScanWithNoIE(order, handler, requestId, scanSettings.second,
                computeSingleScanNativeSettings(scanSettings.first), pnoSettings.second,
                scanResults);

        ArrayList<ScanResult> sortScanList =
                new ArrayList<ScanResult>(Arrays.asList(scanResults.getRawScanResults()));
        Collections.sort(sortScanList, WifiScannerImpl.SCAN_RESULT_SORT_COMPARATOR);
        verifyPnoNetworkFoundReceived(order, handler, requestId,
                sortScanList.toArray(new ScanResult[sortScanList.size()]));
    }

    /**
     * Tests SW PNO scan. This ensures that the background scan results are plumbed back to the
     * client as a PNO network found event.
     */
    @Test
    public void testSuccessfulSwPnoScan() throws Exception {
        startServiceAndLoadDriver();
        mWifiScanningServiceImpl.setWifiHandlerLogForTest(mLog);
        Handler handler = mock(Handler.class);
        BidirectionalAsyncChannel controlChannel = connectChannel(handler);
        InOrder order = inOrder(handler, mWifiScannerImpl);
        int requestId = 12;

        ScanResults scanResults = createScanResultsForPno();
        Pair<WifiScanner.ScanSettings, WifiNative.ScanSettings> scanSettings =
                createScanSettingsForSwPno();
        Pair<WifiScanner.PnoSettings, WifiNative.PnoSettings> pnoSettings =
                createPnoSettings(scanResults);

        sendPnoScanRequest(controlChannel, requestId, scanSettings.first, pnoSettings.first);
        expectSwPnoScan(order, scanSettings.second, scanResults);
        verifyPnoNetworkFoundReceived(order, handler, requestId, scanResults.getRawScanResults());
    }

    /**
     * Tries to simulate the race scenario where a client is disconnected immediately after single
     * scan request is sent to |SingleScanStateMachine|.
     */
    @Test
    public void processSingleScanRequestAfterDisconnect() throws Exception {
        startServiceAndLoadDriver();
        mWifiScanningServiceImpl.setWifiHandlerLogForTest(mLog);
        BidirectionalAsyncChannel controlChannel = connectChannel(mock(Handler.class));
        mLooper.dispatchAll();

        // Send the single scan request and then send the disconnect immediately after.
        WifiScanner.ScanSettings requestSettings = createRequest(WifiScanner.WIFI_BAND_BOTH, 0,
                0, 20, WifiScanner.REPORT_EVENT_AFTER_EACH_SCAN);
        int requestId = 10;

        sendSingleScanRequest(controlChannel, requestId, requestSettings, null);
        // Can't call |disconnect| here because that sends |CMD_CHANNEL_DISCONNECT| followed by
        // |CMD_CHANNEL_DISCONNECTED|.
        controlChannel.sendMessage(Message.obtain(null, AsyncChannel.CMD_CHANNEL_DISCONNECTED,
                        AsyncChannel.STATUS_REMOTE_DISCONNECTION, 0, null));

        // Now process the above 2 actions. This should result in first processing the single scan
        // request (which forwards the request to SingleScanStateMachine) and then processing the
        // disconnect after.
        mLooper.dispatchAll();

        // Now check that we logged the invalid request.
        String serviceDump = dumpService();
        Pattern logLineRegex = Pattern.compile("^.+" + "singleScanInvalidRequest: "
                + "ClientInfo\\[unknown\\],Id=" + requestId + ",bad request$", Pattern.MULTILINE);
        assertTrue("dump did not contain log with ClientInfo[unknown]: " + serviceDump + "\n",
                logLineRegex.matcher(serviceDump).find());
    }

    /**
     * Tries to simulate the race scenario where a client is disconnected immediately after single
     * scan request is sent to |SingleScanStateMachine|.
     */
    @Test
    public void sendScanRequestAfterUnsuccessfulSend() throws Exception {
        WifiScanner.ScanSettings requestSettings = createRequest(WifiScanner.WIFI_BAND_BOTH, 0,
                0, 20, WifiScanner.REPORT_EVENT_AFTER_EACH_SCAN);
        int requestId = 9;

        startServiceAndLoadDriver();
        mWifiScanningServiceImpl.setWifiHandlerLogForTest(mLog);
        Handler handler = mock(Handler.class);
        BidirectionalAsyncChannel controlChannel = connectChannel(handler);
        mLooper.dispatchAll();

        when(mWifiScannerImpl.startSingleScan(any(WifiNative.ScanSettings.class),
                        any(WifiNative.ScanEventHandler.class))).thenReturn(true);
        ScanResults results = ScanResults.create(0, 2400);
        when(mWifiScannerImpl.getLatestSingleScanResults())
                .thenReturn(results.getRawScanData());

        InOrder order = inOrder(mWifiScannerImpl, handler);

        sendSingleScanRequest(controlChannel, requestId, requestSettings, null);
        mLooper.dispatchAll();
        WifiNative.ScanEventHandler eventHandler1 = verifyStartSingleScan(order,
                computeSingleScanNativeSettings(requestSettings));
        verifySuccessfulResponse(order, handler, requestId);

        eventHandler1.onScanStatus(WifiNative.WIFI_SCAN_RESULTS_AVAILABLE);
        mLooper.dispatchAll();
        verifyScanResultsReceived(order, handler, requestId, results.getScanData());
        verifySingleScanCompletedReceived(order, handler, requestId);
        verifyNoMoreInteractions(handler);

        controlChannel.sendMessage(Message.obtain(null, AsyncChannel.CMD_CHANNEL_DISCONNECTED,
                        AsyncChannel.STATUS_SEND_UNSUCCESSFUL, 0, null));
        mLooper.dispatchAll();

        sendSingleScanRequest(controlChannel, requestId, requestSettings, null);
        mLooper.dispatchAll();
        WifiNative.ScanEventHandler eventHandler2 = verifyStartSingleScan(order,
                computeSingleScanNativeSettings(requestSettings));
        verifySuccessfulResponse(order, handler, requestId);

        eventHandler2.onScanStatus(WifiNative.WIFI_SCAN_RESULTS_AVAILABLE);
        mLooper.dispatchAll();
        verifyScanResultsReceived(order, handler, requestId, results.getScanData());
        verifySingleScanCompletedReceived(order, handler, requestId);
        verifyNoMoreInteractions(handler);
    }
}