summaryrefslogtreecommitdiff
path: root/tests/src/com/android/server/telecom/tests/PhoneAccountRegistrarTest.java
blob: 9fcb87a3890c581d5b31da5c9fa0d8c03f13217c (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
/*
 * Copyright (C) 2014 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 org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Matchers.anyBoolean;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.clearInvocations;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import android.annotation.Nullable;
import android.content.ComponentName;
import android.content.Context;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import android.graphics.drawable.Icon;
import android.net.Uri;
import android.os.Bundle;
import android.os.Parcel;
import android.os.PersistableBundle;
import android.os.Process;
import android.os.UserHandle;
import android.os.UserManager;
import android.telecom.Log;
import android.telecom.PhoneAccount;
import android.telecom.PhoneAccountHandle;
import android.telecom.TelecomManager;
import android.telephony.CarrierConfigManager;
import android.telephony.SubscriptionInfo;
import android.telephony.SubscriptionManager;
import android.test.suitebuilder.annotation.SmallTest;
import android.test.suitebuilder.annotation.MediumTest;
import android.util.Xml;

import androidx.test.InstrumentationRegistry;

import com.android.internal.telecom.IConnectionService;
import com.android.internal.util.FastXmlSerializer;
import com.android.server.telecom.AppLabelProxy;
import com.android.server.telecom.DefaultDialerCache;
import com.android.server.telecom.PhoneAccountRegistrar;
import com.android.server.telecom.PhoneAccountRegistrar.DefaultPhoneAccountHandle;
import com.android.server.telecom.TelecomSystem;

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.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlSerializer;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

@RunWith(JUnit4.class)
public class PhoneAccountRegistrarTest extends TelecomTestCase {

    private static final int MAX_VERSION = Integer.MAX_VALUE;
    private static final int INVALID_CHAR_LIMIT_COUNT =
            PhoneAccountRegistrar.MAX_PHONE_ACCOUNT_FIELD_CHAR_LIMIT + 1;
    private static final String INVALID_STR = "a".repeat(INVALID_CHAR_LIMIT_COUNT);
    private static final String FILE_NAME = "phone-account-registrar-test-1223.xml";
    private static final String TEST_LABEL = "right";
    private static final String TEST_ID = "123";
    private final String PACKAGE_1 = "PACKAGE_1";
    private final String PACKAGE_2 = "PACKAGE_2";
    private final String COMPONENT_NAME = "com.android.server.telecom.tests.MockConnectionService";
    private final UserHandle USER_HANDLE_10 = new UserHandle(10);
    private final TelecomSystem.SyncRoot mLock = new TelecomSystem.SyncRoot() { };
    private PhoneAccountRegistrar mRegistrar;
    @Mock private SubscriptionManager mSubscriptionManager;
    @Mock private TelecomManager mTelecomManager;
    @Mock private DefaultDialerCache mDefaultDialerCache;
    @Mock private AppLabelProxy mAppLabelProxy;

    @Override
    @Before
    public void setUp() throws Exception {
        super.setUp();
        MockitoAnnotations.initMocks(this);
        mComponentContextFixture.setTelecomManager(mTelecomManager);
        mComponentContextFixture.setSubscriptionManager(mSubscriptionManager);
        new File(
                mComponentContextFixture.getTestDouble().getApplicationContext().getFilesDir(),
                FILE_NAME)
                .delete();
        when(mDefaultDialerCache.getDefaultDialerApplication(anyInt()))
                .thenReturn("com.android.dialer");
        when(mAppLabelProxy.getAppLabel(anyString()))
                .thenReturn(TEST_LABEL);
        mRegistrar = new PhoneAccountRegistrar(
                mComponentContextFixture.getTestDouble().getApplicationContext(),
                mLock, FILE_NAME, mDefaultDialerCache, mAppLabelProxy);
    }

    @Override
    @After
    public void tearDown() throws Exception {
        mRegistrar = null;
        new File(
                mComponentContextFixture.getTestDouble().getApplicationContext().getFilesDir(),
                FILE_NAME)
                .delete();
        super.tearDown();
    }

    @MediumTest
    @Test
    public void testPhoneAccountHandle() throws Exception {
        PhoneAccountHandle input = new PhoneAccountHandle(new ComponentName("pkg0", "cls0"), "id0");
        PhoneAccountHandle result = roundTripXml(this, input,
                PhoneAccountRegistrar.sPhoneAccountHandleXml, mContext);
        assertPhoneAccountHandleEquals(input, result);

        PhoneAccountHandle inputN = new PhoneAccountHandle(new ComponentName("pkg0", "cls0"), null);
        PhoneAccountHandle resultN = roundTripXml(this, inputN,
                PhoneAccountRegistrar.sPhoneAccountHandleXml, mContext);
        Log.i(this, "inputN = %s, resultN = %s", inputN, resultN);
        assertPhoneAccountHandleEquals(inputN, resultN);
    }

    @MediumTest
    @Test
    public void testPhoneAccount() throws Exception {
        Bundle testBundle = new Bundle();
        testBundle.putInt("EXTRA_INT_1", 1);
        testBundle.putInt("EXTRA_INT_100", 100);
        testBundle.putBoolean("EXTRA_BOOL_TRUE", true);
        testBundle.putBoolean("EXTRA_BOOL_FALSE", false);
        testBundle.putString("EXTRA_STR1", "Hello");
        testBundle.putString("EXTRA_STR2", "There");

        PhoneAccount input = makeQuickAccountBuilder("id0", 0, null)
                .addSupportedUriScheme(PhoneAccount.SCHEME_TEL)
                .addSupportedUriScheme(PhoneAccount.SCHEME_VOICEMAIL)
                .setExtras(testBundle)
                .setIsEnabled(true)
                .build();
        PhoneAccount result = roundTripXml(this, input, PhoneAccountRegistrar.sPhoneAccountXml,
                mContext);

        assertPhoneAccountEquals(input, result);
    }

    @SmallTest
    @Test
    public void testFilterPhoneAccountForTest() throws Exception {
        ComponentName componentA = new ComponentName("a", "a");
        ComponentName componentB1 = new ComponentName("b", "b1");
        ComponentName componentB2 = new ComponentName("b", "b2");
        ComponentName componentC = new ComponentName("c", "c");

        PhoneAccount simAccountA = new PhoneAccount.Builder(
                makeQuickAccountHandle(componentA, "1"), "1")
                .setCapabilities(PhoneAccount.CAPABILITY_CALL_PROVIDER)
                .setIsEnabled(true)
                .build();

        List<PhoneAccount> accountAList = new ArrayList<>();
        accountAList.add(simAccountA);

        PhoneAccount simAccountB1 = new PhoneAccount.Builder(
                makeQuickAccountHandle(componentB1, "2"), "2")
                .setCapabilities(PhoneAccount.CAPABILITY_CALL_PROVIDER)
                .setIsEnabled(true)
                .build();

        PhoneAccount simAccountB2 = new PhoneAccount.Builder(
                makeQuickAccountHandle(componentB2, "3"), "3")
                .setCapabilities(PhoneAccount.CAPABILITY_CALL_PROVIDER)
                .setIsEnabled(true)
                .build();

        List<PhoneAccount> accountBList = new ArrayList<>();
        accountBList.add(simAccountB1);
        accountBList.add(simAccountB2);

        PhoneAccount simAccountC = new PhoneAccount.Builder(
                makeQuickAccountHandle(componentC, "4"), "4")
                .setCapabilities(PhoneAccount.CAPABILITY_CALL_PROVIDER)
                .setIsEnabled(true)
                .build();

        List<PhoneAccount> accountCList = new ArrayList<>();
        accountCList.add(simAccountC);

        List<PhoneAccount> allAccounts = new ArrayList<>();
        allAccounts.addAll(accountAList);
        allAccounts.addAll(accountBList);
        allAccounts.addAll(accountCList);

        assertEquals(allAccounts, mRegistrar.filterRestrictedPhoneAccounts(allAccounts));

        mRegistrar.setTestPhoneAccountPackageNameFilter(componentA.getPackageName());
        assertEquals(accountAList, mRegistrar.filterRestrictedPhoneAccounts(allAccounts));

        mRegistrar.setTestPhoneAccountPackageNameFilter(componentB1.getPackageName());
        assertEquals(accountBList, mRegistrar.filterRestrictedPhoneAccounts(allAccounts));

        mRegistrar.setTestPhoneAccountPackageNameFilter(componentC.getPackageName());
        assertEquals(accountCList, mRegistrar.filterRestrictedPhoneAccounts(allAccounts));

        mRegistrar.setTestPhoneAccountPackageNameFilter(null);
        assertEquals(allAccounts, mRegistrar.filterRestrictedPhoneAccounts(allAccounts));
    }

    @MediumTest
    @Test
    public void testDefaultPhoneAccountHandleEmptyGroup() throws Exception {
        DefaultPhoneAccountHandle input = new DefaultPhoneAccountHandle(Process.myUserHandle(),
                makeQuickAccountHandle("i1"), "");
        when(UserManager.get(mContext).getSerialNumberForUser(input.userHandle))
                .thenReturn(0L);
        when(UserManager.get(mContext).getUserForSerialNumber(0L))
                .thenReturn(input.userHandle);
        DefaultPhoneAccountHandle result = roundTripXml(this, input,
                PhoneAccountRegistrar.sDefaultPhoneAcountHandleXml, mContext);

        assertDefaultPhoneAccountHandleEquals(input, result);
    }

    /**
     * Test to ensure non-supported values
     * @throws Exception
     */
    @MediumTest
    @Test
    public void testPhoneAccountExtrasEdge() throws Exception {
        Bundle testBundle = new Bundle();
        // Ensure null values for string are not persisted.
        testBundle.putString("EXTRA_STR2", null);
        //

        // Ensure unsupported data types are not persisted.
        testBundle.putShort("EXTRA_SHORT", (short) 2);
        testBundle.putByte("EXTRA_BYTE", (byte) 1);
        testBundle.putParcelable("EXTRA_PARC", new Rect(1, 1, 1, 1));
        // Put in something valid so the bundle exists.
        testBundle.putString("EXTRA_OK", "OK");

        PhoneAccount input = makeQuickAccountBuilder("id0", 0, null)
                .addSupportedUriScheme(PhoneAccount.SCHEME_TEL)
                .addSupportedUriScheme(PhoneAccount.SCHEME_VOICEMAIL)
                .setExtras(testBundle)
                .build();
        PhoneAccount result = roundTripXml(this, input, PhoneAccountRegistrar.sPhoneAccountXml,
                mContext);

        Bundle extras = result.getExtras();
        assertFalse(extras.keySet().contains("EXTRA_STR2"));
        assertFalse(extras.keySet().contains("EXTRA_SHORT"));
        assertFalse(extras.keySet().contains("EXTRA_BYTE"));
        assertFalse(extras.keySet().contains("EXTRA_PARC"));
    }

    @MediumTest
    @Test
    public void testState() throws Exception {
        PhoneAccountRegistrar.State input = makeQuickState();
        PhoneAccountRegistrar.State result = roundTripXml(this, input,
                PhoneAccountRegistrar.sStateXml,
                mContext);
        assertStateEquals(input, result);
    }

    private void registerAndEnableAccount(PhoneAccount account) {
        mRegistrar.registerPhoneAccount(account);
        mRegistrar.enablePhoneAccount(account.getAccountHandle(), true);
    }

    @MediumTest
    @Test
    public void testAccounts() throws Exception {
        int i = 0;

        mComponentContextFixture.addConnectionService(makeQuickConnectionServiceComponentName(),
                Mockito.mock(IConnectionService.class));

        registerAndEnableAccount(makeQuickAccountBuilder("id" + i, i++, null)
                .setCapabilities(PhoneAccount.CAPABILITY_CONNECTION_MANAGER
                        | PhoneAccount.CAPABILITY_CALL_PROVIDER)
                .build());
        registerAndEnableAccount(makeQuickAccountBuilder("id" + i, i++, null)
                .setCapabilities(PhoneAccount.CAPABILITY_CONNECTION_MANAGER
                        | PhoneAccount.CAPABILITY_CALL_PROVIDER)
                .build());
        registerAndEnableAccount(makeQuickAccountBuilder("id" + i, i++, null)
                .setCapabilities(PhoneAccount.CAPABILITY_CONNECTION_MANAGER
                        | PhoneAccount.CAPABILITY_CALL_PROVIDER)
                .build());
        registerAndEnableAccount(makeQuickAccountBuilder("id" + i, i++, null)
                .setCapabilities(PhoneAccount.CAPABILITY_CONNECTION_MANAGER)
                .build());
        registerAndEnableAccount(makeQuickAccountBuilder("id" + i, i++, USER_HANDLE_10)
                .setCapabilities(PhoneAccount.CAPABILITY_CONNECTION_MANAGER
                        | PhoneAccount.CAPABILITY_CALL_PROVIDER)
                .build());
        registerAndEnableAccount(makeQuickAccountBuilder("id" + i, i++, USER_HANDLE_10)
                .setCapabilities(PhoneAccount.CAPABILITY_CONNECTION_MANAGER)
                .build());

        assertEquals(6, mRegistrar.
                getAllPhoneAccounts(null, true).size());
        assertEquals(4, mRegistrar.getCallCapablePhoneAccounts(null, false,
                null, true).size());
        assertEquals(null, mRegistrar.getSimCallManagerOfCurrentUser());
        assertEquals(null, mRegistrar.getOutgoingPhoneAccountForSchemeOfCurrentUser(
                PhoneAccount.SCHEME_TEL));
    }

    /**
     * Verify when a {@link android.telecom.ConnectionService} is disabled or cannot be resolved,
     * all phone accounts are unregistered when calling
     * {@link  PhoneAccountRegistrar#getAccountsForPackage_BypassResolveComp(String, UserHandle)}.
     */
    @Test
    public void testCannotResolveServiceUnregistersAccounts() throws Exception {
        ComponentName componentName = makeQuickConnectionServiceComponentName();
        PhoneAccount account = makeQuickAccountBuilder("0", 0, USER_HANDLE_10)
                .setCapabilities(PhoneAccount.CAPABILITY_CONNECTION_MANAGER
                        | PhoneAccount.CAPABILITY_CALL_PROVIDER).build();
        // add the ConnectionService and register a single phone account for it
        mComponentContextFixture.addConnectionService(componentName,
                Mockito.mock(IConnectionService.class));
        registerAndEnableAccount(account);
        // verify the start state
        assertEquals(1,
                mRegistrar.getAccountsForPackage_BypassResolveComp(componentName.getPackageName(),
                        USER_HANDLE_10).size());
        // remove the ConnectionService so that the account cannot be resolved anymore
        mComponentContextFixture.removeConnectionService(componentName,
                Mockito.mock(IConnectionService.class));
        // verify the account is unregistered when fetching the phone accounts for the package
        assertEquals(1,
                mRegistrar.getAccountsForPackage_BypassResolveComp(componentName.getPackageName(),
                        USER_HANDLE_10).size());
        assertEquals(0,mRegistrar.cleanupUnresolvableConnectionServiceAccounts(
                mRegistrar.getAccountsForPackage_BypassResolveComp(componentName.getPackageName(),
                USER_HANDLE_10)).size());
        assertEquals(0,
                mRegistrar.getAccountsForPackage_BypassResolveComp(componentName.getPackageName(),
                        USER_HANDLE_10).size());
    }

    @MediumTest
    @Test
    public void testSimCallManager() throws Exception {
        // TODO
    }

    @MediumTest
    @Test
    public void testDefaultOutgoing() throws Exception {
        mComponentContextFixture.addConnectionService(makeQuickConnectionServiceComponentName(),
                Mockito.mock(IConnectionService.class));

        // By default, there is no default outgoing account (nothing has been registered)
        assertNull(
                mRegistrar.getOutgoingPhoneAccountForSchemeOfCurrentUser(PhoneAccount.SCHEME_TEL));

        // Register one tel: account
        PhoneAccountHandle telAccount = makeQuickAccountHandle("tel_acct");
        registerAndEnableAccount(new PhoneAccount.Builder(telAccount, "tel_acct")
                .setCapabilities(PhoneAccount.CAPABILITY_CALL_PROVIDER)
                .addSupportedUriScheme(PhoneAccount.SCHEME_TEL)
                .build());
        PhoneAccountHandle defaultAccount =
                mRegistrar.getOutgoingPhoneAccountForSchemeOfCurrentUser(PhoneAccount.SCHEME_TEL);
        assertEquals(telAccount, defaultAccount);

        // Add a SIP account, make sure tel: doesn't change
        PhoneAccountHandle sipAccount = makeQuickAccountHandle("sip_acct");
        registerAndEnableAccount(new PhoneAccount.Builder(sipAccount, "sip_acct")
                .setCapabilities(PhoneAccount.CAPABILITY_CALL_PROVIDER)
                .addSupportedUriScheme(PhoneAccount.SCHEME_SIP)
                .build());
        defaultAccount = mRegistrar.getOutgoingPhoneAccountForSchemeOfCurrentUser(
                PhoneAccount.SCHEME_SIP);
        assertEquals(sipAccount, defaultAccount);
        defaultAccount = mRegistrar.getOutgoingPhoneAccountForSchemeOfCurrentUser(
                PhoneAccount.SCHEME_TEL);
        assertEquals(telAccount, defaultAccount);

        // Add a connection manager, make sure tel: doesn't change
        PhoneAccountHandle connectionManager = makeQuickAccountHandle("mgr_acct");
        registerAndEnableAccount(new PhoneAccount.Builder(connectionManager, "mgr_acct")
                .setCapabilities(PhoneAccount.CAPABILITY_CONNECTION_MANAGER)
                .addSupportedUriScheme(PhoneAccount.SCHEME_TEL)
                .build());
        defaultAccount = mRegistrar.getOutgoingPhoneAccountForSchemeOfCurrentUser(
                PhoneAccount.SCHEME_TEL);
        assertEquals(telAccount, defaultAccount);

        // Unregister the tel: account, make sure there is no tel: default now.
        mRegistrar.unregisterPhoneAccount(telAccount);
        assertNull(
                mRegistrar.getOutgoingPhoneAccountForSchemeOfCurrentUser(PhoneAccount.SCHEME_TEL));
    }

    @MediumTest
    @Test
    public void testReplacePhoneAccountByGroup() throws Exception {
        mComponentContextFixture.addConnectionService(makeQuickConnectionServiceComponentName(),
                Mockito.mock(IConnectionService.class));

        // By default, there is no default outgoing account (nothing has been registered)
        assertNull(
                mRegistrar.getOutgoingPhoneAccountForSchemeOfCurrentUser(PhoneAccount.SCHEME_TEL));

        // Register one tel: account
        PhoneAccountHandle telAccount1 = makeQuickAccountHandle("tel_acct1");
        registerAndEnableAccount(new PhoneAccount.Builder(telAccount1, "tel_acct1")
                .setCapabilities(PhoneAccount.CAPABILITY_CALL_PROVIDER)
                .addSupportedUriScheme(PhoneAccount.SCHEME_TEL)
                .setGroupId("testGroup")
                .build());
        mRegistrar.setUserSelectedOutgoingPhoneAccount(telAccount1, Process.myUserHandle());
        PhoneAccountHandle defaultAccount =
                mRegistrar.getOutgoingPhoneAccountForSchemeOfCurrentUser(PhoneAccount.SCHEME_TEL);
        assertEquals(telAccount1, defaultAccount);

        // Add call capable SIP account, make sure tel: doesn't change
        PhoneAccountHandle sipAccount = makeQuickAccountHandle("sip_acct");
        registerAndEnableAccount(new PhoneAccount.Builder(sipAccount, "sip_acct")
                .setCapabilities(PhoneAccount.CAPABILITY_CALL_PROVIDER)
                .addSupportedUriScheme(PhoneAccount.SCHEME_TEL)
                .build());
        defaultAccount = mRegistrar.getOutgoingPhoneAccountForSchemeOfCurrentUser(
                PhoneAccount.SCHEME_TEL);
        assertEquals(telAccount1, defaultAccount);

        // Replace tel: account with another in the same Group
        PhoneAccountHandle telAccount2 = makeQuickAccountHandle("tel_acct2");
        registerAndEnableAccount(new PhoneAccount.Builder(telAccount2, "tel_acct2")
                .setCapabilities(PhoneAccount.CAPABILITY_CALL_PROVIDER)
                .addSupportedUriScheme(PhoneAccount.SCHEME_TEL)
                .setGroupId("testGroup")
                .build());
        defaultAccount = mRegistrar.getOutgoingPhoneAccountForSchemeOfCurrentUser(
                PhoneAccount.SCHEME_TEL);
        assertEquals(telAccount2, defaultAccount);
        assertNull(mRegistrar.getPhoneAccountUnchecked(telAccount1));
    }

    @MediumTest
    @Test
    public void testAddSameDefault() throws Exception {
        mComponentContextFixture.addConnectionService(makeQuickConnectionServiceComponentName(),
                Mockito.mock(IConnectionService.class));

        // By default, there is no default outgoing account (nothing has been registered)
        assertNull(
                mRegistrar.getOutgoingPhoneAccountForSchemeOfCurrentUser(PhoneAccount.SCHEME_TEL));

        // Register one tel: account
        PhoneAccountHandle telAccount1 = makeQuickAccountHandle("tel_acct1");
        registerAndEnableAccount(new PhoneAccount.Builder(telAccount1, "tel_acct1")
                .setCapabilities(PhoneAccount.CAPABILITY_CALL_PROVIDER)
                .addSupportedUriScheme(PhoneAccount.SCHEME_TEL)
                .setGroupId("testGroup")
                .build());
        mRegistrar.setUserSelectedOutgoingPhoneAccount(telAccount1, Process.myUserHandle());
        PhoneAccountHandle defaultAccount =
                mRegistrar.getUserSelectedOutgoingPhoneAccount(Process.myUserHandle());
        assertEquals(telAccount1, defaultAccount);
        mRegistrar.unregisterPhoneAccount(telAccount1);

        // Register Emergency Account and unregister
        PhoneAccountHandle emerAccount = makeQuickAccountHandle("emer_acct");
        registerAndEnableAccount(new PhoneAccount.Builder(emerAccount, "emer_acct")
                .setCapabilities(PhoneAccount.CAPABILITY_CALL_PROVIDER)
                .addSupportedUriScheme(PhoneAccount.SCHEME_TEL)
                .build());
        defaultAccount =
                mRegistrar.getUserSelectedOutgoingPhoneAccount(Process.myUserHandle());
        assertNull(defaultAccount);
        mRegistrar.unregisterPhoneAccount(emerAccount);

        // Re-register the same account and make sure the default is in place
        registerAndEnableAccount(new PhoneAccount.Builder(telAccount1, "tel_acct1")
                .setCapabilities(PhoneAccount.CAPABILITY_CALL_PROVIDER)
                .addSupportedUriScheme(PhoneAccount.SCHEME_TEL)
                .setGroupId("testGroup")
                .build());
        defaultAccount =
                mRegistrar.getUserSelectedOutgoingPhoneAccount(Process.myUserHandle());
        assertEquals(telAccount1, defaultAccount);
    }

    @MediumTest
    @Test
    public void testAddSameGroup() throws Exception {
        mComponentContextFixture.addConnectionService(makeQuickConnectionServiceComponentName(),
                Mockito.mock(IConnectionService.class));

        // By default, there is no default outgoing account (nothing has been registered)
        assertNull(
                mRegistrar.getOutgoingPhoneAccountForSchemeOfCurrentUser(PhoneAccount.SCHEME_TEL));

        // Register one tel: account
        PhoneAccountHandle telAccount1 = makeQuickAccountHandle("tel_acct1");
        registerAndEnableAccount(new PhoneAccount.Builder(telAccount1, "tel_acct1")
                .setCapabilities(PhoneAccount.CAPABILITY_CALL_PROVIDER)
                .addSupportedUriScheme(PhoneAccount.SCHEME_TEL)
                .setGroupId("testGroup")
                .build());
        mRegistrar.setUserSelectedOutgoingPhoneAccount(telAccount1, Process.myUserHandle());
        PhoneAccountHandle defaultAccount =
                mRegistrar.getUserSelectedOutgoingPhoneAccount(Process.myUserHandle());
        assertEquals(telAccount1, defaultAccount);
        mRegistrar.unregisterPhoneAccount(telAccount1);

        // Register Emergency Account and unregister
        PhoneAccountHandle emerAccount = makeQuickAccountHandle("emer_acct");
        registerAndEnableAccount(new PhoneAccount.Builder(emerAccount, "emer_acct")
                .setCapabilities(PhoneAccount.CAPABILITY_CALL_PROVIDER)
                .addSupportedUriScheme(PhoneAccount.SCHEME_TEL)
                .build());
        defaultAccount =
                mRegistrar.getUserSelectedOutgoingPhoneAccount(Process.myUserHandle());
        assertNull(defaultAccount);
        mRegistrar.unregisterPhoneAccount(emerAccount);

        // Re-register a new account with the same group
        PhoneAccountHandle telAccount2 = makeQuickAccountHandle("tel_acct2");
        registerAndEnableAccount(new PhoneAccount.Builder(telAccount2, "tel_acct2")
                .setCapabilities(PhoneAccount.CAPABILITY_CALL_PROVIDER)
                .addSupportedUriScheme(PhoneAccount.SCHEME_TEL)
                .setGroupId("testGroup")
                .build());
        defaultAccount =
                mRegistrar.getUserSelectedOutgoingPhoneAccount(Process.myUserHandle());
        assertEquals(telAccount2, defaultAccount);
    }

    @MediumTest
    @Test
    public void testAddSameGroupButDifferentComponent() throws Exception {
        mComponentContextFixture.addConnectionService(makeQuickConnectionServiceComponentName(),
                Mockito.mock(IConnectionService.class));

        // By default, there is no default outgoing account (nothing has been registered)
        assertNull(mRegistrar.getOutgoingPhoneAccountForSchemeOfCurrentUser(
                PhoneAccount.SCHEME_TEL));

        // Register one tel: account
        PhoneAccountHandle telAccount1 = makeQuickAccountHandle("tel_acct1");
        registerAndEnableAccount(new PhoneAccount.Builder(telAccount1, "tel_acct1")
                .setCapabilities(PhoneAccount.CAPABILITY_CALL_PROVIDER)
                .addSupportedUriScheme(PhoneAccount.SCHEME_TEL)
                .setGroupId("testGroup")
                .build());
        mRegistrar.setUserSelectedOutgoingPhoneAccount(telAccount1, Process.myUserHandle());
        PhoneAccountHandle defaultAccount =
                mRegistrar.getUserSelectedOutgoingPhoneAccount(Process.myUserHandle());
        assertEquals(telAccount1, defaultAccount);
        assertNotNull(mRegistrar.getPhoneAccountUnchecked(telAccount1));

        // Register a new account with the same group, but different Component, so don't replace
        // Default
        PhoneAccountHandle telAccount2 =  makeQuickAccountHandle(
                new ComponentName("other1", "other2"), "tel_acct2");
        registerAndEnableAccount(new PhoneAccount.Builder(telAccount2, "tel_acct2")
                .setCapabilities(PhoneAccount.CAPABILITY_CALL_PROVIDER)
                .addSupportedUriScheme(PhoneAccount.SCHEME_TEL)
                .setGroupId("testGroup")
                .build());
        assertNotNull(mRegistrar.getPhoneAccountUnchecked(telAccount2));

        defaultAccount =
                mRegistrar.getUserSelectedOutgoingPhoneAccount(Process.myUserHandle());
        assertEquals(telAccount1, defaultAccount);
    }

    @MediumTest
    @Test
    public void testAddSameGroupButDifferentComponent2() throws Exception {
        mComponentContextFixture.addConnectionService(makeQuickConnectionServiceComponentName(),
                Mockito.mock(IConnectionService.class));

        // By default, there is no default outgoing account (nothing has been registered)
        assertNull(mRegistrar.getOutgoingPhoneAccountForSchemeOfCurrentUser(
                PhoneAccount.SCHEME_TEL));

        // Register first tel: account
        PhoneAccountHandle telAccount1 =  makeQuickAccountHandle(
                new ComponentName("other1", "other2"), "tel_acct1");
        registerAndEnableAccount(new PhoneAccount.Builder(telAccount1, "tel_acct1")
                .setCapabilities(PhoneAccount.CAPABILITY_CALL_PROVIDER)
                .addSupportedUriScheme(PhoneAccount.SCHEME_TEL)
                .setGroupId("testGroup")
                .build());
        assertNotNull(mRegistrar.getPhoneAccountUnchecked(telAccount1));
        mRegistrar.setUserSelectedOutgoingPhoneAccount(telAccount1, Process.myUserHandle());

        // Register second account with the same group, but a second Component, so don't replace
        // Default
        PhoneAccountHandle telAccount2 = makeQuickAccountHandle("tel_acct2");
        registerAndEnableAccount(new PhoneAccount.Builder(telAccount2, "tel_acct2")
                .setCapabilities(PhoneAccount.CAPABILITY_CALL_PROVIDER)
                .addSupportedUriScheme(PhoneAccount.SCHEME_TEL)
                .setGroupId("testGroup")
                .build());

        PhoneAccountHandle defaultAccount =
                mRegistrar.getOutgoingPhoneAccountForSchemeOfCurrentUser(PhoneAccount.SCHEME_TEL);
        assertEquals(telAccount1, defaultAccount);

        // Register third account with the second component name, but same group id
        PhoneAccountHandle telAccount3 = makeQuickAccountHandle("tel_acct3");
        registerAndEnableAccount(new PhoneAccount.Builder(telAccount3, "tel_acct3")
                .setCapabilities(PhoneAccount.CAPABILITY_CALL_PROVIDER)
                .addSupportedUriScheme(PhoneAccount.SCHEME_TEL)
                .setGroupId("testGroup")
                .build());

        // Make sure that the default account is still the original PhoneAccount and that the
        // second PhoneAccount with the second ComponentName was replaced by the third PhoneAccount
        defaultAccount =
                mRegistrar.getOutgoingPhoneAccountForSchemeOfCurrentUser(PhoneAccount.SCHEME_TEL);
        assertEquals(telAccount1, defaultAccount);

        assertNotNull(mRegistrar.getPhoneAccountUnchecked(telAccount1));
        assertNull(mRegistrar.getPhoneAccountUnchecked(telAccount2));
        assertNotNull(mRegistrar.getPhoneAccountUnchecked(telAccount3));
    }

    @MediumTest
    @Test
    public void testPhoneAccountParceling() throws Exception {
        PhoneAccountHandle handle = makeQuickAccountHandle("foo");
        roundTripPhoneAccount(new PhoneAccount.Builder(handle, null).build());
        roundTripPhoneAccount(new PhoneAccount.Builder(handle, "foo").build());
        roundTripPhoneAccount(
                new PhoneAccount.Builder(handle, "foo")
                        .setAddress(Uri.parse("tel:123456"))
                        .setCapabilities(23)
                        .setHighlightColor(0xf0f0f0)
                        .setIcon(Icon.createWithResource(
                                "com.android.server.telecom.tests", R.drawable.stat_sys_phone_call))
                        // TODO: set icon tint (0xfefefe)
                        .setShortDescription("short description")
                        .setSubscriptionAddress(Uri.parse("tel:2345678"))
                        .setSupportedUriSchemes(Arrays.asList("tel", "sip"))
                        .setGroupId("testGroup")
                        .build());
        roundTripPhoneAccount(
                new PhoneAccount.Builder(handle, "foo")
                        .setAddress(Uri.parse("tel:123456"))
                        .setCapabilities(23)
                        .setHighlightColor(0xf0f0f0)
                        .setIcon(Icon.createWithBitmap(
                                BitmapFactory.decodeResource(
                                        InstrumentationRegistry.getContext().getResources(),
                                        R.drawable.stat_sys_phone_call)))
                        .setShortDescription("short description")
                        .setSubscriptionAddress(Uri.parse("tel:2345678"))
                        .setSupportedUriSchemes(Arrays.asList("tel", "sip"))
                        .setGroupId("testGroup")
                        .build());
    }

    /**
     * Tests ability to register a self-managed PhoneAccount; verifies that the user defined label
     * is overridden.
     * @throws Exception
     */
    @MediumTest
    @Test
    public void testSelfManagedPhoneAccount() throws Exception {
        mComponentContextFixture.addConnectionService(makeQuickConnectionServiceComponentName(),
                Mockito.mock(IConnectionService.class));

        PhoneAccountHandle selfManagedHandle =  makeQuickAccountHandle(
                new ComponentName("self", "managed"), "selfie1");

        PhoneAccount selfManagedAccount = new PhoneAccount.Builder(selfManagedHandle, "Wrong")
                .setCapabilities(PhoneAccount.CAPABILITY_SELF_MANAGED)
                .build();

        mRegistrar.registerPhoneAccount(selfManagedAccount);

        PhoneAccount registeredAccount = mRegistrar.getPhoneAccountUnchecked(selfManagedHandle);
        assertEquals(TEST_LABEL, registeredAccount.getLabel());
    }

    @MediumTest
    @Test
    public void testSecurityExceptionIsThrownWhenSelfManagedLacksPermissions() {
        PhoneAccountHandle handle = makeQuickAccountHandle(
                new ComponentName("self", "managed"), "selfie1");

        PhoneAccount accountWithoutCapability = new PhoneAccount.Builder(handle, "label")
                .setCapabilities(PhoneAccount.CAPABILITY_SELF_MANAGED)
                .build();

        assertFalse(mRegistrar.hasTransactionalCallCapabilities(accountWithoutCapability));

        try {
            mRegistrar.registerPhoneAccount(accountWithoutCapability);
            fail("should not be able to register account");
        } catch (SecurityException securityException) {
            // test pass
        } finally {
            mRegistrar.unregisterPhoneAccount(handle);
        }
    }

    @MediumTest
    @Test
    public void testSelfManagedPhoneAccountWithTransactionalOperations() {
        PhoneAccountHandle handle = makeQuickAccountHandle(
                new ComponentName("self", "managed"), "selfie1");

        PhoneAccount accountWithCapability = new PhoneAccount.Builder(handle, "label")
                .setCapabilities(PhoneAccount.CAPABILITY_SELF_MANAGED |
                        PhoneAccount.CAPABILITY_SUPPORTS_TRANSACTIONAL_OPERATIONS)
                .build();

        assertTrue(mRegistrar.hasTransactionalCallCapabilities(accountWithCapability));

        try {
            mRegistrar.registerPhoneAccount(accountWithCapability);
            PhoneAccount registeredAccount = mRegistrar.getPhoneAccountUnchecked(handle);
            assertEquals(TEST_LABEL, registeredAccount.getLabel().toString());
        } finally {
            mRegistrar.unregisterPhoneAccount(handle);
        }
    }

    @MediumTest
    @Test
    public void testRegisterPhoneAccountAmendsSelfManagedCapabilityInternally() {
        // GIVEN
        PhoneAccountHandle handle = makeQuickAccountHandle(
                new ComponentName("self", "managed"), "selfie1");
        PhoneAccount accountWithCapability = new PhoneAccount.Builder(handle, "label")
                .setCapabilities(
                        PhoneAccount.CAPABILITY_SUPPORTS_TRANSACTIONAL_OPERATIONS)
                .build();

        assertTrue(mRegistrar.hasTransactionalCallCapabilities(accountWithCapability));

        try {
            // WHEN
            mRegistrar.registerPhoneAccount(accountWithCapability);
            PhoneAccount registeredAccount = mRegistrar.getPhoneAccountUnchecked(handle);
            // THEN
            assertEquals(PhoneAccount.CAPABILITY_SELF_MANAGED, (registeredAccount.getCapabilities()
                    & PhoneAccount.CAPABILITY_SELF_MANAGED));
        } finally {
            mRegistrar.unregisterPhoneAccount(handle);
        }
    }

    /**
     * Tests to ensure that when registering a self-managed PhoneAccount, it cannot also be defined
     * as a call provider, connection manager, or sim subscription.
     * @throws Exception
     */
    @MediumTest
    @Test
    public void testSelfManagedCapabilityOverride() throws Exception {
        mComponentContextFixture.addConnectionService(makeQuickConnectionServiceComponentName(),
                Mockito.mock(IConnectionService.class));

        PhoneAccountHandle selfManagedHandle =  makeQuickAccountHandle(
                new ComponentName("self", "managed"), "selfie1");

        PhoneAccount selfManagedAccount = new PhoneAccount.Builder(selfManagedHandle, TEST_LABEL)
                .setCapabilities(PhoneAccount.CAPABILITY_SELF_MANAGED |
                        PhoneAccount.CAPABILITY_CALL_PROVIDER |
                        PhoneAccount.CAPABILITY_CONNECTION_MANAGER |
                        PhoneAccount.CAPABILITY_SIM_SUBSCRIPTION)
                .build();

        mRegistrar.registerPhoneAccount(selfManagedAccount);

        PhoneAccount registeredAccount = mRegistrar.getPhoneAccountUnchecked(selfManagedHandle);
        assertEquals(PhoneAccount.CAPABILITY_SELF_MANAGED, registeredAccount.getCapabilities());
    }

    @MediumTest
    @Test
    public void testSortSimFirst() throws Exception {
        ComponentName componentA = new ComponentName("a", "a");
        ComponentName componentB = new ComponentName("b", "b");
        mComponentContextFixture.addConnectionService(componentA,
                Mockito.mock(IConnectionService.class));
        mComponentContextFixture.addConnectionService(componentB,
                Mockito.mock(IConnectionService.class));

        PhoneAccount simAccount = new PhoneAccount.Builder(
                makeQuickAccountHandle(componentB, "2"), "2")
                .setCapabilities(PhoneAccount.CAPABILITY_CALL_PROVIDER |
                        PhoneAccount.CAPABILITY_SIM_SUBSCRIPTION)
                .setIsEnabled(true)
                .build();

        PhoneAccount nonSimAccount = new PhoneAccount.Builder(
                makeQuickAccountHandle(componentA, "1"), "1")
                .setCapabilities(PhoneAccount.CAPABILITY_CALL_PROVIDER)
                .setIsEnabled(true)
                .build();

        registerAndEnableAccount(nonSimAccount);
        registerAndEnableAccount(simAccount);

        List<PhoneAccount> accounts = mRegistrar.getAllPhoneAccounts(Process.myUserHandle(), false);
        assertTrue(accounts.get(0).getLabel().toString().equals("2"));
        assertTrue(accounts.get(1).getLabel().toString().equals("1"));
    }

    @MediumTest
    @Test
    public void testSortBySortOrder() throws Exception {
        ComponentName componentA = new ComponentName("a", "a");
        ComponentName componentB = new ComponentName("b", "b");
        ComponentName componentC = new ComponentName("c", "c");
        mComponentContextFixture.addConnectionService(componentA,
                Mockito.mock(IConnectionService.class));
        mComponentContextFixture.addConnectionService(componentB,
                Mockito.mock(IConnectionService.class));
        mComponentContextFixture.addConnectionService(componentC,
                Mockito.mock(IConnectionService.class));

        Bundle account1Extras = new Bundle();
        account1Extras.putInt(PhoneAccount.EXTRA_SORT_ORDER, 1);
        PhoneAccount account1 = new PhoneAccount.Builder(
                makeQuickAccountHandle(componentA, "c"), "c")
                .setCapabilities(PhoneAccount.CAPABILITY_CALL_PROVIDER)
                .setExtras(account1Extras)
                .build();

        Bundle account2Extras = new Bundle();
        account2Extras.putInt(PhoneAccount.EXTRA_SORT_ORDER, 2);
        PhoneAccount account2 = new PhoneAccount.Builder(
                makeQuickAccountHandle(componentB, "b"), "b")
                .setCapabilities(PhoneAccount.CAPABILITY_CALL_PROVIDER)
                .setExtras(account2Extras)
                .build();

        PhoneAccount account3 = new PhoneAccount.Builder(
                makeQuickAccountHandle(componentC, "c"), "a")
                .setCapabilities(PhoneAccount.CAPABILITY_CALL_PROVIDER)
                .build();

        registerAndEnableAccount(account3);
        registerAndEnableAccount(account2);
        registerAndEnableAccount(account1);

        List<PhoneAccount> accounts = mRegistrar.getAllPhoneAccounts(Process.myUserHandle(), false);
        assertTrue(accounts.get(0).getLabel().toString().equals("c"));
        assertTrue(accounts.get(1).getLabel().toString().equals("b"));
        assertTrue(accounts.get(2).getLabel().toString().equals("a"));
    }

    @MediumTest
    @Test
    public void testSortByLabel() throws Exception {
        ComponentName componentA = new ComponentName("a", "a");
        ComponentName componentB = new ComponentName("b", "b");
        ComponentName componentC = new ComponentName("c", "c");
        mComponentContextFixture.addConnectionService(componentA,
                Mockito.mock(IConnectionService.class));
        mComponentContextFixture.addConnectionService(componentB,
                Mockito.mock(IConnectionService.class));
        mComponentContextFixture.addConnectionService(componentC,
                Mockito.mock(IConnectionService.class));

        PhoneAccount account1 = new PhoneAccount.Builder(makeQuickAccountHandle(componentA, "c"),
                "c")
                .setCapabilities(PhoneAccount.CAPABILITY_CALL_PROVIDER)
                .build();

        PhoneAccount account2 = new PhoneAccount.Builder(makeQuickAccountHandle(componentB, "b"),
                "b")
                .setCapabilities(PhoneAccount.CAPABILITY_CALL_PROVIDER)
                .build();

        PhoneAccount account3 = new PhoneAccount.Builder(makeQuickAccountHandle(componentC, "a"),
                "a")
                .setCapabilities(PhoneAccount.CAPABILITY_CALL_PROVIDER)
                .build();

        registerAndEnableAccount(account1);
        registerAndEnableAccount(account2);
        registerAndEnableAccount(account3);

        List<PhoneAccount> accounts = mRegistrar.getAllPhoneAccounts(Process.myUserHandle(), false);
        assertTrue(accounts.get(0).getLabel().toString().equals("a"));
        assertTrue(accounts.get(1).getLabel().toString().equals("b"));
        assertTrue(accounts.get(2).getLabel().toString().equals("c"));
    }

    @MediumTest
    @Test
    public void testSortAll() throws Exception {
        ComponentName componentA = new ComponentName("a", "a");
        ComponentName componentB = new ComponentName("b", "b");
        ComponentName componentC = new ComponentName("c", "c");
        ComponentName componentW = new ComponentName("w", "w");
        ComponentName componentX = new ComponentName("x", "x");
        ComponentName componentY = new ComponentName("y", "y");
        ComponentName componentZ = new ComponentName("z", "z");
        mComponentContextFixture.addConnectionService(componentA,
                Mockito.mock(IConnectionService.class));
        mComponentContextFixture.addConnectionService(componentB,
                Mockito.mock(IConnectionService.class));
        mComponentContextFixture.addConnectionService(componentC,
                Mockito.mock(IConnectionService.class));
        mComponentContextFixture.addConnectionService(componentW,
                Mockito.mock(IConnectionService.class));
        mComponentContextFixture.addConnectionService(componentX,
                Mockito.mock(IConnectionService.class));
        mComponentContextFixture.addConnectionService(componentY,
                Mockito.mock(IConnectionService.class));
        mComponentContextFixture.addConnectionService(componentZ,
                Mockito.mock(IConnectionService.class));

        Bundle account1Extras = new Bundle();
        account1Extras.putInt(PhoneAccount.EXTRA_SORT_ORDER, 2);
        PhoneAccount account1 = new PhoneAccount.Builder(makeQuickAccountHandle(
                makeQuickConnectionServiceComponentName(), "y"), "y")
                .setCapabilities(PhoneAccount.CAPABILITY_CALL_PROVIDER |
                        PhoneAccount.CAPABILITY_SIM_SUBSCRIPTION)
                .setExtras(account1Extras)
                .build();

        Bundle account2Extras = new Bundle();
        account2Extras.putInt(PhoneAccount.EXTRA_SORT_ORDER, 1);
        PhoneAccount account2 = new PhoneAccount.Builder(makeQuickAccountHandle(
                makeQuickConnectionServiceComponentName(), "z"), "z")
                .setCapabilities(PhoneAccount.CAPABILITY_CALL_PROVIDER |
                        PhoneAccount.CAPABILITY_SIM_SUBSCRIPTION)
                .setExtras(account2Extras)
                .build();

        PhoneAccount account3 = new PhoneAccount.Builder(makeQuickAccountHandle(
                makeQuickConnectionServiceComponentName(), "x"), "x")
                .setCapabilities(PhoneAccount.CAPABILITY_CALL_PROVIDER |
                        PhoneAccount.CAPABILITY_SIM_SUBSCRIPTION)
                .build();

        PhoneAccount account4 = new PhoneAccount.Builder(makeQuickAccountHandle(
                makeQuickConnectionServiceComponentName(), "w"), "w")
                .setCapabilities(PhoneAccount.CAPABILITY_CALL_PROVIDER |
                        PhoneAccount.CAPABILITY_SIM_SUBSCRIPTION)
                .build();

        PhoneAccount account5 = new PhoneAccount.Builder(makeQuickAccountHandle(
                makeQuickConnectionServiceComponentName(), "b"), "b")
                .setCapabilities(PhoneAccount.CAPABILITY_CALL_PROVIDER)
                .build();

        PhoneAccount account6 = new PhoneAccount.Builder(makeQuickAccountHandle(
                makeQuickConnectionServiceComponentName(), "c"), "a")
                .setCapabilities(PhoneAccount.CAPABILITY_CALL_PROVIDER)
                .build();

        registerAndEnableAccount(account1);
        registerAndEnableAccount(account2);
        registerAndEnableAccount(account3);
        registerAndEnableAccount(account4);
        registerAndEnableAccount(account5);
        registerAndEnableAccount(account6);

        List<PhoneAccount> accounts = mRegistrar.getAllPhoneAccounts(Process.myUserHandle(), false);
        // Sim accts ordered by sort order first
        assertTrue(accounts.get(0).getLabel().toString().equals("z"));
        assertTrue(accounts.get(1).getLabel().toString().equals("y"));

        // Sim accts with no sort order next
        assertTrue(accounts.get(2).getLabel().toString().equals("w"));
        assertTrue(accounts.get(3).getLabel().toString().equals("x"));

        // Other accts sorted by label next
        assertTrue(accounts.get(4).getLabel().toString().equals("a"));
        assertTrue(accounts.get(5).getLabel().toString().equals("b"));
    }

    /**
     * Tests {@link PhoneAccountRegistrar#getCallCapablePhoneAccounts(String, boolean, UserHandle)}
     * to ensure disabled accounts are filtered out of results when requested.
     * @throws Exception
     */
    @MediumTest
    @Test
    public void testGetByEnabledState() throws Exception {
        mComponentContextFixture.addConnectionService(makeQuickConnectionServiceComponentName(),
                Mockito.mock(IConnectionService.class));
        mRegistrar.registerPhoneAccount(makeQuickAccountBuilder("id1", 1, null)
                .setCapabilities(PhoneAccount.CAPABILITY_CALL_PROVIDER)
                .build());

        assertEquals(0, mRegistrar.getCallCapablePhoneAccounts(PhoneAccount.SCHEME_TEL,
                false /* includeDisabled */, Process.myUserHandle(), false).size());
        assertEquals(1, mRegistrar.getCallCapablePhoneAccounts(PhoneAccount.SCHEME_TEL,
                true /* includeDisabled */, Process.myUserHandle(), false).size());
    }

    /**
     * Tests {@link PhoneAccountRegistrar#getCallCapablePhoneAccounts(String, boolean, UserHandle)}
     * to ensure scheme filtering operates.
     * @throws Exception
     */
    @MediumTest
    @Test
    public void testGetByScheme() throws Exception {
        mComponentContextFixture.addConnectionService(makeQuickConnectionServiceComponentName(),
                Mockito.mock(IConnectionService.class));
        registerAndEnableAccount(makeQuickAccountBuilder("id1", 1, null)
                .setCapabilities(PhoneAccount.CAPABILITY_CALL_PROVIDER)
                .setSupportedUriSchemes(Arrays.asList(PhoneAccount.SCHEME_SIP))
                .build());
        registerAndEnableAccount(makeQuickAccountBuilder("id2", 2, null)
                .setCapabilities(PhoneAccount.CAPABILITY_CALL_PROVIDER)
                .setSupportedUriSchemes(Arrays.asList(PhoneAccount.SCHEME_TEL))
                .build());

        assertEquals(1, mRegistrar.getCallCapablePhoneAccounts(PhoneAccount.SCHEME_SIP,
                false /* includeDisabled */, Process.myUserHandle(), false).size());
        assertEquals(1, mRegistrar.getCallCapablePhoneAccounts(PhoneAccount.SCHEME_TEL,
                false /* includeDisabled */, Process.myUserHandle(), false).size());
        assertEquals(2, mRegistrar.getCallCapablePhoneAccounts(null, false /* includeDisabled */,
                Process.myUserHandle(), false).size());
    }

    /**
     * Tests {@link PhoneAccountRegistrar#getCallCapablePhoneAccounts(String, boolean, UserHandle,
     * int)} to ensure capability filtering operates.
     * @throws Exception
     */
    @MediumTest
    @Test
    public void testGetByCapability() throws Exception {
        mComponentContextFixture.addConnectionService(makeQuickConnectionServiceComponentName(),
                Mockito.mock(IConnectionService.class));
        registerAndEnableAccount(makeQuickAccountBuilder("id1", 1, null)
                .setCapabilities(PhoneAccount.CAPABILITY_CALL_PROVIDER
                        | PhoneAccount.CAPABILITY_VIDEO_CALLING)
                .setSupportedUriSchemes(Arrays.asList(PhoneAccount.SCHEME_SIP))
                .build());
        registerAndEnableAccount(makeQuickAccountBuilder("id2", 2, null)
                .setCapabilities(PhoneAccount.CAPABILITY_CALL_PROVIDER)
                .setSupportedUriSchemes(Arrays.asList(PhoneAccount.SCHEME_SIP))
                .build());

        assertEquals(1, mRegistrar.getCallCapablePhoneAccounts(PhoneAccount.SCHEME_SIP,
                false /* includeDisabled */, Process.myUserHandle(), false).size(),
                PhoneAccount.CAPABILITY_VIDEO_CALLING);
        assertEquals(2, mRegistrar.getCallCapablePhoneAccounts(PhoneAccount.SCHEME_SIP,
                false /* includeDisabled */, Process.myUserHandle(), false)
                .size(), 0 /* none extra */);
        assertEquals(0, mRegistrar.getCallCapablePhoneAccounts(PhoneAccount.SCHEME_SIP,
                false /* includeDisabled */, Process.myUserHandle(), false).size(),
                PhoneAccount.CAPABILITY_RTT);
    }

    /**
     * Tests {@link PhoneAccount#equals(Object)} operator.
     * @throws Exception
     */
    @MediumTest
    @Test
    public void testPhoneAccountEquality() throws Exception {
        PhoneAccountHandle handle = new PhoneAccountHandle(new ComponentName("foo", "bar"), "id");
        PhoneAccount.Builder builder = new PhoneAccount.Builder(handle, "label");
        builder.addSupportedUriScheme("tel");
        builder.setAddress(Uri.fromParts("tel", "6505551212", null));
        builder.setCapabilities(PhoneAccount.CAPABILITY_CALL_PROVIDER);
        Bundle extras = new Bundle();
        extras.putInt("INT", 1);
        extras.putString("STR", "str");
        builder.setExtras(extras);
        builder.setGroupId("group");
        builder.setHighlightColor(1);
        builder.setShortDescription("short");
        builder.setSubscriptionAddress(Uri.fromParts("tel", "6505551213", null));
        builder.setSupportedAudioRoutes(2);

        PhoneAccount account1 = builder.build();
        PhoneAccount account2 = builder.build();
        assertEquals(account1, account2);
    }

    /**
     * Tests {@link PhoneAccountHandle#areFromSamePackage(PhoneAccountHandle,
     * PhoneAccountHandle)} comparison.
     */
    @SmallTest
    @Test
    public void testSamePhoneAccountHandlePackage() {
        PhoneAccountHandle a = new PhoneAccountHandle(new ComponentName("packageA", "class1"),
                "id1");
        PhoneAccountHandle b = new PhoneAccountHandle(new ComponentName("packageA", "class2"),
                "id2");
        PhoneAccountHandle c = new PhoneAccountHandle(new ComponentName("packageA", "class1"),
                "id3");
        PhoneAccountHandle d = new PhoneAccountHandle(new ComponentName("packageB", "class1"),
                "id1");

        assertTrue(PhoneAccountHandle.areFromSamePackage(null, null));
        assertTrue(PhoneAccountHandle.areFromSamePackage(a, b));
        assertTrue(PhoneAccountHandle.areFromSamePackage(a, c));
        assertTrue(PhoneAccountHandle.areFromSamePackage(b, c));
        assertFalse(PhoneAccountHandle.areFromSamePackage(a, d));
        assertFalse(PhoneAccountHandle.areFromSamePackage(b, d));
        assertFalse(PhoneAccountHandle.areFromSamePackage(c, d));
        assertFalse(PhoneAccountHandle.areFromSamePackage(a, null));
        assertFalse(PhoneAccountHandle.areFromSamePackage(b, null));
        assertFalse(PhoneAccountHandle.areFromSamePackage(c, null));
        assertFalse(PhoneAccountHandle.areFromSamePackage(null, d));
        assertFalse(PhoneAccountHandle.areFromSamePackage(null, d));
        assertFalse(PhoneAccountHandle.areFromSamePackage(null, d));
    }

    /**
     * Tests {@link PhoneAccountRegistrar#cleanupOrphanedPhoneAccounts } cleans up / deletes an
     * orphan account.
     */
    @Test
    public void testCleanUpOrphanAccounts() throws Exception {
        // GIVEN
        mComponentContextFixture.addConnectionService(makeQuickConnectionServiceComponentName(),
                Mockito.mock(IConnectionService.class));

        List<UserHandle> users = Arrays.asList(new UserHandle(0),
                new UserHandle(1000));

        PhoneAccount pa1 = new PhoneAccount.Builder(
                new PhoneAccountHandle(new ComponentName(PACKAGE_1, COMPONENT_NAME), "1234",
                        users.get(0)), "l1").build();
        PhoneAccount pa2 = new PhoneAccount.Builder(
                new PhoneAccountHandle(new ComponentName(PACKAGE_2, COMPONENT_NAME), "5678",
                        users.get(1)), "l2").build();


        registerAndEnableAccount(pa1);
        registerAndEnableAccount(pa2);

        assertEquals(1, mRegistrar.getAllPhoneAccounts(users.get(0), false).size());
        assertEquals(1, mRegistrar.getAllPhoneAccounts(users.get(1), false).size());


        // WHEN
        when(mContext.getPackageManager().getPackageInfo(PACKAGE_1, 0))
                .thenReturn(new PackageInfo());

        when(mContext.getPackageManager().getPackageInfo(PACKAGE_2, 0))
                .thenThrow(new PackageManager.NameNotFoundException());

        when(UserManager.get(mContext).getSerialNumberForUser(users.get(0)))
                .thenReturn(0L);

        when(UserManager.get(mContext).getSerialNumberForUser(users.get(1)))
                .thenReturn(-1L);

        // THEN
        int deletedAccounts = mRegistrar.cleanupOrphanedPhoneAccounts();
        assertEquals(1, deletedAccounts);
    }

    @Test
    public void testGetSimPhoneAccountsFromSimCallManager() throws Exception {
        // Register the SIM PhoneAccounts
        mComponentContextFixture.addConnectionService(
                makeQuickConnectionServiceComponentName(), Mockito.mock(IConnectionService.class));
        PhoneAccount sim1Account = makeQuickSimAccount(1);
        PhoneAccountHandle sim1Handle = sim1Account.getAccountHandle();
        registerAndEnableAccount(sim1Account);
        PhoneAccount sim2Account = makeQuickSimAccount(2);
        PhoneAccountHandle sim2Handle = sim2Account.getAccountHandle();
        registerAndEnableAccount(sim2Account);

        assertEquals(
            List.of(sim1Handle, sim2Handle), mRegistrar.getSimPhoneAccountsOfCurrentUser());

        // Set up the SIM call manager app + carrier configs
        ComponentName simCallManagerComponent =
                new ComponentName("com.carrier.app", "CarrierConnectionService");
        PhoneAccountHandle simCallManagerHandle =
                makeQuickAccountHandle(simCallManagerComponent, "sim-call-manager");
        setSimCallManagerCarrierConfig(
                1, new ComponentName("com.other.carrier", "OtherConnectionService"));
        setSimCallManagerCarrierConfig(2, simCallManagerComponent);

        // Since SIM 1 names another app, so we only get the handle for SIM 2
        assertEquals(
                List.of(sim2Handle),
                mRegistrar.getSimPhoneAccountsFromSimCallManager(simCallManagerHandle));
        // We do exact component matching, not just package name matching
        assertEquals(
                List.of(),
                mRegistrar.getSimPhoneAccountsFromSimCallManager(
                        makeQuickAccountHandle(
                                new ComponentName("com.carrier.app", "SomeOtherUnrelatedService"),
                                "same-pkg-but-diff-svc")));

        // Results are identical after we register the PhoneAccount
        mComponentContextFixture.addConnectionService(
                simCallManagerComponent, Mockito.mock(IConnectionService.class));
        PhoneAccount simCallManagerAccount =
                new PhoneAccount.Builder(simCallManagerHandle, "SIM call manager")
                        .setCapabilities(PhoneAccount.CAPABILITY_CONNECTION_MANAGER)
                        .build();
        mRegistrar.registerPhoneAccount(simCallManagerAccount);
        assertEquals(
                List.of(sim2Handle),
                mRegistrar.getSimPhoneAccountsFromSimCallManager(simCallManagerHandle));
    }

    @Test
    public void testMaybeNotifyTelephonyForVoiceServiceState() throws Exception {
        // Register the SIM PhoneAccounts
        mComponentContextFixture.addConnectionService(
                makeQuickConnectionServiceComponentName(), Mockito.mock(IConnectionService.class));
        PhoneAccount sim1Account = makeQuickSimAccount(1);
        registerAndEnableAccount(sim1Account);
        PhoneAccount sim2Account = makeQuickSimAccount(2);
        registerAndEnableAccount(sim2Account);
        // Telephony is notified by default when new SIM accounts are registered
        verify(mComponentContextFixture.getTelephonyManager(), times(2))
                .setVoiceServiceStateOverride(false);
        clearInvocations(mComponentContextFixture.getTelephonyManager());

        // Set up the SIM call manager app + carrier configs
        ComponentName simCallManagerComponent =
                new ComponentName("com.carrier.app", "CarrierConnectionService");
        PhoneAccountHandle simCallManagerHandle =
                makeQuickAccountHandle(simCallManagerComponent, "sim-call-manager");
        mComponentContextFixture.addConnectionService(
                simCallManagerComponent, Mockito.mock(IConnectionService.class));
        setSimCallManagerCarrierConfig(1, simCallManagerComponent);
        setSimCallManagerCarrierConfig(2, simCallManagerComponent);

        // When the SIM call manager is registered without the SUPPORTS capability, telephony is
        // still notified for consistency (e.g. runtime capability removal + re-registration).
        PhoneAccount simCallManagerAccount =
                new PhoneAccount.Builder(simCallManagerHandle, "SIM call manager")
                        .setCapabilities(PhoneAccount.CAPABILITY_CONNECTION_MANAGER)
                        .build();
        mRegistrar.registerPhoneAccount(simCallManagerAccount);
        verify(mComponentContextFixture.getTelephonyManager(), times(2))
                .setVoiceServiceStateOverride(false);
        clearInvocations(mComponentContextFixture.getTelephonyManager());

        // Adding the SUPPORTS capability causes the SIMs to get notified with false again for
        // consistency purposes
        simCallManagerAccount =
                copyPhoneAccountAndAddCapabilities(
                        simCallManagerAccount,
                        PhoneAccount.CAPABILITY_SUPPORTS_VOICE_CALLING_INDICATIONS);
        mRegistrar.registerPhoneAccount(simCallManagerAccount);
        verify(mComponentContextFixture.getTelephonyManager(), times(2))
                .setVoiceServiceStateOverride(false);
        clearInvocations(mComponentContextFixture.getTelephonyManager());

        // Adding the AVAILABLE capability updates the SIMs again, this time with hasService = true
        simCallManagerAccount =
                copyPhoneAccountAndAddCapabilities(
                        simCallManagerAccount, PhoneAccount.CAPABILITY_VOICE_CALLING_AVAILABLE);
        mRegistrar.registerPhoneAccount(simCallManagerAccount);
        verify(mComponentContextFixture.getTelephonyManager(), times(2))
                .setVoiceServiceStateOverride(true);
        clearInvocations(mComponentContextFixture.getTelephonyManager());

        // Removing a SIM account does nothing, regardless of SIM call manager capabilities
        mRegistrar.unregisterPhoneAccount(sim1Account.getAccountHandle());
        verify(mComponentContextFixture.getTelephonyManager(), never())
                .setVoiceServiceStateOverride(anyBoolean());
        clearInvocations(mComponentContextFixture.getTelephonyManager());

        // Adding a SIM account while a SIM call manager with both capabilities is registered causes
        // a call to telephony with hasService = true
        mRegistrar.registerPhoneAccount(sim1Account);
        verify(mComponentContextFixture.getTelephonyManager(), times(1))
                .setVoiceServiceStateOverride(true);
        clearInvocations(mComponentContextFixture.getTelephonyManager());

        // Removing the SIM call manager while it has both capabilities causes a call to telephony
        // with hasService = false
        mRegistrar.unregisterPhoneAccount(simCallManagerHandle);
        verify(mComponentContextFixture.getTelephonyManager(), times(2))
                .setVoiceServiceStateOverride(false);
        clearInvocations(mComponentContextFixture.getTelephonyManager());

        // Removing the SIM call manager while it has the SUPPORTS capability but not AVAILABLE
        // still causes a call to telephony with hasService = false for consistency
        simCallManagerAccount =
                copyPhoneAccountAndRemoveCapabilities(
                        simCallManagerAccount, PhoneAccount.CAPABILITY_VOICE_CALLING_AVAILABLE);
        mRegistrar.registerPhoneAccount(simCallManagerAccount);
        clearInvocations(mComponentContextFixture.getTelephonyManager()); // from re-registration
        mRegistrar.unregisterPhoneAccount(simCallManagerHandle);
        verify(mComponentContextFixture.getTelephonyManager(), times(2))
                .setVoiceServiceStateOverride(false);
        clearInvocations(mComponentContextFixture.getTelephonyManager());

        // Finally, removing the SIM call manager while it has neither capability still causes a
        // call to telephony with hasService = false for consistency
        simCallManagerAccount =
                copyPhoneAccountAndRemoveCapabilities(
                        simCallManagerAccount,
                        PhoneAccount.CAPABILITY_SUPPORTS_VOICE_CALLING_INDICATIONS);
        mRegistrar.registerPhoneAccount(simCallManagerAccount);
        clearInvocations(mComponentContextFixture.getTelephonyManager()); // from re-registration
        mRegistrar.unregisterPhoneAccount(simCallManagerHandle);
        verify(mComponentContextFixture.getTelephonyManager(), times(2))
                .setVoiceServiceStateOverride(false);
        clearInvocations(mComponentContextFixture.getTelephonyManager());
    }

    /**
     * Test PhoneAccountHandle Migration Logic.
     */
    @Test
    public void testPhoneAccountMigration() throws Exception {
        PhoneAccountRegistrar.State testState = makeQuickStateWithTelephonyPhoneAccountHandle();
        final int mTestPhoneAccountHandleSubIdInt = 123;
        // Mock SubscriptionManager
        SubscriptionInfo subscriptionInfo = new SubscriptionInfo(
                mTestPhoneAccountHandleSubIdInt, "id0", 1, "a", "b", 1, 1, "test",
                        1, null, null, null, null, false, null, null);
        List<SubscriptionInfo> subscriptionInfoList = new ArrayList<>();
        subscriptionInfoList.add(subscriptionInfo);
        when(mSubscriptionManager.getAllSubscriptionInfoList()).thenReturn(subscriptionInfoList);
        mRegistrar.migratePhoneAccountHandle(testState);
        Collection<DefaultPhoneAccountHandle> defaultPhoneAccountHandles
                = testState.defaultOutgoingAccountHandles.values();
        DefaultPhoneAccountHandle defaultPhoneAccountHandle
                = defaultPhoneAccountHandles.iterator().next();
        assertEquals(Integer.toString(mTestPhoneAccountHandleSubIdInt),
                defaultPhoneAccountHandle.phoneAccountHandle.getId());
    }

    /**
     * Test that an {@link IllegalArgumentException} is thrown when a package registers a
     * {@link PhoneAccountHandle} with a { PhoneAccountHandle#packageName} that is over the
     * character limit set
     */
    @Test
    public void testInvalidPhoneAccountHandlePackageNameThrowsException() {
        // GIVEN
        String invalidPackageName = INVALID_STR;
        PhoneAccountHandle handle = makeQuickAccountHandle(
                new ComponentName(invalidPackageName, this.getClass().getName()), TEST_ID);
        PhoneAccount.Builder builder = makeBuilderWithBindCapabilities(handle);

        // THEN
        try {
            PhoneAccount account = builder.build();
            assertEquals(invalidPackageName,
                    account.getAccountHandle().getComponentName().getPackageName());
            mRegistrar.registerPhoneAccount(account);
            fail("failed to throw IllegalArgumentException");
        } catch (IllegalArgumentException e) {
            // pass test
        } finally {
            mRegistrar.unregisterPhoneAccount(handle);
        }
    }

    /**
     * Test that an {@link IllegalArgumentException} is thrown when a package registers a
     * {@link PhoneAccountHandle} with a { PhoneAccountHandle#className} that is over the
     * character limit set
     */
    @Test
    public void testInvalidPhoneAccountHandleClassNameThrowsException() {
        // GIVEN
        String invalidClassName = INVALID_STR;
        PhoneAccountHandle handle = makeQuickAccountHandle(
                new ComponentName(this.getClass().getPackageName(), invalidClassName), TEST_ID);
        PhoneAccount.Builder builder = makeBuilderWithBindCapabilities(handle);

        // THEN
        try {
            PhoneAccount account = builder.build();
            assertEquals(invalidClassName,
                    account.getAccountHandle().getComponentName().getClassName());
            mRegistrar.registerPhoneAccount(account);
            fail("failed to throw IllegalArgumentException");
        } catch (IllegalArgumentException e) {
            // pass test
        } finally {
            mRegistrar.unregisterPhoneAccount(handle);
        }
    }

    /**
     * Test that an {@link IllegalArgumentException} is thrown when a package registers a
     * {@link PhoneAccountHandle} with a { PhoneAccount#mId} that is over the character limit set
     */
    @Test
    public void testInvalidPhoneAccountHandleIdThrowsException() {
        // GIVEN
        String invalidId = INVALID_STR;
        PhoneAccountHandle handle = makeQuickAccountHandle(invalidId);
        PhoneAccount.Builder builder = makeBuilderWithBindCapabilities(handle);

        // THEN
        try {
            PhoneAccount account = builder.build();
            assertEquals(invalidId, account.getAccountHandle().getId());
            mRegistrar.registerPhoneAccount(account);
            fail("failed to throw IllegalArgumentException");
        } catch (IllegalArgumentException e) {
            // pass test
        } finally {
            mRegistrar.unregisterPhoneAccount(handle);
        }
    }

    /**
     * Test that an {@link IllegalArgumentException} is thrown when a package registers a
     * {@link PhoneAccount} with a { PhoneAccount#mLabel} that is over the character limit set
     */
    @Test
    public void testInvalidLabelThrowsException() {
        // GIVEN
        String invalidLabel = INVALID_STR;
        PhoneAccountHandle handle = makeQuickAccountHandle(TEST_ID);
        PhoneAccount.Builder builder = new PhoneAccount.Builder(handle, invalidLabel)
                .setCapabilities(PhoneAccount.CAPABILITY_SUPPORTS_TRANSACTIONAL_OPERATIONS);

        // WHEN
        when(mAppLabelProxy.getAppLabel(anyString())).thenReturn(invalidLabel);

        // THEN
        try {
            PhoneAccount account = builder.build();
            assertEquals(invalidLabel, account.getLabel());
            mRegistrar.registerPhoneAccount(account);
            fail("failed to throw IllegalArgumentException");
        } catch (IllegalArgumentException e) {
            // pass test
        } finally {
            mRegistrar.unregisterPhoneAccount(handle);
        }
    }

    /**
     * Test that an {@link IllegalArgumentException} is thrown when a package registers a
     * {@link PhoneAccount} with a {PhoneAccount#mShortDescription} that is over the character
     * limit set
     */
    @Test
    public void testInvalidShortDescriptionThrowsException() {
        // GIVEN
        String invalidShortDescription = INVALID_STR;
        PhoneAccountHandle handle = makeQuickAccountHandle(TEST_ID);
        PhoneAccount.Builder builder = makeBuilderWithBindCapabilities(handle)
                .setShortDescription(invalidShortDescription);

        // THEN
        try {
            PhoneAccount account = builder.build();
            assertEquals(invalidShortDescription, account.getShortDescription());
            mRegistrar.registerPhoneAccount(account);
            fail("failed to throw IllegalArgumentException");
        } catch (IllegalArgumentException e) {
            // pass test
        } finally {
            mRegistrar.unregisterPhoneAccount(handle);
        }
    }

    /**
     * Test that an {@link IllegalArgumentException} is thrown when a package registers a
     * {@link PhoneAccount} with a {PhoneAccount#mGroupId} that is over the character limit set
     */
    @Test
    public void testInvalidGroupIdThrowsException() {
        // GIVEN
        String invalidGroupId = INVALID_STR;
        PhoneAccountHandle handle = makeQuickAccountHandle(TEST_ID);
        PhoneAccount.Builder builder = makeBuilderWithBindCapabilities(handle)
                .setGroupId(invalidGroupId);

        // THEN
        try {
            PhoneAccount account = builder.build();
            assertEquals(invalidGroupId, account.getGroupId());
            mRegistrar.registerPhoneAccount(account);
            fail("failed to throw IllegalArgumentException");
        } catch (IllegalArgumentException e) {
            // pass test
        } finally {
            mRegistrar.unregisterPhoneAccount(handle);
        }
    }

    /**
     * Test that an {@link IllegalArgumentException} is thrown when a package registers a
     * {@link PhoneAccount} with a {PhoneAccount#mExtras} that is over the character limit set
     */
    @Test
    public void testInvalidExtraStringKeyThrowsException() {
        // GIVEN
        String invalidBundleKey = INVALID_STR;
        String keyValue = "value";
        Bundle extras = new Bundle();
        extras.putString(invalidBundleKey, keyValue);
        PhoneAccountHandle handle = makeQuickAccountHandle(TEST_ID);
        PhoneAccount.Builder builder = makeBuilderWithBindCapabilities(handle)
                .setExtras(extras);

        // THEN
        try {
            PhoneAccount account = builder.build();
            assertEquals(keyValue, account.getExtras().getString(invalidBundleKey));
            mRegistrar.registerPhoneAccount(account);
            fail("failed to throw IllegalArgumentException");
        } catch (IllegalArgumentException e) {
            // pass test
        } finally {
            mRegistrar.unregisterPhoneAccount(handle);
        }
    }

    /**
     * Test that an {@link IllegalArgumentException} is thrown when a package registers a
     * {@link PhoneAccount} with a {PhoneAccount#mExtras} that is over the character limit set
     */
    @Test
    public void testInvalidExtraStringValueThrowsException() {
        // GIVEN
        String extrasKey = "ExtrasStringKey";
        String invalidBundleValue = INVALID_STR;
        Bundle extras = new Bundle();
        extras.putString(extrasKey, invalidBundleValue);
        PhoneAccountHandle handle = makeQuickAccountHandle(TEST_ID);
        PhoneAccount.Builder builder = makeBuilderWithBindCapabilities(handle)
                .setExtras(extras);

        // THEN
        try {
            PhoneAccount account = builder.build();
            assertEquals(invalidBundleValue, account.getExtras().getString(extrasKey));
            mRegistrar.registerPhoneAccount(account);
            fail("failed to throw IllegalArgumentException");
        } catch (IllegalArgumentException e) {
            // pass test
        } finally {
            mRegistrar.unregisterPhoneAccount(handle);
        }
    }

    /**
     * Test that an {@link IllegalArgumentException} is thrown when a package registers a
     * {@link PhoneAccount} with a {PhoneAccount#mExtras} that is over the (key,value) pair limit
     */
    @Test
    public void testInvalidExtraElementsExceedsLimitAndThrowsException() {
        // GIVEN
        int invalidBundleExtrasLimit =
                PhoneAccountRegistrar.MAX_PHONE_ACCOUNT_EXTRAS_KEY_PAIR_LIMIT + 1;
        Bundle extras = new Bundle();
        for (int i = 0; i < invalidBundleExtrasLimit; i++) {
            extras.putString(UUID.randomUUID().toString(), "value");
        }
        PhoneAccountHandle handle = makeQuickAccountHandle(TEST_ID);
        PhoneAccount.Builder builder = makeBuilderWithBindCapabilities(handle)
                .setExtras(extras);
        // THEN
        try {
            PhoneAccount account = builder.build();
            assertEquals(invalidBundleExtrasLimit, account.getExtras().size());
            mRegistrar.registerPhoneAccount(account);
            fail("failed to throw IllegalArgumentException");
        } catch (IllegalArgumentException e) {
            // Test Pass
        } finally {
            mRegistrar.unregisterPhoneAccount(handle);
        }
    }

    /**
     * Ensure an IllegalArgumentException is thrown when adding more than 10 schemes for a single
     * account
     */
    @Test
    public void testLimitOnSchemeCount() {
        PhoneAccountHandle handle = makeQuickAccountHandle(TEST_ID);
        PhoneAccount.Builder builder = new PhoneAccount.Builder(handle, TEST_LABEL);
        for (int i = 0; i < PhoneAccountRegistrar.MAX_PHONE_ACCOUNT_REGISTRATIONS + 1; i++) {
            builder.addSupportedUriScheme(Integer.toString(i));
        }
        try {
            mRegistrar.enforceLimitsOnSchemes(builder.build());
            fail("should have hit exception in enforceLimitOnSchemes");
        } catch (IllegalArgumentException e) {
            // pass test
        }
    }

    /**
     * Ensure an IllegalArgumentException is thrown when adding more 256 chars for a single
     * account
     */
    @Test
    public void testLimitOnSchemeLength() {
        PhoneAccountHandle handle = makeQuickAccountHandle(TEST_ID);
        PhoneAccount.Builder builder = new PhoneAccount.Builder(handle, TEST_LABEL);
        builder.addSupportedUriScheme(INVALID_STR);
        try {
            mRegistrar.enforceLimitsOnSchemes(builder.build());
            fail("should have hit exception in enforceLimitOnSchemes");
        } catch (IllegalArgumentException e) {
            // pass test
        }
    }

    /**
     * Ensure an IllegalArgumentException is thrown when adding an address over the limit
     */
    @Test
    public void testLimitOnAddress() {
        String text = "a".repeat(100);
        PhoneAccountHandle handle = makeQuickAccountHandle(TEST_ID);
        PhoneAccount.Builder builder = makeBuilderWithBindCapabilities(handle)
                .setAddress(Uri.fromParts(text, text, text));
        try {
            mRegistrar.registerPhoneAccount(builder.build());
            fail("failed to throw IllegalArgumentException");
        } catch (IllegalArgumentException e) {
            // pass test
        }
        finally {
            mRegistrar.unregisterPhoneAccount(handle);
        }
    }

    /**
     * Ensure an IllegalArgumentException is thrown when an Icon that throws an IOException is given
     */
    @Test
    public void testLimitOnIcon() throws Exception {
        Icon mockIcon = mock(Icon.class);
        // GIVEN
        PhoneAccount.Builder builder = makeBuilderWithBindCapabilities(
                makeQuickAccountHandle(TEST_ID)).setIcon(mockIcon);
        try {
            // WHEN
            Mockito.doThrow(new IOException())
                    .when(mockIcon).writeToStream(any(OutputStream.class));
            //THEN
            mRegistrar.enforceIconSizeLimit(builder.build());
            fail("failed to throw IllegalArgumentException");
        } catch (IllegalArgumentException e) {
            // pass test
            assertTrue(e.getMessage().contains(PhoneAccountRegistrar.ICON_ERROR_MSG));
        }
    }

    /**
     * Ensure an IllegalArgumentException is thrown when providing a SubscriptionAddress that
     * exceeds the PhoneAccountRegistrar limit.
     */
    @Test
    public void testLimitOnSubscriptionAddress() throws Exception {
        String text = "a".repeat(100);
        PhoneAccount.Builder builder =  new PhoneAccount.Builder(makeQuickAccountHandle(TEST_ID),
                TEST_LABEL).setSubscriptionAddress(Uri.fromParts(text, text, text));
        try {
            mRegistrar.enforceCharacterLimit(builder.build());
            fail("failed to throw IllegalArgumentException");
        } catch (IllegalArgumentException e) {
            // pass test
        }
    }

    /**
     * PhoneAccounts with CAPABILITY_SUPPORTS_TRANSACTIONAL_OPERATIONS do not require a
     * ConnectionService. Ensure that such an account can be registered and fetched.
     */
    @Test
    public void testFetchingTransactionalAccounts() {
        PhoneAccount account = makeBuilderWithBindCapabilities(
                makeQuickAccountHandle(TEST_ID)).build();

        try {
            assertEquals(0, mRegistrar.getAllPhoneAccounts(null, true).size());
            registerAndEnableAccount(account);
            assertEquals(1, mRegistrar.getAllPhoneAccounts(null, true).size());
        } finally {
            mRegistrar.unregisterPhoneAccount(account.getAccountHandle());
        }
    }

    private static PhoneAccount.Builder makeBuilderWithBindCapabilities(PhoneAccountHandle handle) {
        return new PhoneAccount.Builder(handle, TEST_LABEL)
                .setCapabilities(PhoneAccount.CAPABILITY_SUPPORTS_TRANSACTIONAL_OPERATIONS);
    }

    private static ComponentName makeQuickConnectionServiceComponentName() {
        return new ComponentName(
                "com.android.server.telecom.tests",
                "com.android.server.telecom.tests.MockConnectionService");
    }

    private static PhoneAccountHandle makeQuickAccountHandle(String id) {
        return makeQuickAccountHandle(makeQuickConnectionServiceComponentName(), id);
    }

    private static PhoneAccountHandle makeQuickAccountHandle(ComponentName name, String id) {
        return new PhoneAccountHandle(name, id, Process.myUserHandle());
    }

    private static PhoneAccountHandle makeQuickAccountHandleForUser(
            String id, UserHandle userHandle) {
        return new PhoneAccountHandle(makeQuickConnectionServiceComponentName(), id, userHandle);
    }

    private PhoneAccount.Builder makeQuickAccountBuilder(
            String id, int idx, UserHandle userHandle) {
        return new PhoneAccount.Builder(
                userHandle == null
                        ? makeQuickAccountHandle(id)
                        : makeQuickAccountHandleForUser(id, userHandle),
                "label" + idx);
    }

    private static PhoneAccount copyPhoneAccountAndOverrideCapabilities(
            PhoneAccount base, int newCapabilities) {
        return base.toBuilder().setCapabilities(newCapabilities).build();
    }

    private static PhoneAccount copyPhoneAccountAndAddCapabilities(
            PhoneAccount base, int capabilitiesToAdd) {
        return copyPhoneAccountAndOverrideCapabilities(
                base, base.getCapabilities() | capabilitiesToAdd);
    }

    private static PhoneAccount copyPhoneAccountAndRemoveCapabilities(
            PhoneAccount base, int capabilitiesToRemove) {
        return copyPhoneAccountAndOverrideCapabilities(
                base, base.getCapabilities() & ~capabilitiesToRemove);
    }

    private PhoneAccount makeQuickAccount(String id, int idx) {
        return makeQuickAccountBuilder(id, idx, null)
                .setAddress(Uri.parse("http://foo.com/" + idx))
                .setSubscriptionAddress(Uri.parse("tel:555-000" + idx))
                .setCapabilities(idx)
                .setIcon(Icon.createWithResource(
                            "com.android.server.telecom.tests", R.drawable.stat_sys_phone_call))
                .setShortDescription("desc" + idx)
                .setIsEnabled(true)
                .build();
    }

    /**
     * Similar to {@link #makeQuickAccount}, but also hooks up {@code TelephonyManager} so that it
     * returns {@code simId} as the account's subscriptionId.
     */
    private PhoneAccount makeQuickSimAccount(int simId) {
        PhoneAccount simAccount =
                makeQuickAccountBuilder("sim" + simId, simId, null)
                        .setCapabilities(
                                PhoneAccount.CAPABILITY_CALL_PROVIDER
                                        | PhoneAccount.CAPABILITY_SIM_SUBSCRIPTION)
                        .setIsEnabled(true)
                        .build();
        when(mComponentContextFixture
                        .getTelephonyManager()
                        .getSubscriptionId(simAccount.getAccountHandle()))
                .thenReturn(simId);
        // mComponentContextFixture already sets up the createForSubscriptionId self-reference
        when(mComponentContextFixture
                        .getTelephonyManager()
                        .createForPhoneAccountHandle(simAccount.getAccountHandle()))
                .thenReturn(mComponentContextFixture.getTelephonyManager());
        return simAccount;
    }

    /**
     * Hooks up carrier config to point to {@code simCallManagerComponent} for the given {@code
     * subscriptionId}.
     */
    private void setSimCallManagerCarrierConfig(
            int subscriptionId, @Nullable ComponentName simCallManagerComponent) {
        PersistableBundle config = new PersistableBundle();
        config.putString(
                CarrierConfigManager.KEY_DEFAULT_SIM_CALL_MANAGER_STRING,
                simCallManagerComponent != null ? simCallManagerComponent.flattenToString() : null);
        when(mComponentContextFixture.getCarrierConfigManager().getConfigForSubId(subscriptionId))
                .thenReturn(config);
    }

    private static void roundTripPhoneAccount(PhoneAccount original) throws Exception {
        PhoneAccount copy = null;

        {
            Parcel parcel = Parcel.obtain();
            parcel.writeParcelable(original, 0);
            parcel.setDataPosition(0);
            copy = parcel.readParcelable(PhoneAccountRegistrarTest.class.getClassLoader());
            parcel.recycle();
        }

        assertPhoneAccountEquals(original, copy);
    }

    private static <T> T roundTripXml(
            Object self,
            T input,
            PhoneAccountRegistrar.XmlSerialization<T> xml,
            Context context)
            throws Exception {
        Log.d(self, "Input = %s", input);

        byte[] data;
        {
            XmlSerializer serializer = new FastXmlSerializer();
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            serializer.setOutput(new BufferedOutputStream(baos), "utf-8");
            xml.writeToXml(input, serializer, context);
            serializer.flush();
            data = baos.toByteArray();
        }

        Log.i(self, "====== XML data ======\n%s", new String(data));

        T result = null;
        {
            XmlPullParser parser = Xml.newPullParser();
            parser.setInput(new BufferedInputStream(new ByteArrayInputStream(data)), null);
            parser.nextTag();
            result = xml.readFromXml(parser, MAX_VERSION, context);
        }

        Log.i(self, "result = " + result);

        return result;
    }

    private static void assertPhoneAccountHandleEquals(PhoneAccountHandle a, PhoneAccountHandle b) {
        if (a != b) {
            assertEquals(
                    a.getComponentName().getPackageName(),
                    b.getComponentName().getPackageName());
            assertEquals(
                    a.getComponentName().getClassName(),
                    b.getComponentName().getClassName());
            assertEquals(a.getId(), b.getId());
        }
    }

    private static void assertIconEquals(Icon a, Icon b) {
        if (a != b) {
            if (a != null && b != null) {
                assertEquals(a.toString(), b.toString());
            } else {
                fail("Icons not equal: " + a + ", " + b);
            }
        }
    }

    private static void assertDefaultPhoneAccountHandleEquals(DefaultPhoneAccountHandle a,
            DefaultPhoneAccountHandle b) {
        if (a != b) {
            if (a!= null && b != null) {
                assertEquals(a.userHandle, b.userHandle);
                assertPhoneAccountHandleEquals(a.phoneAccountHandle, b.phoneAccountHandle);
            } else {
                fail("Default phone account handles are not equal: " + a + ", " + b);
            }
        }
    }

    private static void assertPhoneAccountEquals(PhoneAccount a, PhoneAccount b) {
        if (a != b) {
            if (a != null && b != null) {
                assertPhoneAccountHandleEquals(a.getAccountHandle(), b.getAccountHandle());
                assertEquals(a.getAddress(), b.getAddress());
                assertEquals(a.getSubscriptionAddress(), b.getSubscriptionAddress());
                assertEquals(a.getCapabilities(), b.getCapabilities());
                assertIconEquals(a.getIcon(), b.getIcon());
                assertEquals(a.getHighlightColor(), b.getHighlightColor());
                assertEquals(a.getLabel(), b.getLabel());
                assertEquals(a.getShortDescription(), b.getShortDescription());
                assertEquals(a.getSupportedUriSchemes(), b.getSupportedUriSchemes());
                assertBundlesEqual(a.getExtras(), b.getExtras());
                assertEquals(a.isEnabled(), b.isEnabled());
            } else {
                fail("Phone accounts not equal: " + a + ", " + b);
            }
        }
    }

    private static void assertBundlesEqual(Bundle a, Bundle b) {
        if (a == null && b == null) {
            return;
        }

        assertNotNull(a);
        assertNotNull(b);
        Set<String> keySetA = a.keySet();
        Set<String> keySetB = b.keySet();

        assertTrue("Bundle keys not the same", keySetA.containsAll(keySetB));
        assertTrue("Bundle keys not the same", keySetB.containsAll(keySetA));

        for (String keyA : keySetA) {
            assertEquals("Bundle value not the same", a.get(keyA), b.get(keyA));
        }
    }

    private static void assertStateEquals(
            PhoneAccountRegistrar.State a, PhoneAccountRegistrar.State b) {
        assertEquals(a.defaultOutgoingAccountHandles.size(),
                b.defaultOutgoingAccountHandles.size());
        for (Map.Entry<UserHandle, DefaultPhoneAccountHandle> e :
                a.defaultOutgoingAccountHandles.entrySet()) {
            assertDefaultPhoneAccountHandleEquals(e.getValue(),
                    b.defaultOutgoingAccountHandles.get(e.getKey()));
        }
        assertEquals(a.accounts.size(), b.accounts.size());
        for (int i = 0; i < a.accounts.size(); i++) {
            assertPhoneAccountEquals(a.accounts.get(i), b.accounts.get(i));
        }
    }

    private PhoneAccountRegistrar.State makeQuickStateWithTelephonyPhoneAccountHandle() {
        PhoneAccountRegistrar.State s = new PhoneAccountRegistrar.State();
        s.accounts.add(makeQuickAccount("id0", 0));
        s.accounts.add(makeQuickAccount("id1", 1));
        s.accounts.add(makeQuickAccount("id2", 2));
        PhoneAccountHandle phoneAccountHandle = new PhoneAccountHandle(new ComponentName(
                "com.android.phone",
                        "com.android.services.telephony.TelephonyConnectionService"), "id0");
        UserHandle userHandle = phoneAccountHandle.getUserHandle();
        when(UserManager.get(mContext).getSerialNumberForUser(userHandle))
            .thenReturn(0L);
        when(UserManager.get(mContext).getUserForSerialNumber(0L))
            .thenReturn(userHandle);
        s.defaultOutgoingAccountHandles
            .put(userHandle, new DefaultPhoneAccountHandle(userHandle, phoneAccountHandle,
                "testGroup"));
        return s;
    }

    private PhoneAccountRegistrar.State makeQuickState() {
        PhoneAccountRegistrar.State s = new PhoneAccountRegistrar.State();
        s.accounts.add(makeQuickAccount("id0", 0));
        s.accounts.add(makeQuickAccount("id1", 1));
        s.accounts.add(makeQuickAccount("id2", 2));
        PhoneAccountHandle phoneAccountHandle = new PhoneAccountHandle(
                new ComponentName("pkg0", "cls0"), "id0");
        UserHandle userHandle = phoneAccountHandle.getUserHandle();
        when(UserManager.get(mContext).getSerialNumberForUser(userHandle))
                .thenReturn(0L);
        when(UserManager.get(mContext).getUserForSerialNumber(0L))
                .thenReturn(userHandle);
        s.defaultOutgoingAccountHandles
                .put(userHandle, new DefaultPhoneAccountHandle(userHandle, phoneAccountHandle,
                        "testGroup"));
        return s;
    }
}