summaryrefslogtreecommitdiff
path: root/tests/tests/wifi/src/android/net/wifi/cts/WifiManagerTest.java
blob: aaa61439b6780168526b09fc91a6514c67ae1600 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
5713
5714
5715
5716
5717
5718
5719
5720
5721
5722
5723
5724
5725
5726
5727
5728
5729
5730
5731
5732
5733
5734
5735
5736
5737
5738
5739
5740
5741
5742
5743
5744
5745
5746
5747
5748
5749
5750
5751
5752
5753
5754
5755
5756
5757
5758
5759
5760
5761
5762
5763
5764
5765
5766
5767
5768
5769
5770
5771
5772
5773
5774
5775
5776
5777
5778
5779
5780
5781
5782
5783
5784
5785
5786
5787
5788
5789
5790
5791
5792
5793
5794
5795
5796
5797
5798
5799
5800
5801
5802
5803
5804
5805
5806
5807
5808
5809
5810
5811
5812
5813
5814
5815
5816
5817
5818
5819
5820
5821
5822
5823
5824
5825
5826
5827
5828
5829
5830
5831
5832
5833
5834
5835
5836
5837
5838
5839
5840
5841
5842
5843
5844
5845
5846
5847
5848
5849
5850
5851
5852
5853
5854
5855
5856
5857
5858
5859
5860
5861
5862
5863
5864
5865
5866
5867
5868
5869
5870
5871
5872
5873
5874
5875
5876
5877
5878
5879
5880
5881
5882
5883
5884
5885
5886
5887
5888
5889
5890
5891
5892
5893
5894
5895
5896
5897
5898
5899
5900
5901
5902
5903
5904
5905
5906
5907
5908
5909
5910
5911
5912
5913
5914
5915
5916
5917
5918
5919
5920
5921
5922
5923
5924
5925
5926
5927
5928
5929
5930
5931
5932
5933
5934
5935
5936
5937
5938
5939
5940
5941
5942
5943
5944
5945
5946
5947
5948
5949
5950
5951
5952
5953
5954
5955
5956
5957
5958
5959
5960
5961
5962
5963
5964
5965
5966
5967
5968
5969
5970
5971
5972
5973
5974
5975
5976
5977
5978
5979
5980
5981
5982
5983
5984
5985
5986
5987
5988
5989
5990
5991
5992
5993
5994
5995
5996
5997
5998
5999
6000
6001
6002
6003
6004
6005
6006
6007
6008
6009
6010
6011
6012
6013
6014
6015
6016
6017
6018
6019
6020
6021
6022
6023
6024
6025
6026
6027
6028
6029
6030
6031
6032
6033
6034
6035
6036
6037
6038
6039
6040
6041
6042
6043
6044
6045
6046
6047
6048
6049
6050
6051
6052
6053
6054
6055
6056
6057
6058
6059
6060
6061
6062
6063
6064
6065
6066
6067
6068
6069
6070
6071
6072
6073
6074
6075
6076
6077
6078
6079
6080
6081
6082
6083
6084
6085
6086
6087
6088
6089
6090
6091
6092
6093
6094
6095
6096
6097
6098
6099
6100
6101
6102
6103
6104
6105
6106
6107
6108
6109
6110
6111
6112
6113
6114
6115
6116
6117
6118
6119
6120
6121
6122
6123
6124
6125
6126
6127
6128
6129
6130
6131
6132
6133
6134
6135
6136
6137
6138
6139
6140
6141
6142
6143
6144
6145
6146
6147
6148
6149
6150
6151
6152
6153
6154
6155
6156
6157
6158
6159
6160
6161
6162
6163
6164
6165
6166
6167
6168
6169
6170
6171
6172
6173
6174
6175
6176
6177
6178
6179
6180
6181
6182
6183
6184
6185
6186
6187
6188
6189
6190
6191
6192
6193
6194
6195
6196
6197
6198
6199
6200
6201
6202
6203
6204
6205
6206
6207
6208
6209
6210
6211
6212
6213
6214
6215
6216
6217
6218
6219
6220
6221
6222
6223
6224
6225
6226
6227
6228
6229
6230
6231
6232
6233
6234
6235
6236
6237
6238
6239
6240
6241
6242
6243
6244
6245
6246
6247
6248
6249
6250
6251
6252
6253
6254
6255
6256
6257
6258
6259
6260
6261
6262
6263
6264
6265
6266
6267
6268
6269
6270
6271
6272
6273
6274
6275
6276
6277
6278
6279
6280
/*
 * Copyright (C) 2009 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 android.net.wifi.cts;

import static android.content.Context.RECEIVER_EXPORTED;
import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
import static android.net.NetworkCapabilities.TRANSPORT_WIFI;
import static android.net.wifi.SoftApCapability.SOFTAP_FEATURE_ACS_OFFLOAD;
import static android.net.wifi.WifiAvailableChannel.OP_MODE_SAP;
import static android.net.wifi.WifiAvailableChannel.OP_MODE_STA;
import static android.net.wifi.WifiAvailableChannel.OP_MODE_WIFI_DIRECT_GO;
import static android.net.wifi.WifiConfiguration.INVALID_NETWORK_ID;
import static android.net.wifi.WifiManager.COEX_RESTRICTION_SOFTAP;
import static android.net.wifi.WifiManager.COEX_RESTRICTION_WIFI_AWARE;
import static android.net.wifi.WifiManager.COEX_RESTRICTION_WIFI_DIRECT;
import static android.net.wifi.WifiScanner.WIFI_BAND_24_GHZ;

import static com.google.common.truth.Truth.assertThat;
import static com.google.common.truth.Truth.assertWithMessage;

import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertThrows;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.junit.Assume.assumeTrue;

import android.annotation.NonNull;
import android.app.UiAutomation;
import android.app.admin.DevicePolicyManager;
import android.app.admin.WifiSsidPolicy;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.ConnectivityManager;
import android.net.MacAddress;
import android.net.Network;
import android.net.NetworkCapabilities;
import android.net.NetworkInfo;
import android.net.NetworkRequest;
import android.net.TetheringManager;
import android.net.Uri;
import android.net.wifi.CoexUnsafeChannel;
import android.net.wifi.QosPolicyParams;
import android.net.wifi.ScanResult;
import android.net.wifi.SoftApCapability;
import android.net.wifi.SoftApConfiguration;
import android.net.wifi.SoftApInfo;
import android.net.wifi.WifiAvailableChannel;
import android.net.wifi.WifiClient;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiEnterpriseConfig;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.SubsystemRestartTrackingCallback;
import android.net.wifi.WifiNetworkConnectionStatistics;
import android.net.wifi.WifiNetworkSelectionConfig;
import android.net.wifi.WifiNetworkSuggestion;
import android.net.wifi.WifiScanner;
import android.net.wifi.WifiSsid;
import android.net.wifi.hotspot2.ConfigParser;
import android.net.wifi.hotspot2.OsuProvider;
import android.net.wifi.hotspot2.PasspointConfiguration;
import android.net.wifi.hotspot2.ProvisioningCallback;
import android.net.wifi.hotspot2.pps.Credential;
import android.net.wifi.hotspot2.pps.HomeSp;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerExecutor;
import android.os.HandlerThread;
import android.os.PowerManager;
import android.os.Process;
import android.os.SystemClock;
import android.os.SystemProperties;
import android.os.UserHandle;
import android.platform.test.annotations.AppModeFull;
import android.platform.test.annotations.AsbSecurityTest;
import android.provider.DeviceConfig;
import android.provider.Settings;
import android.support.test.uiautomator.UiDevice;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import android.util.ArraySet;
import android.util.Log;
import android.util.SparseArray;
import android.util.SparseIntArray;

import androidx.test.filters.SdkSuppress;
import androidx.test.platform.app.InstrumentationRegistry;

import com.android.compatibility.common.util.ApiLevelUtil;
import com.android.compatibility.common.util.FeatureUtil;
import com.android.compatibility.common.util.PollingCheck;
import com.android.compatibility.common.util.PropertyUtil;
import com.android.compatibility.common.util.ShellIdentityUtils;
import com.android.compatibility.common.util.ThrowingRunnable;
import com.android.modules.utils.build.SdkLevel;
import com.android.net.module.util.MacAddressUtils;

import com.google.common.collect.Range;

import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.reflect.Constructor;
import java.net.HttpURLConnection;
import java.net.InetAddress;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicReference;
import java.util.function.BiConsumer;
import java.util.function.Consumer;
import java.util.stream.Collectors;

@AppModeFull(reason = "Cannot get WifiManager in instant app mode")
public class WifiManagerTest extends WifiJUnit4TestBase {
    private static Context sContext;
    private static boolean sShouldRunTest = false;

    private static class MySync {
        int expectedState = STATE_NULL;
    }

    private static WifiManager sWifiManager;
    private static ConnectivityManager sConnectivityManager;
    private static TetheringManager sTetheringManager;
    private static MySync sMySync;
    private static List<ScanResult> sScanResults = null;
    private static NetworkInfo sNetworkInfo =
            new NetworkInfo(ConnectivityManager.TYPE_WIFI, TelephonyManager.NETWORK_TYPE_UNKNOWN,
                    "wifi", "unknown");
    private final Object mLock = new Object();
    private static UiDevice sUiDevice;
    private static boolean sWasVerboseLoggingEnabled;
    private static boolean sWasScanThrottleEnabled;
    private static SoftApConfiguration sOriginalSoftApConfig = null;
    private static PowerManager sPowerManager;
    private static PowerManager.WakeLock sWakeLock;
    // Please refer to WifiManager
    private static final int MIN_RSSI = -100;
    private static final int MAX_RSSI = -55;

    private static final int STATE_NULL = 0;
    private static final int STATE_WIFI_CHANGING = 1;
    private static final int STATE_WIFI_ENABLED = 2;
    private static final int STATE_WIFI_DISABLED = 3;
    private static final int STATE_SCANNING = 4;
    private static final int STATE_SCAN_DONE = 5;

    private static final String TAG = "WifiManagerTest";
    private static final String SSID1 = "\"WifiManagerTest\"";
    private static final String BOOT_DEFAULT_WIFI_COUNTRY_CODE = "ro.boot.wificountrycode";
    // A full single scan duration is typically about 6-7 seconds, but
    // depending on devices it takes more time (9-11 seconds). For a
    // safety margin, the test waits for 15 seconds.
    private static final int SCAN_TEST_WAIT_DURATION_MS = 15_000;
    private static final int TEST_WAIT_DURATION_MS = 10_000;
    private static final int WIFI_CONNECT_TIMEOUT_MILLIS = 30_000;
    private static final int WIFI_PNO_CONNECT_TIMEOUT_MILLIS = 90_000;
    private static final int WAIT_MSEC = 60;
    private static final int DURATION_SCREEN_TOGGLE = 2000;
    private static final int DURATION_SETTINGS_TOGGLE = 1_000;
    private static final int DURATION_SOFTAP_START_MS = 6_000;
    private static final int WIFI_SCAN_TEST_CACHE_DELAY_MILLIS = 3 * 60 * 1000;
    private static final String DEVICE_CONFIG_NAMESPACE = "wifi";

    private static final int ENFORCED_NUM_NETWORK_SUGGESTIONS_PER_APP = 50;

    private static final String TEST_PAC_URL = "http://www.example.com/proxy.pac";
    private static final String MANAGED_PROVISIONING_PACKAGE_NAME
            = "com.android.managedprovisioning";

    private static final String TEST_SSID_UNQUOTED = "testSsid1";
    private static final String TEST_IP_ADDRESS = "192.168.5.5";
    private static final String TEST_MAC_ADDRESS = "aa:bb:cc:dd:ee:ff";
    private static final MacAddress TEST_MAC = MacAddress.fromString(TEST_MAC_ADDRESS);
    private static final String TEST_PASSPHRASE = "passphrase";
    private static final String PASSPOINT_INSTALLATION_FILE_WITH_CA_CERT =
            "assets/ValidPasspointProfile.base64";
    private static final String TYPE_WIFI_CONFIG = "application/x-wifi-config";
    private static final String TEST_PSK_CAP = "[RSN-PSK-CCMP]";
    private static final String TEST_BSSID = "00:01:02:03:04:05";
    private static final String TEST_COUNTRY_CODE = "JP";
    private static final String TEST_DOM_SUBJECT_MATCH = "domSubjectMatch";
    private static final int TEST_SUB_ID = 2;
    private static final int EID_VSA = 221; // Copied from ScanResult.InformationElement

    private static final int TEST_LINK_LAYER_STATS_POLLING_INTERVAL_MS = 1000;
    private static final List<ScanResult.InformationElement> TEST_VENDOR_ELEMENTS =
            new ArrayList<>(Arrays.asList(
                    new ScanResult.InformationElement(221, 0, new byte[]{ 1, 2, 3, 4 }),
                    new ScanResult.InformationElement(
                            221,
                            0,
                            new byte[]{ (byte) 170, (byte) 187, (byte) 204, (byte) 221 })
            ));
    private static final int[] TEST_RSSI2_THRESHOLDS = {-81, -79, -73, -60};
    private static final int[] TEST_RSSI5_THRESHOLDS = {-80, -77, -71, -55};
    private static final int[] TEST_RSSI6_THRESHOLDS = {-79, -72, -65, -55};
    private static final SparseArray<Integer> TEST_FREQUENCY_WEIGHTS = new SparseArray<>();

    private IntentFilter mIntentFilter;
    private static final BroadcastReceiver sReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (action.equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
                synchronized (sMySync) {
                    if (intent.getBooleanExtra(WifiManager.EXTRA_RESULTS_UPDATED, false)) {
                        sScanResults = sWifiManager.getScanResults();
                    } else {
                        sScanResults = null;
                    }
                    sMySync.expectedState = STATE_SCAN_DONE;
                    sMySync.notifyAll();
                }
            } else if (action.equals(WifiManager.WIFI_STATE_CHANGED_ACTION)) {
                int newState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE,
                        WifiManager.WIFI_STATE_UNKNOWN);
                synchronized (sMySync) {
                    if (newState == WifiManager.WIFI_STATE_ENABLED) {
                        Log.d(TAG, "*** New WiFi state is ENABLED ***");
                        sMySync.expectedState = STATE_WIFI_ENABLED;
                        sMySync.notifyAll();
                    } else if (newState == WifiManager.WIFI_STATE_DISABLED) {
                        Log.d(TAG, "*** New WiFi state is DISABLED ***");
                        sMySync.expectedState = STATE_WIFI_DISABLED;
                        sMySync.notifyAll();
                    }
                }
            } else if (action.equals(WifiManager.NETWORK_STATE_CHANGED_ACTION)) {
                synchronized (sMySync) {
                    sNetworkInfo =
                            (NetworkInfo) intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
                    if (sNetworkInfo.getState() == NetworkInfo.State.CONNECTED) {
                        sMySync.notifyAll();
                    }
                }
            }
        }
    };

    private static class TestProvisioningCallback extends ProvisioningCallback {
        private final Object mObject;
        // Initialize with an invalid status value (0)
        public int mProvisioningStatus = 0;
        // Initialize with an invalid status value (0)
        public int mProvisioningFailureStatus = 0;
        public boolean mProvisioningComplete = false;


        TestProvisioningCallback(Object lock) {
            mObject = lock;
        }

        @Override
        public void onProvisioningFailure(int status) {
            synchronized (mObject) {
                mProvisioningFailureStatus = status;
                mObject.notify();
            }
        }

        @Override
        public void onProvisioningStatus(int status) {
            synchronized (mObject) {
                mProvisioningStatus = status;
                mObject.notify();
            }
        }

        @Override
        public void onProvisioningComplete() {
            mProvisioningComplete = true;
        }
    }

    private static class TestSubsystemRestartTrackingCallback
            extends SubsystemRestartTrackingCallback {
        private final Object mObject;

        public int mSubsystemRestartStatus = 0; // 0: nada, 1: restarting, 2: restarted

        TestSubsystemRestartTrackingCallback(Object lock) {
            mObject = lock;
        }
        @Override
        public void onSubsystemRestarting() {
            synchronized (mObject) {
                mSubsystemRestartStatus = 1;
                mObject.notify();
            }
        }

        @Override
        public void onSubsystemRestarted() {
            synchronized (mObject) {
                mSubsystemRestartStatus = 2;
                mObject.notify();

            }
        }
    }

    private static final String TEST_SSID = "TEST SSID";
    private static final String TEST_FRIENDLY_NAME = "Friendly Name";
    private static final Map<String, String> TEST_FRIENDLY_NAMES = new HashMap<>();
    static {
        TEST_FRIENDLY_NAMES.put("en", TEST_FRIENDLY_NAME);
        TEST_FRIENDLY_NAMES.put("kr", TEST_FRIENDLY_NAME + 2);
        TEST_FRIENDLY_NAMES.put("jp", TEST_FRIENDLY_NAME + 3);
    }

    private static final String TEST_SERVICE_DESCRIPTION = "Dummy Service";
    private static final Uri TEST_SERVER_URI = Uri.parse("https://test.com");
    private static final String TEST_NAI = "test.access.com";
    private static final List<Integer> TEST_METHOD_LIST =
            Arrays.asList(1 /* METHOD_SOAP_XML_SPP */);
    private final HandlerThread mHandlerThread = new HandlerThread("WifiManagerTest");
    protected final Executor mExecutor;
    {
        mHandlerThread.start();
        mExecutor = new HandlerExecutor(new Handler(mHandlerThread.getLooper()));
    }

    /**
     * Class which can be used to fetch an object out of a lambda. Fetching an object
     * out of a local scope with HIDL is a common operation (although usually it can
     * and should be avoided).
     *
     * @param <E> Inner object type.
     */
    public static final class Mutable<E> {
        public E value;

        public Mutable() {
            value = null;
        }

        public Mutable(E value) {
            this.value = value;
        }
    }

    @BeforeClass
    public static void setUpClass() throws Exception {
        sContext = InstrumentationRegistry.getInstrumentation().getContext();
        if (!WifiFeature.isWifiSupported(sContext)) {
            // skip the test if WiFi is not supported
            return;
        }
        sShouldRunTest = true;
        sPowerManager = sContext.getSystemService(PowerManager.class);
        sWakeLock = sPowerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
        sMySync = new MySync();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        intentFilter.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
        intentFilter.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
        intentFilter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
        intentFilter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        intentFilter.addAction(WifiManager.RSSI_CHANGED_ACTION);
        intentFilter.addAction(WifiManager.NETWORK_IDS_CHANGED_ACTION);
        intentFilter.addAction(WifiManager.ACTION_PICK_WIFI_NETWORK);
        intentFilter.setPriority(999);

        if (ApiLevelUtil.isAtLeast(Build.VERSION_CODES.UPSIDE_DOWN_CAKE)) {
            sContext.registerReceiver(sReceiver, intentFilter, RECEIVER_EXPORTED);
        } else {
            sContext.registerReceiver(sReceiver, intentFilter);
        }
        sWifiManager =  sContext.getSystemService(WifiManager.class);
        sConnectivityManager = sContext.getSystemService(ConnectivityManager.class);
        sTetheringManager = sContext.getSystemService(TetheringManager.class);
        assertThat(sWifiManager).isNotNull();
        assertThat(sTetheringManager).isNotNull();

        // turn on verbose logging for tests
        sWasVerboseLoggingEnabled = ShellIdentityUtils.invokeWithShellPermissions(
                () -> sWifiManager.isVerboseLoggingEnabled());
        ShellIdentityUtils.invokeWithShellPermissions(
                () -> sWifiManager.setVerboseLoggingEnabled(true));
        // Disable scan throttling for tests.
        sWasScanThrottleEnabled = ShellIdentityUtils.invokeWithShellPermissions(
                () -> sWifiManager.isScanThrottleEnabled());
        ShellIdentityUtils.invokeWithShellPermissions(
                () -> sWifiManager.setScanThrottleEnabled(false));

        sUiDevice = UiDevice.getInstance(InstrumentationRegistry.getInstrumentation());
        turnScreenOnNoDelay();

        synchronized (sMySync) {
            sMySync.expectedState = STATE_NULL;
        }

        List<WifiConfiguration> savedNetworks = ShellIdentityUtils.invokeWithShellPermissions(
                sWifiManager::getConfiguredNetworks);
        assertThat(savedNetworks.isEmpty()).isFalse();

        // Get original config for restore
        sOriginalSoftApConfig = ShellIdentityUtils.invokeWithShellPermissions(
                sWifiManager::getSoftApConfiguration);
    }

    @AfterClass
    public static void tearDownClass() throws Exception {
        if (!sShouldRunTest) {
            return;
        }
        if (!sWifiManager.isWifiEnabled()) {
            setWifiEnabled(true);
        }
        sContext.unregisterReceiver(sReceiver);
        ShellIdentityUtils.invokeWithShellPermissions(
                () -> sWifiManager.setScanThrottleEnabled(sWasScanThrottleEnabled));
        ShellIdentityUtils.invokeWithShellPermissions(
                () -> sWifiManager.setVerboseLoggingEnabled(sWasVerboseLoggingEnabled));
        // restore original softap config
        ShellIdentityUtils.invokeWithShellPermissions(
                () -> sWifiManager.setSoftApConfiguration(sOriginalSoftApConfig));
        Thread.sleep(TEST_WAIT_DURATION_MS);
        if (sWakeLock.isHeld()) {
            sWakeLock.release();
        }
    }

    @Before
    public void setUp() throws Exception {
        assumeTrue(sShouldRunTest);
        // enable Wifi
        if (!sWifiManager.isWifiEnabled()) setWifiEnabled(true);
        PollingCheck.check("Wifi not enabled", TEST_WAIT_DURATION_MS,
                () -> sWifiManager.isWifiEnabled());

        waitForConnection();
    }

    private static void setWifiEnabled(boolean enable) throws Exception {
        synchronized (sMySync) {
            if (sWifiManager.isWifiEnabled() != enable) {
                // the new state is different, we expect it to change
                sMySync.expectedState = STATE_WIFI_CHANGING;
            } else {
                sMySync.expectedState = (enable ? STATE_WIFI_ENABLED : STATE_WIFI_DISABLED);
            }
            ShellIdentityUtils.invokeWithShellPermissions(
                    () -> sWifiManager.setWifiEnabled(enable));
            waitForExpectedWifiState(enable);
        }
    }

    private static void waitForExpectedWifiState(boolean enabled) throws InterruptedException {
        synchronized (sMySync) {
            long timeout = System.currentTimeMillis() + TEST_WAIT_DURATION_MS;
            int expected = (enabled ? STATE_WIFI_ENABLED : STATE_WIFI_DISABLED);
            while (System.currentTimeMillis() < timeout
                    && sMySync.expectedState != expected) {
                sMySync.wait(WAIT_MSEC);
            }
        }
    }

    // Get the current scan status from sticky broadcast.
    private boolean isScanCurrentlyAvailable() {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(WifiManager.ACTION_WIFI_SCAN_AVAILABILITY_CHANGED);
        Intent intent = sContext.registerReceiver(null, intentFilter);
        assertNotNull(intent);
        if (intent.getAction().equals(WifiManager.ACTION_WIFI_SCAN_AVAILABILITY_CHANGED)) {
            return intent.getBooleanExtra(WifiManager.EXTRA_SCAN_AVAILABLE, false);
        }
        return false;
    }

    private void startScan() throws Exception {
        synchronized (sMySync) {
            sMySync.expectedState = STATE_SCANNING;
            sScanResults = null;
            assertTrue(sWifiManager.startScan());
            long timeout = System.currentTimeMillis() + SCAN_TEST_WAIT_DURATION_MS;
            while (System.currentTimeMillis() < timeout
                    && sMySync.expectedState == STATE_SCANNING) {
                sMySync.wait(WAIT_MSEC);
            }
        }
    }

    private void waitForNetworkInfoState(NetworkInfo.State state, int timeoutMillis)
            throws Exception {
        synchronized (sMySync) {
            if (sNetworkInfo.getState() == state) return;
            long timeout = System.currentTimeMillis() + timeoutMillis;
            while (System.currentTimeMillis() < timeout
                    && sNetworkInfo.getState() != state)
                sMySync.wait(WAIT_MSEC);
            assertEquals(state, sNetworkInfo.getState());
        }
    }

    private void waitForConnection(int timeoutMillis) throws Exception {
        waitForNetworkInfoState(NetworkInfo.State.CONNECTED, timeoutMillis);
    }

    private void waitForConnection() throws Exception {
        waitForNetworkInfoState(NetworkInfo.State.CONNECTED, WIFI_CONNECT_TIMEOUT_MILLIS);
    }

    private void waitForDisconnection() throws Exception {
        waitForNetworkInfoState(NetworkInfo.State.DISCONNECTED, TEST_WAIT_DURATION_MS);
    }

    private void ensureNotNetworkInfoState(NetworkInfo.State state) throws Exception {
        synchronized (sMySync) {
            long timeout = System.currentTimeMillis() + TEST_WAIT_DURATION_MS + WAIT_MSEC;
            while (System.currentTimeMillis() < timeout) {
                assertNotEquals(state, sNetworkInfo.getState());
                sMySync.wait(WAIT_MSEC);
            }
        }
    }

    private void ensureNotConnected() throws Exception {
        ensureNotNetworkInfoState(NetworkInfo.State.CONNECTED);
    }

    private void ensureNotDisconnected() throws Exception {
        ensureNotNetworkInfoState(NetworkInfo.State.DISCONNECTED);
    }

    private boolean existSSID(String ssid) {
        for (final WifiConfiguration w : sWifiManager.getConfiguredNetworks()) {
            if (w.SSID.equals(ssid))
                return true;
        }
        return false;
    }

    private int findConfiguredNetworks(String SSID, List<WifiConfiguration> networks) {
        for (final WifiConfiguration w : networks) {
            if (w.SSID.equals(SSID))
                return networks.indexOf(w);
        }
        return -1;
    }

    /**
     * Test creation of WifiManager Lock.
     */
    @Test
    public void testWifiManagerLock() throws Exception {
        final String TAG = "Test";
        assertNotNull(sWifiManager.createWifiLock(TAG));
        assertNotNull(sWifiManager.createWifiLock(WifiManager.WIFI_MODE_FULL, TAG));
    }

    /**
     * Test wifi scanning when Wifi is off and location scanning is turned on.
     */
    @Test
    public void testWifiManagerScanWhenWifiOffLocationTurnedOn() throws Exception {
        if (!hasLocationFeature()) {
            Log.d(TAG, "Skipping test as location is not supported");
            return;
        }
        if (!isLocationEnabled()) {
            fail("Please enable location for this test - since Marshmallow WiFi scan results are"
                    + " empty when location is disabled!");
        }
        runWithScanning(() -> {
            setWifiEnabled(false);
            Thread.sleep(TEST_WAIT_DURATION_MS);
            startScan();
            if (sWifiManager.isScanAlwaysAvailable() && isScanCurrentlyAvailable()) {
                // Make sure at least one AP is found.
                assertNotNull("mScanResult should not be null!", sScanResults);
                assertFalse("empty scan results!", sScanResults.isEmpty());
            } else {
                // Make sure no scan results are available.
                assertNull("mScanResult should be null!", sScanResults);
            }
            final String TAG = "Test";
            assertNotNull(sWifiManager.createWifiLock(TAG));
            assertNotNull(sWifiManager.createWifiLock(WifiManager.WIFI_MODE_FULL, TAG));
        }, true /* run with enabled*/);
    }

    /**
     * Restart WiFi subsystem - verify that privileged call fails.
     */
    @Test
    @SdkSuppress(minSdkVersion = Build.VERSION_CODES.S)
    public void testRestartWifiSubsystemShouldFailNoPermission() throws Exception {
        try {
            sWifiManager.restartWifiSubsystem();
            fail("The restartWifiSubsystem should not succeed - privileged call");
        } catch (SecurityException e) {
            // expected
        }
    }

    /**
     * Restart WiFi subsystem and verify transition through states.
     */
    @Test
    @SdkSuppress(minSdkVersion = Build.VERSION_CODES.S)
    public void testRestartWifiSubsystem() throws Exception {
        TestSubsystemRestartTrackingCallback callback =
                new TestSubsystemRestartTrackingCallback(mLock);
        UiAutomation uiAutomation = InstrumentationRegistry.getInstrumentation().getUiAutomation();
        try {
            uiAutomation.adoptShellPermissionIdentity();
            sWifiManager.registerSubsystemRestartTrackingCallback(mExecutor, callback);
            synchronized (mLock) {
                sWifiManager.restartWifiSubsystem();
                mLock.wait(TEST_WAIT_DURATION_MS);
            }
            assertEquals(callback.mSubsystemRestartStatus, 1); // 1: restarting
            waitForExpectedWifiState(false);
            assertFalse(sWifiManager.isWifiEnabled());
            synchronized (mLock) {
                mLock.wait(TEST_WAIT_DURATION_MS);
                assertEquals(callback.mSubsystemRestartStatus, 2); // 2: restarted
            }
            waitForExpectedWifiState(true);
            assertTrue(sWifiManager.isWifiEnabled());
        } finally {
            // cleanup
            sWifiManager.unregisterSubsystemRestartTrackingCallback(callback);
            uiAutomation.dropShellPermissionIdentity();
        }
    }

    /**
     * test point of wifiManager properties:
     * 1.enable properties
     * 2.DhcpInfo properties
     * 3.wifi state
     * 4.ConnectionInfo
     */
    @Test
    public void testWifiManagerProperties() throws Exception {
        setWifiEnabled(true);
        assertTrue(sWifiManager.isWifiEnabled());
        assertNotNull(sWifiManager.getDhcpInfo());
        assertEquals(WifiManager.WIFI_STATE_ENABLED, sWifiManager.getWifiState());
        sWifiManager.getConnectionInfo();
        setWifiEnabled(false);
        assertFalse(sWifiManager.isWifiEnabled());
    }

    /**
     * Test WiFi scan timestamp - fails when WiFi scan timestamps are inconsistent with
     * {@link SystemClock#elapsedRealtime()} on device.<p>
     * To run this test in cts-tradefed:
     * run cts --class android.net.wifi.cts.WifiManagerTest --method testWifiScanTimestamp
     */
    @Test
    @VirtualDeviceNotSupported
    public void testWifiScanTimestamp() throws Exception {
        if (!hasLocationFeature()) {
            Log.d(TAG, "Skipping test as location is not supported");
            return;
        }
        if (!isLocationEnabled()) {
            fail("Please enable location for this test - since Marshmallow WiFi scan results are"
                    + " empty when location is disabled!");
        }
        if (!sWifiManager.isWifiEnabled()) {
            setWifiEnabled(true);
        }
        // Make sure the scan timestamps are consistent with the device timestamp within the range
        // of WIFI_SCAN_TEST_CACHE_DELAY_MILLIS.
        startScan();
        // Make sure at least one AP is found.
        assertTrue("mScanResult should not be null. This may be due to a scan timeout",
                   sScanResults != null);
        assertFalse("empty scan results!", sScanResults.isEmpty());
        long nowMillis = SystemClock.elapsedRealtime();
        // Keep track of how many APs are fresh in one scan.
        int numFreshAps = 0;
        for (ScanResult result : sScanResults) {
            long scanTimeMillis = TimeUnit.MICROSECONDS.toMillis(result.timestamp);
            if (Math.abs(nowMillis - scanTimeMillis)  < WIFI_SCAN_TEST_CACHE_DELAY_MILLIS) {
                numFreshAps++;
            }
        }
        // At least half of the APs in the scan should be fresh.
        int numTotalAps = sScanResults.size();
        String msg = "Stale AP count: " + (numTotalAps - numFreshAps) + ", fresh AP count: "
                + numFreshAps;
        assertTrue(msg, numFreshAps * 2 >= sScanResults.size());
    }

    @Test
    public void testConvertBetweenChannelFrequencyMhz() throws Exception {
        int[] testFrequency_2G = {2412, 2437, 2462, 2484};
        int[] testFrequency_5G = {5180, 5220, 5540, 5745};
        int[] testFrequency_6G = {5955, 6435, 6535, 7115};
        int[] testFrequency_60G = {58320, 64800};
        SparseArray<int[]> testData = new SparseArray<>() {{
            put(ScanResult.WIFI_BAND_24_GHZ, testFrequency_2G);
            put(ScanResult.WIFI_BAND_5_GHZ, testFrequency_5G);
            put(ScanResult.WIFI_BAND_6_GHZ, testFrequency_6G);
            put(ScanResult.WIFI_BAND_60_GHZ, testFrequency_60G);
        }};

        for (int i = 0; i < testData.size(); i++) {
            for (int frequency : testData.valueAt(i)) {
                assertEquals(frequency, ScanResult.convertChannelToFrequencyMhzIfSupported(
                      ScanResult.convertFrequencyMhzToChannelIfSupported(frequency), testData.keyAt(i)));
            }
        }
    }

    // Return true if location is enabled.
    private boolean isLocationEnabled() {
        return Settings.Secure.getInt(sContext.getContentResolver(),
                Settings.Secure.LOCATION_MODE, Settings.Secure.LOCATION_MODE_OFF) !=
                Settings.Secure.LOCATION_MODE_OFF;
    }

    // Returns true if the device has location feature.
    private boolean hasLocationFeature() {
        return sContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_LOCATION);
    }

    private boolean hasAutomotiveFeature() {
        return sContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_AUTOMOTIVE);
    }

    private boolean hasWifiDirect() {
        return sContext.getPackageManager().hasSystemFeature(
                PackageManager.FEATURE_WIFI_DIRECT);
    }

    private boolean hasWifiAware() {
        return sContext.getPackageManager().hasSystemFeature(PackageManager.FEATURE_WIFI_AWARE);
    }

    @Test
    public void testSignal() {
        final int numLevels = 9;
        int expectLevel = 0;
        assertEquals(expectLevel, WifiManager.calculateSignalLevel(MIN_RSSI, numLevels));
        assertEquals(numLevels - 1, WifiManager.calculateSignalLevel(MAX_RSSI, numLevels));
        expectLevel = 4;
        assertEquals(expectLevel, WifiManager.calculateSignalLevel((MIN_RSSI + MAX_RSSI) / 2,
                numLevels));
        int rssiA = 4;
        int rssiB = 5;
        assertTrue(WifiManager.compareSignalLevel(rssiA, rssiB) < 0);
        rssiB = 4;
        assertTrue(WifiManager.compareSignalLevel(rssiA, rssiB) == 0);
        rssiA = 5;
        rssiB = 4;
        assertTrue(WifiManager.compareSignalLevel(rssiA, rssiB) > 0);
    }

    /**
     * Test that {@link WifiManager#calculateSignalLevel(int)} returns a value in the range
     * [0, {@link WifiManager#getMaxSignalLevel()}], and its value is monotonically increasing as
     * the RSSI increases.
     */
    @Test
    public void testCalculateSignalLevel() {
        int maxSignalLevel = sWifiManager.getMaxSignalLevel();

        int prevSignalLevel = 0;
        for (int rssi = -150; rssi <= 50; rssi++) {
            int signalLevel = sWifiManager.calculateSignalLevel(rssi);

            // between [0, maxSignalLevel]
            assertWithMessage("For RSSI=%s", rssi).that(signalLevel).isAtLeast(0);
            assertWithMessage("For RSSI=%s", rssi).that(signalLevel).isAtMost(maxSignalLevel);

            // calculateSignalLevel(rssi) <= calculateSignalLevel(rssi + 1)
            assertWithMessage("For RSSI=%s", rssi).that(signalLevel).isAtLeast(prevSignalLevel);
            prevSignalLevel = signalLevel;
        }
    }

    public class TestWifiVerboseLoggingStatusChangedListener implements
            WifiManager.WifiVerboseLoggingStatusChangedListener {
        public int numCalls;
        public boolean status;

        @Override
        public void onWifiVerboseLoggingStatusChanged(boolean enabled) {
            numCalls++;
            status = enabled;
        }
    }

    public class TestSoftApCallback implements WifiManager.SoftApCallback {
        Object softApLock;
        int currentState;
        int currentFailureReason;
        List<SoftApInfo> apInfoList = new ArrayList<>();
        SoftApInfo apInfoOnSingleApMode;
        Map<SoftApInfo, List<WifiClient>> apInfoClients = new HashMap<>();
        List<WifiClient> currentClientList;
        SoftApCapability currentSoftApCapability;
        MacAddress lastBlockedClientMacAddress;
        int lastBlockedClientReason;
        boolean onStateChangedCalled = false;
        boolean onSoftApCapabilityChangedCalled = false;
        boolean onConnectedClientCalled = false;
        boolean onConnectedClientChangedWithInfoCalled = false;
        boolean onBlockedClientConnectingCalled = false;
        int onSoftapInfoChangedCalledCount = 0;
        int onSoftapInfoChangedWithListCalledCount = 0;

        TestSoftApCallback(Object lock) {
            softApLock = lock;
        }

        public boolean getOnStateChangedCalled() {
            synchronized(softApLock) {
                return onStateChangedCalled;
            }
        }

        public int getOnSoftapInfoChangedCalledCount() {
            synchronized(softApLock) {
                return onSoftapInfoChangedCalledCount;
            }
        }

        public int getOnSoftApInfoChangedWithListCalledCount() {
            synchronized(softApLock) {
                return onSoftapInfoChangedWithListCalledCount;
            }
        }

        public boolean getOnSoftApCapabilityChangedCalled() {
            synchronized(softApLock) {
                return onSoftApCapabilityChangedCalled;
            }
        }

        public boolean getOnConnectedClientChangedWithInfoCalled() {
            synchronized(softApLock) {
                return onConnectedClientChangedWithInfoCalled;
            }
        }

        public boolean getOnConnectedClientCalled() {
            synchronized(softApLock) {
                return onConnectedClientCalled;
            }
        }

        public boolean getOnBlockedClientConnectingCalled() {
            synchronized(softApLock) {
                return onBlockedClientConnectingCalled;
            }
        }

        public int getCurrentState() {
            synchronized(softApLock) {
                return currentState;
            }
        }

        public int getCurrentStateFailureReason() {
            synchronized(softApLock) {
                return currentFailureReason;
            }
        }

        public List<WifiClient> getCurrentClientList() {
            synchronized(softApLock) {
                return new ArrayList<>(currentClientList);
            }
        }

        public SoftApInfo getCurrentSoftApInfo() {
            synchronized(softApLock) {
                return apInfoOnSingleApMode;
            }
        }

        public List<SoftApInfo> getCurrentSoftApInfoList() {
            synchronized(softApLock) {
                return new ArrayList<>(apInfoList);
            }
        }

        public SoftApCapability getCurrentSoftApCapability() {
            synchronized(softApLock) {
                return currentSoftApCapability;
            }
        }

        public MacAddress getLastBlockedClientMacAddress() {
            synchronized(softApLock) {
                return lastBlockedClientMacAddress;
            }
        }

        public int getLastBlockedClientReason() {
            synchronized(softApLock) {
                return lastBlockedClientReason;
            }
        }

        @Override
        public void onStateChanged(int state, int failureReason) {
            synchronized(softApLock) {
                currentState = state;
                currentFailureReason = failureReason;
                onStateChangedCalled = true;
            }
        }

        @Override
        public void onConnectedClientsChanged(List<WifiClient> clients) {
            synchronized(softApLock) {
                currentClientList = new ArrayList<>(clients);
                onConnectedClientCalled = true;
            }
        }

        @Override
        public void onConnectedClientsChanged(SoftApInfo info, List<WifiClient> clients) {
            synchronized(softApLock) {
                apInfoClients.put(info, clients);
                onConnectedClientChangedWithInfoCalled = true;
            }
        }

        @Override
        public void onInfoChanged(List<SoftApInfo> infoList) {
            synchronized(softApLock) {
                apInfoList = new ArrayList<>(infoList);
                onSoftapInfoChangedWithListCalledCount++;
            }
        }

        @Override
        public void onInfoChanged(SoftApInfo softApInfo) {
            synchronized(softApLock) {
                apInfoOnSingleApMode = softApInfo;
                onSoftapInfoChangedCalledCount++;
            }
        }

        @Override
        public void onCapabilityChanged(SoftApCapability softApCapability) {
            synchronized(softApLock) {
                currentSoftApCapability = softApCapability;
                onSoftApCapabilityChangedCalled = true;
            }
        }

        @Override
        public void onBlockedClientConnecting(WifiClient client, int blockedReason) {
            synchronized(softApLock) {
                lastBlockedClientMacAddress = client.getMacAddress();
                lastBlockedClientReason = blockedReason;
                onBlockedClientConnectingCalled = true;
            }
        }
    }

    private static class TestLocalOnlyHotspotCallback extends WifiManager.LocalOnlyHotspotCallback {
        Object hotspotLock;
        WifiManager.LocalOnlyHotspotReservation reservation = null;
        boolean onStartedCalled = false;
        boolean onStoppedCalled = false;
        boolean onFailedCalled = false;
        int failureReason = -1;

        TestLocalOnlyHotspotCallback(Object lock) {
            hotspotLock = lock;
        }

        @Override
        public void onStarted(WifiManager.LocalOnlyHotspotReservation r) {
            synchronized (hotspotLock) {
                reservation = r;
                onStartedCalled = true;
                hotspotLock.notify();
            }
        }

        @Override
        public void onStopped() {
            synchronized (hotspotLock) {
                onStoppedCalled = true;
                hotspotLock.notify();
            }
        }

        @Override
        public void onFailed(int reason) {
            synchronized (hotspotLock) {
                onFailedCalled = true;
                failureReason = reason;
                hotspotLock.notify();
            }
        }
    }

    private List<Integer> getSupportedSoftApBand(SoftApCapability capability) {
        List<Integer> supportedApBands = new ArrayList<>();
        if (sWifiManager.is24GHzBandSupported() && capability.areFeaturesSupported(
                SoftApCapability.SOFTAP_FEATURE_BAND_24G_SUPPORTED)) {
            supportedApBands.add(SoftApConfiguration.BAND_2GHZ);
        }
        if (sWifiManager.is5GHzBandSupported() && capability.areFeaturesSupported(
                SoftApCapability.SOFTAP_FEATURE_BAND_5G_SUPPORTED)) {
            supportedApBands.add(SoftApConfiguration.BAND_5GHZ);
        }
        if (sWifiManager.is6GHzBandSupported() && capability.areFeaturesSupported(
                SoftApCapability.SOFTAP_FEATURE_BAND_6G_SUPPORTED)) {
            supportedApBands.add(SoftApConfiguration.BAND_6GHZ);
        }
        if (sWifiManager.is60GHzBandSupported() && capability.areFeaturesSupported(
                SoftApCapability.SOFTAP_FEATURE_BAND_60G_SUPPORTED)) {
            supportedApBands.add(SoftApConfiguration.BAND_60GHZ);
        }
        return supportedApBands;
    }

    private TestLocalOnlyHotspotCallback startLocalOnlyHotspot() {
        // Location mode must be enabled for this test
        if (!isLocationEnabled()) {
            fail("Please enable location for this test");
        }

        TestExecutor executor = new TestExecutor();
        TestSoftApCallback lohsSoftApCallback = new TestSoftApCallback(mLock);
        UiAutomation uiAutomation = InstrumentationRegistry.getInstrumentation().getUiAutomation();
        List<Integer> supportedSoftApBands = new ArrayList<>();
        try {
            uiAutomation.adoptShellPermissionIdentity();
            verifyLohsRegisterSoftApCallback(executor, lohsSoftApCallback);
            supportedSoftApBands = getSupportedSoftApBand(
                    lohsSoftApCallback.getCurrentSoftApCapability());
        } catch (Exception ex) {
        } finally {
            // clean up
            unregisterLocalOnlyHotspotSoftApCallback(lohsSoftApCallback);
            uiAutomation.dropShellPermissionIdentity();
        }
        TestLocalOnlyHotspotCallback callback = new TestLocalOnlyHotspotCallback(mLock);
        synchronized (mLock) {
            try {
                sWifiManager.startLocalOnlyHotspot(callback, null);
                // now wait for callback
                mLock.wait(TEST_WAIT_DURATION_MS);
            } catch (InterruptedException e) {
            }
            // check if we got the callback
            assertTrue(callback.onStartedCalled);

            SoftApConfiguration softApConfig = callback.reservation.getSoftApConfiguration();
            assertNotNull(softApConfig);
            int securityType = softApConfig.getSecurityType();
            if (securityType == SoftApConfiguration.SECURITY_TYPE_OPEN
                    || securityType == SoftApConfiguration.SECURITY_TYPE_WPA2_PSK
                    || securityType == SoftApConfiguration.SECURITY_TYPE_WPA3_SAE_TRANSITION) {
                assertNotNull(softApConfig.toWifiConfiguration());
            } else {
                assertNull(softApConfig.toWifiConfiguration());
            }
            if (!hasAutomotiveFeature()) {
                assertEquals(supportedSoftApBands.size() > 0 ? supportedSoftApBands.get(0)
                        : SoftApConfiguration.BAND_2GHZ,
                        callback.reservation.getSoftApConfiguration().getBand());
            }
            assertFalse(callback.onFailedCalled);
            assertFalse(callback.onStoppedCalled);
        }
        return callback;
    }

    private void stopLocalOnlyHotspot(TestLocalOnlyHotspotCallback callback, boolean wifiEnabled) {
        synchronized (sMySync) {
            // we are expecting a new state
            sMySync.expectedState = STATE_WIFI_CHANGING;

            // now shut down LocalOnlyHotspot
            callback.reservation.close();

            try {
                waitForExpectedWifiState(wifiEnabled);
            } catch (InterruptedException e) { }
        }
    }

    /**
     * Verify that calls to startLocalOnlyHotspot succeed with proper permissions.
     *
     * Note: Location mode must be enabled for this test.
     */
    @Test
    public void testStartLocalOnlyHotspotSuccess() throws Exception {
        // check that softap mode is supported by the device
        if (!sWifiManager.isPortableHotspotSupported()) {
            return;
        }
        boolean wifiEnabled = sWifiManager.isWifiEnabled();
        TestLocalOnlyHotspotCallback callback = startLocalOnlyHotspot();

        // add sleep to avoid calling stopLocalOnlyHotspot before TetherController initialization.
        // TODO: remove this sleep as soon as b/124330089 is fixed.
        Log.d(TAG, "Sleeping for 2 seconds");
        Thread.sleep(2000);

        stopLocalOnlyHotspot(callback, wifiEnabled);

        // wifi should either stay on, or come back on
        assertEquals(wifiEnabled, sWifiManager.isWifiEnabled());
    }

    /**
     * Verify calls to deprecated API's all fail for non-settings apps targeting >= Q SDK.
     */
    @Test
    public void testDeprecatedApis() throws Exception {
        WifiConfiguration wifiConfiguration = new WifiConfiguration();
        wifiConfiguration.SSID = SSID1;
        wifiConfiguration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);

        assertEquals(INVALID_NETWORK_ID,
                sWifiManager.addNetwork(wifiConfiguration));
        assertEquals(INVALID_NETWORK_ID,
                sWifiManager.updateNetwork(wifiConfiguration));
        assertFalse(sWifiManager.enableNetwork(0, true));
        assertFalse(sWifiManager.disableNetwork(0));
        assertFalse(sWifiManager.removeNetwork(0));
        assertFalse(sWifiManager.disconnect());
        assertFalse(sWifiManager.reconnect());
        assertFalse(sWifiManager.reassociate());
        assertTrue(sWifiManager.getConfiguredNetworks().isEmpty());

        boolean wifiEnabled = sWifiManager.isWifiEnabled();
        // now we should fail to toggle wifi state.
        assertFalse(sWifiManager.setWifiEnabled(!wifiEnabled));
        Thread.sleep(TEST_WAIT_DURATION_MS);
        assertEquals(wifiEnabled, sWifiManager.isWifiEnabled());
    }

    /**
     * Test the WifiManager APIs that return whether a feature is supported.
     */
    @Test
    public void testGetSupportedFeatures() {
        if (!WifiBuildCompat.isPlatformOrWifiModuleAtLeastS(sContext)) {
            // Skip the test if wifi module version is older than S.
            return;
        }
        sWifiManager.isMakeBeforeBreakWifiSwitchingSupported();
        sWifiManager.isStaBridgedApConcurrencySupported();
        sWifiManager.isDualBandSimultaneousSupported();
        sWifiManager.isTidToLinkMappingNegotiationSupported();
    }

    /**
     * Verify non DO apps cannot call removeNonCallerConfiguredNetworks.
     */
    @Test
    public void testRemoveNonCallerConfiguredNetworksNotAllowed() {
        if (!WifiBuildCompat.isPlatformOrWifiModuleAtLeastS(sContext)) {
            // Skip the test if wifi module version is older than S.
            return;
        }
        try {
            sWifiManager.removeNonCallerConfiguredNetworks();
            fail("Expected security exception for non DO app");
        } catch (SecurityException e) {
        }
    }

    private WifiNetworkSelectionConfig buildTestNetworkSelectionConfig() {
        TEST_FREQUENCY_WEIGHTS.put(2400, WifiNetworkSelectionConfig.FREQUENCY_WEIGHT_LOW);
        TEST_FREQUENCY_WEIGHTS.put(6000, WifiNetworkSelectionConfig.FREQUENCY_WEIGHT_HIGH);

        return new WifiNetworkSelectionConfig.Builder()
                .setAssociatedNetworkSelectionOverride(
                        WifiNetworkSelectionConfig.ASSOCIATED_NETWORK_SELECTION_OVERRIDE_ENABLED)
                .setSufficiencyCheckEnabledWhenScreenOff(false)
                .setSufficiencyCheckEnabledWhenScreenOn(false)
                .setUserConnectChoiceOverrideEnabled(false)
                .setLastSelectionWeightEnabled(false)
                .setRssiThresholds(ScanResult.WIFI_BAND_24_GHZ, TEST_RSSI2_THRESHOLDS)
                .setRssiThresholds(ScanResult.WIFI_BAND_5_GHZ, TEST_RSSI5_THRESHOLDS)
                .setRssiThresholds(ScanResult.WIFI_BAND_6_GHZ, TEST_RSSI6_THRESHOLDS)
                .setFrequencyWeights(TEST_FREQUENCY_WEIGHTS)
                .build();
    }

    /**
     * Verify the invalid and valid usages of {@code WifiManager#setNetworkSelectionConfig}.
     */
    @SdkSuppress(minSdkVersion = Build.VERSION_CODES.TIRAMISU)
    @Test
    public void testSetNetworkSelectionConfig() throws Exception {
        AtomicReference<WifiNetworkSelectionConfig> config = new AtomicReference<>();
        Consumer<WifiNetworkSelectionConfig> listener = new Consumer<WifiNetworkSelectionConfig>() {
            @Override
            public void accept(WifiNetworkSelectionConfig value) {
                synchronized (mLock) {
                    config.set(value);
                    mLock.notify();
                }
            }
        };

        // cache current WifiNetworkSelectionConfig
        ShellIdentityUtils.invokeWithShellPermissions(
                () -> sWifiManager.getNetworkSelectionConfig(mExecutor, listener));
        synchronized (mLock) {
            mLock.wait(TEST_WAIT_DURATION_MS);
        }
        WifiNetworkSelectionConfig currentConfig = config.get();

        try {
            WifiNetworkSelectionConfig nsConfig = buildTestNetworkSelectionConfig();
            assertTrue(nsConfig.getAssociatedNetworkSelectionOverride()
                    == WifiNetworkSelectionConfig.ASSOCIATED_NETWORK_SELECTION_OVERRIDE_ENABLED);
            assertFalse(nsConfig.isSufficiencyCheckEnabledWhenScreenOff());
            assertFalse(nsConfig.isSufficiencyCheckEnabledWhenScreenOn());
            assertFalse(nsConfig.isUserConnectChoiceOverrideEnabled());
            assertFalse(nsConfig.isLastSelectionWeightEnabled());
            assertArrayEquals(TEST_RSSI2_THRESHOLDS,
                    nsConfig.getRssiThresholds(ScanResult.WIFI_BAND_24_GHZ));
            assertArrayEquals(TEST_RSSI5_THRESHOLDS,
                    nsConfig.getRssiThresholds(ScanResult.WIFI_BAND_5_GHZ));
            assertArrayEquals(TEST_RSSI6_THRESHOLDS,
                    nsConfig.getRssiThresholds(ScanResult.WIFI_BAND_6_GHZ));
            assertTrue(TEST_FREQUENCY_WEIGHTS.contentEquals(nsConfig.getFrequencyWeights()));
            assertThrows(SecurityException.class,
                    () -> sWifiManager.setNetworkSelectionConfig(nsConfig));
            ShellIdentityUtils.invokeWithShellPermissions(
                    () -> sWifiManager.setNetworkSelectionConfig(nsConfig));
            ShellIdentityUtils.invokeWithShellPermissions(
                    () -> sWifiManager.setNetworkSelectionConfig(
                            new WifiNetworkSelectionConfig.Builder().build()));
        } finally {
            // restore WifiNetworkSelectionConfig
            ShellIdentityUtils.invokeWithShellPermissions(
                    () -> sWifiManager.setNetworkSelectionConfig(currentConfig));
        }
    }

    /**
     * Verify the invalid and valid usages of {@code WifiManager#getNetworkSelectionConfig}.
     */
    @SdkSuppress(minSdkVersion = Build.VERSION_CODES.TIRAMISU, codeName = "Tiramisu")
    @Test
    public void testGetNetworkSelectionConfig() throws Exception {
        AtomicReference<WifiNetworkSelectionConfig> config = new AtomicReference<>();
        Consumer<WifiNetworkSelectionConfig> listener = new Consumer<WifiNetworkSelectionConfig>() {
            @Override
            public void accept(WifiNetworkSelectionConfig value) {
                synchronized (mLock) {
                    config.set(value);
                    mLock.notify();
                }
            }
        };

        // cache current WifiNetworkSelectionConfig
        ShellIdentityUtils.invokeWithShellPermissions(
                () -> sWifiManager.getNetworkSelectionConfig(mExecutor, listener));
        synchronized (mLock) {
            mLock.wait(TEST_WAIT_DURATION_MS);
        }
        WifiNetworkSelectionConfig currentConfig = config.get();

        try {
            // Test invalid inputs trigger IllegalArgumentException
            assertThrows("null executor should trigger exception", NullPointerException.class,
                    () -> sWifiManager.getNetworkSelectionConfig(null, listener));
            assertThrows("null listener should trigger exception", NullPointerException.class,
                    () -> sWifiManager.getNetworkSelectionConfig(mExecutor, null));

            // Test caller with no permission triggers SecurityException.
            assertThrows("No permission should trigger SecurityException", SecurityException.class,
                    () -> sWifiManager.getNetworkSelectionConfig(mExecutor, listener));

            // Test get/set WifiNetworkSelectionConfig
            WifiNetworkSelectionConfig nsConfig = buildTestNetworkSelectionConfig();
            ShellIdentityUtils.invokeWithShellPermissions(
                    () -> sWifiManager.setNetworkSelectionConfig(nsConfig));
            ShellIdentityUtils.invokeWithShellPermissions(
                    () -> sWifiManager.getNetworkSelectionConfig(mExecutor, listener));
            synchronized (mLock) {
                mLock.wait(TEST_WAIT_DURATION_MS);
            }
            assertTrue(config.get().equals(nsConfig));
        } finally {
            // restore WifiNetworkSelectionConfig
            ShellIdentityUtils.invokeWithShellPermissions(
                    () -> sWifiManager.setNetworkSelectionConfig(currentConfig));
        }
    }

    /**
     * Verify setting the screen-on connectivity scan delay.
     */
    @SdkSuppress(minSdkVersion = Build.VERSION_CODES.TIRAMISU)
    @Test
    public void testSetOneShotScreenOnConnectivityScanDelayMillis() {
        assertThrows(SecurityException.class,
                () -> sWifiManager.setOneShotScreenOnConnectivityScanDelayMillis(100));
        assertThrows(IllegalArgumentException.class, () -> {
            ShellIdentityUtils.invokeWithShellPermissions(
                    () -> sWifiManager.setOneShotScreenOnConnectivityScanDelayMillis(-1));
        });
        ShellIdentityUtils.invokeWithShellPermissions(
                () -> sWifiManager.setOneShotScreenOnConnectivityScanDelayMillis(10000));
        ShellIdentityUtils.invokeWithShellPermissions(
                () -> sWifiManager.setOneShotScreenOnConnectivityScanDelayMillis(0));
    }

    /**
     * Verify setting the scan schedule.
     */
    @SdkSuppress(minSdkVersion = Build.VERSION_CODES.TIRAMISU)
    @Test
    public void testSetScreenOnScanSchedule() {
        List<WifiManager.ScreenOnScanSchedule> schedules = new ArrayList<>();
        schedules.add(new WifiManager.ScreenOnScanSchedule(Duration.ofSeconds(20),
                WifiScanner.SCAN_TYPE_HIGH_ACCURACY));
        schedules.add(new WifiManager.ScreenOnScanSchedule(Duration.ofSeconds(40),
                WifiScanner.SCAN_TYPE_LOW_LATENCY));
        assertEquals(20, schedules.get(0).getScanInterval().toSeconds());
        assertEquals(40, schedules.get(1).getScanInterval().toSeconds());
        assertEquals(WifiScanner.SCAN_TYPE_HIGH_ACCURACY, schedules.get(0).getScanType());
        assertEquals(WifiScanner.SCAN_TYPE_LOW_LATENCY, schedules.get(1).getScanType());
        ShellIdentityUtils.invokeWithShellPermissions(
                () -> sWifiManager.setScreenOnScanSchedule(schedules));
        ShellIdentityUtils.invokeWithShellPermissions(
                () -> sWifiManager.setScreenOnScanSchedule(null));

        // Creating an invalid ScanSchedule should throw an exception
        assertThrows(IllegalArgumentException.class, () -> new WifiManager.ScreenOnScanSchedule(
                null, WifiScanner.SCAN_TYPE_HIGH_ACCURACY));
    }

    /**
     * Verify a normal app cannot set the scan schedule.
     */
    @SdkSuppress(minSdkVersion = Build.VERSION_CODES.TIRAMISU)
    @Test
    public void testSetScreenOnScanScheduleNoPermission() {
        assertThrows(SecurityException.class, () -> sWifiManager.setScreenOnScanSchedule(null));
    }

    /**
     * Test coverage for the constructor of AddNetworkResult.
     */
    @Test
    public void testAddNetworkResultCreation() {
        if (!WifiBuildCompat.isPlatformOrWifiModuleAtLeastS(sContext)) {
            // Skip the test if wifi module version is older than S.
            return;
        }
        int statusCode = WifiManager.AddNetworkResult.STATUS_NO_PERMISSION;
        int networkId = 5;
        WifiManager.AddNetworkResult result = new WifiManager.AddNetworkResult(
            statusCode, networkId);
        assertEquals("statusCode should match", statusCode, result.statusCode);
        assertEquals("networkId should match", networkId, result.networkId);
    }

    /**
     * Verify {@link WifiManager#setSsidsAllowlist(Set)} can be called with sufficient
     * privilege.
     */
    @Test
    public void testGetAndSetSsidsAllowlist() {
        Set<WifiSsid> ssids = new ArraySet<>();
        ssids.add(WifiSsid.fromBytes("TEST_SSID_1".getBytes(StandardCharsets.UTF_8)));
        ShellIdentityUtils.invokeWithShellPermissions(
                () -> sWifiManager.setSsidsAllowlist(ssids));

        ShellIdentityUtils.invokeWithShellPermissions(
                () -> assertEquals("Ssids should match", ssids,
                        sWifiManager.getSsidsAllowlist()));

        ShellIdentityUtils.invokeWithShellPermissions(
                () -> sWifiManager.setSsidsAllowlist(Collections.EMPTY_SET));
        ShellIdentityUtils.invokeWithShellPermissions(
                () -> assertEquals("Should equal to empty set",
                        Collections.EMPTY_SET,
                        sWifiManager.getSsidsAllowlist()));

        try {
            sWifiManager.setSsidsAllowlist(Collections.EMPTY_SET);
            fail("Expected SecurityException when called without permission");
        } catch (SecurityException e) {
            // expect the exception
        }
    }

    class TestPnoScanResultsCallback implements WifiManager.PnoScanResultsCallback {
        public CountDownLatch latch = new CountDownLatch(1);
        private boolean mRegisterSuccess;
        private int mRegisterFailedReason = -1;
        private int mRemovedReason = -1;
        private List<ScanResult> mScanResults;

        @Override
        public void onScanResultsAvailable(List<ScanResult> scanResults) {
            mScanResults = scanResults;
            latch.countDown();
        }

        @Override
        public void onRegisterSuccess() {
            mRegisterSuccess = true;
            latch.countDown();
        }

        @Override
        public void onRegisterFailed(int reason) {
            mRegisterFailedReason = reason;
            latch.countDown();
        }

        @Override
        public void onRemoved(int reason) {
            mRemovedReason = reason;
            latch.countDown();
        }

        public boolean isRegisterSuccess() {
            return mRegisterSuccess;
        }

        public int getRemovedReason() {
            return mRemovedReason;
        }

        public int getRegisterFailedReason() {
            return mRegisterFailedReason;
        }

        public List<ScanResult> getScanResults() {
            return mScanResults;
        }
    }

    /**
     * Verify {@link WifiManager#setExternalPnoScanRequest(List, int[], Executor,
     * WifiManager.PnoScanResultsCallback)} can be called with proper permissions.
     */
    @SdkSuppress(minSdkVersion = Build.VERSION_CODES.TIRAMISU)
    @Test
    public void testSetExternalPnoScanRequestSuccess() throws Exception {
        TestPnoScanResultsCallback callback = new TestPnoScanResultsCallback();
        List<WifiSsid> ssids = new ArrayList<>();
        ssids.add(WifiSsid.fromBytes("TEST_SSID_1".getBytes(StandardCharsets.UTF_8)));
        int[] frequencies = new int[] {2412, 5180, 5805};

        assertFalse("Callback should be initialized unregistered", callback.isRegisterSuccess());
        ShellIdentityUtils.invokeWithShellPermissions(
                () -> sWifiManager.setExternalPnoScanRequest(
                        ssids, frequencies, Executors.newSingleThreadExecutor(), callback));

        callback.latch.await(TEST_WAIT_DURATION_MS, TimeUnit.MILLISECONDS);
        if (sWifiManager.isPreferredNetworkOffloadSupported()) {
            assertTrue("Expect register success or failed due to resource busy",
                    callback.isRegisterSuccess()
                    || callback.getRegisterFailedReason() == WifiManager.PnoScanResultsCallback
                            .REGISTER_PNO_CALLBACK_RESOURCE_BUSY);
        } else {
            assertEquals("Expect register fail due to not supported.",
                    WifiManager.PnoScanResultsCallback.REGISTER_PNO_CALLBACK_PNO_NOT_SUPPORTED,
                    callback.getRegisterFailedReason());
        }
        sWifiManager.clearExternalPnoScanRequest();
    }

    /**
     * Verify {@link WifiManager#setExternalPnoScanRequest(List, int[], Executor,
     * WifiManager.PnoScanResultsCallback)} can be called with null frequency.
     */
    @SdkSuppress(minSdkVersion = Build.VERSION_CODES.TIRAMISU)
    @Test
    public void testSetExternalPnoScanRequestSuccessNullFrequency() throws Exception {
        TestPnoScanResultsCallback callback = new TestPnoScanResultsCallback();
        List<WifiSsid> ssids = new ArrayList<>();
        ssids.add(WifiSsid.fromBytes("TEST_SSID_1".getBytes(StandardCharsets.UTF_8)));

        ShellIdentityUtils.invokeWithShellPermissions(
                () -> sWifiManager.setExternalPnoScanRequest(
                        ssids, null, Executors.newSingleThreadExecutor(), callback));
        sWifiManager.clearExternalPnoScanRequest();
    }

    /**
     * Verify {@link WifiManager#setExternalPnoScanRequest(List, int[], Executor,
     * WifiManager.PnoScanResultsCallback)} throws an Exception if called with too many SSIDs.
     */
    @SdkSuppress(minSdkVersion = Build.VERSION_CODES.TIRAMISU)
    @Test
    public void testSetExternalPnoScanRequestTooManySsidsException() throws Exception {
        TestPnoScanResultsCallback callback = new TestPnoScanResultsCallback();
        List<WifiSsid> ssids = new ArrayList<>();
        ssids.add(WifiSsid.fromBytes("TEST_SSID_1".getBytes(StandardCharsets.UTF_8)));
        ssids.add(WifiSsid.fromBytes("TEST_SSID_2".getBytes(StandardCharsets.UTF_8)));
        ssids.add(WifiSsid.fromBytes("TEST_SSID_3".getBytes(StandardCharsets.UTF_8)));

        assertFalse("Callback should be initialized unregistered", callback.isRegisterSuccess());
        assertThrows(IllegalArgumentException.class, () -> {
            ShellIdentityUtils.invokeWithShellPermissions(
                    () -> sWifiManager.setExternalPnoScanRequest(
                            ssids, null, Executors.newSingleThreadExecutor(), callback));
        });
    }

    /**
     * Verify {@link WifiManager#setExternalPnoScanRequest(List, int[], Executor,
     * WifiManager.PnoScanResultsCallback)} throws an Exception if called with too many frequencies.
     */
    @SdkSuppress(minSdkVersion = Build.VERSION_CODES.TIRAMISU)
    @Test
    public void testSetExternalPnoScanRequestTooManyFrequenciesException() throws Exception {
        TestPnoScanResultsCallback callback = new TestPnoScanResultsCallback();
        List<WifiSsid> ssids = new ArrayList<>();
        ssids.add(WifiSsid.fromBytes("TEST_SSID_1".getBytes(StandardCharsets.UTF_8)));
        int[] frequencies = new int[] {2412, 2417, 2422, 2427, 2432, 2437, 2447, 2452, 2457, 2462,
                5180, 5200, 5220, 5240, 5745, 5765, 5785, 5805};

        assertFalse("Callback should be initialized unregistered", callback.isRegisterSuccess());
        assertThrows(IllegalArgumentException.class, () -> {
            ShellIdentityUtils.invokeWithShellPermissions(
                    () -> sWifiManager.setExternalPnoScanRequest(
                            ssids, frequencies, Executors.newSingleThreadExecutor(), callback));
        });
    }

    /**
     * Verify {@link WifiManager#setExternalPnoScanRequest(List, int[], Executor,
     * WifiManager.PnoScanResultsCallback)} cannot be called without permission.
     */
    @SdkSuppress(minSdkVersion = Build.VERSION_CODES.TIRAMISU)
    @Test
    public void testSetExternalPnoScanRequestNoPermission() throws Exception {
        TestExecutor executor = new TestExecutor();
        TestPnoScanResultsCallback callback = new TestPnoScanResultsCallback();
        List<WifiSsid> ssids = new ArrayList<>();
        ssids.add(WifiSsid.fromBytes("TEST_SSID_1".getBytes(StandardCharsets.UTF_8)));

        assertFalse("Callback should be initialized unregistered", callback.isRegisterSuccess());
        assertThrows(SecurityException.class,
                () -> sWifiManager.setExternalPnoScanRequest(ssids, null, executor, callback));
    }

    /**
     * Verify the invalid and valid usages of {@code WifiManager#getLastCallerInfoForApi}.
     */
    @Test
    public void testGetLastCallerInfoForApi() throws Exception {
        AtomicReference<String> packageName = new AtomicReference<>();
        AtomicBoolean enabled = new AtomicBoolean(false);
        BiConsumer<String, Boolean> listener = new BiConsumer<String, Boolean>() {
            @Override
            public void accept(String caller, Boolean value) {
                synchronized (mLock) {
                    packageName.set(caller);
                    enabled.set(value);
                    mLock.notify();
                }
            }
        };
        // Test invalid inputs trigger IllegalArgumentException
        assertThrows("Invalid apiType should trigger exception", IllegalArgumentException.class,
                () -> sWifiManager.getLastCallerInfoForApi(-1, mExecutor, listener));
        assertThrows("null executor should trigger exception", IllegalArgumentException.class,
                () -> sWifiManager.getLastCallerInfoForApi(WifiManager.API_SOFT_AP, null,
                        listener));
        assertThrows("null listener should trigger exception", IllegalArgumentException.class,
                () -> sWifiManager.getLastCallerInfoForApi(WifiManager.API_SOFT_AP, mExecutor,
                        null));

        // Test caller with no permission triggers SecurityException.
        assertThrows("No permission should trigger SecurityException", SecurityException.class,
                () -> sWifiManager.getLastCallerInfoForApi(WifiManager.API_SOFT_AP,
                        mExecutor, listener));

        String expectedPackage = "android.net.wifi.cts";
        boolean isEnabledBefore = sWifiManager.isWifiEnabled();
        // toggle wifi and verify getting last caller
        setWifiEnabled(!isEnabledBefore);
        ShellIdentityUtils.invokeWithShellPermissions(
                () -> sWifiManager.getLastCallerInfoForApi(WifiManager.API_WIFI_ENABLED, mExecutor,
                        listener));
        synchronized (mLock) {
            mLock.wait(TEST_WAIT_DURATION_MS);
        }

        assertEquals("package does not match", expectedPackage, packageName.get());
        assertEquals("enabled does not match", !isEnabledBefore, enabled.get());

        // toggle wifi again and verify last caller
        packageName.set(null);
        setWifiEnabled(isEnabledBefore);
        ShellIdentityUtils.invokeWithShellPermissions(
                () -> sWifiManager.getLastCallerInfoForApi(WifiManager.API_WIFI_ENABLED, mExecutor,
                        listener));
        synchronized (mLock) {
            mLock.wait(TEST_WAIT_DURATION_MS);
        }
        assertEquals("package does not match", expectedPackage, packageName.get());
        assertEquals("enabled does not match", isEnabledBefore, enabled.get());
    }

    /**
     * Verify that {@link WifiManager#addNetworkPrivileged(WifiConfiguration)} throws a
     * SecurityException when called by a normal app.
     */
    @Test
    public void testAddNetworkPrivilegedNotAllowedForNormalApps() {
        if (!WifiBuildCompat.isPlatformOrWifiModuleAtLeastS(sContext)) {
            // Skip the test if wifi module version is older than S.
            return;
        }
        try {
            WifiConfiguration newOpenNetwork = new WifiConfiguration();
            newOpenNetwork.SSID = "\"" + TEST_SSID_UNQUOTED + "\"";
            sWifiManager.addNetworkPrivileged(newOpenNetwork);
            fail("A normal app should not be able to call this API.");
        } catch (SecurityException e) {
        }
    }

    /**
     * Verify {@link WifiManager#addNetworkPrivileged(WifiConfiguration)} throws an exception when
     * null is the input.
     */
    @Test
    public void testAddNetworkPrivilegedBadInput() {
        if (!WifiBuildCompat.isPlatformOrWifiModuleAtLeastS(sContext)) {
            // Skip the test if wifi module version is older than S.
            return;
        }
        UiAutomation uiAutomation = InstrumentationRegistry.getInstrumentation().getUiAutomation();
        try {
            uiAutomation.adoptShellPermissionIdentity();
            sWifiManager.addNetworkPrivileged(null);
            fail("Expected IllegalArgumentException");
        } catch (IllegalArgumentException e) {
        } finally {
            uiAutomation.dropShellPermissionIdentity();
        }
    }

    /**
     * Verify {@link WifiManager#getPrivilegedConnectedNetwork()} returns the currently
     * connected WifiConfiguration with randomized MAC address filtered out.
     */
    @Test
    public void testGetPrivilegedConnectedNetworkSuccess() throws Exception {
        UiAutomation uiAutomation = InstrumentationRegistry.getInstrumentation().getUiAutomation();
        try {
            uiAutomation.adoptShellPermissionIdentity();
            sWifiManager.startScan();

            WifiInfo wifiInfo = sWifiManager.getConnectionInfo();
            int curNetworkId = wifiInfo.getNetworkId();
            assertNotEquals("Should be connected to valid networkId", INVALID_NETWORK_ID,
                    curNetworkId);
            WifiConfiguration curConfig = sWifiManager.getPrivilegedConnectedNetwork();
            assertEquals("NetworkId should match", curNetworkId, curConfig.networkId);
            assertEquals("SSID should match", wifiInfo.getSSID(), curConfig.SSID);
            assertEquals("Randomized MAC should be filtered out", WifiInfo.DEFAULT_MAC_ADDRESS,
                    curConfig.getRandomizedMacAddress().toString());
        } finally {
            uiAutomation.dropShellPermissionIdentity();
        }
    }

    /**
     * Verify {@link WifiManager#addNetworkPrivileged(WifiConfiguration)} works properly when the
     * calling app has permissions.
     */
    @Test
    public void testAddNetworkPrivilegedSuccess() {
        if (!WifiBuildCompat.isPlatformOrWifiModuleAtLeastS(sContext)) {
            // Skip the test if wifi module version is older than S.
            return;
        }
        UiAutomation uiAutomation = InstrumentationRegistry.getInstrumentation().getUiAutomation();
        WifiManager.AddNetworkResult result = null;
        try {
            uiAutomation.adoptShellPermissionIdentity();
            WifiConfiguration newOpenNetwork = new WifiConfiguration();
            newOpenNetwork.SSID = "\"" + TEST_SSID_UNQUOTED + "\"";
            result = sWifiManager.addNetworkPrivileged(newOpenNetwork);
            assertEquals(WifiManager.AddNetworkResult.STATUS_SUCCESS, result.statusCode);
            assertTrue(result.networkId >= 0);
            List<WifiConfiguration> configuredNetworks = sWifiManager.getConfiguredNetworks();
            boolean found = false;
            for (WifiConfiguration config : configuredNetworks) {
                if (config.networkId == result.networkId
                        && config.SSID.equals(newOpenNetwork.SSID)) {
                    found = true;
                    break;
                }
            }
            assertTrue("addNetworkPrivileged returns success"
                    + "but the network is not found in getConfiguredNetworks", found);

            List<WifiConfiguration> privilegedConfiguredNetworks =
                    sWifiManager.getPrivilegedConfiguredNetworks();
            found = false;
            for (WifiConfiguration config : privilegedConfiguredNetworks) {
                if (config.networkId == result.networkId
                        && config.SSID.equals(newOpenNetwork.SSID)) {
                    found = true;
                    break;
                }
            }
            assertTrue("addNetworkPrivileged returns success"
                    + "but the network is not found in getPrivilegedConfiguredNetworks", found);

            List<WifiConfiguration> callerConfiguredNetworks =
                    sWifiManager.getCallerConfiguredNetworks();
            found = false;
            for (WifiConfiguration config : callerConfiguredNetworks) {
                if (config.networkId == result.networkId
                        && config.SSID.equals(newOpenNetwork.SSID)) {
                    found = true;
                    break;
                }
            }
            assertTrue("addNetworkPrivileged returns success"
                    + "but the network is not found in getCallerConfiguredNetworks", found);
        } finally {
            if (null != result) {
                sWifiManager.removeNetwork(result.networkId);
            }
            uiAutomation.dropShellPermissionIdentity();
        }
    }

    private WifiConfiguration createConfig(
            String ssid, int type) {
        WifiConfiguration config = new WifiConfiguration();
        config.SSID = "\"" + ssid + "\"";
        config.setSecurityParams(type);
        // set necessary fields for different types.
        switch (type) {
            case WifiConfiguration.SECURITY_TYPE_OPEN:
            case WifiConfiguration.SECURITY_TYPE_OWE:
                break;
            case WifiConfiguration.SECURITY_TYPE_PSK:
            case WifiConfiguration.SECURITY_TYPE_SAE:
                config.preSharedKey = "\"1qaz@WSX\"";
                break;
            case WifiConfiguration.SECURITY_TYPE_EAP:
            case WifiConfiguration.SECURITY_TYPE_EAP_WPA3_ENTERPRISE:
            case WifiConfiguration.SECURITY_TYPE_EAP_WPA3_ENTERPRISE_192_BIT:
                config.enterpriseConfig.setEapMethod(WifiEnterpriseConfig.Eap.SIM);
                break;
        }
        return config;
    }

    private void assertConfigsAreFound(
            List<WifiConfiguration> expectedConfigs,
            List<WifiConfiguration> configs) {
        for (WifiConfiguration expectedConfig: expectedConfigs) {
            boolean found = false;
            for (WifiConfiguration config : configs) {
                if (config.networkId == expectedConfig.networkId
                        && config.getKey().equals(expectedConfig.getKey())) {
                    found = true;
                    break;
                }
            }
            assertTrue("the network " + expectedConfig.getKey() + " is not found", found);
        }
    }

    /**
     * Verify {@link WifiManager#addNetworkPrivileged(WifiConfiguration)} works
     * with merging types properly when the calling app has permissions.
     */
    @Test
    public void testAddNetworkPrivilegedMergingTypeSuccess() {
        if (!WifiBuildCompat.isPlatformOrWifiModuleAtLeastS(sContext)) {
            // Skip the test if wifi module version is older than S.
            return;
        }
        List<WifiConfiguration> baseConfigs = new ArrayList<>();
        baseConfigs.add(createConfig("test-open-owe-jdur", WifiConfiguration.SECURITY_TYPE_OPEN));
        baseConfigs.add(createConfig("test-psk-sae-ijfe", WifiConfiguration.SECURITY_TYPE_PSK));
        baseConfigs.add(createConfig("test-wpa2e-wpa3e-plki",
                WifiConfiguration.SECURITY_TYPE_EAP));
        List<WifiConfiguration> upgradeConfigs = new ArrayList<>();
        upgradeConfigs.add(createConfig("test-open-owe-jdur", WifiConfiguration.SECURITY_TYPE_OWE));
        upgradeConfigs.add(createConfig("test-psk-sae-ijfe", WifiConfiguration.SECURITY_TYPE_SAE));
        upgradeConfigs.add(createConfig("test-wpa2e-wpa3e-plki",
                WifiConfiguration.SECURITY_TYPE_EAP_WPA3_ENTERPRISE));
        UiAutomation uiAutomation = InstrumentationRegistry.getInstrumentation().getUiAutomation();
        try {
            uiAutomation.adoptShellPermissionIdentity();
            final int originalConfiguredNetworksNumber =
                    sWifiManager.getConfiguredNetworks().size();
            final int originalPrivilegedConfiguredNetworksNumber =
                    sWifiManager.getPrivilegedConfiguredNetworks().size();
            final int originalCallerConfiguredNetworksNumber =
                    sWifiManager.getCallerConfiguredNetworks().size();
            for (WifiConfiguration c: baseConfigs) {
                WifiManager.AddNetworkResult result = sWifiManager.addNetworkPrivileged(c);
                assertEquals(WifiManager.AddNetworkResult.STATUS_SUCCESS, result.statusCode);
                assertTrue(result.networkId >= 0);
                c.networkId = result.networkId;
            }
            for (WifiConfiguration c: upgradeConfigs) {
                WifiManager.AddNetworkResult result = sWifiManager.addNetworkPrivileged(c);
                assertEquals(WifiManager.AddNetworkResult.STATUS_SUCCESS, result.statusCode);
                assertTrue(result.networkId >= 0);
                c.networkId = result.networkId;
            }
            // open/owe, psk/sae, and wpa2e/wpa3e should be merged
            // so they should have the same network ID.
            for (int i = 0; i < baseConfigs.size(); i++) {
                assertEquals(baseConfigs.get(i).networkId, upgradeConfigs.get(i).networkId);
            }

            int numAddedConfigs = baseConfigs.size();
            List<WifiConfiguration> expectedConfigs = new ArrayList<>(baseConfigs);
            if (SdkLevel.isAtLeastS()) {
                // S devices and above will return one additional config per each security type
                // added, so we include the number of both base and upgrade configs.
                numAddedConfigs += upgradeConfigs.size();
                expectedConfigs.addAll(upgradeConfigs);
            }
            List<WifiConfiguration> configuredNetworks = sWifiManager.getConfiguredNetworks();
            assertEquals(originalConfiguredNetworksNumber + numAddedConfigs,
                    configuredNetworks.size());
            assertConfigsAreFound(expectedConfigs, configuredNetworks);

            List<WifiConfiguration> privilegedConfiguredNetworks =
                    sWifiManager.getPrivilegedConfiguredNetworks();
            assertEquals(originalPrivilegedConfiguredNetworksNumber + numAddedConfigs,
                    privilegedConfiguredNetworks.size());
            assertConfigsAreFound(expectedConfigs, privilegedConfiguredNetworks);

            List<WifiConfiguration> callerConfiguredNetworks =
                    sWifiManager.getCallerConfiguredNetworks();
            assertEquals(originalCallerConfiguredNetworksNumber + numAddedConfigs,
                    callerConfiguredNetworks.size());
            assertConfigsAreFound(expectedConfigs, callerConfiguredNetworks);

        } finally {
            for (WifiConfiguration c: baseConfigs) {
                if (c.networkId >= 0) {
                    sWifiManager.removeNetwork(c.networkId);
                }
            }
            uiAutomation.dropShellPermissionIdentity();
        }
    }

    /**
     * Verify that applications can only have one registered LocalOnlyHotspot request at a time.
     *
     * Note: Location mode must be enabled for this test.
     */
    @Test
    public void testStartLocalOnlyHotspotSingleRequestByApps() throws Exception {
        // check that softap mode is supported by the device
        assumeTrue(sWifiManager.isPortableHotspotSupported());

        boolean caughtException = false;

        boolean wifiEnabled = sWifiManager.isWifiEnabled();

        TestLocalOnlyHotspotCallback callback = startLocalOnlyHotspot();

        // now make a second request - this should fail.
        TestLocalOnlyHotspotCallback callback2 = new TestLocalOnlyHotspotCallback(mLock);
        try {
            sWifiManager.startLocalOnlyHotspot(callback2, null);
        } catch (IllegalStateException e) {
            Log.d(TAG, "Caught the IllegalStateException we expected: called startLOHS twice");
            caughtException = true;
        }
        if (!caughtException) {
            // second start did not fail, should clean up the hotspot.

            // add sleep to avoid calling stopLocalOnlyHotspot before TetherController initialization.
            // TODO: remove this sleep as soon as b/124330089 is fixed.
            Log.d(TAG, "Sleeping for 2 seconds");
            Thread.sleep(2000);

            stopLocalOnlyHotspot(callback2, wifiEnabled);
        }
        assertTrue(caughtException);

        // add sleep to avoid calling stopLocalOnlyHotspot before TetherController initialization.
        // TODO: remove this sleep as soon as b/124330089 is fixed.
        Log.d(TAG, "Sleeping for 2 seconds");
        Thread.sleep(2000);

        stopLocalOnlyHotspot(callback, wifiEnabled);
    }

    private static class TestExecutor implements Executor {
        private ConcurrentLinkedQueue<Runnable> tasks = new ConcurrentLinkedQueue<>();

        @Override
        public void execute(Runnable task) {
            tasks.add(task);
        }

        private void runAll() {
            Runnable task = tasks.poll();
            while (task != null) {
                task.run();
                task = tasks.poll();
            }
        }
    }

    private SoftApConfiguration.Builder generateSoftApConfigBuilderWithSsid(String ssid) {
        if (ApiLevelUtil.isAtLeast(Build.VERSION_CODES.TIRAMISU)) {
            return new SoftApConfiguration.Builder().setWifiSsid(
                    WifiSsid.fromBytes(ssid.getBytes(StandardCharsets.UTF_8)));
        }
        return new SoftApConfiguration.Builder().setSsid(ssid);
    }

    private void assertSsidEquals(SoftApConfiguration config, String expectedSsid) {
        if (ApiLevelUtil.isAtLeast(Build.VERSION_CODES.TIRAMISU)) {
            assertEquals(WifiSsid.fromBytes(expectedSsid.getBytes(StandardCharsets.UTF_8)),
                    config.getWifiSsid());
        } else {
            assertEquals(expectedSsid, config.getSsid());
        }
    }

    private void unregisterLocalOnlyHotspotSoftApCallback(TestSoftApCallback lohsSoftApCallback) {
        if (ApiLevelUtil.isAtLeast(Build.VERSION_CODES.TIRAMISU)) {
            sWifiManager.unregisterLocalOnlyHotspotSoftApCallback(lohsSoftApCallback);
        } else {
            sWifiManager.unregisterSoftApCallback(lohsSoftApCallback);
        }
    }

    @SdkSuppress(minSdkVersion = Build.VERSION_CODES.TIRAMISU)
    @Test
    public void testStartLocalOnlyHotspotWithSupportedBand() throws Exception {
        // check that softap mode is supported by the device
        if (!sWifiManager.isPortableHotspotSupported()) {
            return;
        }

        TestExecutor executor = new TestExecutor();
        TestSoftApCallback lohsSoftApCallback = new TestSoftApCallback(mLock);
        setWifiEnabled(false);
        Thread.sleep(TEST_WAIT_DURATION_MS);
        boolean wifiEnabled = sWifiManager.isWifiEnabled();
        UiAutomation uiAutomation = InstrumentationRegistry.getInstrumentation().getUiAutomation();
        try {
            uiAutomation.adoptShellPermissionIdentity();
            verifyLohsRegisterSoftApCallback(executor, lohsSoftApCallback);
            SoftApConfiguration.Builder customConfigBuilder =
                    generateSoftApConfigBuilderWithSsid(TEST_SSID_UNQUOTED)
                    .setPassphrase(TEST_PASSPHRASE, SoftApConfiguration.SECURITY_TYPE_WPA2_PSK);

            SparseIntArray testBandsAndChannels = getAvailableBandAndChannelForTesting(
                    lohsSoftApCallback.getCurrentSoftApCapability());
            // The devices which doesn't have SIM and default country code in system property
            // (ro.boot.wificountrycodeCountry) will return a null country code. Since country code
            // is mandatory for 5GHz/6GHz band, skip the softap operation on 5GHz & 6GHz only band.
            boolean skip5g6gBand = false;
            String wifiCountryCode = ShellIdentityUtils.invokeWithShellPermissions(
                    sWifiManager::getCountryCode);
            if (wifiCountryCode == null) {
                skip5g6gBand = true;
                Log.e(TAG, "Country Code is not available - Skip 5GHz and 6GHz test");
            }
            for (int i = 0; i < testBandsAndChannels.size(); i++) {
                TestLocalOnlyHotspotCallback callback = new TestLocalOnlyHotspotCallback(mLock);
                int testBand = testBandsAndChannels.keyAt(i);
                if (skip5g6gBand && (testBand == SoftApConfiguration.BAND_6GHZ
                        || testBand == SoftApConfiguration.BAND_5GHZ)) {
                    continue;
                }
                // WPA2_PSK is not allowed in 6GHz band. So test with WPA3_SAE which is
                // mandatory to support in 6GHz band.
                if (testBand == SoftApConfiguration.BAND_6GHZ) {
                    customConfigBuilder.setPassphrase(TEST_PASSPHRASE,
                            SoftApConfiguration.SECURITY_TYPE_WPA3_SAE);
                }
                customConfigBuilder.setBand(testBand);
                sWifiManager.startLocalOnlyHotspot(customConfigBuilder.build(), executor, callback);
                // now wait for callback
                Thread.sleep(DURATION_SOFTAP_START_MS);

                // Verify callback is run on the supplied executor
                assertFalse(callback.onStartedCalled);
                executor.runAll();
                assertTrue(callback.onStartedCalled);
                assertNotNull(callback.reservation);
                SoftApConfiguration softApConfig = callback.reservation.getSoftApConfiguration();
                assertEquals(
                        WifiSsid.fromBytes(TEST_SSID_UNQUOTED.getBytes(StandardCharsets.UTF_8)),
                        softApConfig.getWifiSsid());
                assertEquals(TEST_PASSPHRASE, softApConfig.getPassphrase());
                // Automotive mode can force the LOHS to specific bands
                if (!hasAutomotiveFeature()) {
                    assertEquals(testBand, softApConfig.getBand());
                }
                if (lohsSoftApCallback.getOnSoftapInfoChangedCalledCount() > 1) {
                    assertTrue(lohsSoftApCallback.getCurrentSoftApInfo().getFrequency() > 0);
                }
                stopLocalOnlyHotspot(callback, wifiEnabled);
            }
        } finally {
            // clean up
            sWifiManager.unregisterSoftApCallback(lohsSoftApCallback);
            uiAutomation.dropShellPermissionIdentity();
        }
    }

    @Test
    public void testStartLocalOnlyHotspotWithConfigBssid() throws Exception {
        // check that softap mode is supported by the device
        if (!sWifiManager.isPortableHotspotSupported()) {
            return;
        }

        TestExecutor executor = new TestExecutor();
        TestLocalOnlyHotspotCallback callback = new TestLocalOnlyHotspotCallback(mLock);
        TestSoftApCallback lohsSoftApCallback = new TestSoftApCallback(mLock);
        UiAutomation uiAutomation = InstrumentationRegistry.getInstrumentation().getUiAutomation();
        boolean wifiEnabled = sWifiManager.isWifiEnabled();
        try {
            uiAutomation.adoptShellPermissionIdentity();
            verifyLohsRegisterSoftApCallback(executor, lohsSoftApCallback);
            SoftApConfiguration.Builder customConfigBuilder =
                    generateSoftApConfigBuilderWithSsid(TEST_SSID_UNQUOTED)
                    .setPassphrase(TEST_PASSPHRASE, SoftApConfiguration.SECURITY_TYPE_WPA2_PSK);

            boolean isSupportCustomizedMac = lohsSoftApCallback.getCurrentSoftApCapability()
                        .areFeaturesSupported(
                        SoftApCapability.SOFTAP_FEATURE_MAC_ADDRESS_CUSTOMIZATION)
                    && PropertyUtil.isVndkApiLevelNewerThan(Build.VERSION_CODES.S);
            if (isSupportCustomizedMac) {
                customConfigBuilder.setBssid(TEST_MAC).setMacRandomizationSetting(
                            SoftApConfiguration.RANDOMIZATION_NONE);
            }
            SoftApConfiguration customConfig = customConfigBuilder.build();

            sWifiManager.startLocalOnlyHotspot(customConfig, executor, callback);
            // now wait for callback
            Thread.sleep(TEST_WAIT_DURATION_MS);

            // Verify callback is run on the supplied executor
            assertFalse(callback.onStartedCalled);
            executor.runAll();
            assertTrue(callback.onStartedCalled);

            assertNotNull(callback.reservation);
            SoftApConfiguration softApConfig = callback.reservation.getSoftApConfiguration();
            assertNotNull(softApConfig);
            if (isSupportCustomizedMac) {
                assertEquals(TEST_MAC, softApConfig.getBssid());
            }
            assertSsidEquals(softApConfig, TEST_SSID_UNQUOTED);
            assertEquals(TEST_PASSPHRASE, softApConfig.getPassphrase());
        } finally {
            // clean up
            stopLocalOnlyHotspot(callback, wifiEnabled);
            unregisterLocalOnlyHotspotSoftApCallback(lohsSoftApCallback);
            uiAutomation.dropShellPermissionIdentity();
        }
    }

    @Test
    public void testStartLocalOnlyHotspotWithNullBssidConfig() throws Exception {
        // check that softap mode is supported by the device
        if (!sWifiManager.isPortableHotspotSupported()) {
            return;
        }
        SoftApConfiguration customConfig =
                generateSoftApConfigBuilderWithSsid(TEST_SSID_UNQUOTED)
                .setPassphrase(TEST_PASSPHRASE, SoftApConfiguration.SECURITY_TYPE_WPA2_PSK)
                .build();

        TestExecutor executor = new TestExecutor();
        TestLocalOnlyHotspotCallback callback = new TestLocalOnlyHotspotCallback(mLock);
        UiAutomation uiAutomation = InstrumentationRegistry.getInstrumentation().getUiAutomation();
        boolean wifiEnabled = sWifiManager.isWifiEnabled();
        try {
            uiAutomation.adoptShellPermissionIdentity();

            sWifiManager.startLocalOnlyHotspot(customConfig, executor, callback);
            // now wait for callback
            Thread.sleep(TEST_WAIT_DURATION_MS);

            // Verify callback is run on the supplied executor
            assertFalse(callback.onStartedCalled);
            executor.runAll();
            assertTrue(callback.onStartedCalled);

            assertNotNull(callback.reservation);
            SoftApConfiguration softApConfig = callback.reservation.getSoftApConfiguration();
            assertNotNull(softApConfig);
            assertSsidEquals(softApConfig, TEST_SSID_UNQUOTED);
            assertEquals(TEST_PASSPHRASE, softApConfig.getPassphrase());
        } finally {
            // clean up
            stopLocalOnlyHotspot(callback, wifiEnabled);
            uiAutomation.dropShellPermissionIdentity();
        }
    }

    /**
     * Read the content of the given resource file into a String.
     *
     * @param filename String name of the file
     * @return String
     * @throws IOException
     */
    private String loadResourceFile(String filename) throws IOException {
        InputStream in = getClass().getClassLoader().getResourceAsStream(filename);
        BufferedReader reader = new BufferedReader(new InputStreamReader(in));
        StringBuilder builder = new StringBuilder();
        String line;
        while ((line = reader.readLine()) != null) {
            builder.append(line).append("\n");
        }
        return builder.toString();
    }

    /**
     * Verify that changing the mac randomization setting of a Passpoint configuration.
     */
    @Test
    public void testMacRandomizationSettingPasspoint() throws Exception {
        String configStr = loadResourceFile(PASSPOINT_INSTALLATION_FILE_WITH_CA_CERT);
        PasspointConfiguration config =
                ConfigParser.parsePasspointConfig(TYPE_WIFI_CONFIG, configStr.getBytes());
        String fqdn = config.getHomeSp().getFqdn();
        String uniqueId = config.getUniqueId();
        UiAutomation uiAutomation = InstrumentationRegistry.getInstrumentation().getUiAutomation();
        try {
            uiAutomation.adoptShellPermissionIdentity();

            sWifiManager.addOrUpdatePasspointConfiguration(config);
            PasspointConfiguration passpointConfig = getTargetPasspointConfiguration(
                    sWifiManager.getPasspointConfigurations(), uniqueId);
            assertNotNull("The installed passpoint profile is missing", passpointConfig);
            assertTrue("Mac randomization should be enabled for passpoint networks by default.",
                    passpointConfig.isMacRandomizationEnabled());

            sWifiManager.setMacRandomizationSettingPasspointEnabled(fqdn, false);
            passpointConfig = getTargetPasspointConfiguration(
                    sWifiManager.getPasspointConfigurations(), uniqueId);
            assertNotNull("The installed passpoint profile is missing", passpointConfig);
            assertFalse("Mac randomization should be disabled by the API call.",
                    passpointConfig.isMacRandomizationEnabled());
        } finally {
            // Clean up
            sWifiManager.removePasspointConfiguration(fqdn);
            uiAutomation.dropShellPermissionIdentity();
        }
    }
    /**
     * Verify that the {@link android.Manifest.permission#NETWORK_STACK} permission is never held by
     * any package.
     * <p>
     * No apps should <em>ever</em> attempt to acquire this permission, since it would give those
     * apps extremely broad access to connectivity functionality.
     */
    @Test
    public void testNetworkStackPermission() {
        final PackageManager pm = sContext.getPackageManager();

        final List<PackageInfo> holding = pm.getPackagesHoldingPermissions(new String[] {
                android.Manifest.permission.NETWORK_STACK
        }, PackageManager.MATCH_UNINSTALLED_PACKAGES);
        for (PackageInfo pi : holding) {
            fail("The NETWORK_STACK permission must not be held by " + pi.packageName
                    + " and must be revoked for security reasons");
        }
    }

    /**
     * Verify that the {@link android.Manifest.permission#NETWORK_SETTINGS} permission is
     * never held by any package.
     * <p>
     * Only Settings, SysUi, NetworkStack and shell apps should <em>ever</em> attempt to acquire
     * this permission, since it would give those apps extremely broad access to connectivity
     * functionality.  The permission is intended to be granted to only those apps with direct user
     * access and no others.
     */
    @Test
    public void testNetworkSettingsPermission() {
        final PackageManager pm = sContext.getPackageManager();

        final ArraySet<String> allowedPackages = new ArraySet();
        final ArraySet<Integer> allowedUIDs = new ArraySet();
        // explicitly add allowed UIDs
        allowedUIDs.add(Process.SYSTEM_UID);
        allowedUIDs.add(Process.SHELL_UID);
        allowedUIDs.add(Process.PHONE_UID);
        allowedUIDs.add(Process.NETWORK_STACK_UID);
        allowedUIDs.add(Process.NFC_UID);

        // only quick settings is allowed to bind to the BIND_QUICK_SETTINGS_TILE permission, using
        // this fact to determined allowed package name for sysui. This is a signature permission,
        // so allow any package with this permission.
        final List<PackageInfo> sysuiPackages = pm.getPackagesHoldingPermissions(new String[] {
                android.Manifest.permission.BIND_QUICK_SETTINGS_TILE
        }, PackageManager.MATCH_UNINSTALLED_PACKAGES);
        for (PackageInfo info : sysuiPackages) {
            allowedPackages.add(info.packageName);
        }

        // the captive portal flow also currently holds the NETWORK_SETTINGS permission
        final Intent intent = new Intent(ConnectivityManager.ACTION_CAPTIVE_PORTAL_SIGN_IN);
        final ResolveInfo ri = pm.resolveActivity(intent, PackageManager.MATCH_DISABLED_COMPONENTS);
        if (ri != null) {
            allowedPackages.add(ri.activityInfo.packageName);
        }

        final List<PackageInfo> holding = pm.getPackagesHoldingPermissions(new String[] {
                android.Manifest.permission.NETWORK_SETTINGS
        }, PackageManager.MATCH_UNINSTALLED_PACKAGES);
        StringBuilder stringBuilder = new StringBuilder();
        for (PackageInfo pi : holding) {
            String packageName = pi.packageName;

            // this is an explicitly allowed package
            if (allowedPackages.contains(packageName)) continue;

            // now check if the packages are from allowed UIDs
            int uid = -1;
            try {
                uid = pm.getPackageUidAsUser(packageName, UserHandle.USER_SYSTEM);
            } catch (PackageManager.NameNotFoundException e) {
                continue;
            }
            if (!allowedUIDs.contains(uid)) {
                stringBuilder.append("The NETWORK_SETTINGS permission must not be held by "
                    + packageName + ":" + uid + " and must be revoked for security reasons\n");
            }
        }
        if (stringBuilder.length() > 0) {
            fail(stringBuilder.toString());
        }
    }

    /**
     * Verify that the {@link android.Manifest.permission#NETWORK_SETUP_WIZARD} permission is
     * only held by the device setup wizard application.
     * <p>
     * Only the SetupWizard app should <em>ever</em> attempt to acquire this
     * permission, since it would give those apps extremely broad access to connectivity
     * functionality.  The permission is intended to be granted to only the device setup wizard.
     */
    @Test
    public void testNetworkSetupWizardPermission() {
        final ArraySet<String> allowedPackages = new ArraySet();

        final PackageManager pm = sContext.getPackageManager();

        final Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_SETUP_WIZARD);
        final ResolveInfo ri = pm.resolveActivity(intent, PackageManager.MATCH_DISABLED_COMPONENTS);
        String validPkg = "";
        if (ri != null) {
            allowedPackages.add(ri.activityInfo.packageName);
            validPkg = ri.activityInfo.packageName;
        }

        final Intent preIntent = new Intent("com.android.setupwizard.OEM_PRE_SETUP");
        preIntent.addCategory(Intent.CATEGORY_DEFAULT);
        final ResolveInfo preRi = pm
            .resolveActivity(preIntent, PackageManager.MATCH_DISABLED_COMPONENTS);
        String prePackageName = "";
        if (null != preRi) {
            prePackageName = preRi.activityInfo.packageName;
        }

        final Intent postIntent = new Intent("com.android.setupwizard.OEM_POST_SETUP");
        postIntent.addCategory(Intent.CATEGORY_DEFAULT);
        final ResolveInfo postRi = pm
            .resolveActivity(postIntent, PackageManager.MATCH_DISABLED_COMPONENTS);
        String postPackageName = "";
        if (null != postRi) {
            postPackageName = postRi.activityInfo.packageName;
        }
        if (!TextUtils.isEmpty(prePackageName) && !TextUtils.isEmpty(postPackageName)
            && prePackageName.equals(postPackageName)) {
            allowedPackages.add(prePackageName);
        }

        final List<PackageInfo> holding = pm.getPackagesHoldingPermissions(new String[]{
            android.Manifest.permission.NETWORK_SETUP_WIZARD
        }, PackageManager.MATCH_UNINSTALLED_PACKAGES);
        for (PackageInfo pi : holding) {
            if (!allowedPackages.contains(pi.packageName)) {
                fail("The NETWORK_SETUP_WIZARD permission must not be held by " + pi.packageName
                    + " and must be revoked for security reasons"
                    + " | validPkg=" + validPkg);
            }
        }
    }

    /**
     * Verify that the {@link android.Manifest.permission#NETWORK_MANAGED_PROVISIONING} permission
     * is only held by the device managed provisioning application.
     * <p>
     * Only the ManagedProvisioning app should <em>ever</em> attempt to acquire this
     * permission, since it would give those apps extremely broad access to connectivity
     * functionality.  The permission is intended to be granted to only the device managed
     * provisioning.
     */
    @Test
    public void testNetworkManagedProvisioningPermission() {
        final PackageManager pm = sContext.getPackageManager();

        // TODO(b/115980767): Using hardcoded package name. Need a better mechanism to find the
        // managed provisioning app.
        // Ensure that the package exists.
        final Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.setPackage(MANAGED_PROVISIONING_PACKAGE_NAME);
        final ResolveInfo ri = pm.resolveActivity(intent, PackageManager.MATCH_DISABLED_COMPONENTS);
        String validPkg = "";
        if (ri != null) {
            validPkg = ri.activityInfo.packageName;
        }
        String dpmHolderName = null;
        if (ApiLevelUtil.isAtLeast(Build.VERSION_CODES.TIRAMISU)) {
            DevicePolicyManager dpm = sContext.getSystemService(DevicePolicyManager.class);
            if (dpm != null) {
                dpmHolderName = dpm.getDevicePolicyManagementRoleHolderPackage();
            }
        }

        final List<PackageInfo> holding = pm.getPackagesHoldingPermissions(new String[] {
                android.Manifest.permission.NETWORK_MANAGED_PROVISIONING
        }, PackageManager.MATCH_UNINSTALLED_PACKAGES);
        for (PackageInfo pi : holding) {
            if (!Objects.equals(pi.packageName, validPkg)
                    && !Objects.equals(pi.packageName, dpmHolderName)) {
                fail("The NETWORK_MANAGED_PROVISIONING permission must not be held by "
                        + pi.packageName + " and must be revoked for security reasons ["
                        + validPkg + ", " + dpmHolderName + "]");
            }
        }
    }

    /**
     * Verify that the {@link android.Manifest.permission#WIFI_SET_DEVICE_MOBILITY_STATE} permission
     * is held by at most one application.
     */
    @Test
    public void testWifiSetDeviceMobilityStatePermission() {
        final PackageManager pm = sContext.getPackageManager();

        final List<PackageInfo> holding = pm.getPackagesHoldingPermissions(new String[] {
                android.Manifest.permission.WIFI_SET_DEVICE_MOBILITY_STATE
        }, PackageManager.MATCH_UNINSTALLED_PACKAGES);

        List<String> uniquePackageNames = holding
                .stream()
                .map(pi -> pi.packageName)
                .distinct()
                .collect(Collectors.toList());

        if (uniquePackageNames.size() > 1) {
            fail("The WIFI_SET_DEVICE_MOBILITY_STATE permission must not be held by more than one "
                    + "application, but is held by " + uniquePackageNames.size() + " applications: "
                    + String.join(", ", uniquePackageNames));
        }
    }

    /**
     * Verify that the {@link android.Manifest.permission#NETWORK_CARRIER_PROVISIONING} permission
     * is held by at most one application.
     */
    @Test
    public void testNetworkCarrierProvisioningPermission() {
        final PackageManager pm = sContext.getPackageManager();

        final List<PackageInfo> holding = pm.getPackagesHoldingPermissions(new String[] {
                android.Manifest.permission.NETWORK_CARRIER_PROVISIONING
        }, PackageManager.MATCH_UNINSTALLED_PACKAGES);

        List<String> uniquePackageNames = holding
                .stream()
                .map(pi -> pi.packageName)
                .distinct()
                .collect(Collectors.toList());

        if (uniquePackageNames.size() > 2) {
            fail("The NETWORK_CARRIER_PROVISIONING permission must not be held by more than two "
                    + "applications, but is held by " + uniquePackageNames.size() + " applications: "
                    + String.join(", ", uniquePackageNames));
        }
    }

    /**
     * Verify that the {@link android.Manifest.permission#WIFI_UPDATE_USABILITY_STATS_SCORE}
     * permission is held by at most one application.
     */
    @Test
    public void testUpdateWifiUsabilityStatsScorePermission() {
        final PackageManager pm = sContext.getPackageManager();

        final List<PackageInfo> holding = pm.getPackagesHoldingPermissions(new String[] {
                android.Manifest.permission.WIFI_UPDATE_USABILITY_STATS_SCORE
        }, PackageManager.MATCH_UNINSTALLED_PACKAGES);

        Set<String> uniqueNonSystemPackageNames = new HashSet<>();
        for (PackageInfo pi : holding) {
            String packageName = pi.packageName;
            // Shell is allowed to hold this permission for testing.
            int uid = -1;
            try {
                uid = pm.getPackageUidAsUser(packageName, UserHandle.USER_SYSTEM);
            } catch (PackageManager.NameNotFoundException e) {
                continue;
            }
            if (uid == Process.SHELL_UID) continue;

            uniqueNonSystemPackageNames.add(packageName);
        }

        if (uniqueNonSystemPackageNames.size() > 1) {
            fail("The WIFI_UPDATE_USABILITY_STATS_SCORE permission must not be held by more than "
                + "one application, but is held by " + uniqueNonSystemPackageNames.size()
                + " applications: " + String.join(", ", uniqueNonSystemPackageNames));
        }
    }

    private static void turnScreenOnNoDelay() throws Exception {
        if (sWakeLock.isHeld()) sWakeLock.release();
        sUiDevice.executeShellCommand("input keyevent KEYCODE_WAKEUP");
        sUiDevice.executeShellCommand("wm dismiss-keyguard");
    }

    private void turnScreenOn() throws Exception {
        turnScreenOnNoDelay();
        // Since the screen on/off intent is ordered, they will not be sent right now.
        Thread.sleep(DURATION_SCREEN_TOGGLE);
    }

    private void turnScreenOffNoDelay() throws Exception {
        sUiDevice.executeShellCommand("input keyevent KEYCODE_SLEEP");
    }

    private void turnScreenOff() throws Exception {
        if (!sWakeLock.isHeld()) sWakeLock.acquire();
        turnScreenOffNoDelay();
        // Since the screen on/off intent is ordered, they will not be sent right now.
        Thread.sleep(DURATION_SCREEN_TOGGLE);
    }

    private void assertWifiScanningIsOn() {
        if (!sWifiManager.isScanAlwaysAvailable()) {
            fail("Wi-Fi scanning should be on.");
        }
    }

    private void runWithScanning(ThrowingRunnable r, boolean isEnabled) throws Exception {
        boolean scanModeChangedForTest = false;
        if (sWifiManager.isScanAlwaysAvailable() != isEnabled) {
            ShellIdentityUtils.invokeWithShellPermissions(
                    () -> sWifiManager.setScanAlwaysAvailable(isEnabled));
            scanModeChangedForTest = true;
        }
        try {
            r.run();
        } finally {
            if (scanModeChangedForTest) {
                ShellIdentityUtils.invokeWithShellPermissions(
                        () -> sWifiManager.setScanAlwaysAvailable(!isEnabled));
            }
        }
    }

    /**
     * Verify that Wi-Fi scanning is not turned off when the screen turns off while wifi is disabled
     * but location is on.
     * @throws Exception
     */
    @Test
    public void testScreenOffDoesNotTurnOffWifiScanningWhenWifiDisabled() throws Exception {
        if (FeatureUtil.isTV() || FeatureUtil.isAutomotive()) {
            // TV and auto do not support the setting options of WIFI scanning and Bluetooth
            // scanning
            return;
        }

        if (!hasLocationFeature()) {
            // skip the test if location is not supported
            return;
        }
        if (!isLocationEnabled()) {
            fail("Please enable location for this test - since Marshmallow WiFi scan results are"
                    + " empty when location is disabled!");
        }
        runWithScanning(() -> {
            setWifiEnabled(false);
            turnScreenOn();
            assertWifiScanningIsOn();
            // Toggle screen and verify Wi-Fi scanning is still on.
            turnScreenOff();
            assertWifiScanningIsOn();
            turnScreenOn();
            assertWifiScanningIsOn();
        }, true /* run with enabled*/);
    }

    /**
     * Verify that Wi-Fi scanning is not turned off when the screen turns off while wifi is enabled.
     * @throws Exception
     */
    @Test
    public void testScreenOffDoesNotTurnOffWifiScanningWhenWifiEnabled() throws Exception {
        if (FeatureUtil.isTV() || FeatureUtil.isAutomotive()) {
            // TV and auto do not support the setting options of WIFI scanning and Bluetooth
            // scanning
            return;
        }

        if (!hasLocationFeature()) {
            // skip the test if location is not supported
            return;
        }
        if (!isLocationEnabled()) {
            fail("Please enable location for this test - since Marshmallow WiFi scan results are"
                    + " empty when location is disabled!");
        }
        runWithScanning(() -> {
            setWifiEnabled(true);
            turnScreenOn();
            assertWifiScanningIsOn();
            // Toggle screen and verify Wi-Fi scanning is still on.
            turnScreenOff();
            assertWifiScanningIsOn();
            turnScreenOn();
            assertWifiScanningIsOn();
        }, true /* run with enabled*/);
    }

    /**
     * Verify that the platform supports a reasonable number of suggestions per app.
     * @throws Exception
     */
    @Test
    public void testMaxNumberOfNetworkSuggestionsPerApp() throws Exception {
        assertTrue(sWifiManager.getMaxNumberOfNetworkSuggestionsPerApp()
                > ENFORCED_NUM_NETWORK_SUGGESTIONS_PER_APP);
    }

    private void verifyRegisterSoftApCallback(TestExecutor executor, TestSoftApCallback callback)
            throws Exception {
        // Register callback to get SoftApCapability
        sWifiManager.registerSoftApCallback(executor, callback);
        PollingCheck.check(
                "SoftAp register failed!", 5_000,
                () -> {
                    executor.runAll();
                    // Verify callback is run on the supplied executor and called
                    return callback.getOnStateChangedCalled()
                            && callback.getOnSoftapInfoChangedCalledCount() > 0
                            && callback.getOnSoftApCapabilityChangedCalled()
                            && callback.getOnConnectedClientCalled();
                });
    }

    private void verifyLohsRegisterSoftApCallback(TestExecutor executor,
            TestSoftApCallback callback) throws Exception {
        // Register callback to get SoftApCapability
        if (ApiLevelUtil.isAtLeast(Build.VERSION_CODES.TIRAMISU)) {
            sWifiManager.registerLocalOnlyHotspotSoftApCallback(executor, callback);
        } else {
            sWifiManager.registerSoftApCallback(executor, callback);
        }
        PollingCheck.check(
                "SoftAp register failed!", 5_000,
                () -> {
                    executor.runAll();
                    // Verify callback is run on the supplied executor and called
                    return callback.getOnStateChangedCalled() &&
                            callback.getOnSoftapInfoChangedCalledCount() > 0 &&
                            callback.getOnSoftApCapabilityChangedCalled() &&
                            callback.getOnConnectedClientCalled();
                });
    }

    private void verifySetGetSoftApConfig(SoftApConfiguration targetConfig) {
        assertTrue(sWifiManager.validateSoftApConfiguration(targetConfig));
        sWifiManager.setSoftApConfiguration(targetConfig);
        // Bssid set dodesn't support for tethered hotspot
        SoftApConfiguration currentConfig = sWifiManager.getSoftApConfiguration();
        compareSoftApConfiguration(targetConfig, currentConfig);
        if (ApiLevelUtil.isAtLeast(Build.VERSION_CODES.S)) {
            assertTrue(currentConfig.isUserConfiguration());
        }
        assertNotNull(currentConfig.getPersistentRandomizedMacAddress());

        if (ApiLevelUtil.isAtLeast(Build.VERSION_CODES.TIRAMISU)) {
            // Verify set/get with the deprecated set/getSsid()
            SoftApConfiguration oldSsidConfig = new SoftApConfiguration.Builder(targetConfig)
                    .setWifiSsid(null)
                    .setSsid(targetConfig.getSsid()).build();
            sWifiManager.setSoftApConfiguration(oldSsidConfig);
            currentConfig = sWifiManager.getSoftApConfiguration();
            compareSoftApConfiguration(oldSsidConfig, currentConfig);
        }
    }

    private void compareSoftApConfiguration(SoftApConfiguration currentConfig,
        SoftApConfiguration testSoftApConfig) {
        if (ApiLevelUtil.isAtLeast(Build.VERSION_CODES.TIRAMISU)) {
            assertEquals(currentConfig.getWifiSsid(), testSoftApConfig.getWifiSsid());
        }
        assertEquals(currentConfig.getSsid(), testSoftApConfig.getSsid());
        assertEquals(currentConfig.getBssid(), testSoftApConfig.getBssid());
        assertEquals(currentConfig.getSecurityType(), testSoftApConfig.getSecurityType());
        assertEquals(currentConfig.getPassphrase(), testSoftApConfig.getPassphrase());
        assertEquals(currentConfig.isHiddenSsid(), testSoftApConfig.isHiddenSsid());
        assertEquals(currentConfig.getBand(), testSoftApConfig.getBand());
        assertEquals(currentConfig.getChannel(), testSoftApConfig.getChannel());
        assertEquals(currentConfig.getMaxNumberOfClients(),
                testSoftApConfig.getMaxNumberOfClients());
        assertEquals(currentConfig.isAutoShutdownEnabled(),
                testSoftApConfig.isAutoShutdownEnabled());
        assertEquals(currentConfig.getShutdownTimeoutMillis(),
                testSoftApConfig.getShutdownTimeoutMillis());
        assertEquals(currentConfig.isClientControlByUserEnabled(),
                testSoftApConfig.isClientControlByUserEnabled());
        assertEquals(currentConfig.getAllowedClientList(),
                testSoftApConfig.getAllowedClientList());
        assertEquals(currentConfig.getBlockedClientList(),
                testSoftApConfig.getBlockedClientList());
        if (ApiLevelUtil.isAtLeast(Build.VERSION_CODES.S)) {
            assertEquals(currentConfig.getMacRandomizationSetting(),
                    testSoftApConfig.getMacRandomizationSetting());
            assertEquals(currentConfig.getChannels().toString(),
                    testSoftApConfig.getChannels().toString());
            assertEquals(currentConfig.isBridgedModeOpportunisticShutdownEnabled(),
                    testSoftApConfig.isBridgedModeOpportunisticShutdownEnabled());
            assertEquals(currentConfig.isIeee80211axEnabled(),
                    testSoftApConfig.isIeee80211axEnabled());
            if (ApiLevelUtil.isAtLeast(Build.VERSION_CODES.TIRAMISU)) {
                assertEquals(currentConfig.getBridgedModeOpportunisticShutdownTimeoutMillis(),
                        testSoftApConfig.getBridgedModeOpportunisticShutdownTimeoutMillis());
                assertEquals(currentConfig.isIeee80211beEnabled(),
                        testSoftApConfig.isIeee80211beEnabled());
                assertEquals(currentConfig.getVendorElements(),
                        testSoftApConfig.getVendorElements());
                assertArrayEquals(
                        currentConfig.getAllowedAcsChannels(SoftApConfiguration.BAND_2GHZ),
                        testSoftApConfig.getAllowedAcsChannels(SoftApConfiguration.BAND_2GHZ));
                assertArrayEquals(
                        currentConfig.getAllowedAcsChannels(SoftApConfiguration.BAND_5GHZ),
                        testSoftApConfig.getAllowedAcsChannels(SoftApConfiguration.BAND_5GHZ));
                assertArrayEquals(
                        currentConfig.getAllowedAcsChannels(SoftApConfiguration.BAND_6GHZ),
                        testSoftApConfig.getAllowedAcsChannels(SoftApConfiguration.BAND_6GHZ));
                assertEquals(currentConfig.getMaxChannelBandwidth(),
                        testSoftApConfig.getMaxChannelBandwidth());
            }
        }
    }

    private void turnOffWifiAndTetheredHotspotIfEnabled() throws Exception {
        if (sWifiManager.isWifiEnabled()) {
            Log.d(TAG, "Turn off WiFi");
            sWifiManager.setWifiEnabled(false);
            PollingCheck.check("Wifi turn off failed!", 2_000,
                    () -> !sWifiManager.isWifiEnabled());
        }
        if (sWifiManager.isWifiApEnabled()) {
            sTetheringManager.stopTethering(ConnectivityManager.TETHERING_WIFI);
            Log.d(TAG, "Turn off tethered Hotspot");
            PollingCheck.check("SoftAp turn off failed!", 2_000,
                    () -> !sWifiManager.isWifiApEnabled());
        }
    }

    private void verifyBridgedModeSoftApCallback(TestExecutor executor,
            TestSoftApCallback callback, boolean shouldFallbackSingleApMode, boolean isEnabled)
            throws Exception {
            // Verify state and info callback value as expected
            PollingCheck.check(
                    "SoftAp state and info on bridged AP mode are mismatch!!!"
                    + " shouldFallbackSingleApMode = " + shouldFallbackSingleApMode
                    + ", isEnabled = "  + isEnabled, 10_000,
                    () -> {
                        executor.runAll();
                        int expectedState = isEnabled ? WifiManager.WIFI_AP_STATE_ENABLED
                                : WifiManager.WIFI_AP_STATE_DISABLED;
                        int expectedInfoSize = isEnabled
                                ? (shouldFallbackSingleApMode ? 1 : 2) : 0;
                        return expectedState == callback.getCurrentState()
                                && callback.getCurrentSoftApInfoList().size() == expectedInfoSize;
                    });
    }

    private boolean shouldFallbackToSingleAp(int[] bands, SoftApCapability capability) {
        for (int band : bands) {
            if (capability.getSupportedChannelList(band).length == 0) {
                return true;
            }
        }
        return false;
    }

    private SparseIntArray getAvailableBandAndChannelForTesting(SoftApCapability capability) {
        final int[] bands = {SoftApConfiguration.BAND_2GHZ, SoftApConfiguration.BAND_5GHZ,
              SoftApConfiguration.BAND_6GHZ, SoftApConfiguration.BAND_60GHZ};
        SparseIntArray testBandsAndChannels = new SparseIntArray();
        if (!ApiLevelUtil.isAtLeast(Build.VERSION_CODES.S)) {
            testBandsAndChannels.put(SoftApConfiguration.BAND_2GHZ, 1);
            return testBandsAndChannels;
        }
        for (int band : bands) {
            int[] supportedList = capability.getSupportedChannelList(band);
            if (supportedList.length != 0) {
                testBandsAndChannels.put(band, supportedList[0]);
            }
        }
        return testBandsAndChannels;
    }

    @Test
    public void testLastConfiguredPassphraseIsKeepInSoftApConfigurationWhenChangingToNone()
            throws Exception {
        final SoftApConfiguration currentConfig = ShellIdentityUtils.invokeWithShellPermissions(
                sWifiManager::getSoftApConfiguration);
        UiAutomation uiAutomation = InstrumentationRegistry.getInstrumentation().getUiAutomation();
        try {
            uiAutomation.adoptShellPermissionIdentity();
            Mutable<String> lastPassphrase = new Mutable<>();
            final String testPassphrase = "testPassphrase";
            sWifiManager.setSoftApConfiguration(
                    new SoftApConfiguration.Builder(currentConfig)
                            .setPassphrase(testPassphrase,
                                    SoftApConfiguration.SECURITY_TYPE_WPA2_PSK).build());
            sWifiManager.queryLastConfiguredTetheredApPassphraseSinceBoot(mExecutor,
                    new Consumer<String>() {
                    @Override
                    public void accept(String value) {
                        synchronized (mLock) {
                            lastPassphrase.value = value;
                            mLock.notify();
                        }
                    }
                });
            synchronized (mLock) {
                mLock.wait(TEST_WAIT_DURATION_MS);
            }
            assertEquals(lastPassphrase.value, testPassphrase);

            sWifiManager.setSoftApConfiguration(
                    new SoftApConfiguration.Builder(currentConfig)
                            .setPassphrase(null,
                                    SoftApConfiguration.SECURITY_TYPE_OPEN).build());
            sWifiManager.queryLastConfiguredTetheredApPassphraseSinceBoot(mExecutor,
                    new Consumer<String>() {
                    @Override
                    public void accept(String value) {
                        synchronized (mLock) {
                            lastPassphrase.value = value;
                            mLock.notify();
                        }
                    }
                });
            synchronized (mLock) {
                mLock.wait(TEST_WAIT_DURATION_MS);
            }
            assertEquals(lastPassphrase.value, testPassphrase);
        } finally {
            // Restore SoftApConfiguration
            ShellIdentityUtils.invokeWithShellPermissions(
                    () -> sWifiManager.setSoftApConfiguration(currentConfig));
        }
    }

    /**
     * Skip the test if telephony is not supported and default country code
     * is not stored in system property.
     */
    private boolean shouldSkipCountryCodeDependentTest() {
        String countryCode = SystemProperties.get(BOOT_DEFAULT_WIFI_COUNTRY_CODE);
        return TextUtils.isEmpty(countryCode) && !WifiFeature.isTelephonySupported(sContext);
    }

    /**
     * Test SoftApConfiguration#getPersistentRandomizedMacAddress(). There are two test cases in
     * this test.
     * 1. configure two different SoftApConfigurations (different SSID) and verify that randomized
     * MAC address is different.
     * 2. configure A then B then A (SSIDs) and verify that the 1st and 3rd MAC addresses are the
     * same.
     */
    @Test
    public void testSoftApConfigurationGetPersistentRandomizedMacAddress() throws Exception {
        SoftApConfiguration currentConfig = ShellIdentityUtils.invokeWithShellPermissions(
                sWifiManager::getSoftApConfiguration);
        final String ssid = currentConfig.getSsid().length() <= 28
                ? currentConfig.getSsid() + "test"
                : "AndroidTest";
        ShellIdentityUtils.invokeWithShellPermissions(
                () -> sWifiManager.setSoftApConfiguration(new SoftApConfiguration.Builder()
                .setSsid(ssid).build()));
        SoftApConfiguration changedSsidConfig = ShellIdentityUtils.invokeWithShellPermissions(
                sWifiManager::getSoftApConfiguration);
        assertNotEquals(currentConfig.getPersistentRandomizedMacAddress(),
                changedSsidConfig.getPersistentRandomizedMacAddress());

        // set currentConfig
        ShellIdentityUtils.invokeWithShellPermissions(
                () -> sWifiManager.setSoftApConfiguration(currentConfig));

        SoftApConfiguration changedSsidBackConfig = ShellIdentityUtils.invokeWithShellPermissions(
                sWifiManager::getSoftApConfiguration);

        assertEquals(currentConfig.getPersistentRandomizedMacAddress(),
                changedSsidBackConfig.getPersistentRandomizedMacAddress());
    }

    /**
     * Test bridged AP enable succeeful when device supports it.
     * Also verify the callback info update correctly.
     * @throws Exception
     */
    @SdkSuppress(minSdkVersion = Build.VERSION_CODES.S)
    @Test
    public void testTetheredBridgedAp() throws Exception {
        // check that softap bridged mode is supported by the device
        if (!sWifiManager.isBridgedApConcurrencySupported()) {
            return;
        }
        runWithScanning(() -> {
            UiAutomation uiAutomation = InstrumentationRegistry.getInstrumentation().getUiAutomation();
            TestExecutor executor = new TestExecutor();
            TestSoftApCallback callback = new TestSoftApCallback(mLock);
            try {
                uiAutomation.adoptShellPermissionIdentity();
                // Off/On Wifi to make sure that we get the supported channel
                turnOffWifiAndTetheredHotspotIfEnabled();
                sWifiManager.setWifiEnabled(true);
                PollingCheck.check("Wifi turn on failed!", 2_000,
                        () -> sWifiManager.isWifiEnabled());
                turnOffWifiAndTetheredHotspotIfEnabled();
                verifyRegisterSoftApCallback(executor, callback);
                if (!callback.getCurrentSoftApCapability()
                        .areFeaturesSupported(SOFTAP_FEATURE_ACS_OFFLOAD)) {
                    return;
                }
                int[] testBands = {SoftApConfiguration.BAND_2GHZ,
                        SoftApConfiguration.BAND_5GHZ};
                int[] expectedBands = {SoftApConfiguration.BAND_2GHZ,
                        SoftApConfiguration.BAND_2GHZ | SoftApConfiguration.BAND_5GHZ};
                // Test bridged SoftApConfiguration set and get (setBands)
                SoftApConfiguration testSoftApConfig =
                        generateSoftApConfigBuilderWithSsid(TEST_SSID_UNQUOTED)
                        .setPassphrase(TEST_PASSPHRASE, SoftApConfiguration.SECURITY_TYPE_WPA2_PSK)
                        .setBands(expectedBands)
                        .build();

                boolean shouldFallbackToSingleAp = shouldFallbackToSingleAp(testBands,
                        callback.getCurrentSoftApCapability());
                verifySetGetSoftApConfig(testSoftApConfig);

                // start tethering which used to verify startTetheredHotspot
                sTetheringManager.startTethering(ConnectivityManager.TETHERING_WIFI, executor,
                    new TetheringManager.StartTetheringCallback() {
                        @Override
                        public void onTetheringFailed(final int result) {
                        }
                    });
                verifyBridgedModeSoftApCallback(executor, callback,
                        shouldFallbackToSingleAp, true /* enabled */);
                // stop tethering which used to verify stopSoftAp
                sTetheringManager.stopTethering(ConnectivityManager.TETHERING_WIFI);
                verifyBridgedModeSoftApCallback(executor, callback,
                        shouldFallbackToSingleAp, false /* disabled */);
            } finally {
                sWifiManager.unregisterSoftApCallback(callback);
                uiAutomation.dropShellPermissionIdentity();
            }
        }, false /* run with disabled */);
    }

    /**
     * Test bridged AP with forced channel config enable succeeful when device supports it.
     * Also verify the callback info update correctly.
     * @throws Exception
     */
    @SdkSuppress(minSdkVersion = Build.VERSION_CODES.S)
    @Test
    public void testTetheredBridgedApWifiForcedChannel() throws Exception {
        // check that softap bridged mode is supported by the device
        if (!sWifiManager.isBridgedApConcurrencySupported()) {
            return;
        }
        runWithScanning(() -> {
            UiAutomation uiAutomation = InstrumentationRegistry.getInstrumentation().getUiAutomation();
            TestExecutor executor = new TestExecutor();
            TestSoftApCallback callback = new TestSoftApCallback(mLock);
            try {
                uiAutomation.adoptShellPermissionIdentity();
                // Off/On Wifi to make sure that we get the supported channel
                turnOffWifiAndTetheredHotspotIfEnabled();
                sWifiManager.setWifiEnabled(true);
                PollingCheck.check("Wifi turn on failed!", 2_000,
                        () -> sWifiManager.isWifiEnabled());
                turnOffWifiAndTetheredHotspotIfEnabled();
                verifyRegisterSoftApCallback(executor, callback);

                boolean shouldFallbackToSingleAp = shouldFallbackToSingleAp(
                        new int[] {SoftApConfiguration.BAND_2GHZ, SoftApConfiguration.BAND_5GHZ},
                        callback.getCurrentSoftApCapability());

                // Test when there are supported channels in both of the bands.
                if (!shouldFallbackToSingleAp) {
                    // Test bridged SoftApConfiguration set and get (setChannels)
                    SparseIntArray dual_channels = new SparseIntArray(2);
                    dual_channels.put(SoftApConfiguration.BAND_2GHZ,
                            callback.getCurrentSoftApCapability()
                            .getSupportedChannelList(SoftApConfiguration.BAND_2GHZ)[0]);
                    dual_channels.put(SoftApConfiguration.BAND_5GHZ,
                            callback.getCurrentSoftApCapability()
                            .getSupportedChannelList(SoftApConfiguration.BAND_5GHZ)[0]);
                    SoftApConfiguration testSoftApConfig =
                            generateSoftApConfigBuilderWithSsid(TEST_SSID_UNQUOTED)
                            .setPassphrase(TEST_PASSPHRASE, SoftApConfiguration.SECURITY_TYPE_WPA2_PSK)
                            .setChannels(dual_channels)
                            .build();

                    verifySetGetSoftApConfig(testSoftApConfig);

                    // start tethering which used to verify startTetheredHotspot
                    sTetheringManager.startTethering(ConnectivityManager.TETHERING_WIFI, executor,
                        new TetheringManager.StartTetheringCallback() {
                            @Override
                            public void onTetheringFailed(final int result) {
                            }
                        });
                    verifyBridgedModeSoftApCallback(executor, callback,
                            shouldFallbackToSingleAp, true /* enabled */);
                    // stop tethering which used to verify stopSoftAp
                    sTetheringManager.stopTethering(ConnectivityManager.TETHERING_WIFI);
                    verifyBridgedModeSoftApCallback(executor, callback,
                            shouldFallbackToSingleAp, false /* disabled */);
                }
            } finally {
                sWifiManager.unregisterSoftApCallback(callback);
                uiAutomation.dropShellPermissionIdentity();
            }
        }, false /* run with disabled */);
    }

    /**
     * Verify that the configuration from getSoftApConfiguration is same as the configuration which
     * set by setSoftApConfiguration. And depends softap capability callback to test different
     * configuration.
     * @throws Exception
     */
    @VirtualDeviceNotSupported
    @Test
    public void testSetGetSoftApConfigurationAndSoftApCapabilityCallback() throws Exception {
        // check that softap mode is supported by the device
        if (!sWifiManager.isPortableHotspotSupported()) {
            return;
        }
        if (shouldSkipCountryCodeDependentTest()) {
            // skip the test  when there is no Country Code available
            return;
        }
        UiAutomation uiAutomation = InstrumentationRegistry.getInstrumentation().getUiAutomation();
        TestExecutor executor = new TestExecutor();
        TestSoftApCallback callback = new TestSoftApCallback(mLock);
        try {
            uiAutomation.adoptShellPermissionIdentity();
            turnOffWifiAndTetheredHotspotIfEnabled();
            verifyRegisterSoftApCallback(executor, callback);

            SoftApConfiguration.Builder softApConfigBuilder =
                     generateSoftApConfigBuilderWithSsid(TEST_SSID_UNQUOTED)
                    .setPassphrase(TEST_PASSPHRASE, SoftApConfiguration.SECURITY_TYPE_WPA2_PSK)
                    .setAutoShutdownEnabled(true)
                    .setShutdownTimeoutMillis(100000)
                    .setBand(getAvailableBandAndChannelForTesting(
                            callback.getCurrentSoftApCapability()).keyAt(0))
                    .setHiddenSsid(false);

            if (ApiLevelUtil.isAtLeast(Build.VERSION_CODES.TIRAMISU)) {
                softApConfigBuilder.setBridgedModeOpportunisticShutdownTimeoutMillis(30_000);
                softApConfigBuilder.setVendorElements(TEST_VENDOR_ELEMENTS);
                softApConfigBuilder.setAllowedAcsChannels(
                        SoftApConfiguration.BAND_2GHZ, new int[] {1, 6, 11});
                softApConfigBuilder.setAllowedAcsChannels(
                        SoftApConfiguration.BAND_5GHZ, new int[] {149});
                softApConfigBuilder.setAllowedAcsChannels(
                        SoftApConfiguration.BAND_6GHZ, new int[] {});
                softApConfigBuilder.setMaxChannelBandwidth(SoftApInfo.CHANNEL_WIDTH_80MHZ);
            }

            // Test SoftApConfiguration set and get
            verifySetGetSoftApConfig(softApConfigBuilder.build());

            boolean isSupportCustomizedMac = callback.getCurrentSoftApCapability()
                        .areFeaturesSupported(
                        SoftApCapability.SOFTAP_FEATURE_MAC_ADDRESS_CUSTOMIZATION)
                    && PropertyUtil.isVndkApiLevelNewerThan(Build.VERSION_CODES.S);

            //Test MAC_ADDRESS_CUSTOMIZATION supported config
            if (isSupportCustomizedMac) {
                softApConfigBuilder.setBssid(TEST_MAC)
                        .setMacRandomizationSetting(SoftApConfiguration.RANDOMIZATION_NONE);

                // Test SoftApConfiguration set and get
                verifySetGetSoftApConfig(softApConfigBuilder.build());
            }

            assertThat(callback.getCurrentSoftApCapability().getMaxSupportedClients())
                    .isGreaterThan(0);
            // Test CLIENT_FORCE_DISCONNECT supported config.
            if (callback.getCurrentSoftApCapability()
                    .areFeaturesSupported(
                    SoftApCapability.SOFTAP_FEATURE_CLIENT_FORCE_DISCONNECT)) {
                softApConfigBuilder.setMaxNumberOfClients(10);
                softApConfigBuilder.setClientControlByUserEnabled(true);
                softApConfigBuilder.setBlockedClientList(new ArrayList<>());
                softApConfigBuilder.setAllowedClientList(new ArrayList<>());
                verifySetGetSoftApConfig(softApConfigBuilder.build());
            }

            // Test SAE config
            if (callback.getCurrentSoftApCapability()
                    .areFeaturesSupported(SoftApCapability.SOFTAP_FEATURE_WPA3_SAE)) {
                softApConfigBuilder
                        .setPassphrase(TEST_PASSPHRASE,
                          SoftApConfiguration.SECURITY_TYPE_WPA3_SAE_TRANSITION);
                verifySetGetSoftApConfig(softApConfigBuilder.build());
                softApConfigBuilder
                        .setPassphrase(TEST_PASSPHRASE,
                        SoftApConfiguration.SECURITY_TYPE_WPA3_SAE);
                verifySetGetSoftApConfig(softApConfigBuilder.build());
            }

            // Test 11 BE control config
            if (ApiLevelUtil.isAtLeast(Build.VERSION_CODES.TIRAMISU)) {
                if (callback.getCurrentSoftApCapability()
                        .areFeaturesSupported(SoftApCapability.SOFTAP_FEATURE_IEEE80211_BE)) {
                    softApConfigBuilder.setIeee80211beEnabled(true);
                    verifySetGetSoftApConfig(softApConfigBuilder.build());
                }
            }

            if (ApiLevelUtil.isAtLeast(Build.VERSION_CODES.S)) {
                // Test 11 AX control config.
                if (callback.getCurrentSoftApCapability()
                        .areFeaturesSupported(SoftApCapability.SOFTAP_FEATURE_IEEE80211_AX)) {
                    softApConfigBuilder.setIeee80211axEnabled(true);
                    verifySetGetSoftApConfig(softApConfigBuilder.build());
                }
                softApConfigBuilder.setBridgedModeOpportunisticShutdownEnabled(false);
                verifySetGetSoftApConfig(softApConfigBuilder.build());
            }

        } finally {
            sWifiManager.unregisterSoftApCallback(callback);
            uiAutomation.dropShellPermissionIdentity();
        }
    }

    /**
     * Verify that startTetheredHotspot with specific channel config.
     * @throws Exception
     */
    @VirtualDeviceNotSupported
    @Test
    public void testStartTetheredHotspotWithChannelConfigAndSoftApStateAndInfoCallback()
            throws Exception {
        // check that softap mode is supported by the device
        if (!sWifiManager.isPortableHotspotSupported()) {
            return;
        }
        if (shouldSkipCountryCodeDependentTest()) {
            // skip the test  when there is no Country Code available
            return;
        }
        UiAutomation uiAutomation = InstrumentationRegistry.getInstrumentation().getUiAutomation();
        TestExecutor executor = new TestExecutor();
        TestSoftApCallback callback = new TestSoftApCallback(mLock);
        try {
            uiAutomation.adoptShellPermissionIdentity();
            // check that tethering is supported by the device
            if (!sTetheringManager.isTetheringSupported()) {
                return;
            }
            turnOffWifiAndTetheredHotspotIfEnabled();
            verifyRegisterSoftApCallback(executor, callback);

            SparseIntArray testBandsAndChannels = getAvailableBandAndChannelForTesting(
                    callback.getCurrentSoftApCapability());

            if (ApiLevelUtil.isAtLeast(Build.VERSION_CODES.S)) {
                assertNotEquals(0, testBandsAndChannels.size());
            }
            boolean isSupportCustomizedMac = callback.getCurrentSoftApCapability()
                    .areFeaturesSupported(
                    SoftApCapability.SOFTAP_FEATURE_MAC_ADDRESS_CUSTOMIZATION)
                    && PropertyUtil.isVndkApiLevelNewerThan(Build.VERSION_CODES.S);

            SoftApConfiguration.Builder testSoftApConfigBuilder =
                     generateSoftApConfigBuilderWithSsid(TEST_SSID_UNQUOTED)
                    .setPassphrase(TEST_PASSPHRASE, SoftApConfiguration.SECURITY_TYPE_WPA2_PSK)
                    .setChannel(testBandsAndChannels.valueAt(0), testBandsAndChannels.keyAt(0));

            if (isSupportCustomizedMac) {
                testSoftApConfigBuilder.setBssid(TEST_MAC)
                        .setMacRandomizationSetting(SoftApConfiguration.RANDOMIZATION_NONE);
            }

            SoftApConfiguration testSoftApConfig = testSoftApConfigBuilder.build();

            sWifiManager.setSoftApConfiguration(testSoftApConfig);

            // start tethering which used to verify startTetheredHotspot
            sTetheringManager.startTethering(ConnectivityManager.TETHERING_WIFI, executor,
                new TetheringManager.StartTetheringCallback() {
                    @Override
                    public void onTetheringFailed(final int result) {
                    }
                });

            // Verify state and info callback value as expected
            PollingCheck.check(
                    "SoftAp channel and state mismatch!!!", 10_000,
                    () -> {
                        executor.runAll();
                        int sapChannel = ScanResult.convertFrequencyMhzToChannelIfSupported(
                                callback.getCurrentSoftApInfo().getFrequency());
                        boolean isInfoCallbackSupported =
                                callback.getOnSoftapInfoChangedCalledCount() > 1;
                        if (isInfoCallbackSupported) {
                            return WifiManager.WIFI_AP_STATE_ENABLED == callback.getCurrentState()
                                && testBandsAndChannels.valueAt(0) == sapChannel;
                        }
                        return WifiManager.WIFI_AP_STATE_ENABLED == callback.getCurrentState();
                    });
            // After Soft Ap enabled, check SoftAp info if it supported
            if (isSupportCustomizedMac && callback.getOnSoftapInfoChangedCalledCount() > 1) {
                assertEquals(callback.getCurrentSoftApInfo().getBssid(), TEST_MAC);
            }
            if (PropertyUtil.isVndkApiLevelNewerThan(Build.VERSION_CODES.S)
                    && callback.getOnSoftapInfoChangedCalledCount() > 1) {
                assertNotEquals(callback.getCurrentSoftApInfo().getWifiStandard(),
                        ScanResult.WIFI_STANDARD_UNKNOWN);
            }

            if (callback.getOnSoftapInfoChangedCalledCount() > 1) {
                assertTrue(callback.getCurrentSoftApInfo().getAutoShutdownTimeoutMillis() > 0);
            }
        } finally {
            // stop tethering which used to verify stopSoftAp
            sTetheringManager.stopTethering(ConnectivityManager.TETHERING_WIFI);

            // Verify clean up
            PollingCheck.check(
                    "Stop Softap failed", 3_000,
                    () -> {
                        executor.runAll();
                        return WifiManager.WIFI_AP_STATE_DISABLED == callback.getCurrentState() &&
                                0 == callback.getCurrentSoftApInfo().getBandwidth() &&
                                0 == callback.getCurrentSoftApInfo().getFrequency();
                    });
            if (ApiLevelUtil.isAtLeast(Build.VERSION_CODES.S)) {
                assertEquals(callback.getCurrentSoftApInfo().getBssid(), null);
                assertEquals(ScanResult.WIFI_STANDARD_UNKNOWN,
                        callback.getCurrentSoftApInfo().getWifiStandard());
            }
            sWifiManager.unregisterSoftApCallback(callback);
            uiAutomation.dropShellPermissionIdentity();
        }
    }

    private static class TestActionListener implements WifiManager.ActionListener {
        private final Object mLock;
        public boolean onSuccessCalled = false;
        public boolean onFailedCalled = false;
        public int failureReason = -1;

        TestActionListener(Object lock) {
            mLock = lock;
        }

        @Override
        public void onSuccess() {
            synchronized (mLock) {
                onSuccessCalled = true;
                mLock.notify();
            }
        }

        @Override
        public void onFailure(int reason) {
            synchronized (mLock) {
                onFailedCalled = true;
                failureReason = reason;
                mLock.notify();
            }
        }
    }

    /**
     * Triggers connection to one of the saved networks using {@link WifiManager#connect(
     * int, WifiManager.ActionListener)} or {@link WifiManager#connect(WifiConfiguration,
     * WifiManager.ActionListener)}
     *
     * @param withNetworkId Use networkId for triggering connection, false for using
     *                      WifiConfiguration.
     * @throws Exception
     */
    private void testConnect(boolean withNetworkId) throws Exception {
        TestActionListener actionListener = new TestActionListener(mLock);
        UiAutomation uiAutomation = InstrumentationRegistry.getInstrumentation().getUiAutomation();
        List<WifiConfiguration> savedNetworks = null;
        try {
            uiAutomation.adoptShellPermissionIdentity();
            // These below API's only work with privileged permissions (obtained via shell identity
            // for test)
            savedNetworks = sWifiManager.getConfiguredNetworks();

            // Disable all the saved networks to trigger disconnect & disable autojoin.
            for (WifiConfiguration network : savedNetworks) {
                assertTrue(sWifiManager.disableNetwork(network.networkId));
            }
            waitForDisconnection();

            // Now trigger connection to the last saved network.
            WifiConfiguration savedNetworkToConnect =
                    savedNetworks.get(savedNetworks.size() - 1);
            synchronized (mLock) {
                try {
                    if (withNetworkId) {
                        sWifiManager.connect(savedNetworkToConnect.networkId, actionListener);
                    } else {
                        sWifiManager.connect(savedNetworkToConnect, actionListener);
                    }
                    // now wait for callback
                    mLock.wait(TEST_WAIT_DURATION_MS);
                } catch (InterruptedException e) {
                }
            }
            // check if we got the success callback
            assertTrue(actionListener.onSuccessCalled);
            // Wait for connection to complete & ensure we are connected to the saved network.
            waitForConnection();
            assertEquals(savedNetworkToConnect.networkId,
                    sWifiManager.getConnectionInfo().getNetworkId());
        } finally {
            // Re-enable all saved networks before exiting.
            if (savedNetworks != null) {
                for (WifiConfiguration network : savedNetworks) {
                    sWifiManager.enableNetwork(network.networkId, true);
                }
            }
            uiAutomation.dropShellPermissionIdentity();
        }
    }

    /**
     * Tests {@link WifiManager#connect(int, WifiManager.ActionListener)} to an existing saved
     * network.
     */
    @Test
    public void testConnectWithNetworkId() throws Exception {
        testConnect(true);
    }

    /**
     * Tests {@link WifiManager#connect(WifiConfiguration, WifiManager.ActionListener)} to an
     * existing saved network.
     */
    @Test
    public void testConnectWithWifiConfiguration() throws Exception {
        testConnect(false);

    }

    private static class TestNetworkCallback extends ConnectivityManager.NetworkCallback {
        private final Object mLock;
        public boolean onAvailableCalled = false;
        public Network network;
        public NetworkCapabilities networkCapabilities;

        TestNetworkCallback(Object lock) {
            mLock = lock;
        }

        @Override
        public void onAvailable(Network network) {
            synchronized (mLock) {
                onAvailableCalled = true;
                this.network = network;
            }
        }

        @Override
        public void onCapabilitiesChanged(Network network,
                NetworkCapabilities networkCapabilities) {
            synchronized (mLock) {
                this.networkCapabilities = networkCapabilities;
                mLock.notify();
            }
        }
    }

    private void waitForNetworkCallbackAndCheckForMeteredness(boolean expectMetered) {
        Object lock = new Object();
        TestNetworkCallback networkCallbackListener = new TestNetworkCallback(lock);
        synchronized (lock) {
            try {
                NetworkRequest.Builder networkRequestBuilder = new NetworkRequest.Builder()
                        .addTransportType(TRANSPORT_WIFI);
                if (expectMetered) {
                    networkRequestBuilder.removeCapability(NET_CAPABILITY_NOT_METERED);
                } else {
                    networkRequestBuilder.addCapability(NET_CAPABILITY_NOT_METERED);
                }
                // File a request for wifi network.
                sConnectivityManager.registerNetworkCallback(
                        networkRequestBuilder.build(), networkCallbackListener);
                // now wait for callback
                lock.wait(TEST_WAIT_DURATION_MS);
            } catch (InterruptedException e) {
            }
        }
        assertTrue(networkCallbackListener.onAvailableCalled);
    }

    /**
     * Tests {@link WifiManager#save(WifiConfiguration, WifiManager.ActionListener)} by marking
     * an existing saved network metered.
     */
    @Test
    public void testSave() throws Exception {
        Object lock = new Object();
        TestActionListener actionListener = new TestActionListener(lock);
        UiAutomation uiAutomation = InstrumentationRegistry.getInstrumentation().getUiAutomation();
        List<WifiConfiguration> savedNetworks = null;
        WifiConfiguration currentConfig = null;
        try {
            uiAutomation.adoptShellPermissionIdentity();
            // These below API's only work with privileged permissions (obtained via shell identity
            // for test)

            WifiInfo wifiInfo = sWifiManager.getConnectionInfo();
            savedNetworks = sWifiManager.getConfiguredNetworks();

            // find the current network's WifiConfiguration
            currentConfig = savedNetworks
                    .stream()
                    .filter(config -> config.networkId == wifiInfo.getNetworkId())
                    .findAny()
                    .get();

            // Ensure that the current network is not metered.
            assertNotEquals("Ensure that the saved network is configured as unmetered",
                    currentConfig.meteredOverride,
                    WifiConfiguration.METERED_OVERRIDE_METERED);

            // Disable all except the currently connected networks to avoid reconnecting to the
            // wrong network after later setting the current network as metered.
            for (WifiConfiguration network : savedNetworks) {
                if (network.networkId != currentConfig.networkId) {
                    assertTrue(sWifiManager.disableNetwork(network.networkId));
                }
            }

            // Check the network capabilities to ensure that the network is marked not metered.
            waitForNetworkCallbackAndCheckForMeteredness(false);

            // Now mark the network metered and save.
            synchronized (lock) {
                try {
                    WifiConfiguration modSavedNetwork = new WifiConfiguration(currentConfig);
                    modSavedNetwork.meteredOverride = WifiConfiguration.METERED_OVERRIDE_METERED;
                    sWifiManager.save(modSavedNetwork, actionListener);
                    // now wait for callback
                    lock.wait(TEST_WAIT_DURATION_MS);
                } catch (InterruptedException e) {
                }
            }
            // check if we got the success callback
            assertTrue(actionListener.onSuccessCalled);
            // Ensure we disconnected on marking the network metered & connect back.
            waitForDisconnection();
            waitForConnection();
            // Check the network capabilities to ensure that the network is marked metered now.
            waitForNetworkCallbackAndCheckForMeteredness(true);

        } finally {
            // Restore original network config (restore the meteredness back);
            if (currentConfig != null) {
                sWifiManager.updateNetwork(currentConfig);
            }
            // re-enable all networks
            if (savedNetworks != null) {
                for (WifiConfiguration network : savedNetworks) {
                    sWifiManager.enableNetwork(network.networkId, true);
                }
            }
            uiAutomation.dropShellPermissionIdentity();
        }
    }

    /**
     * Tests {@link WifiManager#forget(int, WifiManager.ActionListener)} by adding/removing a new
     * network.
     */
    @AsbSecurityTest(cveBugId = 159373687)
    @Test
    public void testForget() throws Exception {
        TestActionListener actionListener = new TestActionListener(mLock);
        UiAutomation uiAutomation = InstrumentationRegistry.getInstrumentation().getUiAutomation();
        int newNetworkId = INVALID_NETWORK_ID;
        try {
            uiAutomation.adoptShellPermissionIdentity();
            // These below API's only work with privileged permissions (obtained via shell identity
            // for test)
            List<WifiConfiguration> savedNetworks = sWifiManager.getConfiguredNetworks();

            WifiConfiguration newOpenNetwork = new WifiConfiguration();
            newOpenNetwork.SSID = "\"" + TEST_SSID_UNQUOTED + "\"";
            newNetworkId = sWifiManager.addNetwork(newOpenNetwork);
            assertNotEquals(INVALID_NETWORK_ID, newNetworkId);

            // Multi-type configurations might be converted to more than 1 configuration.
            assertThat(savedNetworks.size() < sWifiManager.getConfiguredNetworks().size()).isTrue();

            // Need an effectively-final holder because we need to modify inner Intent in callback.
            class IntentHolder {
                Intent intent;
            }
            IntentHolder intentHolder = new IntentHolder();
            sContext.registerReceiver(new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    Log.i(TAG, "Received CONFIGURED_NETWORKS_CHANGED_ACTION broadcast: " + intent);
                    intentHolder.intent = intent;
                }
            }, new IntentFilter(WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION));

            // Now remove the network
            synchronized (mLock) {
                try {
                    sWifiManager.forget(newNetworkId, actionListener);
                    // now wait for callback
                    mLock.wait(TEST_WAIT_DURATION_MS);
                } catch (InterruptedException e) {
                }
            }
            // check if we got the success callback
            assertTrue(actionListener.onSuccessCalled);

            PollingCheck.check(
                    "Didn't receive CONFIGURED_NETWORKS_CHANGED_ACTION broadcast!",
                    TEST_WAIT_DURATION_MS,
                    () -> intentHolder.intent != null);
            Intent intent = intentHolder.intent;
            assertEquals(WifiManager.CONFIGURED_NETWORKS_CHANGED_ACTION, intent.getAction());
            assertTrue(intent.getBooleanExtra(WifiManager.EXTRA_MULTIPLE_NETWORKS_CHANGED, false));
            assertEquals(WifiManager.CHANGE_REASON_REMOVED,
                    intent.getIntExtra(WifiManager.EXTRA_CHANGE_REASON, -1));
            assertNull(intent.getParcelableExtra(WifiManager.EXTRA_WIFI_CONFIGURATION));

            // Ensure that the new network has been successfully removed.
            assertEquals(savedNetworks.size(), sWifiManager.getConfiguredNetworks().size());
        } finally {
            // For whatever reason, if the forget fails, try removing using the public remove API.
            if (newNetworkId != INVALID_NETWORK_ID) sWifiManager.removeNetwork(newNetworkId);
            uiAutomation.dropShellPermissionIdentity();
        }
    }

    /**
     * Tests {@link WifiManager#getFactoryMacAddresses()} returns at least one valid MAC address.
     */
    @VirtualDeviceNotSupported
    @Test
    public void testGetFactoryMacAddresses() throws Exception {
        TestActionListener actionListener = new TestActionListener(mLock);
        UiAutomation uiAutomation = InstrumentationRegistry.getInstrumentation().getUiAutomation();
        int newNetworkId = INVALID_NETWORK_ID;
        try {
            uiAutomation.adoptShellPermissionIdentity();
            // Obtain the factory MAC address
            String[] macAddresses = sWifiManager.getFactoryMacAddresses();
            assertTrue("At list one MAC address should be returned.", macAddresses.length > 0);
            try {
                MacAddress mac = MacAddress.fromString(macAddresses[0]);
                assertNotEquals(WifiInfo.DEFAULT_MAC_ADDRESS, mac);
                assertFalse(MacAddressUtils.isMulticastAddress(mac));
            } catch (IllegalArgumentException e) {
                fail("Factory MAC address is invalid");
            }
        } finally {
            uiAutomation.dropShellPermissionIdentity();
        }
    }

    /**
     * Tests {@link WifiManager#isApMacRandomizationSupported()} does not crash.
     */
    @Test
    public void testIsApMacRandomizationSupported() throws Exception {
        sWifiManager.isApMacRandomizationSupported();
    }

    /**
     * Tests {@link WifiManager#isConnectedMacRandomizationSupported()} does not crash.
     */
    @Test
    public void testIsConnectedMacRandomizationSupported() throws Exception {
        sWifiManager.isConnectedMacRandomizationSupported();
    }

    /**
     * Tests {@link WifiManager#isPreferredNetworkOffloadSupported()} does not crash.
     */
    @Test
    public void testIsPreferredNetworkOffloadSupported() throws Exception {
        sWifiManager.isPreferredNetworkOffloadSupported();
    }

    /** Test that PNO scans reconnects us when the device is disconnected and the screen is off. */
    @Test
    public void testPnoScan() throws Exception {
        if (!sWifiManager.isPreferredNetworkOffloadSupported()) {
            // skip the test if PNO scanning is not supported
            return;
        }

        WifiInfo currentNetwork = ShellIdentityUtils.invokeWithShellPermissions(
                sWifiManager::getConnectionInfo);

        // disable all networks that aren't already disabled
        List<WifiConfiguration> savedNetworks = ShellIdentityUtils.invokeWithShellPermissions(
                sWifiManager::getConfiguredNetworks);
        Set<Integer> disabledNetworkIds = new HashSet<>();
        for (WifiConfiguration config : savedNetworks) {
            if (config.getNetworkSelectionStatus().getNetworkSelectionDisableReason()
                    == WifiConfiguration.NetworkSelectionStatus.DISABLED_NONE) {
                ShellIdentityUtils.invokeWithShellPermissions(
                        () -> sWifiManager.disableNetwork(config.networkId));
                disabledNetworkIds.add(config.networkId);
            }
        }

        try {
            // wait for disconnection from current network
            waitForDisconnection();

            // turn screen off
            turnScreenOffNoDelay();

            // re-enable the current network - this will trigger PNO
            ShellIdentityUtils.invokeWithShellPermissions(
                    () -> sWifiManager.enableNetwork(currentNetwork.getNetworkId(), false));
            disabledNetworkIds.remove(currentNetwork.getNetworkId());

            // PNO should reconnect us back to the network we disconnected from
            waitForConnection(WIFI_PNO_CONNECT_TIMEOUT_MILLIS);
        } finally {
            // re-enable disabled networks
            for (int disabledNetworkId : disabledNetworkIds) {
                ShellIdentityUtils.invokeWithShellPermissions(
                        () -> sWifiManager.enableNetwork(disabledNetworkId, true));
            }
        }
    }

    /**
     * Tests {@link WifiManager#isStaApConcurrencySupported().
     */
    @Test
    public void testIsStaApConcurrencySupported() throws Exception {
        // check that softap mode is supported by the device
        assumeTrue(sWifiManager.isPortableHotspotSupported());

        boolean isStaApConcurrencySupported = sWifiManager.isStaApConcurrencySupported();
        // start local only hotspot.
        TestLocalOnlyHotspotCallback callback = startLocalOnlyHotspot();
        try {
            if (isStaApConcurrencySupported) {
                assertTrue(sWifiManager.isWifiEnabled());
            } else {
                // no concurrency, wifi should be disabled.
                assertFalse(sWifiManager.isWifiEnabled());
            }
        } finally {
            // clean up local only hotspot no matter if assertion passed or failed
            stopLocalOnlyHotspot(callback, true);
        }

        assertTrue(sWifiManager.isWifiEnabled());
    }

    /**
     * state is a bitset, where bit 0 indicates whether there was data in, and bit 1 indicates
     * whether there was data out. Only count down on the latch once there was both data in and out.
     */
    private static class TestTrafficStateCallback implements WifiManager.TrafficStateCallback {
        public final CountDownLatch latch = new CountDownLatch(1);
        private int mAccumulator = 0;

        @Override
        public void onStateChanged(int state) {
            mAccumulator |= state;
            if (mAccumulator == DATA_ACTIVITY_INOUT) {
                latch.countDown();
            }
        }
    }

    private void sendTraffic() {
        boolean didAnyConnectionSucceed = false;
        for (int i = 0; i < 10; i++) {
            // Do some network operations
            HttpURLConnection connection = null;
            try {
                URL url = new URL("http://www.google.com/");
                connection = (HttpURLConnection) url.openConnection();
                connection.setInstanceFollowRedirects(false);
                connection.setConnectTimeout(TEST_WAIT_DURATION_MS);
                connection.setReadTimeout(TEST_WAIT_DURATION_MS);
                connection.setUseCaches(false);
                InputStream stream = connection.getInputStream();
                byte[] bytes = new byte[100];
                int receivedBytes = stream.read(bytes);
                if (receivedBytes > 0) {
                    didAnyConnectionSucceed = true;
                }
            } catch (Exception e) {
                // ignore
            } finally {
                if (connection != null) connection.disconnect();
            }
        }
        assertTrue("All connections failed!", didAnyConnectionSucceed);
    }

    /**
     * Tests {@link WifiManager#registerTrafficStateCallback(Executor,
     * WifiManager.TrafficStateCallback)} by sending some traffic.
     */
    @Test
    public void testTrafficStateCallback() throws Exception {
        TestTrafficStateCallback callback = new TestTrafficStateCallback();
        UiAutomation uiAutomation = InstrumentationRegistry.getInstrumentation().getUiAutomation();
        try {
            uiAutomation.adoptShellPermissionIdentity();

            // Turn screen on for wifi traffic polling.
            turnScreenOn();
            sWifiManager.registerTrafficStateCallback(
                    Executors.newSingleThreadExecutor(), callback);
            // Send some traffic to trigger the traffic state change callbacks.
            sendTraffic();
            // now wait for callback
            boolean success = callback.latch.await(TEST_WAIT_DURATION_MS, TimeUnit.MILLISECONDS);
            // check if we got the state changed callback with both data in and out
            assertTrue(success);
        } finally {
            turnScreenOff();
            sWifiManager.unregisterTrafficStateCallback(callback);
            uiAutomation.dropShellPermissionIdentity();
        }
    }

    /**
     * Tests {@link WifiManager#setScanAlwaysAvailable(boolean)} &
     * {@link WifiManager#isScanAlwaysAvailable()}.
     */
    @Test
    public void testScanAlwaysAvailable() throws Exception {
        UiAutomation uiAutomation = InstrumentationRegistry.getInstrumentation().getUiAutomation();
        Boolean currState = null;
        try {
            uiAutomation.adoptShellPermissionIdentity();
            currState = sWifiManager.isScanAlwaysAvailable();
            boolean newState = !currState;
            sWifiManager.setScanAlwaysAvailable(newState);
            PollingCheck.check(
                    "Wifi settings toggle failed!",
                    DURATION_SETTINGS_TOGGLE,
                    () -> sWifiManager.isScanAlwaysAvailable() == newState);
            assertEquals(newState, sWifiManager.isScanAlwaysAvailable());
        } finally {
            if (currState != null) sWifiManager.setScanAlwaysAvailable(currState);
            uiAutomation.dropShellPermissionIdentity();
        }
    }

    /**
     * Tests {@link WifiManager#setScanThrottleEnabled(boolean)} &
     * {@link WifiManager#isScanThrottleEnabled()}.
     */
    @Test
    public void testScanThrottleEnabled() throws Exception {
        UiAutomation uiAutomation = InstrumentationRegistry.getInstrumentation().getUiAutomation();
        Boolean currState = null;
        try {
            uiAutomation.adoptShellPermissionIdentity();
            currState = sWifiManager.isScanThrottleEnabled();
            boolean newState = !currState;
            sWifiManager.setScanThrottleEnabled(newState);
            PollingCheck.check(
                    "Wifi settings toggle failed!",
                    DURATION_SETTINGS_TOGGLE,
                    () -> sWifiManager.isScanThrottleEnabled() == newState);
            assertEquals(newState, sWifiManager.isScanThrottleEnabled());
        } finally {
            if (currState != null) sWifiManager.setScanThrottleEnabled(currState);
            uiAutomation.dropShellPermissionIdentity();
        }
    }

    /**
     * Tests {@link WifiManager#setAutoWakeupEnabled(boolean)} &
     * {@link WifiManager#isAutoWakeupEnabled()}.
     */
    @Test
    public void testAutoWakeUpEnabled() throws Exception {
        UiAutomation uiAutomation = InstrumentationRegistry.getInstrumentation().getUiAutomation();
        Boolean currState = null;
        try {
            uiAutomation.adoptShellPermissionIdentity();
            currState = sWifiManager.isAutoWakeupEnabled();
            boolean newState = !currState;
            sWifiManager.setAutoWakeupEnabled(newState);
            PollingCheck.check(
                    "Wifi settings toggle failed!",
                    DURATION_SETTINGS_TOGGLE,
                    () -> sWifiManager.isAutoWakeupEnabled() == newState);
            assertEquals(newState, sWifiManager.isAutoWakeupEnabled());
        } finally {
            if (currState != null) sWifiManager.setAutoWakeupEnabled(currState);
            uiAutomation.dropShellPermissionIdentity();
        }
    }

    /**
     * Tests {@link WifiManager#setVerboseLoggingEnabled(boolean)} &
     * {@link WifiManager#isVerboseLoggingEnabled()}.
     */
    @Test
    public void testVerboseLoggingEnabled() throws Exception {
        UiAutomation uiAutomation = InstrumentationRegistry.getInstrumentation().getUiAutomation();
        Boolean currState = null;
        TestWifiVerboseLoggingStatusChangedListener listener =
                WifiBuildCompat.isPlatformOrWifiModuleAtLeastS(sContext)
                        ? new TestWifiVerboseLoggingStatusChangedListener() : null;
        try {
            uiAutomation.adoptShellPermissionIdentity();
            if (listener != null) {
                sWifiManager.addWifiVerboseLoggingStatusChangedListener(mExecutor, listener);
            }
            currState = sWifiManager.isVerboseLoggingEnabled();
            boolean newState = !currState;
            if (listener != null) {
                assertEquals(0, listener.numCalls);
            }
            sWifiManager.setVerboseLoggingEnabled(newState);
            PollingCheck.check(
                    "Wifi verbose logging toggle failed!",
                    DURATION_SETTINGS_TOGGLE,
                    () -> sWifiManager.isVerboseLoggingEnabled() == newState);
            if (listener != null) {
                PollingCheck.check(
                        "Verbose logging listener timeout",
                        DURATION_SETTINGS_TOGGLE,
                        () -> listener.status == newState && listener.numCalls == 1);
            }
        } finally {
            if (currState != null) sWifiManager.setVerboseLoggingEnabled(currState);
            if (listener != null) {
                sWifiManager.removeWifiVerboseLoggingStatusChangedListener(listener);
            }
            uiAutomation.dropShellPermissionIdentity();
        }
    }

    /**
     * Tests {@link WifiManager#setVerboseLoggingLevel(int)}.
     */
    @Test
    public void testSetVerboseLogging() throws Exception {
        UiAutomation uiAutomation = InstrumentationRegistry.getInstrumentation().getUiAutomation();
        Boolean currState = null;
        try {
            uiAutomation.adoptShellPermissionIdentity();
            currState = sWifiManager.isVerboseLoggingEnabled();

            sWifiManager.setVerboseLoggingLevel(WifiManager.VERBOSE_LOGGING_LEVEL_ENABLED);
            assertTrue(sWifiManager.isVerboseLoggingEnabled());
            assertEquals(WifiManager.VERBOSE_LOGGING_LEVEL_ENABLED,
                    sWifiManager.getVerboseLoggingLevel());

            sWifiManager.setVerboseLoggingLevel(WifiManager.VERBOSE_LOGGING_LEVEL_DISABLED);
            assertFalse(sWifiManager.isVerboseLoggingEnabled());
            assertEquals(WifiManager.VERBOSE_LOGGING_LEVEL_DISABLED,
                    sWifiManager.getVerboseLoggingLevel());
        } finally {
            if (currState != null) sWifiManager.setVerboseLoggingEnabled(currState);
            uiAutomation.dropShellPermissionIdentity();
        }
    }

    /**
     * Test {@link WifiManager#setVerboseLoggingLevel(int)} for show key mode.
     */
    @SdkSuppress(minSdkVersion = Build.VERSION_CODES.S)
    @Test
    public void testSetVerboseLoggingShowKeyModeNonUserBuild() throws Exception {
        if (Build.TYPE.equals("user")) return;
        UiAutomation uiAutomation = InstrumentationRegistry.getInstrumentation().getUiAutomation();
        Boolean currState = null;
        try {
            uiAutomation.adoptShellPermissionIdentity();
            currState = sWifiManager.isVerboseLoggingEnabled();

            sWifiManager.setVerboseLoggingLevel(WifiManager.VERBOSE_LOGGING_LEVEL_ENABLED_SHOW_KEY);
            assertTrue(sWifiManager.isVerboseLoggingEnabled());
            assertEquals(WifiManager.VERBOSE_LOGGING_LEVEL_ENABLED_SHOW_KEY,
                    sWifiManager.getVerboseLoggingLevel());
        } finally {
            if (currState != null) sWifiManager.setVerboseLoggingEnabled(currState);
            uiAutomation.dropShellPermissionIdentity();
        }
    }

    /**
     * Test {@link WifiManager#setVerboseLoggingLevel(int)} for show key mode.
     */
    @SdkSuppress(minSdkVersion = Build.VERSION_CODES.S)
    @Test
    public void testSetVerboseLoggingShowKeyModeUserBuild() throws Exception {
        if (!Build.TYPE.equals("user")) return;
        UiAutomation uiAutomation = InstrumentationRegistry.getInstrumentation().getUiAutomation();
        Boolean currState = null;
        try {
            uiAutomation.adoptShellPermissionIdentity();
            currState = sWifiManager.isVerboseLoggingEnabled();

            sWifiManager.setVerboseLoggingLevel(WifiManager.VERBOSE_LOGGING_LEVEL_ENABLED_SHOW_KEY);
            assertTrue(sWifiManager.isVerboseLoggingEnabled());
            assertEquals(WifiManager.VERBOSE_LOGGING_LEVEL_ENABLED_SHOW_KEY,
                    sWifiManager.getVerboseLoggingLevel());
            fail("Verbosing logging show key mode should not be allowed for user build.");
        } catch (SecurityException e) {
            // expected
        } finally {
            if (currState != null) sWifiManager.setVerboseLoggingEnabled(currState);
            uiAutomation.dropShellPermissionIdentity();
        }
    }

    /**
     * Tests {@link WifiManager#factoryReset()} cannot be invoked from a non-privileged app.
     *
     * Note: This intentionally does not test the full reset functionality because it causes
     * the existing saved networks on the device to be lost after the test. If you add the
     * networks back after reset, the ownership of saved networks will change.
     */
    @Test
    public void testFactoryReset() throws Exception {
        List<WifiConfiguration> beforeSavedNetworks = ShellIdentityUtils.invokeWithShellPermissions(
                sWifiManager::getConfiguredNetworks);
        try {
            sWifiManager.factoryReset();
            fail("Factory reset should not be allowed for non-privileged apps");
        } catch (SecurityException e) {
            // expected
        }
        List<WifiConfiguration> afterSavedNetworks = ShellIdentityUtils.invokeWithShellPermissions(
                sWifiManager::getConfiguredNetworks);
        assertEquals(beforeSavedNetworks.size(), afterSavedNetworks.size());
    }

    /**
     * Test {@link WifiNetworkConnectionStatistics} does not crash.
     * TODO(b/150891569): deprecate it in Android S, this API is not used anywhere.
     */
    @Test
    public void testWifiNetworkConnectionStatistics() {
        new WifiNetworkConnectionStatistics();
        WifiNetworkConnectionStatistics stats = new WifiNetworkConnectionStatistics(0, 0);
        new WifiNetworkConnectionStatistics(stats);
    }

    /**
     * Verify that startRestrictingAutoJoinToSubscriptionId disconnects wifi and disables
     * auto-connect to non-carrier-merged networks. Then verify that
     * stopRestrictingAutoJoinToSubscriptionId makes the disabled networks clear to connect
     * again.
     */
    @SdkSuppress(minSdkVersion = Build.VERSION_CODES.S)
    @Test
    public void testStartAndStopRestrictingAutoJoinToSubscriptionId() throws Exception {
        int fakeSubscriptionId = 5;
        ShellIdentityUtils.invokeWithShellPermissions(() ->
                sWifiManager.startRestrictingAutoJoinToSubscriptionId(fakeSubscriptionId));
        waitForDisconnection();
        startScan();
        ensureNotConnected();
        ShellIdentityUtils.invokeWithShellPermissions(() ->
                sWifiManager.stopRestrictingAutoJoinToSubscriptionId());
        startScan();
        waitForConnection();
    }

    private class TestActiveCountryCodeChangedCallback implements
            WifiManager.ActiveCountryCodeChangedCallback  {
        private String mCurrentCountryCode;
        private boolean mIsOnActiveCountryCodeChangedCalled = false;
        private boolean mIsOnCountryCodeInactiveCalled = false;

        public boolean isOnActiveCountryCodeChangedCalled() {
            return mIsOnActiveCountryCodeChangedCalled;
        }

        public boolean isOnCountryCodeInactiveCalled() {
            return mIsOnCountryCodeInactiveCalled;
        }
        public void resetCallbackCallededHistory() {
            mIsOnActiveCountryCodeChangedCalled = false;
            mIsOnCountryCodeInactiveCalled = false;
        }

        public String getCurrentDriverCountryCode() {
            return mCurrentCountryCode;
        }

        @Override
        public void onActiveCountryCodeChanged(String country) {
            Log.d(TAG, "Receive DriverCountryCodeChanged to " + country);
            mCurrentCountryCode = country;
            mIsOnActiveCountryCodeChangedCalled = true;
        }

        @Override
        public void onCountryCodeInactive() {
            Log.d(TAG, "Receive onCountryCodeInactive");
            mCurrentCountryCode = null;
            mIsOnCountryCodeInactiveCalled = true;
        }
    }

    @SdkSuppress(minSdkVersion = Build.VERSION_CODES.TIRAMISU)
    @Test
    public void testActiveCountryCodeChangedCallback() throws Exception {
        if (!hasLocationFeature()) {
            // skip the test if location is not supported
            return;
        }
        if (!isLocationEnabled()) {
            fail("Please enable location for this test - since country code is not available"
                    + " when location is disabled!");
        }
        if (shouldSkipCountryCodeDependentTest()) {
            // skip the test when there is no Country Code available
            return;
        }
        TestActiveCountryCodeChangedCallback testCountryCodeChangedCallback =
                new TestActiveCountryCodeChangedCallback();
        TestExecutor executor = new TestExecutor();
        UiAutomation uiAutomation = InstrumentationRegistry.getInstrumentation().getUiAutomation();
        try {
            // Run with scanning disable to make sure there is no active mode.
            runWithScanning(() -> {
                uiAutomation.adoptShellPermissionIdentity();
                turnOffWifiAndTetheredHotspotIfEnabled();
                sWifiManager.registerActiveCountryCodeChangedCallback(
                        executor, testCountryCodeChangedCallback);


                PollingCheck.check(
                        "DriverCountryCode is non-null when wifi off",
                        5000,
                        () -> {
                            executor.runAll();
                            return testCountryCodeChangedCallback
                                        .isOnCountryCodeInactiveCalled()
                                    && testCountryCodeChangedCallback.getCurrentDriverCountryCode()
                                            == null;
                        });
                // Enable wifi to make sure country code has been updated.
                sWifiManager.setWifiEnabled(true);
                PollingCheck.check(
                        "DriverCountryCode is null when wifi on",
                        5000,
                        () -> {
                            executor.runAll();
                            return testCountryCodeChangedCallback
                                        .isOnActiveCountryCodeChangedCalled()
                                    && testCountryCodeChangedCallback.getCurrentDriverCountryCode()
                                            != null;
                        });
                // Disable wifi to trigger country code change
                sWifiManager.setWifiEnabled(false);
                PollingCheck.check(
                        "DriverCountryCode should be null when wifi off",
                        5000,
                        () -> {
                            executor.runAll();
                            return testCountryCodeChangedCallback.isOnCountryCodeInactiveCalled()
                                    && testCountryCodeChangedCallback
                                            .getCurrentDriverCountryCode() == null;
                        });
                sWifiManager.unregisterActiveCountryCodeChangedCallback(
                            testCountryCodeChangedCallback);
                testCountryCodeChangedCallback.resetCallbackCallededHistory();
                sWifiManager.setWifiEnabled(true);
                // Check there is no callback has been called.
                PollingCheck.check(
                        "Callback is called after unregister",
                        5000,
                        () -> {
                            executor.runAll();
                            return !testCountryCodeChangedCallback.isOnCountryCodeInactiveCalled()
                                    && !testCountryCodeChangedCallback
                                            .isOnActiveCountryCodeChangedCalled();
                        });
            }, false /* Run with disabled */);
        } finally {
            uiAutomation.dropShellPermissionIdentity();
        }
    }

    /**
     * Test that the wifi country code is either null, or a length-2 string.
     */
    @Test
    public void testGetCountryCode() throws Exception {
        String wifiCountryCode = ShellIdentityUtils.invokeWithShellPermissions(
                sWifiManager::getCountryCode);

        if (wifiCountryCode == null) {
            return;
        }
        assertEquals(2, wifiCountryCode.length());

        // assert that the country code is all uppercase
        assertEquals(wifiCountryCode.toUpperCase(Locale.US), wifiCountryCode);

        // skip if Telephony is unsupported
        if (!WifiFeature.isTelephonySupported(sContext)) {
            return;
        }

        String telephonyCountryCode = sContext.getSystemService(TelephonyManager.class)
                .getNetworkCountryIso();

        // skip if Telephony country code is unavailable
        if (telephonyCountryCode == null || telephonyCountryCode.isEmpty()) {
            return;
        }

        assertEquals(telephonyCountryCode, wifiCountryCode.toLowerCase(Locale.US));
    }

    /**
     * Helper function to test getCurrentNetwork
     * @param shouldDisableWifi true to disable wifi, false to disconnect
     * @throws Exception
     */
    private void testGetCurrentNetwork(boolean shouldDisableWifi) throws Exception {
        // ensure Wifi is connected
        ShellIdentityUtils.invokeWithShellPermissions(() -> sWifiManager.reconnect());
        PollingCheck.check(
                "Connection info network id is invalid - Please ensure there is a " +
                " saved network in range of this device",
                WIFI_CONNECT_TIMEOUT_MILLIS,
                () -> sWifiManager.getConnectionInfo().getNetworkId() != -1);
        PollingCheck.check(
                "Wifi current network is null - Please ensure there is a saved network " +
                        " in range of this device",
                WIFI_CONNECT_TIMEOUT_MILLIS,
                () -> ShellIdentityUtils.invokeWithShellPermissions(sWifiManager::getCurrentNetwork)
                        != null);

        String networkKey = sWifiManager.getConnectionInfo().getNetworkKey();
        assertNotNull(networkKey);

        Network wifiCurrentNetwork = ShellIdentityUtils.invokeWithShellPermissions(
                sWifiManager::getCurrentNetwork);
        assertNotNull(wifiCurrentNetwork);

        List<WifiConfiguration> configuredNetwork = ShellIdentityUtils.invokeWithShellPermissions(
                sWifiManager::getConfiguredNetworks);

        boolean isNetworkKeyExist = false;
        for (WifiConfiguration config : configuredNetwork) {
            if (config.getAllNetworkKeys().contains(networkKey)) {
                isNetworkKeyExist = true;
                break;
            }
        }

        assertTrue(isNetworkKeyExist);

        TestNetworkCallback networkCallbackListener = new TestNetworkCallback(mLock);
        synchronized (mLock) {
            try {
                // File a request for wifi network.
                sConnectivityManager.registerNetworkCallback(
                        new NetworkRequest.Builder()
                                .addTransportType(TRANSPORT_WIFI)
                                .build(),
                        networkCallbackListener);
                // now wait for callback
                mLock.wait(TEST_WAIT_DURATION_MS);
            } catch (InterruptedException e) {
            }
        }
        assertTrue(networkCallbackListener.onAvailableCalled);
        Network connectivityCurrentNetwork = networkCallbackListener.network;
        assertEquals(connectivityCurrentNetwork, wifiCurrentNetwork);

        if (shouldDisableWifi) {
            setWifiEnabled(false);
            PollingCheck.check(
                    "Wifi not disabled!",
                    20000,
                    () -> !sWifiManager.isWifiEnabled());
        } else {
            ShellIdentityUtils.invokeWithShellPermissions(() -> sWifiManager.disconnect());
        }
        PollingCheck.check(
                "Wifi not disconnected! Connection info network id still valid",
                20000,
                () -> sWifiManager.getConnectionInfo().getNetworkId() == -1);

        PollingCheck.check(
                "Wifi not disconnected! Current network is not null",
                WIFI_CONNECT_TIMEOUT_MILLIS,
                () -> ShellIdentityUtils.invokeWithShellPermissions(sWifiManager::getCurrentNetwork)
                        == null);
    }

    /**
     * Test that {@link WifiManager#getCurrentNetwork()} returns a Network object consistent
     * with {@link ConnectivityManager#registerNetworkCallback} when connected to a Wifi network,
     * and returns null when disconnected.
     */
    @Test
    public void testGetCurrentNetworkWifiDisconnected() throws Exception {
        testGetCurrentNetwork(false);
    }

    /**
     * Test that {@link WifiManager#getCurrentNetwork()} returns a Network object consistent
     * with {@link ConnectivityManager#registerNetworkCallback} when connected to a Wifi network,
     * and returns null when wifi disabled.
     */
    @Test
    public void testGetCurrentNetworkWifiDisabled() throws Exception {
        testGetCurrentNetwork(true);
    }

    /**
     * Tests {@link WifiManager#isWpa3SaeSupported()} does not crash.
     */
    @Test
    public void testIsWpa3SaeSupported() throws Exception {
        sWifiManager.isWpa3SaeSupported();
    }

    /**
     * Tests {@link WifiManager#isWpa3SuiteBSupported()} does not crash.
     */
    @Test
    public void testIsWpa3SuiteBSupported() throws Exception {
        sWifiManager.isWpa3SuiteBSupported();
    }

    /**
     * Tests {@link WifiManager#isEnhancedOpenSupported()} does not crash.
     */
    @Test
    public void testIsEnhancedOpenSupported() throws Exception {
        sWifiManager.isEnhancedOpenSupported();
    }

    /**
     * Test that {@link WifiManager#is5GHzBandSupported()} returns successfully in
     * both WiFi enabled/disabled states.
     * Note that the response depends on device support and hence both true/false
     * are valid responses.
     */
    @Test
    public void testIs5GhzBandSupported() throws Exception {
        // Check for 5GHz support with wifi enabled
        setWifiEnabled(true);
        PollingCheck.check(
                "Wifi not enabled!",
                20000,
                () -> sWifiManager.isWifiEnabled());
        boolean isSupportedEnabled = sWifiManager.is5GHzBandSupported();

        // Check for 5GHz support with wifi disabled
        setWifiEnabled(false);
        PollingCheck.check(
                "Wifi not disabled!",
                20000,
                () -> !sWifiManager.isWifiEnabled());
        boolean isSupportedDisabled = sWifiManager.is5GHzBandSupported();

        // If Support is true when WiFi is disable, then it has to be true when it is enabled.
        // Note, the reverse is a valid case.
        if (isSupportedDisabled) {
            assertTrue(isSupportedEnabled);
        }
    }

    /**
     * Test that {@link WifiManager#is6GHzBandSupported()} returns successfully in
     * both Wifi enabled/disabled states.
     * Note that the response depends on device support and hence both true/false
     * are valid responses.
     */
    @Test
    public void testIs6GhzBandSupported() throws Exception {
        // Check for 6GHz support with wifi enabled
        setWifiEnabled(true);
        PollingCheck.check(
                "Wifi not enabled!",
                20000,
                () -> sWifiManager.isWifiEnabled());
        boolean isSupportedEnabled = sWifiManager.is6GHzBandSupported();

        // Check for 6GHz support with wifi disabled
        setWifiEnabled(false);
        PollingCheck.check(
                "Wifi not disabled!",
                20000,
                () -> !sWifiManager.isWifiEnabled());
        boolean isSupportedDisabled = sWifiManager.is6GHzBandSupported();

        // If Support is true when WiFi is disable, then it has to be true when it is enabled.
        // Note, the reverse is a valid case.
        if (isSupportedDisabled) {
            assertTrue(isSupportedEnabled);
        }
    }

    /**
     * Test that {@link WifiManager#is60GHzBandSupported()} returns successfully in
     * both Wifi enabled/disabled states.
     * Note that the response depends on device support and hence both true/false
     * are valid responses.
     */
    @Test
    public void testIs60GhzBandSupported() throws Exception {
        if (!(WifiFeature.isWifiSupported(sContext)
                && ApiLevelUtil.isAtLeast(Build.VERSION_CODES.S))) {
            // skip the test if WiFi is not supported
            return;
        }

        // Check for 60GHz support with wifi enabled
        setWifiEnabled(true);
        PollingCheck.check(
                "Wifi not enabled!",
                20000,
                () -> sWifiManager.isWifiEnabled());
        boolean isSupportedEnabled = sWifiManager.is60GHzBandSupported();

        // Check for 60GHz support with wifi disabled
        setWifiEnabled(false);
        PollingCheck.check(
                "Wifi not disabled!",
                20000,
                () -> !sWifiManager.isWifiEnabled());
        boolean isSupportedDisabled = sWifiManager.is60GHzBandSupported();

        // If Support is true when WiFi is disable, then it has to be true when it is enabled.
        // Note, the reverse is a valid case.
        if (isSupportedDisabled) {
            assertTrue(isSupportedEnabled);
        }
    }

    /**
     * Test that {@link WifiManager#isWifiStandardSupported()} returns successfully in
     * both Wifi enabled/disabled states. The test is to be performed on
     * {@link WifiAnnotations}'s {@code WIFI_STANDARD_}
     * Note that the response depends on device support and hence both true/false
     * are valid responses.
     */
    @Test
    public void testIsWifiStandardsSupported() throws Exception {
        // Check for WiFi standards support with wifi enabled
        setWifiEnabled(true);
        PollingCheck.check(
                "Wifi not enabled!",
                20000,
                () -> sWifiManager.isWifiEnabled());
        boolean isLegacySupportedEnabled =
                sWifiManager.isWifiStandardSupported(ScanResult.WIFI_STANDARD_LEGACY);
        boolean is11nSupporedEnabled =
                sWifiManager.isWifiStandardSupported(ScanResult.WIFI_STANDARD_11N);
        boolean is11acSupportedEnabled =
                sWifiManager.isWifiStandardSupported(ScanResult.WIFI_STANDARD_11AC);
        boolean is11axSupportedEnabled =
                sWifiManager.isWifiStandardSupported(ScanResult.WIFI_STANDARD_11AX);
        boolean is11beSupportedEnabled =
                sWifiManager.isWifiStandardSupported(ScanResult.WIFI_STANDARD_11BE);

        // Check for WiFi standards support with wifi disabled
        setWifiEnabled(false);
        PollingCheck.check(
                "Wifi not disabled!",
                20000,
                () -> !sWifiManager.isWifiEnabled());

        boolean isLegacySupportedDisabled =
                sWifiManager.isWifiStandardSupported(ScanResult.WIFI_STANDARD_LEGACY);
        boolean is11nSupportedDisabled =
                sWifiManager.isWifiStandardSupported(ScanResult.WIFI_STANDARD_11N);
        boolean is11acSupportedDisabled =
                sWifiManager.isWifiStandardSupported(ScanResult.WIFI_STANDARD_11AC);
        boolean is11axSupportedDisabled =
                sWifiManager.isWifiStandardSupported(ScanResult.WIFI_STANDARD_11AX);
        boolean is11beSupportedDisabled =
                sWifiManager.isWifiStandardSupported(ScanResult.WIFI_STANDARD_11BE);

        if (isLegacySupportedDisabled) {
            assertTrue(isLegacySupportedEnabled);
        }

        if (is11nSupportedDisabled) {
            assertTrue(is11nSupporedEnabled);
        }

        if (is11acSupportedDisabled) {
            assertTrue(is11acSupportedEnabled);
        }

        if (is11axSupportedDisabled) {
            assertTrue(is11axSupportedEnabled);
        }

        if (is11beSupportedDisabled) {
            assertTrue(is11beSupportedEnabled);
        }
    }

    private static PasspointConfiguration createPasspointConfiguration() {
        PasspointConfiguration config = new PasspointConfiguration();
        HomeSp homeSp = new HomeSp();
        homeSp.setFqdn("test.com");
        homeSp.setFriendlyName("friendly name");
        homeSp.setRoamingConsortiumOis(new long[]{0x55, 0x66});
        config.setHomeSp(homeSp);
        Credential.SimCredential simCred = new Credential.SimCredential();
        simCred.setImsi("123456*");
        simCred.setEapType(23 /* EAP_AKA */);
        Credential cred = new Credential();
        cred.setRealm("realm");
        cred.setSimCredential(simCred);
        config.setCredential(cred);

        return config;
    }

    /**
     * Tests {@link WifiManager#addOrUpdatePasspointConfiguration(PasspointConfiguration)}
     * adds a Passpoint configuration correctly by getting it once it is added, and comparing it
     * to the local copy of the configuration.
     */
    @Test
    public void testAddOrUpdatePasspointConfiguration() throws Exception {
        // Create and install a Passpoint configuration
        PasspointConfiguration passpointConfiguration = createPasspointConfiguration();
        UiAutomation uiAutomation = InstrumentationRegistry.getInstrumentation().getUiAutomation();
        try {
            uiAutomation.adoptShellPermissionIdentity();
            sWifiManager.addOrUpdatePasspointConfiguration(passpointConfiguration);

            // Compare configurations
            List<PasspointConfiguration> configurations = sWifiManager.getPasspointConfigurations();
            assertNotNull("The installed passpoint profile is missing", configurations);
            assertEquals(passpointConfiguration, getTargetPasspointConfiguration(configurations,
                    passpointConfiguration.getUniqueId()));
        } finally {
            // Clean up
            sWifiManager.removePasspointConfiguration(passpointConfiguration.getHomeSp().getFqdn());
            uiAutomation.dropShellPermissionIdentity();
        }
    }

    /**
     * Tests {@link WifiManager#setPasspointMeteredOverride(String, int)}
     * adds a Passpoint configuration correctly, check the default metered setting. Use API change
     * metered override, verify Passpoint configuration changes with it.
     */
    @Test
    public void testSetPasspointMeteredOverride() throws Exception {
        // Create and install a Passpoint configuration
        PasspointConfiguration passpointConfiguration = createPasspointConfiguration();
        String fqdn = passpointConfiguration.getHomeSp().getFqdn();
        String uniqueId = passpointConfiguration.getUniqueId();
        UiAutomation uiAutomation = InstrumentationRegistry.getInstrumentation().getUiAutomation();

        try {
            uiAutomation.adoptShellPermissionIdentity();
            sWifiManager.addOrUpdatePasspointConfiguration(passpointConfiguration);
            PasspointConfiguration saved = getTargetPasspointConfiguration(
                    sWifiManager.getPasspointConfigurations(), uniqueId);
            assertNotNull("The installed passpoint profile is missing", saved);
            // Verify meter override setting.
            assertEquals("Metered overrider default should be none",
                    WifiConfiguration.METERED_OVERRIDE_NONE, saved.getMeteredOverride());
            // Change the meter override setting.
            sWifiManager.setPasspointMeteredOverride(fqdn,
                    WifiConfiguration.METERED_OVERRIDE_METERED);
            // Verify passpoint config change with the new setting.
            saved = getTargetPasspointConfiguration(
                    sWifiManager.getPasspointConfigurations(), uniqueId);
            assertNotNull("The installed passpoint profile is missing", saved);
            assertEquals("Metered override should be metered",
                    WifiConfiguration.METERED_OVERRIDE_METERED, saved.getMeteredOverride());
        } finally {
            // Clean up
            sWifiManager.removePasspointConfiguration(fqdn);
            uiAutomation.dropShellPermissionIdentity();
        }
    }

    /**
     * Tests that
     * {@link WifiManager#startSubscriptionProvisioning(OsuProvider, Executor, ProvisioningCallback)}
     * starts a subscription provisioning, and confirm a status callback invoked once.
     */
    @Test
    public void testStartSubscriptionProvisioning() throws Exception {
        // Using Java reflection to construct an OsuProvider instance because its constructor is
        // hidden and not available to apps.
        Class<?> osuProviderClass = Class.forName("android.net.wifi.hotspot2.OsuProvider");
        Constructor<?> osuProviderClassConstructor = osuProviderClass.getConstructor(String.class,
                Map.class, String.class, Uri.class, String.class, List.class);

        OsuProvider osuProvider = (OsuProvider) osuProviderClassConstructor.newInstance(TEST_SSID,
                TEST_FRIENDLY_NAMES, TEST_SERVICE_DESCRIPTION, TEST_SERVER_URI, TEST_NAI,
                TEST_METHOD_LIST);
        TestProvisioningCallback callback = new TestProvisioningCallback(mLock);
        UiAutomation uiAutomation = InstrumentationRegistry.getInstrumentation().getUiAutomation();
        try {
            uiAutomation.adoptShellPermissionIdentity();
            synchronized (mLock) {
                // Start a subscription provisioning for a non-existent Passpoint R2 AP
                sWifiManager.startSubscriptionProvisioning(osuProvider, mExecutor, callback);
                mLock.wait(TEST_WAIT_DURATION_MS);
            }
        } finally {
            uiAutomation.dropShellPermissionIdentity();
        }
        waitForDisconnection();
        // Expect only a single callback event, connecting. Since AP doesn't exist, it ends here
        assertEquals(ProvisioningCallback.OSU_STATUS_AP_CONNECTING, callback.mProvisioningStatus);
        // No failure callbacks expected
        assertEquals(0, callback.mProvisioningFailureStatus);
        // No completion callback expected
        assertFalse(callback.mProvisioningComplete);
        ShellIdentityUtils.invokeWithShellPermissions(() -> sWifiManager.setWifiEnabled(false));
        PollingCheck.check("Wifi not disabled!", 20000,
                () -> !sWifiManager.isWifiEnabled());
    }

    /**
     * Tests {@link WifiManager#setTdlsEnabled(InetAddress, boolean)} does not crash.
     */
    @Test
    public void testSetTdlsEnabled() throws Exception {
        InetAddress inetAddress = InetAddress.getByName(TEST_IP_ADDRESS);

        sWifiManager.setTdlsEnabled(inetAddress, true);
        Thread.sleep(50);
        sWifiManager.setTdlsEnabled(inetAddress, false);
    }

    /**
     * Tests {@link WifiManager#setTdlsEnabledWithMacAddress(String, boolean)} does not crash.
     */
    @Test
    public void testSetTdlsEnabledWithMacAddress() throws Exception {
        sWifiManager.setTdlsEnabledWithMacAddress(TEST_MAC_ADDRESS, true);
        Thread.sleep(50);
        sWifiManager.setTdlsEnabledWithMacAddress(TEST_MAC_ADDRESS, false);
    }

    /**
     * Verify the usage of {@code WifiManager#isTdlsOperationCurrentlyAvailable}.
     */
    @Test
    public void testIsTdlsOperationCurrentlyAvailable() throws Exception {
        boolean expectedResult = sWifiManager.isTdlsSupported();
        AtomicBoolean enabled = new AtomicBoolean(false);
        sWifiManager.isTdlsOperationCurrentlyAvailable(mExecutor,
                (enabledLocal) -> {
                    synchronized (mLock) {
                        enabled.set(enabledLocal);
                        mLock.notify();
                    }
                });
        synchronized (mLock) {
            mLock.wait(TEST_WAIT_DURATION_MS);
        }
        assertEquals(expectedResult, enabled.get());
    }

    /**
     * Verify the usage of {@code WifiManager#getMaxSupportedConcurrentTdlsSessions}.
     */
    @SdkSuppress(minSdkVersion = Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
    @Test
    public void testGetMaxSupportedConcurrentTdlsSessions() throws Exception {
        if (!sWifiManager.isTdlsSupported()) {
            // skip the test if TDLS is not supported
            return;
        }

        AtomicInteger maxNumOfTdlsSessions = new AtomicInteger(0);
        sWifiManager.getMaxSupportedConcurrentTdlsSessions(mExecutor,
                (maxNumOfTdlsSessionsLocal) -> {
                    synchronized (mLock) {
                        maxNumOfTdlsSessions.set(maxNumOfTdlsSessionsLocal);
                        mLock.notify();
                    }
                });
        synchronized (mLock) {
            mLock.wait(TEST_WAIT_DURATION_MS);
        }
        // {@code WifiManager#getMaxSupportedConcurrentTdlsSessions} returns -1
        // if HAL doesn't provide this TDLS capability.
        assertTrue(maxNumOfTdlsSessions.get() == -1 || maxNumOfTdlsSessions.get() > 0);
    }

    /**
     * Verify the usage of
     * {@link WifiManager#setTdlsEnabled(InetAddress, boolean, Executor, Consumer)}.
     */
    @Test
    public void testSetTdlsEnabledWithIpAddressConsumerModel() throws Exception {
        if (!sWifiManager.isTdlsSupported()) {
            // skip the test if TDLS is not supported
            return;
        }

        InetAddress inetAddress = InetAddress.getByName(TEST_IP_ADDRESS);
        sWifiManager.setTdlsEnabled(inetAddress, true, mExecutor, (e) -> {});
        sWifiManager.setTdlsEnabled(inetAddress, false, mExecutor, (e) -> {});
    }

    /**
     * Verify the usage of
     * {@link WifiManager#setTdlsEnabledWithMacAddress(String, boolean, Executor, Consumer)}
     * and {@link WifiManager#getNumberOfEnabledTdlsSessions(Executor, Consumer)}.
     */
    @Test
    public void testSetTdlsEnabledWithMacAddressConsumerModel() throws Exception {
        if (!sWifiManager.isTdlsSupported()) {
            // skip the test if TDLS is not supported
            return;
        }

        AtomicBoolean enabled = new AtomicBoolean(false);
        AtomicInteger numOfTdlsSessions = new AtomicInteger(0);
        Consumer<Integer> listener2 = new Consumer<Integer>() {
            @Override
            public void accept(Integer value) {
                synchronized (mLock) {
                    numOfTdlsSessions.set(value);
                    mLock.notify();
                }
            }
        };

        sWifiManager.setTdlsEnabledWithMacAddress(TEST_MAC_ADDRESS, true, mExecutor,
                (enabledLocal) -> {
                    synchronized (mLock) {
                        enabled.set(enabledLocal);
                        mLock.notify();
                    }
                });
        synchronized (mLock) {
            mLock.wait(TEST_WAIT_DURATION_MS);
        }
        assertTrue(enabled.get());
        sWifiManager.getNumberOfEnabledTdlsSessions(mExecutor, listener2);
        synchronized (mLock) {
            mLock.wait(TEST_WAIT_DURATION_MS);
        }
        assertEquals(1, numOfTdlsSessions.get());

        sWifiManager.setTdlsEnabledWithMacAddress(TEST_MAC_ADDRESS, false, mExecutor, (e) -> {});
        sWifiManager.getNumberOfEnabledTdlsSessions(mExecutor, listener2);
        synchronized (mLock) {
            mLock.wait(TEST_WAIT_DURATION_MS);
        }
        assertEquals(0, numOfTdlsSessions.get());
    }

    /**
     * Verify WifiNetworkSuggestion.Builder.setMacRandomizationSetting(WifiNetworkSuggestion
     * .RANDOMIZATION_NON_PERSISTENT) creates a
     * WifiConfiguration with macRandomizationSetting == RANDOMIZATION_NON_PERSISTENT.
     * Then verify by default, a WifiConfiguration created by suggestions should have
     * macRandomizationSetting == RANDOMIZATION_PERSISTENT.
     */
    @SdkSuppress(minSdkVersion = Build.VERSION_CODES.S)
    @Test
    public void testSuggestionBuilderNonPersistentRandomization() throws Exception {
        WifiNetworkSuggestion suggestion = new WifiNetworkSuggestion.Builder()
                .setSsid(TEST_SSID).setWpa2Passphrase(TEST_PASSPHRASE)
                .setMacRandomizationSetting(WifiNetworkSuggestion.RANDOMIZATION_NON_PERSISTENT)
                .build();
        assertEquals(WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS,
                sWifiManager.addNetworkSuggestions(Arrays.asList(suggestion)));
        verifySuggestionFoundWithMacRandomizationSetting(TEST_SSID,
                WifiNetworkSuggestion.RANDOMIZATION_NON_PERSISTENT);

        suggestion = new WifiNetworkSuggestion.Builder()
                .setSsid(TEST_SSID).setWpa2Passphrase(TEST_PASSPHRASE)
                .build();
        assertEquals(WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS,
                sWifiManager.addNetworkSuggestions(Arrays.asList(suggestion)));
        verifySuggestionFoundWithMacRandomizationSetting(TEST_SSID,
                WifiNetworkSuggestion.RANDOMIZATION_PERSISTENT);
    }

    private void verifySuggestionFoundWithMacRandomizationSetting(String ssid,
            int macRandomizationSetting) {
        List<WifiNetworkSuggestion> retrievedSuggestions = sWifiManager.getNetworkSuggestions();
        for (WifiNetworkSuggestion entry : retrievedSuggestions) {
            if (entry.getSsid().equals(ssid)) {
                assertEquals(macRandomizationSetting, entry.getMacRandomizationSetting());
                return; // pass test after the MAC randomization setting is verified.
            }
        }
        fail("WifiNetworkSuggestion not found for SSID=" + ssid + ", macRandomizationSetting="
                + macRandomizationSetting);
    }

    /**
     * Tests {@link WifiManager#getWifiConfigForMatchedNetworkSuggestionsSharedWithUser(List)}
     */
    @Test
    public void testGetAllWifiConfigForMatchedNetworkSuggestion() {
        UiAutomation uiAutomation = InstrumentationRegistry.getInstrumentation().getUiAutomation();
        ScanResult scanResult = new ScanResult();
        scanResult.SSID = TEST_SSID;
        scanResult.capabilities = TEST_PSK_CAP;
        scanResult.BSSID = TEST_BSSID;
        List<ScanResult> testList = Arrays.asList(scanResult);
        WifiNetworkSuggestion suggestion = new WifiNetworkSuggestion.Builder()
                .setSsid(TEST_SSID).setWpa2Passphrase(TEST_PASSPHRASE).build();

        assertEquals(WifiManager.STATUS_NETWORK_SUGGESTIONS_SUCCESS,
                sWifiManager.addNetworkSuggestions(Arrays.asList(suggestion)));
        List<WifiConfiguration> matchedResult;
        try {
            uiAutomation.adoptShellPermissionIdentity();
            matchedResult = sWifiManager
                    .getWifiConfigForMatchedNetworkSuggestionsSharedWithUser(testList);
        } finally {
            uiAutomation.dropShellPermissionIdentity();
        }
        // As suggestion is not approved, will return empty list.
        assertTrue(matchedResult.isEmpty());
    }

    /**
     * Tests {@link WifiManager#getMatchingScanResults(List, List)}
     */
    @Test
    public void testGetMatchingScanResults() {
        // Create pair of ScanResult and WifiNetworkSuggestion
        ScanResult scanResult = new ScanResult();
        scanResult.SSID = TEST_SSID;
        scanResult.capabilities = TEST_PSK_CAP;
        scanResult.BSSID = TEST_BSSID;

        WifiNetworkSuggestion suggestion = new WifiNetworkSuggestion.Builder()
                .setSsid(TEST_SSID).setWpa2Passphrase(TEST_PASSPHRASE).build();

        Map<WifiNetworkSuggestion, List<ScanResult>> matchedResults = sWifiManager
                .getMatchingScanResults(Arrays.asList(suggestion), Arrays.asList(scanResult));
        // Verify result is matched pair of ScanResult and WifiNetworkSuggestion
        assertEquals(scanResult.SSID, matchedResults.get(suggestion).get(0).SSID);

        // Change ScanResult to unmatched should return empty result.
        scanResult.SSID = TEST_SSID_UNQUOTED;
        matchedResults = sWifiManager
                .getMatchingScanResults(Arrays.asList(suggestion), Arrays.asList(scanResult));
        assertTrue(matchedResults.get(suggestion).isEmpty());
    }

    /**
     * Tests {@link WifiManager#disableEphemeralNetwork(String)}.
     */
    @Test
    public void testDisableEphemeralNetwork() throws Exception {
        UiAutomation uiAutomation = InstrumentationRegistry.getInstrumentation().getUiAutomation();
        List<WifiConfiguration> savedNetworks = null;
        try {
            uiAutomation.adoptShellPermissionIdentity();
            // Temporarily disable on all networks.
            savedNetworks = sWifiManager.getConfiguredNetworks();
            for (WifiConfiguration network : savedNetworks) {
                sWifiManager.disableEphemeralNetwork(network.SSID);
            }
            // trigger a disconnect and wait for disconnect.
            sWifiManager.disconnect();
            waitForDisconnection();

            // Now trigger scan and ensure that the device does not connect to any networks.
            sWifiManager.startScan();
            ensureNotConnected();
        } finally {
            uiAutomation.dropShellPermissionIdentity();
            setWifiEnabled(false);
        }
    }

    /**
     * Tests {@link WifiManager#allowAutojoin(int, boolean)}.
     */
    @Test
    public void testAllowAutojoin() throws Exception {
        UiAutomation uiAutomation = InstrumentationRegistry.getInstrumentation().getUiAutomation();
        List<WifiConfiguration> savedNetworks = null;
        try {
            uiAutomation.adoptShellPermissionIdentity();
            // disable autojoin on all networks.
            savedNetworks = sWifiManager.getConfiguredNetworks();
            for (WifiConfiguration network : savedNetworks) {
                sWifiManager.allowAutojoin(network.networkId, false);
            }
            // trigger a disconnect and wait for disconnect.
            sWifiManager.disconnect();
            waitForDisconnection();

            // Now trigger scan and ensure that the device does not connect to any networks.
            sWifiManager.startScan();
            ensureNotConnected();

            // Now enable autojoin on all networks.
            for (WifiConfiguration network : savedNetworks) {
                sWifiManager.allowAutojoin(network.networkId, true);
            }

            // Trigger a scan & wait for connection to one of the saved networks.
            sWifiManager.startScan();
            waitForConnection();
        } finally {
            // Restore auto join state.
            if (savedNetworks != null) {
                for (WifiConfiguration network : savedNetworks) {
                    sWifiManager.allowAutojoin(network.networkId, network.allowAutojoin);
                }
            }
            uiAutomation.dropShellPermissionIdentity();
        }
    }

    /**
     * Tests {@link WifiManager#allowAutojoinPasspoint(String, boolean)}.
     */
    @Test
    public void testAllowAutojoinPasspoint() throws Exception {
        PasspointConfiguration passpointConfiguration = createPasspointConfiguration();
        UiAutomation uiAutomation = InstrumentationRegistry.getInstrumentation().getUiAutomation();
        try {
            uiAutomation.adoptShellPermissionIdentity();
            sWifiManager.addOrUpdatePasspointConfiguration(passpointConfiguration);
            // Turn off auto-join
            sWifiManager.allowAutojoinPasspoint(
                    passpointConfiguration.getHomeSp().getFqdn(), false);
            // Turn on auto-join
            sWifiManager.allowAutojoinPasspoint(
                    passpointConfiguration.getHomeSp().getFqdn(), true);
        } finally {
            sWifiManager.removePasspointConfiguration(passpointConfiguration.getHomeSp().getFqdn());
            uiAutomation.dropShellPermissionIdentity();
        }
    }

    /**
     * Tests {@link WifiManager#allowAutojoinGlobal(boolean)}.
     */
    @Test
    public void testAllowAutojoinGlobal() throws Exception {
        UiAutomation uiAutomation = InstrumentationRegistry.getInstrumentation().getUiAutomation();
        try {
            uiAutomation.adoptShellPermissionIdentity();
            // disable autojoin on all networks.
            sWifiManager.allowAutojoinGlobal(false);

            // trigger a disconnect and wait for disconnect.
            sWifiManager.disconnect();
            waitForDisconnection();

            // Now trigger scan and ensure that the device does not connect to any networks.
            sWifiManager.startScan();
            ensureNotConnected();

            // verify null is returned when attempting to get current configured network.
            WifiConfiguration config = sWifiManager.getPrivilegedConnectedNetwork();
            assertNull("config should be null because wifi is not connected", config);

            // Now enable autojoin on all networks.
            sWifiManager.allowAutojoinGlobal(true);

            // Trigger a scan & wait for connection to one of the saved networks.
            sWifiManager.startScan();
            waitForConnection();
        } finally {
            // Re-enable auto join if the test fails for some reason.
            sWifiManager.allowAutojoinGlobal(true);
            uiAutomation.dropShellPermissionIdentity();
        }
    }

    /**
     * Verify the invalid and valid usages of {@code WifiManager#queryAutojoinGlobal}.
     */
    @SdkSuppress(minSdkVersion = Build.VERSION_CODES.TIRAMISU)
    @Test
    public void testQueryAutojoinGlobal() throws Exception {
        AtomicBoolean enabled = new AtomicBoolean(false);
        Consumer<Boolean> listener = new Consumer<Boolean>() {
            @Override
            public void accept(Boolean value) {
                synchronized (mLock) {
                    enabled.set(value);
                    mLock.notify();
                }
            }
        };
        // Test invalid inputs trigger IllegalArgumentException
        assertThrows("null executor should trigger exception", NullPointerException.class,
                () -> sWifiManager.queryAutojoinGlobal(null, listener));
        assertThrows("null listener should trigger exception", NullPointerException.class,
                () -> sWifiManager.queryAutojoinGlobal(mExecutor, null));

        // Test caller with no permission triggers SecurityException.
        assertThrows("No permission should trigger SecurityException", SecurityException.class,
                () -> sWifiManager.queryAutojoinGlobal(mExecutor, listener));

        UiAutomation uiAutomation = InstrumentationRegistry.getInstrumentation().getUiAutomation();
        try {
            uiAutomation.adoptShellPermissionIdentity();
            // Test get/set autojoin global enabled
            sWifiManager.allowAutojoinGlobal(true);
            sWifiManager.queryAutojoinGlobal(mExecutor, listener);
            synchronized (mLock) {
                mLock.wait(TEST_WAIT_DURATION_MS);
            }
            assertTrue(enabled.get());

            // Test get/set autojoin global disabled
            sWifiManager.allowAutojoinGlobal(false);
            sWifiManager.queryAutojoinGlobal(mExecutor, listener);
            synchronized (mLock) {
                mLock.wait(TEST_WAIT_DURATION_MS);
            }
            assertFalse(enabled.get());
        } finally {
            // Re-enable auto join if the test fails for some reason.
            sWifiManager.allowAutojoinGlobal(true);
            uiAutomation.dropShellPermissionIdentity();
        }
    }

    /**
     * Tests {@link WifiManager#isWapiSupported()} does not crash.
     */
    @Test
    public void testIsWapiSupported() throws Exception {
        sWifiManager.isWapiSupported();
    }

    /**
     * Tests {@link WifiManager#isWpa3SaePublicKeySupported()} does not crash.
     */
    @SdkSuppress(minSdkVersion = Build.VERSION_CODES.S)
    @Test
    public void testIsWpa3SaePublicKeySupported() throws Exception {
        sWifiManager.isWpa3SaePublicKeySupported();
    }

    /**
     * Tests {@link WifiManager#isWpa3SaeH2eSupported()} does not crash.
     */
    @SdkSuppress(minSdkVersion = Build.VERSION_CODES.S)
    @Test
    public void testIsWpa3SaeH2eSupported() throws Exception {
        sWifiManager.isWpa3SaeH2eSupported();
    }

    /**
     * Tests {@link WifiManager#isWifiDisplayR2Supported()} does not crash.
     */
    @SdkSuppress(minSdkVersion = Build.VERSION_CODES.S)
    @Test
    public void testIsWifiDisplayR2Supported() throws Exception {
        sWifiManager.isWifiDisplayR2Supported();
    }

    /**
     * Tests {@link WifiManager#isP2pSupported()} returns true
     * if this device supports it, otherwise, ensure no crash.
     */
    @Test
    public void testIsP2pSupported() throws Exception {
        if (WifiFeature.isP2pSupported(sContext)) {
            // if this device supports P2P, ensure hw capability is correct.
            assertTrue(sWifiManager.isP2pSupported());
        } else {
            // ensure no crash.
            sWifiManager.isP2pSupported();
        }

    }

    @SdkSuppress(minSdkVersion = Build.VERSION_CODES.S)
    @Test
    public void testIsMultiStaConcurrencySupported() throws Exception {
        // ensure no crash.
        sWifiManager.isStaApConcurrencySupported();
    }

    private PasspointConfiguration getTargetPasspointConfiguration(
            List<PasspointConfiguration> configurationList, String uniqueId) {
        if (configurationList == null || configurationList.isEmpty()) {
            return null;
        }
        for (PasspointConfiguration config : configurationList) {
            if (TextUtils.equals(config.getUniqueId(), uniqueId)) {
                return config;
            }
        }
        return null;
    }

    /**
     * Test that {@link WifiManager#is60GHzBandSupported()} throws UnsupportedOperationException
     * if the release is older than S.
     */
    @SdkSuppress(maxSdkVersion = Build.VERSION_CODES.R)
    @Test
    public void testIs60GhzBandSupportedOnROrOlder() throws Exception {
        // check for 60ghz support with wifi enabled
        try {
            boolean isSupported = sWifiManager.is60GHzBandSupported();
            fail("Expected UnsupportedOperationException");
        } catch (UnsupportedOperationException ex) {
        }

    }

    /**
     * Test that {@link WifiManager#is60GHzBandSupported()} returns successfully in
     * both Wifi enabled/disabled states for release newer than R.
     * Note that the response depends on device support and hence both true/false
     * are valid responses.
     */
    @SdkSuppress(minSdkVersion = Build.VERSION_CODES.S)
    @Test
    public void testIs60GhzBandSupportedOnSOrNewer() throws Exception {
        // check for 60ghz support with wifi enabled
        boolean isSupportedWhenWifiEnabled = sWifiManager.is60GHzBandSupported();

        // Check for 60GHz support with wifi disabled
        setWifiEnabled(false);
        PollingCheck.check(
                "Wifi not disabled!",
                20000,
                () -> !sWifiManager.isWifiEnabled());
        boolean isSupportedWhenWifiDisabled = sWifiManager.is60GHzBandSupported();

        // If Support is true when WiFi is disable, then it has to be true when it is enabled.
        // Note, the reverse is a valid case.
        if (isSupportedWhenWifiDisabled) {
            assertTrue(isSupportedWhenWifiEnabled);
        }
    }

    /**
     * Tests {@link WifiManager#isTrustOnFirstUseSupported()} does not crash.
     */
    // TODO(b/196180536): Wait for T SDK finalization before changing
    // to `@SdkSuppress(minSdkVersion = Build.VERSION_CODES.TIRAMISU)`
    @SdkSuppress(minSdkVersion = 31)
    @Test
    public void testIsTrustOnFirstUseSupported() throws Exception {
        sWifiManager.isTrustOnFirstUseSupported();
    }

    public class TestCoexCallback extends WifiManager.CoexCallback {
        private Object mCoexLock;
        private int mOnCoexUnsafeChannelChangedCount;
        private List<CoexUnsafeChannel> mCoexUnsafeChannels;
        private int mCoexRestrictions;

        TestCoexCallback(Object lock) {
            mCoexLock = lock;
        }

        @Override
        public void onCoexUnsafeChannelsChanged(
                    @NonNull List<CoexUnsafeChannel> unsafeChannels, int restrictions) {
            synchronized (mCoexLock) {
                mCoexUnsafeChannels = unsafeChannels;
                mCoexRestrictions = restrictions;
                mOnCoexUnsafeChannelChangedCount++;
                mCoexLock.notify();
            }
        }

        public int getOnCoexUnsafeChannelChangedCount() {
            synchronized (mCoexLock) {
                return mOnCoexUnsafeChannelChangedCount;
            }
        }

        public List<CoexUnsafeChannel> getCoexUnsafeChannels() {
            return mCoexUnsafeChannels;
        }

        public int getCoexRestrictions() {
            return mCoexRestrictions;
        }
    }

    /**
     * Test that coex-related methods fail without the needed privileged permissions
     */
    @SdkSuppress(minSdkVersion = Build.VERSION_CODES.S)
    @Test
    public void testCoexMethodsShouldFailNoPermission() {
        try {
            sWifiManager.setCoexUnsafeChannels(Collections.emptyList(), 0);
            fail("setCoexUnsafeChannels should not succeed - privileged call");
        } catch (SecurityException e) {
            // expected
        }
        final TestCoexCallback callback = new TestCoexCallback(mLock);
        try {
            sWifiManager.registerCoexCallback(mExecutor, callback);
            fail("registerCoexCallback should not succeed - privileged call");
        } catch (SecurityException e) {
            // expected
        }
        try {
            sWifiManager.unregisterCoexCallback(callback);
            fail("unregisterCoexCallback should not succeed - privileged call");
        } catch (SecurityException e) {
            // expected
        }
    }

    /**
     * Test that coex-related methods succeed in setting the current unsafe channels and notifying
     * the listener. Since the default coex algorithm may be enabled, no-op is also valid behavior.
     */
    @SdkSuppress(minSdkVersion = Build.VERSION_CODES.S)
    @Test
    public void testListenOnCoexUnsafeChannels() {
        // These below API's only work with privileged permissions (obtained via shell identity
        // for test)
        UiAutomation uiAutomation = InstrumentationRegistry.getInstrumentation().getUiAutomation();
        List<CoexUnsafeChannel> prevUnsafeChannels = null;
        int prevRestrictions = -1;
        try {
            uiAutomation.adoptShellPermissionIdentity();
            final TestCoexCallback callback = new TestCoexCallback(mLock);
            final List<CoexUnsafeChannel> testUnsafeChannels = new ArrayList<>();
            testUnsafeChannels.add(new CoexUnsafeChannel(WIFI_BAND_24_GHZ, 6));
            final int testRestrictions = COEX_RESTRICTION_WIFI_DIRECT
                    | COEX_RESTRICTION_SOFTAP | COEX_RESTRICTION_WIFI_AWARE;
            synchronized (mLock) {
                try {
                    sWifiManager.registerCoexCallback(mExecutor, callback);
                    // Callback should be called after registering
                    mLock.wait(TEST_WAIT_DURATION_MS);
                    assertEquals(1, callback.getOnCoexUnsafeChannelChangedCount());
                    // Store the previous coex channels and set new coex channels
                    prevUnsafeChannels = callback.getCoexUnsafeChannels();
                    prevRestrictions = callback.getCoexRestrictions();
                    sWifiManager.setCoexUnsafeChannels(testUnsafeChannels, testRestrictions);
                    mLock.wait(TEST_WAIT_DURATION_MS);
                    // Unregister callback and try setting again
                    sWifiManager.unregisterCoexCallback(callback);
                    sWifiManager.setCoexUnsafeChannels(testUnsafeChannels, testRestrictions);
                    // Callback should not be called here since it was unregistered.
                    mLock.wait(TEST_WAIT_DURATION_MS);
                } catch (InterruptedException e) {
                    fail("Thread interrupted unexpectedly while waiting on mLock");
                }
            }
            if (callback.getOnCoexUnsafeChannelChangedCount() == 2) {
                // Default algorithm disabled, setter should set the getter values.
                assertEquals(testUnsafeChannels, callback.getCoexUnsafeChannels());
                assertEquals(testRestrictions, callback.getCoexRestrictions());
            } else if (callback.getOnCoexUnsafeChannelChangedCount() != 1) {
                fail("Coex callback called " + callback.mOnCoexUnsafeChannelChangedCount
                        + " times. Expected 0 or 1 calls." );
            }
        } finally {
            // Reset the previous unsafe channels if we overrode them.
            if (prevRestrictions != -1) {
                sWifiManager.setCoexUnsafeChannels(prevUnsafeChannels, prevRestrictions);
            }
            uiAutomation.dropShellPermissionIdentity();
        }
    }

    /**
     * Verify that secure WPA-Enterprise network configurations can be added and updated.
     */
    @SdkSuppress(minSdkVersion = Build.VERSION_CODES.S)
    @Test
    public void testSecureEnterpriseConfigurationsAccepted() throws Exception {
        WifiConfiguration wifiConfiguration = new WifiConfiguration();
        wifiConfiguration.SSID = SSID1;
        wifiConfiguration.setSecurityParams(WifiConfiguration.SECURITY_TYPE_EAP_WPA3_ENTERPRISE);
        wifiConfiguration.enterpriseConfig.setEapMethod(WifiEnterpriseConfig.Eap.TTLS);
        int networkId = INVALID_NETWORK_ID;

        // These below API's only work with privileged permissions (obtained via shell identity
        // for test)
        UiAutomation uiAutomation = InstrumentationRegistry.getInstrumentation().getUiAutomation();
        try {
            uiAutomation.adoptShellPermissionIdentity();

            // Now configure it correctly with a Root CA cert and domain name
            wifiConfiguration.enterpriseConfig.setCaCertificate(FakeKeys.CA_CERT0);
            wifiConfiguration.enterpriseConfig.setAltSubjectMatch(TEST_DOM_SUBJECT_MATCH);

            // Verify that the network is added
            networkId = sWifiManager.addNetwork(wifiConfiguration);
            assertNotEquals(INVALID_NETWORK_ID, networkId);

            // Verify that the update API accepts configurations configured securely
            wifiConfiguration.networkId = networkId;
            assertEquals(networkId, sWifiManager.updateNetwork(wifiConfiguration));
        } finally {
            if (networkId != INVALID_NETWORK_ID) {
                // Clean up the previously added network
                sWifiManager.removeNetwork(networkId);
            }
            uiAutomation.dropShellPermissionIdentity();
        }
    }

    /**
     * Tests {@link WifiManager#isPasspointTermsAndConditionsSupported)} does not crash.
     */
    @Test
    public void testIsPasspointTermsAndConditionsSupported() throws Exception {
        if (!WifiBuildCompat.isPlatformOrWifiModuleAtLeastS(sContext)) {
            // Skip the test if wifi module version is older than S.
            return;
        }
        sWifiManager.isPasspointTermsAndConditionsSupported();
    }

    /**
     * Test that call to {@link WifiManager#setOverrideCountryCode()},
     * {@link WifiManager#clearOverrideCountryCode()} and
     * {@link WifiManager#setDefaultCountryCode()} need privileged permission
     * and the permission is not even given to shell user.
     */
    @SdkSuppress(minSdkVersion = Build.VERSION_CODES.S)
    @Test
    public void testManageCountryCodeMethodsFailWithoutPermissions() throws Exception {
        ShellIdentityUtils.invokeWithShellPermissions(() -> {
            try {
                sWifiManager.setOverrideCountryCode(TEST_COUNTRY_CODE);
                fail("setOverrideCountryCode() expected to fail - privileged call");
            } catch (SecurityException e) {
                // expected
            }

            try {
                sWifiManager.clearOverrideCountryCode();
                fail("clearOverrideCountryCode() expected to fail - privileged call");
            } catch (SecurityException e) {
                // expected
            }

            try {
                sWifiManager.setDefaultCountryCode(TEST_COUNTRY_CODE);
                fail("setDefaultCountryCode() expected to fail - privileged call");
            } catch (SecurityException e) {
                // expected
            }
        });
    }

    /**
     * Tests {@link WifiManager#flushPasspointAnqpCache)} does not crash.
     */
    @Test
    public void testFlushPasspointAnqpCache() throws Exception {
        if (!WifiBuildCompat.isPlatformOrWifiModuleAtLeastS(sContext)) {
            // Skip the test if wifi module version is older than S.
            return;
        }
        // The below API only works with privileged permissions (obtained via shell identity
        // for test)
        UiAutomation uiAutomation = InstrumentationRegistry.getInstrumentation().getUiAutomation();
        try {
            uiAutomation.adoptShellPermissionIdentity();
            sWifiManager.flushPasspointAnqpCache();
        } finally {
            uiAutomation.dropShellPermissionIdentity();
        }
    }

    /**
     * Tests {@link WifiManager#setWifiPasspointEnabled)} raise security exception without
     * permission.
     */
    // TODO(b/139192273): Wait for T SDK finalization before changing
    // to `@SdkSuppress(minSdkVersion = Build.VERSION_CODES.T)`
    @SdkSuppress(minSdkVersion = 31)
    @Test
    public void testEnablePasspointWithoutPermission() throws Exception {
        try {
            sWifiManager.setWifiPasspointEnabled(true);
            fail("setWifiPasspointEnabled() expected to fail - privileged call");
        } catch (SecurityException e) {
            // expected
        }
    }

    /**
     * Tests {@link WifiManager#setWifiPasspointEnabled)} does not crash and returns success.
     */
    // TODO(b/139192273): Wait for T SDK finalization before changing
    // to `@SdkSuppress(minSdkVersion = Build.VERSION_CODES.T)`
    @SdkSuppress(minSdkVersion = 31)
    @Test
    public void testEnablePasspoint() throws Exception {
        // The below API only works with privileged permissions (obtained via shell identity
        // for test)
        UiAutomation uiAutomation = InstrumentationRegistry.getInstrumentation().getUiAutomation();
        try {
            uiAutomation.adoptShellPermissionIdentity();
            // Check if passpoint is enabled by default.
            assertTrue(sWifiManager.isWifiPasspointEnabled());
            // Try to disable passpoint
            sWifiManager.setWifiPasspointEnabled(false);
            PollingCheck.check("Wifi passpoint turn off failed!", 2_000,
                    () -> !sWifiManager.isWifiPasspointEnabled());
            // Try to enable passpoint
            sWifiManager.setWifiPasspointEnabled(true);
            PollingCheck.check("Wifi passpoint turn on failed!", 2_000,
                    () -> sWifiManager.isWifiPasspointEnabled());
        } finally {
            uiAutomation.dropShellPermissionIdentity();
        }
    }

    /**
     * Tests {@link WifiManager#isDecoratedIdentitySupported)} does not crash.
     */
    @Test
    public void testIsDecoratedIdentitySupported() throws Exception {
        if (!WifiBuildCompat.isPlatformOrWifiModuleAtLeastS(sContext)) {
            // Skip the test if wifi module version is older than S.
            return;
        }
        sWifiManager.isDecoratedIdentitySupported();
    }

    /**
     * Tests {@link WifiManager#setCarrierNetworkOffloadEnabled)} and
     * {@link WifiManager#isCarrierNetworkOffloadEnabled} work as expected.
     */
    @Test
    public void testSetCarrierNetworkOffloadEnabled() {
        if (!WifiFeature.isWifiSupported(sContext)
                || !WifiBuildCompat.isPlatformOrWifiModuleAtLeastS(sContext)) {
            // skip the test if WiFi is not supported
            return;
        }
        assertTrue(sWifiManager.isCarrierNetworkOffloadEnabled(TEST_SUB_ID, false));
        // The below API only works with privileged permissions (obtained via shell identity
        // for test)
        UiAutomation uiAutomation = InstrumentationRegistry.getInstrumentation().getUiAutomation();
        try {
            uiAutomation.adoptShellPermissionIdentity();
            sWifiManager.setCarrierNetworkOffloadEnabled(TEST_SUB_ID, false, false);
            assertFalse(sWifiManager.isCarrierNetworkOffloadEnabled(TEST_SUB_ID, false));
        } finally {
            sWifiManager.setCarrierNetworkOffloadEnabled(TEST_SUB_ID, false, true);
            uiAutomation.dropShellPermissionIdentity();
        }
        assertTrue(sWifiManager.isCarrierNetworkOffloadEnabled(TEST_SUB_ID, false));
    }

    /**
     * Test that {@link WifiManager#getUsableChannels(int, int)},
     * {@link WifiManager#getAllowedChannels(int, int)}
     * throws UnsupportedOperationException if the release is older than S.
     */
    @SdkSuppress(maxSdkVersion = Build.VERSION_CODES.R)
    @Test
    public void testGetAllowedUsableChannelsOnROrOlder() throws Exception {
        try {
            sWifiManager.getAllowedChannels(WIFI_BAND_24_GHZ, OP_MODE_STA);
            fail("getAllowedChannels Expected to fail - UnsupportedOperationException");
        } catch (UnsupportedOperationException ex) {}

        try {
            sWifiManager.getUsableChannels(WIFI_BAND_24_GHZ, OP_MODE_STA);
            fail("getUsableChannels Expected to fail - UnsupportedOperationException");
        } catch (UnsupportedOperationException ex) {}
    }

    /**
     * Tests {@link WifiManager#getAllowedChannels(int, int))} does not crash
     */
    @SdkSuppress(minSdkVersion = Build.VERSION_CODES.S)
    @Test
    public void testGetAllowedChannels() throws Exception {
        // The below API only works with privileged permissions (obtained via shell identity
        // for test)
        UiAutomation uiAutomation = InstrumentationRegistry.getInstrumentation().getUiAutomation();
        try {
            WifiAvailableChannel channel = new WifiAvailableChannel(2412, OP_MODE_SAP);
            assertEquals(channel.getFrequencyMhz(), 2412);
            assertEquals(channel.getOperationalModes(), OP_MODE_SAP);
            final List<Integer> valid24GhzFreqs = Arrays.asList(
                2412, 2417, 2422, 2427, 2432, 2437, 2442,
                2447, 2452, 2457, 2462, 2467, 2472, 2484);
            Set<Integer> supported24GhzFreqs = new HashSet<Integer>();
            uiAutomation.adoptShellPermissionIdentity();
            List<WifiAvailableChannel> allowedChannels =
                    sWifiManager.getAllowedChannels(WIFI_BAND_24_GHZ, OP_MODE_STA);
            assertNotNull(allowedChannels);
            for (WifiAvailableChannel ch : allowedChannels) {
                //Must contain a valid 2.4GHz frequency
                assertTrue(valid24GhzFreqs.contains(ch.getFrequencyMhz()));
                if(ch.getFrequencyMhz() <= 2462) {
                    //Channels 1-11 are supported for STA in all countries
                    assertEquals(ch.getOperationalModes() & OP_MODE_STA, OP_MODE_STA);
                    supported24GhzFreqs.add(ch.getFrequencyMhz());
                }
            }
            //Channels 1-11 are supported for STA in all countries
            assertEquals(supported24GhzFreqs.size(), 11);
        } catch (UnsupportedOperationException ex) {
            //expected if the device does not support this API
        } catch (Exception ex) {
            fail("getAllowedChannels unexpected Exception " + ex);
        } finally {
            uiAutomation.dropShellPermissionIdentity();
        }
    }

    /**
     * Tests {@link WifiManager#getUsableChannels(int, int))} does not crash
     * and returns at least one 2G channel in STA and WFD GO modes (if WFD is supported)
     */
    @SdkSuppress(minSdkVersion = Build.VERSION_CODES.S)
    @Test
    public void testGetUsableChannelsStaWfdMode() throws Exception {
        // The below API only works with privileged permissions (obtained via shell identity
        // for test)
        UiAutomation uiAutomation = InstrumentationRegistry.getInstrumentation().getUiAutomation();
        try {
            uiAutomation.adoptShellPermissionIdentity();
            List<WifiAvailableChannel> usableStaChannels =
                    sWifiManager.getUsableChannels(WIFI_BAND_24_GHZ, OP_MODE_STA);
            //There must be at least one usable STA channel in 2.4GHz band
            assertFalse(usableStaChannels.isEmpty());
            if (sWifiManager.isP2pSupported()) {
                List<WifiAvailableChannel> usableGoChannels =
                        sWifiManager.getUsableChannels(WIFI_BAND_24_GHZ, OP_MODE_WIFI_DIRECT_GO);
                //There must be at least one usable P2P channel in 2.4GHz band
                assertFalse(usableGoChannels.isEmpty());
            }

        } catch (UnsupportedOperationException ex) {
            //expected if the device does not support this API
        } catch (Exception ex) {
            fail("getUsableChannels unexpected Exception " + ex);
        } finally {
            uiAutomation.dropShellPermissionIdentity();
        }
    }

    /**
     * Tests {@link WifiManager#getChannelData(Executor, Consumer<List<Bundle>>)}
     * does not crash.
     */
    @SdkSuppress(minSdkVersion = Build.VERSION_CODES.TIRAMISU)
    @Test
    public void testGetChannelData() throws Exception {
        List<Bundle> dataList = new ArrayList<>();
        Consumer<List<Bundle>> listener = new Consumer<List<Bundle>>() {
            @Override
            public void accept(List<Bundle> value) {
                synchronized (mLock) {
                    dataList.addAll(value);
                    mLock.notify();
                }
            }
        };
        // Test invalid inputs trigger IllegalArgumentException
        assertThrows("null executor should trigger exception", NullPointerException.class,
                () -> sWifiManager.getChannelData(null, listener));
        assertThrows("null listener should trigger exception", NullPointerException.class,
                () -> sWifiManager.getChannelData(mExecutor, null));

        UiAutomation uiAutomation = InstrumentationRegistry.getInstrumentation().getUiAutomation();
        try {
            uiAutomation.adoptShellPermissionIdentity();
            // Start scan and wait for scan results
            startScan();
            sWifiManager.getChannelData(mExecutor, listener);
            synchronized (mLock) {
                mLock.wait(TEST_WAIT_DURATION_MS);
            }
            if (sWifiManager.isScanAlwaysAvailable() && isScanCurrentlyAvailable()) {
                assertFalse(dataList.isEmpty());
            }
        } catch (UnsupportedOperationException ex) {
            //expected if the device does not support this API
        } catch (Exception ex) {
            fail("getChannelData unexpected Exception " + ex);
        } finally {
            uiAutomation.dropShellPermissionIdentity();
        }
    }

    /**
     * Validate that the Passpoint feature is enabled on the device.
     */
    @SdkSuppress(minSdkVersion = Build.VERSION_CODES.S)
    @Test
    public void testPasspointCapability() {
        if (PropertyUtil.getVsrApiLevel() < Build.VERSION_CODES.S) {
            return;
        }
        PackageManager packageManager = sContext.getPackageManager();
        assertTrue("Passpoint must be supported",
                packageManager.hasSystemFeature(PackageManager.FEATURE_WIFI_PASSPOINT));
    }

    /**
     * Validate add and remove SuggestionUserApprovalStatusListener. And verify the listener's
     * stickiness.
     */
    @Test
    public void testAddRemoveSuggestionUserApprovalStatusListener() throws Exception {
        if (!WifiFeature.isWifiSupported(sContext)
                || !WifiBuildCompat.isPlatformOrWifiModuleAtLeastS(sContext)) {
            return;
        }
        CountDownLatch countDownLatch = new CountDownLatch(1);
        TestUserApprovalStatusListener listener = new TestUserApprovalStatusListener(
                countDownLatch);
        try {
            sWifiManager.addSuggestionUserApprovalStatusListener(mExecutor, listener);
            assertTrue(countDownLatch.await(TEST_WAIT_DURATION_MS, TimeUnit.MILLISECONDS));
        } finally {
            sWifiManager.removeSuggestionUserApprovalStatusListener(listener);
        }
    }

    private static class TestUserApprovalStatusListener implements
            WifiManager.SuggestionUserApprovalStatusListener {
        private final CountDownLatch mBlocker;

        public TestUserApprovalStatusListener(CountDownLatch countDownLatch) {
            mBlocker = countDownLatch;
        }
        @Override
        public void onUserApprovalStatusChange(int status) {
            mBlocker.countDown();
        }
    }

    /**
     * Tests {@link WifiManager#setStaConcurrencyForMultiInternetMode)} raise security exception
     * without permission.
     */
    @SdkSuppress(minSdkVersion = Build.VERSION_CODES.TIRAMISU)
    @Test
    public void testIsStaConcurrencyForMultiInternetSupported() throws Exception {
        // ensure no crash.
        sWifiManager.isStaConcurrencyForMultiInternetSupported();
    }

    /**
     * Tests {@link WifiManager#setStaConcurrencyForMultiInternetMode)} raise security exception
     * without permission.
     */
    @SdkSuppress(minSdkVersion = Build.VERSION_CODES.TIRAMISU)
    @Test
    public void testSetStaConcurrencyForMultiInternetModeWithoutPermission() throws Exception {
        if (!WifiFeature.isWifiSupported(sContext)
                || !sWifiManager.isStaConcurrencyForMultiInternetSupported()) {
            // skip the test if WiFi is not supported or multi internet feature not supported.
            return;
        }
        try {
            sWifiManager.setStaConcurrencyForMultiInternetMode(
                    WifiManager.WIFI_MULTI_INTERNET_MODE_DISABLED);
            fail("setWifiPasspointEnabled() expected to fail - privileged call");
        } catch (SecurityException e) {
            // expected
        }
    }

    /**
     * Tests {@link WifiManager#setStaConcurrencyForMultiInternetMode)} does not crash.
     */
    @SdkSuppress(minSdkVersion = Build.VERSION_CODES.TIRAMISU)
    @Test
    public void testSetStaConcurrencyForMultiInternetMode() throws Exception {
        if (!WifiFeature.isWifiSupported(sContext)
                || !sWifiManager.isStaConcurrencyForMultiInternetSupported()) {
            // skip the test if WiFi is not supported or multi internet feature not supported.
            return;
        }

        // The below API only works with privileged permissions (obtained via shell identity
        // for test)
        UiAutomation uiAutomation = InstrumentationRegistry.getInstrumentation().getUiAutomation();
        try {
            uiAutomation.adoptShellPermissionIdentity();
            // Try to disable multi internet
            sWifiManager.setStaConcurrencyForMultiInternetMode(
                    WifiManager.WIFI_MULTI_INTERNET_MODE_DISABLED);
            PollingCheck.check(
                    "Wifi multi internet disable failed!", 2_000,
                    () -> sWifiManager.getStaConcurrencyForMultiInternetMode()
                            == WifiManager.WIFI_MULTI_INTERNET_MODE_DISABLED);
            // Try to enable multi internet
            sWifiManager.setStaConcurrencyForMultiInternetMode(
                    WifiManager.WIFI_MULTI_INTERNET_MODE_MULTI_AP);
            PollingCheck.check(
                    "Wifi multi internet turn on failed!", 2_000,
                    () -> sWifiManager.getStaConcurrencyForMultiInternetMode()
                            == WifiManager.WIFI_MULTI_INTERNET_MODE_MULTI_AP);
        } finally {
            uiAutomation.dropShellPermissionIdentity();
        }
    }

    static class TestWifiNetworkStateChangeListener implements
            WifiManager.WifiNetworkStateChangedListener {
        final int mCmmRole;
        private List<Integer> mStateList = new ArrayList<>();

        TestWifiNetworkStateChangeListener(int cmmRole) {
            mCmmRole = cmmRole;
        }

        @Override
        public void onWifiNetworkStateChanged(int cmmRole, int state) {
            if (cmmRole != mCmmRole) {
                return;
            }
            if (mStateList.contains(state)) {
                // ignore duplicate state transitions
                return;
            }
            mStateList.add(state);
        }

        public List<Integer> getStateList() {
            return mStateList;
        }

        public void clear() {
            mStateList.clear();
        }
    }

    @Test
    public void testWifiNetworkStateChangeListener() throws Exception {
        TestWifiNetworkStateChangeListener testListener = new TestWifiNetworkStateChangeListener(
                WifiManager.WifiNetworkStateChangedListener.WIFI_ROLE_CLIENT_PRIMARY);
        // Verify permission check
        assertThrows(SecurityException.class,
                () -> sWifiManager.addWifiNetworkStateChangedListener(mExecutor, testListener));

        // Disable wifi
        setWifiEnabled(false);
        waitForDisconnection();

        try {
            // Register listener then enable wifi
            ShellIdentityUtils.invokeWithShellPermissions(
                    () -> sWifiManager.addWifiNetworkStateChangedListener(mExecutor, testListener));
            setWifiEnabled(true);

            // Trigger a scan & wait for connection to one of the saved networks.
            sWifiManager.startScan();
            waitForConnection();

            PollingCheck.check(
                    "Wifi network state change listener did not receive connected!", 1_000,
                    () -> testListener.getStateList().contains(
                            WifiManager.WifiNetworkStateChangedListener
                                    .WIFI_NETWORK_STATUS_CONNECTED));
            int firstState = testListener.getStateList().get(0);
            int lastState = testListener.getStateList().get(testListener.getStateList().size() - 1);
            assertEquals(WifiManager.WifiNetworkStateChangedListener
                    .WIFI_NETWORK_STATUS_CONNECTING, firstState);
            assertEquals(WifiManager.WifiNetworkStateChangedListener
                    .WIFI_NETWORK_STATUS_CONNECTED, lastState);

            // Disable wifi and verify disconnect is reported.
            testListener.clear();
            setWifiEnabled(false);
            waitForDisconnection();
            PollingCheck.check(
                    "Wifi network state change listener did not receive disconnected!", 1_000,
                    () -> testListener.getStateList().contains(
                            WifiManager.WifiNetworkStateChangedListener
                                    .WIFI_NETWORK_STATUS_DISCONNECTED));
        } finally {
            sWifiManager.removeWifiNetworkStateChangedListener(testListener);
        }
    }

    /**
     * Tests {@link WifiConfiguration#setBssidAllowlist(List)}.
     */
    @Test
    public void testBssidAllowlist() throws Exception {
        UiAutomation uiAutomation = InstrumentationRegistry.getInstrumentation().getUiAutomation();
        List<WifiConfiguration> savedNetworks = null;
        try {
            uiAutomation.adoptShellPermissionIdentity();

            WifiInfo wifiInfo = sWifiManager.getConnectionInfo();
            String connectedBssid = wifiInfo.getBSSID();
            int networkId = wifiInfo.getNetworkId();

            // Set empty BSSID allow list to block all APs
            savedNetworks = sWifiManager.getConfiguredNetworks();
            for (WifiConfiguration network : savedNetworks) {
                network.setBssidAllowlist(Collections.emptyList());
                sWifiManager.updateNetwork(network);
            }

            // Disable and re-enable Wifi to avoid reconnect to the secondary candidate
            sWifiManager.setWifiEnabled(false);
            waitForDisconnection();
            sWifiManager.setWifiEnabled(true);
            // Now trigger scan and ensure that the device does not connect to any networks.
            sWifiManager.startScan();
            ensureNotConnected();

            // Set the previous connected BSSID on that network. Other network set with a fake
            // (not visible) BSSID only
            for (WifiConfiguration network : savedNetworks) {
                if (network.networkId == networkId) {
                    network.setBssidAllowlist(List.of(MacAddress.fromString(connectedBssid)));
                    sWifiManager.updateNetwork(network);
                } else {
                    network.setBssidAllowlist(List.of(MacAddress.fromString(TEST_BSSID)));
                    sWifiManager.updateNetwork(network);
                }
            }

            // Trigger a scan & wait for connection to one of the saved networks.
            sWifiManager.startScan();
            waitForConnection();
            wifiInfo = sWifiManager.getConnectionInfo();
            assertEquals(networkId, wifiInfo.getNetworkId());
        } finally {
            // Reset BSSID allow list to accept all APs
            for (WifiConfiguration network : savedNetworks) {
                assertNotNull(network.getBssidAllowlist());
                network.setBssidAllowlist(null);
                sWifiManager.updateNetwork(network);
            }
            uiAutomation.dropShellPermissionIdentity();
        }
    }

    /**
     * Tests {@link WifiManager#notifyMinimumRequiredWifiSecurityLevelChanged(int)}
     * raise security exception without permission.
     */
    @SdkSuppress(minSdkVersion = Build.VERSION_CODES.TIRAMISU)
    @Test
    public void testNotifyMinimumRequiredWifiSecurityLevelChangedWithoutPermission()
            throws Exception {
        if (!WifiFeature.isWifiSupported(sContext)) {
            // skip the test if WiFi is not supported.
            return;
        }
        assertThrows(SecurityException.class,
                () -> sWifiManager.notifyMinimumRequiredWifiSecurityLevelChanged(
                        DevicePolicyManager.WIFI_SECURITY_PERSONAL));
    }

    /**
     * Tests {@link WifiManager#notifyMinimumRequiredWifiSecurityLevelChanged(int)}
     * raise security exception without permission.
     */
    @SdkSuppress(minSdkVersion = Build.VERSION_CODES.TIRAMISU)
    @Test
    public void testNotifyWifiSsidPolicyChangedWithoutPermission() throws Exception {
        if (!WifiFeature.isWifiSupported(sContext)) {
            // skip the test if WiFi is not supported.
            return;
        }
        WifiSsidPolicy policy = new WifiSsidPolicy(
                WifiSsidPolicy.WIFI_SSID_POLICY_TYPE_ALLOWLIST, new ArraySet<>(Arrays.asList(
                WifiSsid.fromBytes("ssid".getBytes(StandardCharsets.UTF_8)))));
        try {
            sWifiManager.notifyWifiSsidPolicyChanged(policy);
            fail("Expected security exception due to lack of permission");
        } catch (SecurityException e) {
            // expected
        }
    }

    /**
     * Verifies that
     * {@link WifiManager#reportCreateInterfaceImpact(int, boolean, Executor, BiConsumer)} raises
     * a security exception without permission.
     */
    @SdkSuppress(minSdkVersion = Build.VERSION_CODES.TIRAMISU)
    @Test
    public void testIsItPossibleToCreateInterfaceNotAllowed() throws Exception {
        assertThrows(SecurityException.class, () -> sWifiManager.reportCreateInterfaceImpact(
                WifiManager.WIFI_INTERFACE_TYPE_AP, false, mExecutor,
                (canBeCreatedLocal, interfacesWhichWillBeDeletedLocal) -> {
                    // should not get here (security exception!)
                }));
    }

    /**
     * Verifies
     * {@link WifiManager#reportCreateInterfaceImpact(int, boolean, Executor, BiConsumer)} .
     */
    @SdkSuppress(minSdkVersion = Build.VERSION_CODES.TIRAMISU)
    @Test
    public void testIsItPossibleToCreateInterface() throws Exception {
        AtomicBoolean called = new AtomicBoolean(false);
        AtomicBoolean canBeCreated = new AtomicBoolean(false);
        AtomicReference<Set<WifiManager.InterfaceCreationImpact>>
                interfacesWhichWillBeDeleted = new AtomicReference<>(null);
        ShellIdentityUtils.invokeWithShellPermissions(
                () -> sWifiManager.reportCreateInterfaceImpact(
                        WifiManager.WIFI_INTERFACE_TYPE_AP, false, mExecutor,
                        (canBeCreatedLocal, interfacesWhichWillBeDeletedLocal) -> {
                            synchronized (mLock) {
                                canBeCreated.set(canBeCreatedLocal);
                                called.set(true);
                                interfacesWhichWillBeDeleted.set(interfacesWhichWillBeDeletedLocal);
                                mLock.notify();
                            }
                        }));
        synchronized (mLock) {
            mLock.wait(TEST_WAIT_DURATION_MS);
        }
        assertTrue(called.get());
        if (canBeCreated.get()) {
            for (WifiManager.InterfaceCreationImpact entry : interfacesWhichWillBeDeleted.get()) {
                int interfaceType = entry.getInterfaceType();
                assertTrue(interfaceType == WifiManager.WIFI_INTERFACE_TYPE_STA
                        || interfaceType == WifiManager.WIFI_INTERFACE_TYPE_AP
                        || interfaceType == WifiManager.WIFI_INTERFACE_TYPE_DIRECT
                        || interfaceType == WifiManager.WIFI_INTERFACE_TYPE_AWARE);
                Set<String> packages = entry.getPackages();
                for (String p : packages) {
                    assertNotNull(p);
                }
            }
        }

        // verify the WifiManager.InterfaceCreationImpact APIs
        int interfaceType = WifiManager.WIFI_INTERFACE_TYPE_STA;
        Set<String> packages = Set.of("package1", "packages2");
        WifiManager.InterfaceCreationImpact element = new WifiManager.InterfaceCreationImpact(
                interfaceType, packages);
        assertEquals(interfaceType, element.getInterfaceType());
        assertEquals(packages, element.getPackages());
    }

    /**
     * Tests {@link WifiManager#isEasyConnectDppAkmSupported)} does not crash.
     */
    @SdkSuppress(minSdkVersion = Build.VERSION_CODES.TIRAMISU)
    @Test
    public void testIsEasyConnectDppAkmSupported() throws Exception {
        sWifiManager.isEasyConnectDppAkmSupported();
    }

    /**
     * Tests {@link WifiManager#getMaxNumberOfChannelsPerNetworkSpecifierRequest)} works
     */
    @Test
    public void testGetMaxNumberOfChannelsPerNetworkSpecifierRequest() {
        assertTrue(sWifiManager.getMaxNumberOfChannelsPerNetworkSpecifierRequest() > 0);
    }

    /**
     * Tests {@link WifiManager#isTlsV13Supported)} does not crash.
     */
    @Test
    public void testIsTlsV13Supported() throws Exception {
        sWifiManager.isTlsV13Supported();
    }

    /**
     * Tests {@link WifiManager#isTlsMinimumVersionSupported)} does not crash.
     */
    @Test
    public void testIsTlsMinimumVersionSupported() throws Exception {
        sWifiManager.isTlsMinimumVersionSupported();
    }

    private void fillQosPolicyParamsList(List<QosPolicyParams> policyParamsList,
            int size, boolean uniqueIds) {
        policyParamsList.clear();
        for (int i = 0; i < size; i++) {
            int policyId = uniqueIds ? i + 2 : 5;
            policyParamsList.add(new QosPolicyParams.Builder(
                    policyId, QosPolicyParams.DIRECTION_DOWNLINK)
                            .setUserPriority(QosPolicyParams.USER_PRIORITY_VIDEO_LOW)
                            .setIpVersion(QosPolicyParams.IP_VERSION_4)
                            .build());
        }
    }

    /**
     * Check whether the application QoS feature is enabled.
     *
     * The feature is enabled if the overlay is true, the experiment feature flag
     * is true, and the supplicant service implements V2 of the AIDL interface.
     */
    private boolean applicationQosFeatureEnabled() {
        boolean overlayEnabled;
        try {
            WifiResourceUtil resourceUtil = new WifiResourceUtil(sContext);
            overlayEnabled = resourceUtil
                    .getWifiBoolean("config_wifiApplicationCentricQosPolicyFeatureEnabled");
        } catch (Exception e) {
            Log.i(TAG, "Unable to retrieve the QoS overlay value");
            return false;
        }

        // Supplicant V2 is supported if the vendor partition indicates API > T.
        boolean halSupport = PropertyUtil.isVndkApiLevelNewerThan(Build.VERSION_CODES.TIRAMISU);
        boolean featureFlagEnabled = DeviceConfig.getBoolean(DEVICE_CONFIG_NAMESPACE,
                "application_qos_policy_api_enabled", true);

        return overlayEnabled && featureFlagEnabled && halSupport;
    }

    /**
     * Tests that {@link WifiManager#addQosPolicies(List, Executor, Consumer)},
     * {@link WifiManager#removeQosPolicies(int[])}, and
     * {@link WifiManager#removeAllQosPolicies()} do not crash.
     */
    @SdkSuppress(minSdkVersion = Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
    @Test
    public void testAddAndRemoveQosPolicies() throws Exception {
        final Mutable<Boolean> callbackReceived = new Mutable<Boolean>(false);
        final Mutable<Boolean> policiesRejected = new Mutable<Boolean>(true);
        Consumer<List<Integer>> listener = new Consumer<List<Integer>>() {
            @Override
            public void accept(List value) {
                synchronized (mLock) {
                    callbackReceived.value = true;
                    List<Integer> statusList = value;
                    for (Integer status : statusList) {
                        if (status != WifiManager.QOS_REQUEST_STATUS_FAILURE_UNKNOWN) {
                            policiesRejected.value = false;
                            break;
                        }
                    }
                    Log.i(TAG, "Callback received for QoS add request, size=" + statusList.size()
                            + ", rejected=" + policiesRejected.value);
                    mLock.notify();
                }
            }
        };

        // Test that invalid inputs trigger an Exception.
        final List<QosPolicyParams> policyParamsList = new ArrayList<>();
        assertThrows("null executor should trigger exception", NullPointerException.class,
                () -> sWifiManager.addQosPolicies(policyParamsList, null, listener));
        assertThrows("null listener should trigger exception", NullPointerException.class,
                () -> sWifiManager.addQosPolicies(policyParamsList, mExecutor, null));
        assertThrows("null policy list should trigger exception", NullPointerException.class,
                () -> sWifiManager.addQosPolicies(null, mExecutor, listener));

        UiAutomation uiAutomation = InstrumentationRegistry.getInstrumentation().getUiAutomation();
        try {
            uiAutomation.adoptShellPermissionIdentity();
            boolean enabled = applicationQosFeatureEnabled();

            // If the feature is disabled, verify that all policies are rejected.
            if (!enabled) {
                Log.i(TAG, "QoS policy APIs are not enabled");
                fillQosPolicyParamsList(policyParamsList, 4, true);
                sWifiManager.addQosPolicies(policyParamsList, mExecutor, listener);
                synchronized (mLock) {
                    mLock.wait(TEST_WAIT_DURATION_MS);
                }
                assertTrue(callbackReceived.value);
                assertTrue(policiesRejected.value);
                return;
            }

            // Empty params list
            assertThrows("empty list should trigger exception", IllegalArgumentException.class,
                    () -> sWifiManager.addQosPolicies(new ArrayList<>(), mExecutor, listener));

            // More than {@link WifiManager#getMaxNumberOfPoliciesPerQosRequest()}
            // policies in the list
            fillQosPolicyParamsList(policyParamsList,
                    sWifiManager.getMaxNumberOfPoliciesPerQosRequest() + 1, true);
            assertThrows("large list should trigger exception", IllegalArgumentException.class,
                    () -> sWifiManager.addQosPolicies(policyParamsList, mExecutor, listener));

            // Params list contains duplicate policy ids
            fillQosPolicyParamsList(policyParamsList, 4, false);
            assertThrows("duplicate ids should trigger exception", IllegalArgumentException.class,
                    () -> sWifiManager.addQosPolicies(policyParamsList, mExecutor, listener));

            // Valid list
            fillQosPolicyParamsList(policyParamsList, 4, true);
            sWifiManager.addQosPolicies(policyParamsList, mExecutor, listener);

            // sleep to wait for a response from supplicant
            synchronized (mLock) {
                mLock.wait(TEST_WAIT_DURATION_MS);
            }

            int[] policyIds = new int[policyParamsList.size()];
            for (int i = 0; i < policyParamsList.size(); i++) {
                policyIds[i] = policyParamsList.get(i).getPolicyId();
            }
            sWifiManager.removeQosPolicies(policyIds);

            // sleep to wait for a response from supplicant
            synchronized (mLock) {
                mLock.wait(TEST_WAIT_DURATION_MS);
            }
            sWifiManager.removeAllQosPolicies();
        } catch (Exception e) {
            fail("addAndRemoveQosPolicy unexpected Exception " + e);
        } finally {
            uiAutomation.dropShellPermissionIdentity();
        }
    }

    /**
     * Tests the builder and get methods for {@link QosPolicyParams}.
     */
    @SdkSuppress(minSdkVersion = Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
    @Test
    public void testQosPolicyParamsBuilder() throws Exception {
        final int policyId = 5;
        final int direction = QosPolicyParams.DIRECTION_DOWNLINK;
        final int ipVersion = QosPolicyParams.IP_VERSION_6;
        final int dscp = 12;
        final int userPriority = QosPolicyParams.USER_PRIORITY_VIDEO_LOW;
        final String ipv6Address = "2001:db8:3333:4444:5555:6666:7777:8888";
        final InetAddress srcAddr = InetAddress.getByName(ipv6Address);
        final InetAddress dstAddr = InetAddress.getByName(ipv6Address);
        final int srcPort = 123;
        final int protocol = QosPolicyParams.PROTOCOL_TCP;
        final int dstPort = 17;
        final int[] dstPortRange = new int[]{15, 22};
        final byte[] flowLabel = new byte[]{17, 18, 19};

        // Invalid parameter
        assertThrows("Invalid dscp should trigger an exception", IllegalArgumentException.class,
                () -> new QosPolicyParams.Builder(policyId, direction)
                        .setDscp(70)
                        .build());

        // Valid downlink parameters
        QosPolicyParams downlinkParams =
                new QosPolicyParams.Builder(policyId, QosPolicyParams.DIRECTION_DOWNLINK)
                        .setSourceAddress(srcAddr)
                        .setDestinationAddress(dstAddr)
                        .setUserPriority(userPriority)
                        .setIpVersion(ipVersion)
                        .setSourcePort(srcPort)
                        .setProtocol(protocol)
                        .setDestinationPort(dstPort)
                        .setFlowLabel(flowLabel)
                        .build();
        assertEquals(policyId, downlinkParams.getPolicyId());
        assertEquals(QosPolicyParams.DIRECTION_DOWNLINK, downlinkParams.getDirection());
        assertEquals(srcAddr, downlinkParams.getSourceAddress());
        assertEquals(dstAddr, downlinkParams.getDestinationAddress());
        assertEquals(userPriority, downlinkParams.getUserPriority());
        assertEquals(ipVersion, downlinkParams.getIpVersion());
        assertEquals(srcPort, downlinkParams.getSourcePort());
        assertEquals(protocol, downlinkParams.getProtocol());
        assertEquals(dstPort, downlinkParams.getDestinationPort());
        assertArrayEquals(flowLabel, downlinkParams.getFlowLabel());

        // Valid uplink parameters
        QosPolicyParams uplinkParams =
                new QosPolicyParams.Builder(policyId, QosPolicyParams.DIRECTION_UPLINK)
                    .setSourceAddress(srcAddr)
                    .setDestinationAddress(dstAddr)
                    .setDscp(dscp)
                    .setSourcePort(srcPort)
                    .setProtocol(protocol)
                    .setDestinationPortRange(dstPortRange[0], dstPortRange[1])
                    .build();
        assertEquals(policyId, uplinkParams.getPolicyId());
        assertEquals(QosPolicyParams.DIRECTION_UPLINK, uplinkParams.getDirection());
        assertEquals(srcAddr, uplinkParams.getSourceAddress());
        assertEquals(dstAddr, uplinkParams.getDestinationAddress());
        assertEquals(dscp, uplinkParams.getDscp());
        assertEquals(srcPort, uplinkParams.getSourcePort());
        assertEquals(protocol, uplinkParams.getProtocol());
        assertArrayEquals(dstPortRange, uplinkParams.getDestinationPortRange());
    }

    /**
     * Verifies when the link layer stats polling interval is overridden by
     * {@link WifiManager#setLinkLayerStatsPollingInterval(int)},
     * the new interval is set correctly by checking
     * {@link WifiManager#getLinkLayerStatsPollingInterval(Executor, Consumer)}
     */
    @SdkSuppress(minSdkVersion = Build.VERSION_CODES.TIRAMISU)
    @Test
    public void testSetAndGetLinkLayerStatsPollingInterval() throws Exception {
        AtomicInteger currentInterval = new AtomicInteger(-1);
        Consumer<Integer> listener = new Consumer<Integer>() {
            @Override
            public void accept(Integer value) {
                synchronized (mLock) {
                    currentInterval.set(value);
                    mLock.notify();
                }
            }
        };

        // SecurityException
        assertThrows(SecurityException.class,
                () -> sWifiManager.setLinkLayerStatsPollingInterval(
                        TEST_LINK_LAYER_STATS_POLLING_INTERVAL_MS));
        assertThrows(SecurityException.class,
                () -> sWifiManager.getLinkLayerStatsPollingInterval(mExecutor, listener));
        // null executor
        assertThrows("null executor should trigger exception", NullPointerException.class,
                () -> sWifiManager.getLinkLayerStatsPollingInterval(null, listener));
        // null listener
        assertThrows("null listener should trigger exception", NullPointerException.class,
                () -> sWifiManager.getLinkLayerStatsPollingInterval(mExecutor, null));

        UiAutomation uiAutomation = InstrumentationRegistry.getInstrumentation().getUiAutomation();

        try {
            uiAutomation.adoptShellPermissionIdentity();
            assertThrows(IllegalArgumentException.class,
                    () -> sWifiManager.setLinkLayerStatsPollingInterval(
                            -TEST_LINK_LAYER_STATS_POLLING_INTERVAL_MS));
            sWifiManager.setLinkLayerStatsPollingInterval(
                    TEST_LINK_LAYER_STATS_POLLING_INTERVAL_MS);
            sWifiManager.getLinkLayerStatsPollingInterval(mExecutor, listener);
            synchronized (mLock) {
                mLock.wait(TEST_WAIT_DURATION_MS);
            }
            assertEquals(TEST_LINK_LAYER_STATS_POLLING_INTERVAL_MS, currentInterval.get());
            // set the interval to automatic handling after the test
            sWifiManager.setLinkLayerStatsPollingInterval(0);
        } catch (UnsupportedOperationException ex) {
            // Expected if the device does not support this API
        } catch (Exception e) {
            fail("setLinkLayerStatsPollingInterval / getLinkLayerStatsPollingInterval "
                    + "unexpected Exception " + e);
        } finally {
            uiAutomation.dropShellPermissionIdentity();
        }
    }

    /**
     * Tests {@link WifiManager#setLinkMode} and {@link WifiManager#getLinkMode} works
     */
    @Test
    public void testMloMode() {
        // Skip the test if Wifi is not supported.
        if (!WifiFeature.isWifiSupported(sContext)) return;
        // Need elevated permission.
        UiAutomation uiAutomation = InstrumentationRegistry.getInstrumentation().getUiAutomation();
        uiAutomation.adoptShellPermissionIdentity();
        // Get listener.
        AtomicInteger getMode = new AtomicInteger();
        Consumer<Integer> getListener = new Consumer<Integer>() {
            @Override
            public void accept(Integer value) {
                synchronized (mLock) {
                    getMode.set(value);
                    mLock.notify();
                }
            }
        };
        // Set listener.
        AtomicBoolean setStatus = new AtomicBoolean();
        Consumer<Boolean> setListener = new Consumer<Boolean>() {
            @Override
            public void accept(Boolean value) {
                synchronized (mLock) {
                    setStatus.set(value);
                    mLock.notify();
                }
            }
        };
        // Test that invalid inputs trigger an exception.
        assertThrows("null executor should trigger exception", NullPointerException.class,
                () -> sWifiManager.setMloMode(WifiManager.MLO_MODE_DEFAULT, null, setListener));
        assertThrows("null listener should trigger exception", NullPointerException.class,
                () -> sWifiManager.setMloMode(WifiManager.MLO_MODE_DEFAULT, mExecutor, null));
        assertThrows("null executor should trigger exception", NullPointerException.class,
                () -> sWifiManager.getMloMode(null, getListener));
        assertThrows("null listener should trigger exception", NullPointerException.class,
                () -> sWifiManager.getMloMode(mExecutor, null));

        // Test that invalid inputs trigger an IllegalArgumentException.
        assertThrows("Invalid mode", IllegalArgumentException.class,
                () -> sWifiManager.setMloMode(-1, mExecutor, setListener));
        assertThrows("Invalid mode", IllegalArgumentException.class,
                () -> sWifiManager.setMloMode(1000, mExecutor, setListener));
        // Test set if supported.
        try {
            // Check getMloMode() returns values in range.
            sWifiManager.getMloMode(mExecutor, getListener);
            assertThat(getMode.get()).isIn(Range.closed(WifiManager.MLO_MODE_DEFAULT,
                    WifiManager.MLO_MODE_LOW_POWER));
            // Try to set default MLO mode and get.
            sWifiManager.setMloMode(WifiManager.MLO_MODE_DEFAULT, mExecutor, setListener);
            if (setStatus.get()) {
                sWifiManager.getMloMode(mExecutor, getListener);
                assertTrue(getMode.get() == WifiManager.MLO_MODE_DEFAULT);
            }
            // Try to set low latency MLO mode and get.
            sWifiManager.setMloMode(WifiManager.MLO_MODE_LOW_LATENCY, mExecutor, setListener);
            if (setStatus.get()) {
                sWifiManager.getMloMode(mExecutor, getListener);
                assertTrue(getMode.get() == WifiManager.MLO_MODE_LOW_LATENCY);
            }
            // Try to set high throughput MLO mode and get.
            sWifiManager.setMloMode(WifiManager.MLO_MODE_HIGH_THROUGHPUT, mExecutor, setListener);
            if (setStatus.get()) {
                sWifiManager.getMloMode(mExecutor, getListener);
                assertTrue(getMode.get() == WifiManager.MLO_MODE_DEFAULT);
            }
            // Try to set low power MLO mode and get.
            sWifiManager.setMloMode(WifiManager.MLO_MODE_LOW_POWER, mExecutor, setListener);
            if (setStatus.get()) {
                sWifiManager.getMloMode(mExecutor, getListener);
                assertTrue(getMode.get() == WifiManager.MLO_MODE_DEFAULT);
            }
        } catch (UnsupportedOperationException e) {
            // Skip the set method if not supported.
        }
        // Drop the permission.
        uiAutomation.dropShellPermissionIdentity();
    }

    /**
     * Tests {@link WifiManager#isThirdPartyAppEnablingWifiConfirmationDialogEnabled()}
     * and {@link WifiManager#setThirdPartyAppEnablingWifiConfirmationDialogEnabled(boolean)}
     */
    @SdkSuppress(minSdkVersion = Build.VERSION_CODES.UPSIDE_DOWN_CAKE)
    @Test
    public void testGetAndSetThirdPartyAppEnablingWifiConfirmationDialogEnabled() {
        // Expect a SecurityException without the required permissions.
        assertThrows(SecurityException.class,
                () -> sWifiManager.isThirdPartyAppEnablingWifiConfirmationDialogEnabled());
        assertThrows(SecurityException.class,
                () -> sWifiManager.setThirdPartyAppEnablingWifiConfirmationDialogEnabled(true));

        UiAutomation uiAutomation = InstrumentationRegistry.getInstrumentation().getUiAutomation();
        try {
            uiAutomation.adoptShellPermissionIdentity();

            // Store a new value.
            boolean defaultVal =
                    sWifiManager.isThirdPartyAppEnablingWifiConfirmationDialogEnabled();
            boolean newVal = !defaultVal;
            sWifiManager.setThirdPartyAppEnablingWifiConfirmationDialogEnabled(newVal);
            assertEquals(newVal,
                    sWifiManager.isThirdPartyAppEnablingWifiConfirmationDialogEnabled());

            // Restore the original value.
            sWifiManager.setThirdPartyAppEnablingWifiConfirmationDialogEnabled(defaultVal);
            assertEquals(defaultVal,
                    sWifiManager.isThirdPartyAppEnablingWifiConfirmationDialogEnabled());
        } catch (Exception e) {
            fail("Unexpected exception " + e);
        } finally {
            uiAutomation.dropShellPermissionIdentity();
        }
    }
}