summaryrefslogtreecommitdiff
path: root/tests/src/com/android/server/telecom/tests/CallsManagerTest.java
blob: 56cf22feed9a3d076596a933b460361e2f5b88ce (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
/*
 * Copyright (C) 2017 The Android Open Source Project
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License
 */

package com.android.server.telecom.tests;

import static android.provider.CallLog.Calls.USER_MISSED_NOT_RUNNING;

import static junit.framework.Assert.assertNotNull;
import static junit.framework.TestCase.fail;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyChar;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.nullable;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import android.Manifest;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.media.AudioManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.OutcomeReceiver;
import android.os.Process;
import android.os.ResultReceiver;
import android.os.SystemClock;
import android.os.UserHandle;
import android.os.UserManager;
import android.provider.BlockedNumberContract;
import android.telecom.CallException;
import android.telecom.CallScreeningService;
import android.telecom.CallerInfo;
import android.telecom.Connection;
import android.telecom.DisconnectCause;
import android.telecom.GatewayInfo;
import android.telecom.PhoneAccount;
import android.telecom.PhoneAccountHandle;
import android.telecom.TelecomManager;
import android.telecom.VideoProfile;
import android.telephony.CarrierConfigManager;
import android.telephony.PhoneCapability;
import android.telephony.TelephonyManager;
import android.test.suitebuilder.annotation.MediumTest;
import android.test.suitebuilder.annotation.SmallTest;
import android.util.Pair;
import android.widget.Toast;

import com.android.server.telecom.AnomalyReporterAdapter;
import com.android.server.telecom.AsyncRingtonePlayer;
import com.android.server.telecom.Call;
import com.android.server.telecom.CallAnomalyWatchdog;
import com.android.server.telecom.CallAudioManager;
import com.android.server.telecom.CallAudioModeStateMachine;
import com.android.server.telecom.CallAudioRouteStateMachine;
import com.android.server.telecom.CallDiagnosticServiceController;
import com.android.server.telecom.CallEndpointController;
import com.android.server.telecom.CallEndpointControllerFactory;
import com.android.server.telecom.CallState;
import com.android.server.telecom.CallerInfoLookupHelper;
import com.android.server.telecom.CallsManager;
import com.android.server.telecom.ClockProxy;
import com.android.server.telecom.ConnectionServiceFocusManager;
import com.android.server.telecom.ConnectionServiceFocusManager.ConnectionServiceFocusManagerFactory;
import com.android.server.telecom.ConnectionServiceWrapper;
import com.android.server.telecom.DefaultDialerCache;
import com.android.server.telecom.EmergencyCallDiagnosticLogger;
import com.android.server.telecom.EmergencyCallHelper;
import com.android.server.telecom.HandoverState;
import com.android.server.telecom.HeadsetMediaButton;
import com.android.server.telecom.HeadsetMediaButtonFactory;
import com.android.server.telecom.InCallController;
import com.android.server.telecom.InCallControllerFactory;
import com.android.server.telecom.InCallTonePlayer;
import com.android.server.telecom.InCallWakeLockController;
import com.android.server.telecom.InCallWakeLockControllerFactory;
import com.android.server.telecom.MissedCallNotifier;
import com.android.server.telecom.PhoneAccountRegistrar;
import com.android.server.telecom.PhoneNumberUtilsAdapter;
import com.android.server.telecom.ProximitySensorManager;
import com.android.server.telecom.ProximitySensorManagerFactory;
import com.android.server.telecom.Ringer;
import com.android.server.telecom.RoleManagerAdapter;
import com.android.server.telecom.SystemStateHelper;
import com.android.server.telecom.TelecomSystem;
import com.android.server.telecom.Timeouts;
import com.android.server.telecom.WiredHeadsetManager;
import com.android.server.telecom.bluetooth.BluetoothRouteManager;
import com.android.server.telecom.bluetooth.BluetoothStateReceiver;
import com.android.server.telecom.callfiltering.BlockedNumbersAdapter;
import com.android.server.telecom.callfiltering.CallFilteringResult;
import com.android.server.telecom.ui.AudioProcessingNotification;
import com.android.server.telecom.ui.CallStreamingNotification;
import com.android.server.telecom.ui.DisconnectedCallNotifier;
import com.android.server.telecom.ui.ToastFactory;
import com.android.server.telecom.voip.TransactionManager;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import org.mockito.ArgumentCaptor;
import org.mockito.Matchers;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.TimeUnit;

@RunWith(JUnit4.class)
public class CallsManagerTest extends TelecomTestCase {
    private static final int TEST_TIMEOUT = 5000;  // milliseconds
    private static final long STATE_TIMEOUT = 5000L;
    private static final int SECONDARY_USER_ID = 12;
    private static final UserHandle TEST_USER_HANDLE = UserHandle.of(123);
    private static final String TEST_PACKAGE_NAME = "GoogleMeet";
    private static final PhoneAccountHandle SIM_1_HANDLE = new PhoneAccountHandle(
            ComponentName.unflattenFromString("com.foo/.Blah"), "Sim1");
    private static final PhoneAccountHandle SIM_1_HANDLE_SECONDARY = new PhoneAccountHandle(
            ComponentName.unflattenFromString("com.foo/.Blah"), "Sim1",
            new UserHandle(SECONDARY_USER_ID));
    private static final PhoneAccountHandle SIM_2_HANDLE = new PhoneAccountHandle(
            ComponentName.unflattenFromString("com.foo/.Blah"), "Sim2");
    private static final PhoneAccountHandle CONNECTION_MGR_1_HANDLE = new PhoneAccountHandle(
            ComponentName.unflattenFromString("com.bar/.Conn"), "Cm1");
    private static final PhoneAccountHandle CONNECTION_MGR_2_HANDLE = new PhoneAccountHandle(
            ComponentName.unflattenFromString("com.spa/.Conn"), "Cm2");
    private static final PhoneAccountHandle VOIP_1_HANDLE = new PhoneAccountHandle(
            ComponentName.unflattenFromString("com.voip/.Stuff"), "Voip1");
    private static final PhoneAccountHandle SELF_MANAGED_HANDLE = new PhoneAccountHandle(
            ComponentName.unflattenFromString("com.baz/.Self"), "Self");
    private static final PhoneAccountHandle SELF_MANAGED_2_HANDLE = new PhoneAccountHandle(
            ComponentName.unflattenFromString("com.baz/.Self2"), "Self2");
    private static final PhoneAccountHandle WORK_HANDLE = new PhoneAccountHandle(
            ComponentName.unflattenFromString("com.foo/.Blah"), "work", new UserHandle(10));
    private static final PhoneAccountHandle SELF_MANAGED_W_CUSTOM_HANDLE = new PhoneAccountHandle(
            new ComponentName(TEST_PACKAGE_NAME, "class"), "1", TEST_USER_HANDLE);
    private static final PhoneAccount SIM_1_ACCOUNT = new PhoneAccount.Builder(SIM_1_HANDLE, "Sim1")
            .setCapabilities(PhoneAccount.CAPABILITY_SIM_SUBSCRIPTION
                    | PhoneAccount.CAPABILITY_CALL_PROVIDER
                    | PhoneAccount.CAPABILITY_PLACE_EMERGENCY_CALLS)
            .setIsEnabled(true)
            .build();
    private static final PhoneAccount SIM_1_ACCOUNT_SECONDARY = new PhoneAccount
            .Builder(SIM_1_HANDLE_SECONDARY, "Sim1")
            .setCapabilities(PhoneAccount.CAPABILITY_SIM_SUBSCRIPTION
                    | PhoneAccount.CAPABILITY_CALL_PROVIDER
                    | PhoneAccount.CAPABILITY_PLACE_EMERGENCY_CALLS)
            .setIsEnabled(true)
            .build();
    private static final PhoneAccount SIM_2_ACCOUNT = new PhoneAccount.Builder(SIM_2_HANDLE, "Sim2")
            .setCapabilities(PhoneAccount.CAPABILITY_SIM_SUBSCRIPTION
                    | PhoneAccount.CAPABILITY_CALL_PROVIDER
                    | PhoneAccount.CAPABILITY_SUPPORTS_VIDEO_CALLING)
            .setIsEnabled(true)
            .build();
    private static final PhoneAccount SELF_MANAGED_ACCOUNT = new PhoneAccount.Builder(
            SELF_MANAGED_HANDLE, "Self")
            .setCapabilities(PhoneAccount.CAPABILITY_SELF_MANAGED)
            .setIsEnabled(true)
            .build();
    private static final PhoneAccount SELF_MANAGED_2_ACCOUNT = new PhoneAccount.Builder(
            SELF_MANAGED_2_HANDLE, "Self2")
            .setCapabilities(PhoneAccount.CAPABILITY_SELF_MANAGED)
            .setIsEnabled(true)
            .build();
    private static final PhoneAccount WORK_ACCOUNT = new PhoneAccount.Builder(
            WORK_HANDLE, "work")
            .setCapabilities(PhoneAccount.CAPABILITY_SIM_SUBSCRIPTION
                    | PhoneAccount.CAPABILITY_CALL_PROVIDER
                    | PhoneAccount.CAPABILITY_PLACE_EMERGENCY_CALLS)
            .setIsEnabled(true)
            .build();
    private static final PhoneAccount SM_W_DIFFERENT_PACKAGE_AND_USER = new PhoneAccount.Builder(
            SELF_MANAGED_W_CUSTOM_HANDLE, "Self")
            .setCapabilities(PhoneAccount.CAPABILITY_SELF_MANAGED)
            .setIsEnabled(true)
            .build();

    private static final Uri TEST_ADDRESS = Uri.parse("tel:555-1212");
    private static final Uri TEST_ADDRESS2 = Uri.parse("tel:555-1213");
    private static final Uri TEST_ADDRESS3 = Uri.parse("tel:555-1214");
    private static final Map<Uri, PhoneAccountHandle> CONTACT_PREFERRED_ACCOUNT = Map.of(
            TEST_ADDRESS2, SIM_1_HANDLE,
            TEST_ADDRESS3, SIM_2_HANDLE);

    private static final String DEFAULT_CALL_SCREENING_APP = "com.foo.call_screen_app";

    private static int sCallId = 1;
    private final TelecomSystem.SyncRoot mLock = new TelecomSystem.SyncRoot() { };
    @Mock private CallerInfoLookupHelper mCallerInfoLookupHelper;
    @Mock private MissedCallNotifier mMissedCallNotifier;
    @Mock private DisconnectedCallNotifier.Factory mDisconnectedCallNotifierFactory;
    @Mock private DisconnectedCallNotifier mDisconnectedCallNotifier;
    @Mock private PhoneAccountRegistrar mPhoneAccountRegistrar;
    @Mock private HeadsetMediaButton mHeadsetMediaButton;
    @Mock private HeadsetMediaButtonFactory mHeadsetMediaButtonFactory;
    @Mock private ProximitySensorManager mProximitySensorManager;
    @Mock private ProximitySensorManagerFactory mProximitySensorManagerFactory;
    @Mock private InCallWakeLockController mInCallWakeLockController;
    @Mock private ConnectionServiceFocusManagerFactory mConnSvrFocusManagerFactory;
    @Mock private InCallWakeLockControllerFactory mInCallWakeLockControllerFactory;
    @Mock private CallAudioManager.AudioServiceFactory mAudioServiceFactory;
    @Mock private BluetoothRouteManager mBluetoothRouteManager;
    @Mock private WiredHeadsetManager mWiredHeadsetManager;
    @Mock private SystemStateHelper mSystemStateHelper;
    @Mock private DefaultDialerCache mDefaultDialerCache;
    @Mock private Timeouts.Adapter mTimeoutsAdapter;
    @Mock private AsyncRingtonePlayer mAsyncRingtonePlayer;
    @Mock private PhoneNumberUtilsAdapter mPhoneNumberUtilsAdapter;
    @Mock private EmergencyCallHelper mEmergencyCallHelper;
    @Mock private InCallTonePlayer.ToneGeneratorFactory mToneGeneratorFactory;
    @Mock private ClockProxy mClockProxy;
    @Mock private AudioProcessingNotification mAudioProcessingNotification;
    @Mock private InCallControllerFactory mInCallControllerFactory;
    @Mock private InCallController mInCallController;
    @Mock private CallEndpointControllerFactory mCallEndpointControllerFactory;
    @Mock private CallEndpointController mCallEndpointController;
    @Mock private ConnectionServiceFocusManager mConnectionSvrFocusMgr;
    @Mock private CallAudioRouteStateMachine mCallAudioRouteStateMachine;
    @Mock private CallAudioRouteStateMachine.Factory mCallAudioRouteStateMachineFactory;
    @Mock private CallAudioModeStateMachine mCallAudioModeStateMachine;
    @Mock private CallAudioModeStateMachine.Factory mCallAudioModeStateMachineFactory;
    @Mock private CallDiagnosticServiceController mCallDiagnosticServiceController;
    @Mock private BluetoothStateReceiver mBluetoothStateReceiver;
    @Mock private RoleManagerAdapter mRoleManagerAdapter;
    @Mock private ToastFactory mToastFactory;
    @Mock private Toast mToast;
    @Mock private CallAnomalyWatchdog mCallAnomalyWatchdog;

    @Mock private EmergencyCallDiagnosticLogger mEmergencyCallDiagnosticLogger;
    @Mock private AnomalyReporterAdapter mAnomalyReporterAdapter;
    @Mock private Ringer.AccessibilityManagerAdapter mAccessibilityManagerAdapter;
    @Mock private BlockedNumbersAdapter mBlockedNumbersAdapter;
    @Mock private PhoneCapability mPhoneCapability;
    @Mock private CallStreamingNotification mCallStreamingNotification;

    private CallsManager mCallsManager;

    @Override
    @Before
    public void setUp() throws Exception {
        super.setUp();
        MockitoAnnotations.initMocks(this);
        when(mInCallWakeLockControllerFactory.create(any(), any())).thenReturn(
                mInCallWakeLockController);
        when(mHeadsetMediaButtonFactory.create(any(), any(), any())).thenReturn(
                mHeadsetMediaButton);
        when(mProximitySensorManagerFactory.create(any(), any())).thenReturn(
                mProximitySensorManager);
        when(mInCallControllerFactory.create(any(), any(), any(), any(), any(), any(),
                any())).thenReturn(mInCallController);
        when(mCallEndpointControllerFactory.create(any(), any(), any())).thenReturn(
                mCallEndpointController);
        when(mCallAudioRouteStateMachineFactory.create(any(), any(), any(), any(), any(), any(),
                anyInt(), any())).thenReturn(mCallAudioRouteStateMachine);
        when(mCallAudioModeStateMachineFactory.create(any(), any()))
                .thenReturn(mCallAudioModeStateMachine);
        when(mClockProxy.currentTimeMillis()).thenReturn(System.currentTimeMillis());
        when(mClockProxy.elapsedRealtime()).thenReturn(SystemClock.elapsedRealtime());
        when(mConnSvrFocusManagerFactory.create(any())).thenReturn(mConnectionSvrFocusMgr);
        doNothing().when(mRoleManagerAdapter).setCurrentUserHandle(any());
        when(mDisconnectedCallNotifierFactory.create(any(Context.class),any(CallsManager.class)))
                .thenReturn(mDisconnectedCallNotifier);
        when(mTimeoutsAdapter.getCallDiagnosticServiceTimeoutMillis(any(ContentResolver.class)))
                .thenReturn(2000L);
        when(mTimeoutsAdapter.getNonVoipCallTransitoryStateTimeoutMillis())
                .thenReturn(STATE_TIMEOUT);
        when(mClockProxy.elapsedRealtime()).thenReturn(0L);
        mCallsManager = new CallsManager(
                mComponentContextFixture.getTestDouble().getApplicationContext(),
                mLock,
                mCallerInfoLookupHelper,
                mMissedCallNotifier,
                mDisconnectedCallNotifierFactory,
                mPhoneAccountRegistrar,
                mHeadsetMediaButtonFactory,
                mProximitySensorManagerFactory,
                mInCallWakeLockControllerFactory,
                mConnSvrFocusManagerFactory,
                mAudioServiceFactory,
                mBluetoothRouteManager,
                mWiredHeadsetManager,
                mSystemStateHelper,
                mDefaultDialerCache,
                mTimeoutsAdapter,
                mAsyncRingtonePlayer,
                mPhoneNumberUtilsAdapter,
                mEmergencyCallHelper,
                mToneGeneratorFactory,
                mClockProxy,
                mAudioProcessingNotification,
                mBluetoothStateReceiver,
                mCallAudioRouteStateMachineFactory,
                mCallAudioModeStateMachineFactory,
                mInCallControllerFactory,
                mCallDiagnosticServiceController,
                mRoleManagerAdapter,
                mToastFactory,
                mCallEndpointControllerFactory,
                mCallAnomalyWatchdog,
                mAccessibilityManagerAdapter,
                // Just do async tasks synchronously to support testing.
                command -> command.run(),
                // For call audio tasks
                command -> command.run(),
                mBlockedNumbersAdapter,
                TransactionManager.getTestInstance(),
                mEmergencyCallDiagnosticLogger,
                mCallStreamingNotification);

        when(mPhoneAccountRegistrar.getPhoneAccount(
                eq(SELF_MANAGED_HANDLE), any())).thenReturn(SELF_MANAGED_ACCOUNT);
        when(mPhoneAccountRegistrar.getPhoneAccount(
                eq(SIM_1_HANDLE), any())).thenReturn(SIM_1_ACCOUNT);
        when(mPhoneAccountRegistrar.getPhoneAccount(
                eq(SIM_2_HANDLE), any())).thenReturn(SIM_2_ACCOUNT);
        when(mPhoneAccountRegistrar.getPhoneAccount(
                eq(WORK_HANDLE), any())).thenReturn(WORK_ACCOUNT);
        when(mToastFactory.makeText(any(), anyInt(), anyInt())).thenReturn(mToast);
        when(mToastFactory.makeText(any(), any(), anyInt())).thenReturn(mToast);
    }

    @Override
    @After
    public void tearDown() throws Exception {
        super.tearDown();
    }

    @MediumTest
    @Test
    public void testConstructPossiblePhoneAccounts() throws Exception {
        // Should be empty since the URI is null.
        assertEquals(0, mCallsManager.constructPossiblePhoneAccounts(null, null, false, false).size());
    }

    private Call constructOngoingCall(String callId, PhoneAccountHandle phoneAccountHandle) {
        Call ongoingCall = new Call(
                callId,
                mContext,
                mCallsManager,
                mLock,
                null /* ConnectionServiceRepository */,
                mPhoneNumberUtilsAdapter,
                TEST_ADDRESS,
                null /* GatewayInfo */,
                null /* connectionManagerPhoneAccountHandle */,
                phoneAccountHandle,
                Call.CALL_DIRECTION_INCOMING,
                false /* shouldAttachToExistingConnection*/,
                false /* isConference */,
                mClockProxy,
                mToastFactory);
        ongoingCall.setState(CallState.ACTIVE, "just cuz");
        return ongoingCall;
    }
    /**
     * Verify behavior for multisim devices where we want to ensure that the active sim is used for
     * placing a new call.
     * @throws Exception
     */
    @MediumTest
    @Test
    public void testConstructPossiblePhoneAccountsMultiSimActive() throws Exception {
        setupMsimAccounts();

        Call ongoingCall = constructOngoingCall("1", SIM_2_HANDLE);
        mCallsManager.addCall(ongoingCall);

        List<PhoneAccountHandle> phoneAccountHandles = mCallsManager.constructPossiblePhoneAccounts(
                TEST_ADDRESS, null, false, false);
        assertEquals(1, phoneAccountHandles.size());
        assertEquals(SIM_2_HANDLE, phoneAccountHandles.get(0));
    }

    /**
     * Verify behavior for multisim devices when there are no calls active; expect both accounts.
     * @throws Exception
     */
    @MediumTest
    @Test
    public void testConstructPossiblePhoneAccountsMultiSimIdle() throws Exception {
        setupMsimAccounts();

        List<PhoneAccountHandle> phoneAccountHandles = mCallsManager.constructPossiblePhoneAccounts(
                TEST_ADDRESS, null, false, false);
        assertEquals(2, phoneAccountHandles.size());
    }

    /**
     * For DSDA-enabled multisim devices with an ongoing call, verify that both SIMs'
     * PhoneAccountHandles are constructed while placing a new call.
     * @throws Exception
     */
    @MediumTest
    @Test
    public void testConstructPossiblePhoneAccountsMultiSimActive_dsdaCallingPossible() throws
            Exception {
        setupMsimAccounts();
        setMaxActiveVoiceSubscriptions(2);

        Call ongoingCall = constructOngoingCall("1", SIM_2_HANDLE);
        mCallsManager.addCall(ongoingCall);

        List<PhoneAccountHandle> phoneAccountHandles = mCallsManager.constructPossiblePhoneAccounts(
                TEST_ADDRESS, null, false, false);
        assertEquals(2, phoneAccountHandles.size());
    }

    /**
     * For DSDA-enabled multisim devices with an ongoing call, verify that only the active SIMs'
     * PhoneAccountHandle is constructed while placing an emergency call.
     * @throws Exception
     */
    @MediumTest
    @Test
    public void testConstructPossiblePhoneAccountsMultiSimActive_dsdaCallingPossible_emergencyCall()
            throws Exception {
        setupMsimAccounts();
        setMaxActiveVoiceSubscriptions(2);

        Call ongoingCall = constructOngoingCall("1", SIM_2_HANDLE);
        mCallsManager.addCall(ongoingCall);

        List<PhoneAccountHandle> phoneAccountHandles = mCallsManager.constructPossiblePhoneAccounts(
                TEST_ADDRESS, null, false, true /* isEmergency */);
        assertEquals(1, phoneAccountHandles.size());
        assertEquals(SIM_2_HANDLE, phoneAccountHandles.get(0));
    }

    private void setupCallerInfoLookupHelper() {
        doAnswer(invocation -> {
            Uri handle = invocation.getArgument(0);
            CallerInfoLookupHelper.OnQueryCompleteListener listener = invocation.getArgument(1);
            CallerInfo info = new CallerInfo();
            if (CONTACT_PREFERRED_ACCOUNT.get(handle) != null) {
                PhoneAccountHandle pah = CONTACT_PREFERRED_ACCOUNT.get(handle);
                info.preferredPhoneAccountComponent = pah.getComponentName();
                info.preferredPhoneAccountId = pah.getId();
            }
            listener.onCallerInfoQueryComplete(handle, info);
            return null;
        }).when(mCallerInfoLookupHelper).startLookup(any(Uri.class),
                any(CallerInfoLookupHelper.OnQueryCompleteListener.class));
    }
    /**
     * Tests finding the outgoing call phone account where the call is being placed on a
     * self-managed ConnectionService.
     * @throws Exception
     */
    @MediumTest
    @Test
    public void testFindOutgoingCallPhoneAccountSelfManaged() throws Exception {
        setupCallerInfoLookupHelper();
        List<PhoneAccountHandle> accounts = mCallsManager.findOutgoingCallPhoneAccount(
                SELF_MANAGED_HANDLE, TEST_ADDRESS, false /* isVideo */, false /* isEmergency */, null /* userHandle */)
                .get();
        assertEquals(1, accounts.size());
        assertEquals(SELF_MANAGED_HANDLE, accounts.get(0));
    }

    /**
     * Tests finding the outgoing calling account where the call has no associated phone account,
     * but there is a user specified default which can be used.
     * @throws Exception
     */
    @MediumTest
    @Test
    public void testFindOutgoingCallAccountDefault() throws Exception {
        setupCallerInfoLookupHelper();
        when(mPhoneAccountRegistrar.getOutgoingPhoneAccountForScheme(any(), any())).thenReturn(
                SIM_1_HANDLE);
        when(mPhoneAccountRegistrar.getCallCapablePhoneAccounts(any(), anyBoolean(),
                any(), anyInt(), anyInt(), anyBoolean())).thenReturn(
                new ArrayList<>(Arrays.asList(SIM_1_HANDLE, SIM_2_HANDLE)));

        List<PhoneAccountHandle> accounts = mCallsManager.findOutgoingCallPhoneAccount(
                null /* phoneAcct */, TEST_ADDRESS, false /* isVideo */, false /* isEmergency */, null /* userHandle */)
                .get();

        // Should have found just the default.
        assertEquals(1, accounts.size());
        assertEquals(SIM_1_HANDLE, accounts.get(0));
    }

    /**
     * Tests finding the outgoing calling account where the call has no associated phone account,
     * but there is no user specified default which can be used.
     * @throws Exception
     */
    @MediumTest
    @Test
    public void testFindOutgoingCallAccountNoDefault() throws Exception {
        setupCallerInfoLookupHelper();
        when(mPhoneAccountRegistrar.getOutgoingPhoneAccountForScheme(any(), any())).thenReturn(
                null);
        when(mPhoneAccountRegistrar.getCallCapablePhoneAccounts(any(), anyBoolean(),
                any(), anyInt(), anyInt(), anyBoolean())).thenReturn(
                new ArrayList<>(Arrays.asList(SIM_1_HANDLE, SIM_2_HANDLE)));

        List<PhoneAccountHandle> accounts = mCallsManager.findOutgoingCallPhoneAccount(
                null /* phoneAcct */, TEST_ADDRESS, false /* isVideo */, false /* isEmergency */, null /* userHandle */)
                .get();

        assertEquals(2, accounts.size());
        assertTrue(accounts.contains(SIM_1_HANDLE));
        assertTrue(accounts.contains(SIM_2_HANDLE));
    }

    /**
     * Tests that we will default to a video capable phone account if one is available for a video
     * call.
     * @throws Exception
     */
    @MediumTest
    @Test
    public void testFindOutgoingCallAccountVideo() throws Exception {
        setupCallerInfoLookupHelper();
        when(mPhoneAccountRegistrar.getOutgoingPhoneAccountForScheme(any(), any())).thenReturn(
                null);
        when(mPhoneAccountRegistrar.getCallCapablePhoneAccounts(any(), anyBoolean(),
                any(), eq(PhoneAccount.CAPABILITY_VIDEO_CALLING), anyInt(), anyBoolean()))
                .thenReturn(new ArrayList<>(Arrays.asList(SIM_2_HANDLE)));

        List<PhoneAccountHandle> accounts = mCallsManager.findOutgoingCallPhoneAccount(
                null /* phoneAcct */, TEST_ADDRESS, true /* isVideo */, false /* isEmergency */, null /* userHandle */)
                .get();

        assertEquals(1, accounts.size());
        assertTrue(accounts.contains(SIM_2_HANDLE));
    }

    /**
     * Tests that we will default to a non-video capable phone account for a video call if no video
     * capable phone accounts are available.
     * @throws Exception
     */
    @MediumTest
    @Test
    public void testFindOutgoingCallAccountVideoNotAvailable() throws Exception {
        setupCallerInfoLookupHelper();
        when(mPhoneAccountRegistrar.getOutgoingPhoneAccountForScheme(any(), any())).thenReturn(
                null);
        // When querying for video capable accounts, return nothing.
        when(mPhoneAccountRegistrar.getCallCapablePhoneAccounts(any(), anyBoolean(),
                any(), eq(PhoneAccount.CAPABILITY_VIDEO_CALLING), anyInt(), anyBoolean())).
                thenReturn(Collections.emptyList());
        // When querying for non-video capable accounts, return one.
        when(mPhoneAccountRegistrar.getCallCapablePhoneAccounts(any(), anyBoolean(),
                any(), eq(0 /* none specified */), anyInt(), anyBoolean())).thenReturn(
                new ArrayList<>(Arrays.asList(SIM_1_HANDLE)));
        List<PhoneAccountHandle> accounts = mCallsManager.findOutgoingCallPhoneAccount(
                null /* phoneAcct */, TEST_ADDRESS, true /* isVideo */, false /* isEmergency */, null /* userHandle */)
                .get();

        // Should have found one.
        assertEquals(1, accounts.size());
        assertTrue(accounts.contains(SIM_1_HANDLE));
    }

    /**
     * Tests that we will use the provided target phone account if it exists.
     * @throws Exception
     */
    @MediumTest
    @Test
    public void testUseSpecifiedAccount() throws Exception {
        setupCallerInfoLookupHelper();
        when(mPhoneAccountRegistrar.getOutgoingPhoneAccountForScheme(any(), any())).thenReturn(
                null);
        when(mPhoneAccountRegistrar.getCallCapablePhoneAccounts(any(), anyBoolean(),
                any(), anyInt(), anyInt(), anyBoolean())).thenReturn(
                new ArrayList<>(Arrays.asList(SIM_1_HANDLE, SIM_2_HANDLE)));

        List<PhoneAccountHandle> accounts = mCallsManager.findOutgoingCallPhoneAccount(
                SIM_2_HANDLE, TEST_ADDRESS, false /* isVideo */, false /* isEmergency */, null /* userHandle */).get();

        assertEquals(1, accounts.size());
        assertTrue(accounts.contains(SIM_2_HANDLE));
    }

    /**
     * Tests that we will use the provided target phone account if it exists.
     * @throws Exception
     */
    @MediumTest
    @Test
    public void testUseContactSpecificAcct() throws Exception {
        setupCallerInfoLookupHelper();
        when(mPhoneAccountRegistrar.getOutgoingPhoneAccountForScheme(any(), any())).thenReturn(
                null);
        when(mPhoneAccountRegistrar.getCallCapablePhoneAccounts(any(), anyBoolean(),
                any(), anyInt(), anyInt(), anyBoolean())).thenReturn(
                new ArrayList<>(Arrays.asList(SIM_1_HANDLE, SIM_2_HANDLE)));

        List<PhoneAccountHandle> accounts = mCallsManager.findOutgoingCallPhoneAccount(
                null, TEST_ADDRESS2, false /* isVideo */, false /* isEmergency */, Process.myUserHandle()).get();

        assertEquals(1, accounts.size());
        assertTrue(accounts.contains(SIM_1_HANDLE));
    }

    /**
     * Verifies that an active call will result in playing a DTMF tone when requested.
     * @throws Exception
     */
    @MediumTest
    @Test
    public void testPlayDtmfWhenActive() throws Exception {
        Call callSpy = addSpyCall();
        mCallsManager.playDtmfTone(callSpy, '1');
        verify(callSpy).playDtmfTone(anyChar());
    }

    /**
     * Verifies that DTMF requests are suppressed when a call is held.
     * @throws Exception
     */
    @MediumTest
    @Test
    public void testSuppessDtmfWhenHeld() throws Exception {
        Call callSpy = addSpyCall();
        callSpy.setState(CallState.ON_HOLD, "test");

        mCallsManager.playDtmfTone(callSpy, '1');
        verify(callSpy, never()).playDtmfTone(anyChar());
    }

    /**
     * Verifies that DTMF requests are suppressed when a call is held.
     * @throws Exception
     */
    @MediumTest
    @Test
    public void testCancelDtmfWhenHeld() throws Exception {
        Call callSpy = addSpyCall();
        mCallsManager.playDtmfTone(callSpy, '1');
        mCallsManager.markCallAsOnHold(callSpy);
        verify(callSpy).stopDtmfTone();
    }

    @SmallTest
    @Test
    public void testUnholdCallWhenOngoingCallCanBeHeld() {
        // GIVEN a CallsManager with ongoing call, and this call can be held
        Call ongoingCall = addSpyCall();
        doReturn(true).when(ongoingCall).can(Connection.CAPABILITY_HOLD);
        doReturn(true).when(ongoingCall).can(Connection.CAPABILITY_SUPPORT_HOLD);
        when(mConnectionSvrFocusMgr.getCurrentFocusCall()).thenReturn(ongoingCall);

        // and a held call
        Call heldCall = addSpyCall();

        // WHEN unhold the held call
        mCallsManager.unholdCall(heldCall);

        // THEN the ongoing call is held, and the focus request for incoming call is sent
        verify(ongoingCall).hold(any());
        verifyFocusRequestAndExecuteCallback(heldCall);

        // and held call is unhold now
        verify(heldCall).unhold(any());
    }

    @SmallTest
    @Test
    public void testUnholdCallWhenOngoingCallCanNotBeHeldAndFromDifferentConnectionService() {
        // GIVEN a CallsManager with ongoing call, and this call can not be held
        Call ongoingCall = addSpyCall(SIM_1_HANDLE, CallState.ACTIVE);
        doReturn(false).when(ongoingCall).can(Connection.CAPABILITY_HOLD);
        doReturn(false).when(ongoingCall).can(Connection.CAPABILITY_SUPPORT_HOLD);
        when(mConnectionSvrFocusMgr.getCurrentFocusCall()).thenReturn(ongoingCall);

        // and a held call which has different ConnectionService
        Call heldCall = addSpyCall(VOIP_1_HANDLE, CallState.ON_HOLD);

        // WHEN unhold the held call
        mCallsManager.unholdCall(heldCall);

        // THEN the ongoing call is disconnected, and the focus request for incoming call is sent
        verify(ongoingCall).disconnect(any());
        verifyFocusRequestAndExecuteCallback(heldCall);

        // and held call is unhold now
        verify(heldCall).unhold(any());
    }

    /**
     * Ensures we don't auto-unhold a call from a different app when we locally disconnect a call.
     */
    @SmallTest
    @Test
    public void testDontUnholdCallsBetweenConnectionServices() {
        // GIVEN a CallsManager with ongoing call
        Call ongoingCall = addSpyCall(SIM_1_HANDLE, CallState.ACTIVE);
        when(ongoingCall.isDisconnectHandledViaFuture()).thenReturn(false);
        doReturn(true).when(ongoingCall).can(Connection.CAPABILITY_HOLD);
        doReturn(true).when(ongoingCall).can(Connection.CAPABILITY_SUPPORT_HOLD);
        when(mConnectionSvrFocusMgr.getCurrentFocusCall()).thenReturn(ongoingCall);

        // and a held call which has different ConnectionService
        Call heldCall = addSpyCall(VOIP_1_HANDLE, CallState.ON_HOLD);

        // Disconnect and cleanup the active ongoing call.
        mCallsManager.disconnectCall(ongoingCall);
        mCallsManager.markCallAsRemoved(ongoingCall);

        // Should not unhold the held call since its in another app.
        verify(heldCall, never()).unhold();
    }

    /**
     * Ensures we do auto-unhold a call from the same app when we locally disconnect a call.
     */
    @SmallTest
    @Test
    public void testUnholdCallWhenDisconnectingInSameApp() {
        // GIVEN a CallsManager with ongoing call
        Call ongoingCall = addSpyCall(SIM_1_HANDLE, CallState.ACTIVE);
        when(ongoingCall.isDisconnectHandledViaFuture()).thenReturn(false);
        doReturn(true).when(ongoingCall).can(Connection.CAPABILITY_HOLD);
        doReturn(true).when(ongoingCall).can(Connection.CAPABILITY_SUPPORT_HOLD);
        when(mConnectionSvrFocusMgr.getCurrentFocusCall()).thenReturn(ongoingCall);

        // and a held call which has same ConnectionService
        Call heldCall = addSpyCall(SIM_1_HANDLE, CallState.ON_HOLD);

        // Disconnect and cleanup the active ongoing call.
        mCallsManager.disconnectCall(ongoingCall);
        mCallsManager.markCallAsRemoved(ongoingCall);

        // Should auto-unhold the held call since its in the same app.
        verify(heldCall).unhold();
    }

    @SmallTest
    @Test
    public void testUnholdCallWhenOngoingEmergCallCanNotBeHeldAndFromDifferentConnectionService() {
        // GIVEN a CallsManager with ongoing call, and this call can not be held, but it also an
        // emergency call.
        Call ongoingCall = addSpyCall(SIM_1_HANDLE, CallState.ACTIVE);
        doReturn(false).when(ongoingCall).can(Connection.CAPABILITY_HOLD);
        doReturn(false).when(ongoingCall).can(Connection.CAPABILITY_SUPPORT_HOLD);
        doReturn(true).when(ongoingCall).isEmergencyCall();
        when(mConnectionSvrFocusMgr.getCurrentFocusCall()).thenReturn(ongoingCall);

        // and a held call which has different ConnectionService
        Call heldCall = addSpyCall(VOIP_1_HANDLE, CallState.ON_HOLD);

        // WHEN unhold the held call
        mCallsManager.unholdCall(heldCall);

        // THEN the ongoing call will not be disconnected (because its an emergency call)
        verify(ongoingCall, never()).disconnect(any());

        // and held call is not un-held
        verify(heldCall, never()).unhold(any());
    }

    @SmallTest
    @Test
    public void testUnholdCallWhenOngoingCallCanNotBeHeldAndHasSameConnectionService() {
        // GIVEN a CallsManager with ongoing call, and this call can not be held
        Call ongoingCall = addSpyCall(SIM_1_HANDLE, CallState.ACTIVE);
        doReturn(false).when(ongoingCall).can(Connection.CAPABILITY_HOLD);
        doReturn(true).when(ongoingCall).can(Connection.CAPABILITY_SUPPORT_HOLD);
        when(mConnectionSvrFocusMgr.getCurrentFocusCall()).thenReturn(ongoingCall);

        // and a held call which has the same ConnectionService
        Call heldCall = addSpyCall(SIM_2_HANDLE, CallState.ON_HOLD);

        // WHEN unhold the held call
        mCallsManager.unholdCall(heldCall);

        // THEN the ongoing call is held
        verify(ongoingCall).hold(any());
        verifyFocusRequestAndExecuteCallback(heldCall);

        // and held call is unhold now
        verify(heldCall).unhold(any());
    }

    @SmallTest
    @Test
    public void testDuplicateAnswerCall() {
        Call incomingCall = addSpyCall(CallState.RINGING);
        doAnswer(invocation -> {
            doReturn(CallState.ANSWERED).when(incomingCall).getState();
            return null;
        }).when(incomingCall).answer(anyInt());
        mCallsManager.answerCall(incomingCall, VideoProfile.STATE_AUDIO_ONLY);
        verifyFocusRequestAndExecuteCallback(incomingCall);
        reset(mConnectionSvrFocusMgr);
        mCallsManager.answerCall(incomingCall, VideoProfile.STATE_AUDIO_ONLY);
        verifyFocusRequestAndExecuteCallback(incomingCall);

        verify(incomingCall, times(2)).answer(anyInt());
    }

    @SmallTest
    @Test
    public void testAnswerCallWhenOngoingCallCanBeHeld() {
        // GIVEN a CallsManager with ongoing call, and this call can be held
        Call ongoingCall = addSpyCall();
        doReturn(true).when(ongoingCall).can(Connection.CAPABILITY_HOLD);
        doReturn(true).when(ongoingCall).can(Connection.CAPABILITY_SUPPORT_HOLD);
        when(mConnectionSvrFocusMgr.getCurrentFocusCall()).thenReturn(ongoingCall);

        // WHEN answer an incoming call
        Call incomingCall = addSpyCall(CallState.RINGING);
        mCallsManager.answerCall(incomingCall, VideoProfile.STATE_AUDIO_ONLY);

        // THEN the ongoing call is held and the focus request for incoming call is sent
        verify(ongoingCall).hold(anyString());
        verifyFocusRequestAndExecuteCallback(incomingCall);

        // and the incoming call is answered.
        verify(incomingCall).answer(VideoProfile.STATE_AUDIO_ONLY);
    }

    @SmallTest
    @Test
    public void testAnswerCallWhenOngoingHasSameConnectionService() {
        // GIVEN a CallsManager with ongoing call, and this call can not be held
        Call ongoingCall = addSpyCall(SIM_1_HANDLE, CallState.ACTIVE);
        doReturn(false).when(ongoingCall).can(Connection.CAPABILITY_HOLD);
        when(mConnectionSvrFocusMgr.getCurrentFocusCall()).thenReturn(ongoingCall);

        // WHEN answer an incoming call
        Call incomingCall = addSpyCall(VOIP_1_HANDLE, CallState.RINGING);
        mCallsManager.answerCall(incomingCall, VideoProfile.STATE_AUDIO_ONLY);

        // THEN nothing happened on the ongoing call and the focus request for incoming call is sent
        verifyFocusRequestAndExecuteCallback(incomingCall);

        // and the incoming call is answered.
        verify(incomingCall).answer(VideoProfile.STATE_AUDIO_ONLY);
    }

    @SmallTest
    @Test
    public void testAnswerCallWhenOngoingHasDifferentConnectionService() {
        // GIVEN a CallsManager with ongoing call, and this call can not be held
        Call ongoingCall = addSpyCall(SIM_1_HANDLE, CallState.ACTIVE);
        doReturn(false).when(ongoingCall).can(Connection.CAPABILITY_HOLD);
        doReturn(true).when(ongoingCall).can(Connection.CAPABILITY_SUPPORT_HOLD);
        when(mConnectionSvrFocusMgr.getCurrentFocusCall()).thenReturn(ongoingCall);

        // WHEN answer an incoming call
        Call incomingCall = addSpyCall(VOIP_1_HANDLE, CallState.RINGING);
        mCallsManager.answerCall(incomingCall, VideoProfile.STATE_AUDIO_ONLY);

        // THEN the ongoing call is disconnected and the focus request for incoming call is sent
        verify(ongoingCall).disconnect();
        verifyFocusRequestAndExecuteCallback(incomingCall);

        // and the incoming call is answered.
        verify(incomingCall).answer(VideoProfile.STATE_AUDIO_ONLY);
    }

    @SmallTest
    @Test
    public void testAnswerCallWhenOngoingHasDifferentConnectionServiceButIsEmerg() {
        // GIVEN a CallsManager with ongoing call, and this call can not be held
        Call ongoingCall = addSpyCall(SIM_1_HANDLE, CallState.ACTIVE);
        doReturn(false).when(ongoingCall).can(Connection.CAPABILITY_HOLD);
        doReturn(true).when(ongoingCall).can(Connection.CAPABILITY_SUPPORT_HOLD);
        doReturn(true).when(ongoingCall).isEmergencyCall();
        when(mConnectionSvrFocusMgr.getCurrentFocusCall()).thenReturn(ongoingCall);

        // WHEN answer an incoming call
        Call incomingCall = addSpyCall(VOIP_1_HANDLE, CallState.RINGING);
        mCallsManager.answerCall(incomingCall, VideoProfile.STATE_AUDIO_ONLY);

        // THEN the ongoing call is not disconnected
        verify(ongoingCall, never()).disconnect();

        // and the incoming call is not answered, but is rejected instead.
        verify(incomingCall, never()).answer(VideoProfile.STATE_AUDIO_ONLY);
        verify(incomingCall).reject(eq(false), any(), any());
    }

    @SmallTest
    @Test
    public void testAnswerCallWhenMultipleHeldCallsExisted() {
        // Given an ongoing call and held call with the ConnectionService connSvr1. The
        // ConnectionService connSvr1 can handle one held call
        Call ongoingCall = addSpyCall(SIM_1_HANDLE, CallState.ACTIVE);
        doReturn(false).when(ongoingCall).can(Connection.CAPABILITY_HOLD);
        doReturn(true).when(ongoingCall).can(Connection.CAPABILITY_SUPPORT_HOLD);
        doReturn(CallState.ACTIVE).when(ongoingCall).getState();
        when(mConnectionSvrFocusMgr.getCurrentFocusCall()).thenReturn(ongoingCall);

        Call heldCall = addSpyCall(SIM_1_HANDLE, CallState.ON_HOLD);
        doReturn(CallState.ON_HOLD).when(heldCall).getState();

        // and other held call has difference ConnectionService
        Call heldCall2 = addSpyCall(VOIP_1_HANDLE, CallState.ON_HOLD);
        doReturn(CallState.ON_HOLD).when(heldCall2).getState();

        // WHEN answer an incoming call which ConnectionService is connSvr1
        Call incomingCall = addSpyCall(SIM_1_HANDLE, CallState.RINGING);
        doReturn(true).when(incomingCall).can(Connection.CAPABILITY_SUPPORT_HOLD);
        mCallsManager.answerCall(incomingCall, VideoProfile.STATE_AUDIO_ONLY);

        // THEN the previous held call is disconnected
        verify(heldCall).disconnect();

        // and the ongoing call is held
        verify(ongoingCall).hold();

        // and the heldCall2 is not disconnected
        verify(heldCall2, never()).disconnect();

        // and the focus request is sent
        verifyFocusRequestAndExecuteCallback(incomingCall);

        // and the incoming call is answered
        verify(incomingCall).answer(VideoProfile.STATE_AUDIO_ONLY);
    }

    @SmallTest
    @Test
    public void testAnswerThirdCallWhenTwoCallsOnDifferentSims_disconnectsHeldCall() {
        // Given an ongoing call on SIM1
        Call ongoingCall = addSpyCall(SIM_1_HANDLE, CallState.ACTIVE);
        doReturn(true).when(ongoingCall).can(Connection.CAPABILITY_SUPPORT_HOLD);
        doReturn(CallState.ACTIVE).when(ongoingCall).getState();
        when(mConnectionSvrFocusMgr.getCurrentFocusCall()).thenReturn(ongoingCall);

        // And a held call on SIM2, which belongs to the same ConnectionService
        Call heldCall = addSpyCall(SIM_2_HANDLE, CallState.ON_HOLD);
        doReturn(CallState.ON_HOLD).when(heldCall).getState();

        // on answering an incoming call on SIM1, which belongs to the same ConnectionService
        Call incomingCall = addSpyCall(SIM_1_HANDLE, CallState.RINGING);
        mCallsManager.answerCall(incomingCall, VideoProfile.STATE_AUDIO_ONLY);

        // THEN the previous held call is disconnected
        verify(heldCall).disconnect();

        // and the ongoing call is held
        verify(ongoingCall).hold();

        // and the focus request is sent
        verifyFocusRequestAndExecuteCallback(incomingCall);
        // and the incoming call is answered
        verify(incomingCall).answer(VideoProfile.STATE_AUDIO_ONLY);
    }

    @SmallTest
    @Test
    public void testAnswerThirdCallDifferentSimWhenTwoCallsOnSameSim_disconnectsHeldCall() {
        // Given an ongoing call on SIM1
        Call ongoingCall = addSpyCall(SIM_1_HANDLE, CallState.ACTIVE);
        doReturn(true).when(ongoingCall).can(Connection.CAPABILITY_SUPPORT_HOLD);
        doReturn(CallState.ACTIVE).when(ongoingCall).getState();
        when(mConnectionSvrFocusMgr.getCurrentFocusCall()).thenReturn(ongoingCall);

        // And a held call on SIM1
        Call heldCall = addSpyCall(SIM_1_HANDLE, CallState.ON_HOLD);
        doReturn(CallState.ON_HOLD).when(heldCall).getState();

        // on answering an incoming call on SIM2, which belongs to the same ConnectionService
        Call incomingCall = addSpyCall(SIM_2_HANDLE, CallState.RINGING);
        mCallsManager.answerCall(incomingCall, VideoProfile.STATE_AUDIO_ONLY);

        // THEN the previous held call is disconnected
        verify(heldCall).disconnect();

        // and the ongoing call is held
        verify(ongoingCall).hold();

        // and the focus request is sent
        verifyFocusRequestAndExecuteCallback(incomingCall);
        // and the incoming call is answered
        verify(incomingCall).answer(VideoProfile.STATE_AUDIO_ONLY);
    }

    @SmallTest
    @Test
    public void testAnswerCallWhenNoOngoingCallExisted() {
        // GIVEN a CallsManager with no ongoing call.

        // WHEN answer an incoming call
        Call incomingCall = addSpyCall(CallState.RINGING);
        mCallsManager.answerCall(incomingCall, VideoProfile.STATE_AUDIO_ONLY);

        // THEN the focus request for incoming call is sent
        verifyFocusRequestAndExecuteCallback(incomingCall);

        // and the incoming call is answered.
        verify(incomingCall).answer(VideoProfile.STATE_AUDIO_ONLY);
    }

    @SmallTest
    @Test
    public void testAnswerAlreadyActiveCall() {
        // GIVEN a CallsManager with no ongoing call.

        // WHEN answer an already active call
        Call incomingCall = addSpyCall(CallState.RINGING);
        mCallsManager.answerCall(incomingCall, VideoProfile.STATE_AUDIO_ONLY);

        // THEN the focus request for incoming call is sent
        verifyFocusRequestAndExecuteCallback(incomingCall);

        // and the incoming call is answered.
        verify(incomingCall).answer(VideoProfile.STATE_AUDIO_ONLY);

        // and the incoming call's state is now ANSWERED
        assertEquals(CallState.ANSWERED, incomingCall.getState());
    }

    @SmallTest
    @Test
    public void testSetActiveCallWhenOngoingCallCanNotBeHeldAndFromDifferentConnectionService() {
        // GIVEN a CallsManager with ongoing call, and this call can not be held
        Call ongoingCall = addSpyCall(SIM_1_HANDLE, CallState.ACTIVE);
        doReturn(false).when(ongoingCall).can(Connection.CAPABILITY_HOLD);
        doReturn(false).when(ongoingCall).can(Connection.CAPABILITY_SUPPORT_HOLD);
        doReturn(ongoingCall).when(mConnectionSvrFocusMgr).getCurrentFocusCall();

        // and a new self-managed call which has different ConnectionService
        Call newCall = addSpyCall(VOIP_1_HANDLE, CallState.ACTIVE);
        doReturn(true).when(newCall).isSelfManaged();

        // WHEN active the new call
        mCallsManager.markCallAsActive(newCall);

        // THEN the ongoing call is disconnected, and the focus request for the new call is sent
        verify(ongoingCall).disconnect();
        verifyFocusRequestAndExecuteCallback(newCall);

        // and the new call is active
        assertEquals(CallState.ACTIVE, newCall.getState());
    }

    @SmallTest
    @Test
    public void testSetActiveCallWhenOngoingCallCanNotBeHeldAndHasSameConnectionService() {
        // GIVEN a CallsManager with ongoing call, and this call can not be held
        Call ongoingCall = addSpyCall(SIM_1_HANDLE, CallState.ACTIVE);
        doReturn(false).when(ongoingCall).can(Connection.CAPABILITY_HOLD);
        doReturn(false).when(ongoingCall).can(Connection.CAPABILITY_SUPPORT_HOLD);
        when(mConnectionSvrFocusMgr.getCurrentFocusCall()).thenReturn(ongoingCall);

        // and a new self-managed call which has the same ConnectionService
        Call newCall = addSpyCall(SIM_1_HANDLE, CallState.ACTIVE);
        doReturn(true).when(newCall).isSelfManaged();

        // WHEN active the new call
        mCallsManager.markCallAsActive(newCall);

        // THEN the ongoing call isn't disconnected
        verify(ongoingCall, never()).disconnect();
        verifyFocusRequestAndExecuteCallback(newCall);

        // and the new call is active
        assertEquals(CallState.ACTIVE, newCall.getState());
    }

    @SmallTest
    @Test
    public void testSetActiveCallWhenOngoingCallCanBeHeld() {
        // GIVEN a CallsManager with ongoing call, and this call can be held
        Call ongoingCall = addSpyCall();
        doReturn(true).when(ongoingCall).can(Connection.CAPABILITY_HOLD);
        doReturn(true).when(ongoingCall).can(Connection.CAPABILITY_SUPPORT_HOLD);
        doReturn(ongoingCall).when(mConnectionSvrFocusMgr).getCurrentFocusCall();

        // and a new self-managed call
        Call newCall = addSpyCall();
        doReturn(true).when(newCall).isSelfManaged();

        // WHEN active the new call
        mCallsManager.markCallAsActive(newCall);

        // THEN the ongoing call is held
        verify(ongoingCall).hold(anyString());
        verifyFocusRequestAndExecuteCallback(newCall);

        // and the new call is active
        assertEquals(CallState.ACTIVE, newCall.getState());
    }

    @SmallTest
    @Test
    public void testDisconnectDialingCallOnIncoming() {
        // GIVEN a CallsManager with a self-managed call which is dialing, and this call can be held
        Call ongoingCall = addSpyCall(SELF_MANAGED_HANDLE, CallState.DIALING);
        ongoingCall.setState(CallState.DIALING, "test");
        doReturn(true).when(ongoingCall).can(Connection.CAPABILITY_HOLD);
        doReturn(true).when(ongoingCall).can(Connection.CAPABILITY_SUPPORT_HOLD);
        doReturn(true).when(ongoingCall).isSelfManaged();
        doReturn(ongoingCall).when(mConnectionSvrFocusMgr).getCurrentFocusCall();

        // and a new incoming managed call
        Call newCall = addSpyCall();
        doReturn(false).when(newCall).isRespondViaSmsCapable();
        newCall.setState(CallState.RINGING, "test");

        // WHEN answering the new call
        mCallsManager.answerCall(newCall, VideoProfile.STATE_AUDIO_ONLY);

        // THEN the ongoing call is disconnected
        verify(ongoingCall).disconnect();

        // AND focus is requested for the new call
        ArgumentCaptor<CallsManager.RequestCallback> requestCaptor =
                ArgumentCaptor.forClass(CallsManager.RequestCallback.class);
        verify(mConnectionSvrFocusMgr).requestFocus(eq(newCall), requestCaptor.capture());
        // since we're mocking the focus manager, we'll just pretend it did its thing.
        requestCaptor.getValue().onRequestFocusDone(newCall);

        // and the new call is marked answered
        assertEquals(CallState.ANSWERED, newCall.getState());
    }

    @SmallTest
    @Test
    public void testNoFilteringOfSelfManagedCalls() {
        // GIVEN an incoming call which is self managed.
        Call incomingCall = addSpyCall(SELF_MANAGED_HANDLE, CallState.NEW);
        doReturn(false).when(incomingCall).can(Connection.CAPABILITY_HOLD);
        doReturn(false).when(incomingCall).can(Connection.CAPABILITY_SUPPORT_HOLD);
        doReturn(true).when(incomingCall).isSelfManaged();
        doReturn(true).when(incomingCall).setState(anyInt(), any());

        // WHEN the incoming call is successfully added.
        mCallsManager.onSuccessfulIncomingCall(incomingCall);

        // THEN the incoming call is not using call filtering
        verify(incomingCall).setIsUsingCallFiltering(eq(false));
    }

    @SmallTest
    @Test
    public void testNoFilteringOfNetworkIdentifiedEmergencyCalls() {
        // GIVEN an incoming call which is network identified as an emergency call.
        Call incomingCall = addSpyCall(CallState.NEW);
        incomingCall.setConnectionProperties(Connection.PROPERTY_NETWORK_IDENTIFIED_EMERGENCY_CALL);
        doReturn(false).when(incomingCall).can(Connection.CAPABILITY_HOLD);
        doReturn(false).when(incomingCall).can(Connection.CAPABILITY_SUPPORT_HOLD);
        doReturn(true).when(incomingCall)
                .hasProperty(Connection.PROPERTY_NETWORK_IDENTIFIED_EMERGENCY_CALL);
        doReturn(true).when(incomingCall).setState(anyInt(), any());

        // WHEN the incoming call is successfully added.
        mCallsManager.onSuccessfulIncomingCall(incomingCall);

        // THEN the incoming call is not using call filtering
        verify(incomingCall).setIsUsingCallFiltering(eq(false));
    }

    @SmallTest
    @Test
    public void testNoFilteringOfEmergencySmsModeCalls() {
        // GIVEN an incoming call which is network identified as an emergency call.
        Call incomingCall = addSpyCall(CallState.NEW);
        when(mComponentContextFixture.getTelephonyManager().isInEmergencySmsMode())
                .thenReturn(true);
        doReturn(false).when(incomingCall).can(Connection.CAPABILITY_HOLD);
        doReturn(false).when(incomingCall).can(Connection.CAPABILITY_SUPPORT_HOLD);
        doReturn(true).when(incomingCall).setState(anyInt(), any());

        // WHEN the incoming call is successfully added.
        mCallsManager.onSuccessfulIncomingCall(incomingCall);

        // THEN the incoming call is not using call filtering
        verify(incomingCall).setIsUsingCallFiltering(eq(false));
    }

    @SmallTest
    @Test
    public void testAcceptIncomingCallWhenHeadsetMediaButtonShortPress() {
        // GIVEN an incoming call
        Call incomingCall = addSpyCall();
        doReturn(CallState.RINGING).when(incomingCall).getState();

        // WHEN media button short press
        mCallsManager.onMediaButton(HeadsetMediaButton.SHORT_PRESS);

        // THEN the incoming call is answered
        ArgumentCaptor<CallsManager.RequestCallback> captor = ArgumentCaptor.forClass(
                CallsManager.RequestCallback.class);
        verify(mConnectionSvrFocusMgr).requestFocus(eq(incomingCall), captor.capture());
        captor.getValue().onRequestFocusDone(incomingCall);
        verify(incomingCall).answer(VideoProfile.STATE_AUDIO_ONLY);
    }

    @SmallTest
    @Test
    public void testRejectIncomingCallWhenHeadsetMediaButtonLongPress() {
        // GIVEN an incoming call
        Call incomingCall = addSpyCall();
        doReturn(CallState.RINGING).when(incomingCall).getState();

        // WHEN media button long press
        mCallsManager.onMediaButton(HeadsetMediaButton.LONG_PRESS);

        // THEN the incoming call is rejected
        verify(incomingCall).reject(false, null);
    }

    @SmallTest
    @Test
    public void testHangupOngoingCallWhenHeadsetMediaButtonShortPress() {
        // GIVEN an ongoing call
        Call ongoingCall = addSpyCall();
        doReturn(CallState.ACTIVE).when(ongoingCall).getState();

        // WHEN media button short press
        mCallsManager.onMediaButton(HeadsetMediaButton.SHORT_PRESS);

        // THEN the active call is disconnected
        verify(ongoingCall).disconnect();
    }

    @SmallTest
    @Test
    public void testToggleMuteWhenHeadsetMediaButtonLongPressDuringOngoingCall() {
        // GIVEN an ongoing call
        Call ongoingCall = addSpyCall();
        doReturn(CallState.ACTIVE).when(ongoingCall).getState();

        // WHEN media button long press
        mCallsManager.onMediaButton(HeadsetMediaButton.LONG_PRESS);

        // THEN the microphone toggle mute
        verify(mCallAudioRouteStateMachine)
                .sendMessageWithSessionInfo(CallAudioRouteStateMachine.TOGGLE_MUTE);
    }

    @SmallTest
    @Test
    public void testSwapCallsWhenHeadsetMediaButtonShortPressDuringTwoCalls() {
        // GIVEN an ongoing call, and this call can be held
        Call ongoingCall = addSpyCall();
        doReturn(CallState.ACTIVE).when(ongoingCall).getState();
        doReturn(true).when(ongoingCall).can(Connection.CAPABILITY_HOLD);
        doReturn(true).when(ongoingCall).can(Connection.CAPABILITY_SUPPORT_HOLD);
        when(mConnectionSvrFocusMgr.getCurrentFocusCall()).thenReturn(ongoingCall);

        // and a held call
        Call heldCall = addSpyCall();
        doReturn(CallState.ON_HOLD).when(heldCall).getState();

        // WHEN media button short press
        mCallsManager.onMediaButton(HeadsetMediaButton.SHORT_PRESS);

        // THEN the ongoing call is held, and the focus request for heldCall call is sent
        verify(ongoingCall).hold(nullable(String.class));
        verifyFocusRequestAndExecuteCallback(heldCall);

        // and held call is unhold now
        verify(heldCall).unhold(nullable(String.class));
    }

    @SmallTest
    @Test
    public void testHangupActiveCallWhenHeadsetMediaButtonLongPressDuringTwoCalls() {
        // GIVEN an ongoing call
        Call ongoingCall = addSpyCall();
        doReturn(CallState.ACTIVE).when(ongoingCall).getState();

        // and a held call
        Call heldCall = addSpyCall();
        doReturn(CallState.ON_HOLD).when(heldCall).getState();

        // WHEN media button long press
        mCallsManager.onMediaButton(HeadsetMediaButton.LONG_PRESS);

        // THEN the ongoing call is disconnected
        verify(ongoingCall).disconnect();
    }

    @SmallTest
    @Test
    public void testNoFilteringOfCallsWhenPhoneAccountRequestsSkipped() {
        // GIVEN an incoming call which is from a PhoneAccount that requested to skip filtering.
        Call incomingCall = addSpyCall(SIM_1_HANDLE, CallState.NEW);
        Bundle extras = new Bundle();
        extras.putBoolean(PhoneAccount.EXTRA_SKIP_CALL_FILTERING, true);
        PhoneAccount skipRequestedAccount = new PhoneAccount.Builder(SIM_2_HANDLE, "Skipper")
            .setCapabilities(PhoneAccount.CAPABILITY_SIM_SUBSCRIPTION
                | PhoneAccount.CAPABILITY_CALL_PROVIDER)
            .setExtras(extras)
            .setIsEnabled(true)
            .build();
        when(mPhoneAccountRegistrar.getPhoneAccountUnchecked(SIM_1_HANDLE))
            .thenReturn(skipRequestedAccount);
        doReturn(false).when(incomingCall).can(Connection.CAPABILITY_HOLD);
        doReturn(false).when(incomingCall).can(Connection.CAPABILITY_SUPPORT_HOLD);
        doReturn(false).when(incomingCall).isSelfManaged();
        doReturn(true).when(incomingCall).setState(anyInt(), any());

        // WHEN the incoming call is successfully added.
        mCallsManager.onSuccessfulIncomingCall(incomingCall);

        // THEN the incoming call is not using call filtering
        verify(incomingCall).setIsUsingCallFiltering(eq(false));
    }

    @SmallTest
    @Test
    public void testIsInEmergencyCallNetwork() {
        // Setup a call which the network identified as an emergency call.
        Call ongoingCall = addSpyCall();
        ongoingCall.setConnectionProperties(Connection.PROPERTY_NETWORK_IDENTIFIED_EMERGENCY_CALL);

        assertFalse(ongoingCall.isEmergencyCall());
        assertTrue(ongoingCall.isNetworkIdentifiedEmergencyCall());
        assertTrue(mCallsManager.isInEmergencyCall());
    }

    @SmallTest
    @Test
    public void testIsInEmergencyCallLocal() {
        // Setup a call which is considered emergency based on its phone number.
        Call ongoingCall = addSpyCall();
        when(mComponentContextFixture.getTelephonyManager().isEmergencyNumber(any()))
                .thenReturn(true);
        ongoingCall.setHandle(Uri.fromParts("tel", "5551212", null),
                TelecomManager.PRESENTATION_ALLOWED);

        assertTrue(ongoingCall.isEmergencyCall());
        assertFalse(ongoingCall.isNetworkIdentifiedEmergencyCall());
        assertTrue(mCallsManager.isInEmergencyCall());
    }

    @SmallTest
    @Test
    public void testIsInEmergencyCallLocalDisconnected() {
        // Setup a call which is considered emergency based on its phone number.
        Call ongoingCall = addSpyCall();
        when(mComponentContextFixture.getTelephonyManager().isEmergencyNumber(any()))
                .thenReturn(true);
        ongoingCall.setHandle(Uri.fromParts("tel", "5551212", null),
                TelecomManager.PRESENTATION_ALLOWED);

        // and then set it as disconnected.
        ongoingCall.setState(CallState.DISCONNECTED, "");
        assertTrue(ongoingCall.isEmergencyCall());
        assertFalse(ongoingCall.isNetworkIdentifiedEmergencyCall());
        assertFalse(mCallsManager.isInEmergencyCall());
    }


    @SmallTest
    @Test
    public void testBlockNonEmergencyCallDuringEmergencyCall() throws Exception {
        // Setup a call which the network identified as an emergency call.
        Call ongoingCall = addSpyCall();
        ongoingCall.setConnectionProperties(Connection.PROPERTY_NETWORK_IDENTIFIED_EMERGENCY_CALL);
        assertTrue(mCallsManager.isInEmergencyCall());

        Call newCall = addSpyCall(CallState.NEW);
        ConnectionServiceWrapper service = mock(ConnectionServiceWrapper.class);
        doReturn(SIM_2_HANDLE.getComponentName()).when(service).getComponentName();

        // Ensure contact info lookup succeeds
        doAnswer(invocation -> {
            Uri handle = invocation.getArgument(0);
            CallerInfo info = new CallerInfo();
            CompletableFuture<Pair<Uri, CallerInfo>> callerInfoFuture = new CompletableFuture<>();
            callerInfoFuture.complete(new Pair<>(handle, info));
            return callerInfoFuture;
        }).when(mCallerInfoLookupHelper).startLookup(any(Uri.class));

        // Ensure we have candidate phone account handle info.
        when(mPhoneAccountRegistrar.getOutgoingPhoneAccountForScheme(any(), any())).thenReturn(
                SIM_1_HANDLE);
        when(mPhoneAccountRegistrar.getCallCapablePhoneAccounts(any(), anyBoolean(),
                any(), anyInt(), anyInt(), anyBoolean())).thenReturn(
                new ArrayList<>(Arrays.asList(SIM_1_HANDLE, SIM_2_HANDLE)));
        mCallsManager.addConnectionServiceRepositoryCache(SIM_2_HANDLE.getComponentName(),
                SIM_2_HANDLE.getUserHandle(), service);

        CompletableFuture<Call> callFuture = mCallsManager.startOutgoingCall(
                newCall.getHandle(), newCall.getTargetPhoneAccount(), new Bundle(),
                UserHandle.CURRENT, new Intent(), "com.test.stuff");

        verify(service, timeout(TEST_TIMEOUT)).createConnectionFailed(any());
        Call result = callFuture.get(TEST_TIMEOUT, TimeUnit.MILLISECONDS);
        assertNull(result);
    }

    @SmallTest
    @Test
    public void testHasEmergencyCallIncomingCallPermitted() {
        // Setup a call which is considered emergency based on its phone number.
        Call ongoingCall = addSpyCall();
        when(mComponentContextFixture.getTelephonyManager().isEmergencyNumber(any()))
                .thenReturn(true);
        ongoingCall.setHandle(Uri.fromParts("tel", "5551212", null),
                TelecomManager.PRESENTATION_ALLOWED);
        when(mPhoneAccountRegistrar.getPhoneAccountUnchecked(SELF_MANAGED_HANDLE))
                .thenReturn(SELF_MANAGED_ACCOUNT);
        when(mPhoneAccountRegistrar.getPhoneAccountUnchecked(SIM_1_HANDLE))
                .thenReturn(SIM_1_ACCOUNT);

        assertFalse(mCallsManager.isIncomingCallPermitted(SELF_MANAGED_HANDLE));
        assertFalse(mCallsManager.isIncomingCallPermitted(SIM_1_HANDLE));
    }

    @MediumTest
    @Test
    public void testManagedIncomingCallPermitted() {
        when(mPhoneAccountRegistrar.getPhoneAccountUnchecked(SIM_1_HANDLE))
                .thenReturn(SIM_1_ACCOUNT);

        // Don't care
        Call selfManagedCall = addSpyCall(SELF_MANAGED_HANDLE, CallState.ACTIVE);
        when(selfManagedCall.isSelfManaged()).thenReturn(true);
        assertTrue(mCallsManager.isIncomingCallPermitted(SIM_1_HANDLE));

        Call existingCall = addSpyCall(SIM_1_HANDLE, CallState.NEW);
        when(existingCall.isSelfManaged()).thenReturn(false);

        when(existingCall.getState()).thenReturn(CallState.RINGING);
        assertFalse(mCallsManager.isIncomingCallPermitted(SIM_1_HANDLE));

        when(existingCall.getState()).thenReturn(CallState.ON_HOLD);
        assertFalse(mCallsManager.isIncomingCallPermitted(SIM_1_HANDLE));
    }

    @MediumTest
    @Test
    public void testSelfManagedIncomingCallPermitted() {
        when(mPhoneAccountRegistrar.getPhoneAccountUnchecked(SELF_MANAGED_HANDLE))
                .thenReturn(SELF_MANAGED_ACCOUNT);

        // Don't care
        Call managedCall = addSpyCall(SIM_1_HANDLE, CallState.ACTIVE);
        when(managedCall.isSelfManaged()).thenReturn(false);
        assertTrue(mCallsManager.isIncomingCallPermitted(SELF_MANAGED_HANDLE));

        Call existingCall = addSpyCall(SELF_MANAGED_HANDLE, CallState.RINGING);
        when(existingCall.isSelfManaged()).thenReturn(true);
        assertFalse(mCallsManager.isIncomingCallPermitted(SELF_MANAGED_HANDLE));

        when(existingCall.getState()).thenReturn(CallState.ACTIVE);
        assertTrue(mCallsManager.isIncomingCallPermitted(SELF_MANAGED_HANDLE));

        // Add self managed calls up to 10
        for (int i = 0; i < 9; i++) {
            Call selfManagedCall = addSpyCall(SELF_MANAGED_HANDLE, CallState.ON_HOLD);
            when(selfManagedCall.isSelfManaged()).thenReturn(true);
        }
        assertFalse(mCallsManager.isIncomingCallPermitted(SELF_MANAGED_HANDLE));
    }

    @SmallTest
    @Test
    public void testManagedOutgoingCallPermitted() {
        when(mPhoneAccountRegistrar.getPhoneAccountUnchecked(SIM_1_HANDLE))
                .thenReturn(SIM_1_ACCOUNT);

        // Don't care
        Call selfManagedCall = addSpyCall(SELF_MANAGED_HANDLE, CallState.ACTIVE);
        when(selfManagedCall.isSelfManaged()).thenReturn(true);
        assertTrue(mCallsManager.isOutgoingCallPermitted(SIM_1_HANDLE));

        Call existingCall = addSpyCall(SIM_1_HANDLE, CallState.NEW);
        when(existingCall.isSelfManaged()).thenReturn(false);

        when(existingCall.getState()).thenReturn(CallState.CONNECTING);
        assertFalse(mCallsManager.isOutgoingCallPermitted(SIM_1_HANDLE));

        when(existingCall.getState()).thenReturn(CallState.DIALING);
        assertFalse(mCallsManager.isOutgoingCallPermitted(SIM_1_HANDLE));

        when(existingCall.getState()).thenReturn(CallState.ACTIVE);
        assertFalse(mCallsManager.isOutgoingCallPermitted(SIM_1_HANDLE));

        when(existingCall.getState()).thenReturn(CallState.ON_HOLD);
        assertFalse(mCallsManager.isOutgoingCallPermitted(SIM_1_HANDLE));
    }

    @SmallTest
    @Test
    public void testSelfManagedOutgoingCallPermitted() {
        when(mPhoneAccountRegistrar.getPhoneAccountUnchecked(SELF_MANAGED_HANDLE))
                .thenReturn(SELF_MANAGED_ACCOUNT);

        // Don't care
        Call managedCall = addSpyCall(SIM_1_HANDLE, CallState.ACTIVE);
        when(managedCall.isSelfManaged()).thenReturn(false);
        assertTrue(mCallsManager.isOutgoingCallPermitted(SELF_MANAGED_HANDLE));

        Call ongoingCall = addSpyCall(SELF_MANAGED_HANDLE, CallState.ACTIVE);
        when(ongoingCall.isSelfManaged()).thenReturn(true);
        when(mConnectionSvrFocusMgr.getCurrentFocusCall()).thenReturn(ongoingCall);

        when(ongoingCall.can(Connection.CAPABILITY_HOLD)).thenReturn(false);
        assertFalse(mCallsManager.isOutgoingCallPermitted(SELF_MANAGED_HANDLE));

        when(ongoingCall.can(Connection.CAPABILITY_HOLD)).thenReturn(true);
        assertTrue(mCallsManager.isOutgoingCallPermitted(SELF_MANAGED_HANDLE));

        Call handoverCall = addSpyCall(SELF_MANAGED_HANDLE, CallState.NEW);
        when(handoverCall.isSelfManaged()).thenReturn(true);
        when(handoverCall.getHandoverSourceCall()).thenReturn(mock(Call.class));
        assertTrue(mCallsManager.isOutgoingCallPermitted(handoverCall, SELF_MANAGED_HANDLE));

        // Add self managed calls up to 10
        for (int i = 0; i < 8; i++) {
            Call selfManagedCall = addSpyCall(SELF_MANAGED_HANDLE, CallState.ON_HOLD);
            when(selfManagedCall.isSelfManaged()).thenReturn(true);
        }
        assertFalse(mCallsManager.isOutgoingCallPermitted(SELF_MANAGED_HANDLE));
    }

    @SmallTest
    @Test
    public void testSelfManagedOutgoingCallPermittedHasEmergencyCall() {
        when(mPhoneAccountRegistrar.getPhoneAccountUnchecked(SELF_MANAGED_HANDLE))
                .thenReturn(SELF_MANAGED_ACCOUNT);

        Call emergencyCall = addSpyCall();
        when(emergencyCall.isEmergencyCall()).thenReturn(true);
        assertFalse(mCallsManager.isOutgoingCallPermitted(SELF_MANAGED_HANDLE));
    }

    @SmallTest
    @Test
    public void testMakeRoomForEmergencyCallAudioProcessingInProgress() {
        Call ongoingCall = addSpyCall(SIM_2_HANDLE, CallState.AUDIO_PROCESSING);

        Call newEmergencyCall = createCall(SIM_1_HANDLE, CallState.NEW);
        when(mComponentContextFixture.getTelephonyManager().isEmergencyNumber(any()))
                .thenReturn(true);
        newEmergencyCall.setHandle(Uri.fromParts("tel", "5551213", null),
                TelecomManager.PRESENTATION_ALLOWED);

        assertTrue(mCallsManager.makeRoomForOutgoingEmergencyCall(newEmergencyCall));
        verify(ongoingCall).disconnect(anyLong(), anyString());
    }

    @SmallTest
    @Test
    public void testMakeRoomForEmergencyCallDuringIncomingCall() {
        Call ongoingCall = addSpyCall(SIM_2_HANDLE, CallState.RINGING);

        Call newEmergencyCall = createCall(SIM_1_HANDLE, CallState.NEW);
        when(mComponentContextFixture.getTelephonyManager().isEmergencyNumber(any()))
                .thenReturn(true);
        newEmergencyCall.setHandle(Uri.fromParts("tel", "5551213", null),
                TelecomManager.PRESENTATION_ALLOWED);

        assertTrue(mCallsManager.makeRoomForOutgoingEmergencyCall(newEmergencyCall));
        verify(ongoingCall).reject(anyBoolean(), any(), any());
    }

    @SmallTest
    @Test
    public void testMakeRoomForEmergencyCallSimulatedRingingInProgress() {
        Call ongoingCall = addSpyCall(SIM_2_HANDLE, CallState.SIMULATED_RINGING);

        Call newEmergencyCall = createCall(SIM_1_HANDLE, CallState.NEW);
        when(mComponentContextFixture.getTelephonyManager().isEmergencyNumber(any()))
                .thenReturn(true);
        newEmergencyCall.setHandle(Uri.fromParts("tel", "5551213", null),
                TelecomManager.PRESENTATION_ALLOWED);

        assertTrue(mCallsManager.makeRoomForOutgoingEmergencyCall(newEmergencyCall));
        verify(ongoingCall).disconnect(anyString());
    }

    @SmallTest
    @Test
    public void testMakeRoomForEmergencyCallSimulatedRingingInProgressHasBeenActive() {
        Call ongoingCall = addSpyCall(SIM_2_HANDLE, CallState.ACTIVE);
        ongoingCall.setState(CallState.SIMULATED_RINGING, "");

        Call newEmergencyCall = createCall(SIM_1_HANDLE, CallState.NEW);
        when(mComponentContextFixture.getTelephonyManager().isEmergencyNumber(any()))
                .thenReturn(true);
        newEmergencyCall.setHandle(Uri.fromParts("tel", "5551213", null),
                TelecomManager.PRESENTATION_ALLOWED);

        assertTrue(mCallsManager.makeRoomForOutgoingEmergencyCall(newEmergencyCall));
        verify(ongoingCall).reject(anyBoolean(), any(), any());
    }

    @SmallTest
    @Test
    public void testMakeRoomForEmergencyCallDuringActiveAndRingingCallDisconnectRinging() {
        when(mPhoneAccountRegistrar.getPhoneAccountUnchecked(SIM_1_HANDLE))
                .thenReturn(SIM_1_ACCOUNT);
        Call ongoingCall = addSpyCall(SIM_1_HANDLE, CallState.ACTIVE);
        doReturn(true).when(ongoingCall).can(Connection.CAPABILITY_HOLD);
        Call ringingCall = addSpyCall(SIM_1_HANDLE, CallState.RINGING);

        Call newEmergencyCall = createCall(SIM_1_HANDLE, CallState.NEW);
        when(mComponentContextFixture.getTelephonyManager().isEmergencyNumber(any()))
                .thenReturn(true);
        newEmergencyCall.setHandle(Uri.fromParts("tel", "5551213", null),
                TelecomManager.PRESENTATION_ALLOWED);

        assertTrue(mCallsManager.makeRoomForOutgoingEmergencyCall(newEmergencyCall));
        verify(ringingCall).reject(anyBoolean(), any(), any());
    }

    /**
     * Verifies that an anomaly report is triggered when a stuck/zombie call is found and force
     * disconnected when making room for an outgoing call.
     */
    @SmallTest
    @Test
    public void testAnomalyReportedWhenMakeRoomForOutgoingCallConnecting() {
        mCallsManager.setAnomalyReporterAdapter(mAnomalyReporterAdapter);
        Call ongoingCall = addSpyCall(SIM_2_HANDLE, CallState.CONNECTING);

        Call newCall = createCall(SIM_1_HANDLE, CallState.NEW);
        when(mComponentContextFixture.getTelephonyManager().isEmergencyNumber(any()))
                .thenReturn(false);
        newCall.setHandle(TEST_ADDRESS, TelecomManager.PRESENTATION_ALLOWED);

        // Make sure enough time has passed that we'd drop the connecting call.
        when(mClockProxy.elapsedRealtime()).thenReturn(STATE_TIMEOUT + 10L);
        assertTrue(mCallsManager.makeRoomForOutgoingCall(newCall));
        verify(mAnomalyReporterAdapter).reportAnomaly(
                CallsManager.LIVE_CALL_STUCK_CONNECTING_ERROR_UUID,
                CallsManager.LIVE_CALL_STUCK_CONNECTING_ERROR_MSG);
        verify(ongoingCall).disconnect(anyLong(), anyString());
    }

    /**
     * Verifies that we won't auto-disconnect an outgoing CONNECTING call unless it has timed out.
     */
    @SmallTest
    @Test
    public void testDontDisconnectConnectingCallWhenNotTimedOut() {
        mCallsManager.setAnomalyReporterAdapter(mAnomalyReporterAdapter);
        Call ongoingCall = addSpyCall(SIM_2_HANDLE, CallState.CONNECTING);

        Call newCall = createCall(SIM_1_HANDLE, CallState.NEW);
        when(mComponentContextFixture.getTelephonyManager().isEmergencyNumber(any()))
                .thenReturn(false);
        newCall.setHandle(TEST_ADDRESS, TelecomManager.PRESENTATION_ALLOWED);

        // Make sure it has been a short time so we don't try to disconnect the call
        when(mClockProxy.elapsedRealtime()).thenReturn(STATE_TIMEOUT / 2);
        assertFalse(mCallsManager.makeRoomForOutgoingCall(newCall));
        verify(ongoingCall, never()).disconnect(anyLong(), anyString());
    }

    @SmallTest
    @Test
    public void testMakeRoomForEmergencyCallHasOutgoingCall() {
        Call outgoingCall = addSpyCall(SIM_1_HANDLE, CallState.CONNECTING);
        when(outgoingCall.isEmergencyCall()).thenReturn(false);

        Call newEmergencyCall = createSpyCall(SIM_1_HANDLE, CallState.NEW);
        when(newEmergencyCall.isEmergencyCall()).thenReturn(true);

        assertTrue(mCallsManager.makeRoomForOutgoingEmergencyCall(newEmergencyCall));
        verify(outgoingCall).disconnect(anyString());
    }

    @SmallTest
    @Test
    public void testMakeRoomForEmergencyCallHasOutgoingEmergencyCall() {
        Call outgoingCall = addSpyCall(SIM_1_HANDLE, CallState.CONNECTING);
        when(outgoingCall.isEmergencyCall()).thenReturn(true);

        Call newEmergencyCall = createSpyCall(SIM_1_HANDLE, CallState.NEW);
        when(newEmergencyCall.isEmergencyCall()).thenReturn(true);

        assertFalse(mCallsManager.makeRoomForOutgoingEmergencyCall(newEmergencyCall));
        verify(outgoingCall, never()).disconnect(anyString());
    }

    @SmallTest
    @Test
    public void testMakeRoomForEmergencyCallHasUnholdableCallAndManagedCallInHold() {
        Call unholdableCall = addSpyCall(SIM_1_HANDLE, CallState.ACTIVE);
        when(unholdableCall.can(Connection.CAPABILITY_HOLD)).thenReturn(false);

        Call managedHoldingCall = addSpyCall(SIM_1_HANDLE, CallState.ON_HOLD);
        when(managedHoldingCall.isSelfManaged()).thenReturn(false);

        Call newEmergencyCall = createSpyCall(SIM_1_HANDLE, CallState.NEW);
        when(newEmergencyCall.isEmergencyCall()).thenReturn(true);

        assertTrue(mCallsManager.makeRoomForOutgoingEmergencyCall(newEmergencyCall));
        verify(unholdableCall).disconnect(anyString());
    }

    @SmallTest
    @Test
    public void testMakeRoomForEmergencyCallHasHoldableCall() {
        Call holdableCall = addSpyCall(null, CallState.ACTIVE);
        when(holdableCall.can(Connection.CAPABILITY_HOLD)).thenReturn(true);

        Call newEmergencyCall = createSpyCall(SIM_1_HANDLE, CallState.NEW);
        when(newEmergencyCall.isEmergencyCall()).thenReturn(true);

        assertTrue(mCallsManager.makeRoomForOutgoingEmergencyCall(newEmergencyCall));
        verify(holdableCall).hold(anyString());
    }

    @SmallTest
    @Test
    public void testMakeRoomForEmergencyCallHasUnholdableCall() {
        Call unholdableCall = addSpyCall(null, CallState.ACTIVE);
        when(unholdableCall.can(Connection.CAPABILITY_HOLD)).thenReturn(false);

        Call newEmergencyCall = createSpyCall(SIM_1_HANDLE, CallState.NEW);
        when(newEmergencyCall.isEmergencyCall()).thenReturn(true);

        assertFalse(mCallsManager.makeRoomForOutgoingEmergencyCall(newEmergencyCall));
    }

    @SmallTest
    @Test
    public void testMakeRoomForOutgoingCallHasConnectingCall() {
        Call ongoingCall = addSpyCall(SIM_2_HANDLE, CallState.CONNECTING);
        Call newCall = createCall(SIM_1_HANDLE, CallState.NEW);

        when(mClockProxy.elapsedRealtime()).thenReturn(STATE_TIMEOUT + 10L);
        assertTrue(mCallsManager.makeRoomForOutgoingCall(newCall));
        verify(ongoingCall).disconnect(anyLong(), anyString());
    }

    @SmallTest
    @Test
    public void testMakeRoomForOutgoingCallForSameCall() {
        addSpyCall(SIM_2_HANDLE, CallState.CONNECTING);
        Call ongoingCall2 = addSpyCall();
        when(mClockProxy.elapsedRealtime()).thenReturn(STATE_TIMEOUT + 10L);
        assertTrue(mCallsManager.makeRoomForOutgoingCall(ongoingCall2));
    }

    /**
     * Test where a VoIP app adds another new call and has one active already; ensure we hold the
     * active call.  This assumes same connection service in the same app.
     */
    @SmallTest
    @Test
    public void testMakeRoomForOutgoingCallForSameVoipApp() {
        Call activeCall = addSpyCall(SELF_MANAGED_HANDLE, null /* connMgr */,
                CallState.ACTIVE, Connection.CAPABILITY_HOLD | Connection.CAPABILITY_SUPPORT_HOLD,
                0 /* properties */);
        Call newDialingCall = createCall(SELF_MANAGED_HANDLE, CallState.DIALING);
        newDialingCall.setConnectionProperties(Connection.CAPABILITY_HOLD
                        | Connection.CAPABILITY_SUPPORT_HOLD);
        assertTrue(mCallsManager.makeRoomForOutgoingCall(newDialingCall));
        verify(activeCall).hold(anyString());
    }

    /**
     * Test where a VoIP app adds another new call and has one active already; ensure we hold the
     * active call.  This assumes different connection services in the same app.
     */
    @SmallTest
    @Test
    public void testMakeRoomForOutgoingCallForSameVoipAppDifferentConnectionService() {
        Call activeCall = addSpyCall(SELF_MANAGED_HANDLE, null /* connMgr */,
                CallState.ACTIVE, Connection.CAPABILITY_HOLD | Connection.CAPABILITY_SUPPORT_HOLD,
                0 /* properties */);
        Call newDialingCall = createCall(SELF_MANAGED_2_HANDLE, CallState.DIALING);
        newDialingCall.setConnectionProperties(Connection.CAPABILITY_HOLD
                | Connection.CAPABILITY_SUPPORT_HOLD);
        assertTrue(mCallsManager.makeRoomForOutgoingCall(newDialingCall));
        verify(activeCall).hold(anyString());
    }

    /**
     * Test where a VoIP app adds another new call and has one active already; ensure we hold the
     * active call.  This assumes different connection services in the same app.
     */
    @SmallTest
    @Test
    public void testMakeRoomForOutgoingCallForSameNonVoipApp() {
        Call activeCall = addSpyCall(SIM_1_HANDLE, null /* connMgr */,
                CallState.ACTIVE, Connection.CAPABILITY_HOLD | Connection.CAPABILITY_SUPPORT_HOLD,
                0 /* properties */);
        Call newDialingCall = createCall(SIM_1_HANDLE, CallState.DIALING);
        newDialingCall.setConnectionProperties(Connection.CAPABILITY_HOLD
                | Connection.CAPABILITY_SUPPORT_HOLD);
        assertTrue(mCallsManager.makeRoomForOutgoingCall(newDialingCall));
        verify(activeCall, never()).hold(anyString());
    }

    @SmallTest
    @Test
    public void testMakeRoomForOutgoingCallHasOutgoingCallSelectingAccount() {
        Call outgoingCall = addSpyCall(SIM_1_HANDLE, CallState.SELECT_PHONE_ACCOUNT);
        Call newCall = createSpyCall(SIM_1_HANDLE, CallState.NEW);

        assertTrue(mCallsManager.makeRoomForOutgoingCall(newCall));
        verify(outgoingCall).disconnect(anyString());
    }

    @SmallTest
    @Test
    public void testMakeRoomForOutgoingCallHasDialingCall() {
        addSpyCall(SIM_1_HANDLE, CallState.DIALING);
        Call newCall = createSpyCall(SIM_1_HANDLE, CallState.NEW);

        assertFalse(mCallsManager.makeRoomForOutgoingCall(newCall));
    }

    @MediumTest
    @Test
    public void testMakeRoomForOutgoingCallHasHoldableCall() {
        Call holdableCall = addSpyCall(SIM_1_HANDLE, CallState.ACTIVE);
        when(holdableCall.can(Connection.CAPABILITY_HOLD)).thenReturn(true);

        Call newCall = createSpyCall(CONNECTION_MGR_1_HANDLE, CallState.NEW);

        assertTrue(mCallsManager.makeRoomForOutgoingCall(newCall));
        verify(holdableCall).hold(anyString());
    }

    @SmallTest
    @Test
    public void testMakeRoomForOutgoingCallHasUnholdableCall() {
        Call holdableCall = addSpyCall(SIM_1_HANDLE, CallState.ACTIVE);
        when(holdableCall.can(Connection.CAPABILITY_HOLD)).thenReturn(false);

        Call newCall = createSpyCall(CONNECTION_MGR_1_HANDLE, CallState.NEW);

        assertFalse(mCallsManager.makeRoomForOutgoingCall(newCall));
    }

    /**
     * Verifies that changes to a {@link PhoneAccount}'s
     * {@link PhoneAccount#CAPABILITY_VIDEO_CALLING} capability will be reflected on a call.
     * @throws Exception
     */
    @SmallTest
    @Test
    public void testPhoneAccountVideoAvailability() throws InterruptedException {
        Call ongoingCall = addSpyCall(); // adds to SIM_2_ACCT
        LinkedBlockingQueue<Integer> capabilitiesQueue = new LinkedBlockingQueue<>(1);
        ongoingCall.addListener(new Call.ListenerBase() {
            @Override
            public void onConnectionCapabilitiesChanged(Call call) {
                try {
                    capabilitiesQueue.put(call.getConnectionCapabilities());
                } catch (InterruptedException e) {
                    fail();
                }
            }
        });

        // Lets make the phone account video capable.
        PhoneAccount videoCapableAccount = new PhoneAccount.Builder(SIM_2_ACCOUNT)
                .setCapabilities(SIM_2_ACCOUNT.getCapabilities()
                        | PhoneAccount.CAPABILITY_VIDEO_CALLING)
                .build();
        mCallsManager.getPhoneAccountListener().onPhoneAccountChanged(mPhoneAccountRegistrar,
                videoCapableAccount);
        // Absorb first update; it'll be from when phone account changed initially (since we force
        // a capabilities update.
        int newCapabilities = capabilitiesQueue.poll(TEST_TIMEOUT, TimeUnit.MILLISECONDS);

        // Lets pretend the ConnectionService made it video capable as well.
        ongoingCall.setConnectionCapabilities(
                Connection.CAPABILITY_SUPPORTS_VT_LOCAL_BIDIRECTIONAL);
        newCapabilities = capabilitiesQueue.poll(TEST_TIMEOUT, TimeUnit.MILLISECONDS);
        assertTrue((newCapabilities & Connection.CAPABILITY_SUPPORTS_VT_LOCAL_BIDIRECTIONAL)
                == Connection.CAPABILITY_SUPPORTS_VT_LOCAL_BIDIRECTIONAL);
        assertTrue(ongoingCall.isVideoCallingSupportedByPhoneAccount());
    }

    /**
     * Verifies that adding and removing a call triggers external calls to have capabilities
     * recalculated.
     */
    @SmallTest
    @Test
    public void testExternalCallCapabilitiesUpdated() throws InterruptedException {
        Call externalCall = addSpyCall(SIM_2_HANDLE, null, CallState.ACTIVE,
                Connection.CAPABILITY_CAN_PULL_CALL, Connection.PROPERTY_IS_EXTERNAL_CALL);
        LinkedBlockingQueue<Integer> capabilitiesQueue = new LinkedBlockingQueue<>(1);
        externalCall.addListener(new Call.ListenerBase() {
            @Override
            public void onConnectionCapabilitiesChanged(Call call) {
                try {
                    capabilitiesQueue.put(call.getConnectionCapabilities());
                } catch (InterruptedException e) {
                    fail();
                }
            }
        });

        Call call = createSpyCall(SIM_2_HANDLE, CallState.DIALING);
        doReturn(true).when(call).isEmergencyCall();
        mCallsManager.addCall(call);
        Integer result = capabilitiesQueue.poll(TEST_TIMEOUT, TimeUnit.MILLISECONDS);
        assertNotNull(result);
        assertEquals(0, Connection.CAPABILITY_CAN_PULL_CALL & result);

        mCallsManager.removeCall(call);
        result = capabilitiesQueue.poll(TEST_TIMEOUT, TimeUnit.MILLISECONDS);
        assertNotNull(result);
        assertEquals(Connection.CAPABILITY_CAN_PULL_CALL,
                Connection.CAPABILITY_CAN_PULL_CALL & result);
    }

    /**
     * Verifies that speakers is disabled when there's no video capabilities, even if a video call
     * tried to place.
     * @throws Exception
     */
    @SmallTest
    @Test
    public void testSpeakerDisabledWhenNoVideoCapabilities() throws Exception {
        Call outgoingCall = addSpyCall(CallState.NEW);
        when(mPhoneAccountRegistrar.getPhoneAccount(
                any(PhoneAccountHandle.class), any(UserHandle.class))).thenReturn(SIM_1_ACCOUNT);
        mCallsManager.placeOutgoingCall(outgoingCall, TEST_ADDRESS, null, true,
                VideoProfile.STATE_TX_ENABLED);
        assertFalse(outgoingCall.getStartWithSpeakerphoneOn());
    }

    /**
     * Verify that a parent call will inherit the connect time of its children.
     * @throws Exception
     */
    @SmallTest
    @Test
    public void testParentInheritsChildConnectTime() throws Exception {
        Call callSim1 = createCall(SIM_1_HANDLE, null, CallState.ACTIVE);
        Call callSim2 = createCall(SIM_1_HANDLE, null, CallState.ACTIVE);
        callSim1.setConnectTimeMillis(100);

        // Pretend it is a conference made later.
        callSim2.setConnectTimeMillis(0);

        // Make the first call a child of the second (pretend conference).
        callSim1.setChildOf(callSim2);

        assertEquals(100, callSim2.getConnectTimeMillis());

        // Add another later call.
        Call callSim3 = createCall(SIM_1_HANDLE, null, CallState.ACTIVE);
        callSim3.setConnectTimeMillis(200);
        callSim3.setChildOf(callSim2);

        // Later call shouldn't impact parent.
        assertEquals(100, callSim2.getConnectTimeMillis());
    }

    /**
     * Make sure that CallsManager handles a screening result that has both
     * silence and screen-further set to true as a request to screen further.
     * @throws Exception
     */
    @SmallTest
    @Test
    public void testHandleSilenceVsBackgroundScreeningOrdering() throws Exception {
        Call screenedCall = mock(Call.class);
        Bundle extra = new Bundle();
        when(screenedCall.getIntentExtras()).thenReturn(extra);
        when(screenedCall.getTargetPhoneAccount()).thenReturn(SIM_1_HANDLE);
        String appName = "blah";
        CallFilteringResult result = new CallFilteringResult.Builder()
                .setShouldAllowCall(true)
                .setShouldReject(false)
                .setShouldSilence(true)
                .setShouldScreenViaAudio(true)
                .setShouldAddToCallLog(true)
                .setShouldShowNotification(true)
                .setCallScreeningAppName(appName)
                .build();
        mCallsManager.onCallFilteringComplete(screenedCall, result, false);

        verify(mConnectionSvrFocusMgr).requestFocus(eq(screenedCall),
                nullable(ConnectionServiceFocusManager.RequestFocusCallback.class));
        verify(screenedCall).setAudioProcessingRequestingApp(appName);
    }

    /**
     * Verify the behavior of the {@link CallsManager#areFromSameSource(Call, Call)} method.
     * @throws Exception
     */
    @SmallTest
    @Test
    public void testAreFromSameSource() throws Exception {
        Call callSim1 = createCall(SIM_1_HANDLE, null, CallState.ACTIVE);
        Call callSim2 = createCall(SIM_2_HANDLE, null, CallState.ACTIVE);
        Call callVoip1 = createCall(VOIP_1_HANDLE, null, CallState.ACTIVE);
        assertTrue(CallsManager.areFromSameSource(callSim1, callSim1));
        assertTrue(CallsManager.areFromSameSource(callSim1, callSim2));
        assertFalse(CallsManager.areFromSameSource(callSim1, callVoip1));
        assertFalse(CallsManager.areFromSameSource(callSim2, callVoip1));

        Call callSim1ConnectionMgr1 = createCall(SIM_1_HANDLE, CONNECTION_MGR_1_HANDLE,
                CallState.ACTIVE);
        Call callSim2ConnectionMgr2 = createCall(SIM_2_HANDLE, CONNECTION_MGR_2_HANDLE,
                CallState.ACTIVE);
        assertFalse(CallsManager.areFromSameSource(callSim1ConnectionMgr1, callVoip1));
        assertFalse(CallsManager.areFromSameSource(callSim2ConnectionMgr2, callVoip1));
        // Even though the connection manager differs, the underlying telephony CS is the same
        // so hold/swap will still work as expected.
        assertTrue(CallsManager.areFromSameSource(callSim1ConnectionMgr1, callSim2ConnectionMgr2));

        // Sometimes connection managers have been known to also have calls
        Call callConnectionMgr = createCall(CONNECTION_MGR_2_HANDLE, CONNECTION_MGR_2_HANDLE,
                CallState.ACTIVE);
        assertTrue(CallsManager.areFromSameSource(callSim2ConnectionMgr2, callConnectionMgr));
    }

    /**
     * This test verifies a race condition seen with the new outgoing call broadcast.
     * The scenario occurs when an incoming call is handled by an app which receives the
     * NewOutgoingCallBroadcast.  That app cancels the call by modifying the new outgoing call
     * broadcast.  Meanwhile, it places that same call again, expecting that Telecom will reuse the
     * same same.  HOWEVER, if the system delays passing of the new outgoing call broadcast back to
     * Telecom, the app will have placed a new outgoing call BEFORE telecom is aware that the call
     * was cancelled.
     * The consequence of this is that in CallsManager#startOutgoingCall, when we first get the
     * call to reuse, it will come back empty.  Meanwhile, by the time we get into the various
     * completable futures, the call WILL be in the list of calls which can be reused.  Since the
     * reusable call was not found earlier on, we end up aborting the new outgoing call.
     * @throws Exception
     */
    @SmallTest
    @Test
    public void testReuseCallConcurrency() throws Exception {
        // Ensure contact info lookup succeeds
        doAnswer(invocation -> {
            Uri handle = invocation.getArgument(0);
            CallerInfo info = new CallerInfo();
            CompletableFuture<Pair<Uri, CallerInfo>> callerInfoFuture = new CompletableFuture<>();
            callerInfoFuture.complete(new Pair<>(handle, info));
            return callerInfoFuture;
        }).when(mCallerInfoLookupHelper).startLookup(any(Uri.class));

        // Ensure we have candidate phone account handle info.
        when(mPhoneAccountRegistrar.getOutgoingPhoneAccountForScheme(any(), any())).thenReturn(
                SIM_1_HANDLE);
        when(mPhoneAccountRegistrar.getCallCapablePhoneAccounts(any(), anyBoolean(),
                any(), anyInt(), anyInt(), anyBoolean())).thenReturn(
                new ArrayList<>(Arrays.asList(SIM_1_HANDLE, SIM_2_HANDLE)));

        // Let's add an existing call which is in connecting state; this emulates the case where
        // we have an outgoing call which we have not yet disconnected as a result of the new
        // outgoing call broadcast cancelling the call.
        Call outgoingCall = addSpyCall(CallState.CONNECTING);

        final CountDownLatch latch = new CountDownLatch(1);
        // Get the handler for the main looper, which is the same one the CallsManager will use.
        // We'll post a little something to block up the handler for now.  This prevents
        // startOutgoingCall from process it's completablefutures.
        Handler handler = new Handler(Looper.getMainLooper());
        handler.post(() -> {
            try {
                latch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        // Now while the main handler is blocked up we'll start another outgoing call.
        CompletableFuture<Call> callFuture = mCallsManager.startOutgoingCall(
                outgoingCall.getHandle(), outgoingCall.getTargetPhoneAccount(), new Bundle(),
                UserHandle.CURRENT, new Intent(), "com.test.stuff");

        // And we'll add the initial outgoing call to the list of pending disconnects; this
        // emulates a scenario where the pending disconnect call came in AFTER this call began.
        mCallsManager.addToPendingCallsToDisconnect(outgoingCall);

        // And we'll unblock the handler; this will let all the startOutgoingCall futures to happen.
        latch.countDown();

        // Wait for the future to become the present.
        callFuture.join();

        // We should have gotten a call out of this; if we did not then it means the call was
        // aborted.
        assertNotNull(callFuture.get());

        // And the original call should be disconnected now.
        assertEquals(CallState.DISCONNECTED, outgoingCall.getState());
    }

    /**
     * Ensures that if we have two calls hosted by the same connection manager, but with
     * different target phone accounts, we can swap between them.
     * @throws Exception
     */
    @SmallTest
    @Test
    public void testSwapCallsWithSameConnectionMgr() throws Exception {
        // GIVEN a CallsManager with ongoing call, and this call can not be held
        Call ongoingCall = addSpyCall(SIM_1_HANDLE, CONNECTION_MGR_1_HANDLE, CallState.ACTIVE);
        doReturn(false).when(ongoingCall).can(Connection.CAPABILITY_HOLD);
        doReturn(true).when(ongoingCall).can(Connection.CAPABILITY_SUPPORT_HOLD);
        when(mConnectionSvrFocusMgr.getCurrentFocusCall()).thenReturn(ongoingCall);

        // and a held call which has the same connection manager, but a different target phone
        // account.  We have seen cases where a connection mgr adds its own calls and these can
        // be problematic for swapping.
        Call heldCall = addSpyCall(CONNECTION_MGR_1_HANDLE, CONNECTION_MGR_1_HANDLE,
                CallState.ON_HOLD);

        // WHEN unhold the held call
        mCallsManager.unholdCall(heldCall);

        // THEN the ongoing call is held
        verify(ongoingCall).hold(any());
        verifyFocusRequestAndExecuteCallback(heldCall);

        // and held call is unhold now
        verify(heldCall).unhold(any());
    }

    /**
     * Verifies we inform the InCallService on local disconnect.
     * @throws Exception
     */
    @SmallTest
    @Test
    public void testRequestDisconnect() throws Exception {
        CallsManager.CallsManagerListener listener = mock(CallsManager.CallsManagerListener.class);
        mCallsManager.addListener(listener);

        Call ongoingCall = addSpyCall(CallState.ACTIVE);
        mCallsManager.addCall(ongoingCall);

        mCallsManager.disconnectCall(ongoingCall);
        // Seems odd, but ultimately the call state is still active even though it is locally
        // disconnecting.
        verify(listener).onCallStateChanged(eq(ongoingCall), eq(CallState.ACTIVE),
                eq(CallState.ACTIVE));
    }

    /**
     * Verifies where a call diagnostic service is NOT in use that we don't try to relay to the
     * CallDiagnosticService and that we get a synchronous disconnect.
     * @throws Exception
     */
    @MediumTest
    @Test
    public void testDisconnectCallSynchronous() throws Exception {
        Call callSpy = addSpyCall();
        callSpy.setIsSimCall(true);
        when(mCallDiagnosticServiceController.isConnected()).thenReturn(false);
        mCallsManager.markCallAsDisconnected(callSpy, new DisconnectCause(DisconnectCause.ERROR));

        verify(mCallDiagnosticServiceController, never()).onCallDisconnected(any(Call.class),
                any(DisconnectCause.class));
        verify(callSpy).setDisconnectCause(any(DisconnectCause.class));
    }

    @MediumTest
    @Test
    public void testDisconnectCallAsynchronous() throws Exception {
        Call callSpy = addSpyCall();
        callSpy.setIsSimCall(true);
        when(mCallDiagnosticServiceController.isConnected()).thenReturn(true);
        when(mCallDiagnosticServiceController.onCallDisconnected(any(Call.class),
                any(DisconnectCause.class))).thenReturn(true);
        mCallsManager.markCallAsDisconnected(callSpy, new DisconnectCause(DisconnectCause.ERROR));

        verify(mCallDiagnosticServiceController).onCallDisconnected(any(Call.class),
                any(DisconnectCause.class));
        verify(callSpy, never()).setDisconnectCause(any(DisconnectCause.class));
    }

    @SmallTest
    @Test
    public void testCallStreamingStateChanged() throws Exception {
        Call call = createCall(SIM_1_HANDLE, CallState.NEW);
        call.setIsTransactionalCall(true);
        CountDownLatch streamingStarted = new CountDownLatch(1);
        CountDownLatch streamingStopped = new CountDownLatch(1);
        Call.Listener l = new Call.ListenerBase() {
            @Override
            public void onCallStreamingStateChanged(Call call, boolean isStreaming) {
                if (isStreaming) {
                    streamingStarted.countDown();
                } else {
                    streamingStopped.countDown();
                }
            }
        };
        call.addListener(l);

        // Start call streaming
        call.startStreaming();
        assertTrue(streamingStarted.await(TEST_TIMEOUT, TimeUnit.MILLISECONDS));

        // Stop call streaming
        call.stopStreaming();
        assertTrue(streamingStopped.await(TEST_TIMEOUT, TimeUnit.MILLISECONDS));
    }

    /**
     * Verifies that if call state goes from DIALING to DISCONNECTED, and a call diagnostic service
     * IS in use, it would call onCallDisconnected of the CallDiagnosticService
     * @throws Exception
     */
    @MediumTest
    @Test
    public void testDisconnectDialingCall() throws Exception {
        Call callSpy = addSpyCall(CallState.DIALING);
        callSpy.setIsSimCall(true);
        when(mCallDiagnosticServiceController.isConnected()).thenReturn(true);
        when(mCallDiagnosticServiceController.onCallDisconnected(any(Call.class),
                any(DisconnectCause.class))).thenReturn(true);
        mCallsManager.markCallAsDisconnected(callSpy, new DisconnectCause(DisconnectCause.ERROR));

        verify(mCallDiagnosticServiceController).onCallDisconnected(any(Call.class),
                any(DisconnectCause.class));
        verify(callSpy, never()).setDisconnectCause(any(DisconnectCause.class));
    }

    @Test
    public void testIsInSelfManagedCallOnlyManaged() {
        Call managedCall = createCall(SIM_1_HANDLE, CallState.ACTIVE);
        managedCall.setIsSelfManaged(false);
        mCallsManager.addCall(managedCall);

        // Certainly nothing from the self managed handle.
        assertFalse(mCallsManager.isInSelfManagedCall(
                SELF_MANAGED_HANDLE.getComponentName().getPackageName(),
                SELF_MANAGED_HANDLE.getUserHandle()));
        // And nothing in a random other package.
        assertFalse(mCallsManager.isInSelfManagedCall(
                "com.foo",
                SELF_MANAGED_HANDLE.getUserHandle()));
        // And this method is only checking self managed not managed.
        assertFalse(mCallsManager.isInSelfManagedCall(
                SIM_1_HANDLE.getComponentName().getPackageName(),
                SELF_MANAGED_HANDLE.getUserHandle()));
    }

    /**
     * Emulate the case where a new incoming call is created but the connection fails for a known
     * reason before being added to CallsManager. In this case, the listeners should be notified
     * properly.
     */
    @Test
    public void testIncomingCallCreatedButNotAddedNotifyListener() {
        //The call is created and a listener is added:
        Call incomingCall = createCall(SIM_2_HANDLE, null, CallState.NEW);
        CallsManager.CallsManagerListener listener = mock(CallsManager.CallsManagerListener.class);
        mCallsManager.addListener(listener);

        //The connection fails before being added to CallsManager for a known reason:
        incomingCall.handleCreateConnectionFailure(new DisconnectCause(DisconnectCause.CANCELED));

        //Ensure the listener is notified properly:
        verify(listener).onCreateConnectionFailed(incomingCall);
    }

    /**
     * Emulate the case where a new incoming call is created but the connection fails for a known
     * reason after being added to CallsManager. Since the call was added to CallsManager, the
     * listeners should not be notified via onCreateConnectionFailed().
     */
    @Test
    public void testIncomingCallCreatedAndAddedDoNotNotifyListener() {
        //The call is created and a listener is added:
        Call incomingCall = createCall(SIM_2_HANDLE, null, CallState.NEW);
        CallsManager.CallsManagerListener listener = mock(CallsManager.CallsManagerListener.class);
        mCallsManager.addListener(listener);

        //The call is added to CallsManager:
        mCallsManager.addCall(incomingCall);

        //The connection fails after being added to CallsManager for a known reason:
        incomingCall.handleCreateConnectionFailure(new DisconnectCause(DisconnectCause.CANCELED));

        //Since the call was added to CallsManager, onCreateConnectionFailed shouldn't be invoked:
        verify(listener, never()).onCreateConnectionFailed(incomingCall);
    }

    /**
     * Emulate the case where a new outgoing call is created but is aborted before being added to
     * CallsManager since there are no available phone accounts. In this case, the listeners
     * should be notified properly.
     */
    @Test
    public void testAbortOutgoingCallNoPhoneAccountsNotifyListeners() throws Exception {
        // Setup a new outgoing call and add a listener
        Call newCall = addSpyCall(CallState.NEW);
        CallsManager.CallsManagerListener listener = mock(CallsManager.CallsManagerListener.class);
        mCallsManager.addListener(listener);

        // Ensure contact info lookup succeeds but do not set the phone account info
        doAnswer(invocation -> {
            Uri handle = invocation.getArgument(0);
            CallerInfo info = new CallerInfo();
            CompletableFuture<Pair<Uri, CallerInfo>> callerInfoFuture = new CompletableFuture<>();
            callerInfoFuture.complete(new Pair<>(handle, info));
            return callerInfoFuture;
        }).when(mCallerInfoLookupHelper).startLookup(any(Uri.class));

        // Start the outgoing call
        CompletableFuture<Call> callFuture = mCallsManager.startOutgoingCall(
                newCall.getHandle(), newCall.getTargetPhoneAccount(), new Bundle(),
                UserHandle.CURRENT, new Intent(), "com.test.stuff");
        Call result = callFuture.get(TEST_TIMEOUT, TimeUnit.MILLISECONDS);

        //Ensure the listener is notified properly:
        verify(listener).onCreateConnectionFailed(any());
        assertNull(result);
    }

    @Test
    public void testIsInSelfManagedCallOnlySelfManaged() {
        Call selfManagedCall = createCall(SELF_MANAGED_HANDLE, CallState.ACTIVE);
        selfManagedCall.setIsSelfManaged(true);
        mCallsManager.addCall(selfManagedCall);

        assertTrue(mCallsManager.isInSelfManagedCall(
                SELF_MANAGED_HANDLE.getComponentName().getPackageName(),
                SELF_MANAGED_HANDLE.getUserHandle()));
        assertFalse(mCallsManager.isInSelfManagedCall(
                "com.foo",
                SELF_MANAGED_HANDLE.getUserHandle()));
        assertFalse(mCallsManager.isInSelfManagedCall(
                SIM_1_HANDLE.getComponentName().getPackageName(),
                SELF_MANAGED_HANDLE.getUserHandle()));

        Call managedCall = createCall(SIM_1_HANDLE, CallState.ACTIVE);
        managedCall.setIsSelfManaged(false);
        mCallsManager.addCall(managedCall);

        // Still not including managed
        assertFalse(mCallsManager.isInSelfManagedCall(
                SIM_1_HANDLE.getComponentName().getPackageName(),
                SELF_MANAGED_HANDLE.getUserHandle()));

        // Also shouldn't be something in another user's version of the same package.
        assertFalse(mCallsManager.isInSelfManagedCall(
                SELF_MANAGED_HANDLE.getComponentName().getPackageName(),
                new UserHandle(90210)));
    }

    /**
     * Verifies that if a {@link android.telecom.CallScreeningService} app can properly request
     * notification show for rejected calls.
     */
    @SmallTest
    @Test
    public void testCallScreeningServiceRequestShowNotification() {
        Call callSpy = addSpyCall(CallState.NEW);
        CallFilteringResult result = new CallFilteringResult.Builder()
                .setShouldAllowCall(false)
                .setShouldReject(true)
                .setCallScreeningComponentName("com.foo/.Blah")
                .setCallScreeningAppName("Blah")
                .setShouldAddToCallLog(true)
                .setShouldShowNotification(true).build();

        mCallsManager.onCallFilteringComplete(callSpy, result, false /* timeout */);
        verify(mMissedCallNotifier).showMissedCallNotification(
                any(MissedCallNotifier.CallInfo.class));
    }

    @Test
    public void testSetStateOnlyCalledOnce() {
        // GIVEN a new self-managed call
        Call newCall = addSpyCall();
        doReturn(true).when(newCall).isSelfManaged();
        newCall.setState(CallState.DISCONNECTED, "");

        // WHEN ActionSetCallState is given a disconnect call
        assertEquals(CallState.DISCONNECTED, newCall.getState());
        // attempt to set the call active
        mCallsManager.createActionSetCallStateAndPerformAction(newCall, CallState.ACTIVE, "");

        // THEN assert remains disconnected
        assertEquals(CallState.DISCONNECTED, newCall.getState());
    }

    @SmallTest
    @Test
    public void testCrossUserCallRedirectionEndEarlyForIncapablePhoneAccount() {
        when(mPhoneAccountRegistrar.getPhoneAccountUnchecked(eq(SIM_1_HANDLE_SECONDARY)))
                .thenReturn(SIM_1_ACCOUNT);
        mCallsManager.onUserSwitch(UserHandle.SYSTEM);

        Call callSpy = addSpyCall(CallState.NEW);
        mCallsManager.onCallRedirectionComplete(callSpy, TEST_ADDRESS, SIM_1_HANDLE_SECONDARY,
                new GatewayInfo("foo", TEST_ADDRESS2, TEST_ADDRESS), true /* speakerphoneOn */,
                VideoProfile.STATE_AUDIO_ONLY, false /* shouldCancelCall */, "" /* uiAction */);

        ArgumentCaptor<String> argumentCaptor = ArgumentCaptor.forClass(String.class);
        verify(callSpy).disconnect(argumentCaptor.capture());
        assertTrue(argumentCaptor.getValue().contains("Unavailable phoneAccountHandle"));
    }

    /**
     * Verifies that target phone account is set in startOutgoingCall. The multi-user functionality
     * is dependent on the call's phone account handle being present so this test ensures that
     * existing outgoing call flow does not break from future updates.
     * @throws Exception
     */
    @Test
    public void testStartOutgoingCall_TargetPhoneAccountSet() throws Exception {
        // Ensure contact info lookup succeeds
        doAnswer(invocation -> {
            Uri handle = invocation.getArgument(0);
            CallerInfo info = new CallerInfo();
            CompletableFuture<Pair<Uri, CallerInfo>> callerInfoFuture = new CompletableFuture<>();
            callerInfoFuture.complete(new Pair<>(handle, info));
            return callerInfoFuture;
        }).when(mCallerInfoLookupHelper).startLookup(any(Uri.class));

        // Ensure we have candidate phone account handle info.
        when(mPhoneAccountRegistrar.getOutgoingPhoneAccountForScheme(any(), any())).thenReturn(
                SIM_1_HANDLE);
        when(mPhoneAccountRegistrar.getCallCapablePhoneAccounts(any(), anyBoolean(),
                any(), anyInt(), anyInt(), anyBoolean())).thenReturn(
                new ArrayList<>(Arrays.asList(SIM_1_HANDLE, SIM_2_HANDLE)));

        // start an outgoing call
        CompletableFuture<Call> callFuture = mCallsManager.startOutgoingCall(
                TEST_ADDRESS, SIM_2_HANDLE, new Bundle(),
                UserHandle.CURRENT, new Intent(), "com.test.stuff");
        Call outgoingCall = callFuture.get();
        // assert call was created
        assertNotNull(outgoingCall);
        // assert target phone account was set
        assertNotNull(outgoingCall.getTargetPhoneAccount());
    }

    /**
     * Verifies that target phone account is set before call filtering occurs.
     * @throws Exception
     */
    @SmallTest
    @Test
    public void testOnSuccessfulIncomingCall_TargetPhoneAccountSet() throws Exception {
        Call incomingCall = addSpyCall(CallState.NEW);
        doReturn(false).when(incomingCall).can(Connection.CAPABILITY_HOLD);
        doReturn(false).when(incomingCall).can(Connection.CAPABILITY_SUPPORT_HOLD);
        doReturn(true).when(incomingCall).isSelfManaged();
        doReturn(true).when(incomingCall).setState(anyInt(), any());
        // assert phone account is present before onSuccessfulIncomingCall is called
        assertNotNull(incomingCall.getTargetPhoneAccount());
    }

    /**
     * Verifies that outgoing call's post call package name is set during
     * onSuccessfulOutgoingCall.
     * @throws Exception
     */
    @SmallTest
    @Test
    public void testPostCallPackageNameSetOnSuccessfulOutgoingCall() throws Exception {
        Call outgoingCall = addSpyCall(CallState.NEW);
        when(mCallsManager.getRoleManagerAdapter().getDefaultCallScreeningApp(
                outgoingCall.getAssociatedUser()))
                .thenReturn(DEFAULT_CALL_SCREENING_APP);
        assertNull(outgoingCall.getPostCallPackageName());
        mCallsManager.onSuccessfulOutgoingCall(outgoingCall, CallState.CONNECTING);
        assertEquals(DEFAULT_CALL_SCREENING_APP, outgoingCall.getPostCallPackageName());
    }

    @SmallTest
    @Test
    public void testRejectIncomingCallOnPAHInactive_SecondaryUser() throws Exception {
        ConnectionServiceWrapper service = mock(ConnectionServiceWrapper.class);
        doReturn(WORK_HANDLE.getComponentName()).when(service).getComponentName();
        mCallsManager.addConnectionServiceRepositoryCache(WORK_HANDLE.getComponentName(),
                WORK_HANDLE.getUserHandle(), service);

        UserManager um = mContext.getSystemService(UserManager.class);
        UserHandle newUser = new UserHandle(11);
        when(mCallsManager.getCurrentUserHandle()).thenReturn(newUser);
        when(um.isUserAdmin(eq(newUser.getIdentifier()))).thenReturn(false);
        when(um.isQuietModeEnabled(eq(WORK_HANDLE.getUserHandle()))).thenReturn(false);
        when(mPhoneAccountRegistrar.getPhoneAccountUnchecked(eq(WORK_HANDLE)))
                .thenReturn(WORK_ACCOUNT);
        Call newCall = mCallsManager.processIncomingCallIntent(
                WORK_HANDLE, new Bundle(), false);

        verify(service, timeout(TEST_TIMEOUT)).createConnectionFailed(any());
        assertFalse(newCall.isInECBM());
        assertEquals(USER_MISSED_NOT_RUNNING, newCall.getMissedReason());
    }

    @SmallTest
    @Test
    public void testRejectIncomingCallOnPAHInactive_ProfilePaused() throws Exception {
        ConnectionServiceWrapper service = mock(ConnectionServiceWrapper.class);
        doReturn(SIM_2_HANDLE.getComponentName()).when(service).getComponentName();
        mCallsManager.addConnectionServiceRepositoryCache(SIM_2_HANDLE.getComponentName(),
                SIM_2_HANDLE.getUserHandle(), service);

        UserManager um = mContext.getSystemService(UserManager.class);
        when(um.isQuietModeEnabled(eq(SIM_2_HANDLE.getUserHandle()))).thenReturn(true);
        Call newCall = mCallsManager.processIncomingCallIntent(
                SIM_2_HANDLE, new Bundle(), false);

        verify(service, timeout(TEST_TIMEOUT)).createConnectionFailed(any());
        assertFalse(newCall.isInECBM());
        assertEquals(USER_MISSED_NOT_RUNNING, newCall.getMissedReason());
    }

    @SmallTest
    @Test
    public void testAcceptIncomingCallOnPAHInactiveAndECBMActive() throws Exception {
        ConnectionServiceWrapper service = mock(ConnectionServiceWrapper.class);
        doReturn(SIM_2_HANDLE.getComponentName()).when(service).getComponentName();
        mCallsManager.addConnectionServiceRepositoryCache(SIM_2_HANDLE.getComponentName(),
                SIM_2_HANDLE.getUserHandle(), service);

        when(mEmergencyCallHelper.isLastOutgoingEmergencyCallPAH(eq(SIM_2_HANDLE)))
                .thenReturn(true);
        UserManager um = mContext.getSystemService(UserManager.class);
        when(um.isQuietModeEnabled(eq(SIM_2_HANDLE.getUserHandle()))).thenReturn(true);
        Call newCall = mCallsManager.processIncomingCallIntent(
                SIM_2_HANDLE, new Bundle(), false);

        assertTrue(newCall.isInECBM());
        verify(service, timeout(TEST_TIMEOUT).times(0)).createConnectionFailed(any());
    }

    @SmallTest
    @Test
    public void testAcceptIncomingCallOnPAHInactiveAndECBMActive_SecondaryUser() throws Exception {
        ConnectionServiceWrapper service = mock(ConnectionServiceWrapper.class);
        doReturn(WORK_HANDLE.getComponentName()).when(service).getComponentName();
        mCallsManager.addConnectionServiceRepositoryCache(SIM_2_HANDLE.getComponentName(),
                WORK_HANDLE.getUserHandle(), service);

        when(mEmergencyCallHelper.isLastOutgoingEmergencyCallPAH(eq(WORK_HANDLE)))
                .thenReturn(true);
        UserManager um = mContext.getSystemService(UserManager.class);
        UserHandle newUser = new UserHandle(11);
        when(mCallsManager.getCurrentUserHandle()).thenReturn(newUser);
        when(um.isUserAdmin(eq(newUser.getIdentifier()))).thenReturn(false);
        when(um.isQuietModeEnabled(eq(WORK_HANDLE.getUserHandle()))).thenReturn(false);
        when(mPhoneAccountRegistrar.getPhoneAccountUnchecked(eq(WORK_HANDLE)))
                .thenReturn(WORK_ACCOUNT);
        Call newCall = mCallsManager.processIncomingCallIntent(
                WORK_HANDLE, new Bundle(), false);

        assertTrue(newCall.isInECBM());
        verify(service, timeout(TEST_TIMEOUT).times(0)).createConnectionFailed(any());
    }

    @SmallTest
    @Test
    public void testAcceptIncomingEmergencyCallOnPAHInactive() throws Exception {
        ConnectionServiceWrapper service = mock(ConnectionServiceWrapper.class);
        doReturn(SIM_2_HANDLE.getComponentName()).when(service).getComponentName();
        mCallsManager.addConnectionServiceRepositoryCache(SIM_2_HANDLE.getComponentName(),
                SIM_2_HANDLE.getUserHandle(), service);

        Bundle extras = new Bundle();
        extras.putParcelable(TelecomManager.EXTRA_INCOMING_CALL_ADDRESS, TEST_ADDRESS);
        TelephonyManager tm = mContext.getSystemService(TelephonyManager.class);
        UserManager um = mContext.getSystemService(UserManager.class);
        when(um.isQuietModeEnabled(eq(SIM_2_HANDLE.getUserHandle()))).thenReturn(true);
        when(tm.isEmergencyNumber(any(String.class))).thenReturn(true);
        Call newCall = mCallsManager.processIncomingCallIntent(
                SIM_2_HANDLE, extras, false);

        assertFalse(newCall.isInECBM());
        assertTrue(newCall.isEmergencyCall());
        verify(service, timeout(TEST_TIMEOUT).times(0)).createConnectionFailed(any());
    }

    public class LatchedOutcomeReceiver implements OutcomeReceiver<Boolean,
            CallException> {
        CountDownLatch mCountDownLatch;
        Boolean mIsOnResultExpected;

        public LatchedOutcomeReceiver(CountDownLatch latch, boolean isOnResultExpected){
            mCountDownLatch = latch;
            mIsOnResultExpected = isOnResultExpected;
        }

        @Override
        public void onResult(Boolean result) {
            if(mIsOnResultExpected) {
                mCountDownLatch.countDown();
            }
        }

        @Override
        public void onError(CallException error) {
            OutcomeReceiver.super.onError(error);
            if(!mIsOnResultExpected){
                mCountDownLatch.countDown();
            }
        }
    }

    @SmallTest
    @Test
    public void testCanHold() {
        Call newCall = addSpyCall();
        when(newCall.isTransactionalCall()).thenReturn(true);
        when(newCall.can(Connection.CAPABILITY_SUPPORT_HOLD)).thenReturn(false);
        assertFalse(mCallsManager.canHold(newCall));
        when(newCall.can(Connection.CAPABILITY_SUPPORT_HOLD)).thenReturn(true);
        assertTrue(mCallsManager.canHold(newCall));
    }

    @MediumTest
    @Test
    public void testOnFailedOutgoingCallRemovesCallImmediately() {
        Call call = addSpyCall();
        when(call.isDisconnectHandledViaFuture()).thenReturn(false);
        CompletableFuture future = CompletableFuture.completedFuture(true);
        when(mInCallController.getBindingFuture()).thenReturn(future);

        mCallsManager.onFailedOutgoingCall(call, new DisconnectCause(DisconnectCause.OTHER));

        future.join();
        waitForHandlerAction(new Handler(Looper.getMainLooper()), TEST_TIMEOUT);

        assertFalse(mCallsManager.getCalls().contains(call));
    }

    @MediumTest
    @Test
    public void testHoldTransactional() throws Exception {
        CountDownLatch latch = new CountDownLatch(1);
        Call newCall = addSpyCall();

        // case 1: no active call, no need to put the call on hold
        when(mConnectionSvrFocusMgr.getCurrentFocusCall()).thenReturn(null);
        mCallsManager.transactionHoldPotentialActiveCallForNewCall(newCall,
                new LatchedOutcomeReceiver(latch, true));
        waitForCountDownLatch(latch);

        // case 2: active call == new call, no need to put the call on hold
        latch = new CountDownLatch(1);
        when(mConnectionSvrFocusMgr.getCurrentFocusCall()).thenReturn(newCall);
        mCallsManager.transactionHoldPotentialActiveCallForNewCall(newCall,
                new LatchedOutcomeReceiver(latch, true));
        waitForCountDownLatch(latch);

        // case 3: cannot hold current active call early check
        Call cannotHoldCall = addSpyCall(SIM_1_HANDLE, null,
                CallState.ACTIVE, 0, 0);
        latch = new CountDownLatch(1);
        when(mConnectionSvrFocusMgr.getCurrentFocusCall()).thenReturn(cannotHoldCall);
        mCallsManager.transactionHoldPotentialActiveCallForNewCall(newCall,
                new LatchedOutcomeReceiver(latch, false));
        waitForCountDownLatch(latch);

        // case 4: activeCall != newCall && canHold(activeCall)
        Call canHoldCall = addSpyCall(SIM_1_HANDLE, null,
                CallState.ACTIVE, Connection.CAPABILITY_HOLD, 0);
        latch = new CountDownLatch(1);
        when(mConnectionSvrFocusMgr.getCurrentFocusCall()).thenReturn(canHoldCall);
        mCallsManager.transactionHoldPotentialActiveCallForNewCall(newCall,
                new LatchedOutcomeReceiver(latch, true));
        waitForCountDownLatch(latch);
    }

    @SmallTest
    @Test
    public void testGetNumCallsWithState_MultiUser() throws Exception {
        when(mContext.checkCallingOrSelfPermission(Manifest.permission.INTERACT_ACROSS_USERS))
                .thenReturn(PackageManager.PERMISSION_GRANTED);
        // Add call under secondary user
        Call call = addSpyCall(SIM_1_HANDLE_SECONDARY, CallState.ACTIVE);
        when(call.getPhoneAccountFromHandle()).thenReturn(SIM_1_ACCOUNT_SECONDARY);
        // Verify that call is visible to primary user
        assertEquals(mCallsManager.getNumCallsWithState(0, null,
                UserHandle.CURRENT_OR_SELF, true,
                null, CallState.ACTIVE), 1);
        // Verify that call is not visible to primary user
        // when a different phone account handle is specified.
        assertEquals(mCallsManager.getNumCallsWithState(0, null,
                UserHandle.CURRENT_OR_SELF, true,
                SIM_1_HANDLE, CallState.ACTIVE), 0);
        // Deny INTERACT_ACROSS_USERS permission and verify that call is not visible to primary user
        assertEquals(mCallsManager.getNumCallsWithState(0, null,
                UserHandle.CURRENT_OR_SELF, false,
                null, CallState.ACTIVE), 0);
    }

    public void waitForCountDownLatch(CountDownLatch latch) throws InterruptedException {
            boolean success = latch.await(5000, TimeUnit.MILLISECONDS);
            if (!success) {
                fail("assertOnResultWasReceived success failed");
            }
    }

    /**
     * When queryCurrentLocation is called, check whether the result is received through the
     * ResultReceiver.
     * @throws Exception if {@link CompletableFuture#get()} fails.
     */
    @Test
    public void testQueryCurrentLocationCheckOnReceiveResult() throws Exception {
        ConnectionServiceWrapper service = new ConnectionServiceWrapper(
                new ComponentName(mContext.getPackageName(),
                        mContext.getPackageName().getClass().getName()),
                null, mPhoneAccountRegistrar, mCallsManager, mContext, mLock, null);

        CompletableFuture<String> resultFuture = new CompletableFuture<>();
        try {
            service.queryCurrentLocation(500L, "Test_provider",
                    new ResultReceiver(new Handler(Looper.getMainLooper())) {
                        @Override
                        protected void onReceiveResult(int resultCode, Bundle result) {
                            super.onReceiveResult(resultCode, result);
                            resultFuture.complete("onReceiveResult");
                        }
                    });
        } catch (Exception e) {
            resultFuture.complete("Exception : " + e);
        }

        String result = resultFuture.get(1000L, TimeUnit.MILLISECONDS);
        assertTrue(result.contains("onReceiveResult"));
    }

    @SmallTest
    @Test
    public void testOnFailedOutgoingCallUnholdsCallAfterLocallyDisconnect() {
        Call existingCall = addSpyCall();
        when(existingCall.getState()).thenReturn(CallState.ON_HOLD);

        Call call = addSpyCall();
        when(call.isDisconnectHandledViaFuture()).thenReturn(false);
        when(call.isDisconnectingChildCall()).thenReturn(false);
        CompletableFuture future = CompletableFuture.completedFuture(true);
        when(mInCallController.getBindingFuture()).thenReturn(future);

        mCallsManager.disconnectCall(call);
        mCallsManager.onFailedOutgoingCall(call, new DisconnectCause(DisconnectCause.OTHER));

        future.join();
        waitForHandlerAction(new Handler(Looper.getMainLooper()), TEST_TIMEOUT);

        verify(existingCall).unhold();
    }

    @MediumTest
    @Test
    public void testOnFailedOutgoingCallUnholdsCallIfNoHoldButton() {
        Call existingCall = addSpyCall();
        when(existingCall.can(Connection.CAPABILITY_SUPPORT_HOLD)).thenReturn(false);
        when(existingCall.getState()).thenReturn(CallState.ON_HOLD);

        Call call = addSpyCall();
        when(call.isDisconnectHandledViaFuture()).thenReturn(false);
        CompletableFuture future = CompletableFuture.completedFuture(true);
        when(mInCallController.getBindingFuture()).thenReturn(future);

        mCallsManager.disconnectCall(call);
        mCallsManager.onFailedOutgoingCall(call, new DisconnectCause(DisconnectCause.OTHER));

        future.join();
        waitForHandlerAction(new Handler(Looper.getMainLooper()), TEST_TIMEOUT);

        verify(existingCall).unhold();
    }

    @MediumTest
    @Test
    public void testOnCallFilteringCompleteRemovesUnwantedCallComposerAttachments() {
        Call call = addSpyCall(CallState.NEW);
        Bundle extras = mock(Bundle.class);
        when(call.getIntentExtras()).thenReturn(extras);

        final int attachmentDisabledMask = ~0
                ^ CallScreeningService.CallResponse.CALL_COMPOSER_ATTACHMENT_LOCATION
                ^ CallScreeningService.CallResponse.CALL_COMPOSER_ATTACHMENT_SUBJECT
                ^ CallScreeningService.CallResponse.CALL_COMPOSER_ATTACHMENT_PRIORITY;
        CallScreeningService.ParcelableCallResponse response =
                mock(CallScreeningService.ParcelableCallResponse.class);
        when(response.getCallComposerAttachmentsToShow()).thenReturn(attachmentDisabledMask);

        CallFilteringResult result = new CallFilteringResult.Builder()
                .setCallScreeningResponse(response, true)
                .build();

        mCallsManager.onCallFilteringComplete(call, result, false);

        verify(extras).remove(TelecomManager.EXTRA_LOCATION);
        verify(extras).remove(TelecomManager.EXTRA_CALL_SUBJECT);
        verify(extras).remove(TelecomManager.EXTRA_PRIORITY);
    }

    @SmallTest
    @Test
    public void testOnFailedIncomingCall() {
        Call call = createSpyCall(SIM_1_HANDLE, CallState.NEW);

        mCallsManager.onFailedIncomingCall(call);

        assertEquals(CallState.DISCONNECTED, call.getState());
        verify(call).removeListener(mCallsManager);
    }

    @SmallTest
    @Test
    public void testOnSuccessfulUnknownCall() {
        Call call = createSpyCall(SIM_1_HANDLE, CallState.NEW);

        final int newState = CallState.ACTIVE;
        mCallsManager.onSuccessfulUnknownCall(call, newState);

        assertEquals(newState, call.getState());
        assertTrue(mCallsManager.getCalls().contains(call));
    }

    @SmallTest
    @Test
    public void testOnFailedUnknownCall() {
        Call call = createSpyCall(SIM_1_HANDLE, CallState.NEW);

        mCallsManager.onFailedUnknownCall(call);

        assertEquals(CallState.DISCONNECTED, call.getState());
        verify(call).removeListener(mCallsManager);
    }

    @SmallTest
    @Test
    public void testOnRingbackRequested() {
        Call call = mock(Call.class);
        final boolean ringback = true;

        CallsManager.CallsManagerListener listener = mock(CallsManager.CallsManagerListener.class);
        mCallsManager.addListener(listener);

        mCallsManager.onRingbackRequested(call, ringback);

        verify(listener).onRingbackRequested(call, ringback);
    }

    @MediumTest
    @Test
    public void testSetCallDialingAndDontIncreaseVolume() {
        // Start with a non zero volume.
        mComponentContextFixture.getAudioManager().setStreamVolume(AudioManager.STREAM_VOICE_CALL,
                4, 0 /* flags */);

        Call call = mock(Call.class);
        mCallsManager.markCallAsDialing(call);

        // We set the volume to non-zero above, so expect 1
        verify(mComponentContextFixture.getAudioManager(), times(1)).setStreamVolume(
                eq(AudioManager.STREAM_VOICE_CALL), anyInt(), anyInt());
    }
    @MediumTest
    @Test
    public void testSetCallDialingAndIncreaseVolume() {
        // Start with a zero volume stream.
        mComponentContextFixture.getAudioManager().setStreamVolume(AudioManager.STREAM_VOICE_CALL,
                0, 0 /* flags */);

        Call call = mock(Call.class);
        mCallsManager.markCallAsDialing(call);

        // We set the volume to zero above, so expect 2
        verify(mComponentContextFixture.getAudioManager(), times(2)).setStreamVolume(
                eq(AudioManager.STREAM_VOICE_CALL), anyInt(), anyInt());
    }

    @MediumTest
    @Test
    public void testSetCallActiveAndDontIncreaseVolume() {
        // Start with a non-zero volume.
        mComponentContextFixture.getAudioManager().setStreamVolume(AudioManager.STREAM_VOICE_CALL,
                4, 0 /* flags */);

        Call call = mock(Call.class);
        mCallsManager.markCallAsActive(call);

        // We set the volume to non-zero above, so expect 1 only.
        verify(mComponentContextFixture.getAudioManager(), times(1)).setStreamVolume(
                eq(AudioManager.STREAM_VOICE_CALL), anyInt(), anyInt());
    }

    @MediumTest
    @Test
    public void testHandoverToIsAccepted() {
        Call sourceCall = addSpyCall(CONNECTION_MGR_1_HANDLE, CallState.NEW);
        Call call = addSpyCall(CONNECTION_MGR_1_HANDLE, CallState.NEW);
        when(call.getHandoverSourceCall()).thenReturn(sourceCall);
        when(call.getHandoverState()).thenReturn(HandoverState.HANDOVER_TO_STARTED);

        mCallsManager.createActionSetCallStateAndPerformAction(call, CallState.ACTIVE, "");

        verify(call).setHandoverState(HandoverState.HANDOVER_ACCEPTED);
        verify(call).onHandoverComplete();
        verify(sourceCall).setHandoverState(HandoverState.HANDOVER_ACCEPTED);
        verify(sourceCall).onHandoverComplete();
        verify(sourceCall).disconnect();
    }

    @MediumTest
    @Test
    public void testSelfManagedHandoverToIsAccepted() {
        Call sourceCall = addSpyCall(CONNECTION_MGR_1_HANDLE, CallState.NEW);
        Call call = addSpyCall(SELF_MANAGED_HANDLE, CallState.NEW);
        when(call.getHandoverSourceCall()).thenReturn(sourceCall);
        when(call.getHandoverState()).thenReturn(HandoverState.HANDOVER_TO_STARTED);
        when(call.isSelfManaged()).thenReturn(true);
        Call otherCall = addSpyCall(CONNECTION_MGR_1_HANDLE, CallState.ON_HOLD);

        mCallsManager.createActionSetCallStateAndPerformAction(call, CallState.ACTIVE, "");

        verify(call).setHandoverState(HandoverState.HANDOVER_ACCEPTED);
        verify(call).onHandoverComplete();
        verify(sourceCall).setHandoverState(HandoverState.HANDOVER_ACCEPTED);
        verify(sourceCall).onHandoverComplete();
        verify(sourceCall, times(2)).disconnect();
        verify(otherCall).disconnect();
    }

    @SmallTest
    @Test
    public void testHandoverToIsRejected() {
        Call sourceCall = addSpyCall(CONNECTION_MGR_1_HANDLE, CallState.NEW);
        Call call = addSpyCall(CONNECTION_MGR_1_HANDLE, CallState.NEW);
        when(call.getHandoverSourceCall()).thenReturn(sourceCall);
        when(call.getHandoverState()).thenReturn(HandoverState.HANDOVER_TO_STARTED);
        when(call.getConnectionService()).thenReturn(mock(ConnectionServiceWrapper.class));

        mCallsManager.createActionSetCallStateAndPerformAction(
                call, CallState.DISCONNECTED, "");

        verify(sourceCall).onConnectionEvent(eq(Connection.EVENT_HANDOVER_FAILED), any());
        verify(sourceCall).onHandoverFailed(
                    android.telecom.Call.Callback.HANDOVER_FAILURE_USER_REJECTED);

        verify(call).sendCallEvent(eq(android.telecom.Call.EVENT_HANDOVER_FAILED), any());
        verify(call).markFinishedHandoverStateAndCleanup(HandoverState.HANDOVER_FAILED);
    }

    @SmallTest
    @Test
    public void testHandoverFromIsStarted() {
        Call destinationCall = addSpyCall(CONNECTION_MGR_1_HANDLE, CallState.NEW);
        Call call = addSpyCall(CONNECTION_MGR_1_HANDLE, CallState.NEW);
        when(call.getHandoverDestinationCall()).thenReturn(destinationCall);
        when(call.getHandoverState()).thenReturn(HandoverState.HANDOVER_FROM_STARTED);

        mCallsManager.createActionSetCallStateAndPerformAction(
                call, CallState.DISCONNECTED, "");

        verify(destinationCall).sendCallEvent(
                eq(android.telecom.Call.EVENT_HANDOVER_SOURCE_DISCONNECTED), any());
    }

    @SmallTest
    @Test
    public void testHandoverFromIsAccepted() {
        Call destinationCall = addSpyCall(CONNECTION_MGR_1_HANDLE, CallState.NEW);
        Call call = addSpyCall(CONNECTION_MGR_1_HANDLE, CallState.NEW);
        when(call.getHandoverDestinationCall()).thenReturn(destinationCall);
        when(call.getHandoverState()).thenReturn(HandoverState.HANDOVER_ACCEPTED);

        mCallsManager.createActionSetCallStateAndPerformAction(
                call, CallState.DISCONNECTED, "");

        verify(call).onConnectionEvent(eq(Connection.EVENT_HANDOVER_COMPLETE), any());
        verify(call).onHandoverComplete();
        verify(call).markFinishedHandoverStateAndCleanup(HandoverState.HANDOVER_COMPLETE);
        verify(destinationCall).sendCallEvent(
                eq(android.telecom.Call.EVENT_HANDOVER_COMPLETE), any());
        verify(destinationCall).onHandoverComplete();
    }

    @SmallTest
    @Test
    public void testSelfManagedHandoverFromIsAccepted() {
        Call destinationCall = addSpyCall(SELF_MANAGED_HANDLE, CallState.NEW);
        when(destinationCall.isSelfManaged()).thenReturn(true);
        Call call = addSpyCall(CONNECTION_MGR_1_HANDLE, CallState.NEW);
        when(call.getHandoverDestinationCall()).thenReturn(destinationCall);
        when(call.getHandoverState()).thenReturn(HandoverState.HANDOVER_ACCEPTED);
        Call otherCall = addSpyCall(CONNECTION_MGR_1_HANDLE, CallState.ON_HOLD);

        mCallsManager.createActionSetCallStateAndPerformAction(
                call, CallState.DISCONNECTED, "");

        verify(call).onConnectionEvent(eq(Connection.EVENT_HANDOVER_COMPLETE), any());
        verify(call).onHandoverComplete();
        verify(call).markFinishedHandoverStateAndCleanup(HandoverState.HANDOVER_COMPLETE);
        verify(destinationCall).sendCallEvent(
                eq(android.telecom.Call.EVENT_HANDOVER_COMPLETE), any());
        verify(destinationCall).onHandoverComplete();
        verify(otherCall).disconnect();
    }

    @MediumTest
    @Test
    public void testGetNumUnholdableCallsForOtherConnectionService() {
        final int notDialingState = CallState.ACTIVE;
        final PhoneAccountHandle accountHande = SIM_1_HANDLE;
        assertFalse(mCallsManager.hasUnholdableCallsForOtherConnectionService(accountHande));

        Call unholdableCall = addSpyCall(accountHande, notDialingState);
        when(unholdableCall.can(Connection.CAPABILITY_HOLD)).thenReturn(false);
        assertFalse(mCallsManager.hasUnholdableCallsForOtherConnectionService(accountHande));

        Call holdableCall = addSpyCall(accountHande, notDialingState);
        when(holdableCall.can(Connection.CAPABILITY_HOLD)).thenReturn(true);
        assertFalse(mCallsManager.hasUnholdableCallsForOtherConnectionService(accountHande));

        Call dialingCall = addSpyCall(accountHande, CallState.DIALING);
        when(dialingCall.can(Connection.CAPABILITY_HOLD)).thenReturn(true);
        assertFalse(mCallsManager.hasUnholdableCallsForOtherConnectionService(accountHande));

        Call externalCall = addSpyCall(accountHande, notDialingState);
        when(externalCall.isExternalCall()).thenReturn(true);
        assertFalse(mCallsManager.hasUnholdableCallsForOtherConnectionService(accountHande));

        Call unholdableOtherCall = addSpyCall(VOIP_1_HANDLE, notDialingState);
        when(unholdableOtherCall.can(Connection.CAPABILITY_HOLD)).thenReturn(false);
        assertTrue(mCallsManager.hasUnholdableCallsForOtherConnectionService(accountHande));
        assertEquals(1, mCallsManager.getNumUnholdableCallsForOtherConnectionService(accountHande));
    }

    @SmallTest
    @Test
    public void testHasManagedCalls() {
        assertFalse(mCallsManager.hasManagedCalls());

        Call selfManagedCall = addSpyCall();
        when(selfManagedCall.isSelfManaged()).thenReturn(true);
        assertFalse(mCallsManager.hasManagedCalls());

        Call externalCall = addSpyCall();
        when(externalCall.isSelfManaged()).thenReturn(false);
        when(externalCall.isExternalCall()).thenReturn(true);
        assertFalse(mCallsManager.hasManagedCalls());

        Call managedCall = addSpyCall();
        when(managedCall.isSelfManaged()).thenReturn(false);
        assertTrue(mCallsManager.hasManagedCalls());
    }

    @SmallTest
    @Test
    public void testHasSelfManagedCalls() {
        Call managedCall = addSpyCall();
        when(managedCall.isSelfManaged()).thenReturn(false);
        assertFalse(mCallsManager.hasSelfManagedCalls());

        Call selfManagedCall = addSpyCall();
        when(selfManagedCall.isSelfManaged()).thenReturn(true);
        assertTrue(mCallsManager.hasSelfManagedCalls());
    }

    /**
     * Verifies when {@link CallsManager} receives a carrier config change it will trigger an
     * update of the emergency call notification.
     * Note: this test mocks out {@link BlockedNumbersAdapter} so does not actually test posting of
     * the notification.  Notification posting in the actual implementation is covered by
     * {@link BlockedNumbersUtilTests}.
     */
    @SmallTest
    @Test
    public void testUpdateEmergencyCallNotificationOnCarrierConfigChange() {
        when(mBlockedNumbersAdapter.shouldShowEmergencyCallNotification(any(Context.class)))
                .thenReturn(true);
        mComponentContextFixture.getBroadcastReceivers().forEach(c -> c.onReceive(mContext,
                new Intent(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED)));
        verify(mBlockedNumbersAdapter).updateEmergencyCallNotification(any(Context.class),
                eq(true));

        when(mBlockedNumbersAdapter.shouldShowEmergencyCallNotification(any(Context.class)))
                .thenReturn(false);
        mComponentContextFixture.getBroadcastReceivers().forEach(c -> c.onReceive(mContext,
                new Intent(CarrierConfigManager.ACTION_CARRIER_CONFIG_CHANGED)));
        verify(mBlockedNumbersAdapter).updateEmergencyCallNotification(any(Context.class),
                eq(false));
    }

    /**
     * Verifies when {@link CallsManager} receives a signal from the blocked number provider that
     * the call blocking enabled state changes, it will trigger an update of the emergency call
     * notification.
     * Note: this test mocks out {@link BlockedNumbersAdapter} so does not actually test posting of
     * the notification.  Notification posting in the actual implementation is covered by
     * {@link BlockedNumbersUtilTests}.
     */
    @SmallTest
    @Test
    public void testUpdateEmergencyCallNotificationOnNotificationVisibilityChange() {
        when(mBlockedNumbersAdapter.shouldShowEmergencyCallNotification(any(Context.class)))
                .thenReturn(true);
        mComponentContextFixture.getBroadcastReceivers().forEach(c -> c.onReceive(mContext,
                new Intent(
                        BlockedNumberContract.SystemContract
                                .ACTION_BLOCK_SUPPRESSION_STATE_CHANGED)));
        verify(mBlockedNumbersAdapter).updateEmergencyCallNotification(any(Context.class),
                eq(true));

        when(mBlockedNumbersAdapter.shouldShowEmergencyCallNotification(any(Context.class)))
                .thenReturn(false);
        mComponentContextFixture.getBroadcastReceivers().forEach(c -> c.onReceive(mContext,
                new Intent(
                        BlockedNumberContract.SystemContract
                                .ACTION_BLOCK_SUPPRESSION_STATE_CHANGED)));
        verify(mBlockedNumbersAdapter).updateEmergencyCallNotification(any(Context.class),
                eq(false));
    }

    /**
     * Verify CallsManager#isInSelfManagedCall(packageName, userHandle) returns true when
     * CallsManager is first made aware of the incoming call in processIncomingCallIntent.
     */
    @SmallTest
    @Test
    public void testAddNewIncomingCall_IsInSelfManagedCall() {
        // GIVEN
        assertEquals(0, mCallsManager.getSelfManagedCallsBeingSetup().size());
        assertFalse(mCallsManager.isInSelfManagedCall(TEST_PACKAGE_NAME, TEST_USER_HANDLE));

        // WHEN
        when(mPhoneAccountRegistrar.getPhoneAccountUnchecked(any()))
                .thenReturn(SM_W_DIFFERENT_PACKAGE_AND_USER);
        UserManager um = mContext.getSystemService(UserManager.class);
        when(um.isUserAdmin(eq(mCallsManager.getCurrentUserHandle().getIdentifier())))
                .thenReturn(true);

        // THEN
        mCallsManager.processIncomingCallIntent(SELF_MANAGED_W_CUSTOM_HANDLE, new Bundle(), false);

        assertEquals(1, mCallsManager.getSelfManagedCallsBeingSetup().size());
        assertTrue(mCallsManager.isInSelfManagedCall(TEST_PACKAGE_NAME, TEST_USER_HANDLE));
        assertEquals(0, mCallsManager.getCalls().size());
    }

    /**
     * Verify CallsManager#isInSelfManagedCall(packageName, userHandle) returns true when
     * CallsManager is first made aware of the outgoing call in StartOutgoingCall.
     */
    @SmallTest
    @Test
    public void testStartOutgoing_IsInSelfManagedCall() {
        // GIVEN
        assertEquals(0, mCallsManager.getSelfManagedCallsBeingSetup().size());
        assertFalse(mCallsManager.isInSelfManagedCall(TEST_PACKAGE_NAME, TEST_USER_HANDLE));

        // WHEN
        when(mPhoneAccountRegistrar.getPhoneAccount(any(), any()))
                .thenReturn(SM_W_DIFFERENT_PACKAGE_AND_USER);
        // Ensure contact info lookup succeeds
        doAnswer(invocation -> {
            Uri handle = invocation.getArgument(0);
            CallerInfo info = new CallerInfo();
            CompletableFuture<Pair<Uri, CallerInfo>> callerInfoFuture = new CompletableFuture<>();
            callerInfoFuture.complete(new Pair<>(handle, info));
            return callerInfoFuture;
        }).when(mCallerInfoLookupHelper).startLookup(any(Uri.class));
        // Ensure we have candidate phone account handle info.
        when(mPhoneAccountRegistrar.getOutgoingPhoneAccountForScheme(any(), any())).thenReturn(
                SELF_MANAGED_W_CUSTOM_HANDLE);
        when(mPhoneAccountRegistrar.getCallCapablePhoneAccounts(any(), anyBoolean(),
                any(), anyInt(), anyInt(), anyBoolean())).thenReturn(
                new ArrayList<>(List.of(SELF_MANAGED_W_CUSTOM_HANDLE)));

        // THEN
        mCallsManager.startOutgoingCall(TEST_ADDRESS, SELF_MANAGED_W_CUSTOM_HANDLE, new Bundle(),
                TEST_USER_HANDLE, new Intent(), TEST_PACKAGE_NAME);

        assertEquals(1, mCallsManager.getSelfManagedCallsBeingSetup().size());
        assertTrue(mCallsManager.isInSelfManagedCall(TEST_PACKAGE_NAME, TEST_USER_HANDLE));
        assertEquals(0, mCallsManager.getCalls().size());
    }

    /**
     * Verify SelfManagedCallsBeingSetup is being cleaned up in CallsManager#addCall and
     * CallsManager#removeCall.  This ensures no memory leaks.
     */
    @SmallTest
    @Test
    public void testCallsBeingSetupCleanup() {
        Call spyCall = addSpyCall();
        assertEquals(0, mCallsManager.getSelfManagedCallsBeingSetup().size());
        // verify CallsManager#removeCall removes the call from SelfManagedCallsBeingSetup
        mCallsManager.addCallBeingSetup(spyCall);
        mCallsManager.removeCall(spyCall);
        assertEquals(0, mCallsManager.getSelfManagedCallsBeingSetup().size());
        // verify CallsManager#addCall removes the call from SelfManagedCallsBeingSetup
        mCallsManager.addCallBeingSetup(spyCall);
        mCallsManager.addCall(spyCall);
        assertEquals(0, mCallsManager.getSelfManagedCallsBeingSetup().size());
    }

    /**
     * Verify isInSelfManagedCall returns false if there is a self-managed call, but it is for a
     * different package and user
     */
    @SmallTest
    @Test
    public void testIsInSelfManagedCall_PackageUserQueryIsWorkingAsIntended() {
        // start an active call
        Call randomCall = createSpyCall(SELF_MANAGED_HANDLE, CallState.ACTIVE);
        mCallsManager.addCallBeingSetup(randomCall);
        assertEquals(1, mCallsManager.getSelfManagedCallsBeingSetup().size());
        // query isInSelfManagedCall for a package that is NOT in a call;  expect false
        assertFalse(mCallsManager.isInSelfManagedCall(TEST_PACKAGE_NAME, TEST_USER_HANDLE));
        // start another call
        Call targetCall = addSpyCall(SELF_MANAGED_W_CUSTOM_HANDLE, CallState.DIALING);
        when(targetCall.getTargetPhoneAccount()).thenReturn(SELF_MANAGED_W_CUSTOM_HANDLE);
        when(targetCall.isSelfManaged()).thenReturn(true);
        mCallsManager.addCallBeingSetup(targetCall);
        // query isInSelfManagedCall for a package that is in a call
        assertTrue(mCallsManager.isInSelfManagedCall(TEST_PACKAGE_NAME, TEST_USER_HANDLE));
    }


    private Call addSpyCall() {
        return addSpyCall(SIM_2_HANDLE, CallState.ACTIVE);
    }

    private Call addSpyCall(int initialState) {
        return addSpyCall(SIM_2_HANDLE, initialState);
    }

    private Call addSpyCall(PhoneAccountHandle targetPhoneAccount, int initialState) {
        return addSpyCall(targetPhoneAccount, null, initialState, 0 /*caps*/, 0 /*props*/);
    }

    private Call addSpyCall(PhoneAccountHandle targetPhoneAccount,
            PhoneAccountHandle connectionMgrAcct, int initialState) {
        return addSpyCall(targetPhoneAccount, connectionMgrAcct, initialState, 0 /*caps*/,
                0 /*props*/);
    }

    private Call addSpyCall(PhoneAccountHandle targetPhoneAccount,
            PhoneAccountHandle connectionMgrAcct, int initialState,
            int connectionCapabilities, int connectionProperties) {
        Call ongoingCall = createCall(targetPhoneAccount, connectionMgrAcct, initialState);
        ongoingCall.setConnectionProperties(connectionProperties);
        ongoingCall.setConnectionCapabilities(connectionCapabilities);
        Call callSpy = Mockito.spy(ongoingCall);

        // Mocks some methods to not call the real method.
        doNothing().when(callSpy).unhold();
        doNothing().when(callSpy).hold();
        doNothing().when(callSpy).answer(Matchers.anyInt());
        doNothing().when(callSpy).setStartWithSpeakerphoneOn(Matchers.anyBoolean());

        mCallsManager.addCall(callSpy);
        return callSpy;
    }

    private Call createSpyCall(PhoneAccountHandle handle, int initialState) {
        Call ongoingCall = createCall(handle, initialState);
        Call callSpy = Mockito.spy(ongoingCall);

        // Mocks some methods to not call the real method.
        doNothing().when(callSpy).unhold();
        doNothing().when(callSpy).hold();
        doNothing().when(callSpy).disconnect();
        doNothing().when(callSpy).answer(Matchers.anyInt());
        doNothing().when(callSpy).setStartWithSpeakerphoneOn(Matchers.anyBoolean());

        return callSpy;
    }

    private Call createCall(PhoneAccountHandle targetPhoneAccount, int initialState) {
        return createCall(targetPhoneAccount, null /* connectionManager */, initialState);
    }

    private Call createCall(PhoneAccountHandle targetPhoneAccount,
            PhoneAccountHandle connectionManagerAccount, int initialState) {
        Call ongoingCall = new Call(String.format("TC@%d", sCallId++), /* callId */
                mContext,
                mCallsManager,
                mLock, /* ConnectionServiceRepository */
                null,
                mPhoneNumberUtilsAdapter,
                TEST_ADDRESS,
                null /* GatewayInfo */,
                connectionManagerAccount,
                targetPhoneAccount,
                Call.CALL_DIRECTION_INCOMING,
                false /* shouldAttachToExistingConnection*/,
                false /* isConference */,
                mClockProxy,
                mToastFactory);
        ongoingCall.setState(initialState, "just cuz");
        if (targetPhoneAccount == SELF_MANAGED_HANDLE
                || targetPhoneAccount == SELF_MANAGED_2_HANDLE) {
            ongoingCall.setIsSelfManaged(true);
        }
        return ongoingCall;
    }

    private void verifyFocusRequestAndExecuteCallback(Call call) {
        ArgumentCaptor<CallsManager.RequestCallback> captor =
                ArgumentCaptor.forClass(CallsManager.RequestCallback.class);
        verify(mConnectionSvrFocusMgr).requestFocus(eq(call), captor.capture());
        CallsManager.RequestCallback callback = captor.getValue();
        callback.onRequestFocusDone(call);
    }

    private void setupMsimAccounts() {
        TelephonyManager mockTelephonyManager = mComponentContextFixture.getTelephonyManager();
        when(mockTelephonyManager.getMaxNumberOfSimultaneouslyActiveSims()).thenReturn(1);
        when(mPhoneAccountRegistrar.getCallCapablePhoneAccounts(any(), anyBoolean(),
                any(), anyInt(), anyInt(), anyBoolean())).thenReturn(
                new ArrayList<>(Arrays.asList(SIM_1_HANDLE, SIM_2_HANDLE)));
        when(mPhoneAccountRegistrar.getSimPhoneAccountsOfCurrentUser()).thenReturn(
                new ArrayList<>(Arrays.asList(SIM_1_HANDLE, SIM_2_HANDLE)));
    }

    private void setMaxActiveVoiceSubscriptions(int num) {
        TelephonyManager mockTelephonyManager = mComponentContextFixture.getTelephonyManager();
        when(mockTelephonyManager.getPhoneCapability()).thenReturn(mPhoneCapability);
        when(mPhoneCapability.getMaxActiveVoiceSubscriptions()).thenReturn(num);
    }
}