1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
content / web_test / browser / web_test_bluetooth_adapter_provider.cc [blame]
// Copyright 2015 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "content/web_test/browser/web_test_bluetooth_adapter_provider.h"
#include <set>
#include <utility>
#include <vector>
#include "base/format_macros.h"
#include "base/functional/bind.h"
#include "base/functional/callback_helpers.h"
#include "base/location.h"
#include "base/logging.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/string_split.h"
#include "base/strings/string_util.h"
#include "base/strings/stringprintf.h"
#include "base/task/sequenced_task_runner.h"
#include "base/task/single_thread_task_runner.h"
#include "base/test/gmock_callback_support.h"
#include "base/threading/thread.h"
#include "device/bluetooth/bluetooth_adapter.h"
#include "device/bluetooth/bluetooth_device.h"
#include "device/bluetooth/bluetooth_discovery_session.h"
#include "device/bluetooth/public/cpp/bluetooth_address.h"
#include "device/bluetooth/public/cpp/bluetooth_uuid.h"
#include "device/bluetooth/test/mock_bluetooth_adapter.h"
#include "device/bluetooth/test/mock_bluetooth_gatt_connection.h"
#include "device/bluetooth/test/mock_bluetooth_gatt_descriptor.h"
#include "device/bluetooth/test/mock_bluetooth_gatt_notify_session.h"
#include "testing/gmock/include/gmock/gmock.h"
namespace {
using ::base::test::RunOnceCallback;
using ::device::BluetoothAdapter;
using ::device::BluetoothDevice;
using ::device::BluetoothGattCharacteristic;
using ::device::BluetoothGattService;
using ::device::BluetoothRemoteGattCharacteristic;
using ::device::BluetoothRemoteGattDescriptor;
using ::device::BluetoothRemoteGattService;
using ::device::BluetoothUUID;
using ::device::MockBluetoothAdapter;
using ::device::MockBluetoothDevice;
using ::device::MockBluetoothGattCharacteristic;
using ::device::MockBluetoothGattConnection;
using ::device::MockBluetoothGattDescriptor;
using ::device::MockBluetoothGattNotifySession;
using ::device::MockBluetoothGattService;
using ::testing::_;
using ::testing::ElementsAre;
using ::testing::Invoke;
using ::testing::InvokeWithoutArgs;
using ::testing::ResultOf;
using ::testing::Return;
using ::testing::WithArg;
using NiceMockBluetoothAdapter = ::testing::NiceMock<MockBluetoothAdapter>;
using NiceMockBluetoothDevice = ::testing::NiceMock<MockBluetoothDevice>;
using NiceMockBluetoothGattDescriptor =
::testing::NiceMock<MockBluetoothGattDescriptor>;
using NiceMockBluetoothGattCharacteristic =
::testing::NiceMock<MockBluetoothGattCharacteristic>;
using NiceMockBluetoothGattConnection =
::testing::NiceMock<MockBluetoothGattConnection>;
using NiceMockBluetoothGattService =
::testing::NiceMock<MockBluetoothGattService>;
using NiceMockBluetoothGattNotifySession =
::testing::NiceMock<MockBluetoothGattNotifySession>;
// Bluetooth UUIDs suitable to pass to BluetoothUUID():
// Services:
const char kBatteryServiceUUID[] = "180f";
const char kBlocklistTestServiceUUID[] = "611c954a-263b-4f4a-aab6-01ddb953f985";
const char kDeviceInformationServiceUUID[] = "180a";
const char kGenericAccessServiceUUID[] = "1800";
const char kGlucoseServiceUUID[] = "1808";
const char kHealthThermometerUUID[] = "1809";
const char kHeartRateServiceUUID[] = "180d";
const char kHumanInterfaceDeviceServiceUUID[] = "1812";
const char kRequestDisconnectionServiceUUID[] =
"01d7d889-7451-419f-aeb8-d65e7b9277af";
const char kTxPowerServiceUUID[] = "1804";
// Characteristics:
const char kBlocklistExcludeReadsCharacteristicUUID[] =
"bad1c9a2-9a5b-4015-8b60-1579bbbf2135";
const char kRequestDisconnectionCharacteristicUUID[] =
"01d7d88a-7451-419f-aeb8-d65e7b9277af";
const char kBodySensorLocation[] = "2a38";
const char kDeviceNameUUID[] = "2a00";
const char kMeasurementIntervalUUID[] = "2a21";
const char kHeartRateMeasurementUUID[] = "2a37";
const char kSerialNumberStringUUID[] = "2a25";
const char kPeripheralPrivacyFlagUUID[] = "2a02";
// Descriptors:
const char kUserDescriptionUUID[] = "2901";
// Client Config is in our blocklist. It must not be writable
const char kClientConfigUUID[] = "2902";
// Blocklisted descriptor
const char kBlocklistedDescriptorUUID[] =
"bad2ddcf-60db-45cd-bef9-fd72b153cf7c";
const char kBlocklistedReadDescriptorUUID[] =
"bad3ec61-3cc3-4954-9702-7977df514114";
const char kCharacteristicUserDescription[] =
"gatt.characteristic_user_description";
// Invokes Run() on the k-th argument of the function with no arguments.
ACTION_TEMPLATE(RunCallback,
HAS_1_TEMPLATE_PARAMS(int, k),
AND_0_VALUE_PARAMS()) {
return std::move(std::get<k>(args)).Run();
}
// Invokes Run() on the k-th argument of the function with 1 argument.
ACTION_TEMPLATE(RunCallback,
HAS_1_TEMPLATE_PARAMS(int, k),
AND_1_VALUE_PARAMS(p0)) {
return std::move(std::get<k>(args)).Run(p0);
}
// Invokes Run() on the k-th argument of the function with the result
// of |func| as an argument.
ACTION_TEMPLATE(RunCallbackWithResult,
HAS_1_TEMPLATE_PARAMS(int, k),
AND_1_VALUE_PARAMS(func)) {
return std::move(std::get<k>(args)).Run(func());
}
// Invokes Run() on the k-th argument of the function with the arguments p0
// and p1
ACTION_TEMPLATE(RunCallbackWithResult,
HAS_1_TEMPLATE_PARAMS(int, k),
AND_2_VALUE_PARAMS(p0, p1)) {
return std::move(std::get<k>(args)).Run(p0, p1);
}
// Invokes Run() on the k-th argument of the function with the arguments p0
// and the result from func
ACTION_TEMPLATE(RunCallbackWithResultFunction,
HAS_1_TEMPLATE_PARAMS(int, k),
AND_2_VALUE_PARAMS(p0, func)) {
return std::move(std::get<k>(args)).Run(p0, func());
}
// Invokes Run() on the k-th argument of the function with the
// result from func and argument p1
ACTION_TEMPLATE(RunCallbackWithFunctionResult,
HAS_1_TEMPLATE_PARAMS(int, k),
AND_2_VALUE_PARAMS(func, p1)) {
return std::move(std::get<k>(args)).Run(func(), p1);
}
// Function to iterate over the adapter's devices and return the one
// that matches the address.
ACTION_P(GetMockDevice, adapter) {
std::string address = arg0;
for (BluetoothDevice* device : adapter->GetMockDevices()) {
if (device->GetAddress() == address)
return device;
}
return nullptr;
}
std::set<BluetoothUUID> GetUUIDs(
const device::BluetoothDiscoveryFilter* filter) {
std::set<BluetoothUUID> result;
filter->GetUUIDs(result);
return result;
}
// Notifies the adapter's observers for each device id the adapter.
void NotifyDevicesAdded(MockBluetoothAdapter* adapter) {
for (BluetoothDevice* device : adapter->GetMockDevices()) {
for (auto& observer : adapter->GetObservers())
observer.DeviceAdded(adapter, device);
}
}
// Notifies the adapter's observers that the services have been discovered.
void NotifyServicesDiscovered(MockBluetoothAdapter* adapter,
MockBluetoothDevice* device) {
for (auto& observer : adapter->GetObservers())
observer.GattServicesDiscovered(adapter, device);
}
// Notifies the adapter's observers that a device has changed.
void NotifyDeviceChanged(MockBluetoothAdapter* adapter,
MockBluetoothDevice* device) {
for (auto& observer : adapter->GetObservers())
observer.DeviceChanged(adapter, device);
}
} // namespace
namespace content {
// static
scoped_refptr<BluetoothAdapter>
WebTestBluetoothAdapterProvider::GetBluetoothAdapter(
const std::string& fake_adapter_name) {
// When modifying the set of supported test adapters this information must be
// kept in sync with
// third_party/blink/renderer/modules/bluetooth/testing/clusterfuzz/wbt_fakes.py
// so that invalid test cases are not generated.
if (fake_adapter_name == "BaseAdapter")
return GetBaseAdapter();
if (fake_adapter_name == "ScanFilterCheckingAdapter")
return GetScanFilterCheckingAdapter();
if (fake_adapter_name == "EmptyAdapter")
return GetEmptyAdapter();
if (fake_adapter_name == "FailStartDiscoveryAdapter")
return GetFailStartDiscoveryAdapter();
if (fake_adapter_name == "GlucoseHeartRateAdapter")
return GetGlucoseHeartRateAdapter();
if (fake_adapter_name == "MissingServiceHeartRateAdapter")
return GetMissingServiceHeartRateAdapter();
if (fake_adapter_name == "MissingCharacteristicHeartRateAdapter")
return GetMissingCharacteristicHeartRateAdapter();
if (fake_adapter_name == "HeartRateAdapter")
return GetHeartRateAdapter();
if (fake_adapter_name == "NoNameDeviceAdapter")
return GetNoNameDeviceAdapter();
if (fake_adapter_name == "EmptyNameHeartRateAdapter")
return GetEmptyNameHeartRateAdapter();
if (fake_adapter_name == "NoNameHeartRateAdapter")
return GetNoNameHeartRateAdapter();
if (fake_adapter_name == "TwoHeartRateServicesAdapter")
return GetTwoHeartRateServicesAdapter();
if (fake_adapter_name == "DisconnectingHeartRateAdapter")
return GetDisconnectingHeartRateAdapter();
if (fake_adapter_name == "DisconnectingHealthThermometerAdapter")
return GetDisconnectingHealthThermometer(true);
if (fake_adapter_name ==
"MissingDescriptorsDisconnectingHealthThermometerAdapter")
return GetDisconnectingHealthThermometer(false);
if (fake_adapter_name == "DisconnectingDuringServiceRetrievalAdapter")
return GetServicesDiscoveredAfterReconnectionAdapter(true /* disconnect */);
if (fake_adapter_name == "ServicesDiscoveredAfterReconnectionAdapter")
return GetServicesDiscoveredAfterReconnectionAdapter(
false /* disconnect */);
if (fake_adapter_name == "DisconnectingDuringSuccessGATTOperationAdapter") {
return GetGATTOperationFinishesAfterReconnectionAdapter(
true /* disconnect */, true /* succeeds */);
}
if (fake_adapter_name == "DisconnectingDuringFailureGATTOperationAdapter") {
return GetGATTOperationFinishesAfterReconnectionAdapter(
true /* disconnect */, false /* succeeds */);
}
if (fake_adapter_name == "GATTOperationSucceedsAfterReconnectionAdapter") {
return GetGATTOperationFinishesAfterReconnectionAdapter(
false /* disconnect */, true /* succeeds */);
}
if (fake_adapter_name == "GATTOperationFailsAfterReconnectionAdapter") {
return GetGATTOperationFinishesAfterReconnectionAdapter(
false /* disconnect */, false /* succeeds */);
}
if (fake_adapter_name == "DisconnectingDuringStopNotifySessionAdapter") {
return GetStopNotifySessionFinishesAfterReconnectionAdapter(
true /* disconnect */);
}
if (fake_adapter_name ==
"StopNotifySessionFinishesAfterReconnectionAdapter") {
return GetStopNotifySessionFinishesAfterReconnectionAdapter(
false /* disconnect */);
}
if (fake_adapter_name == "BlocklistTestAdapter")
return GetBlocklistTestAdapter();
if (fake_adapter_name == "FailingConnectionsAdapter")
return GetFailingConnectionsAdapter();
if (fake_adapter_name == "FailingGATTOperationsAdapter")
return GetFailingGATTOperationsAdapter();
if (fake_adapter_name == "SecondDiscoveryFindsHeartRateAdapter")
return GetSecondDiscoveryFindsHeartRateAdapter();
if (fake_adapter_name == "DeviceEventAdapter")
return GetDeviceEventAdapter();
if (fake_adapter_name == "DevicesRemovedAdapter")
return GetDevicesRemovedAdapter();
if (fake_adapter_name == "DelayedServicesDiscoveryAdapter")
return GetDelayedServicesDiscoveryAdapter();
if (fake_adapter_name.empty())
return nullptr;
LOG(ERROR) << "Test requested unrecognized adapter: " << fake_adapter_name;
return nullptr;
}
// Adapters
// static
scoped_refptr<NiceMockBluetoothAdapter>
WebTestBluetoothAdapterProvider::GetBaseAdapter() {
scoped_refptr<NiceMockBluetoothAdapter> adapter(
new NiceMockBluetoothAdapter());
// Using Invoke allows the adapter returned from this method to be futher
// modified and have devices added to it. The call to ::GetDevices will
// invoke ::GetConstMockDevices, returning all devices added up to that time.
ON_CALL(*adapter, GetDevices())
.WillByDefault(
Invoke(adapter.get(), &MockBluetoothAdapter::GetConstMockDevices));
// The call to ::GetDevice will invoke GetMockDevice which returns a device
// matching the address provided if the device was added to the mock.
ON_CALL(*adapter, GetDevice(_)).WillByDefault(GetMockDevice(adapter.get()));
return adapter;
}
// static
scoped_refptr<NiceMockBluetoothAdapter>
WebTestBluetoothAdapterProvider::GetPresentAdapter() {
scoped_refptr<NiceMockBluetoothAdapter> adapter(GetBaseAdapter());
ON_CALL(*adapter, IsPresent()).WillByDefault(Return(true));
return adapter;
}
// static
scoped_refptr<NiceMockBluetoothAdapter>
WebTestBluetoothAdapterProvider::GetPoweredAdapter() {
scoped_refptr<NiceMockBluetoothAdapter> adapter(GetPresentAdapter());
ON_CALL(*adapter, IsPowered()).WillByDefault(Return(true));
return adapter;
}
// static
scoped_refptr<NiceMockBluetoothAdapter>
WebTestBluetoothAdapterProvider::GetScanFilterCheckingAdapter() {
scoped_refptr<NiceMockBluetoothAdapter> adapter(GetPoweredAdapter());
MockBluetoothAdapter* adapter_ptr = adapter.get();
// This fails the test with an error message listing actual and expected UUIDs
// if StartDiscoverySessionWithFilter() is called with the wrong argument.
EXPECT_CALL(
*adapter,
StartScanWithFilter_(
ResultOf(&GetUUIDs, ElementsAre(BluetoothUUID(kGlucoseServiceUUID),
BluetoothUUID(kHeartRateServiceUUID),
BluetoothUUID(kBatteryServiceUUID))),
_))
.WillRepeatedly(
Invoke([adapter_ptr](
const device::BluetoothDiscoveryFilter* discovery_filter,
device::BluetoothAdapter::DiscoverySessionResultCallback&
callback) {
base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, base::BindOnce(&NotifyDevicesAdded,
base::RetainedRef(adapter_ptr)));
std::move(callback).Run(
/*is_error=*/false,
device::UMABluetoothDiscoverySessionOutcome::SUCCESS);
}));
// Any unexpected call results in the failure callback.
ON_CALL(*adapter, StartScanWithFilter_(_, _))
.WillByDefault(RunCallbackWithResult<1 /* result_callback */>(
/*is_error=*/true,
device::UMABluetoothDiscoverySessionOutcome::UNKNOWN));
// We need to add a device otherwise requestDevice would reject.
adapter->AddMockDevice(GetBatteryDevice(adapter.get()));
return adapter;
}
// static
scoped_refptr<NiceMockBluetoothAdapter>
WebTestBluetoothAdapterProvider::GetFailStartDiscoveryAdapter() {
scoped_refptr<NiceMockBluetoothAdapter> adapter(GetPoweredAdapter());
ON_CALL(*adapter, StartScanWithFilter_(_, _))
.WillByDefault(RunCallbackWithResult<1 /* result_callback */>(
/*is_error=*/true,
device::UMABluetoothDiscoverySessionOutcome::UNKNOWN));
return adapter;
}
// static
scoped_refptr<NiceMockBluetoothAdapter>
WebTestBluetoothAdapterProvider::GetEmptyAdapter() {
scoped_refptr<NiceMockBluetoothAdapter> adapter(GetPoweredAdapter());
MockBluetoothAdapter* adapter_ptr = adapter.get();
ON_CALL(*adapter, StartScanWithFilter_(_, _))
.WillByDefault(RunCallbackWithResultFunction<1 /* result_callback */>(
/*is_error=*/false, [adapter_ptr]() {
base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, base::BindOnce(&NotifyDevicesAdded,
base::RetainedRef(adapter_ptr)));
return device::UMABluetoothDiscoverySessionOutcome::SUCCESS;
}));
ON_CALL(*adapter, StopScan(_))
.WillByDefault(
Invoke([](device::BluetoothAdapter::DiscoverySessionResultCallback
callback) {
std::move(callback).Run(
/*is_error=*/false,
device::UMABluetoothDiscoverySessionOutcome::SUCCESS);
}));
return adapter;
}
// static
scoped_refptr<NiceMockBluetoothAdapter>
WebTestBluetoothAdapterProvider::GetGlucoseHeartRateAdapter() {
scoped_refptr<NiceMockBluetoothAdapter> adapter(GetEmptyAdapter());
adapter->AddMockDevice(GetHeartRateDevice(adapter.get()));
adapter->AddMockDevice(GetGlucoseDevice(adapter.get()));
return adapter;
}
// Adds a device to |adapter| and notifies all observers about that new device.
// Mocks can call this asynchronously to cause changes in the middle of a test.
static void AddDevice(scoped_refptr<NiceMockBluetoothAdapter> adapter,
std::unique_ptr<NiceMockBluetoothDevice> new_device) {
NiceMockBluetoothDevice* new_device_ptr = new_device.get();
adapter->AddMockDevice(std::move(new_device));
for (auto& observer : adapter->GetObservers())
observer.DeviceAdded(adapter.get(), new_device_ptr);
}
static void RemoveDevice(scoped_refptr<NiceMockBluetoothAdapter> adapter,
const std::string& device_address) {
std::unique_ptr<MockBluetoothDevice> removed_device =
adapter->RemoveMockDevice(device_address);
for (auto& observer : adapter->GetObservers())
observer.DeviceRemoved(adapter.get(), removed_device.get());
}
// static
scoped_refptr<NiceMockBluetoothAdapter>
WebTestBluetoothAdapterProvider::GetSecondDiscoveryFindsHeartRateAdapter() {
scoped_refptr<NiceMockBluetoothAdapter> adapter(GetPoweredAdapter());
NiceMockBluetoothAdapter* adapter_ptr = adapter.get();
EXPECT_CALL(*adapter, StartScanWithFilter_(_, _))
.WillOnce(RunCallbackWithResult<1 /* result_callback */>(
/*is_error=*/false,
device::UMABluetoothDiscoverySessionOutcome::SUCCESS))
.WillOnce(RunCallbackWithResultFunction<1 /* result_callback */>(
/*is_error=*/false, [adapter_ptr]() {
// In the second discovery session, have the adapter discover a new
// device, shortly after the session starts.
base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE,
base::BindOnce(&AddDevice, base::WrapRefCounted(adapter_ptr),
GetHeartRateDevice(adapter_ptr)));
return device::UMABluetoothDiscoverySessionOutcome::SUCCESS;
}));
EXPECT_CALL(*adapter, StopScan(_)).Times(2);
ON_CALL(*adapter, StopScan(_))
.WillByDefault(
Invoke([](device::BluetoothAdapter::DiscoverySessionResultCallback
callback) {
std::move(callback).Run(
/*is_error=*/false,
device::UMABluetoothDiscoverySessionOutcome::SUCCESS);
}));
return adapter;
}
// static
scoped_refptr<NiceMockBluetoothAdapter>
WebTestBluetoothAdapterProvider::GetDeviceEventAdapter() {
scoped_refptr<NiceMockBluetoothAdapter> adapter(GetPoweredAdapter());
NiceMockBluetoothAdapter* adapter_ptr = adapter.get();
// Add ConnectedHeartRateDevice.
auto connected_hr(GetBaseDevice(adapter.get(), "Connected Heart Rate Device",
{BluetoothUUID(kHeartRateServiceUUID)},
makeMACAddress(0x0)));
connected_hr->SetConnected(true);
adapter->AddMockDevice(std::move(connected_hr));
// Add ChangingBatteryDevice with no uuids.
auto changing_battery(GetBaseDevice(adapter.get(), "Changing Battery Device",
BluetoothDevice::UUIDList(),
makeMACAddress(0x1)));
changing_battery->SetConnected(false);
NiceMockBluetoothDevice* changing_battery_ptr = changing_battery.get();
adapter->AddMockDevice(std::move(changing_battery));
// Add Non Connected Tx Power Device.
auto non_connected_tx_power(
GetBaseDevice(adapter.get(), "Non Connected Tx Power Device",
{BluetoothUUID(kTxPowerServiceUUID)}, makeMACAddress(0x2)));
non_connected_tx_power->SetConnected(false);
adapter->AddMockDevice(std::move(non_connected_tx_power));
// Add Discovery Generic Access Device with no uuids.
auto discovery_generic_access(
GetBaseDevice(adapter.get(), "Discovery Generic Access Device",
BluetoothDevice::UUIDList(), makeMACAddress(0x3)));
discovery_generic_access->SetConnected(true);
NiceMockBluetoothDevice* discovery_generic_access_ptr =
discovery_generic_access.get();
adapter->AddMockDevice(std::move(discovery_generic_access));
ON_CALL(*adapter, StartScanWithFilter_(_, _))
.WillByDefault(RunCallbackWithResultFunction<1 /* result_callback */>(
/*is_error=*/false,
[adapter_ptr, changing_battery_ptr, discovery_generic_access_ptr]() {
if (adapter_ptr->GetDevices().size() == 4) {
// Post task to add NewGlucoseDevice.
auto glucose_device(GetBaseDevice(
adapter_ptr, "New Glucose Device",
{BluetoothUUID(kGlucoseServiceUUID)}, makeMACAddress(0x4)));
base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE,
base::BindOnce(&AddDevice, base::WrapRefCounted(adapter_ptr),
std::move(glucose_device)));
// Add uuid and notify of device changed.
changing_battery_ptr->AddUUID(BluetoothUUID(kBatteryServiceUUID));
base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, base::BindOnce(&NotifyDeviceChanged,
base::RetainedRef(adapter_ptr),
changing_battery_ptr));
// Add uuid and notify of services discovered.
discovery_generic_access_ptr->AddUUID(
BluetoothUUID(kGenericAccessServiceUUID));
base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, base::BindOnce(&NotifyServicesDiscovered,
base::RetainedRef(adapter_ptr),
discovery_generic_access_ptr));
}
return device::UMABluetoothDiscoverySessionOutcome::SUCCESS;
}));
ON_CALL(*adapter, StopScan(_))
.WillByDefault(
Invoke([](device::BluetoothAdapter::DiscoverySessionResultCallback
callback) {
std::move(callback).Run(
/*is_error=*/false,
device::UMABluetoothDiscoverySessionOutcome::SUCCESS);
}));
return adapter;
}
// static
scoped_refptr<NiceMockBluetoothAdapter>
WebTestBluetoothAdapterProvider::GetDevicesRemovedAdapter() {
scoped_refptr<NiceMockBluetoothAdapter> adapter(GetPoweredAdapter());
NiceMockBluetoothAdapter* adapter_ptr = adapter.get();
// Add ConnectedHeartRateDevice.
auto connected_hr(GetBaseDevice(adapter.get(), "Connected Heart Rate Device",
{BluetoothUUID(kHeartRateServiceUUID)},
makeMACAddress(0x0)));
connected_hr->SetConnected(true);
std::string connected_hr_address = connected_hr->GetAddress();
adapter->AddMockDevice(std::move(connected_hr));
ON_CALL(*adapter, StartScanWithFilter_(_, _))
.WillByDefault(RunCallbackWithResultFunction<1 /* result_callback */>(
/*is_error=*/false, [adapter_ptr, connected_hr_address]() {
if (adapter_ptr->GetDevices().size() == 1) {
// Post task to add NewGlucoseDevice.
auto glucose_device(GetBaseDevice(
adapter_ptr, "New Glucose Device",
{BluetoothUUID(kGlucoseServiceUUID)}, makeMACAddress(0x4)));
std::string glucose_address = glucose_device->GetAddress();
base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE,
base::BindOnce(&AddDevice, base::WrapRefCounted(adapter_ptr),
std::move(glucose_device)));
// Post task to remove ConnectedHeartRateDevice.
base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, base::BindOnce(&RemoveDevice,
base::WrapRefCounted(adapter_ptr),
connected_hr_address));
// Post task to remove NewGlucoseDevice.
base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, base::BindOnce(&RemoveDevice,
base::WrapRefCounted(adapter_ptr),
glucose_address));
}
return device::UMABluetoothDiscoverySessionOutcome::SUCCESS;
}));
return adapter;
}
// static
scoped_refptr<NiceMockBluetoothAdapter>
WebTestBluetoothAdapterProvider::GetMissingServiceHeartRateAdapter() {
scoped_refptr<NiceMockBluetoothAdapter> adapter(GetEmptyAdapter());
adapter->AddMockDevice(GetHeartRateDevice(adapter.get()));
return adapter;
}
// static
scoped_refptr<NiceMockBluetoothAdapter>
WebTestBluetoothAdapterProvider::GetMissingCharacteristicHeartRateAdapter() {
scoped_refptr<NiceMockBluetoothAdapter> adapter(GetEmptyAdapter());
auto device(GetHeartRateDevice(adapter.get()));
auto generic_access(GetBaseGATTService("Generic Access", device.get(),
kGenericAccessServiceUUID));
auto heart_rate(
GetBaseGATTService("Heart Rate", device.get(), kHeartRateServiceUUID));
// Intentionally NOT adding a characteristic to heart_rate service.
device->AddMockService(std::move(generic_access));
device->AddMockService(std::move(heart_rate));
adapter->AddMockDevice(std::move(device));
return adapter;
}
// static
scoped_refptr<NiceMockBluetoothAdapter>
WebTestBluetoothAdapterProvider::GetDelayedServicesDiscoveryAdapter() {
scoped_refptr<NiceMockBluetoothAdapter> adapter(GetEmptyAdapter());
auto device(GetHeartRateDevice(adapter.get()));
MockBluetoothAdapter* adapter_ptr = adapter.get();
MockBluetoothDevice* device_ptr = device.get();
// Override the previous mock implementation of
// IsGattServicesDiscoveryComplete so that the first time the function is
// called it returns false, adds a service and posts a task to notify
// the services have been discovered. Subsequent calls to the function
// will return true.
ON_CALL(*device, IsGattServicesDiscoveryComplete())
.WillByDefault(Invoke([adapter_ptr, device_ptr] {
std::vector<BluetoothRemoteGattService*> services =
device_ptr->GetMockServices();
if (services.size() == 0) {
auto heart_rate(GetBaseGATTService("Heart Rate", device_ptr,
kHeartRateServiceUUID));
device_ptr->AddMockService(std::move(heart_rate));
base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE,
base::BindOnce(&NotifyServicesDiscovered,
base::RetainedRef(adapter_ptr), device_ptr));
DCHECK(services.empty());
return false;
}
return true;
}));
adapter->AddMockDevice(std::move(device));
return adapter;
}
// static
scoped_refptr<NiceMockBluetoothAdapter>
WebTestBluetoothAdapterProvider::GetHeartRateAdapter() {
scoped_refptr<NiceMockBluetoothAdapter> adapter(GetEmptyAdapter());
auto device(GetHeartRateDevice(adapter.get()));
// TODO(ortuno): Implement the rest of the service's characteristics
// See: http://crbug.com/529975
device->AddMockService(GetGenericAccessService(device.get()));
device->AddMockService(GetHeartRateService(adapter.get(), device.get()));
adapter->AddMockDevice(std::move(device));
return adapter;
}
// static
scoped_refptr<NiceMockBluetoothAdapter>
WebTestBluetoothAdapterProvider::GetDisconnectingHealthThermometer(
bool add_descriptors) {
scoped_refptr<NiceMockBluetoothAdapter> adapter(GetEmptyAdapter());
NiceMockBluetoothAdapter* adapter_ptr = adapter.get();
auto device(GetConnectableDevice(
adapter_ptr, "Disconnecting Health Thermometer",
std::vector<BluetoothUUID>({BluetoothUUID(kGenericAccessServiceUUID),
BluetoothUUID(kHealthThermometerUUID)})));
device->AddMockService(GetGenericAccessService(device.get()));
device->AddMockService(GetDisconnectingService(adapter.get(), device.get()));
auto health_thermometer(GetBaseGATTService("Health Thermometer", device.get(),
kHealthThermometerUUID));
// Measurement Interval
auto measurement_interval(GetBaseGATTCharacteristic(
"Measurement Interval", health_thermometer.get(),
kMeasurementIntervalUUID,
BluetoothRemoteGattCharacteristic::PROPERTY_READ |
BluetoothRemoteGattCharacteristic::PROPERTY_WRITE |
BluetoothRemoteGattCharacteristic::PROPERTY_NOTIFY));
NiceMockBluetoothGattCharacteristic* measurement_ptr =
measurement_interval.get();
ON_CALL(*measurement_interval, ReadRemoteCharacteristic_(_))
.WillByDefault(RunCallbackWithResult<0>(/*error_code=*/std::nullopt,
std::vector<uint8_t>({1})));
ON_CALL(*measurement_interval, WriteRemoteCharacteristic_(_, _, _, _))
.WillByDefault(RunCallback<2 /* success_callback */>());
ON_CALL(*measurement_interval, DeprecatedWriteRemoteCharacteristic_(_, _, _))
.WillByDefault(RunCallback<1 /* success_callback */>());
ON_CALL(*measurement_interval, StartNotifySession_(_, _))
.WillByDefault(
RunCallbackWithResult<0 /* success_callback */>([measurement_ptr]() {
return GetBaseGATTNotifySession(measurement_ptr->GetWeakPtr());
}));
if (add_descriptors) {
const std::string descriptorName = kCharacteristicUserDescription;
auto user_description = std::make_unique<NiceMockBluetoothGattDescriptor>(
measurement_interval.get(), descriptorName,
BluetoothUUID(kUserDescriptionUUID),
device::BluetoothRemoteGattCharacteristic::PROPERTY_READ);
ON_CALL(*user_description, ReadRemoteDescriptor_(_))
.WillByDefault(
Invoke([descriptorName](
BluetoothRemoteGattDescriptor::ValueCallback& callback) {
std::vector<uint8_t> value(descriptorName.begin(),
descriptorName.end());
std::move(callback).Run(/*error_code=*/std::nullopt, value);
}));
ON_CALL(*user_description, WriteRemoteDescriptor_(_, _, _))
.WillByDefault(RunCallback<1 /* success_callback */>());
auto client_config = std::make_unique<NiceMockBluetoothGattDescriptor>(
measurement_interval.get(), "gatt.client_characteristic_configuration",
BluetoothUUID(kClientConfigUUID),
device::BluetoothRemoteGattCharacteristic::PROPERTY_READ |
device::BluetoothRemoteGattCharacteristic::PROPERTY_WRITE);
// Crash if WriteRemoteDescriptor called. Not using GoogleMock's Expect
// because this is used in web tests that may not report a mock
// expectation.
ON_CALL(*client_config, WriteRemoteDescriptor_(_, _, _))
.WillByDefault(
Invoke([](const std::vector<uint8_t>&, base::OnceClosure&,
BluetoothRemoteGattDescriptor::ErrorCallback&) {
NOTREACHED_IN_MIGRATION();
}));
auto no_read_descriptor = std::make_unique<NiceMockBluetoothGattDescriptor>(
measurement_interval.get(), kBlocklistedReadDescriptorUUID,
BluetoothUUID(kBlocklistedReadDescriptorUUID),
device::BluetoothRemoteGattCharacteristic::PROPERTY_READ |
device::BluetoothRemoteGattCharacteristic::PROPERTY_WRITE);
// Crash if ReadRemoteDescriptor called. Not using GoogleMock's Expect
// because this is used in web tests that may not report a mock
// expectation
// error correctly as a web test failure.
ON_CALL(*no_read_descriptor, ReadRemoteDescriptor_(_))
.WillByDefault(
Invoke([](BluetoothRemoteGattDescriptor::ValueCallback&) {
NOTREACHED_IN_MIGRATION();
}));
// Add it here with full permission as the blocklist should prevent us from
// accessing this descriptor
auto blocklisted_descriptor =
std::make_unique<NiceMockBluetoothGattDescriptor>(
measurement_interval.get(), kBlocklistedDescriptorUUID,
BluetoothUUID(kBlocklistedDescriptorUUID),
device::BluetoothRemoteGattCharacteristic::PROPERTY_READ |
device::BluetoothRemoteGattCharacteristic::PROPERTY_WRITE);
measurement_interval->AddMockDescriptor(std::move(user_description));
measurement_interval->AddMockDescriptor(std::move(client_config));
measurement_interval->AddMockDescriptor(std::move(blocklisted_descriptor));
measurement_interval->AddMockDescriptor(std::move(no_read_descriptor));
}
health_thermometer->AddMockCharacteristic(std::move(measurement_interval));
device->AddMockService(std::move(health_thermometer));
adapter->AddMockDevice(std::move(device));
return adapter;
}
// static
scoped_refptr<NiceMockBluetoothAdapter>
WebTestBluetoothAdapterProvider::GetNoNameDeviceAdapter() {
scoped_refptr<NiceMockBluetoothAdapter> adapter(GetEmptyAdapter());
auto device(GetConnectableDevice(adapter.get(), nullptr /* device_name */));
adapter->AddMockDevice(std::move(device));
return adapter;
}
// static
scoped_refptr<NiceMockBluetoothAdapter>
WebTestBluetoothAdapterProvider::GetEmptyNameHeartRateAdapter() {
scoped_refptr<NiceMockBluetoothAdapter> adapter(GetEmptyAdapter());
auto device(GetHeartRateDevice(adapter.get(), /* device_name */ ""));
// TODO(ortuno): Implement the rest of the service's characteristics
// See: http://crbug.com/529975
device->AddMockService(GetGenericAccessService(device.get()));
device->AddMockService(GetHeartRateService(adapter.get(), device.get()));
adapter->AddMockDevice(std::move(device));
return adapter;
}
// static
scoped_refptr<NiceMockBluetoothAdapter>
WebTestBluetoothAdapterProvider::GetNoNameHeartRateAdapter() {
scoped_refptr<NiceMockBluetoothAdapter> adapter(GetEmptyAdapter());
auto device(GetHeartRateDevice(adapter.get(), /* device_name */ nullptr));
// TODO(ortuno): Implement the rest of the service's characteristics
// See: http://crbug.com/529975
device->AddMockService(GetGenericAccessService(device.get()));
device->AddMockService(GetHeartRateService(adapter.get(), device.get()));
adapter->AddMockDevice(std::move(device));
return adapter;
}
// static
scoped_refptr<NiceMockBluetoothAdapter>
WebTestBluetoothAdapterProvider::GetTwoHeartRateServicesAdapter() {
scoped_refptr<NiceMockBluetoothAdapter> adapter(GetEmptyAdapter());
auto device(GetHeartRateDevice(adapter.get()));
device->AddMockService(GetGenericAccessService(device.get()));
// First Heart Rate Service has one Heart Rate Measurement characteristic
// and one Body Sensor Location characteristic.
auto first_heart_rate(GetBaseGATTService("First Heart Rate", device.get(),
kHeartRateServiceUUID));
// Heart Rate Measurement
auto heart_rate_measurement(GetBaseGATTCharacteristic(
"Heart Rate Measurement", first_heart_rate.get(),
kHeartRateMeasurementUUID,
BluetoothRemoteGattCharacteristic::PROPERTY_NOTIFY));
// Body Sensor Location Characteristic
std::unique_ptr<NiceMockBluetoothGattCharacteristic>
body_sensor_location_chest(GetBaseGATTCharacteristic(
"Body Sensor Location Chest", first_heart_rate.get(),
kBodySensorLocation,
BluetoothRemoteGattCharacteristic::PROPERTY_READ));
first_heart_rate->AddMockCharacteristic(std::move(heart_rate_measurement));
first_heart_rate->AddMockCharacteristic(
std::move(body_sensor_location_chest));
device->AddMockService(std::move(first_heart_rate));
// Second Heart Rate Service has only one Body Sensor Location
// characteristic.
auto second_heart_rate(GetBaseGATTService("Second Heart Rate", device.get(),
kHeartRateServiceUUID));
std::unique_ptr<NiceMockBluetoothGattCharacteristic>
body_sensor_location_wrist(GetBaseGATTCharacteristic(
"Body Sensor Location Wrist", second_heart_rate.get(),
kBodySensorLocation,
BluetoothRemoteGattCharacteristic::PROPERTY_READ));
second_heart_rate->AddMockCharacteristic(
std::move(body_sensor_location_wrist));
device->AddMockService(std::move(second_heart_rate));
adapter->AddMockDevice(std::move(device));
return adapter;
}
// static
scoped_refptr<NiceMockBluetoothAdapter>
WebTestBluetoothAdapterProvider::GetDisconnectingHeartRateAdapter() {
scoped_refptr<NiceMockBluetoothAdapter> adapter(GetEmptyAdapter());
auto device(GetHeartRateDevice(adapter.get()));
// TODO(ortuno): Implement the rest of the service's characteristics
// See: http://crbug.com/529975
device->AddMockService(GetGenericAccessService(device.get()));
device->AddMockService(GetHeartRateService(adapter.get(), device.get()));
device->AddMockService(GetDisconnectingService(adapter.get(), device.get()));
adapter->AddMockDevice(std::move(device));
return adapter;
}
// static
scoped_refptr<NiceMockBluetoothAdapter>
WebTestBluetoothAdapterProvider::GetServicesDiscoveredAfterReconnectionAdapter(
bool disconnect) {
scoped_refptr<NiceMockBluetoothAdapter> adapter(GetEmptyAdapter());
NiceMockBluetoothAdapter* adapter_ptr = adapter.get();
auto device(GetHeartRateDevice(adapter.get()));
NiceMockBluetoothDevice* device_ptr = device.get();
// When called before IsGattDiscoveryComplete, run success callback with a new
// Gatt connection. When called after after IsGattDiscoveryComplete runs
// success callback with a new Gatt connection and notifies of services
// discovered.
ON_CALL(*device, CreateGattConnection(_, _))
.WillByDefault(
[adapter_ptr, device_ptr](
BluetoothDevice::GattConnectionCallback callback,
std::optional<BluetoothUUID> service_uuid) {
std::vector<BluetoothRemoteGattService*> services =
device_ptr->GetMockServices();
if (services.size() != 0) {
base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE,
base::BindOnce(&NotifyServicesDiscovered,
base::RetainedRef(adapter_ptr), device_ptr));
}
device_ptr->SetConnected(true);
std::move(callback).Run(
std::make_unique<NiceMockBluetoothGattConnection>(
adapter_ptr, device_ptr->GetAddress()),
/*error_code=*/std::nullopt);
});
// The first time this function is called we:
// 1. Add a service (This indicates that this function has been called)
// 2. If |disconnect| is true, disconnect the device.
// 3. Return false.
// The second time this function is called we just return true.
ON_CALL(*device, IsGattServicesDiscoveryComplete())
.WillByDefault(Invoke([adapter_ptr, device_ptr, disconnect] {
std::vector<BluetoothRemoteGattService*> services =
device_ptr->GetMockServices();
if (services.size() == 0) {
auto heart_rate(GetBaseGATTService("Heart Rate", device_ptr,
kHeartRateServiceUUID));
device_ptr->AddMockService(GetGenericAccessService(device_ptr));
device_ptr->AddMockService(
GetHeartRateService(adapter_ptr, device_ptr));
if (disconnect) {
device_ptr->SetConnected(false);
base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE,
base::BindOnce(&NotifyDeviceChanged,
base::RetainedRef(adapter_ptr), device_ptr));
}
DCHECK(services.empty());
return false;
}
return true;
}));
adapter->AddMockDevice(std::move(device));
return adapter;
}
// static
scoped_refptr<NiceMockBluetoothAdapter> WebTestBluetoothAdapterProvider::
GetGATTOperationFinishesAfterReconnectionAdapter(bool disconnect,
bool succeeds) {
scoped_refptr<NiceMockBluetoothAdapter> adapter(GetEmptyAdapter());
NiceMockBluetoothAdapter* adapter_ptr = adapter.get();
auto device(GetConnectableDevice(
adapter_ptr, "GATT Operation finishes after reconnection Device",
BluetoothDevice::UUIDList({BluetoothUUID(kGenericAccessServiceUUID),
BluetoothUUID(kHealthThermometerUUID)})));
NiceMockBluetoothDevice* device_ptr = device.get();
ON_CALL(*device, CreateGattConnection(_, _))
.WillByDefault([adapter_ptr, device_ptr](
BluetoothDevice::GattConnectionCallback callback,
std::optional<BluetoothUUID> service_uuid) {
device_ptr->SetConnected(true);
std::move(callback).Run(
std::make_unique<NiceMockBluetoothGattConnection>(
adapter_ptr, device_ptr->GetAddress()),
/*error_code=*/std::nullopt);
device_ptr->RunPendingCallbacks();
});
device->AddMockService(GetGenericAccessService(device.get()));
auto health_thermometer(GetBaseGATTService("Health Thermometer", device.get(),
kHealthThermometerUUID));
// Measurement Interval
auto measurement_interval(GetBaseGATTCharacteristic(
"Measurement Interval", health_thermometer.get(),
kMeasurementIntervalUUID,
BluetoothRemoteGattCharacteristic::PROPERTY_READ |
BluetoothRemoteGattCharacteristic::PROPERTY_WRITE |
BluetoothRemoteGattCharacteristic::PROPERTY_NOTIFY));
NiceMockBluetoothGattCharacteristic* measurement_ptr =
measurement_interval.get();
ON_CALL(*measurement_interval, ReadRemoteCharacteristic_(_))
.WillByDefault(Invoke(
[adapter_ptr, device_ptr, disconnect, succeeds](
BluetoothRemoteGattCharacteristic::ValueCallback& callback) {
base::OnceClosure pending;
if (succeeds) {
pending = base::BindOnce(std::move(callback),
/*error_code=*/std::nullopt,
std::vector<uint8_t>({1}));
} else {
pending =
base::BindOnce(std::move(callback),
BluetoothGattService::GattErrorCode::kFailed,
/*value=*/std::vector<uint8_t>());
}
device_ptr->PushPendingCallback(std::move(pending));
if (disconnect) {
device_ptr->SetConnected(false);
base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE,
base::BindOnce(&NotifyDeviceChanged,
base::RetainedRef(adapter_ptr), device_ptr));
}
}));
ON_CALL(*measurement_interval, WriteRemoteCharacteristic_(_, _, _, _))
.WillByDefault(
Invoke([adapter_ptr, device_ptr, disconnect, succeeds](
const std::vector<uint8_t>& value,
BluetoothRemoteGattCharacteristic::WriteType write_type,
base::OnceClosure& callback,
BluetoothRemoteGattCharacteristic::ErrorCallback&
error_callback) {
base::OnceClosure pending;
if (succeeds) {
pending = std::move(callback);
} else {
pending =
base::BindOnce(std::move(error_callback),
BluetoothGattService::GattErrorCode::kFailed);
}
device_ptr->PushPendingCallback(std::move(pending));
if (disconnect) {
device_ptr->SetConnected(false);
base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE,
base::BindOnce(&NotifyDeviceChanged,
base::RetainedRef(adapter_ptr), device_ptr));
}
}));
ON_CALL(*measurement_interval, DeprecatedWriteRemoteCharacteristic_(_, _, _))
.WillByDefault(Invoke(
[adapter_ptr, device_ptr, disconnect, succeeds](
const std::vector<uint8_t>& value, base::OnceClosure& callback,
BluetoothRemoteGattCharacteristic::ErrorCallback&
error_callback) {
base::OnceClosure pending;
if (succeeds) {
pending = std::move(callback);
} else {
pending =
base::BindOnce(std::move(error_callback),
BluetoothGattService::GattErrorCode::kFailed);
}
device_ptr->PushPendingCallback(std::move(pending));
if (disconnect) {
device_ptr->SetConnected(false);
base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE,
base::BindOnce(&NotifyDeviceChanged,
base::RetainedRef(adapter_ptr), device_ptr));
}
}));
ON_CALL(*measurement_interval, StartNotifySession_(_, _))
.WillByDefault(Invoke(
[adapter_ptr, device_ptr, measurement_ptr, disconnect, succeeds](
BluetoothRemoteGattCharacteristic::NotifySessionCallback&
callback,
BluetoothRemoteGattCharacteristic::ErrorCallback&
error_callback) {
base::OnceClosure pending;
if (succeeds) {
pending = base::BindOnce(
std::move(callback),
GetBaseGATTNotifySession(measurement_ptr->GetWeakPtr()));
} else {
pending =
base::BindOnce(std::move(error_callback),
BluetoothGattService::GattErrorCode::kFailed);
}
device_ptr->PushPendingCallback(std::move(pending));
if (disconnect) {
device_ptr->SetConnected(false);
base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE,
base::BindOnce(&NotifyDeviceChanged,
base::RetainedRef(adapter_ptr), device_ptr));
}
}));
auto user_descriptor = std::make_unique<NiceMockBluetoothGattDescriptor>(
measurement_interval.get(), kCharacteristicUserDescription,
BluetoothUUID(kUserDescriptionUUID),
device::BluetoothRemoteGattCharacteristic::PROPERTY_READ);
ON_CALL(*user_descriptor, ReadRemoteDescriptor_(_))
.WillByDefault(
Invoke([adapter_ptr, device_ptr, disconnect, succeeds](
BluetoothRemoteGattDescriptor::ValueCallback& callback) {
base::OnceClosure pending;
if (succeeds) {
pending = base::BindOnce(std::move(callback),
/*error_code=*/std::nullopt,
std::vector<uint8_t>({1}));
} else {
pending =
base::BindOnce(std::move(callback),
BluetoothGattService::GattErrorCode::kFailed,
/*value=*/std::vector<uint8_t>());
}
device_ptr->PushPendingCallback(std::move(pending));
if (disconnect) {
device_ptr->SetConnected(false);
base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE,
base::BindOnce(&NotifyDeviceChanged,
base::RetainedRef(adapter_ptr), device_ptr));
}
}));
ON_CALL(*user_descriptor, WriteRemoteDescriptor_(_, _, _))
.WillByDefault(Invoke(
[adapter_ptr, device_ptr, disconnect, succeeds](
const std::vector<uint8_t>& value, base::OnceClosure& callback,
BluetoothRemoteGattDescriptor::ErrorCallback& error_callback) {
base::OnceClosure pending;
if (succeeds) {
pending = std::move(callback);
} else {
pending =
base::BindOnce(std::move(error_callback),
BluetoothGattService::GattErrorCode::kFailed);
}
device_ptr->PushPendingCallback(std::move(pending));
if (disconnect) {
device_ptr->SetConnected(false);
base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE,
base::BindOnce(&NotifyDeviceChanged,
base::RetainedRef(adapter_ptr), device_ptr));
}
}));
measurement_interval->AddMockDescriptor(std::move(user_descriptor));
health_thermometer->AddMockCharacteristic(std::move(measurement_interval));
device->AddMockService(std::move(health_thermometer));
adapter->AddMockDevice(std::move(device));
return adapter;
}
// static
scoped_refptr<NiceMockBluetoothAdapter> WebTestBluetoothAdapterProvider::
GetStopNotifySessionFinishesAfterReconnectionAdapter(bool disconnect) {
scoped_refptr<NiceMockBluetoothAdapter> adapter(GetEmptyAdapter());
NiceMockBluetoothAdapter* adapter_ptr = adapter.get();
auto device(GetConnectableDevice(
adapter_ptr, "GATT Operation finishes after reconnection Device",
BluetoothDevice::UUIDList({BluetoothUUID(kGenericAccessServiceUUID),
BluetoothUUID(kHealthThermometerUUID)})));
NiceMockBluetoothDevice* device_ptr = device.get();
ON_CALL(*device, CreateGattConnection(_, _))
.WillByDefault([adapter_ptr, device_ptr](
BluetoothDevice::GattConnectionCallback callback,
std::optional<BluetoothUUID> service_uuid) {
device_ptr->SetConnected(true);
std::move(callback).Run(
std::make_unique<NiceMockBluetoothGattConnection>(
adapter_ptr, device_ptr->GetAddress()),
/*error_code=*/std::nullopt);
device_ptr->RunPendingCallbacks();
});
device->AddMockService(GetGenericAccessService(device.get()));
auto health_thermometer(GetBaseGATTService("Health Thermometer", device.get(),
kHealthThermometerUUID));
// Measurement Interval
auto measurement_interval(GetBaseGATTCharacteristic(
"Measurement Interval", health_thermometer.get(),
kMeasurementIntervalUUID,
BluetoothRemoteGattCharacteristic::PROPERTY_NOTIFY));
NiceMockBluetoothGattCharacteristic* measurement_ptr =
measurement_interval.get();
ON_CALL(*measurement_interval, StartNotifySession_(_, _))
.WillByDefault(RunCallbackWithResult<0 /* success_callback */>(
[adapter_ptr, device_ptr, measurement_ptr, disconnect]() {
std::unique_ptr<NiceMockBluetoothGattNotifySession> notify_session =
std::make_unique<NiceMockBluetoothGattNotifySession>(
measurement_ptr->GetWeakPtr());
ON_CALL(*notify_session, Stop_(_))
.WillByDefault(Invoke([adapter_ptr, device_ptr, disconnect](
base::OnceClosure& callback) {
device_ptr->PushPendingCallback(std::move(callback));
if (disconnect) {
device_ptr->SetConnected(false);
base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE,
base::BindOnce(&NotifyDeviceChanged,
base::RetainedRef(adapter_ptr),
device_ptr));
}
}));
return notify_session;
}));
health_thermometer->AddMockCharacteristic(std::move(measurement_interval));
device->AddMockService(std::move(health_thermometer));
adapter->AddMockDevice(std::move(device));
return adapter;
}
// static
scoped_refptr<NiceMockBluetoothAdapter>
WebTestBluetoothAdapterProvider::GetBlocklistTestAdapter() {
scoped_refptr<NiceMockBluetoothAdapter> adapter(GetEmptyAdapter());
BluetoothDevice::UUIDList uuids;
uuids.push_back(BluetoothUUID(kBlocklistTestServiceUUID));
uuids.push_back(BluetoothUUID(kDeviceInformationServiceUUID));
uuids.push_back(BluetoothUUID(kGenericAccessServiceUUID));
uuids.push_back(BluetoothUUID(kHeartRateServiceUUID));
uuids.push_back(BluetoothUUID(kHumanInterfaceDeviceServiceUUID));
auto device(
GetConnectableDevice(adapter.get(), "Blocklist Test Device", uuids));
device->AddMockService(GetBlocklistTestService(device.get()));
device->AddMockService(GetDeviceInformationService(device.get()));
device->AddMockService(GetGenericAccessService(device.get()));
device->AddMockService(GetHeartRateService(adapter.get(), device.get()));
device->AddMockService(GetBaseGATTService("Human Interface Device",
device.get(),
kHumanInterfaceDeviceServiceUUID));
adapter->AddMockDevice(std::move(device));
return adapter;
}
// static
scoped_refptr<NiceMockBluetoothAdapter>
WebTestBluetoothAdapterProvider::GetFailingConnectionsAdapter() {
scoped_refptr<NiceMockBluetoothAdapter> adapter(GetEmptyAdapter());
for (int error = 0; error < BluetoothDevice::NUM_CONNECT_ERROR_CODES;
error++) {
adapter->AddMockDevice(GetUnconnectableDevice(
adapter.get(), static_cast<BluetoothDevice::ConnectErrorCode>(error)));
}
return adapter;
}
// static
scoped_refptr<NiceMockBluetoothAdapter>
WebTestBluetoothAdapterProvider::GetFailingGATTOperationsAdapter() {
scoped_refptr<NiceMockBluetoothAdapter> adapter(GetEmptyAdapter());
const std::string errorsServiceUUID = errorUUID(0xA0);
BluetoothDevice::UUIDList uuids;
uuids.push_back(BluetoothUUID(errorsServiceUUID));
auto device(GetConnectableDevice(adapter.get(), "Errors Device", uuids));
device->AddMockService(GetDisconnectingService(adapter.get(), device.get()));
auto service(
GetBaseGATTService("Errors Service", device.get(), errorsServiceUUID));
for (int error =
static_cast<int>(BluetoothGattService::GattErrorCode::kUnknown);
error <=
static_cast<int>(BluetoothGattService::GattErrorCode::kMaxValue);
error++) {
service->AddMockCharacteristic(GetErrorCharacteristic(
service.get(),
static_cast<BluetoothGattService::GattErrorCode>(error)));
}
device->AddMockService(std::move(service));
adapter->AddMockDevice(std::move(device));
return adapter;
}
// Devices
// static
std::unique_ptr<NiceMockBluetoothDevice>
WebTestBluetoothAdapterProvider::GetBaseDevice(
MockBluetoothAdapter* adapter,
const char* device_name,
device::BluetoothDevice::UUIDList uuids,
const std::string& address) {
auto device = std::make_unique<NiceMockBluetoothDevice>(
adapter, 0x1F00 /* Bluetooth class */, device_name, address,
false /* paired */, false /* connected */);
for (const auto& uuid : uuids) {
device->AddUUID(uuid);
}
// Using Invoke allows the device returned from this method to be futher
// modified and have more services added to it. The call to ::GetGattServices
// will invoke ::GetMockServices, returning all services added up to that
// time.
ON_CALL(*device, GetGattServices())
.WillByDefault(
Invoke(device.get(), &MockBluetoothDevice::GetMockServices));
// The call to BluetoothDevice::GetGattService will invoke ::GetMockService
// which returns a service matching the identifier provided if the service
// was added to the mock.
ON_CALL(*device, GetGattService(_))
.WillByDefault(
Invoke(device.get(), &MockBluetoothDevice::GetMockService));
ON_CALL(*device, CreateGattConnection(_, _))
.WillByDefault(RunOnceCallback<0>(
/*connection=*/nullptr, BluetoothDevice::ERROR_UNSUPPORTED_DEVICE));
auto* device_ptr = device.get();
ON_CALL(*device, Pair(_, _))
.WillByDefault(
WithArg<1>([device_ptr](BluetoothDevice::ConnectCallback callback) {
device_ptr->SetPaired(/*paired=*/true);
base::SequencedTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, base::BindOnce(std::move(callback),
/*error_code=*/std::nullopt));
}));
return device;
}
// static
std::unique_ptr<NiceMockBluetoothDevice>
WebTestBluetoothAdapterProvider::GetBatteryDevice(
MockBluetoothAdapter* adapter) {
BluetoothDevice::UUIDList uuids;
uuids.push_back(BluetoothUUID(kBatteryServiceUUID));
return GetBaseDevice(adapter, "Battery Device", uuids, makeMACAddress(0x1));
}
// static
std::unique_ptr<NiceMockBluetoothDevice>
WebTestBluetoothAdapterProvider::GetGlucoseDevice(
MockBluetoothAdapter* adapter) {
BluetoothDevice::UUIDList uuids;
uuids.push_back(BluetoothUUID(kGenericAccessServiceUUID));
uuids.push_back(BluetoothUUID(kGlucoseServiceUUID));
uuids.push_back(BluetoothUUID(kTxPowerServiceUUID));
auto device =
GetBaseDevice(adapter, "Glucose Device", uuids, makeMACAddress(0x2));
device->SetManufacturerData({{0x0001, {1, 2}}, {0x0002, {3, 4}}});
return device;
}
// static
std::unique_ptr<NiceMockBluetoothDevice>
WebTestBluetoothAdapterProvider::GetConnectableDevice(
device::MockBluetoothAdapter* adapter,
const char* device_name,
BluetoothDevice::UUIDList uuids,
const std::string& address) {
auto device(GetBaseDevice(adapter, device_name, uuids, address));
MockBluetoothDevice* device_ptr = device.get();
ON_CALL(*device, CreateGattConnection(_, _))
.WillByDefault([adapter, device_ptr](
BluetoothDevice::GattConnectionCallback callback,
std::optional<BluetoothUUID> service_uuid) {
device_ptr->SetConnected(true);
std::move(callback).Run(
std::make_unique<NiceMockBluetoothGattConnection>(
adapter, device_ptr->GetAddress()),
/*error_code=*/std::nullopt);
});
ON_CALL(*device, IsGattServicesDiscoveryComplete())
.WillByDefault(Return(true));
return device;
}
// static
std::unique_ptr<NiceMockBluetoothDevice>
WebTestBluetoothAdapterProvider::GetUnconnectableDevice(
MockBluetoothAdapter* adapter,
BluetoothDevice::ConnectErrorCode error_code,
const char* device_name) {
BluetoothDevice::UUIDList uuids;
uuids.push_back(BluetoothUUID(errorUUID(error_code)));
auto device(
GetBaseDevice(adapter, device_name, uuids, makeMACAddress(error_code)));
ON_CALL(*device, CreateGattConnection(_, _))
.WillByDefault(RunOnceCallback<0>(/*connection=*/nullptr, error_code));
return device;
}
// static
std::unique_ptr<NiceMockBluetoothDevice>
WebTestBluetoothAdapterProvider::GetHeartRateDevice(
MockBluetoothAdapter* adapter,
const char* device_name) {
BluetoothDevice::UUIDList uuids;
uuids.push_back(BluetoothUUID(kGenericAccessServiceUUID));
uuids.push_back(BluetoothUUID(kHeartRateServiceUUID));
return GetConnectableDevice(adapter, device_name, uuids);
}
// Services
// static
std::unique_ptr<NiceMockBluetoothGattService>
WebTestBluetoothAdapterProvider::GetBaseGATTService(
const std::string& identifier,
MockBluetoothDevice* device,
const std::string& uuid) {
auto service = std::make_unique<NiceMockBluetoothGattService>(
device, identifier, BluetoothUUID(uuid), /*is_primary=*/true);
return service;
}
// static
std::unique_ptr<NiceMockBluetoothGattService>
WebTestBluetoothAdapterProvider::GetBlocklistTestService(
device::MockBluetoothDevice* device) {
auto blocklist_test_service(
GetBaseGATTService("Blocklist Test", device, kBlocklistTestServiceUUID));
std::unique_ptr<NiceMockBluetoothGattCharacteristic>
blocklist_exclude_reads_characteristic(GetBaseGATTCharacteristic(
"Excluded Reads Characteristic", blocklist_test_service.get(),
kBlocklistExcludeReadsCharacteristicUUID,
BluetoothRemoteGattCharacteristic::PROPERTY_READ |
BluetoothRemoteGattCharacteristic::PROPERTY_WRITE));
// Crash if ReadRemoteCharacteristic called. Not using GoogleMock's Expect
// because this is used in web tests that may not report a mock expectation
// error correctly as a web test failure.
ON_CALL(*blocklist_exclude_reads_characteristic, ReadRemoteCharacteristic_(_))
.WillByDefault(
Invoke([](BluetoothRemoteGattCharacteristic::ValueCallback&) {
NOTREACHED_IN_MIGRATION();
}));
// Write response.
ON_CALL(*blocklist_exclude_reads_characteristic,
WriteRemoteCharacteristic_(_, _, _, _))
.WillByDefault(RunCallback<2 /* success callback */>());
// Write response.
ON_CALL(*blocklist_exclude_reads_characteristic,
DeprecatedWriteRemoteCharacteristic_(_, _, _))
.WillByDefault(RunCallback<1 /* success callback */>());
blocklist_test_service->AddMockCharacteristic(
std::move(blocklist_exclude_reads_characteristic));
return blocklist_test_service;
}
// static
std::unique_ptr<NiceMockBluetoothGattService>
WebTestBluetoothAdapterProvider::GetDeviceInformationService(
device::MockBluetoothDevice* device) {
auto device_information(GetBaseGATTService("Device Information", device,
kDeviceInformationServiceUUID));
auto serial_number_string(GetBaseGATTCharacteristic(
"Serial Number String", device_information.get(), kSerialNumberStringUUID,
BluetoothRemoteGattCharacteristic::PROPERTY_READ));
// Crash if ReadRemoteCharacteristic called. Not using GoogleMock's Expect
// because this is used in web tests that may not report a mock expectation
// error correctly as a web test failure.
ON_CALL(*serial_number_string, ReadRemoteCharacteristic_(_))
.WillByDefault(
Invoke([](BluetoothRemoteGattCharacteristic::ValueCallback&) {
NOTREACHED_IN_MIGRATION();
}));
device_information->AddMockCharacteristic(std::move(serial_number_string));
return device_information;
}
// static
std::unique_ptr<NiceMockBluetoothGattService>
WebTestBluetoothAdapterProvider::GetGenericAccessService(
device::MockBluetoothDevice* device) {
auto generic_access(
GetBaseGATTService("Generic Access", device, kGenericAccessServiceUUID));
{ // Device Name:
auto device_name(GetBaseGATTCharacteristic(
"Device Name", generic_access.get(), kDeviceNameUUID,
BluetoothRemoteGattCharacteristic::PROPERTY_READ |
BluetoothRemoteGattCharacteristic::PROPERTY_WRITE));
// Read response.
std::vector<uint8_t> device_name_value;
if (std::optional<std::string> name = device->GetName()) {
device_name_value.assign(name.value().begin(), name.value().end());
}
ON_CALL(*device_name, ReadRemoteCharacteristic_(_))
.WillByDefault(RunCallbackWithResult<0>(/*error_code=*/std::nullopt,
device_name_value));
// Write response.
ON_CALL(*device_name, WriteRemoteCharacteristic_(_, _, _, _))
.WillByDefault(RunCallback<2 /* success callback */>());
// Write response.
ON_CALL(*device_name, DeprecatedWriteRemoteCharacteristic_(_, _, _))
.WillByDefault(RunCallback<1 /* success callback */>());
generic_access->AddMockCharacteristic(std::move(device_name));
}
{ // Peripheral Privacy Flag:
std::unique_ptr<NiceMockBluetoothGattCharacteristic>
peripheral_privacy_flag(GetBaseGATTCharacteristic(
"Peripheral Privacy Flag", generic_access.get(),
kPeripheralPrivacyFlagUUID,
BluetoothRemoteGattCharacteristic::PROPERTY_READ |
BluetoothRemoteGattCharacteristic::PROPERTY_WRITE));
// Read response.
std::vector<uint8_t> value(1);
value[0] = false;
ON_CALL(*peripheral_privacy_flag, ReadRemoteCharacteristic_(_))
.WillByDefault(
RunCallbackWithResult<0>(/*error_code=*/std::nullopt, value));
// Crash if WriteRemoteCharacteristic called. Not using GoogleMock's Expect
// because this is used in web tests that may not report a mock
// expectation error correctly as a web test failure.
ON_CALL(*peripheral_privacy_flag, WriteRemoteCharacteristic_(_, _, _, _))
.WillByDefault(Invoke(
[](const std::vector<uint8_t>&,
BluetoothRemoteGattCharacteristic::WriteType, base::OnceClosure&,
BluetoothRemoteGattCharacteristic::ErrorCallback&) {
NOTREACHED_IN_MIGRATION();
}));
// Crash if WriteRemoteCharacteristic called. Not using GoogleMock's Expect
// because this is used in web tests that may not report a mock
// expectation error correctly as a web test failure.
ON_CALL(*peripheral_privacy_flag,
DeprecatedWriteRemoteCharacteristic_(_, _, _))
.WillByDefault(
Invoke([](const std::vector<uint8_t>&, base::OnceClosure&,
BluetoothRemoteGattCharacteristic::ErrorCallback&) {
NOTREACHED_IN_MIGRATION();
}));
generic_access->AddMockCharacteristic(std::move(peripheral_privacy_flag));
}
return generic_access;
}
// static
std::unique_ptr<NiceMockBluetoothGattService>
WebTestBluetoothAdapterProvider::GetHeartRateService(
MockBluetoothAdapter* adapter,
MockBluetoothDevice* device) {
auto heart_rate(
GetBaseGATTService("Heart Rate", device, kHeartRateServiceUUID));
// Heart Rate Measurement
auto heart_rate_measurement(GetBaseGATTCharacteristic(
"Heart Rate Measurement", heart_rate.get(), kHeartRateMeasurementUUID,
BluetoothRemoteGattCharacteristic::PROPERTY_NOTIFY));
NiceMockBluetoothGattCharacteristic* measurement_ptr =
heart_rate_measurement.get();
ON_CALL(*heart_rate_measurement, StartNotifySession_(_, _))
.WillByDefault(RunCallbackWithResult<0 /* success_callback */>(
[adapter, measurement_ptr]() {
auto notify_session(
GetBaseGATTNotifySession(measurement_ptr->GetWeakPtr()));
std::vector<uint8_t> rate(1 /* size */);
rate[0] = 60;
notify_session->StartTestNotifications(adapter, measurement_ptr,
rate);
return notify_session;
}));
// Body Sensor Location Characteristic (Chest)
std::unique_ptr<NiceMockBluetoothGattCharacteristic>
body_sensor_location_chest(GetBaseGATTCharacteristic(
"Body Sensor Location Chest", heart_rate.get(), kBodySensorLocation,
BluetoothRemoteGattCharacteristic::PROPERTY_READ));
ON_CALL(*body_sensor_location_chest, ReadRemoteCharacteristic_(_))
.WillByDefault(RunCallbackWithResult<0>(
/*error_code=*/std::nullopt, std::vector<uint8_t>({1} /* Chest */)));
// Body Sensor Location Characteristic (Wrist)
std::unique_ptr<NiceMockBluetoothGattCharacteristic>
body_sensor_location_wrist(GetBaseGATTCharacteristic(
"Body Sensor Location Wrist", heart_rate.get(), kBodySensorLocation,
BluetoothRemoteGattCharacteristic::PROPERTY_READ));
ON_CALL(*body_sensor_location_wrist, ReadRemoteCharacteristic_(_))
.WillByDefault(RunCallbackWithResult<0>(
/*error_code=*/std::nullopt, std::vector<uint8_t>({2} /* Wrist */)));
heart_rate->AddMockCharacteristic(std::move(heart_rate_measurement));
heart_rate->AddMockCharacteristic(std::move(body_sensor_location_chest));
heart_rate->AddMockCharacteristic(std::move(body_sensor_location_wrist));
return heart_rate;
}
// static
std::unique_ptr<NiceMockBluetoothGattService>
WebTestBluetoothAdapterProvider::GetDisconnectingService(
MockBluetoothAdapter* adapter,
MockBluetoothDevice* device) {
// Set up a service and a characteristic to disconnect the device when it's
// written to.
std::unique_ptr<NiceMockBluetoothGattService> disconnection_service =
GetBaseGATTService("Disconnection", device,
kRequestDisconnectionServiceUUID);
std::unique_ptr<NiceMockBluetoothGattCharacteristic>
disconnection_characteristic(GetBaseGATTCharacteristic(
"Disconnection Characteristic", disconnection_service.get(),
kRequestDisconnectionCharacteristicUUID,
BluetoothRemoteGattCharacteristic::PROPERTY_WRITE_WITHOUT_RESPONSE));
ON_CALL(*disconnection_characteristic, WriteRemoteCharacteristic_(_, _, _, _))
.WillByDefault(
Invoke([adapter, device](
const std::vector<uint8_t>& value,
BluetoothRemoteGattCharacteristic::WriteType write_type,
base::OnceClosure& success,
BluetoothRemoteGattCharacteristic::ErrorCallback& error) {
device->SetConnected(false);
for (auto& observer : adapter->GetObservers())
observer.DeviceChanged(adapter, device);
std::move(success).Run();
}));
ON_CALL(*disconnection_characteristic,
DeprecatedWriteRemoteCharacteristic_(_, _, _))
.WillByDefault(Invoke(
[adapter, device](
const std::vector<uint8_t>& value, base::OnceClosure& success,
BluetoothRemoteGattCharacteristic::ErrorCallback& error) {
device->SetConnected(false);
for (auto& observer : adapter->GetObservers())
observer.DeviceChanged(adapter, device);
std::move(success).Run();
}));
disconnection_service->AddMockCharacteristic(
std::move(disconnection_characteristic));
return disconnection_service;
}
// Characteristics
// static
std::unique_ptr<NiceMockBluetoothGattCharacteristic>
WebTestBluetoothAdapterProvider::GetBaseGATTCharacteristic(
const std::string& identifier,
MockBluetoothGattService* service,
const std::string& uuid,
BluetoothRemoteGattCharacteristic::Properties properties) {
auto characteristic = std::make_unique<NiceMockBluetoothGattCharacteristic>(
service, identifier, BluetoothUUID(uuid), properties,
BluetoothGattCharacteristic::Permission::PERMISSION_NONE);
ON_CALL(*characteristic, ReadRemoteCharacteristic_(_))
.WillByDefault(RunCallbackWithResult<0>(
BluetoothGattService::GattErrorCode::kNotSupported,
/*value=*/std::vector<uint8_t>()));
ON_CALL(*characteristic, WriteRemoteCharacteristic_(_, _, _, _))
.WillByDefault(
RunCallback<3>(BluetoothGattService::GattErrorCode::kNotSupported));
ON_CALL(*characteristic, DeprecatedWriteRemoteCharacteristic_(_, _, _))
.WillByDefault(
RunCallback<2>(BluetoothGattService::GattErrorCode::kNotSupported));
ON_CALL(*characteristic, StartNotifySession_(_, _))
.WillByDefault(
RunCallback<1>(BluetoothGattService::GattErrorCode::kNotSupported));
return characteristic;
}
// static
std::unique_ptr<NiceMockBluetoothGattCharacteristic>
WebTestBluetoothAdapterProvider::GetErrorCharacteristic(
MockBluetoothGattService* service,
BluetoothGattService::GattErrorCode error_code) {
// Error UUIDs start at 0xA1.
uint32_t error_alias = static_cast<int>(error_code) + 0xA1;
auto characteristic(GetBaseGATTCharacteristic(
// Use the UUID to generate unique identifiers.
"Error Characteristic " + errorUUID(error_alias), service,
errorUUID(error_alias),
BluetoothRemoteGattCharacteristic::PROPERTY_READ |
BluetoothRemoteGattCharacteristic::PROPERTY_WRITE |
BluetoothRemoteGattCharacteristic::PROPERTY_INDICATE));
// Read response.
ON_CALL(*characteristic, ReadRemoteCharacteristic_(_))
.WillByDefault(
RunCallbackWithResult<0>(error_code,
/*value=*/std::vector<uint8_t>()));
// Write response.
ON_CALL(*characteristic, WriteRemoteCharacteristic_(_, _, _, _))
.WillByDefault(RunCallback<3 /* error_callback */>(error_code));
// Write response.
ON_CALL(*characteristic, DeprecatedWriteRemoteCharacteristic_(_, _, _))
.WillByDefault(RunCallback<2 /* error_callback */>(error_code));
// StartNotifySession response
ON_CALL(*characteristic, StartNotifySession_(_, _))
.WillByDefault(RunCallback<1 /* error_callback */>(error_code));
// Add error descriptor to |characteristic|
auto error_descriptor = std::make_unique<NiceMockBluetoothGattDescriptor>(
characteristic.get(), kCharacteristicUserDescription,
BluetoothUUID(kUserDescriptionUUID),
device::BluetoothRemoteGattCharacteristic::PROPERTY_READ);
ON_CALL(*error_descriptor, ReadRemoteDescriptor_(_))
.WillByDefault(
RunCallbackWithResult<0>(error_code,
/*value=*/std::vector<uint8_t>()));
ON_CALL(*error_descriptor, WriteRemoteDescriptor_(_, _, _))
.WillByDefault(RunCallback<2 /* error_callback */>(error_code));
characteristic->AddMockDescriptor(std::move(error_descriptor));
return characteristic;
}
// Notify sessions
// static
std::unique_ptr<NiceMockBluetoothGattNotifySession>
WebTestBluetoothAdapterProvider::GetBaseGATTNotifySession(
base::WeakPtr<device::BluetoothRemoteGattCharacteristic> characteristic) {
auto session =
std::make_unique<NiceMockBluetoothGattNotifySession>(characteristic);
ON_CALL(*session, Stop_(_))
.WillByDefault(testing::DoAll(
InvokeWithoutArgs(
session.get(),
&MockBluetoothGattNotifySession::StopTestNotifications),
RunCallback<0>()));
return session;
}
// Helper functions
// static
std::string WebTestBluetoothAdapterProvider::errorUUID(uint32_t alias) {
return base::StringPrintf("%08x-97e5-4cd7-b9f1-f5a427670c59", alias);
}
// static
std::string WebTestBluetoothAdapterProvider::makeMACAddress(uint64_t addr) {
return device::CanonicalizeBluetoothAddress(
base::StringPrintf("%012" PRIx64, addr));
}
} // namespace content