1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239
|
// Copyright 2014 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "device/bluetooth/bluetooth_adapter.h"
#include <stddef.h>
#include <stdint.h>
#include <memory>
#include <utility>
#include <vector>
#include "base/barrier_closure.h"
#include "base/functional/bind.h"
#include "base/functional/callback_helpers.h"
#include "base/logging.h"
#include "base/memory/ref_counted.h"
#include "base/run_loop.h"
#include "base/task/single_thread_task_runner.h"
#include "base/test/bind.h"
#include "base/test/task_environment.h"
#include "build/build_config.h"
#include "device/bluetooth/bluetooth_common.h"
#include "device/bluetooth/bluetooth_device.h"
#include "device/bluetooth/bluetooth_discovery_session.h"
#include "device/bluetooth/bluetooth_gatt_service.h"
#include "device/bluetooth/bluetooth_local_gatt_characteristic.h"
#include "device/bluetooth/bluetooth_local_gatt_descriptor.h"
#include "device/bluetooth/bluetooth_local_gatt_service.h"
#include "device/bluetooth/test/bluetooth_test.h"
#include "device/bluetooth/test/test_bluetooth_adapter_observer.h"
#include "device/bluetooth/test/test_bluetooth_advertisement_observer.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#if BUILDFLAG(IS_ANDROID)
#include "base/android/build_info.h"
#include "device/bluetooth/test/bluetooth_test_android.h"
#elif BUILDFLAG(IS_APPLE)
#include "device/bluetooth/test/bluetooth_test_mac.h"
#elif BUILDFLAG(IS_WIN)
#include "base/win/windows_version.h"
#include "device/bluetooth/test/bluetooth_test_win.h"
#elif defined(USE_CAST_BLUETOOTH_ADAPTER)
#include "device/bluetooth/test/bluetooth_test_cast.h"
#elif BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_LINUX)
#include "device/bluetooth/test/bluetooth_test_bluez.h"
#elif BUILDFLAG(IS_FUCHSIA)
#include "device/bluetooth/test/bluetooth_test_fuchsia.h"
#endif
#if BUILDFLAG(IS_CHROMEOS)
#include "device/bluetooth/bluetooth_low_energy_scan_filter.h"
#include "device/bluetooth/bluetooth_low_energy_scan_session.h"
#endif // BUILDFLAG(IS_CHROMEOS)
using device::BluetoothDevice;
namespace device {
void AddDeviceFilterWithUUID(BluetoothDiscoveryFilter* filter,
BluetoothUUID uuid) {
BluetoothDiscoveryFilter::DeviceInfoFilter device_filter;
device_filter.uuids.insert(uuid);
filter->AddDeviceFilter(device_filter);
}
namespace {
class TestBluetoothAdapter final : public BluetoothAdapter {
public:
TestBluetoothAdapter() = default;
void Initialize(base::OnceClosure callback) override {
std::move(callback).Run();
}
std::string GetAddress() const override { return ""; }
std::string GetName() const override { return ""; }
void SetName(const std::string& name,
base::OnceClosure callback,
ErrorCallback error_callback) override {}
bool IsInitialized() const override { return false; }
bool IsPresent() const override { return false; }
bool IsPowered() const override { return false; }
void SetPowered(bool powered,
base::OnceClosure callback,
ErrorCallback error_callback) override {}
bool IsDiscoverable() const override { return false; }
void SetDiscoverable(bool discoverable,
base::OnceClosure callback,
ErrorCallback error_callback) override {}
#if BUILDFLAG(IS_LINUX) || BUILDFLAG(IS_CHROMEOS)
base::TimeDelta GetDiscoverableTimeout() const override {
return base::Microseconds(0);
}
#endif
bool IsDiscovering() const override { return false; }
UUIDList GetUUIDs() const override { return UUIDList(); }
void CreateRfcommService(const BluetoothUUID& uuid,
const ServiceOptions& options,
CreateServiceCallback callback,
CreateServiceErrorCallback error_callback) override {
}
void CreateL2capService(const BluetoothUUID& uuid,
const ServiceOptions& options,
CreateServiceCallback callback,
CreateServiceErrorCallback error_callback) override {}
void RegisterAdvertisement(
std::unique_ptr<BluetoothAdvertisement::Data> advertisement_data,
CreateAdvertisementCallback callback,
AdvertisementErrorCallback error_callback) override {}
#if BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_LINUX)
void SetAdvertisingInterval(
const base::TimeDelta& min,
const base::TimeDelta& max,
base::OnceClosure callback,
AdvertisementErrorCallback error_callback) override {}
void ResetAdvertising(base::OnceClosure callback,
AdvertisementErrorCallback error_callback) override {}
void ConnectDevice(
const std::string& address,
const std::optional<BluetoothDevice::AddressType>& address_type,
ConnectDeviceCallback callback,
ConnectDeviceErrorCallback error_callback) override {}
#endif
BluetoothLocalGattService* GetGattService(
const std::string& identifier) const override {
return nullptr;
}
#if BUILDFLAG(IS_CHROMEOS)
void SetServiceAllowList(const UUIDList& uuids,
base::OnceClosure callback,
ErrorCallback error_callback) override {}
LowEnergyScanSessionHardwareOffloadingStatus
GetLowEnergyScanSessionHardwareOffloadingStatus() override {
return LowEnergyScanSessionHardwareOffloadingStatus::kNotSupported;
}
std::unique_ptr<BluetoothLowEnergyScanSession> StartLowEnergyScanSession(
std::unique_ptr<BluetoothLowEnergyScanFilter> filter,
base::WeakPtr<BluetoothLowEnergyScanSession::Delegate> delegate)
override {
return nullptr;
}
std::vector<BluetoothRole> GetSupportedRoles() override {
return std::vector<BluetoothRole>{};
}
void SetStandardChromeOSAdapterName() override {}
#endif // BUILDFLAG(IS_CHROMEOS)
void OnStartDiscoverySessionQuitLoop(
base::OnceClosure run_loop_quit,
std::unique_ptr<device::BluetoothDiscoverySession> discovery_session) {
++callback_count_;
std::move(run_loop_quit).Run();
discovery_sessions_holder_.push(std::move(discovery_session));
}
void OnRemoveDiscoverySession(base::OnceClosure run_loop_quit) {
++callback_count_;
std::move(run_loop_quit).Run();
}
void OnRemoveDiscoverySessionError(base::OnceClosure run_loop_quit) {
++callback_count_;
std::move(run_loop_quit).Run();
}
void set_discovery_session_outcome(
UMABluetoothDiscoverySessionOutcome outcome) {
discovery_session_outcome_ = outcome;
}
void StopDiscoverySession(base::OnceClosure run_loop_quit) {
auto split_run_loop = base::SplitOnceCallback(std::move(run_loop_quit));
discovery_sessions_holder_.front()->Stop(
base::BindOnce(&TestBluetoothAdapter::OnRemoveDiscoverySession, this,
std::move(split_run_loop.first)),
base::BindOnce(&TestBluetoothAdapter::OnRemoveDiscoverySessionError,
this, std::move(split_run_loop.second)));
discovery_sessions_holder_.pop();
}
void StopAllDiscoverySessions(base::OnceClosure run_loop_quit) {
base::RepeatingClosure closure = base::BarrierClosure(
discovery_sessions_holder_.size(), std::move(run_loop_quit));
while (!discovery_sessions_holder_.empty()) {
discovery_sessions_holder_.front()->Stop(
base::BindLambdaForTesting([closure, this]() {
++callback_count_;
closure.Run();
}),
base::BindOnce(&TestBluetoothAdapter::OnRemoveDiscoverySessionError,
this, closure));
discovery_sessions_holder_.pop();
}
}
void CleanupSessions() {
// clear discovery_sessions_holder_
base::queue<std::unique_ptr<BluetoothDiscoverySession>> empty_queue;
std::swap(discovery_sessions_holder_, empty_queue);
}
void QueueStartRequests(base::OnceClosure run_loop_quit, int num_requests) {
base::RepeatingClosure closure =
base::BarrierClosure(num_requests, std::move(run_loop_quit));
for (int i = 0; i < num_requests; ++i) {
StartDiscoverySession(
/*client_name=*/std::string(),
base::BindLambdaForTesting(
[closure, this](std::unique_ptr<device::BluetoothDiscoverySession>
discovery_session) {
++callback_count_;
discovery_sessions_holder_.push(std::move(discovery_session));
closure.Run();
}),
closure);
}
}
void StartSessionWithFilter(
std::unique_ptr<BluetoothDiscoveryFilter> discovery_filter,
base::OnceClosure run_loop_quit) {
StartDiscoverySessionWithFilter(
std::move(discovery_filter),
/*client_name=*/std::string(),
base::BindOnce(&TestBluetoothAdapter::OnStartDiscoverySessionQuitLoop,
this, std::move(run_loop_quit)),
base::DoNothing());
}
void RunStartSessionWithFilter(
std::unique_ptr<BluetoothDiscoveryFilter> filter) {
base::RunLoop loop;
StartSessionWithFilter(std::move(filter), loop.QuitClosure());
loop.Run();
}
// |discovery_sessions_holder_| is used to hold unique pointers of Discovery
// Sessions so that the destructors don't get called and so we can test
// removing them
base::queue<std::unique_ptr<BluetoothDiscoverySession>>
discovery_sessions_holder_;
std::unique_ptr<BluetoothDiscoveryFilter> current_filter =
std::make_unique<BluetoothDiscoveryFilter>();
int callback_count_ = 0;
bool is_discovering_ = false;
protected:
~TestBluetoothAdapter() override = default;
bool SetPoweredImpl(bool powered) override { return false; }
base::WeakPtr<BluetoothAdapter> GetWeakPtr() override {
return weak_ptr_factory_.GetWeakPtr();
}
void StartScanWithFilter(
std::unique_ptr<BluetoothDiscoveryFilter> discovery_filter,
DiscoverySessionResultCallback callback) override {
base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE,
base::BindOnce(&TestBluetoothAdapter::SetFilter,
weak_ptr_factory_.GetWeakPtr(),
std::move(discovery_filter), std::move(callback)));
}
void UpdateFilter(std::unique_ptr<BluetoothDiscoveryFilter> discovery_filter,
DiscoverySessionResultCallback callback) override {
base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE,
base::BindOnce(&TestBluetoothAdapter::SetFilter,
weak_ptr_factory_.GetWeakPtr(),
std::move(discovery_filter), std::move(callback)));
}
void SetFilter(std::unique_ptr<BluetoothDiscoveryFilter> discovery_filter,
DiscoverySessionResultCallback callback) {
bool is_error = discovery_session_outcome_ !=
UMABluetoothDiscoverySessionOutcome::SUCCESS;
if (!is_error) {
is_discovering_ = true;
current_filter->CopyFrom(*discovery_filter.get());
}
std::move(callback).Run(is_error, discovery_session_outcome_);
}
void StopScan(DiscoverySessionResultCallback callback) override {
base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE,
base::BindOnce(&TestBluetoothAdapter::FakeOSStopScan,
weak_ptr_factory_.GetWeakPtr(), std::move(callback)));
}
void FakeOSStopScan(DiscoverySessionResultCallback callback) {
is_discovering_ = false;
std::move(callback).Run(/*is_error=*/false,
UMABluetoothDiscoverySessionOutcome::SUCCESS);
}
void RemovePairingDelegateInternal(
BluetoothDevice::PairingDelegate* pairing_delegate) override {}
private:
void PostDelayedTask(base::OnceClosure callback) {
base::SingleThreadTaskRunner::GetCurrentDefault()->PostTask(
FROM_HERE, std::move(callback));
}
UMABluetoothDiscoverySessionOutcome discovery_session_outcome_ =
UMABluetoothDiscoverySessionOutcome::SUCCESS;
// This must be the last field in the class so that weak pointers are
// invalidated first.
base::WeakPtrFactory<TestBluetoothAdapter> weak_ptr_factory_{this};
};
class TestPairingDelegate : public BluetoothDevice::PairingDelegate {
public:
void RequestPinCode(BluetoothDevice* device) override {}
void RequestPasskey(BluetoothDevice* device) override {}
void DisplayPinCode(BluetoothDevice* device,
const std::string& pincode) override {}
void DisplayPasskey(BluetoothDevice* device, uint32_t passkey) override {}
void KeysEntered(BluetoothDevice* device, uint32_t entered) override {}
void ConfirmPasskey(BluetoothDevice* device, uint32_t passkey) override {}
void AuthorizePairing(BluetoothDevice* device) override {}
};
bool ServiceSetsEqual(
std::vector<BluetoothLocalGattService*> services,
std::initializer_list<BluetoothLocalGattService*> services_to_check) {
using ServiceSet = std::set<BluetoothLocalGattService*,
bool (*)(BluetoothLocalGattService*,
BluetoothLocalGattService*)>;
auto comparator = [](BluetoothLocalGattService* a,
BluetoothLocalGattService* b) -> bool {
return a->GetIdentifier() < b->GetIdentifier();
};
return ServiceSet(services.begin(), services.end(), comparator) ==
ServiceSet(services_to_check, comparator);
}
} // namespace
class BluetoothAdapterTest : public testing::Test {
public:
void SetUp() override { adapter_ = new TestBluetoothAdapter(); }
protected:
scoped_refptr<TestBluetoothAdapter> adapter_;
base::test::TaskEnvironment task_environment_;
};
TEST_F(BluetoothAdapterTest, NoDefaultPairingDelegate) {
// Verify that when there is no registered pairing delegate, NULL is returned.
EXPECT_TRUE(adapter_->DefaultPairingDelegate() == nullptr);
}
TEST_F(BluetoothAdapterTest, OneDefaultPairingDelegate) {
// Verify that when there is one registered pairing delegate, it is returned.
TestPairingDelegate delegate;
adapter_->AddPairingDelegate(&delegate,
BluetoothAdapter::PAIRING_DELEGATE_PRIORITY_LOW);
EXPECT_EQ(&delegate, adapter_->DefaultPairingDelegate());
}
TEST_F(BluetoothAdapterTest, SamePriorityDelegates) {
// Verify that when there are two registered pairing delegates of the same
// priority, the first one registered is returned.
TestPairingDelegate delegate1, delegate2;
adapter_->AddPairingDelegate(&delegate1,
BluetoothAdapter::PAIRING_DELEGATE_PRIORITY_LOW);
adapter_->AddPairingDelegate(&delegate2,
BluetoothAdapter::PAIRING_DELEGATE_PRIORITY_LOW);
EXPECT_EQ(&delegate1, adapter_->DefaultPairingDelegate());
// After unregistering the first, the second can be returned.
adapter_->RemovePairingDelegate(&delegate1);
EXPECT_EQ(&delegate2, adapter_->DefaultPairingDelegate());
}
TEST_F(BluetoothAdapterTest, HighestPriorityDelegate) {
// Verify that when there are two registered pairing delegates, the one with
// the highest priority is returned.
TestPairingDelegate delegate1, delegate2;
adapter_->AddPairingDelegate(&delegate1,
BluetoothAdapter::PAIRING_DELEGATE_PRIORITY_LOW);
adapter_->AddPairingDelegate(
&delegate2, BluetoothAdapter::PAIRING_DELEGATE_PRIORITY_HIGH);
EXPECT_EQ(&delegate2, adapter_->DefaultPairingDelegate());
}
TEST_F(BluetoothAdapterTest, UnregisterDelegate) {
// Verify that after unregistering a delegate, NULL is returned.
TestPairingDelegate delegate;
adapter_->AddPairingDelegate(&delegate,
BluetoothAdapter::PAIRING_DELEGATE_PRIORITY_LOW);
adapter_->RemovePairingDelegate(&delegate);
EXPECT_TRUE(adapter_->DefaultPairingDelegate() == nullptr);
}
TEST_F(BluetoothAdapterTest, GetMergedDiscoveryFilterEmpty) {
std::unique_ptr<BluetoothDiscoveryFilter> discovery_filter;
discovery_filter = adapter_->GetMergedDiscoveryFilter();
EXPECT_TRUE(discovery_filter->IsDefault());
}
TEST_F(BluetoothAdapterTest, GetMergedDiscoveryFilterRegular) {
std::unique_ptr<BluetoothDiscoveryFilter> discovery_filter;
// having one reglar session should result in no filter
std::unique_ptr<BluetoothDiscoveryFilter> resulting_filter =
adapter_->GetMergedDiscoveryFilter();
EXPECT_TRUE(resulting_filter->IsDefault());
adapter_->CleanupSessions();
}
TEST_F(BluetoothAdapterTest, TestQueueingLogic) {
auto discovery_filter =
std::make_unique<BluetoothDiscoveryFilter>(BLUETOOTH_TRANSPORT_LE);
AddDeviceFilterWithUUID(discovery_filter.get(), BluetoothUUID("1001"));
auto discovery_filter2 =
std::make_unique<BluetoothDiscoveryFilter>(BLUETOOTH_TRANSPORT_LE);
AddDeviceFilterWithUUID(discovery_filter2.get(), BluetoothUUID("1002"));
// Start a discovery session
base::RunLoop run_loop1;
adapter_->StartSessionWithFilter(std::move(discovery_filter),
run_loop1.QuitClosure());
// Since the first request is still running we have not hit a single callback
EXPECT_EQ(0, adapter_->callback_count_);
// While our first Discovery Session is starting queue up another one with a
// different filter.
base::RunLoop run_loop2;
adapter_->StartSessionWithFilter(std::move(discovery_filter2),
run_loop2.QuitClosure());
// Finish the first request. This should automatically start the queued
// request when completed.
run_loop1.Run();
EXPECT_EQ(1, adapter_->callback_count_);
EXPECT_TRUE(adapter_->is_discovering_);
adapter_->callback_count_ = 0;
// While our second discovery session is starting queue up 4 start requests
// with default filters.
base::RunLoop run_loop3;
adapter_->QueueStartRequests(run_loop3.QuitClosure(), 4);
// Finish the second request. This should start the 4 queued requests.
run_loop2.Run();
EXPECT_EQ(1, adapter_->callback_count_);
adapter_->callback_count_ = 0;
// Queue up stop requests for the 2 started sessions.
base::RunLoop run_loop4;
adapter_->StopAllDiscoverySessions(base::DoNothing());
// Confirm that no callbacks were hit and the filter has not changed.
EXPECT_EQ(0, adapter_->callback_count_);
EXPECT_FALSE(adapter_->current_filter->IsDefault());
// Run the 4 queued default requests. This should call all 4 callbacks from
// the start requests and automatically call the start the queue stop
// requests. These will short circuit and return immediately because the
// filter remains the default filter.
run_loop3.Run();
EXPECT_EQ(6, adapter_->callback_count_);
EXPECT_TRUE(adapter_->current_filter->IsDefault());
adapter_->CleanupSessions();
}
TEST_F(BluetoothAdapterTest, ShortCircuitUpdateTest) {
auto discovery_filter_default1 = std::make_unique<BluetoothDiscoveryFilter>();
auto discovery_filter =
std::make_unique<BluetoothDiscoveryFilter>(BLUETOOTH_TRANSPORT_LE);
discovery_filter->SetRSSI(-30);
base::RunLoop run_loop;
adapter_->StartSessionWithFilter(std::move(discovery_filter_default1),
run_loop.QuitClosure());
run_loop.Run();
EXPECT_TRUE(adapter_->current_filter->IsDefault());
EXPECT_EQ(1, adapter_->callback_count_);
// This time since there is no actual change being made the adapter should
// short circuit the callback immediately with success
auto discovery_filter_default2 = std::make_unique<BluetoothDiscoveryFilter>();
adapter_->StartSessionWithFilter(std::move(discovery_filter_default2),
base::DoNothing());
EXPECT_TRUE(adapter_->current_filter->IsDefault());
EXPECT_EQ(2, adapter_->callback_count_);
// This filter is different but is already covered under the default filter so
// it should still short circuit
adapter_->StartSessionWithFilter(std::move(discovery_filter),
base::DoNothing());
EXPECT_TRUE(adapter_->current_filter->IsDefault());
EXPECT_EQ(3, adapter_->callback_count_);
// End the first discovery session which still short circuits because there is
// still a default session active
adapter_->StopDiscoverySession(base::DoNothing());
EXPECT_TRUE(adapter_->current_filter->IsDefault());
EXPECT_EQ(4, adapter_->callback_count_);
// When removing the second default filter we should now actually update
// because discovery_filter is the only filter left
base::RunLoop run_loop2;
adapter_->StopDiscoverySession(run_loop2.QuitClosure());
EXPECT_TRUE(adapter_->current_filter->IsDefault());
EXPECT_EQ(4, adapter_->callback_count_);
run_loop2.Run();
EXPECT_FALSE(adapter_->current_filter->IsDefault());
EXPECT_EQ(5, adapter_->callback_count_);
// Adding another default but not finishing the update
base::RunLoop run_loop3;
auto discovery_filter_default3 = std::make_unique<BluetoothDiscoveryFilter>();
adapter_->StartSessionWithFilter(std::move(discovery_filter_default3),
run_loop3.QuitClosure());
EXPECT_FALSE(adapter_->current_filter->IsDefault());
EXPECT_EQ(5, adapter_->callback_count_);
// Queue up another request that should short circuit and return success when
// default filter 3 updates
auto discovery_filter_default4 = std::make_unique<BluetoothDiscoveryFilter>();
adapter_->StartSessionWithFilter(std::move(discovery_filter_default4),
base::DoNothing());
EXPECT_FALSE(adapter_->current_filter->IsDefault());
EXPECT_EQ(5, adapter_->callback_count_);
// Running the loop default filter 3 will update the the OS filter then then
// start processing the queued request. The queued request does not change
// the filter so it should automatically short circuit and return success.
run_loop3.Run();
EXPECT_TRUE(adapter_->current_filter->IsDefault());
EXPECT_EQ(7, adapter_->callback_count_);
adapter_->CleanupSessions();
}
TEST_F(BluetoothAdapterTest, GetMergedDiscoveryFilterRssi) {
int16_t resulting_rssi;
uint16_t resulting_pathloss;
std::unique_ptr<BluetoothDiscoveryFilter> resulting_filter;
auto discovery_filter =
std::make_unique<BluetoothDiscoveryFilter>(BLUETOOTH_TRANSPORT_LE);
discovery_filter->SetRSSI(-30);
auto discovery_filter2 =
std::make_unique<BluetoothDiscoveryFilter>(BLUETOOTH_TRANSPORT_LE);
discovery_filter2->SetRSSI(-65);
// Make sure adapter has one session without filtering.
adapter_->RunStartSessionWithFilter(std::move(discovery_filter));
resulting_filter = adapter_->GetMergedDiscoveryFilter();
resulting_filter->GetRSSI(&resulting_rssi);
EXPECT_EQ(-30, resulting_rssi);
adapter_->RunStartSessionWithFilter(std::move(discovery_filter2));
// result of merging two rssi values should be lower one
resulting_filter = adapter_->GetMergedDiscoveryFilter();
resulting_filter->GetRSSI(&resulting_rssi);
EXPECT_EQ(-65, resulting_rssi);
BluetoothDiscoveryFilter* df3 =
new BluetoothDiscoveryFilter(BLUETOOTH_TRANSPORT_LE);
df3->SetPathloss(60);
std::unique_ptr<BluetoothDiscoveryFilter> discovery_filter3(df3);
// when rssi and pathloss are merged, both should be cleared, because there is
// no way to tell which filter will be more generic
{
base::RunLoop run_loop;
adapter_->StartSessionWithFilter(std::move(discovery_filter3),
run_loop.QuitClosure());
run_loop.Run();
}
resulting_filter = adapter_->GetMergedDiscoveryFilter();
EXPECT_FALSE(resulting_filter->GetRSSI(&resulting_rssi));
EXPECT_FALSE(resulting_filter->GetPathloss(&resulting_pathloss));
adapter_->CleanupSessions();
}
TEST_F(BluetoothAdapterTest, GetMergedDiscoveryFilterTransport) {
std::unique_ptr<BluetoothDiscoveryFilter> resulting_filter;
auto discovery_filter =
std::make_unique<BluetoothDiscoveryFilter>(BLUETOOTH_TRANSPORT_CLASSIC);
auto discovery_filter2 =
std::make_unique<BluetoothDiscoveryFilter>(BLUETOOTH_TRANSPORT_LE);
adapter_->RunStartSessionWithFilter(std::move(discovery_filter));
// Just one filter, make sure transport was properly rewritten
resulting_filter = adapter_->GetMergedDiscoveryFilter();
EXPECT_EQ(BLUETOOTH_TRANSPORT_CLASSIC, resulting_filter->GetTransport());
adapter_->RunStartSessionWithFilter(std::move(discovery_filter2));
// Two filters, should have OR of both transport's
resulting_filter = adapter_->GetMergedDiscoveryFilter();
EXPECT_EQ(BLUETOOTH_TRANSPORT_DUAL, resulting_filter->GetTransport());
auto discovery_filter3 =
std::make_unique<BluetoothDiscoveryFilter>(BLUETOOTH_TRANSPORT_LE);
discovery_filter3->CopyFrom(
BluetoothDiscoveryFilter(BLUETOOTH_TRANSPORT_DUAL));
// Merging empty filter in should result in empty filter
adapter_->RunStartSessionWithFilter(std::move(discovery_filter3));
resulting_filter = adapter_->GetMergedDiscoveryFilter();
EXPECT_TRUE(resulting_filter->IsDefault());
adapter_->CleanupSessions();
}
TEST_F(BluetoothAdapterTest, GetMergedDiscoveryFilterAllFields) {
int16_t resulting_rssi;
std::set<device::BluetoothUUID> resulting_uuids;
auto discovery_filter =
std::make_unique<BluetoothDiscoveryFilter>(BLUETOOTH_TRANSPORT_LE);
discovery_filter->SetRSSI(-60);
AddDeviceFilterWithUUID(discovery_filter.get(), BluetoothUUID("1000"));
auto discovery_filter2 =
std::make_unique<BluetoothDiscoveryFilter>(BLUETOOTH_TRANSPORT_LE);
discovery_filter2->SetRSSI(-85);
AddDeviceFilterWithUUID(discovery_filter2.get(), BluetoothUUID("1020"));
AddDeviceFilterWithUUID(discovery_filter2.get(), BluetoothUUID("1001"));
auto discovery_filter3 =
std::make_unique<BluetoothDiscoveryFilter>(BLUETOOTH_TRANSPORT_LE);
discovery_filter3->SetRSSI(-65);
discovery_filter3->SetTransport(BLUETOOTH_TRANSPORT_CLASSIC);
AddDeviceFilterWithUUID(discovery_filter3.get(), BluetoothUUID("1020"));
AddDeviceFilterWithUUID(discovery_filter3.get(), BluetoothUUID("1003"));
adapter_->RunStartSessionWithFilter(std::move(discovery_filter));
adapter_->RunStartSessionWithFilter(std::move(discovery_filter2));
adapter_->RunStartSessionWithFilter(std::move(discovery_filter3));
std::unique_ptr<BluetoothDiscoveryFilter> resulting_filter =
adapter_->GetMergedDiscoveryFilter();
resulting_filter->GetRSSI(&resulting_rssi);
resulting_filter->GetUUIDs(resulting_uuids);
EXPECT_TRUE(resulting_filter->GetTransport());
EXPECT_EQ(BLUETOOTH_TRANSPORT_DUAL, resulting_filter->GetTransport());
EXPECT_EQ(-85, resulting_rssi);
EXPECT_THAT(resulting_uuids,
testing::UnorderedElementsAre(device::BluetoothUUID("1000"),
device::BluetoothUUID("1001"),
device::BluetoothUUID("1003"),
device::BluetoothUUID("1020")));
adapter_->CleanupSessions();
}
TEST_F(BluetoothAdapterTest, StartDiscoverySession_Destroy) {
base::RunLoop loop;
adapter_->StartDiscoverySession(
/*client_name=*/std::string(),
base::BindLambdaForTesting(
[&](std::unique_ptr<BluetoothDiscoverySession> session) {
adapter_.reset();
loop.Quit();
}),
base::DoNothing());
loop.Run();
}
TEST_F(BluetoothAdapterTest, StartDiscoverySessionError_Destroy) {
base::RunLoop loop;
adapter_->set_discovery_session_outcome(
UMABluetoothDiscoverySessionOutcome::FAILED);
adapter_->StartDiscoverySession(/*client_name=*/std::string(),
base::DoNothing(),
base::BindLambdaForTesting([&]() {
adapter_.reset();
loop.Quit();
}));
loop.Run();
}
// TODO(scheib): Enable BluetoothTest fixture tests on all platforms.
// TODO(https://crbug.com/331653043): Re-enable when passing on macOS 14 bots.
#if BUILDFLAG(IS_ANDROID)
#define MAYBE_ConstructDefaultAdapter ConstructDefaultAdapter
#else
#define MAYBE_ConstructDefaultAdapter DISABLED_ConstructDefaultAdapter
#endif
#if BUILDFLAG(IS_WIN)
TEST_P(BluetoothTestWinrt, ConstructDefaultAdapter) {
#else
TEST_F(BluetoothTest, MAYBE_ConstructDefaultAdapter) {
#endif
InitWithDefaultAdapter();
if (!adapter_->IsPresent() || !adapter_->IsPowered()) {
GTEST_SKIP()
<< "Bluetooth adapter not present or not powered; skipping unit test.";
}
EXPECT_FALSE(adapter_->GetAddress().empty());
EXPECT_FALSE(adapter_->GetName().empty());
EXPECT_FALSE(adapter_->IsDiscoverable());
EXPECT_FALSE(adapter_->IsDiscovering());
} // namespace device
// TODO(scheib): Enable BluetoothTest fixture tests on all platforms.
#if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_APPLE)
#define MAYBE_ConstructWithoutDefaultAdapter ConstructWithoutDefaultAdapter
#else
#define MAYBE_ConstructWithoutDefaultAdapter \
DISABLED_ConstructWithoutDefaultAdapter
#endif
#if BUILDFLAG(IS_WIN)
TEST_P(BluetoothTestWinrt, ConstructWithoutDefaultAdapter) {
#else
TEST_F(BluetoothTest, MAYBE_ConstructWithoutDefaultAdapter) {
#endif // BUILDFLAG(IS_WIN)
InitWithoutDefaultAdapter();
EXPECT_EQ(adapter_->GetAddress(), "");
EXPECT_EQ(adapter_->GetName(), "");
#if !BUILDFLAG(IS_IOS)
EXPECT_FALSE(adapter_->IsPresent());
EXPECT_FALSE(adapter_->IsPowered());
#endif
EXPECT_FALSE(adapter_->IsDiscoverable());
EXPECT_FALSE(adapter_->IsDiscovering());
#if BUILDFLAG(IS_ANDROID)
EXPECT_EQ(adapter_->GetOsPermissionStatus(),
BluetoothAdapter::PermissionStatus::kDenied);
#endif // BUILDFLAG(IS_ANDROID)
}
// TODO(scheib): Enable BluetoothTest fixture tests on all platforms.
#if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_APPLE)
#define MAYBE_ConstructFakeAdapter ConstructFakeAdapter
#else
#define MAYBE_ConstructFakeAdapter DISABLED_ConstructFakeAdapter
#endif
#if BUILDFLAG(IS_WIN)
TEST_P(BluetoothTestWinrt, ConstructFakeAdapter) {
#else
TEST_F(BluetoothTest, MAYBE_ConstructFakeAdapter) {
#endif // BUILDFLAG(IS_WIN)
if (!PlatformSupportsLowEnergy()) {
GTEST_SKIP() << "Low Energy Bluetooth unavailable, skipping unit test.";
}
InitWithFakeAdapter();
#if !BUILDFLAG(IS_IOS)
EXPECT_EQ(adapter_->GetAddress(), kTestAdapterAddress);
EXPECT_EQ(adapter_->GetName(), kTestAdapterName);
#endif
EXPECT_TRUE(adapter_->CanPower());
EXPECT_TRUE(adapter_->IsPresent());
EXPECT_TRUE(adapter_->IsPowered());
#if !BUILDFLAG(IS_APPLE)
EXPECT_EQ(BluetoothAdapter::PermissionStatus::kAllowed,
adapter_->GetOsPermissionStatus());
#endif // !BUILDFLAG(IS_APPLE)
EXPECT_TRUE(adapter_->IsPeripheralRoleSupported());
EXPECT_FALSE(adapter_->IsDiscoverable());
EXPECT_FALSE(adapter_->IsDiscovering());
}
#if BUILDFLAG(IS_WIN)
TEST_P(BluetoothTestWinrt, ConstructFakeAdapterWithoutRadio) {
if (!PlatformSupportsLowEnergy()) {
GTEST_SKIP() << "Low Energy Bluetooth unavailable, skipping unit test.";
}
InitFakeAdapterWithoutRadio();
EXPECT_EQ(adapter_->GetAddress(), kTestAdapterAddress);
EXPECT_EQ(adapter_->GetName(), kTestAdapterName);
EXPECT_TRUE(adapter_->IsPresent());
EXPECT_FALSE(adapter_->CanPower());
EXPECT_FALSE(adapter_->IsPowered());
EXPECT_FALSE(adapter_->IsDiscoverable());
EXPECT_FALSE(adapter_->IsDiscovering());
}
TEST_P(BluetoothTestWinrt, ConstructFakeAdapterWithoutPowerControl) {
if (!PlatformSupportsLowEnergy()) {
GTEST_SKIP() << "Low Energy Bluetooth unavailable, skipping unit test.";
}
InitFakeAdapterWithRadioAccessDenied();
EXPECT_EQ(adapter_->GetAddress(), kTestAdapterAddress);
EXPECT_EQ(adapter_->GetName(), kTestAdapterName);
EXPECT_TRUE(adapter_->IsPresent());
EXPECT_FALSE(adapter_->CanPower());
EXPECT_TRUE(adapter_->IsPowered());
EXPECT_FALSE(adapter_->IsDiscoverable());
EXPECT_FALSE(adapter_->IsDiscovering());
}
#endif // BUILDFLAG(IS_WIN)
// TODO(scheib): Enable BluetoothTest fixture tests on all platforms.
#if BUILDFLAG(IS_ANDROID)
#define MAYBE_DiscoverySession DiscoverySession
#else
#define MAYBE_DiscoverySession DISABLED_DiscoverySession
#endif
// Starts and Stops a discovery session.
TEST_F(BluetoothTest, MAYBE_DiscoverySession) {
InitWithFakeAdapter();
EXPECT_FALSE(adapter_->IsDiscovering());
StartLowEnergyDiscoverySession();
EXPECT_EQ(1, callback_count_);
EXPECT_EQ(0, error_callback_count_);
EXPECT_TRUE(adapter_->IsDiscovering());
ASSERT_EQ((size_t)1, discovery_sessions_.size());
EXPECT_TRUE(discovery_sessions_[0]->IsActive());
ResetEventCounts();
discovery_sessions_[0]->Stop(GetCallback(Call::EXPECTED),
GetErrorCallback(Call::NOT_EXPECTED));
EXPECT_FALSE(adapter_->IsDiscovering());
EXPECT_FALSE(discovery_sessions_[0]->IsActive());
}
// Android only: this test is specific for Android and should not be
// enabled for other platforms.
#if BUILDFLAG(IS_ANDROID)
TEST_F(BluetoothTest, AdapterIllegalStateBeforeStartScan) {
if (!PlatformSupportsLowEnergy()) {
GTEST_SKIP() << "Low Energy Bluetooth unavailable, skipping unit test.";
}
InitWithFakeAdapter();
ForceIllegalStateException();
StartLowEnergyDiscoverySessionExpectedToFail();
EXPECT_EQ(0, callback_count_);
EXPECT_EQ(1, error_callback_count_);
EXPECT_FALSE(adapter_->IsDiscovering());
}
#endif // BUILDFLAG(IS_ANDROID)
// Android only: this test is specific for Android and should not be
// enabled for other platforms.
#if BUILDFLAG(IS_ANDROID)
TEST_F(BluetoothTest, AdapterIllegalStateBeforeStopScan) {
if (!PlatformSupportsLowEnergy()) {
GTEST_SKIP() << "Low Energy Bluetooth unavailable, skipping unit test.";
}
InitWithFakeAdapter();
StartLowEnergyDiscoverySession();
EXPECT_EQ(1, callback_count_);
EXPECT_EQ(0, error_callback_count_);
EXPECT_TRUE(adapter_->IsDiscovering());
ForceIllegalStateException();
discovery_sessions_[0]->Stop(GetCallback(Call::EXPECTED),
GetErrorCallback(Call::NOT_EXPECTED));
EXPECT_FALSE(adapter_->IsDiscovering());
}
#endif // BUILDFLAG(IS_ANDROID)
#if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_APPLE)
#define MAYBE_NoPermissions NoPermissions
#else
#define MAYBE_NoPermissions DISABLED_NoPermissions
#endif
// Checks that discovery fails (instead of hanging) when permissions are denied.
TEST_F(BluetoothTest, MAYBE_NoPermissions) {
if (!PlatformSupportsLowEnergy()) {
GTEST_SKIP() << "Low Energy Bluetooth unavailable, skipping unit test.";
}
InitWithFakeAdapter();
TestBluetoothAdapterObserver observer(adapter_);
if (!DenyPermission()) {
// Platform always gives permission to scan.
return;
}
EXPECT_EQ(BluetoothAdapter::PermissionStatus::kDenied,
adapter_->GetOsPermissionStatus());
StartLowEnergyDiscoverySessionExpectedToFail();
EXPECT_EQ(0, callback_count_);
EXPECT_EQ(1, error_callback_count_);
}
// Android-only: Only Android requires location services to be turned on to scan
// for Bluetooth devices.
#if BUILDFLAG(IS_ANDROID)
// Checks that discovery fails (instead of hanging) when location services are
// turned off.
TEST_F(BluetoothTest, NoLocationServices) {
if (!PlatformSupportsLowEnergy()) {
GTEST_SKIP() << "Low Energy Bluetooth unavailable, skipping unit test.";
}
if (base::android::BuildInfo::GetInstance()->sdk_int() >=
base::android::SDK_VERSION_S) {
GTEST_SKIP() << "Android S+ doesn't require location services perform "
"Bluetooth scanning, skipping unit test.";
}
InitWithFakeAdapter();
TestBluetoothAdapterObserver observer(adapter_);
SimulateLocationServicesOff();
EXPECT_EQ(BluetoothAdapter::PermissionStatus::kDenied,
adapter_->GetOsPermissionStatus());
StartLowEnergyDiscoverySessionExpectedToFail();
EXPECT_EQ(0, callback_count_);
EXPECT_EQ(1, error_callback_count_);
}
#endif // BUILDFLAG(IS_ANDROID)
#if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_APPLE)
#define MAYBE_DiscoverLowEnergyDevice DiscoverLowEnergyDevice
#else
#define MAYBE_DiscoverLowEnergyDevice DISABLED_DiscoverLowEnergyDevice
#endif
// Discovers a device.
#if BUILDFLAG(IS_WIN)
TEST_P(BluetoothTestWinrt, DiscoverLowEnergyDevice) {
#else
TEST_F(BluetoothTest, MAYBE_DiscoverLowEnergyDevice) {
#endif
if (!PlatformSupportsLowEnergy()) {
GTEST_SKIP() << "Low Energy Bluetooth unavailable, skipping unit test.";
}
InitWithFakeAdapter();
TestBluetoothAdapterObserver observer(adapter_);
// Start discovery and find a device.
StartLowEnergyDiscoverySession();
SimulateLowEnergyDevice(1);
EXPECT_EQ(1, observer.device_added_count());
BluetoothDevice* device = adapter_->GetDevice(observer.last_device_address());
EXPECT_TRUE(device);
}
#if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_APPLE)
#define MAYBE_DiscoverLowEnergyDeviceTwice DiscoverLowEnergyDeviceTwice
#else
#define MAYBE_DiscoverLowEnergyDeviceTwice DISABLED_DiscoverLowEnergyDeviceTwice
#endif
// Discovers the same device multiple times.
#if BUILDFLAG(IS_WIN)
TEST_P(BluetoothTestWinrt, DiscoverLowEnergyDeviceTwice) {
#else
TEST_F(BluetoothTest, MAYBE_DiscoverLowEnergyDeviceTwice) {
#endif
if (!PlatformSupportsLowEnergy()) {
GTEST_SKIP() << "Low Energy Bluetooth unavailable, skipping unit test.";
}
InitWithFakeAdapter();
TestBluetoothAdapterObserver observer(adapter_);
// Start discovery and find a device.
StartLowEnergyDiscoverySession();
SimulateLowEnergyDevice(1);
EXPECT_EQ(1, observer.device_added_count());
BluetoothDevice* device = adapter_->GetDevice(observer.last_device_address());
EXPECT_TRUE(device);
// Find the same device again. This should not create a new device object.
observer.Reset();
SimulateLowEnergyDevice(1);
base::RunLoop().RunUntilIdle();
EXPECT_EQ(0, observer.device_added_count());
EXPECT_EQ(1u, adapter_->GetDevices().size());
}
#if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_APPLE)
#define MAYBE_DiscoverLowEnergyDeviceWithUpdatedUUIDs \
DiscoverLowEnergyDeviceWithUpdatedUUIDs
#else
#define MAYBE_DiscoverLowEnergyDeviceWithUpdatedUUIDs \
DISABLED_DiscoverLowEnergyDeviceWithUpdatedUUIDs
#endif
// Discovers a device, and then again with new Service UUIDs.
// Makes sure we don't create another device when we've found the
// device in the past.
#if BUILDFLAG(IS_WIN)
TEST_P(BluetoothTestWinrt, DiscoverLowEnergyDeviceWithUpdatedUUIDs) {
#else
TEST_F(BluetoothTest, MAYBE_DiscoverLowEnergyDeviceWithUpdatedUUIDs) {
#endif
if (!PlatformSupportsLowEnergy()) {
GTEST_SKIP() << "Low Energy Bluetooth unavailable, skipping unit test.";
}
InitWithFakeAdapter();
TestBluetoothAdapterObserver observer(adapter_);
// Start discovery and find a device.
StartLowEnergyDiscoverySession();
BluetoothDevice* device = SimulateLowEnergyDevice(1);
// Discover same device again with updated UUIDs:
observer.Reset();
SimulateLowEnergyDevice(2);
EXPECT_EQ(0, observer.device_added_count());
EXPECT_EQ(1, observer.device_changed_count());
EXPECT_EQ(1u, adapter_->GetDevices().size());
EXPECT_EQ(device, observer.last_device());
// Discover same device again with empty UUIDs:
observer.Reset();
SimulateLowEnergyDevice(3);
EXPECT_EQ(0, observer.device_added_count());
EXPECT_EQ(1, observer.device_changed_count());
EXPECT_EQ(1u, adapter_->GetDevices().size());
}
#if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_APPLE)
#define MAYBE_DiscoverMultipleLowEnergyDevices DiscoverMultipleLowEnergyDevices
#else
#define MAYBE_DiscoverMultipleLowEnergyDevices \
DISABLED_DiscoverMultipleLowEnergyDevices
#endif
// Discovers multiple devices when addresses vary.
#if BUILDFLAG(IS_WIN)
TEST_P(BluetoothTestWinrt, DiscoverMultipleLowEnergyDevices) {
#else
TEST_F(BluetoothTest, MAYBE_DiscoverMultipleLowEnergyDevices) {
#endif
if (!PlatformSupportsLowEnergy()) {
GTEST_SKIP() << "Low Energy Bluetooth unavailable, skipping unit test.";
}
InitWithFakeAdapter();
TestBluetoothAdapterObserver observer(adapter_);
// Start discovery and find a device.
StartLowEnergyDiscoverySession();
SimulateLowEnergyDevice(1);
SimulateLowEnergyDevice(4);
EXPECT_EQ(2, observer.device_added_count());
EXPECT_EQ(2u, adapter_->GetDevices().size());
}
#if BUILDFLAG(IS_WIN)
// Tests that the adapter responds to external changes to the power state.
TEST_P(BluetoothTestWinrt, SimulateAdapterPoweredOffAndOn) {
if (!PlatformSupportsLowEnergy()) {
GTEST_SKIP() << "Low Energy Bluetooth unavailable, skipping unit test.";
}
InitWithFakeAdapter();
TestBluetoothAdapterObserver observer(adapter_);
ASSERT_TRUE(adapter_->IsPresent());
ASSERT_TRUE(adapter_->IsPowered());
EXPECT_EQ(0, observer.powered_changed_count());
SimulateAdapterPoweredOff();
base::RunLoop().RunUntilIdle();
EXPECT_FALSE(adapter_->IsPowered());
EXPECT_EQ(1, observer.powered_changed_count());
EXPECT_FALSE(observer.last_powered());
SimulateAdapterPoweredOn();
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(adapter_->IsPowered());
EXPECT_EQ(2, observer.powered_changed_count());
EXPECT_TRUE(observer.last_powered());
}
// Tests that power change notifications are deduplicated.
// Multiple StateChanged events with the same state only cause a
// single AdapterPoweredChanged() call.
TEST_P(BluetoothTestWinrt, SimulateDuplicateStateChanged) {
if (!PlatformSupportsLowEnergy()) {
GTEST_SKIP() << "Low Energy Bluetooth unavailable, skipping unit test.";
}
InitWithFakeAdapter();
TestBluetoothAdapterObserver observer(adapter_);
ASSERT_TRUE(adapter_->IsPresent());
ASSERT_TRUE(adapter_->IsPowered());
EXPECT_EQ(0, observer.powered_changed_count());
SimulateSpuriousRadioStateChangedEvent();
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(adapter_->IsPowered());
EXPECT_EQ(0, observer.powered_changed_count());
SimulateAdapterPoweredOff();
SimulateSpuriousRadioStateChangedEvent();
base::RunLoop().RunUntilIdle();
EXPECT_FALSE(adapter_->IsPowered());
EXPECT_EQ(1, observer.powered_changed_count());
EXPECT_FALSE(observer.last_powered());
SimulateAdapterPoweredOn();
SimulateSpuriousRadioStateChangedEvent();
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(adapter_->IsPowered());
EXPECT_EQ(2, observer.powered_changed_count());
EXPECT_TRUE(observer.last_powered());
}
// Tests that the adapter responds to external changes to the power state, even
// if it failed to obtain the underlying radio.
TEST_P(BluetoothTestWinrt, SimulateAdapterPoweredOnAndOffWithoutRadio) {
if (!PlatformSupportsLowEnergy()) {
GTEST_SKIP() << "Low Energy Bluetooth unavailable, skipping unit test.";
}
InitFakeAdapterWithoutRadio();
TestBluetoothAdapterObserver observer(adapter_);
ASSERT_TRUE(adapter_->IsPresent());
ASSERT_FALSE(adapter_->IsPowered());
EXPECT_EQ(0, observer.powered_changed_count());
SimulateAdapterPoweredOn();
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(adapter_->IsPowered());
EXPECT_EQ(1, observer.powered_changed_count());
EXPECT_TRUE(observer.last_powered());
SimulateAdapterPoweredOff();
base::RunLoop().RunUntilIdle();
EXPECT_FALSE(adapter_->IsPowered());
EXPECT_EQ(2, observer.powered_changed_count());
EXPECT_FALSE(observer.last_powered());
}
// Makes sure the error callback gets run when changing the adapter power state
// fails.
// TODO(crbug.com/41410591): Implement SimulateAdapterPowerSuccess() and
// enable on all platforms.
TEST_P(BluetoothTestWinrt, SimulateAdapterPowerFailure) {
if (!PlatformSupportsLowEnergy()) {
GTEST_SKIP() << "Low Energy Bluetooth unavailable, skipping unit test.";
}
InitWithFakeAdapter();
ASSERT_TRUE(adapter_->IsPresent());
ASSERT_TRUE(adapter_->IsPowered());
adapter_->SetPowered(false, GetCallback(Call::NOT_EXPECTED),
GetErrorCallback(Call::EXPECTED));
SimulateAdapterPowerFailure();
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(adapter_->IsPowered());
}
#endif // BUILDFLAG(IS_WIN)
// TODO(crbug.com/41366193): Enable this test on old Windows versions as
// well.
#if BUILDFLAG(IS_WIN)
TEST_P(BluetoothTestWinrt, TogglePowerFakeAdapter) {
#else
#if BUILDFLAG(IS_IOS)
#define MAYBE_TogglePowerFakeAdapter DISABLED_TogglePowerFakeAdapter
#else
#define MAYBE_TogglePowerFakeAdapter TogglePowerFakeAdapter
#endif
TEST_F(BluetoothTest, MAYBE_TogglePowerFakeAdapter) {
#endif
if (!PlatformSupportsLowEnergy()) {
GTEST_SKIP() << "Low Energy Bluetooth unavailable, skipping unit test.";
}
InitWithFakeAdapter();
TestBluetoothAdapterObserver observer(adapter_);
ASSERT_TRUE(adapter_->IsPresent());
ASSERT_TRUE(adapter_->IsPowered());
EXPECT_EQ(0, observer.powered_changed_count());
// Check if power can be turned off.
adapter_->SetPowered(false, GetCallback(Call::EXPECTED),
GetErrorCallback(Call::NOT_EXPECTED));
task_environment_.RunUntilIdle();
EXPECT_FALSE(adapter_->IsPowered());
EXPECT_EQ(1, observer.powered_changed_count());
// Check if power can be turned on again.
adapter_->SetPowered(true, GetCallback(Call::EXPECTED),
GetErrorCallback(Call::NOT_EXPECTED));
task_environment_.RunUntilIdle();
EXPECT_TRUE(adapter_->IsPowered());
EXPECT_EQ(2, observer.powered_changed_count());
}
#if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_MAC)
#define MAYBE_TogglePowerFakeAdapter_Twice TogglePowerFakeAdapter_Twice
#else
#define MAYBE_TogglePowerFakeAdapter_Twice DISABLED_TogglePowerFakeAdapter_Twice
#endif
// These tests are not relevant for BlueZ and old Windows versions. On these
// platforms the corresponding system APIs are blocking or use callbacks, so
// that it is not necessary to store pending callbacks and wait for the
// appropriate events.
#if BUILDFLAG(IS_WIN)
TEST_P(BluetoothTestWinrt, TogglePowerFakeAdapter_Twice) {
#else
TEST_F(BluetoothTest, MAYBE_TogglePowerFakeAdapter_Twice) {
#endif
if (!PlatformSupportsLowEnergy()) {
GTEST_SKIP() << "Low Energy Bluetooth unavailable, skipping unit test.";
}
InitWithFakeAdapter();
TestBluetoothAdapterObserver observer(adapter_);
ASSERT_TRUE(adapter_->IsPresent());
ASSERT_TRUE(adapter_->IsPowered());
EXPECT_EQ(0, observer.powered_changed_count());
// Post two pending turn off requests, the second should fail due to the
// presence of another callback.
adapter_->SetPowered(false, GetCallback(Call::EXPECTED),
GetErrorCallback(Call::NOT_EXPECTED));
adapter_->SetPowered(false, GetCallback(Call::NOT_EXPECTED),
GetErrorCallback(Call::EXPECTED));
task_environment_.RunUntilIdle();
EXPECT_FALSE(adapter_->IsPowered());
EXPECT_EQ(1, observer.powered_changed_count());
// Post two pending turn on requests, the second should fail due to the
// presence of another callback.
adapter_->SetPowered(true, GetCallback(Call::EXPECTED),
GetErrorCallback(Call::NOT_EXPECTED));
adapter_->SetPowered(true, GetCallback(Call::NOT_EXPECTED),
GetErrorCallback(Call::EXPECTED));
task_environment_.RunUntilIdle();
EXPECT_TRUE(adapter_->IsPowered());
EXPECT_EQ(2, observer.powered_changed_count());
}
#if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_MAC)
#define MAYBE_TogglePowerFakeAdapter_WithinCallback_On_Off \
TogglePowerFakeAdapter_WithinCallback_On_Off
#else
#define MAYBE_TogglePowerFakeAdapter_WithinCallback_On_Off \
DISABLED_TogglePowerFakeAdapter_WithinCallback_On_Off
#endif
#if BUILDFLAG(IS_WIN)
TEST_P(BluetoothTestWinrt, TogglePowerFakeAdapter_WithinCallback_On_Off) {
#else
TEST_F(BluetoothTest, MAYBE_TogglePowerFakeAdapter_WithinCallback_On_Off) {
#endif
if (!PlatformSupportsLowEnergy()) {
GTEST_SKIP() << "Low Energy Bluetooth unavailable, skipping unit test.";
}
InitWithFakeAdapter();
TestBluetoothAdapterObserver observer(adapter_);
ASSERT_TRUE(adapter_->IsPresent());
ASSERT_TRUE(adapter_->IsPowered());
EXPECT_EQ(0, observer.powered_changed_count());
// Turn adapter off, while powering it on in the callback.
adapter_->SetPowered(false, base::BindLambdaForTesting([&] {
adapter_->SetPowered(
true, GetCallback(Call::EXPECTED),
GetErrorCallback(Call::NOT_EXPECTED));
}),
GetErrorCallback(Call::NOT_EXPECTED));
task_environment_.RunUntilIdle();
EXPECT_TRUE(adapter_->IsPowered());
EXPECT_EQ(2, observer.powered_changed_count());
}
#if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_MAC)
#define MAYBE_TogglePowerFakeAdapter_WithinCallback_Off_On \
TogglePowerFakeAdapter_WithinCallback_Off_On
#else
#define MAYBE_TogglePowerFakeAdapter_WithinCallback_Off_On \
DISABLED_TogglePowerFakeAdapter_WithinCallback_Off_On
#endif
#if BUILDFLAG(IS_WIN)
TEST_P(BluetoothTestWinrt, TogglePowerFakeAdapter_WithinCallback_Off_On) {
#else
TEST_F(BluetoothTest, MAYBE_TogglePowerFakeAdapter_WithinCallback_Off_On) {
#endif
if (!PlatformSupportsLowEnergy()) {
GTEST_SKIP() << "Low Energy Bluetooth unavailable, skipping unit test.";
}
InitWithFakeAdapter();
TestBluetoothAdapterObserver observer(adapter_);
ASSERT_TRUE(adapter_->IsPresent());
ASSERT_TRUE(adapter_->IsPowered());
EXPECT_EQ(0, observer.powered_changed_count());
// Turn power off.
adapter_->SetPowered(false, GetCallback(Call::EXPECTED),
GetErrorCallback(Call::NOT_EXPECTED));
task_environment_.RunUntilIdle();
EXPECT_FALSE(adapter_->IsPowered());
EXPECT_EQ(1, observer.powered_changed_count());
// Turn adapter on, while powering it off in the callback.
adapter_->SetPowered(true, base::BindLambdaForTesting([&] {
adapter_->SetPowered(
false, GetCallback(Call::EXPECTED),
GetErrorCallback(Call::NOT_EXPECTED));
}),
GetErrorCallback(Call::NOT_EXPECTED));
task_environment_.RunUntilIdle();
EXPECT_FALSE(adapter_->IsPowered());
EXPECT_EQ(3, observer.powered_changed_count());
}
#if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_MAC)
#define MAYBE_TogglePowerFakeAdapter_DestroyWithPending \
TogglePowerFakeAdapter_DestroyWithPending
#else
#define MAYBE_TogglePowerFakeAdapter_DestroyWithPending \
DISABLED_TogglePowerFakeAdapter_DestroyWithPending
#endif
#if BUILDFLAG(IS_WIN)
TEST_P(BluetoothTestWinrt, TogglePowerFakeAdapter_DestroyWithPending) {
#else
TEST_F(BluetoothTest, MAYBE_TogglePowerFakeAdapter_DestroyWithPending) {
#endif
if (!PlatformSupportsLowEnergy()) {
GTEST_SKIP() << "Low Energy Bluetooth unavailable, skipping unit test.";
}
InitWithFakeAdapter();
ASSERT_TRUE(adapter_->IsPresent());
ASSERT_TRUE(adapter_->IsPowered());
// Schedule pending power off request and cause destruction of the adapter by
// dropping the reference count to 0. Note that we are intentionally not using
// a TestBluetoothAdapterObserver, as this would hold another reference to the
// adapter and thus interfere with the intended destruction.
// We expect the error callback to be invoked, and any other subsequent calls
// to SetPowered() should fail as well.
bool error_callback_called = false;
BluetoothAdapter* adapter = adapter_.get();
adapter->SetPowered(
false, GetCallback(Call::NOT_EXPECTED),
base::BindLambdaForTesting(
// Note that we explicitly need to capture a pointer to the
// underlying adapter, even though we pass |this| implicitly. This is
// because by the time this callback is invoked, |adapter| is already
// set to null, but the pointed to adapter instance is still alive. So
// using the pointer is safe, but dereferencing |adapter| crashes.
[&] {
error_callback_called = true;
adapter->SetPowered(false, GetCallback(Call::NOT_EXPECTED),
GetErrorCallback(Call::EXPECTED));
adapter->SetPowered(true, GetCallback(Call::NOT_EXPECTED),
GetErrorCallback(Call::EXPECTED));
}));
adapter_ = nullptr;
// Empty the message loop to make sure posted callbacks get run.
task_environment_.RunUntilIdle();
EXPECT_TRUE(error_callback_called);
}
#if BUILDFLAG(IS_ANDROID)
#define MAYBE_TogglePowerBeforeScan TogglePowerBeforeScan
#else
#define MAYBE_TogglePowerBeforeScan DISABLED_TogglePowerBeforeScan
#endif
TEST_F(BluetoothTest, MAYBE_TogglePowerBeforeScan) {
InitWithFakeAdapter();
TestBluetoothAdapterObserver observer(adapter_);
ASSERT_TRUE(adapter_->IsPresent());
ASSERT_TRUE(adapter_->IsPowered());
EXPECT_EQ(0, observer.powered_changed_count());
// Turn off adapter.
adapter_->SetPowered(false, GetCallback(Call::EXPECTED),
GetErrorCallback(Call::NOT_EXPECTED));
task_environment_.RunUntilIdle();
ASSERT_FALSE(adapter_->IsPowered());
EXPECT_EQ(1, observer.powered_changed_count());
// Try to perform a scan.
StartLowEnergyDiscoverySessionExpectedToFail();
// Turn on adapter.
adapter_->SetPowered(true, GetCallback(Call::EXPECTED),
GetErrorCallback(Call::NOT_EXPECTED));
task_environment_.RunUntilIdle();
ASSERT_TRUE(adapter_->IsPowered());
EXPECT_EQ(2, observer.powered_changed_count());
// Try to perform a scan again.
ResetEventCounts();
StartLowEnergyDiscoverySession();
EXPECT_EQ(1, callback_count_);
EXPECT_EQ(0, error_callback_count_);
EXPECT_TRUE(adapter_->IsDiscovering());
ASSERT_EQ((size_t)1, discovery_sessions_.size());
EXPECT_TRUE(discovery_sessions_[0]->IsActive());
}
#if BUILDFLAG(IS_WIN)
TEST_P(BluetoothTestWinrt, DiscoverySessionFailure) {
if (!PlatformSupportsLowEnergy()) {
GTEST_SKIP() << "Low Energy Bluetooth unavailable, skipping unit test.";
}
InitWithFakeAdapter();
TestBluetoothAdapterObserver observer(adapter_);
EXPECT_FALSE(adapter_->IsDiscovering());
StartLowEnergyDiscoverySession();
EXPECT_EQ(1, callback_count_);
EXPECT_EQ(0, error_callback_count_);
EXPECT_TRUE(adapter_->IsDiscovering());
EXPECT_EQ(1, observer.discovering_changed_count());
EXPECT_TRUE(observer.last_discovering());
ASSERT_EQ((size_t)1, discovery_sessions_.size());
EXPECT_TRUE(discovery_sessions_[0]->IsActive());
SimulateLowEnergyDiscoveryFailure();
EXPECT_FALSE(adapter_->IsDiscovering());
EXPECT_FALSE(discovery_sessions_[0]->IsActive());
EXPECT_EQ(2, observer.discovering_changed_count());
EXPECT_FALSE(observer.last_discovering());
}
#endif // BUILDFLAG(IS_WIN)
#if BUILDFLAG(IS_MAC)
#define MAYBE_TurnOffAdapterWithConnectedDevice \
TurnOffAdapterWithConnectedDevice
#else
#define MAYBE_TurnOffAdapterWithConnectedDevice \
DISABLED_TurnOffAdapterWithConnectedDevice
#endif
// TODO(crbug.com/40522060): Enable on relevant platforms.
TEST_F(BluetoothTest, MAYBE_TurnOffAdapterWithConnectedDevice) {
if (!PlatformSupportsLowEnergy()) {
GTEST_SKIP() << "Low Energy Bluetooth unavailable, skipping unit test.";
}
InitWithFakeAdapter();
TestBluetoothAdapterObserver observer(adapter_);
StartLowEnergyDiscoverySession();
BluetoothDevice* device = SimulateLowEnergyDevice(3);
device->CreateGattConnection(
GetGattConnectionCallback(Call::EXPECTED, Result::SUCCESS));
SimulateGattConnection(device);
base::RunLoop().RunUntilIdle();
ASSERT_TRUE(device->IsGattConnected());
ResetEventCounts();
SimulateAdapterPoweredOff();
EXPECT_EQ(2, observer.device_changed_count());
EXPECT_FALSE(device->IsConnected());
EXPECT_FALSE(device->IsGattConnected());
}
#if BUILDFLAG(IS_WIN)
TEST_P(BluetoothTestWinrt, RegisterAdvertisement) {
if (!PlatformSupportsLowEnergy()) {
GTEST_SKIP() << "Low Energy Bluetooth unavailable, skipping unit test.";
}
auto advertisement_data = std::make_unique<BluetoothAdvertisement::Data>(
BluetoothAdvertisement::ADVERTISEMENT_TYPE_BROADCAST);
advertisement_data->set_manufacturer_data(
BluetoothAdvertisement::ManufacturerData());
InitWithFakeAdapter();
adapter_->RegisterAdvertisement(
std::move(advertisement_data),
GetCreateAdvertisementCallback(Call::EXPECTED),
GetAdvertisementErrorCallback(Call::NOT_EXPECTED));
auto pending_advertisements = adapter_->GetPendingAdvertisementsForTesting();
ASSERT_FALSE(pending_advertisements.empty());
SimulateAdvertisementStarted(pending_advertisements[0]);
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(adapter_->GetPendingAdvertisementsForTesting().empty());
}
TEST_P(BluetoothTestWinrt, FailRegisterAdvertisement) {
if (!PlatformSupportsLowEnergy()) {
GTEST_SKIP() << "Low Energy Bluetooth unavailable, skipping unit test.";
}
auto advertisement_data = std::make_unique<BluetoothAdvertisement::Data>(
BluetoothAdvertisement::ADVERTISEMENT_TYPE_BROADCAST);
advertisement_data->set_manufacturer_data(
BluetoothAdvertisement::ManufacturerData());
InitWithFakeAdapter();
adapter_->RegisterAdvertisement(
std::move(advertisement_data),
GetCreateAdvertisementCallback(Call::NOT_EXPECTED),
GetAdvertisementErrorCallback(Call::EXPECTED));
auto pending_advertisements = adapter_->GetPendingAdvertisementsForTesting();
ASSERT_FALSE(pending_advertisements.empty());
SimulateAdvertisementError(pending_advertisements[0],
BluetoothAdvertisement::ERROR_ADAPTER_POWERED_OFF);
base::RunLoop().RunUntilIdle();
EXPECT_EQ(BluetoothAdvertisement::ERROR_ADAPTER_POWERED_OFF,
last_advertisement_error_code_);
EXPECT_TRUE(adapter_->GetPendingAdvertisementsForTesting().empty());
}
TEST_P(BluetoothTestWinrt, RegisterAndUnregisterAdvertisement) {
if (!PlatformSupportsLowEnergy()) {
GTEST_SKIP() << "Low Energy Bluetooth unavailable, skipping unit test.";
}
auto advertisement_data = std::make_unique<BluetoothAdvertisement::Data>(
BluetoothAdvertisement::ADVERTISEMENT_TYPE_BROADCAST);
advertisement_data->set_manufacturer_data(
BluetoothAdvertisement::ManufacturerData());
InitWithFakeAdapter();
adapter_->RegisterAdvertisement(
std::move(advertisement_data),
GetCreateAdvertisementCallback(Call::EXPECTED),
GetAdvertisementErrorCallback(Call::NOT_EXPECTED));
auto pending_advertisements = adapter_->GetPendingAdvertisementsForTesting();
ASSERT_FALSE(pending_advertisements.empty());
auto* advertisement = pending_advertisements[0];
SimulateAdvertisementStarted(advertisement);
base::RunLoop().RunUntilIdle();
TestBluetoothAdvertisementObserver observer(advertisement);
advertisement->Unregister(GetCallback(Call::EXPECTED),
GetAdvertisementErrorCallback(Call::NOT_EXPECTED));
SimulateAdvertisementStopped(advertisement);
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(observer.released());
EXPECT_EQ(1u, observer.released_count());
EXPECT_TRUE(adapter_->GetPendingAdvertisementsForTesting().empty());
}
TEST_P(BluetoothTestWinrt, FailUnregisterAdvertisement) {
if (!PlatformSupportsLowEnergy()) {
GTEST_SKIP() << "Low Energy Bluetooth unavailable, skipping unit test.";
}
auto advertisement_data = std::make_unique<BluetoothAdvertisement::Data>(
BluetoothAdvertisement::ADVERTISEMENT_TYPE_BROADCAST);
advertisement_data->set_manufacturer_data(
BluetoothAdvertisement::ManufacturerData());
InitWithFakeAdapter();
adapter_->RegisterAdvertisement(
std::move(advertisement_data),
GetCreateAdvertisementCallback(Call::EXPECTED),
GetAdvertisementErrorCallback(Call::NOT_EXPECTED));
auto pending_advertisements = adapter_->GetPendingAdvertisementsForTesting();
ASSERT_FALSE(pending_advertisements.empty());
auto* advertisement = pending_advertisements[0];
SimulateAdvertisementStarted(advertisement);
base::RunLoop().RunUntilIdle();
TestBluetoothAdvertisementObserver observer(advertisement);
advertisement->Unregister(GetCallback(Call::NOT_EXPECTED),
GetAdvertisementErrorCallback(Call::EXPECTED));
SimulateAdvertisementError(advertisement,
BluetoothAdvertisement::ERROR_RESET_ADVERTISING);
base::RunLoop().RunUntilIdle();
// Expect no change to the observer status.
EXPECT_FALSE(observer.released());
EXPECT_EQ(0u, observer.released_count());
EXPECT_EQ(BluetoothAdvertisement::ERROR_RESET_ADVERTISING,
last_advertisement_error_code_);
EXPECT_TRUE(adapter_->GetPendingAdvertisementsForTesting().empty());
}
TEST_P(BluetoothTestWinrt, RegisterAdvertisementWithInvalidData) {
if (!PlatformSupportsLowEnergy()) {
GTEST_SKIP() << "Low Energy Bluetooth unavailable, skipping unit test.";
}
// WinRT only accepts ManufacturerData in the payload, other data should be
// rejected.
auto advertisement_data = std::make_unique<BluetoothAdvertisement::Data>(
BluetoothAdvertisement::ADVERTISEMENT_TYPE_BROADCAST);
advertisement_data->set_service_data(BluetoothAdvertisement::ServiceData());
InitWithFakeAdapter();
adapter_->RegisterAdvertisement(
std::move(advertisement_data),
GetCreateAdvertisementCallback(Call::NOT_EXPECTED),
GetAdvertisementErrorCallback(Call::EXPECTED));
base::RunLoop().RunUntilIdle();
EXPECT_EQ(BluetoothAdvertisement::ERROR_STARTING_ADVERTISEMENT,
last_advertisement_error_code_);
EXPECT_TRUE(adapter_->GetPendingAdvertisementsForTesting().empty());
}
TEST_P(BluetoothTestWinrt, RegisterMultipleAdvertisements) {
if (!PlatformSupportsLowEnergy()) {
GTEST_SKIP() << "Low Energy Bluetooth unavailable, skipping unit test.";
}
InitWithFakeAdapter();
constexpr size_t kNumAdvertisements = 10u;
for (size_t i = 0; i < kNumAdvertisements; ++i) {
auto advertisement_data = std::make_unique<BluetoothAdvertisement::Data>(
BluetoothAdvertisement::ADVERTISEMENT_TYPE_BROADCAST);
advertisement_data->set_manufacturer_data(
BluetoothAdvertisement::ManufacturerData());
adapter_->RegisterAdvertisement(
std::move(advertisement_data),
GetCreateAdvertisementCallback(Call::EXPECTED),
GetAdvertisementErrorCallback(Call::NOT_EXPECTED));
}
base::RunLoop().RunUntilIdle();
auto pending_advertisements = adapter_->GetPendingAdvertisementsForTesting();
ASSERT_EQ(kNumAdvertisements, pending_advertisements.size());
for (size_t i = 0; i < kNumAdvertisements; ++i)
SimulateAdvertisementStarted(pending_advertisements[i]);
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(adapter_->GetPendingAdvertisementsForTesting().empty());
}
TEST_P(BluetoothTestWinrt, UnregisterAdvertisementWhilePendingUnregister) {
if (!PlatformSupportsLowEnergy()) {
GTEST_SKIP() << "Low Energy Bluetooth unavailable, skipping unit test.";
}
InitWithFakeAdapter();
auto advertisement_data = std::make_unique<BluetoothAdvertisement::Data>(
BluetoothAdvertisement::ADVERTISEMENT_TYPE_BROADCAST);
advertisement_data->set_manufacturer_data(
BluetoothAdvertisement::ManufacturerData());
adapter_->RegisterAdvertisement(
std::move(advertisement_data),
GetCreateAdvertisementCallback(Call::EXPECTED),
GetAdvertisementErrorCallback(Call::NOT_EXPECTED));
base::RunLoop().RunUntilIdle();
auto pending_advertisements = adapter_->GetPendingAdvertisementsForTesting();
ASSERT_EQ(1u, pending_advertisements.size());
auto* advertisement = pending_advertisements[0];
SimulateAdvertisementStarted(advertisement);
base::RunLoop().RunUntilIdle();
TestBluetoothAdvertisementObserver observer(advertisement);
advertisement->Unregister(GetCallback(Call::EXPECTED),
GetAdvertisementErrorCallback(Call::NOT_EXPECTED));
// Schedule another Unregister, which is expected to fail.
advertisement->Unregister(GetCallback(Call::NOT_EXPECTED),
GetAdvertisementErrorCallback(Call::EXPECTED));
base::RunLoop().RunUntilIdle();
// Expect no change to the observer status.
EXPECT_FALSE(observer.released());
EXPECT_EQ(0u, observer.released_count());
EXPECT_EQ(BluetoothAdvertisement::ERROR_RESET_ADVERTISING,
last_advertisement_error_code_);
// Simulate success of the first unregistration.
SimulateAdvertisementStopped(advertisement);
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(observer.released());
EXPECT_EQ(1u, observer.released_count());
EXPECT_TRUE(adapter_->GetPendingAdvertisementsForTesting().empty());
}
TEST_P(BluetoothTestWinrt, DoubleUnregisterAdvertisement) {
if (!PlatformSupportsLowEnergy()) {
GTEST_SKIP() << "Low Energy Bluetooth unavailable, skipping unit test.";
}
InitWithFakeAdapter();
auto advertisement_data = std::make_unique<BluetoothAdvertisement::Data>(
BluetoothAdvertisement::ADVERTISEMENT_TYPE_BROADCAST);
advertisement_data->set_manufacturer_data(
BluetoothAdvertisement::ManufacturerData());
adapter_->RegisterAdvertisement(
std::move(advertisement_data),
GetCreateAdvertisementCallback(Call::EXPECTED),
GetAdvertisementErrorCallback(Call::NOT_EXPECTED));
base::RunLoop().RunUntilIdle();
auto pending_advertisements = adapter_->GetPendingAdvertisementsForTesting();
ASSERT_EQ(1u, pending_advertisements.size());
auto* advertisement = pending_advertisements[0];
SimulateAdvertisementStarted(advertisement);
base::RunLoop().RunUntilIdle();
// Perform two unregistrations after each other. Both should succeed.
TestBluetoothAdvertisementObserver observer(advertisement);
advertisement->Unregister(GetCallback(Call::EXPECTED),
GetAdvertisementErrorCallback(Call::NOT_EXPECTED));
SimulateAdvertisementStopped(advertisement);
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(observer.released());
EXPECT_EQ(1u, observer.released_count());
advertisement->Unregister(GetCallback(Call::EXPECTED),
GetAdvertisementErrorCallback(Call::NOT_EXPECTED));
SimulateAdvertisementStopped(advertisement);
base::RunLoop().RunUntilIdle();
// The second unregister is a no-op, and should not notify observers again.
EXPECT_TRUE(observer.released());
EXPECT_EQ(1u, observer.released_count());
EXPECT_TRUE(adapter_->GetPendingAdvertisementsForTesting().empty());
}
TEST_P(BluetoothTestWinrt, SimulateAdvertisementStoppedByOS) {
if (!PlatformSupportsLowEnergy()) {
GTEST_SKIP() << "Low Energy Bluetooth unavailable, skipping unit test.";
}
InitWithFakeAdapter();
auto advertisement_data = std::make_unique<BluetoothAdvertisement::Data>(
BluetoothAdvertisement::ADVERTISEMENT_TYPE_BROADCAST);
advertisement_data->set_manufacturer_data(
BluetoothAdvertisement::ManufacturerData());
adapter_->RegisterAdvertisement(
std::move(advertisement_data),
GetCreateAdvertisementCallback(Call::EXPECTED),
GetAdvertisementErrorCallback(Call::NOT_EXPECTED));
base::RunLoop().RunUntilIdle();
auto pending_advertisements = adapter_->GetPendingAdvertisementsForTesting();
ASSERT_EQ(1u, pending_advertisements.size());
auto* advertisement = pending_advertisements[0];
SimulateAdvertisementStarted(advertisement);
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(adapter_->GetPendingAdvertisementsForTesting().empty());
TestBluetoothAdvertisementObserver observer(advertisement);
// Simulate the OS stopping the advertisement. This should notify the
// |observer|.
SimulateAdvertisementStopped(advertisement);
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(observer.released());
EXPECT_EQ(1u, observer.released_count());
// While Unregister() is a no-op now, we still expect an invocation of the
// success callback, but no change to the |observer| state.
advertisement->Unregister(GetCallback(Call::EXPECTED),
GetAdvertisementErrorCallback(Call::NOT_EXPECTED));
base::RunLoop().RunUntilIdle();
EXPECT_TRUE(observer.released());
EXPECT_EQ(1u, observer.released_count());
}
#endif // BUILDFLAG(IS_WIN)
#if (BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_LINUX)) && \
!defined(USE_CAST_BLUETOOTH_ADAPTER)
#define MAYBE_RegisterLocalGattServices RegisterLocalGattServices
#else
#define MAYBE_RegisterLocalGattServices DISABLED_RegisterLocalGattServices
#endif
TEST_F(BluetoothTest, MAYBE_RegisterLocalGattServices) {
InitWithFakeAdapter();
base::WeakPtr<BluetoothLocalGattService> service =
adapter_->CreateLocalGattService(BluetoothUUID(kTestUUIDGenericAttribute),
true, nullptr);
base::WeakPtr<BluetoothLocalGattCharacteristic> characteristic1 =
service->CreateCharacteristic(
BluetoothUUID(kTestUUIDGenericAttribute),
BluetoothLocalGattCharacteristic::Properties(),
BluetoothLocalGattCharacteristic::Permissions());
base::WeakPtr<BluetoothLocalGattCharacteristic> characteristic2 =
service->CreateCharacteristic(
BluetoothUUID(kTestUUIDGenericAttribute),
BluetoothLocalGattCharacteristic::Properties(),
BluetoothLocalGattCharacteristic::Permissions());
base::WeakPtr<BluetoothLocalGattDescriptor> descriptor =
BluetoothLocalGattDescriptor::Create(
BluetoothUUID(kTestUUIDGenericAttribute),
BluetoothLocalGattCharacteristic::Permissions(),
characteristic1.get());
service->Register(GetCallback(Call::EXPECTED),
GetGattErrorCallback(Call::NOT_EXPECTED));
service->Register(GetCallback(Call::NOT_EXPECTED),
GetGattErrorCallback(Call::EXPECTED));
service->Unregister(GetCallback(Call::EXPECTED),
GetGattErrorCallback(Call::NOT_EXPECTED));
service->Unregister(GetCallback(Call::NOT_EXPECTED),
GetGattErrorCallback(Call::EXPECTED));
}
#if (BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_LINUX)) && \
!defined(USE_CAST_BLUETOOTH_ADAPTER)
#define MAYBE_RegisterMultipleServices RegisterMultipleServices
#else
#define MAYBE_RegisterMultipleServices DISABLED_RegisterMultipleServices
#endif
TEST_F(BluetoothTest, MAYBE_RegisterMultipleServices) {
InitWithFakeAdapter();
base::WeakPtr<BluetoothLocalGattService> service2 =
adapter_->CreateLocalGattService(BluetoothUUID(kTestUUIDGenericAttribute),
true, nullptr);
base::WeakPtr<BluetoothLocalGattService> service3 =
adapter_->CreateLocalGattService(BluetoothUUID(kTestUUIDGenericAttribute),
true, nullptr);
base::WeakPtr<BluetoothLocalGattService> service4 =
adapter_->CreateLocalGattService(BluetoothUUID(kTestUUIDGenericAttribute),
true, nullptr);
service2->Register(GetCallback(Call::EXPECTED),
GetGattErrorCallback(Call::NOT_EXPECTED));
EXPECT_TRUE(ServiceSetsEqual(RegisteredGattServices(), {service2.get()}));
service3->Register(GetCallback(Call::EXPECTED),
GetGattErrorCallback(Call::NOT_EXPECTED));
EXPECT_TRUE(ServiceSetsEqual(RegisteredGattServices(),
{service2.get(), service3.get()}));
service2->Unregister(GetCallback(Call::EXPECTED),
GetGattErrorCallback(Call::NOT_EXPECTED));
EXPECT_TRUE(ServiceSetsEqual(RegisteredGattServices(), {service3.get()}));
service4->Register(GetCallback(Call::EXPECTED),
GetGattErrorCallback(Call::NOT_EXPECTED));
EXPECT_TRUE(ServiceSetsEqual(RegisteredGattServices(),
{service3.get(), service4.get()}));
service3->Register(GetCallback(Call::NOT_EXPECTED),
GetGattErrorCallback(Call::EXPECTED));
EXPECT_TRUE(ServiceSetsEqual(RegisteredGattServices(),
{service3.get(), service4.get()}));
service3->Unregister(GetCallback(Call::EXPECTED),
GetGattErrorCallback(Call::NOT_EXPECTED));
EXPECT_TRUE(ServiceSetsEqual(RegisteredGattServices(), {service4.get()}));
service4->Unregister(GetCallback(Call::EXPECTED),
GetGattErrorCallback(Call::NOT_EXPECTED));
EXPECT_TRUE(ServiceSetsEqual(RegisteredGattServices(), {}));
}
#if (BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_LINUX)) && \
!defined(USE_CAST_BLUETOOTH_ADAPTER)
#define MAYBE_DeleteServices DeleteServices
#else
#define MAYBE_DeleteServices DISABLED_DeleteServices
#endif
TEST_F(BluetoothTest, MAYBE_DeleteServices) {
InitWithFakeAdapter();
base::WeakPtr<BluetoothLocalGattService> service2 =
adapter_->CreateLocalGattService(BluetoothUUID(kTestUUIDGenericAttribute),
true, nullptr);
base::WeakPtr<BluetoothLocalGattService> service3 =
adapter_->CreateLocalGattService(BluetoothUUID(kTestUUIDGenericAttribute),
true, nullptr);
service2->Register(GetCallback(Call::EXPECTED),
GetGattErrorCallback(Call::NOT_EXPECTED));
EXPECT_TRUE(ServiceSetsEqual(RegisteredGattServices(), {service2.get()}));
service3->Register(GetCallback(Call::EXPECTED),
GetGattErrorCallback(Call::NOT_EXPECTED));
EXPECT_TRUE(ServiceSetsEqual(RegisteredGattServices(),
{service2.get(), service3.get()}));
service2->Unregister(GetCallback(Call::EXPECTED),
GetGattErrorCallback(Call::NOT_EXPECTED));
EXPECT_TRUE(ServiceSetsEqual(RegisteredGattServices(), {service3.get()}));
service2->Delete();
EXPECT_TRUE(ServiceSetsEqual(RegisteredGattServices(), {service3.get()}));
service3->Delete();
EXPECT_TRUE(ServiceSetsEqual(RegisteredGattServices(), {}));
// Create a service, register and then delete it, just to check everything
// still works.
base::WeakPtr<BluetoothLocalGattService> service4 =
adapter_->CreateLocalGattService(BluetoothUUID(kTestUUIDGenericAttribute),
true, nullptr);
service4->Register(GetCallback(Call::EXPECTED),
GetGattErrorCallback(Call::NOT_EXPECTED));
EXPECT_TRUE(ServiceSetsEqual(RegisteredGattServices(), {service4.get()}));
service4->Delete();
EXPECT_TRUE(ServiceSetsEqual(RegisteredGattServices(), {}));
}
// This test should only be enabled for platforms that uses the
// BluetoothAdapter#RemoveOutdatedDevices function to purge outdated
// devices.
#if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_APPLE)
#define MAYBE_EnsureUpdatedTimestamps EnsureUpdatedTimestamps
#else
#define MAYBE_EnsureUpdatedTimestamps DISABLED_EnsureUpdatedTimestamps
#endif
TEST_F(BluetoothTest, MAYBE_EnsureUpdatedTimestamps) {
if (!PlatformSupportsLowEnergy()) {
GTEST_SKIP() << "Low Energy Bluetooth unavailable, skipping unit test.";
}
InitWithFakeAdapter();
TestBluetoothAdapterObserver observer(adapter_);
// Test that the timestamp of a device is updated during multiple
// discovery sessions.
StartLowEnergyDiscoverySession();
BluetoothDevice* device = SimulateLowEnergyDevice(1);
EXPECT_EQ(1, observer.device_added_count());
EXPECT_EQ(1u, adapter_->GetDevices().size());
base::Time first_timestamp = device->GetLastUpdateTime();
// Do a new discovery and check that the timestamp is updated.
observer.Reset();
StartLowEnergyDiscoverySession();
SimulateLowEnergyDevice(1);
EXPECT_EQ(0, observer.device_added_count());
EXPECT_EQ(1u, adapter_->GetDevices().size());
base::Time second_timestamp = device->GetLastUpdateTime();
EXPECT_TRUE(second_timestamp > first_timestamp);
// Check that timestamp doesn't change when there is no discovery.
base::Time third_timestamp = device->GetLastUpdateTime();
EXPECT_TRUE(second_timestamp == third_timestamp);
}
// This test should only be enabled for platforms that uses the
// BluetoothAdapter#RemoveOutdatedDevices function to purge outdated
// devices.
#if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_APPLE)
#define MAYBE_RemoveOutdatedDevices RemoveOutdatedDevices
#else
#define MAYBE_RemoveOutdatedDevices DISABLED_RemoveOutdatedDevices
#endif
TEST_F(BluetoothTest, MAYBE_RemoveOutdatedDevices) {
if (!PlatformSupportsLowEnergy()) {
GTEST_SKIP() << "Low Energy Bluetooth unavailable, skipping unit test.";
}
InitWithFakeAdapter();
TestBluetoothAdapterObserver observer(adapter_);
StartLowEnergyDiscoverySession();
BluetoothDevice* device1 = SimulateLowEnergyDevice(1);
BluetoothDevice* device2 = SimulateLowEnergyDevice(4);
EXPECT_EQ(2u, adapter_->GetDevices().size());
device1->SetAsExpiredForTesting();
// Check that the outdated device is removed.
RemoveTimedOutDevices();
EXPECT_EQ(1, observer.device_removed_count());
EXPECT_EQ(1u, adapter_->GetDevices().size());
EXPECT_EQ(adapter_->GetDevices()[0]->GetAddress(), device2->GetAddress());
}
// This test should only be enabled for platforms that uses the
// BluetoothAdapter#RemoveOutdatedDevices function to purge outdated
// devices.
#if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_APPLE)
#define MAYBE_RemoveOutdatedDeviceGattConnect RemoveOutdatedDeviceGattConnect
#else
#define MAYBE_RemoveOutdatedDeviceGattConnect \
DISABLED_RemoveOutdatedDeviceGattConnect
#endif
TEST_F(BluetoothTest, MAYBE_RemoveOutdatedDeviceGattConnect) {
// Test that a device with GATT connection isn't removed.
if (!PlatformSupportsLowEnergy()) {
GTEST_SKIP() << "Low Energy Bluetooth unavailable, skipping unit test.";
}
InitWithFakeAdapter();
TestBluetoothAdapterObserver observer(adapter_);
StartLowEnergyDiscoverySession();
BluetoothDevice* device = SimulateLowEnergyDevice(1);
device->SetAsExpiredForTesting();
device->CreateGattConnection(
GetGattConnectionCallback(Call::EXPECTED, Result::SUCCESS));
SimulateGattConnection(device);
base::RunLoop().RunUntilIdle();
EXPECT_EQ(1u, adapter_->GetDevices().size());
RemoveTimedOutDevices();
EXPECT_EQ(0, observer.device_removed_count());
EXPECT_EQ(1u, adapter_->GetDevices().size());
}
#if BUILDFLAG(IS_APPLE)
// Simulate two devices being connected before calling
// RetrieveGattConnectedDevicesWithDiscoveryFilter() with no service filter.
TEST_F(BluetoothTest, DiscoverConnectedLowEnergyDeviceWithNoFilter) {
if (!PlatformSupportsLowEnergy()) {
GTEST_SKIP() << "Low Energy Bluetooth unavailable, skipping unit test.";
}
InitWithFakeAdapter();
TestBluetoothAdapterObserver observer(adapter_);
SimulateConnectedLowEnergyDevice(ConnectedDeviceType::GENERIC_DEVICE);
SimulateConnectedLowEnergyDevice(ConnectedDeviceType::HEART_RATE_DEVICE);
BluetoothDiscoveryFilter discovery_filter(BLUETOOTH_TRANSPORT_LE);
std::unordered_map<BluetoothDevice*, BluetoothDevice::UUIDSet> result =
adapter_->RetrieveGattConnectedDevicesWithDiscoveryFilter(
discovery_filter);
EXPECT_EQ(2u, result.size());
for (const auto& pair : result) {
EXPECT_TRUE(adapter_->GetDevice(pair.first->GetAddress()));
EXPECT_TRUE(pair.second.empty());
}
EXPECT_EQ(BluetoothDevice::UUIDSet({BluetoothUUID(kTestUUIDGenericAccess)}),
RetrieveConnectedPeripheralServiceUUIDs());
EXPECT_EQ(2, observer.device_added_count());
EXPECT_EQ(2u, adapter_->GetDevices().size());
}
#endif // BUILDFLAG(IS_APPLE)
#if BUILDFLAG(IS_APPLE)
// Simulate two devices being connected before calling
// RetrieveGattConnectedDevicesWithDiscoveryFilter() with one service filter.
TEST_F(BluetoothTest, DiscoverConnectedLowEnergyDeviceWithFilter) {
if (!PlatformSupportsLowEnergy()) {
GTEST_SKIP() << "Low Energy Bluetooth unavailable, skipping unit test.";
}
InitWithFakeAdapter();
TestBluetoothAdapterObserver observer(adapter_);
SimulateConnectedLowEnergyDevice(ConnectedDeviceType::GENERIC_DEVICE);
SimulateConnectedLowEnergyDevice(ConnectedDeviceType::HEART_RATE_DEVICE);
BluetoothDiscoveryFilter discovery_filter(BLUETOOTH_TRANSPORT_LE);
BluetoothUUID heart_service_uuid = BluetoothUUID(kTestUUIDHeartRate);
AddDeviceFilterWithUUID(&discovery_filter, heart_service_uuid);
std::unordered_map<BluetoothDevice*, BluetoothDevice::UUIDSet> result =
adapter_->RetrieveGattConnectedDevicesWithDiscoveryFilter(
discovery_filter);
EXPECT_EQ(1u, result.size());
for (const auto& pair : result) {
EXPECT_EQ(kTestDeviceAddress2, pair.first->GetAddress());
EXPECT_TRUE(adapter_->GetDevice(pair.first->GetAddress()));
EXPECT_EQ(BluetoothDevice::UUIDSet({heart_service_uuid}), pair.second);
}
EXPECT_EQ(BluetoothDevice::UUIDSet({heart_service_uuid}),
RetrieveConnectedPeripheralServiceUUIDs());
EXPECT_EQ(1, observer.device_added_count());
EXPECT_EQ(1u, adapter_->GetDevices().size());
}
#endif // BUILDFLAG(IS_APPLE)
#if BUILDFLAG(IS_APPLE)
// Simulate two devices being connected before calling
// RetrieveGattConnectedDevicesWithDiscoveryFilter() with one service filter
// that doesn't match.
TEST_F(BluetoothTest, DiscoverConnectedLowEnergyDeviceWithWrongFilter) {
if (!PlatformSupportsLowEnergy()) {
GTEST_SKIP() << "Low Energy Bluetooth unavailable, skipping unit test.";
}
InitWithFakeAdapter();
TestBluetoothAdapterObserver observer(adapter_);
SimulateConnectedLowEnergyDevice(ConnectedDeviceType::GENERIC_DEVICE);
SimulateConnectedLowEnergyDevice(ConnectedDeviceType::HEART_RATE_DEVICE);
BluetoothDiscoveryFilter discovery_filter(BLUETOOTH_TRANSPORT_LE);
AddDeviceFilterWithUUID(&discovery_filter, BluetoothUUID(kTestUUIDLinkLoss));
std::unordered_map<BluetoothDevice*, BluetoothDevice::UUIDSet> result =
adapter_->RetrieveGattConnectedDevicesWithDiscoveryFilter(
discovery_filter);
EXPECT_TRUE(result.empty());
EXPECT_EQ(
BluetoothDevice::UUIDSet({device::BluetoothUUID(kTestUUIDLinkLoss)}),
RetrieveConnectedPeripheralServiceUUIDs());
EXPECT_EQ(0, observer.device_added_count());
EXPECT_EQ(0u, adapter_->GetDevices().size());
}
#endif // BUILDFLAG(IS_APPLE)
#if BUILDFLAG(IS_APPLE)
// Simulate two devices being connected before calling
// RetrieveGattConnectedDevicesWithDiscoveryFilter() with two service filters
// that both match.
TEST_F(BluetoothTest, DiscoverConnectedLowEnergyDeviceWithTwoFilters) {
if (!PlatformSupportsLowEnergy()) {
GTEST_SKIP() << "Low Energy Bluetooth unavailable, skipping unit test.";
}
InitWithFakeAdapter();
TestBluetoothAdapterObserver observer(adapter_);
SimulateConnectedLowEnergyDevice(ConnectedDeviceType::GENERIC_DEVICE);
SimulateConnectedLowEnergyDevice(ConnectedDeviceType::HEART_RATE_DEVICE);
BluetoothDiscoveryFilter discovery_filter(BLUETOOTH_TRANSPORT_LE);
BluetoothUUID heart_service_uuid = BluetoothUUID(kTestUUIDHeartRate);
AddDeviceFilterWithUUID(&discovery_filter, heart_service_uuid);
BluetoothUUID generic_service_uuid = BluetoothUUID(kTestUUIDGenericAccess);
AddDeviceFilterWithUUID(&discovery_filter, generic_service_uuid);
std::unordered_map<BluetoothDevice*, BluetoothDevice::UUIDSet> result =
adapter_->RetrieveGattConnectedDevicesWithDiscoveryFilter(
discovery_filter);
EXPECT_EQ(2u, result.size());
for (const auto& pair : result) {
EXPECT_TRUE(adapter_->GetDevice(pair.first->GetAddress()));
if (pair.first->GetAddress() == kTestDeviceAddress2) {
EXPECT_EQ(
BluetoothDevice::UUIDSet({heart_service_uuid, generic_service_uuid}),
pair.second);
} else if (pair.first->GetAddress() == kTestDeviceAddress1) {
EXPECT_EQ(BluetoothDevice::UUIDSet({generic_service_uuid}), pair.second);
} else {
// Unknown device.
EXPECT_TRUE(false);
}
}
EXPECT_EQ(
BluetoothDevice::UUIDSet({generic_service_uuid, heart_service_uuid}),
RetrieveConnectedPeripheralServiceUUIDs());
EXPECT_EQ(2, observer.device_added_count());
EXPECT_EQ(2u, adapter_->GetDevices().size());
}
#endif // BUILDFLAG(IS_APPLE)
#if BUILDFLAG(IS_APPLE)
// Simulate two devices being connected before calling
// RetrieveGattConnectedDevicesWithDiscoveryFilter() with one service filter
// that one match device, and then
// RetrieveGattConnectedDevicesWithDiscoveryFilter() again.
TEST_F(BluetoothTest, DiscoverConnectedLowEnergyDeviceTwice) {
if (!PlatformSupportsLowEnergy()) {
GTEST_SKIP() << "Low Energy Bluetooth unavailable, skipping unit test.";
}
InitWithFakeAdapter();
TestBluetoothAdapterObserver observer(adapter_);
SimulateConnectedLowEnergyDevice(ConnectedDeviceType::GENERIC_DEVICE);
SimulateConnectedLowEnergyDevice(ConnectedDeviceType::HEART_RATE_DEVICE);
BluetoothDiscoveryFilter discovery_filter(BLUETOOTH_TRANSPORT_LE);
BluetoothUUID heart_service_uuid = BluetoothUUID(kTestUUIDHeartRate);
AddDeviceFilterWithUUID(&discovery_filter, heart_service_uuid);
std::unordered_map<BluetoothDevice*, BluetoothDevice::UUIDSet> result =
adapter_->RetrieveGattConnectedDevicesWithDiscoveryFilter(
discovery_filter);
EXPECT_EQ(1u, result.size());
for (const auto& pair : result) {
EXPECT_EQ(kTestDeviceAddress2, pair.first->GetAddress());
EXPECT_TRUE(adapter_->GetDevice(pair.first->GetAddress()));
EXPECT_EQ(BluetoothDevice::UUIDSet({heart_service_uuid}), pair.second);
}
EXPECT_EQ(BluetoothDevice::UUIDSet({heart_service_uuid}),
RetrieveConnectedPeripheralServiceUUIDs());
EXPECT_EQ(1, observer.device_added_count());
EXPECT_EQ(1u, adapter_->GetDevices().size());
observer.Reset();
ResetRetrieveConnectedPeripheralServiceUUIDs();
result = adapter_->RetrieveGattConnectedDevicesWithDiscoveryFilter(
discovery_filter);
EXPECT_EQ(1u, result.size());
for (const auto& pair : result) {
EXPECT_EQ(kTestDeviceAddress2, pair.first->GetAddress());
EXPECT_TRUE(adapter_->GetDevice(pair.first->GetAddress()));
EXPECT_EQ(BluetoothDevice::UUIDSet({heart_service_uuid}), pair.second);
}
EXPECT_EQ(BluetoothDevice::UUIDSet({heart_service_uuid}),
RetrieveConnectedPeripheralServiceUUIDs());
EXPECT_EQ(0, observer.device_added_count());
EXPECT_EQ(1u, adapter_->GetDevices().size());
}
#endif // BUILDFLAG(IS_APPLE)
#if BUILDFLAG(IS_WIN)
INSTANTIATE_TEST_SUITE_P(All,
BluetoothTestWinrt,
::testing::ValuesIn(kBluetoothTestWinrtParam));
#endif // BUILDFLAG(IS_WIN)
} // namespace device
|