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

package com.android.server.telecom.tests;


import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.ArgumentMatchers.nullable;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyBoolean;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyString;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doNothing;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.reset;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import android.app.AppOpsManager;
import android.bluetooth.BluetoothManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.IAudioService;
import android.media.ToneGenerator;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Process;
import android.os.UserHandle;
import android.telecom.Call;
import android.telecom.ConnectionRequest;
import android.telecom.DisconnectCause;
import android.telecom.Log;
import android.telecom.ParcelableCall;
import android.telecom.PhoneAccount;
import android.telecom.PhoneAccountHandle;
import android.telecom.TelecomManager;
import android.telecom.VideoProfile;
import android.telephony.TelephonyManager;
import android.telephony.TelephonyRegistryManager;

import com.android.internal.telecom.IInCallAdapter;
import com.android.server.telecom.AsyncRingtonePlayer;
import com.android.server.telecom.CallAudioManager;
import com.android.server.telecom.CallAudioModeStateMachine;
import com.android.server.telecom.CallAudioRouteStateMachine;
import com.android.server.telecom.CallerInfoLookupHelper;
import com.android.server.telecom.CallsManager;
import com.android.server.telecom.CallsManagerListenerBase;
import com.android.server.telecom.ClockProxy;
import com.android.server.telecom.ConnectionServiceFocusManager;
import com.android.server.telecom.ContactsAsyncHelper;
import com.android.server.telecom.DeviceIdleControllerAdapter;
import com.android.server.telecom.HeadsetMediaButton;
import com.android.server.telecom.HeadsetMediaButtonFactory;
import com.android.server.telecom.InCallWakeLockController;
import com.android.server.telecom.InCallWakeLockControllerFactory;
import com.android.server.telecom.MissedCallNotifier;
import com.android.server.telecom.PhoneAccountRegistrar;
import com.android.server.telecom.PhoneNumberUtilsAdapterImpl;
import com.android.server.telecom.ProximitySensorManager;
import com.android.server.telecom.ProximitySensorManagerFactory;
import com.android.server.telecom.Ringer;
import com.android.server.telecom.RoleManagerAdapter;
import com.android.server.telecom.StatusBarNotifier;
import com.android.server.telecom.SystemStateHelper;
import com.android.server.telecom.TelecomSystem;
import com.android.server.telecom.Timeouts;
import com.android.server.telecom.WiredHeadsetManager;
import com.android.server.telecom.bluetooth.BluetoothRouteManager;
import com.android.server.telecom.callfiltering.BlockedNumbersAdapter;
import com.android.server.telecom.components.UserCallIntentProcessor;
import com.android.server.telecom.ui.IncomingCallNotifier;

import com.google.common.base.Predicate;

import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.invocation.InvocationOnMock;
import org.mockito.stubbing.Answer;

import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.TimeUnit;

/**
 * Implements mocks and functionality required to implement telecom system tests.
 */
public class TelecomSystemTest extends TelecomTestCase {

    private static final String CALLING_PACKAGE = TelecomSystemTest.class.getPackageName();
    static final int TEST_POLL_INTERVAL = 10;  // milliseconds
    static final int TEST_TIMEOUT = 1000;  // milliseconds

    // Purposely keep the connect time (which is wall clock) and elapsed time (which is time since
    // boot) different to test that wall clock time operations and elapsed time operations perform
    // as they individually should.
    static final long TEST_CREATE_TIME = 100;
    static final long TEST_CREATE_ELAPSED_TIME = 200;
    static final long TEST_CONNECT_TIME = 1000;
    static final long TEST_CONNECT_ELAPSED_TIME = 2000;
    static final long TEST_DISCONNECT_TIME = 8000;
    static final long TEST_DISCONNECT_ELAPSED_TIME = 4000;

    public class HeadsetMediaButtonFactoryF implements HeadsetMediaButtonFactory  {
        @Override
        public HeadsetMediaButton create(Context context, CallsManager callsManager,
                TelecomSystem.SyncRoot lock) {
            return mHeadsetMediaButton;
        }
    }

    public class ProximitySensorManagerFactoryF implements ProximitySensorManagerFactory {
        @Override
        public ProximitySensorManager create(Context context, CallsManager callsManager) {
            return mProximitySensorManager;
        }
    }

    public class InCallWakeLockControllerFactoryF implements InCallWakeLockControllerFactory {
        @Override
        public InCallWakeLockController create(Context context, CallsManager callsManager) {
            return mInCallWakeLockController;
        }
    }

    public static class MissedCallNotifierFakeImpl extends CallsManagerListenerBase
            implements MissedCallNotifier {
        List<CallInfo> missedCallsNotified = new ArrayList<>();

        @Override
        public void clearMissedCalls(UserHandle userHandle) {

        }

        @Override
        public void showMissedCallNotification(CallInfo call) {
            missedCallsNotified.add(call);
        }

        @Override
        public void reloadAfterBootComplete(CallerInfoLookupHelper callerInfoLookupHelper,
                CallInfoFactory callInfoFactory) { }

        @Override
        public void reloadFromDatabase(CallerInfoLookupHelper callerInfoLookupHelper,
                CallInfoFactory callInfoFactory, UserHandle userHandle) { }

        @Override
        public void setCurrentUserHandle(UserHandle userHandle) {

        }
    }

    MissedCallNotifierFakeImpl mMissedCallNotifier = new MissedCallNotifierFakeImpl();

    private class IncomingCallAddedListener extends CallsManagerListenerBase {

        private final CountDownLatch mCountDownLatch;

        public IncomingCallAddedListener(CountDownLatch latch) {
            mCountDownLatch = latch;
        }

        @Override
        public void onCallAdded(com.android.server.telecom.Call call) {
            mCountDownLatch.countDown();
        }
    }

    @Mock HeadsetMediaButton mHeadsetMediaButton;
    @Mock ProximitySensorManager mProximitySensorManager;
    @Mock InCallWakeLockController mInCallWakeLockController;
    @Mock AsyncRingtonePlayer mAsyncRingtonePlayer;
    @Mock IncomingCallNotifier mIncomingCallNotifier;
    @Mock ClockProxy mClockProxy;
    @Mock RoleManagerAdapter mRoleManagerAdapter;
    @Mock ToneGenerator mToneGenerator;
    @Mock DeviceIdleControllerAdapter mDeviceIdleControllerAdapter;

    @Mock Ringer.AccessibilityManagerAdapter mAccessibilityManagerAdapter;
    @Mock
    BlockedNumbersAdapter mBlockedNumbersAdapter;

    final ComponentName mInCallServiceComponentNameX =
            new ComponentName(
                    "incall-service-package-X",
                    "incall-service-class-X");
    private static final int SERVICE_X_UID = 1;
    final ComponentName mInCallServiceComponentNameY =
            new ComponentName(
                    "incall-service-package-Y",
                    "incall-service-class-Y");
    private static final int SERVICE_Y_UID = 1;
    InCallServiceFixture mInCallServiceFixtureX;
    InCallServiceFixture mInCallServiceFixtureY;

    final ComponentName mConnectionServiceComponentNameA =
            new ComponentName(
                    "connection-service-package-A",
                    "connection-service-class-A");
    final ComponentName mConnectionServiceComponentNameB =
            new ComponentName(
                    "connection-service-package-B",
                    "connection-service-class-B");

    final PhoneAccount mPhoneAccountA0 =
            PhoneAccount.builder(
                    new PhoneAccountHandle(
                            mConnectionServiceComponentNameA,
                            "id A 0"),
                    "Phone account service A ID 0")
                    .addSupportedUriScheme("tel")
                    .setCapabilities(
                            PhoneAccount.CAPABILITY_CALL_PROVIDER |
                                    PhoneAccount.CAPABILITY_SIM_SUBSCRIPTION |
                                    PhoneAccount.CAPABILITY_VIDEO_CALLING)
                    .build();
    final PhoneAccount mPhoneAccountA1 =
            PhoneAccount.builder(
                    new PhoneAccountHandle(
                            mConnectionServiceComponentNameA,
                            "id A 1"),
                    "Phone account service A ID 1")
                    .addSupportedUriScheme("tel")
                    .setCapabilities(
                            PhoneAccount.CAPABILITY_CALL_PROVIDER |
                                    PhoneAccount.CAPABILITY_SIM_SUBSCRIPTION |
                                    PhoneAccount.CAPABILITY_VIDEO_CALLING)
                    .build();
    final PhoneAccount mPhoneAccountA2 =
            PhoneAccount.builder(
                    new PhoneAccountHandle(
                            mConnectionServiceComponentNameA,
                            "id A 2"),
                    "Phone account service A ID 2")
                    .addSupportedUriScheme("tel")
                    .setCapabilities(
                            PhoneAccount.CAPABILITY_CALL_PROVIDER |
                                    PhoneAccount.CAPABILITY_SIM_SUBSCRIPTION)
                    .build();
    final PhoneAccount mPhoneAccountSelfManaged =
            PhoneAccount.builder(
                    new PhoneAccountHandle(
                            mConnectionServiceComponentNameA,
                            "id SM"),
                    "Phone account service A SM")
                    .addSupportedUriScheme("tel")
                    .setCapabilities(
                            PhoneAccount.CAPABILITY_SELF_MANAGED)
                    .build();
    final PhoneAccount mPhoneAccountB0 =
            PhoneAccount.builder(
                    new PhoneAccountHandle(
                            mConnectionServiceComponentNameB,
                            "id B 0"),
                    "Phone account service B ID 0")
                    .addSupportedUriScheme("tel")
                    .setCapabilities(
                            PhoneAccount.CAPABILITY_CALL_PROVIDER |
                                    PhoneAccount.CAPABILITY_SIM_SUBSCRIPTION |
                                    PhoneAccount.CAPABILITY_VIDEO_CALLING)
                    .build();
    final PhoneAccount mPhoneAccountE0 =
            PhoneAccount.builder(
                    new PhoneAccountHandle(
                            mConnectionServiceComponentNameA,
                            "id E 0"),
                    "Phone account service E ID 0")
                    .addSupportedUriScheme("tel")
                    .setCapabilities(
                            PhoneAccount.CAPABILITY_CALL_PROVIDER |
                                    PhoneAccount.CAPABILITY_SIM_SUBSCRIPTION |
                                    PhoneAccount.CAPABILITY_PLACE_EMERGENCY_CALLS)
                    .build();

    final PhoneAccount mPhoneAccountE1 =
            PhoneAccount.builder(
                    new PhoneAccountHandle(
                            mConnectionServiceComponentNameA,
                            "id E 1"),
                    "Phone account service E ID 1")
                    .addSupportedUriScheme("tel")
                    .setCapabilities(
                            PhoneAccount.CAPABILITY_CALL_PROVIDER |
                                    PhoneAccount.CAPABILITY_SIM_SUBSCRIPTION |
                                    PhoneAccount.CAPABILITY_PLACE_EMERGENCY_CALLS)
                    .build();

    ConnectionServiceFixture mConnectionServiceFixtureA;
    ConnectionServiceFixture mConnectionServiceFixtureB;
    Timeouts.Adapter mTimeoutsAdapter;

    CallerInfoAsyncQueryFactoryFixture mCallerInfoAsyncQueryFactoryFixture;

    IAudioService mAudioService;

    TelecomSystem mTelecomSystem;

    Context mSpyContext;

    ConnectionServiceFocusManager mConnectionServiceFocusManager;

    private HandlerThread mHandlerThread;

    private int mNumOutgoingCallsMade;

    class IdPair {
        final String mConnectionId;
        final String mCallId;

        public IdPair(String connectionId, String callId) {
            this.mConnectionId = connectionId;
            this.mCallId = callId;
        }
    }

    @Override
    public void setUp() throws Exception {
        super.setUp();
        mSpyContext = mComponentContextFixture.getTestDouble().getApplicationContext();
        doReturn(mSpyContext).when(mSpyContext).getApplicationContext();
        doNothing().when(mSpyContext).sendBroadcastAsUser(any(), any(), any());

        doReturn(mock(AppOpsManager.class)).when(mSpyContext).getSystemService(AppOpsManager.class);
        doReturn(mock(BluetoothManager.class)).when(mSpyContext).getSystemService(BluetoothManager.class);

        mHandlerThread = new HandlerThread("TelecomHandlerThread");
        mHandlerThread.start();

        mNumOutgoingCallsMade = 0;

        doReturn(false).when(mComponentContextFixture.getTelephonyManager())
                .isEmergencyNumber(any());
        doReturn(false).when(mComponentContextFixture.getTelephonyManager())
                .isPotentialEmergencyNumber(any());

        // First set up information about the In-Call services in the mock Context, since
        // Telecom will search for these as soon as it is instantiated
        setupInCallServices();

        // Next, create the TelecomSystem, our system under test
        setupTelecomSystem();
        // Need to reset testing tag here
        Log.setTag(TESTING_TAG);

        // Finally, register the ConnectionServices with the PhoneAccountRegistrar of the
        // now-running TelecomSystem
        setupConnectionServices();

        waitForHandlerAction(new Handler(Looper.getMainLooper()), TEST_TIMEOUT);
    }

    @Override
    public void tearDown() throws Exception {
        if (mTelecomSystem != null && mTelecomSystem.getCallsManager() != null) {
            mTelecomSystem.getCallsManager().waitOnHandlers();
            LinkedList<HandlerThread> handlerThreads = mTelecomSystem.getCallsManager()
                    .getGraphHandlerThreads();
            for (HandlerThread handlerThread : handlerThreads) {
                handlerThread.quitSafely();
            }
            handlerThreads.clear();
            mTelecomSystem.getCallsManager().getVoipCallMonitor().stopMonitor();
        }
        waitForHandlerAction(new Handler(Looper.getMainLooper()), TEST_TIMEOUT);
        waitForHandlerAction(mHandlerThread.getThreadHandler(), TEST_TIMEOUT);
        // Bring down the threads that are active.
        mHandlerThread.quit();
        try {
            mHandlerThread.join();
        } catch (InterruptedException e) {
            // don't do anything
        }

        if (mConnectionServiceFocusManager != null) {
            mConnectionServiceFocusManager.getHandler().removeCallbacksAndMessages(null);
            waitForHandlerAction(mConnectionServiceFocusManager.getHandler(), TEST_TIMEOUT);
            mConnectionServiceFocusManager.getHandler().getLooper().quit();
        }

        if (mConnectionServiceFixtureA != null) {
            mConnectionServiceFixtureA.waitForHandlerToClear();
        }

        if (mConnectionServiceFixtureA != null) {
            mConnectionServiceFixtureB.waitForHandlerToClear();
        }

        // Forcefully clean all sessions at the end of the test, which will also log any stale
        // sessions for debugging.
        Log.getSessionManager().cleanupStaleSessions(0);

        mTelecomSystem = null;
        super.tearDown();
    }

    protected ParcelableCall makeConferenceCall(
            Intent callIntentExtras1, Intent callIntentExtras2) throws Exception {
        IdPair callId1 = startAndMakeActiveOutgoingCallWithExtras("650-555-1212",
                mPhoneAccountA0.getAccountHandle(), mConnectionServiceFixtureA, callIntentExtras1);

        IdPair callId2 = startAndMakeActiveOutgoingCallWithExtras("650-555-1213",
                mPhoneAccountA0.getAccountHandle(), mConnectionServiceFixtureA, callIntentExtras2);

        IInCallAdapter inCallAdapter = mInCallServiceFixtureX.getInCallAdapter();
        inCallAdapter.conference(callId1.mCallId, callId2.mCallId);
        // Wait for the handler in ConnectionService
        waitForHandlerAction(new Handler(Looper.getMainLooper()), TEST_TIMEOUT);
        ParcelableCall call1 = mInCallServiceFixtureX.getCall(callId1.mCallId);
        ParcelableCall call2 = mInCallServiceFixtureX.getCall(callId2.mCallId);
        // Check that the two calls end up with a parent in the end
        assertNotNull(call1.getParentCallId());
        assertNotNull(call2.getParentCallId());
        assertEquals(call1.getParentCallId(), call2.getParentCallId());

        // Check to make sure that the parent call made it to the in-call service
        String parentCallId = call1.getParentCallId();
        ParcelableCall conferenceCall = mInCallServiceFixtureX.getCall(parentCallId);
        assertEquals(2, conferenceCall.getChildCallIds().size());
        assertTrue(conferenceCall.getChildCallIds().contains(callId1.mCallId));
        assertTrue(conferenceCall.getChildCallIds().contains(callId2.mCallId));
        return conferenceCall;
    }

    private void setupTelecomSystem() throws Exception {
        // Remove any cached PhoneAccount xml
        File phoneAccountFile =
                new File(mComponentContextFixture.getTestDouble()
                        .getApplicationContext().getFilesDir(),
                        PhoneAccountRegistrar.FILE_NAME);
        if (phoneAccountFile.exists()) {
            phoneAccountFile.delete();
        }

        // Use actual implementations instead of mocking the interface out.
        HeadsetMediaButtonFactory headsetMediaButtonFactory =
                spy(new HeadsetMediaButtonFactoryF());
        ProximitySensorManagerFactory proximitySensorManagerFactory =
                spy(new ProximitySensorManagerFactoryF());
        InCallWakeLockControllerFactory inCallWakeLockControllerFactory =
                spy(new InCallWakeLockControllerFactoryF());
        mAudioService = setupAudioService();

        mCallerInfoAsyncQueryFactoryFixture = new CallerInfoAsyncQueryFactoryFixture();

        ConnectionServiceFocusManager.ConnectionServiceFocusManagerFactory mConnServFMFactory =
                requester -> {
                    mConnectionServiceFocusManager = new ConnectionServiceFocusManager(requester);
                    return mConnectionServiceFocusManager;
                };

        mTimeoutsAdapter = mock(Timeouts.Adapter.class);
        when(mTimeoutsAdapter.getCallScreeningTimeoutMillis(any(ContentResolver.class)))
                .thenReturn(TEST_TIMEOUT / 5L);
        mIncomingCallNotifier = mock(IncomingCallNotifier.class);
        mClockProxy = mock(ClockProxy.class);
        when(mClockProxy.currentTimeMillis()).thenReturn(TEST_CREATE_TIME);
        when(mClockProxy.elapsedRealtime()).thenReturn(TEST_CREATE_ELAPSED_TIME);
        when(mRoleManagerAdapter.getCallCompanionApps()).thenReturn(Collections.emptyList());
        when(mRoleManagerAdapter.getDefaultCallScreeningApp(any(UserHandle.class)))
                .thenReturn(null);
        mTelecomSystem = new TelecomSystem(
                mComponentContextFixture.getTestDouble(),
                (context, phoneAccountRegistrar, defaultDialerCache, mDeviceIdleControllerAdapter)
                        -> mMissedCallNotifier,
                mCallerInfoAsyncQueryFactoryFixture.getTestDouble(),
                headsetMediaButtonFactory,
                proximitySensorManagerFactory,
                inCallWakeLockControllerFactory,
                () -> mAudioService,
                mConnServFMFactory,
                mTimeoutsAdapter,
                mAsyncRingtonePlayer,
                new PhoneNumberUtilsAdapterImpl(),
                mIncomingCallNotifier,
                (streamType, volume) -> mToneGenerator,
                new CallAudioRouteStateMachine.Factory() {
                    @Override
                    public CallAudioRouteStateMachine create(
                            Context context,
                            CallsManager callsManager,
                            BluetoothRouteManager bluetoothManager,
                            WiredHeadsetManager wiredHeadsetManager,
                            StatusBarNotifier statusBarNotifier,
                            CallAudioManager.AudioServiceFactory audioServiceFactory,
                            int earpieceControl,
                            Executor asyncTaskExecutor) {
                        return new CallAudioRouteStateMachine(context,
                                callsManager,
                                bluetoothManager,
                                wiredHeadsetManager,
                                statusBarNotifier,
                                audioServiceFactory,
                                // Force enable an earpiece for the end-to-end tests
                                CallAudioRouteStateMachine.EARPIECE_FORCE_ENABLED,
                                mHandlerThread.getLooper(),
                                Runnable::run /* async tasks as now sync for testing! */);
                    }
                },
                new CallAudioModeStateMachine.Factory() {
                    @Override
                    public CallAudioModeStateMachine create(SystemStateHelper systemStateHelper,
                            AudioManager am) {
                        return new CallAudioModeStateMachine(systemStateHelper, am,
                                mHandlerThread.getLooper());
                    }
                },
                mClockProxy,
                mRoleManagerAdapter,
                new ContactsAsyncHelper.Factory() {
                    @Override
                    public ContactsAsyncHelper create(
                            ContactsAsyncHelper.ContentResolverAdapter adapter) {
                        return new ContactsAsyncHelper(adapter, mHandlerThread.getLooper());
                    }
                }, mDeviceIdleControllerAdapter, mAccessibilityManagerAdapter,
                Runnable::run,
                Runnable::run,
                mBlockedNumbersAdapter);

        mComponentContextFixture.setTelecomManager(new TelecomManager(
                mComponentContextFixture.getTestDouble(),
                mTelecomSystem.getTelecomServiceImpl().getBinder()));

        verify(headsetMediaButtonFactory).create(
                eq(mComponentContextFixture.getTestDouble().getApplicationContext()),
                any(CallsManager.class),
                any(TelecomSystem.SyncRoot.class));
        verify(proximitySensorManagerFactory).create(
                eq(mComponentContextFixture.getTestDouble().getApplicationContext()),
                any(CallsManager.class));
        verify(inCallWakeLockControllerFactory).create(
                eq(mComponentContextFixture.getTestDouble().getApplicationContext()),
                any(CallsManager.class));
    }

    private void setupConnectionServices() throws Exception {
        mConnectionServiceFixtureA = new ConnectionServiceFixture(mContext);
        mConnectionServiceFixtureB = new ConnectionServiceFixture(mContext);

        mComponentContextFixture.addConnectionService(mConnectionServiceComponentNameA,
                mConnectionServiceFixtureA.getTestDouble());
        mComponentContextFixture.addConnectionService(mConnectionServiceComponentNameB,
                mConnectionServiceFixtureB.getTestDouble());

        mTelecomSystem.getPhoneAccountRegistrar().registerPhoneAccount(mPhoneAccountA0);
        mTelecomSystem.getPhoneAccountRegistrar().registerPhoneAccount(mPhoneAccountA1);
        mTelecomSystem.getPhoneAccountRegistrar().registerPhoneAccount(mPhoneAccountA2);
        mTelecomSystem.getPhoneAccountRegistrar().registerPhoneAccount(mPhoneAccountSelfManaged);
        mTelecomSystem.getPhoneAccountRegistrar().registerPhoneAccount(mPhoneAccountB0);
        mTelecomSystem.getPhoneAccountRegistrar().registerPhoneAccount(mPhoneAccountE0);
        mTelecomSystem.getPhoneAccountRegistrar().registerPhoneAccount(mPhoneAccountE1);

        mTelecomSystem.getPhoneAccountRegistrar().setUserSelectedOutgoingPhoneAccount(
                mPhoneAccountA0.getAccountHandle(), Process.myUserHandle());
    }

    private void setupInCallServices() throws Exception {
        mComponentContextFixture.putResource(
                com.android.internal.R.string.config_defaultDialer,
                mInCallServiceComponentNameX.getPackageName());
        mComponentContextFixture.putResource(
                com.android.server.telecom.R.string.incall_default_class,
                mInCallServiceComponentNameX.getClassName());

        mInCallServiceFixtureX = new InCallServiceFixture();
        mInCallServiceFixtureY = new InCallServiceFixture();

        mComponentContextFixture.addInCallService(mInCallServiceComponentNameX,
                mInCallServiceFixtureX.getTestDouble(), SERVICE_X_UID);
        mComponentContextFixture.addInCallService(mInCallServiceComponentNameY,
                mInCallServiceFixtureY.getTestDouble(), SERVICE_Y_UID);
    }

    /**
     * Helper method for setting up the fake audio service.
     * Calls to the fake audio service need to toggle the return
     * value of AudioManager#isMicrophoneMute.
     * @return mock of IAudioService
     */
    private IAudioService setupAudioService() {
        IAudioService audioService = mock(IAudioService.class);

        final AudioManager fakeAudioManager =
                (AudioManager) mComponentContextFixture.getTestDouble()
                        .getApplicationContext().getSystemService(Context.AUDIO_SERVICE);

        try {
            doAnswer(new Answer() {
                @Override
                public Object answer(InvocationOnMock i) {
                    Object[] args = i.getArguments();
                    doReturn(args[0]).when(fakeAudioManager).isMicrophoneMute();
                    return null;
                }
            }).when(audioService).setMicrophoneMute(any(Boolean.class), any(String.class),
                    any(Integer.class), nullable(String.class));

        } catch (android.os.RemoteException e) {
            // Do nothing, leave the faked microphone state as-is
        }
        return audioService;
    }

    protected String startOutgoingPhoneCallWithNoPhoneAccount(String number,
            ConnectionServiceFixture connectionServiceFixture)
            throws Exception {

        startOutgoingPhoneCallWaitForBroadcaster(number, null,
                connectionServiceFixture, Process.myUserHandle(), VideoProfile.STATE_AUDIO_ONLY,
                false /*isEmergency*/, null);

        return mInCallServiceFixtureX.mLatestCallId;
    }

    protected IdPair outgoingCallPhoneAccountSelected(PhoneAccountHandle phoneAccountHandle,
            int startingNumConnections, int startingNumCalls,
            ConnectionServiceFixture connectionServiceFixture) throws Exception {

        IdPair ids = outgoingCallCreateConnectionComplete(startingNumConnections, startingNumCalls,
                phoneAccountHandle, connectionServiceFixture);

        connectionServiceFixture.sendSetDialing(ids.mConnectionId);
        assertEquals(Call.STATE_DIALING, mInCallServiceFixtureX.getCall(ids.mCallId).getState());
        assertEquals(Call.STATE_DIALING, mInCallServiceFixtureY.getCall(ids.mCallId).getState());

        connectionServiceFixture.sendSetVideoState(ids.mConnectionId);

        connectionServiceFixture.sendSetActive(ids.mConnectionId);
        assertEquals(Call.STATE_ACTIVE, mInCallServiceFixtureX.getCall(ids.mCallId).getState());
        assertEquals(Call.STATE_ACTIVE, mInCallServiceFixtureY.getCall(ids.mCallId).getState());

        return ids;
    }

    protected IdPair startOutgoingPhoneCall(String number, PhoneAccountHandle phoneAccountHandle,
            ConnectionServiceFixture connectionServiceFixture, UserHandle initiatingUser)
            throws Exception {

        return startOutgoingPhoneCall(number, phoneAccountHandle, connectionServiceFixture,
                initiatingUser, VideoProfile.STATE_AUDIO_ONLY, null);
    }

    protected IdPair startOutgoingPhoneCall(String number, PhoneAccountHandle phoneAccountHandle,
            ConnectionServiceFixture connectionServiceFixture, UserHandle initiatingUser,
            int videoState, Intent callIntentExtras) throws Exception {
        int startingNumConnections = connectionServiceFixture.mConnectionById.size();
        int startingNumCalls = mInCallServiceFixtureX.mCallById.size();

        startOutgoingPhoneCallPendingCreateConnection(number, phoneAccountHandle,
                connectionServiceFixture, initiatingUser, videoState, callIntentExtras);

        verify(connectionServiceFixture.getTestDouble(), timeout(TEST_TIMEOUT))
                .createConnectionComplete(anyString(), any());

        return outgoingCallCreateConnectionComplete(startingNumConnections, startingNumCalls,
                phoneAccountHandle, connectionServiceFixture);
    }

    protected IdPair triggerEmergencyRedial(PhoneAccountHandle phoneAccountHandle,
            ConnectionServiceFixture connectionServiceFixture, IdPair emergencyIds)
            throws Exception {
        int startingNumConnections = connectionServiceFixture.mConnectionById.size();
        int startingNumCalls = mInCallServiceFixtureX.mCallById.size();

        // Send the message to disconnect the Emergency call due to an error.
        // CreateConnectionProcessor should now try the second SIM account
        connectionServiceFixture.sendSetDisconnected(emergencyIds.mConnectionId,
                DisconnectCause.ERROR);
        waitForHandlerAction(new Handler(Looper.getMainLooper()), TEST_TIMEOUT);
        assertEquals(Call.STATE_DIALING, mInCallServiceFixtureX.getCall(
                emergencyIds.mCallId).getState());
        assertEquals(Call.STATE_DIALING, mInCallServiceFixtureY.getCall(
                emergencyIds.mCallId).getState());

        return redialingCallCreateConnectionComplete(startingNumConnections, startingNumCalls,
                phoneAccountHandle, connectionServiceFixture);
    }

    protected IdPair startOutgoingEmergencyCall(String number,
            PhoneAccountHandle phoneAccountHandle,
            ConnectionServiceFixture connectionServiceFixture, UserHandle initiatingUser,
            int videoState) throws Exception {
        int startingNumConnections = connectionServiceFixture.mConnectionById.size();
        int startingNumCalls = mInCallServiceFixtureX.mCallById.size();

        doReturn(true).when(mComponentContextFixture.getTelephonyManager())
                .isEmergencyNumber(any());
        doReturn(true).when(mComponentContextFixture.getTelephonyManager())
                .isPotentialEmergencyNumber(any());

        // Call will not use the ordered broadcaster, since it is an Emergency Call
        startOutgoingPhoneCallWaitForBroadcaster(number, phoneAccountHandle,
                connectionServiceFixture, initiatingUser, videoState, true /*isEmergency*/, null);

        return outgoingCallCreateConnectionComplete(startingNumConnections, startingNumCalls,
                phoneAccountHandle, connectionServiceFixture);
    }

    protected void startOutgoingPhoneCallWaitForBroadcaster(String number,
            PhoneAccountHandle phoneAccountHandle,
            ConnectionServiceFixture connectionServiceFixture, UserHandle initiatingUser,
            int videoState, boolean isEmergency, Intent actionCallIntent) throws Exception {
        reset(connectionServiceFixture.getTestDouble(), mInCallServiceFixtureX.getTestDouble(),
                mInCallServiceFixtureY.getTestDouble());

        assertEquals(mInCallServiceFixtureX.mCallById.size(),
                mInCallServiceFixtureY.mCallById.size());
        assertEquals((mInCallServiceFixtureX.mInCallAdapter != null),
                (mInCallServiceFixtureY.mInCallAdapter != null));

        mNumOutgoingCallsMade++;

        boolean hasInCallAdapter = mInCallServiceFixtureX.mInCallAdapter != null;

        if (actionCallIntent == null) {
            actionCallIntent = new Intent();
        }
        actionCallIntent.setData(Uri.parse("tel:" + number));
        actionCallIntent.putExtra(Intent.EXTRA_PHONE_NUMBER, number);
        if(isEmergency) {
            actionCallIntent.setAction(Intent.ACTION_CALL_EMERGENCY);
        } else {
            actionCallIntent.setAction(Intent.ACTION_CALL);
        }
        if (phoneAccountHandle != null) {
            actionCallIntent.putExtra(
                    TelecomManager.EXTRA_PHONE_ACCOUNT_HANDLE,
                    phoneAccountHandle);
        }
        if (videoState != VideoProfile.STATE_AUDIO_ONLY) {
            actionCallIntent.putExtra(TelecomManager.EXTRA_START_CALL_WITH_VIDEO_STATE, videoState);
        }

        final UserHandle userHandle = initiatingUser;
        Context localAppContext = mComponentContextFixture.getTestDouble().getApplicationContext();
        new UserCallIntentProcessor(localAppContext, userHandle).processIntent(
                actionCallIntent, null, false, true /* hasCallAppOp*/, false /* isLocal */);
        // Wait for handler to start CallerInfo lookup.
        waitForHandlerAction(new Handler(Looper.getMainLooper()), TEST_TIMEOUT);
        // Send the CallerInfo lookup reply.
        mCallerInfoAsyncQueryFactoryFixture.mRequests.forEach(
                CallerInfoAsyncQueryFactoryFixture.Request::reply);
        if (phoneAccountHandle != null) {
            mTelecomSystem.getCallsManager().getLatestPostSelectionProcessingFuture().join();
        }
        waitForHandlerAction(new Handler(Looper.getMainLooper()), TEST_TIMEOUT);

        boolean isSelfManaged = phoneAccountHandle == mPhoneAccountSelfManaged.getAccountHandle();
        if (!hasInCallAdapter && !isSelfManaged) {
            verify(mInCallServiceFixtureX.getTestDouble(), timeout(TEST_TIMEOUT))
                    .setInCallAdapter(
                            any(IInCallAdapter.class));
            verify(mInCallServiceFixtureY.getTestDouble(), timeout(TEST_TIMEOUT))
                    .setInCallAdapter(
                            any(IInCallAdapter.class));
        }
    }

    protected String startOutgoingPhoneCallPendingCreateConnection(String number,
            PhoneAccountHandle phoneAccountHandle,
            ConnectionServiceFixture connectionServiceFixture, UserHandle initiatingUser,
            int videoState, Intent callIntentExtras) throws Exception {
        startOutgoingPhoneCallWaitForBroadcaster(number,phoneAccountHandle,
                connectionServiceFixture, initiatingUser,
                videoState, false /*isEmergency*/, callIntentExtras);
        waitForHandlerAction(new Handler(Looper.getMainLooper()), TEST_TIMEOUT);

        verifyAndProcessOutgoingCallBroadcast(phoneAccountHandle);
        return mInCallServiceFixtureX.mLatestCallId;
    }

    protected void verifyAndProcessOutgoingCallBroadcast(PhoneAccountHandle phoneAccountHandle) {
        ArgumentCaptor<Intent> newOutgoingCallIntent =
                ArgumentCaptor.forClass(Intent.class);
        ArgumentCaptor<BroadcastReceiver> newOutgoingCallReceiver =
                ArgumentCaptor.forClass(BroadcastReceiver.class);

        if (phoneAccountHandle != mPhoneAccountSelfManaged.getAccountHandle()) {
            verify(mComponentContextFixture.getTestDouble().getApplicationContext(),
                    times(mNumOutgoingCallsMade))
                    .sendOrderedBroadcastAsUser(
                            newOutgoingCallIntent.capture(),
                            any(UserHandle.class),
                            anyString(),
                            anyInt(),
                            any(Bundle.class),
                            newOutgoingCallReceiver.capture(),
                            nullable(Handler.class),
                            anyInt(),
                            anyString(),
                            nullable(Bundle.class));
            // Pass on the new outgoing call Intent
            // Set a dummy PendingResult so the BroadcastReceiver agrees to accept onReceive()
            newOutgoingCallReceiver.getValue().setPendingResult(
                    new BroadcastReceiver.PendingResult(0, "", null, 0, true, false, null, 0, 0));
            newOutgoingCallReceiver.getValue().setResultData(
                    newOutgoingCallIntent.getValue().getStringExtra(Intent.EXTRA_PHONE_NUMBER));
            newOutgoingCallReceiver.getValue().onReceive(mComponentContextFixture.getTestDouble(),
                    newOutgoingCallIntent.getValue());
        }

    }

    // When Telecom is redialing due to an error, we need to make sure the number of connections
    // increase, but not the number of Calls in the InCallService.
    protected IdPair redialingCallCreateConnectionComplete(int startingNumConnections,
            int startingNumCalls, PhoneAccountHandle phoneAccountHandle,
            ConnectionServiceFixture connectionServiceFixture) throws Exception {

        assertEquals(startingNumConnections + 1, connectionServiceFixture.mConnectionById.size());

        verify(connectionServiceFixture.getTestDouble())
                .createConnection(eq(phoneAccountHandle), anyString(), any(ConnectionRequest.class),
                        eq(false)/*isIncoming*/, anyBoolean(), any());
        // Wait for handleCreateConnectionComplete
        waitForHandlerAction(new Handler(Looper.getMainLooper()), TEST_TIMEOUT);

        // Make sure the number of registered InCallService Calls stays the same.
        assertEquals(startingNumCalls, mInCallServiceFixtureX.mCallById.size());
        assertEquals(startingNumCalls, mInCallServiceFixtureY.mCallById.size());

        assertEquals(mInCallServiceFixtureX.mLatestCallId, mInCallServiceFixtureY.mLatestCallId);

        return new IdPair(connectionServiceFixture.mLatestConnectionId,
                mInCallServiceFixtureX.mLatestCallId);
    }

    protected IdPair outgoingCallCreateConnectionComplete(int startingNumConnections,
            int startingNumCalls, PhoneAccountHandle phoneAccountHandle,
            ConnectionServiceFixture connectionServiceFixture) throws Exception {

        // Wait for the focus tracker.
        waitForHandlerAction(mTelecomSystem.getCallsManager()
                .getConnectionServiceFocusManager().getHandler(), TEST_TIMEOUT);

        verify(connectionServiceFixture.getTestDouble())
                .createConnection(eq(phoneAccountHandle), anyString(), any(ConnectionRequest.class),
                        eq(false)/*isIncoming*/, anyBoolean(), any());
        // Wait for handleCreateConnectionComplete
        waitForHandlerAction(new Handler(Looper.getMainLooper()), TEST_TIMEOUT);
        assertEquals(startingNumConnections + 1,
                connectionServiceFixture.mConnectionById.size());

        // Wait for the callback in ConnectionService#onAdapterAttached to execute.
        waitForHandlerAction(new Handler(Looper.getMainLooper()), TEST_TIMEOUT);

        // Ensure callback to CS on successful creation happened.
        verify(connectionServiceFixture.getTestDouble(), timeout(TEST_TIMEOUT))
                .createConnectionComplete(anyString(), any());

        if (phoneAccountHandle == mPhoneAccountSelfManaged.getAccountHandle()) {
            assertEquals(startingNumCalls, mInCallServiceFixtureX.mCallById.size());
            assertEquals(startingNumCalls, mInCallServiceFixtureY.mCallById.size());
        } else {
            assertEquals(startingNumCalls + 1, mInCallServiceFixtureX.mCallById.size());
            assertEquals(startingNumCalls + 1, mInCallServiceFixtureY.mCallById.size());
        }

        assertEquals(mInCallServiceFixtureX.mLatestCallId, mInCallServiceFixtureY.mLatestCallId);

        return new IdPair(connectionServiceFixture.mLatestConnectionId,
                mInCallServiceFixtureX.mLatestCallId);
    }

    protected IdPair startIncomingPhoneCall(
            String number,
            PhoneAccountHandle phoneAccountHandle,
            final ConnectionServiceFixture connectionServiceFixture) throws Exception {
        return startIncomingPhoneCall(number, phoneAccountHandle, VideoProfile.STATE_AUDIO_ONLY,
                connectionServiceFixture, null);
    }

    protected IdPair startIncomingPhoneCallWithExtras(
            String number,
            PhoneAccountHandle phoneAccountHandle,
            final ConnectionServiceFixture connectionServiceFixture,
            Bundle extras) throws Exception {
        return startIncomingPhoneCall(number, phoneAccountHandle, VideoProfile.STATE_AUDIO_ONLY,
                connectionServiceFixture, extras);
    }

    protected IdPair startIncomingPhoneCall(
            String number,
            PhoneAccountHandle phoneAccountHandle,
            int videoState,
            final ConnectionServiceFixture connectionServiceFixture,
            Bundle extras) throws Exception {
        reset(connectionServiceFixture.getTestDouble(), mInCallServiceFixtureX.getTestDouble(),
                mInCallServiceFixtureY.getTestDouble());

        assertEquals(mInCallServiceFixtureX.mCallById.size(),
                mInCallServiceFixtureY.mCallById.size());
        assertEquals((mInCallServiceFixtureX.mInCallAdapter != null),
                (mInCallServiceFixtureY.mInCallAdapter != null));
        final int startingNumConnections = connectionServiceFixture.mConnectionById.size();
        final int startingNumCalls = mInCallServiceFixtureX.mCallById.size();
        boolean hasInCallAdapter = mInCallServiceFixtureX.mInCallAdapter != null;
        connectionServiceFixture.mConnectionServiceDelegate.mVideoState = videoState;
        CountDownLatch incomingCallAddedLatch = new CountDownLatch(1);
        IncomingCallAddedListener callAddedListener =
                new IncomingCallAddedListener(incomingCallAddedLatch);
        mTelecomSystem.getCallsManager().addListener(callAddedListener);

        if (extras == null) {
            extras = new Bundle();
        }
        extras.putParcelable(
                TelecomManager.EXTRA_INCOMING_CALL_ADDRESS,
                Uri.fromParts(PhoneAccount.SCHEME_TEL, number, null));
        mTelecomSystem.getTelecomServiceImpl().getBinder()
                .addNewIncomingCall(phoneAccountHandle, extras, CALLING_PACKAGE);

        verify(connectionServiceFixture.getTestDouble())
                .createConnection(any(PhoneAccountHandle.class), anyString(),
                        any(ConnectionRequest.class), eq(true), eq(false), any());

        // Wait for the handler to start the CallerInfo lookup
        waitForHandlerAction(new Handler(Looper.getMainLooper()), TEST_TIMEOUT);

        // Wait a few more times to address flakiness due to timing issues.
        waitForHandlerAction(new Handler(Looper.getMainLooper()), TEST_TIMEOUT);
        waitForHandlerAction(new Handler(Looper.getMainLooper()), TEST_TIMEOUT);

        // Ensure callback to CS on successful creation happened.

        verify(connectionServiceFixture.getTestDouble(), timeout(TEST_TIMEOUT))
                .createConnectionComplete(anyString(), any());

        // Process the CallerInfo lookup reply
        mCallerInfoAsyncQueryFactoryFixture.mRequests.forEach(
                CallerInfoAsyncQueryFactoryFixture.Request::reply);

        //Wait for/Verify call blocking happened asynchronously
        incomingCallAddedLatch.await(TEST_TIMEOUT, TimeUnit.MILLISECONDS);

        // For the case of incoming calls, Telecom connecting the InCall services and adding the
        // Call is triggered by the async completion of the CallerInfoAsyncQuery. Once the Call
        // is added, future interactions as triggered by the ConnectionService, through the various
        // test fixtures, will be synchronous.

        if (phoneAccountHandle != mPhoneAccountSelfManaged.getAccountHandle()) {
            if (!hasInCallAdapter) {
                verify(mInCallServiceFixtureX.getTestDouble(), timeout(TEST_TIMEOUT))
                        .setInCallAdapter(any(IInCallAdapter.class));
                verify(mInCallServiceFixtureY.getTestDouble(), timeout(TEST_TIMEOUT))
                        .setInCallAdapter(any(IInCallAdapter.class));

                // Give the InCallService time to respond
                assertTrueWithTimeout(new Predicate<Void>() {
                    @Override
                    public boolean apply(Void v) {
                        return mInCallServiceFixtureX.mInCallAdapter != null;
                    }
                });

                assertTrueWithTimeout(new Predicate<Void>() {
                    @Override
                    public boolean apply(Void v) {
                        return mInCallServiceFixtureY.mInCallAdapter != null;
                    }
                });

                verify(mInCallServiceFixtureX.getTestDouble(), timeout(TEST_TIMEOUT))
                        .addCall(any(ParcelableCall.class));
                verify(mInCallServiceFixtureY.getTestDouble(), timeout(TEST_TIMEOUT))
                        .addCall(any(ParcelableCall.class));

                // Give the InCallService time to respond
            }

            assertTrueWithTimeout(new Predicate<Void>() {
                @Override
                public boolean apply(Void v) {
                    return startingNumConnections + 1 ==
                            connectionServiceFixture.mConnectionById.size();
                }
            });

            mInCallServiceFixtureX.waitUntilNumCalls(startingNumCalls + 1);
            mInCallServiceFixtureY.waitUntilNumCalls(startingNumCalls + 1);
            assertEquals(startingNumCalls + 1, mInCallServiceFixtureX.mCallById.size());
            assertEquals(startingNumCalls + 1, mInCallServiceFixtureY.mCallById.size());

            assertEquals(mInCallServiceFixtureX.mLatestCallId,
                    mInCallServiceFixtureY.mLatestCallId);
        }

        return new IdPair(connectionServiceFixture.mLatestConnectionId,
                mInCallServiceFixtureX.mLatestCallId);
    }

    protected IdPair startAndMakeActiveOutgoingCall(
            String number,
            PhoneAccountHandle phoneAccountHandle,
            ConnectionServiceFixture connectionServiceFixture) throws Exception {
        return startAndMakeActiveOutgoingCall(number, phoneAccountHandle, connectionServiceFixture,
                VideoProfile.STATE_AUDIO_ONLY, null);
    }

    protected IdPair startAndMakeActiveOutgoingCallWithExtras(
            String number,
            PhoneAccountHandle phoneAccountHandle,
            ConnectionServiceFixture connectionServiceFixture,
            Intent callIntentExtras) throws Exception {
        return startAndMakeActiveOutgoingCall(number, phoneAccountHandle, connectionServiceFixture,
                VideoProfile.STATE_AUDIO_ONLY, callIntentExtras);
    }

    // A simple outgoing call, verifying that the appropriate connection service is contacted,
    // the proper lifecycle is followed, and both In-Call Services are updated correctly.
    protected IdPair startAndMakeActiveOutgoingCall(
            String number,
            PhoneAccountHandle phoneAccountHandle,
            ConnectionServiceFixture connectionServiceFixture, int videoState,
            Intent callIntentExtras) throws Exception {
        IdPair ids = startOutgoingPhoneCall(number, phoneAccountHandle, connectionServiceFixture,
                Process.myUserHandle(), videoState, callIntentExtras);

        connectionServiceFixture.sendSetDialing(ids.mConnectionId);
        if (phoneAccountHandle != mPhoneAccountSelfManaged.getAccountHandle()) {
            assertEquals(Call.STATE_DIALING,
                    mInCallServiceFixtureX.getCall(ids.mCallId).getState());
            assertEquals(Call.STATE_DIALING,
                    mInCallServiceFixtureY.getCall(ids.mCallId).getState());
        }

        connectionServiceFixture.sendSetVideoState(ids.mConnectionId);

        when(mClockProxy.currentTimeMillis()).thenReturn(TEST_CONNECT_TIME);
        when(mClockProxy.elapsedRealtime()).thenReturn(TEST_CONNECT_ELAPSED_TIME);
        connectionServiceFixture.sendSetActive(ids.mConnectionId);
        if (phoneAccountHandle != mPhoneAccountSelfManaged.getAccountHandle()) {
            assertEquals(Call.STATE_ACTIVE, mInCallServiceFixtureX.getCall(ids.mCallId).getState());
            assertEquals(Call.STATE_ACTIVE, mInCallServiceFixtureY.getCall(ids.mCallId).getState());

            if ((mInCallServiceFixtureX.getCall(ids.mCallId).getProperties() &
                    Call.Details.PROPERTY_IS_EXTERNAL_CALL) == 0) {
                // Test the PhoneStateBroadcaster functionality if the call is not external.
                verify(mContext.getSystemService(TelephonyRegistryManager.class),
                        timeout(TEST_TIMEOUT).atLeastOnce())
                        .notifyCallStateChangedForAllSubscriptions(
                                eq(TelephonyManager.CALL_STATE_OFFHOOK),
                                nullable(String.class));
            }
        }
        return ids;
    }

    protected IdPair startAndMakeActiveIncomingCall(
            String number,
            PhoneAccountHandle phoneAccountHandle,
            ConnectionServiceFixture connectionServiceFixture) throws Exception {
        return startAndMakeActiveIncomingCall(number, phoneAccountHandle, connectionServiceFixture,
                VideoProfile.STATE_AUDIO_ONLY);
    }

    // A simple incoming call, similar in scope to the previous test
    protected IdPair startAndMakeActiveIncomingCall(
            String number,
            PhoneAccountHandle phoneAccountHandle,
            ConnectionServiceFixture connectionServiceFixture,
            int videoState) throws Exception {
        IdPair ids = startIncomingPhoneCall(number, phoneAccountHandle, connectionServiceFixture);

        if (phoneAccountHandle != mPhoneAccountSelfManaged.getAccountHandle()) {
            assertEquals(Call.STATE_RINGING,
                    mInCallServiceFixtureX.getCall(ids.mCallId).getState());
            assertEquals(Call.STATE_RINGING,
                    mInCallServiceFixtureY.getCall(ids.mCallId).getState());

            mInCallServiceFixtureX.mInCallAdapter
                    .answerCall(ids.mCallId, videoState);
            // Wait on the CS focus manager handler
            waitForHandlerAction(mTelecomSystem.getCallsManager()
                    .getConnectionServiceFocusManager().getHandler(), TEST_TIMEOUT);

            if (!VideoProfile.isVideo(videoState)) {
                verify(connectionServiceFixture.getTestDouble(), timeout(TEST_TIMEOUT))
                        .answer(eq(ids.mConnectionId), any());
            } else {
                verify(connectionServiceFixture.getTestDouble(), timeout(TEST_TIMEOUT))
                        .answerVideo(eq(ids.mConnectionId), eq(videoState), any());
            }
        }

        when(mClockProxy.currentTimeMillis()).thenReturn(TEST_CONNECT_TIME);
        when(mClockProxy.elapsedRealtime()).thenReturn(TEST_CONNECT_ELAPSED_TIME);
        connectionServiceFixture.sendSetActive(ids.mConnectionId);

        if (phoneAccountHandle != mPhoneAccountSelfManaged.getAccountHandle()) {
            assertEquals(Call.STATE_ACTIVE, mInCallServiceFixtureX.getCall(ids.mCallId).getState());
            assertEquals(Call.STATE_ACTIVE, mInCallServiceFixtureY.getCall(ids.mCallId).getState());

            if ((mInCallServiceFixtureX.getCall(ids.mCallId).getProperties() &
                    Call.Details.PROPERTY_IS_EXTERNAL_CALL) == 0) {
                // Test the PhoneStateBroadcaster functionality if the call is not external.
                verify(mContext.getSystemService(TelephonyRegistryManager.class),
                        timeout(TEST_TIMEOUT).atLeastOnce())
                        .notifyCallStateChangedForAllSubscriptions(
                                eq(TelephonyManager.CALL_STATE_OFFHOOK),
                                nullable(String.class));
            }
        }
        return ids;
    }

    protected IdPair startAndMakeDialingEmergencyCall(
            String number,
            PhoneAccountHandle phoneAccountHandle,
            ConnectionServiceFixture connectionServiceFixture) throws Exception {
        IdPair ids = startOutgoingEmergencyCall(number, phoneAccountHandle,
                connectionServiceFixture, Process.myUserHandle(), VideoProfile.STATE_AUDIO_ONLY);

        connectionServiceFixture.sendSetDialing(ids.mConnectionId);
        assertEquals(Call.STATE_DIALING, mInCallServiceFixtureX.getCall(ids.mCallId).getState());
        assertEquals(Call.STATE_DIALING, mInCallServiceFixtureY.getCall(ids.mCallId).getState());

        return ids;
    }

    protected IdPair startAndMakeDialingOutgoingCall(
            String number,
            PhoneAccountHandle phoneAccountHandle,
            ConnectionServiceFixture connectionServiceFixture) throws Exception {
        IdPair ids = startOutgoingPhoneCall(number, phoneAccountHandle, connectionServiceFixture,
                Process.myUserHandle(), VideoProfile.STATE_AUDIO_ONLY, null);

        connectionServiceFixture.sendSetDialing(ids.mConnectionId);
        if (phoneAccountHandle != mPhoneAccountSelfManaged.getAccountHandle()) {
            assertEquals(Call.STATE_DIALING,
                    mInCallServiceFixtureX.getCall(ids.mCallId).getState());
            assertEquals(Call.STATE_DIALING,
                    mInCallServiceFixtureY.getCall(ids.mCallId).getState());
        }

        return ids;
    }

    protected IdPair startAndMakeRingingIncomingCall(
            String number,
            PhoneAccountHandle phoneAccountHandle,
            ConnectionServiceFixture connectionServiceFixture) throws Exception {
        IdPair ids = startIncomingPhoneCall(number, phoneAccountHandle, connectionServiceFixture);

        if (phoneAccountHandle != mPhoneAccountSelfManaged.getAccountHandle()) {
            assertEquals(Call.STATE_RINGING,
                    mInCallServiceFixtureX.getCall(ids.mCallId).getState());
            assertEquals(Call.STATE_RINGING,
                    mInCallServiceFixtureY.getCall(ids.mCallId).getState());

            mInCallServiceFixtureX.mInCallAdapter
                    .answerCall(ids.mCallId, VideoProfile.STATE_AUDIO_ONLY);

            waitForHandlerAction(mTelecomSystem.getCallsManager()
                    .getConnectionServiceFocusManager().getHandler(), TEST_TIMEOUT);

            if (!VideoProfile.isVideo(VideoProfile.STATE_AUDIO_ONLY)) {
                verify(connectionServiceFixture.getTestDouble(), timeout(TEST_TIMEOUT))
                        .answer(eq(ids.mConnectionId), any());
            } else {
                verify(connectionServiceFixture.getTestDouble(), timeout(TEST_TIMEOUT))
                        .answerVideo(eq(ids.mConnectionId), eq(VideoProfile.STATE_AUDIO_ONLY),
                                any());
            }
        }
        return ids;
    }

    protected static void assertTrueWithTimeout(Predicate<Void> predicate) {
        int elapsed = 0;
        while (elapsed < TEST_TIMEOUT) {
            if (predicate.apply(null)) {
                return;
            } else {
                try {
                    Thread.sleep(TEST_POLL_INTERVAL);
                    elapsed += TEST_POLL_INTERVAL;
                } catch (InterruptedException e) {
                    fail(e.toString());
                }
            }
        }
        fail("Timeout in assertTrueWithTimeout");
    }
}