aboutsummaryrefslogtreecommitdiff
path: root/robolectric/src/test/java/org/robolectric/shadows/ShadowBluetoothAdapterTest.java
blob: aadac4457ee076eab9385a4ad31963533dd0a072 (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
package org.robolectric.shadows;

import static android.os.Build.VERSION_CODES.M;
import static android.os.Build.VERSION_CODES.O;
import static android.os.Build.VERSION_CODES.Q;
import static android.os.Build.VERSION_CODES.R;
import static android.os.Build.VERSION_CODES.S;
import static android.os.Build.VERSION_CODES.S_V2;
import static android.os.Build.VERSION_CODES.TIRAMISU;
import static android.os.Build.VERSION_CODES.UPSIDE_DOWN_CAKE;
import static androidx.test.core.app.ApplicationProvider.getApplicationContext;
import static com.google.common.truth.Truth.assertThat;
import static java.nio.charset.StandardCharsets.UTF_8;
import static org.junit.Assert.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyInt;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoMoreInteractions;
import static org.robolectric.Shadows.shadowOf;

import android.Manifest.permission;
import android.app.Application;
import android.app.PendingIntent;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothHeadset;
import android.bluetooth.BluetoothProfile;
import android.bluetooth.BluetoothProfile.ServiceListener;
import android.bluetooth.BluetoothSocket;
import android.bluetooth.BluetoothStatusCodes;
import android.bluetooth.le.BluetoothLeScanner;
import android.content.Intent;
import android.os.Looper;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import java.time.Duration;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.UUID;
import java.util.concurrent.LinkedBlockingQueue;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.robolectric.RuntimeEnvironment;
import org.robolectric.annotation.Config;
import org.robolectric.shadow.api.Shadow;
import org.robolectric.util.ReflectionHelpers;
import org.robolectric.util.ReflectionHelpers.ClassParameter;
import org.robolectric.versioning.AndroidVersions.U;

/** Unit tests for {@link ShadowBluetoothAdapter} */
@RunWith(AndroidJUnit4.class)
public class ShadowBluetoothAdapterTest {
  private static final int MOCK_PROFILE1 = 17;
  private static final int MOCK_PROFILE2 = 21;
  private static final String MOCK_MAC_ADDRESS = "00:11:22:33:AA:BB";

  private static final UUID UUID1 = UUID.fromString("3e9507d3-20c9-4b1a-a75d-30c795334389");
  private static final UUID UUID2 = UUID.fromString("cdba7974-3e3f-476a-9119-0d1be6b0e548");
  private static final UUID UUID3 = UUID.fromString("4524c169-531b-4f27-8097-fd9f19e0c788");
  private static final UUID UUID4 = UUID.fromString("468c2e72-8d89-43e3-b153-940c8ddee1da");
  private static final UUID UUID5 = UUID.fromString("19ad4589-af27-4ccc-8cfb-de1bf2212298");
  private static final Intent testIntent = new Intent("com.test.action.DUMMY_ACTION");

  private BluetoothAdapter bluetoothAdapter;

  @Before
  public void setUp() throws Exception {
    bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
  }

  @Test
  public void testAdapterBluetoothSupported() {
    assertThat(BluetoothAdapter.getDefaultAdapter()).isNotNull();

    ShadowBluetoothAdapter.setIsBluetoothSupported(false);
    assertThat(BluetoothAdapter.getDefaultAdapter()).isNull();

    ShadowBluetoothAdapter.reset();
    assertThat(BluetoothAdapter.getDefaultAdapter()).isNotNull();
  }

  @Test
  @Config(minSdk = O)
  public void testIsLeExtendedAdvertisingSupported() {
    assertThat(bluetoothAdapter.isLeExtendedAdvertisingSupported()).isTrue();

    shadowOf(bluetoothAdapter).setIsLeExtendedAdvertisingSupported(false);

    assertThat(bluetoothAdapter.isLeExtendedAdvertisingSupported()).isFalse();
  }

  @Test
  @Config(minSdk = UPSIDE_DOWN_CAKE)
  public void canSetAndGetIsLeCodedPhySupported() {
    assertThat(bluetoothAdapter.isLeCodedPhySupported()).isTrue();

    shadowOf(bluetoothAdapter).setIsLeCodedPhySupported(false);

    assertThat(bluetoothAdapter.isLeCodedPhySupported()).isFalse();
  }

  @Test
  @Config(minSdk = UPSIDE_DOWN_CAKE)
  public void canSetAndGetIsLe2MPhySupported() {
    assertThat(bluetoothAdapter.isLe2MPhySupported()).isTrue();

    shadowOf(bluetoothAdapter).setIsLe2MPhySupported(false);

    assertThat(bluetoothAdapter.isLe2MPhySupported()).isFalse();
  }

  @Test
  public void testAdapterDefaultsDisabled() {
    assertThat(bluetoothAdapter.isEnabled()).isFalse();
  }

  @Test
  public void testAdapterCanBeEnabled_forTesting() {
    shadowOf(bluetoothAdapter).setEnabled(true);
    assertThat(bluetoothAdapter.isEnabled()).isTrue();
  }

  @Test
  public void canGetAndSetAddress() throws Exception {
    BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
    shadowOf(adapter).setAddress("expected");
    assertThat(adapter.getAddress()).isEqualTo("expected");
  }

  @Test
  @Config(minSdk = TIRAMISU)
  public void canGetAndSetMostRecentlyConnectedDevices() {
    BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();

    // By default return empty list for most recently connected devices
    assertThat(adapter.getMostRecentlyConnectedDevices()).isEmpty();

    // set most recently connected devices
    BluetoothDevice remoteDevice1 = bluetoothAdapter.getRemoteDevice(MOCK_MAC_ADDRESS);
    BluetoothDevice remoteDevice2 = bluetoothAdapter.getRemoteDevice(MOCK_MAC_ADDRESS);
    List<BluetoothDevice> result = new ArrayList<>();
    result.add(remoteDevice1);
    result.add(remoteDevice2);
    shadowOf(adapter).setMostRecentlyConnectedDevices(result);

    assertThat(adapter.getMostRecentlyConnectedDevices()).hasSize(2);
    assertThat(adapter.getMostRecentlyConnectedDevices())
        .containsExactly(remoteDevice1, remoteDevice2);
  }

  @Test
  public void canGetBluetoothLeScanner() {
    if (RuntimeEnvironment.getApiLevel() < M) {
      // On SDK < 23, bluetooth has to be in STATE_ON in order to get a BluetoothLeScanner.
      shadowOf(bluetoothAdapter).setState(BluetoothAdapter.STATE_ON);
    }
    BluetoothLeScanner bluetoothLeScanner = bluetoothAdapter.getBluetoothLeScanner();
    assertThat(bluetoothLeScanner).isNotNull();
  }

  @Test
  public void canGetBluetoothLeAdvertiser() throws Exception {
    // bluetooth needs to be ON in APIS 21 and 22 for getBluetoothLeAdvertiser to return a
    // non null value
    bluetoothAdapter.enable();
    assertThat(bluetoothAdapter.getBluetoothLeAdvertiser()).isNotNull();
  }

  @Test
  @Config(minSdk = M)
  public void canGetAndSetBleScanAlwaysAvailable() throws Exception {
    BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();

    // By default, scanning with BT is not supported.
    assertThat(adapter.isBleScanAlwaysAvailable()).isTrue();

    // Flipping it on should update state accordingly.
    shadowOf(adapter).setBleScanAlwaysAvailable(false);
    assertThat(adapter.isBleScanAlwaysAvailable()).isFalse();
  }

  @Test
  public void canGetAndSetMultipleAdvertisementSupport() throws Exception {
    BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();

    // By default, multiple advertising is supported.
    assertThat(adapter.isMultipleAdvertisementSupported()).isTrue();

    // Flipping it off should update state accordingly.
    shadowOf(adapter).setIsMultipleAdvertisementSupported(false);
    assertThat(adapter.isMultipleAdvertisementSupported()).isFalse();
  }

  @Test
  public void canEnable_withAndroidApi() throws Exception {
    bluetoothAdapter.enable();
    assertThat(bluetoothAdapter.isEnabled()).isTrue();
  }

  @Test
  public void getState_afterEnable() {
    bluetoothAdapter.enable();
    assertThat(bluetoothAdapter.getState()).isEqualTo(BluetoothAdapter.STATE_ON);
    bluetoothAdapter.disable();
    assertThat(bluetoothAdapter.getState()).isEqualTo(BluetoothAdapter.STATE_OFF);
  }

  @Test
  public void isEnabled_afterSetState() {
    assertThat(bluetoothAdapter.isEnabled()).isFalse();
    shadowOf(bluetoothAdapter).setState(BluetoothAdapter.STATE_ON);
    assertThat(bluetoothAdapter.isEnabled()).isTrue();
    shadowOf(bluetoothAdapter).setState(BluetoothAdapter.STATE_DISCONNECTING);
    assertThat(bluetoothAdapter.isEnabled()).isFalse();
  }

  @Test
  public void canDisable_withAndroidApi() throws Exception {
    shadowOf(bluetoothAdapter).setEnabled(true);
    bluetoothAdapter.disable();
    assertThat(bluetoothAdapter.isEnabled()).isFalse();
  }

  @Test
  public void name_getAndSet() throws Exception {
    // The name shouldn't be null, even before we set anything.
    assertThat(bluetoothAdapter.getName()).isNotNull();

    bluetoothAdapter.setName("Foo");
    assertThat(bluetoothAdapter.getName()).isEqualTo("Foo");
  }

  @Test
  @Config(maxSdk = S_V2)
  public void scanMode_getAndSet_connectable() {
    boolean result =
        ReflectionHelpers.callInstanceMethod(
            bluetoothAdapter,
            "setScanMode",
            ClassParameter.from(int.class, BluetoothAdapter.SCAN_MODE_CONNECTABLE));
    assertThat(result).isTrue();
    assertThat(bluetoothAdapter.getScanMode()).isEqualTo(BluetoothAdapter.SCAN_MODE_CONNECTABLE);
  }

  @Test
  @Config(maxSdk = S_V2)
  public void scanMode_getAndSet_discoverable() {
    boolean result =
        ReflectionHelpers.callInstanceMethod(
            bluetoothAdapter,
            "setScanMode",
            ClassParameter.from(int.class, BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE));
    assertThat(result).isTrue();
    assertThat(bluetoothAdapter.getScanMode())
        .isEqualTo(BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE);
  }

  @Test
  @Config(maxSdk = S_V2)
  public void scanMode_getAndSet_none() throws Exception {
    boolean result =
        ReflectionHelpers.callInstanceMethod(
            bluetoothAdapter,
            "setScanMode",
            ClassParameter.from(int.class, BluetoothAdapter.SCAN_MODE_NONE));
    assertThat(result).isTrue();
    assertThat(bluetoothAdapter.getScanMode()).isEqualTo(BluetoothAdapter.SCAN_MODE_NONE);
  }

  @Test
  @Config(maxSdk = S_V2)
  public void scanMode_getAndSet_invalid() throws Exception {
    boolean result =
        ReflectionHelpers.callInstanceMethod(
            bluetoothAdapter, "setScanMode", ClassParameter.from(int.class, 9999));
    assertThat(result).isFalse();
  }

  @Config(maxSdk = Q)
  @Test
  public void scanMode_withDiscoverableTimeout() {
    assertThat(
            (boolean)
                ReflectionHelpers.callInstanceMethod(
                    bluetoothAdapter,
                    "setScanMode",
                    ClassParameter.from(
                        int.class, BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE),
                    ClassParameter.from(int.class, 42)))
        .isTrue();
    assertThat(bluetoothAdapter.getScanMode())
        .isEqualTo(BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE);
    int result = ReflectionHelpers.callInstanceMethod(bluetoothAdapter, "getDiscoverableTimeout");
    assertThat(result).isEqualTo(42);
  }

  @Config(minSdk = R, maxSdk = S_V2)
  @Test
  public void scanMode_withDiscoverableTimeout_R() {
    assertThat(
            (boolean)
                ReflectionHelpers.callInstanceMethod(
                    bluetoothAdapter,
                    "setScanMode",
                    ClassParameter.from(
                        int.class, BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE),
                    ClassParameter.from(long.class, 42_000L)))
        .isTrue();
    assertThat(bluetoothAdapter.getScanMode())
        .isEqualTo(BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE);
    int result = ReflectionHelpers.callInstanceMethod(bluetoothAdapter, "getDiscoverableTimeout");
    assertThat(result).isEqualTo(42);
  }

  @Test
  @Config(maxSdk = S)
  public void discoverableTimeout_getAndSet() {
    ReflectionHelpers.callInstanceMethod(
        bluetoothAdapter,
        "setDiscoverableTimeout",
        ClassParameter.from(int.class, 60 /* seconds */));
    int result = ReflectionHelpers.callInstanceMethod(bluetoothAdapter, "getDiscoverableTimeout");
    assertThat(result).isEqualTo(60);
  }

  @Config(minSdk = TIRAMISU)
  @Test
  public void scanMode_getAndSet_connectable_T() throws Exception {
    assertThat(bluetoothAdapter.setScanMode(BluetoothAdapter.SCAN_MODE_CONNECTABLE))
        .isEqualTo(BluetoothStatusCodes.SUCCESS);
    assertThat(bluetoothAdapter.getScanMode()).isEqualTo(BluetoothAdapter.SCAN_MODE_CONNECTABLE);
  }

  @Config(minSdk = TIRAMISU)
  @Test
  public void scanMode_getAndSet_discoverable_T() throws Exception {
    assertThat(bluetoothAdapter.setScanMode(BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE))
        .isEqualTo(BluetoothStatusCodes.SUCCESS);
    assertThat(bluetoothAdapter.getScanMode())
        .isEqualTo(BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE);
  }

  @Config(minSdk = TIRAMISU)
  @Test
  public void scanMode_getAndSet_none_T() throws Exception {
    assertThat(bluetoothAdapter.setScanMode(BluetoothAdapter.SCAN_MODE_NONE))
        .isEqualTo(BluetoothStatusCodes.SUCCESS);
    assertThat(bluetoothAdapter.getScanMode()).isEqualTo(BluetoothAdapter.SCAN_MODE_NONE);
  }

  @Config(minSdk = TIRAMISU)
  @Test
  public void scanMode_getAndSet_invalid_T() throws Exception {
    assertThat(bluetoothAdapter.setScanMode(9999)).isEqualTo(BluetoothStatusCodes.ERROR_UNKNOWN);
  }

  @Test
  @Config(minSdk = M)
  public void isLeEnabled() throws Exception {
    // Le is enabled when either BT or BLE is enabled. Check all states.
    BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();

    // Both BT and BLE enabled.
    adapter.enable();
    shadowOf(adapter).setBleScanAlwaysAvailable(true);
    assertThat(adapter.isLeEnabled()).isTrue();

    // BT enabled, BLE disabled.
    adapter.enable();
    shadowOf(adapter).setBleScanAlwaysAvailable(false);
    assertThat(adapter.isLeEnabled()).isTrue();

    // BT disabled, BLE enabled.
    adapter.disable();
    shadowOf(adapter).setBleScanAlwaysAvailable(true);
    assertThat(adapter.isLeEnabled()).isTrue();

    // BT disabled, BLE disabled.
    adapter.disable();
    shadowOf(adapter).setBleScanAlwaysAvailable(false);
    assertThat(adapter.isLeEnabled()).isFalse();
  }

  @Test
  public void testLeScan() {
    BluetoothAdapter.LeScanCallback callback1 = newLeScanCallback();
    BluetoothAdapter.LeScanCallback callback2 = newLeScanCallback();

    bluetoothAdapter.startLeScan(callback1);
    assertThat(shadowOf(bluetoothAdapter).getLeScanCallbacks()).containsExactly(callback1);
    bluetoothAdapter.startLeScan(callback2);
    assertThat(shadowOf(bluetoothAdapter).getLeScanCallbacks())
        .containsExactly(callback1, callback2);

    bluetoothAdapter.stopLeScan(callback1);
    assertThat(shadowOf(bluetoothAdapter).getLeScanCallbacks()).containsExactly(callback2);
    bluetoothAdapter.stopLeScan(callback2);
    assertThat(shadowOf(bluetoothAdapter).getLeScanCallbacks()).isEmpty();
  }

  @Test
  public void testGetSingleLeScanCallback() {
    BluetoothAdapter.LeScanCallback callback1 = newLeScanCallback();
    BluetoothAdapter.LeScanCallback callback2 = newLeScanCallback();

    bluetoothAdapter.startLeScan(callback1);
    assertThat(shadowOf(bluetoothAdapter).getSingleLeScanCallback()).isEqualTo(callback1);

    bluetoothAdapter.startLeScan(callback2);
    IllegalStateException expected =
        assertThrows(
            IllegalStateException.class,
            () -> shadowOf(bluetoothAdapter).getSingleLeScanCallback());
    assertThat(expected).hasMessageThat().isEqualTo("There are 2 callbacks");
  }

  /**
   * Verifies that the state of any specific remote device is global. Although in robolectric this
   * is accomplished by caching the same instance, in android, multiple unique instances
   * nevertheless return the same state so long as they point to the same address.
   */
  @Test
  public void testGetRemoteDevice_sameState() {
    BluetoothDevice remoteDevice1 = bluetoothAdapter.getRemoteDevice(MOCK_MAC_ADDRESS);
    BluetoothDevice remoteDevice2 = bluetoothAdapter.getRemoteDevice(MOCK_MAC_ADDRESS);

    assertThat(remoteDevice2.getBondState()).isEqualTo(BluetoothDevice.BOND_NONE);
    shadowOf(remoteDevice1).setBondState(BluetoothDevice.BOND_BONDED);
    assertThat(remoteDevice2.getBondState()).isEqualTo(BluetoothDevice.BOND_BONDED);
  }

  @Test
  public void insecureRfcomm_notNull() throws Exception {
    assertThat(
            bluetoothAdapter.listenUsingInsecureRfcommWithServiceRecord(
                "serviceName", UUID.randomUUID()))
        .isNotNull();
  }

  @Test
  public void secureRfcomm_notNull() throws Exception {
    assertThat(
            bluetoothAdapter.listenUsingRfcommWithServiceRecord("serviceName", UUID.randomUUID()))
        .isNotNull();
  }

  @Test
  @Config(minSdk = Q)
  public void insecureL2capChannel_notNull() throws Exception {
    assertThat(bluetoothAdapter.listenUsingInsecureL2capChannel()).isNotNull();
  }

  @Test
  @Config(minSdk = Q)
  public void l2capChannel_notNull() throws Exception {
    assertThat(bluetoothAdapter.listenUsingL2capChannel()).isNotNull();
  }

  @Test
  public void canGetProfileConnectionState() throws Exception {
    BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
    assertThat(adapter.getProfileConnectionState(BluetoothProfile.HEADSET))
        .isEqualTo(BluetoothProfile.STATE_DISCONNECTED);
    shadowOf(adapter)
        .setProfileConnectionState(BluetoothProfile.HEADSET, BluetoothProfile.STATE_CONNECTED);
    assertThat(adapter.getProfileConnectionState(BluetoothProfile.HEADSET))
        .isEqualTo(BluetoothProfile.STATE_CONNECTED);
    assertThat(adapter.getProfileConnectionState(BluetoothProfile.A2DP))
        .isEqualTo(BluetoothProfile.STATE_DISCONNECTED);
  }

  @Test
  public void getProfileProxy_afterSetProfileProxy_callsServiceListener() {
    BluetoothProfile mockProxy = mock(BluetoothProfile.class);
    BluetoothProfile.ServiceListener mockServiceListener =
        mock(BluetoothProfile.ServiceListener.class);
    shadowOf(bluetoothAdapter).setProfileProxy(MOCK_PROFILE1, mockProxy);

    boolean result =
        bluetoothAdapter.getProfileProxy(
            RuntimeEnvironment.getApplication(), mockServiceListener, MOCK_PROFILE1);

    assertThat(result).isTrue();
    verify(mockServiceListener).onServiceConnected(MOCK_PROFILE1, mockProxy);
  }

  @Test
  public void getProfileProxy_afterSetProfileProxyWithNullArgument_doesNotCallServiceListener() {
    shadowOf(bluetoothAdapter).setProfileProxy(MOCK_PROFILE1, null);
    BluetoothProfile.ServiceListener mockServiceListener =
        mock(BluetoothProfile.ServiceListener.class);

    boolean result =
        bluetoothAdapter.getProfileProxy(
            RuntimeEnvironment.getApplication(), mockServiceListener, MOCK_PROFILE1);

    assertThat(result).isFalse();
    verifyNoMoreInteractions(mockServiceListener);
  }

  @Test
  public void getProfileProxy_afterSetProfileProxy_forMultipleProfiles() {
    BluetoothProfile mockProxy1 = mock(BluetoothProfile.class);
    shadowOf(bluetoothAdapter).setProfileProxy(MOCK_PROFILE1, mockProxy1);
    BluetoothProfile mockProxy2 = mock(BluetoothProfile.class);
    shadowOf(bluetoothAdapter).setProfileProxy(MOCK_PROFILE2, mockProxy2);
    BluetoothProfile.ServiceListener mockServiceListener =
        mock(BluetoothProfile.ServiceListener.class);

    boolean result1 =
        bluetoothAdapter.getProfileProxy(
            RuntimeEnvironment.getApplication(), mockServiceListener, MOCK_PROFILE1);
    boolean result2 =
        bluetoothAdapter.getProfileProxy(
            RuntimeEnvironment.getApplication(), mockServiceListener, MOCK_PROFILE2);

    assertThat(result1).isTrue();
    assertThat(result2).isTrue();
    verify(mockServiceListener).onServiceConnected(MOCK_PROFILE1, mockProxy1);
    verify(mockServiceListener).onServiceConnected(MOCK_PROFILE2, mockProxy2);
  }

  @Test
  public void hasActiveProfileProxy_reflectsSetProfileProxy() {
    BluetoothProfile mockProxy = mock(BluetoothProfile.class);
    shadowOf(bluetoothAdapter).setProfileProxy(MOCK_PROFILE1, mockProxy);

    assertThat(shadowOf(bluetoothAdapter).hasActiveProfileProxy(MOCK_PROFILE1)).isTrue();
    assertThat(shadowOf(bluetoothAdapter).hasActiveProfileProxy(MOCK_PROFILE2)).isFalse();
  }

  @Test
  public void hasActiveProfileProxy_afterSetProfileProxyWithNullArgument_returnsFalse() {
    shadowOf(bluetoothAdapter).setProfileProxy(MOCK_PROFILE1, null);

    assertThat(shadowOf(bluetoothAdapter).hasActiveProfileProxy(MOCK_PROFILE1)).isFalse();
  }

  @Test
  public void closeProfileProxy_severalCallersObserving_allNotified() {
    BluetoothProfile mockProxy = mock(BluetoothProfile.class);
    BluetoothProfile.ServiceListener mockServiceListener =
        mock(BluetoothProfile.ServiceListener.class);
    BluetoothProfile.ServiceListener mockServiceListener2 =
        mock(BluetoothProfile.ServiceListener.class);
    shadowOf(bluetoothAdapter).setProfileProxy(MOCK_PROFILE1, mockProxy);

    bluetoothAdapter.getProfileProxy(
        RuntimeEnvironment.getApplication(), mockServiceListener, MOCK_PROFILE1);
    bluetoothAdapter.getProfileProxy(
        RuntimeEnvironment.getApplication(), mockServiceListener2, MOCK_PROFILE1);

    bluetoothAdapter.closeProfileProxy(MOCK_PROFILE1, mockProxy);

    verify(mockServiceListener).onServiceDisconnected(MOCK_PROFILE1);
    verify(mockServiceListener2).onServiceDisconnected(MOCK_PROFILE1);
  }

  @Test
  public void closeProfileProxy_severalCallersObservingAndClosedTwice_allNotifiedOnce() {
    BluetoothProfile mockProxy = mock(BluetoothProfile.class);
    BluetoothProfile.ServiceListener mockServiceListener =
        mock(BluetoothProfile.ServiceListener.class);
    BluetoothProfile.ServiceListener mockServiceListener2 =
        mock(BluetoothProfile.ServiceListener.class);
    shadowOf(bluetoothAdapter).setProfileProxy(MOCK_PROFILE1, mockProxy);

    bluetoothAdapter.getProfileProxy(
        RuntimeEnvironment.getApplication(), mockServiceListener, MOCK_PROFILE1);
    bluetoothAdapter.getProfileProxy(
        RuntimeEnvironment.getApplication(), mockServiceListener2, MOCK_PROFILE1);

    bluetoothAdapter.closeProfileProxy(MOCK_PROFILE1, mockProxy);
    verify(mockServiceListener).onServiceConnected(MOCK_PROFILE1, mockProxy);
    verify(mockServiceListener2).onServiceConnected(MOCK_PROFILE1, mockProxy);
    verify(mockServiceListener).onServiceDisconnected(MOCK_PROFILE1);
    verify(mockServiceListener2).onServiceDisconnected(MOCK_PROFILE1);

    bluetoothAdapter.closeProfileProxy(MOCK_PROFILE1, mockProxy);
    verifyNoMoreInteractions(mockServiceListener);
    verifyNoMoreInteractions(mockServiceListener2);
  }

  @Test
  public void closeProfileProxy_reversesSetProfileProxy() {
    BluetoothProfile mockProxy = mock(BluetoothProfile.class);
    BluetoothProfile.ServiceListener mockServiceListener =
        mock(BluetoothProfile.ServiceListener.class);
    shadowOf(bluetoothAdapter).setProfileProxy(MOCK_PROFILE1, mockProxy);

    bluetoothAdapter.closeProfileProxy(MOCK_PROFILE1, mockProxy);
    boolean result =
        bluetoothAdapter.getProfileProxy(
            RuntimeEnvironment.getApplication(), mockServiceListener, MOCK_PROFILE1);

    assertThat(result).isFalse();
    verifyNoMoreInteractions(mockServiceListener);
    assertThat(shadowOf(bluetoothAdapter).hasActiveProfileProxy(MOCK_PROFILE1)).isFalse();
  }

  @Test
  public void closeProfileProxy_afterSetProfileProxy_mismatchedProxy_noOp() {
    BluetoothProfile mockProxy1 = mock(BluetoothProfile.class);
    BluetoothProfile mockProxy2 = mock(BluetoothProfile.class);
    shadowOf(bluetoothAdapter).setProfileProxy(MOCK_PROFILE1, mockProxy1);

    bluetoothAdapter.closeProfileProxy(MOCK_PROFILE1, mockProxy2);

    assertThat(shadowOf(bluetoothAdapter).hasActiveProfileProxy(MOCK_PROFILE1)).isTrue();
  }

  @Test
  public void closeProfileProxy_afterSetProfileProxyWithNullArgument_noOp() {
    BluetoothProfile mockProxy = mock(BluetoothProfile.class);
    shadowOf(bluetoothAdapter).setProfileProxy(MOCK_PROFILE1, null);

    bluetoothAdapter.closeProfileProxy(MOCK_PROFILE1, mockProxy);

    assertThat(shadowOf(bluetoothAdapter).hasActiveProfileProxy(MOCK_PROFILE1)).isFalse();
  }

  @Test
  @Config(minSdk = O)
  public void getLeMaximumAdvertisingDataLength_nonZero() {
    assertThat(bluetoothAdapter.getLeMaximumAdvertisingDataLength()).isEqualTo(1650);

    shadowOf(bluetoothAdapter).setIsLeExtendedAdvertisingSupported(false);

    assertThat(bluetoothAdapter.getLeMaximumAdvertisingDataLength()).isEqualTo(31);
  }

  @Config(minSdk = TIRAMISU)
  @Test
  public void startRfcommServer_mutablePendingIntent_throwsIllegalArgumentException() {
    assertThrows(
        IllegalArgumentException.class,
        () ->
            bluetoothAdapter.startRfcommServer(
                "testname",
                UUID.randomUUID(),
                PendingIntent.getBroadcast(
                    getApplicationContext(),
                    /* requestCode= */ 0,
                    new Intent("com.dummy.action.DUMMY_ACTION")
                        .setPackage(getApplicationContext().getPackageName()),
                    /* flags= */ PendingIntent.FLAG_MUTABLE)));
  }

  @Config(minSdk = TIRAMISU)
  @Test
  public void startRfcommServer_newUuid_success() {
    PendingIntent rfcommServerIntent =
        PendingIntent.getBroadcast(
            getApplicationContext(),
            /* requestCode= */ 0,
            new Intent("com.dummy.action.DUMMY_ACTION"),
            /* flags= */ PendingIntent.FLAG_IMMUTABLE);

    assertThat(
            bluetoothAdapter.startRfcommServer("testname", UUID.randomUUID(), rfcommServerIntent))
        .isEqualTo(BluetoothStatusCodes.SUCCESS);
  }

  @Config(minSdk = TIRAMISU)
  @Test
  public void startRfcommServer_existingUuid_fails() {
    PendingIntent rfcommServerIntent = createTestPendingIntent(testIntent);

    bluetoothAdapter.startRfcommServer("testname", UUID1, rfcommServerIntent);

    assertThat(bluetoothAdapter.startRfcommServer("newtestname", UUID1, rfcommServerIntent))
        .isEqualTo(ShadowBluetoothAdapter.RFCOMM_LISTENER_START_FAILED_UUID_IN_USE);
  }

  @Config(minSdk = TIRAMISU)
  @Test
  public void stopRfcommServer_existingUuid_succeeds() {
    PendingIntent rfcommServerIntent = createTestPendingIntent(testIntent);

    bluetoothAdapter.startRfcommServer("testname", UUID1, rfcommServerIntent);

    assertThat(bluetoothAdapter.stopRfcommServer(UUID1)).isEqualTo(BluetoothStatusCodes.SUCCESS);
  }

  @Config(minSdk = TIRAMISU)
  @Test
  public void stopRfcommServer_noExistingUuid_fails() {
    PendingIntent rfcommServerIntent = createTestPendingIntent(testIntent);

    bluetoothAdapter.startRfcommServer("testname", UUID1, rfcommServerIntent);

    assertThat(bluetoothAdapter.stopRfcommServer(UUID2))
        .isEqualTo(
            ShadowBluetoothAdapter.RFCOMM_LISTENER_OPERATION_FAILED_NO_MATCHING_SERVICE_RECORD);
  }

  @Config(minSdk = TIRAMISU)
  @Test
  public void retrieveConnectedRfcommSocket_noPendingSocket_returnsNull() {
    PendingIntent rfcommServerIntent = createTestPendingIntent(testIntent);

    bluetoothAdapter.startRfcommServer("testname", UUID1, rfcommServerIntent);

    assertThat(bluetoothAdapter.retrieveConnectedRfcommSocket(UUID1)).isNull();
  }

  @Config(minSdk = TIRAMISU)
  @Test
  public void retrieveConnectedRfcommSocket_pendingSocket_returnsSocket() throws Exception {
    PendingIntent rfcommServerIntent = createTestPendingIntent(testIntent);

    bluetoothAdapter.startRfcommServer("testname", UUID1, rfcommServerIntent);
    ((ShadowBluetoothAdapter) Shadow.extract(bluetoothAdapter))
        .addIncomingRfcommConnection(bluetoothAdapter.getRemoteDevice("AB:CD:EF:12:34:56"), UUID1);

    assertThat(bluetoothAdapter.retrieveConnectedRfcommSocket(UUID1)).isNotNull();
  }

  @Config(minSdk = TIRAMISU)
  @Test
  public void retrieveConnectedRfcommSocket_pendingSocket_wrongUuid_returnsNull() throws Exception {
    PendingIntent rfcommServerIntent = createTestPendingIntent(testIntent);

    bluetoothAdapter.startRfcommServer("testname", UUID1, rfcommServerIntent);
    bluetoothAdapter.startRfcommServer("othertestname", UUID2, rfcommServerIntent);
    ((ShadowBluetoothAdapter) Shadow.extract(bluetoothAdapter))
        .addIncomingRfcommConnection(bluetoothAdapter.getRemoteDevice("AB:CD:EF:12:34:56"), UUID1);

    assertThat(bluetoothAdapter.retrieveConnectedRfcommSocket(UUID2)).isNull();
  }

  @Config(minSdk = TIRAMISU)
  @Test
  public void addIncomingRfcommConnection_pendingIntentFired() throws Exception {
    PendingIntent rfcommServerIntent = createTestPendingIntent(testIntent);

    bluetoothAdapter.startRfcommServer("testname", UUID1, rfcommServerIntent);
    ((ShadowBluetoothAdapter) Shadow.extract(bluetoothAdapter))
        .addIncomingRfcommConnection(bluetoothAdapter.getRemoteDevice("AB:CD:EF:12:34:56"), UUID1);

    assertThat(shadowOf((Application) getApplicationContext()).getBroadcastIntents())
        .contains(testIntent);
  }

  @Config(minSdk = TIRAMISU)
  @Test
  public void addIncomingRfcommConnection_socketRetrieved_canCommunicate() throws Exception {
    PendingIntent rfcommServerIntent = createTestPendingIntent(testIntent);

    bluetoothAdapter.startRfcommServer("testname", UUID1, rfcommServerIntent);
    ((ShadowBluetoothAdapter) Shadow.extract(bluetoothAdapter))
        .addIncomingRfcommConnection(bluetoothAdapter.getRemoteDevice("AB:CD:EF:12:34:56"), UUID1);
    BluetoothSocket socket = bluetoothAdapter.retrieveConnectedRfcommSocket(UUID1);

    byte[] testBytes = "i can haz test string".getBytes(UTF_8);

    shadowOf(socket).getInputStreamFeeder().write(testBytes);
    shadowOf(socket).getInputStreamFeeder().flush();
    shadowOf(socket).getInputStreamFeeder().close();
    socket.getOutputStream().write(testBytes);
    socket.getOutputStream().flush();
    socket.getOutputStream().close();

    assertThat(socket.getInputStream().readAllBytes()).isEqualTo(testBytes);
    assertThat(shadowOf(socket).getOutputStreamSink().readAllBytes()).isEqualTo(testBytes);
  }

  @Config(minSdk = TIRAMISU)
  @Test
  @SuppressWarnings("JdkImmutableCollections")
  public void getResgisteredUuids_returnsRegisteredServers() {
    PendingIntent rfcommServerIntent = createTestPendingIntent(testIntent);

    Set<UUID> serverUuids = Set.of(UUID1, UUID2, UUID3, UUID4, UUID5);

    serverUuids.forEach(
        uuid -> bluetoothAdapter.startRfcommServer(uuid.toString(), uuid, rfcommServerIntent));

    assertThat(
            ((ShadowBluetoothAdapter) Shadow.extract(bluetoothAdapter))
                .getRegisteredRfcommServerUuids())
        .containsExactlyElementsIn(serverUuids);
  }

  @Config(minSdk = TIRAMISU)
  @Test
  @SuppressWarnings("JdkImmutableCollections")
  public void getRegisteredUuids_serversStopped_doesNotReturnStoppedServerUuids() {
    PendingIntent rfcommServerIntent = createTestPendingIntent(testIntent);

    Set<UUID> serverUuids = Set.of(UUID1, UUID2, UUID3, UUID4, UUID5);

    serverUuids.forEach(
        uuid -> bluetoothAdapter.startRfcommServer(uuid.toString(), uuid, rfcommServerIntent));

    bluetoothAdapter.stopRfcommServer(UUID4);

    assertThat(
            ((ShadowBluetoothAdapter) Shadow.extract(bluetoothAdapter))
                .getRegisteredRfcommServerUuids())
        .containsExactly(UUID1, UUID2, UUID3, UUID5);
  }

  @Config(minSdk = TIRAMISU)
  @Test
  public void setDiscoverableTimeout() {
    BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
    adapter.enable();
    assertThat(adapter.setDiscoverableTimeout(Duration.ofSeconds(1000)))
        .isEqualTo(BluetoothStatusCodes.SUCCESS);
    assertThat(adapter.getDiscoverableTimeout().toSeconds()).isEqualTo(1000);
  }

  @Config(minSdk = TIRAMISU)
  @Test
  public void setDiscoverableTimeout_adapterNotEnabled() {
    BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();
    assertThat(adapter.setDiscoverableTimeout(Duration.ZERO))
        .isEqualTo(BluetoothStatusCodes.ERROR_BLUETOOTH_NOT_ENABLED);
  }

  @Config(minSdk = U.SDK_INT)
  @Test
  public void getProfileProxy_serviceListenerInvoked() throws Exception {
    shadowOf((Application) getApplicationContext()).grantPermissions(permission.BLUETOOTH);
    bluetoothAdapter.enable();
    LinkedBlockingQueue<Integer> profileQueue = new LinkedBlockingQueue<>();
    LinkedBlockingQueue<BluetoothProfile> proxyQueue = new LinkedBlockingQueue<>();
    BluetoothProfile.ServiceListener listener =
        new ServiceListener() {
          @Override
          public void onServiceConnected(int profile, BluetoothProfile proxy) {
            profileQueue.add(profile);
            proxyQueue.add(proxy);
          }

          @Override
          public void onServiceDisconnected(int profile) {}
        };

    assertThat(
            bluetoothAdapter.getProfileProxy(
                getApplicationContext(), listener, BluetoothProfile.HEADSET))
        .isTrue();
    shadowOf(Looper.getMainLooper()).idle();

    assertThat(profileQueue.take()).isEqualTo(BluetoothProfile.HEADSET);
    assertThat(proxyQueue.take()).isInstanceOf(BluetoothHeadset.class);
  }

  @Config(minSdk = U.SDK_INT)
  @Test
  public void getProfileProxy_adapterDisabled_serviceListenerNotInvoked() {
    shadowOf((Application) getApplicationContext()).grantPermissions(permission.BLUETOOTH);
    BluetoothProfile.ServiceListener listener =
        Mockito.mock(BluetoothProfile.ServiceListener.class);

    bluetoothAdapter.getProfileProxy(getApplicationContext(), listener, BluetoothProfile.HEADSET);
    shadowOf(Looper.getMainLooper()).idle();

    verify(listener, never()).onServiceConnected(anyInt(), any(BluetoothProfile.class));
  }

  @Config(minSdk = U.SDK_INT)
  @Test
  public void disconnectProfileProxy_serviceListenerInvoked() throws Exception {
    shadowOf((Application) getApplicationContext()).grantPermissions(permission.BLUETOOTH);
    bluetoothAdapter.enable();
    LinkedBlockingQueue<Integer> profileQueue = new LinkedBlockingQueue<>();
    LinkedBlockingQueue<BluetoothHeadset> headsetProxies = new LinkedBlockingQueue<>();
    BluetoothProfile.ServiceListener listener =
        new ServiceListener() {
          @Override
          public void onServiceConnected(int profile, BluetoothProfile proxy) {
            headsetProxies.add((BluetoothHeadset) proxy);
          }

          @Override
          public void onServiceDisconnected(int profile) {
            profileQueue.add(profile);
          }
        };

    bluetoothAdapter.getProfileProxy(getApplicationContext(), listener, BluetoothProfile.HEADSET);
    shadowOf(Looper.getMainLooper()).idle();
    bluetoothAdapter.closeProfileProxy(BluetoothProfile.HEADSET, headsetProxies.take());
    shadowOf(Looper.getMainLooper()).idle();

    assertThat(profileQueue.take()).isEqualTo(BluetoothProfile.HEADSET);
  }

  private PendingIntent createTestPendingIntent(Intent intent) {
    return PendingIntent.getBroadcast(
        getApplicationContext(), /* requestCode= */ 0, intent, PendingIntent.FLAG_IMMUTABLE);
  }

  private BluetoothAdapter.LeScanCallback newLeScanCallback() {
    return new BluetoothAdapter.LeScanCallback() {
      @Override
      public void onLeScan(BluetoothDevice bluetoothDevice, int i, byte[] bytes) {}
    };
  }

  @Config(minSdk = TIRAMISU)
  @Test
  public void canGetAndSetLeAudioSupport() {
    BluetoothAdapter adapter = BluetoothAdapter.getDefaultAdapter();

    // By default LE feature is not supported
    assertThat(adapter.isLeAudioSupported()).isEqualTo(BluetoothStatusCodes.FEATURE_NOT_SUPPORTED);

    // set Le audio feature to supported.
    shadowOf(adapter).setLeAudioSupported(BluetoothStatusCodes.FEATURE_SUPPORTED);
    assertThat(adapter.isLeAudioSupported()).isEqualTo(BluetoothStatusCodes.FEATURE_SUPPORTED);
  }

  @Config(minSdk = UPSIDE_DOWN_CAKE)
  @Test
  public void canGetAndSetDistanceMeasurementSupport() {
    // By default distance measurement is not supported
    assertThat(bluetoothAdapter.isDistanceMeasurementSupported())
        .isEqualTo(BluetoothStatusCodes.FEATURE_NOT_SUPPORTED);

    // set distance measurement feature to supported.
    shadowOf(bluetoothAdapter)
        .setDistanceMeasurementSupported(BluetoothStatusCodes.FEATURE_SUPPORTED);

    assertThat(bluetoothAdapter.isDistanceMeasurementSupported())
        .isEqualTo(BluetoothStatusCodes.FEATURE_SUPPORTED);
  }

  @Test
  @SuppressWarnings("JdkImmutableCollections")
  public void getBondedDevices_whenSeededWithSet_returnsThatSet() {
    BluetoothDevice device1 = bluetoothAdapter.getRemoteDevice("AB:CD:EF:12:34:56");
    BluetoothDevice device2 = bluetoothAdapter.getRemoteDevice("12:34:56:AB:CD:EF");
    shadowOf(bluetoothAdapter).setBondedDevices(Set.of(device1, device2));

    assertThat(bluetoothAdapter.getBondedDevices()).containsExactly(device1, device2);
  }

  @Test
  public void getBondedDevices_whenSeededWithNull_returnsNull() {
    shadowOf(bluetoothAdapter).setBondedDevices(null);

    assertThat(bluetoothAdapter.getBondedDevices()).isNull();
  }
}