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

package com.android.server.telecom.tests;

import static android.provider.Settings.Global.ZEN_MODE_IMPORTANT_INTERRUPTIONS;

import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyBoolean;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.ArgumentMatchers.isNull;
import static org.mockito.ArgumentMatchers.nullable;
import static org.mockito.Mockito.atLeastOnce;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.timeout;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.mockito.Mockito.verifyZeroInteractions;
import static org.mockito.Mockito.when;

import android.app.NotificationManager;
import android.content.ComponentName;
import android.content.Context;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.Ringtone;
import android.media.VolumeShaper;
import android.net.Uri;
import android.os.Bundle;
import android.os.UserHandle;
import android.os.UserManager;
import android.os.VibrationAttributes;
import android.os.VibrationEffect;
import android.os.Vibrator;
import android.telecom.PhoneAccountHandle;
import android.telecom.TelecomManager;
import android.test.suitebuilder.annotation.SmallTest;

import com.android.server.telecom.AsyncRingtonePlayer;
import com.android.server.telecom.Call;
import com.android.server.telecom.CallState;
import com.android.server.telecom.InCallController;
import com.android.server.telecom.InCallTonePlayer;
import com.android.server.telecom.Ringer;
import com.android.server.telecom.RingtoneFactory;
import com.android.server.telecom.SystemSettingsUtil;

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.Spy;

import java.util.concurrent.CompletableFuture;

@RunWith(JUnit4.class)
public class RingerTest extends TelecomTestCase {
    private static final Uri FAKE_RINGTONE_URI = Uri.parse("content://media/fake/audio/1729");
    // Returned when the a URI-based VibrationEffect is attempted, to avoid depending on actual
    // device configuration for ringtone URIs. The actual Uri can be verified via the
    // VibrationEffectProxy mock invocation.
    private static final VibrationEffect URI_VIBRATION_EFFECT =
            VibrationEffect.createPredefined(VibrationEffect.EFFECT_CLICK);

    @Mock InCallTonePlayer.Factory mockPlayerFactory;
    @Mock SystemSettingsUtil mockSystemSettingsUtil;
    @Mock RingtoneFactory mockRingtoneFactory;
    @Mock Vibrator mockVibrator;
    @Mock InCallController mockInCallController;
    @Mock NotificationManager mockNotificationManager;
    @Mock Ringer.AccessibilityManagerAdapter mockAccessibilityManagerAdapter;

    @Spy Ringer.VibrationEffectProxy spyVibrationEffectProxy;

    @Mock InCallTonePlayer mockTonePlayer;
    @Mock Call mockCall1;
    @Mock Call mockCall2;

    private static final PhoneAccountHandle PA_HANDLE =
            new PhoneAccountHandle(new ComponentName("pa_pkg", "pa_cls"),
                    "pa_id");

    boolean mIsHapticPlaybackSupported = true;  // Note: initializeRinger() after changes.
    AsyncRingtonePlayer asyncRingtonePlayer = new AsyncRingtonePlayer();
    Ringer mRingerUnderTest;
    AudioManager mockAudioManager;
    CompletableFuture<Void> mRingCompletionFuture = new CompletableFuture<>();

    @Override
    @Before
    public void setUp() throws Exception {
        super.setUp();
        mContext = mComponentContextFixture.getTestDouble().getApplicationContext();
        doReturn(URI_VIBRATION_EFFECT).when(spyVibrationEffectProxy).get(any(), any());
        when(mockPlayerFactory.createPlayer(anyInt())).thenReturn(mockTonePlayer);
        mockAudioManager = mContext.getSystemService(AudioManager.class);
        when(mockAudioManager.getRingerMode()).thenReturn(AudioManager.RINGER_MODE_NORMAL);
        when(mockSystemSettingsUtil.isHapticPlaybackSupported(any(Context.class)))
                .thenAnswer((invocation) -> mIsHapticPlaybackSupported);
        mockNotificationManager =mContext.getSystemService(NotificationManager.class);
        when(mockTonePlayer.startTone()).thenReturn(true);
        when(mockNotificationManager.matchesCallFilter(any(Bundle.class))).thenReturn(true);
        when(mockRingtoneFactory.hasHapticChannels(any(Ringtone.class))).thenReturn(false);
        when(mockCall1.getState()).thenReturn(CallState.RINGING);
        when(mockCall2.getState()).thenReturn(CallState.RINGING);
        when(mockCall1.getAssociatedUser()).thenReturn(PA_HANDLE.getUserHandle());
        when(mockCall2.getAssociatedUser()).thenReturn(PA_HANDLE.getUserHandle());
        // Set BT active state in tests to ensure that we do not end up blocking tests for 1 sec
        // waiting for BT to connect in unit tests by default.
        asyncRingtonePlayer.updateBtActiveState(true);

        createRingerUnderTest();
    }

    /**
     * (Re-)Creates the Ringer for the test. This needs to be called if changing final properties,
     * like mIsHapticPlaybackSupported.
     */
    private void createRingerUnderTest() {
        mRingerUnderTest = new Ringer(mockPlayerFactory, mContext, mockSystemSettingsUtil,
                asyncRingtonePlayer, mockRingtoneFactory, mockVibrator, spyVibrationEffectProxy,
                mockInCallController, mockNotificationManager, mockAccessibilityManagerAdapter);
        // This future is used to wait for AsyncRingtonePlayer to finish its part.
        mRingerUnderTest.setBlockOnRingingFuture(mRingCompletionFuture);
    }

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

    @SmallTest
    @Test
    public void testNoActionInTheaterMode() throws Exception {
        // Start call waiting to make sure that it doesn't stop when we start ringing
        mRingerUnderTest.startCallWaiting(mockCall1);
        when(mockSystemSettingsUtil.isTheaterModeOn(any(Context.class))).thenReturn(true);
        assertFalse(startRingingAndWaitForAsync(mockCall2, false));
        verifyZeroInteractions(mockRingtoneFactory);
        verify(mockTonePlayer, never()).stopTone();
        verify(mockVibrator, never())
                .vibrate(any(VibrationEffect.class), any(VibrationAttributes.class));
    }

    @SmallTest
    @Test
    public void testNoActionWithExternalRinger() throws Exception {
        Bundle externalRingerExtra = new Bundle();
        externalRingerExtra.putBoolean(TelecomManager.EXTRA_CALL_HAS_IN_BAND_RINGTONE, true);
        when(mockCall1.getIntentExtras()).thenReturn(externalRingerExtra);
        when(mockCall2.getIntentExtras()).thenReturn(externalRingerExtra);
        // Start call waiting to make sure that it doesn't stop when we start ringing
        mRingerUnderTest.startCallWaiting(mockCall1);
        assertFalse(startRingingAndWaitForAsync(mockCall2, false));

        verifyZeroInteractions(mockRingtoneFactory);
        verify(mockTonePlayer, never()).stopTone();
        verify(mockVibrator, never())
                .vibrate(any(VibrationEffect.class), any(VibrationAttributes.class));
    }

    @SmallTest
    @Test
    public void testNoActionWhenDialerRings() throws Exception {
        // Start call waiting to make sure that it doesn't stop when we start ringing
        mRingerUnderTest.startCallWaiting(mockCall1);
        when(mockInCallController.doesConnectedDialerSupportRinging(
                any(UserHandle.class))).thenReturn(true);
        ensureRingerIsNotAudible();
        assertFalse(startRingingAndWaitForAsync(mockCall2, false));

        verifyZeroInteractions(mockRingtoneFactory);
        verify(mockTonePlayer, never()).stopTone();
        verify(mockVibrator, never())
                .vibrate(any(VibrationEffect.class), any(AudioAttributes.class));
    }

    @SmallTest
    @Test
    public void testAudioFocusStillAcquiredWhenDialerRings() throws Exception {

        // Start call waiting to make sure that it doesn't stop when we start ringing
        mRingerUnderTest.startCallWaiting(mockCall1);
        when(mockInCallController.doesConnectedDialerSupportRinging(
                any(UserHandle.class))).thenReturn(true);
        ensureRingerIsAudible();
        assertTrue(startRingingAndWaitForAsync(mockCall2, false));
        verifyZeroInteractions(mockRingtoneFactory);
        verify(mockTonePlayer, never()).stopTone();
        verify(mockVibrator, never())
                .vibrate(any(VibrationEffect.class), any(VibrationAttributes.class));
    }

    @SmallTest
    @Test
    public void testNoActionWhenCallIsSelfManaged() throws Exception {
        // Start call waiting to make sure that it doesn't stop when we start ringing
        mRingerUnderTest.startCallWaiting(mockCall1);
        when(mockCall2.isSelfManaged()).thenReturn(true);
        // We do want to acquire audio focus when self-managed
        assertTrue(startRingingAndWaitForAsync(mockCall2, true));

        verifyZeroInteractions(mockRingtoneFactory);
        verify(mockTonePlayer, never()).stopTone();
        verify(mockVibrator, never())
                .vibrate(any(VibrationEffect.class), any(VibrationAttributes.class));
    }

    @SmallTest
    @Test
    public void testCallWaitingButNoRingForSpecificContacts() throws Exception {
        when(mockNotificationManager.matchesCallFilter(any(Bundle.class))).thenReturn(false);
        // Start call waiting to make sure that it does stop when we start ringing
        mRingerUnderTest.startCallWaiting(mockCall1);
        verify(mockTonePlayer).startTone();

        assertFalse(startRingingAndWaitForAsync(mockCall2, false));

        verifyZeroInteractions(mockRingtoneFactory);
        verify(mockTonePlayer).stopTone();
        verify(mockVibrator, never())
                .vibrate(any(VibrationEffect.class), any(VibrationAttributes.class));
    }

    @SmallTest
    @Test
    public void testNoVibrateDueToAudioCoupledHaptics() throws Exception {
        Ringtone mockRingtone = ensureRingtoneMocked();

        mRingerUnderTest.startCallWaiting(mockCall1);
        ensureRingerIsAudible();
        enableVibrationWhenRinging();
        // Pretend we're using audio coupled haptics.
        setIsUsingHaptics(mockRingtone, true);
        assertTrue(startRingingAndWaitForAsync(mockCall1, false));
        verify(mockRingtoneFactory, times(1))
            .getRingtone(any(Call.class), nullable(VolumeShaper.Configuration.class), anyBoolean());
        verifyNoMoreInteractions(mockRingtoneFactory);
        verify(mockTonePlayer).stopTone();
        verify(mockRingtone).play();
        verify(mockVibrator, never()).vibrate(any(VibrationEffect.class),
                any(VibrationAttributes.class));
    }

    @SmallTest
    @Test
    public void testVibrateButNoRingForNullRingtone() throws Exception {
        when(mockRingtoneFactory.getRingtone(
                 any(Call.class), nullable(VolumeShaper.Configuration.class), anyBoolean()))
            .thenReturn(null);

        mRingerUnderTest.startCallWaiting(mockCall1);
        when(mockAudioManager.getRingerMode()).thenReturn(AudioManager.RINGER_MODE_NORMAL);
        enableVibrationWhenRinging();
        // The ringtone isn't known to be null until the async portion after the call completes,
        // so startRinging still returns true here as there should nominally be a ringtone.
        // Notably, vibration still happens in this scenario.
        assertTrue(startRingingAndWaitForAsync(mockCall2, false));
        verify(mockTonePlayer).stopTone();

        // Just the one call to mockRingtoneFactory, which returned null.
        verify(mockRingtoneFactory).getRingtone(
                any(Call.class), nullable(VolumeShaper.Configuration.class), anyBoolean());
        verifyNoMoreInteractions(mockRingtoneFactory);

        // Play default vibration when future completes with no audio coupled haptics
        verify(mockVibrator).vibrate(eq(mRingerUnderTest.mDefaultVibrationEffect),
                any(VibrationAttributes.class));
    }

    @SmallTest
    @Test
    public void testVibrateButNoRingForSilentRingtone() throws Exception {
        Ringtone mockRingtone = ensureRingtoneMocked();

        mRingerUnderTest.startCallWaiting(mockCall1);
        when(mockRingtoneFactory.getRingtone(any(Call.class), eq(null), anyBoolean()))
            .thenReturn(mockRingtone);
        when(mockAudioManager.getRingerMode()).thenReturn(AudioManager.RINGER_MODE_VIBRATE);
        when(mockAudioManager.getStreamVolume(AudioManager.STREAM_RING)).thenReturn(0);
        enableVibrationWhenRinging();
        assertFalse(startRingingAndWaitForAsync(mockCall2, false));
        verify(mockTonePlayer).stopTone();
        // Try to play a silent haptics ringtone
        verify(mockRingtoneFactory, times(1)).getHapticOnlyRingtone();
        verifyNoMoreInteractions(mockRingtoneFactory);
        verify(mockRingtone).play();

        // Play default vibration when future completes with no audio coupled haptics
        verify(mockVibrator).vibrate(eq(mRingerUnderTest.mDefaultVibrationEffect),
                any(VibrationAttributes.class));
    }

    @SmallTest
    @Test
    public void testVibrateButNoRingForSilentRingtoneWithoutAudioHapticSupport() throws Exception {
        mIsHapticPlaybackSupported = false;
        createRingerUnderTest();  // Needed after changing haptic playback support.
        mRingerUnderTest.startCallWaiting(mockCall1);
        when(mockAudioManager.getRingerMode()).thenReturn(AudioManager.RINGER_MODE_VIBRATE);
        when(mockAudioManager.getStreamVolume(AudioManager.STREAM_RING)).thenReturn(0);
        enableVibrationWhenRinging();
        assertFalse(startRingingAndWaitForAsync(mockCall2, false));
        verify(mockTonePlayer).stopTone();
        verifyZeroInteractions(mockRingtoneFactory);

        // Play default vibration when future completes with no audio coupled haptics
        verify(mockVibrator).vibrate(eq(mRingerUnderTest.mDefaultVibrationEffect),
                any(VibrationAttributes.class));
    }

    @SmallTest
    @Test
    public void testAudioCoupledHapticsForSilentRingtone() throws Exception {
        Ringtone mockRingtone = ensureRingtoneMocked();

        mRingerUnderTest.startCallWaiting(mockCall1);
        when(mockAudioManager.getRingerMode()).thenReturn(AudioManager.RINGER_MODE_VIBRATE);
        when(mockAudioManager.getStreamVolume(AudioManager.STREAM_RING)).thenReturn(0);
        setIsUsingHaptics(mockRingtone, true);
        enableVibrationWhenRinging();
        assertFalse(startRingingAndWaitForAsync(mockCall2, false));

        verify(mockRingtoneFactory, times(1)).getHapticOnlyRingtone();
        verifyNoMoreInteractions(mockRingtoneFactory);
        verify(mockTonePlayer).stopTone();
        // Try to play a silent haptics ringtone
        verify(mockRingtone).play();
        // Skip vibration for audio coupled haptics
        verify(mockVibrator, never()).vibrate(any(VibrationEffect.class),
                any(VibrationAttributes.class));
    }

    @SmallTest
    @Test
    public void testCustomVibrationForRingtone() throws Exception {
        mRingerUnderTest.startCallWaiting(mockCall1);
        Ringtone mockRingtone = ensureRingtoneMocked();
        when(mockAudioManager.getRingerMode()).thenReturn(AudioManager.RINGER_MODE_NORMAL);
        when(mockRingtone.getUri()).thenReturn(FAKE_RINGTONE_URI);
        enableVibrationWhenRinging();
        assertTrue(startRingingAndWaitForAsync(mockCall2, false));
        verify(mockTonePlayer).stopTone();
        verify(mockRingtoneFactory, times(1))
            .getRingtone(any(Call.class), isNull(), anyBoolean());
        verifyNoMoreInteractions(mockRingtoneFactory);
        verify(mockRingtone).play();
        verify(spyVibrationEffectProxy).get(eq(FAKE_RINGTONE_URI), any(Context.class));
        verify(mockVibrator).vibrate(eq(URI_VIBRATION_EFFECT), any(VibrationAttributes.class));
    }

    @SmallTest
    @Test
    public void testRingAndNoVibrate() throws Exception {
        Ringtone mockRingtone = ensureRingtoneMocked();

        mRingerUnderTest.startCallWaiting(mockCall1);
        ensureRingerIsAudible();
        enableVibrationOnlyWhenNotRinging();
        assertTrue(startRingingAndWaitForAsync(mockCall2, false));
        verify(mockRingtoneFactory, times(1))
            .getRingtone(any(Call.class), nullable(VolumeShaper.Configuration.class), anyBoolean());
        verifyNoMoreInteractions(mockRingtoneFactory);
        verify(mockTonePlayer).stopTone();
        verify(mockRingtone).play();
        verify(mockVibrator, never())
                .vibrate(any(VibrationEffect.class), any(VibrationAttributes.class));
    }

    @SmallTest
    @Test
    public void testRingWithRampingRinger() throws Exception {
        Ringtone mockRingtone = ensureRingtoneMocked();

        mRingerUnderTest.startCallWaiting(mockCall1);
        ensureRingerIsAudible();
        enableRampingRinger();
        enableVibrationWhenRinging();
        assertTrue(startRingingAndWaitForAsync(mockCall2, false));
        verify(mockRingtoneFactory, times(1))
            .getRingtone(any(Call.class), nullable(VolumeShaper.Configuration.class), anyBoolean());
        verifyNoMoreInteractions(mockRingtoneFactory);
        verify(mockTonePlayer).stopTone();
        verify(mockRingtone).play();
    }

    @SmallTest
    @Test
    public void testSilentRingWithHfpStillAcquiresFocus() throws Exception {
        mRingerUnderTest.startCallWaiting(mockCall1);
        when(mockAudioManager.getRingerMode()).thenReturn(AudioManager.RINGER_MODE_NORMAL);
        when(mockAudioManager.getStreamVolume(AudioManager.STREAM_RING)).thenReturn(0);
        enableVibrationOnlyWhenNotRinging();
        assertTrue(startRingingAndWaitForAsync(mockCall2, true));
        verify(mockTonePlayer).stopTone();
        // Ringer not audible, so never tries to create a ringtone.
        verifyZeroInteractions(mockRingtoneFactory);
        verify(mockVibrator, never())
                .vibrate(any(VibrationEffect.class), any(VibrationAttributes.class));
    }

    @SmallTest
    @Test
    public void testRingAndVibrateForAllowedCallInDndMode() throws Exception {
        mRingerUnderTest.startCallWaiting(mockCall1);
        Ringtone mockRingtone = ensureRingtoneMocked();
        when(mockNotificationManager.getZenMode()).thenReturn(ZEN_MODE_IMPORTANT_INTERRUPTIONS);
        when(mockAudioManager.getRingerMode()).thenReturn(AudioManager.RINGER_MODE_SILENT);
        when(mockAudioManager.getStreamVolume(AudioManager.STREAM_RING)).thenReturn(100);
        enableVibrationWhenRinging();
        assertTrue(startRingingAndWaitForAsync(mockCall2, true));
        verify(mockRingtoneFactory, times(1))
            .getRingtone(any(Call.class), isNull(), anyBoolean());
        verifyNoMoreInteractions(mockRingtoneFactory);
        verify(mockTonePlayer).stopTone();
        verify(mockRingtone).play();
    }

    @SmallTest
    @Test
    public void testDelayRingerForBtHfpDevices() throws Exception {
        asyncRingtonePlayer.updateBtActiveState(false);
        Ringtone mockRingtone = ensureRingtoneMocked();

        ensureRingerIsAudible();
        assertTrue(mRingerUnderTest.startRinging(mockCall1, true));
        assertTrue(mRingerUnderTest.isRinging());
        // We should not have the ringtone play until BT moves active
        verify(mockRingtone, never()).play();

        asyncRingtonePlayer.updateBtActiveState(true);
        mRingCompletionFuture.get();
        verify(mockRingtoneFactory, times(1))
                .getRingtone(any(Call.class), nullable(VolumeShaper.Configuration.class),
                        anyBoolean());
        verifyNoMoreInteractions(mockRingtoneFactory);
        verify(mockRingtone).play();

        mRingerUnderTest.stopRinging();
        verify(mockRingtone, timeout(1000/*ms*/)).stop();
        assertFalse(mRingerUnderTest.isRinging());
    }

    @SmallTest
    @Test
    public void testUnblockRingerForStopCommand() throws Exception {
        asyncRingtonePlayer.updateBtActiveState(false);
        Ringtone mockRingtone = ensureRingtoneMocked();

        ensureRingerIsAudible();
        assertTrue(mRingerUnderTest.startRinging(mockCall1, true));
        // We should not have the ringtone play until BT moves active
        verify(mockRingtone, never()).play();

        // We are not setting BT active, but calling stop ringing while the other thread is waiting
        // for BT active should also unblock it.
        mRingerUnderTest.stopRinging();
        verify(mockRingtone, timeout(1000/*ms*/)).stop();
    }

    /**
     * test shouldRingForContact will suppress the incoming call if matchesCallFilter returns
     * false (meaning DND is ON and the caller cannot bypass the settings)
     */
    @Test
    public void testShouldRingForContact_CallSuppressed() {
        // WHEN
        when(mockCall1.wasDndCheckComputedForCall()).thenReturn(false);
        when(mockCall1.getHandle()).thenReturn(Uri.parse(""));
        when(mContext.getSystemService(NotificationManager.class)).thenReturn(
                mockNotificationManager);
        // suppress the call
        when(mockNotificationManager.matchesCallFilter(any(Bundle.class))).thenReturn(false);

        // run the method under test
        assertFalse(mRingerUnderTest.shouldRingForContact(mockCall1));

        // THEN
        // verify we never set the call object and matchesCallFilter is called
        verify(mockCall1, never()).setCallIsSuppressedByDoNotDisturb(true);
        verify(mockNotificationManager, times(1))
                .matchesCallFilter(any(Bundle.class));
    }

    /**
     * test shouldRingForContact will alert the user of an incoming call if matchesCallFilter
     * returns true (meaning DND is NOT suppressing the caller)
     */
    @Test
    public void testShouldRingForContact_CallShouldRing() {
        // WHEN
        when(mockCall1.wasDndCheckComputedForCall()).thenReturn(false);
        when(mockCall1.getHandle()).thenReturn(Uri.parse(""));
        // alert the user of the call
        when(mockNotificationManager.matchesCallFilter(any(Bundle.class))).thenReturn(true);

        // run the method under test
        assertTrue(mRingerUnderTest.shouldRingForContact(mockCall1));

        // THEN
        // verify we never set the call object and matchesCallFilter is called
        verify(mockCall1, never()).setCallIsSuppressedByDoNotDisturb(false);
        verify(mockNotificationManager, times(1))
                .matchesCallFilter(any(Bundle.class));
    }

    /**
     * ensure Telecom does not re-query the NotificationManager if the call object already has
     * the result.
     */
    @Test
    public void testShouldRingForContact_matchesCallFilterIsAlreadyComputed() {
        // WHEN
        when(mockCall1.wasDndCheckComputedForCall()).thenReturn(true);
        when(mockCall1.isCallSuppressedByDoNotDisturb()).thenReturn(true);

        // THEN
        assertFalse(mRingerUnderTest.shouldRingForContact(mockCall1));
        verify(mockCall1, never()).setCallIsSuppressedByDoNotDisturb(false);
        verify(mockNotificationManager, never()).matchesCallFilter(any(Bundle.class));
    }

    @Test
    public void testNoFlashNotificationWhenCallSuppressed() throws Exception {
        ensureRingtoneMocked();
        // Start call waiting to make sure that it doesn't stop when we start ringing
        mRingerUnderTest.startCallWaiting(mockCall1);
        when(mockCall2.wasDndCheckComputedForCall()).thenReturn(false);
        when(mockCall2.getHandle()).thenReturn(Uri.parse(""));
        when(mockNotificationManager.matchesCallFilter(any(Bundle.class))).thenReturn(false);

        assertFalse(mRingerUnderTest.shouldRingForContact(mockCall2));
        assertFalse(startRingingAndWaitForAsync(mockCall2, false));
        verify(mockAccessibilityManagerAdapter, never())
                .startFlashNotificationSequence(any(Context.class), anyInt());
    }

    @Test
    public void testStartFlashNotificationWhenRingStarts() throws Exception {
        ensureRingtoneMocked();
        // Start call waiting to make sure that it doesn't stop when we start ringing
        mRingerUnderTest.startCallWaiting(mockCall1);
        when(mockCall2.wasDndCheckComputedForCall()).thenReturn(false);
        when(mockCall2.getHandle()).thenReturn(Uri.parse(""));
        when(mockNotificationManager.matchesCallFilter(any(Bundle.class))).thenReturn(true);

        assertTrue(mRingerUnderTest.shouldRingForContact(mockCall2));
        assertTrue(startRingingAndWaitForAsync(mockCall2, false));
        verify(mockAccessibilityManagerAdapter, atLeastOnce())
                .startFlashNotificationSequence(any(Context.class), anyInt());
    }

    @Test
    public void testStopFlashNotificationWhenRingStops() throws Exception {
        Ringtone mockRingtone = mock(Ringtone.class);
        when(mockRingtoneFactory.getRingtone(
                any(Call.class), nullable(VolumeShaper.Configuration.class), anyBoolean()))
                .thenAnswer(x -> {
                    // Be slow to create ringtone.
                    try {
                        Thread.sleep(300);
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                    }
                    return mockRingtone;
                });
        // Start call waiting to make sure that it doesn't stop when we start ringing
        enableVibrationWhenRinging();
        mRingerUnderTest.startCallWaiting(mockCall1);
        when(mockCall2.wasDndCheckComputedForCall()).thenReturn(false);
        when(mockCall2.getHandle()).thenReturn(Uri.parse(""));
        when(mockNotificationManager.matchesCallFilter(any(Bundle.class))).thenReturn(true);

        assertTrue(mRingerUnderTest.shouldRingForContact(mockCall2));
        assertTrue(mRingerUnderTest.startRinging(mockCall2, false));
        mRingerUnderTest.stopRinging();
        verify(mockAccessibilityManagerAdapter, atLeastOnce())
                .stopFlashNotificationSequence(any(Context.class));
        mRingCompletionFuture.get();  // Don't leak async work.
        verify(mockVibrator, never())  // cancelled before it started.
                .vibrate(any(VibrationEffect.class), any(VibrationAttributes.class));
    }

    @SmallTest
    @Test
    public void testNoRingingForQuietProfile() throws Exception {
        UserManager um = mContext.getSystemService(UserManager.class);
        when(um.isManagedProfile(PA_HANDLE.getUserHandle().getIdentifier())).thenReturn(true);
        when(um.isQuietModeEnabled(PA_HANDLE.getUserHandle())).thenReturn(true);
        // We don't want to acquire audio focus when self-managed
        assertFalse(startRingingAndWaitForAsync(mockCall2, true));

        verify(mockTonePlayer, never()).stopTone();
        verifyZeroInteractions(mockRingtoneFactory);
        verify(mockVibrator, never())
                .vibrate(any(VibrationEffect.class), any(VibrationAttributes.class));
    }

    /**
     * Call startRinging and wait for its effects to have played out, to allow reliable assertions
     * after it. The effects are generally "start playing ringtone" and "start vibration" - not
     * waiting for anything open-ended.
     */
    private boolean startRingingAndWaitForAsync(Call mockCall2, boolean isHfpDeviceAttached)
            throws Exception {
        boolean result = mRingerUnderTest.startRinging(mockCall2, isHfpDeviceAttached);
        mRingCompletionFuture.get();
        return result;
    }

    private void ensureRingerIsAudible() {
        when(mockAudioManager.getRingerMode()).thenReturn(AudioManager.RINGER_MODE_NORMAL);
        when(mockAudioManager.getStreamVolume(AudioManager.STREAM_RING)).thenReturn(100);
    }

    private void ensureRingerIsNotAudible() {
        when(mockAudioManager.getRingerMode()).thenReturn(AudioManager.RINGER_MODE_NORMAL);
        when(mockAudioManager.getStreamVolume(AudioManager.STREAM_RING)).thenReturn(0);
    }

    private void enableVibrationWhenRinging() {
        when(mockVibrator.hasVibrator()).thenReturn(true);
        when(mockSystemSettingsUtil.isRingVibrationEnabled(any(Context.class))).thenReturn(true);
    }

    private void enableVibrationOnlyWhenNotRinging() {
        when(mockVibrator.hasVibrator()).thenReturn(true);
        when(mockSystemSettingsUtil.isRingVibrationEnabled(any(Context.class))).thenReturn(false);
    }

    private void enableRampingRinger() {
        when(mockSystemSettingsUtil.isRampingRingerEnabled(any(Context.class))).thenReturn(true);
    }

    private void setIsUsingHaptics(Ringtone mockRingtone, boolean useHaptics) {
        // Note: using haptics can also depend on mIsHapticPlaybackSupported. If changing
        // that, the ringerUnderTest needs to be re-created.
        when(mockSystemSettingsUtil.isAudioCoupledVibrationForRampingRingerEnabled())
            .thenReturn(useHaptics);
        when(mockRingtone.hasHapticChannels()).thenReturn(useHaptics);
    }

    private Ringtone ensureRingtoneMocked() {
        Ringtone mockRingtone = mock(Ringtone.class);
        when(mockRingtoneFactory.getRingtone(
                any(Call.class), nullable(VolumeShaper.Configuration.class), anyBoolean()))
                .thenReturn(mockRingtone);
        when(mockRingtoneFactory.getHapticOnlyRingtone()).thenReturn(mockRingtone);
        return mockRingtone;
    }
}