bluetooth_device_unittest.cc 91 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491
  1. // Copyright 2014 The Chromium Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "device/bluetooth/bluetooth_device.h"
  5. #include <stddef.h>
  6. #include "base/bind.h"
  7. #include "base/containers/contains.h"
  8. #include "base/logging.h"
  9. #include "base/run_loop.h"
  10. #include "base/strings/utf_string_conversions.h"
  11. #include "base/test/bind.h"
  12. #include "base/test/test_future.h"
  13. #include "base/threading/sequenced_task_runner_handle.h"
  14. #include "build/build_config.h"
  15. #include "device/bluetooth/bluetooth_remote_gatt_service.h"
  16. #include "device/bluetooth/public/cpp/bluetooth_address.h"
  17. #include "device/bluetooth/test/mock_pairing_delegate.h"
  18. #include "device/bluetooth/test/test_bluetooth_adapter_observer.h"
  19. #include "testing/gtest/include/gtest/gtest.h"
  20. #if BUILDFLAG(IS_ANDROID)
  21. #include "device/bluetooth/test/bluetooth_test_android.h"
  22. #elif BUILDFLAG(IS_MAC)
  23. #include "device/bluetooth/test/bluetooth_test_mac.h"
  24. #elif BUILDFLAG(IS_WIN)
  25. #include "device/bluetooth/test/bluetooth_test_win.h"
  26. #elif defined(USE_CAST_BLUETOOTH_ADAPTER)
  27. #include "device/bluetooth/test/bluetooth_test_cast.h"
  28. #elif BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_LINUX)
  29. #include "device/bluetooth/test/bluetooth_test_bluez.h"
  30. #elif BUILDFLAG(IS_FUCHSIA)
  31. #include "device/bluetooth/test/bluetooth_test_fuchsia.h"
  32. #endif
  33. namespace device {
  34. namespace {
  35. using ::testing::_;
  36. using ::testing::StrictMock;
  37. int8_t ToInt8(BluetoothTest::TestRSSI rssi) {
  38. return static_cast<int8_t>(rssi);
  39. }
  40. int8_t ToInt8(BluetoothTest::TestTxPower tx_power) {
  41. return static_cast<int8_t>(tx_power);
  42. }
  43. #if BUILDFLAG(IS_WIN)
  44. void ScheduleAsynchronousCancelPairing(BluetoothDevice* device) {
  45. base::SequencedTaskRunnerHandle::Get()->PostTask(
  46. FROM_HERE, base::BindOnce(&BluetoothDevice::CancelPairing,
  47. base::Unretained(device)));
  48. }
  49. void ScheduleAsynchronousRejectPairing(BluetoothDevice* device) {
  50. base::SequencedTaskRunnerHandle::Get()->PostTask(
  51. FROM_HERE, base::BindOnce(&BluetoothDevice::RejectPairing,
  52. base::Unretained(device)));
  53. }
  54. #endif // BUILDFLAG(IS_WIN)
  55. } // namespace
  56. using UUIDSet = BluetoothDevice::UUIDSet;
  57. using ServiceDataMap = BluetoothDevice::ServiceDataMap;
  58. using ManufacturerDataMap = BluetoothDevice::ManufacturerDataMap;
  59. TEST(BluetoothDeviceTest, CanonicalizeAddressFormat_AcceptsAllValidFormats) {
  60. // There are three valid separators (':', '-', and none).
  61. // Case shouldn't matter.
  62. const char* const kValidFormats[] = {
  63. "1A:2B:3C:4D:5E:6F",
  64. "1a:2B:3c:4D:5e:6F",
  65. "1a:2b:3c:4d:5e:6f",
  66. "1A-2B-3C-4D-5E-6F",
  67. "1a-2B-3c-4D-5e-6F",
  68. "1a-2b-3c-4d-5e-6f",
  69. "1A2B3C4D5E6F",
  70. "1a2B3c4D5e6F",
  71. "1a2b3c4d5e6f",
  72. };
  73. for (size_t i = 0; i < std::size(kValidFormats); ++i) {
  74. SCOPED_TRACE(std::string("Input format: '") + kValidFormats[i] + "'");
  75. EXPECT_EQ("1A:2B:3C:4D:5E:6F",
  76. CanonicalizeBluetoothAddress(kValidFormats[i]));
  77. std::array<uint8_t, 6> parsed;
  78. EXPECT_TRUE(ParseBluetoothAddress(kValidFormats[i], parsed));
  79. EXPECT_EQ("\x1a\x2b\x3c\x4d\x5e\x6f",
  80. std::string(parsed.begin(), parsed.end()));
  81. }
  82. }
  83. TEST(BluetoothDeviceTest,
  84. CanonicalizeAddressFormat_AcceptsAllValidFormatsBytes) {
  85. std::array<uint8_t, 6> kValidBytes = {12, 14, 76, 200, 5, 8};
  86. EXPECT_EQ("0C:0E:4C:C8:05:08", CanonicalizeBluetoothAddress(kValidBytes));
  87. }
  88. TEST(BluetoothDeviceTest, CanonicalizeAddressFormat_RejectsInvalidFormats) {
  89. const char* const kInvalidFormats[] = {
  90. // Empty string.
  91. "",
  92. // Too short.
  93. "1A:2B:3C:4D:5E",
  94. // Too long.
  95. "1A:2B:3C:4D:5E:6F:70",
  96. // Missing a separator.
  97. "1A:2B:3C:4D:5E6F",
  98. // Mixed separators.
  99. "1A:2B-3C:4D-5E:6F",
  100. // Invalid hex (6X)
  101. "1A:2B:3C:4D:5E:6X",
  102. // Separators in the wrong place.
  103. "1:A2:B3:C4:D5:E6F",
  104. // Wrong separator
  105. "1A|2B|3C|4D|5E|6F",
  106. };
  107. for (size_t i = 0; i < std::size(kInvalidFormats); ++i) {
  108. SCOPED_TRACE(std::string("Input format: '") + kInvalidFormats[i] + "'");
  109. EXPECT_EQ(std::string(), CanonicalizeBluetoothAddress(kInvalidFormats[i]));
  110. std::array<uint8_t, 6> parsed;
  111. EXPECT_FALSE(ParseBluetoothAddress(kInvalidFormats[i], parsed));
  112. }
  113. }
  114. #if BUILDFLAG(IS_WIN)
  115. TEST_P(BluetoothTestWinrtOnly, DeviceIsPaired) {
  116. if (!PlatformSupportsLowEnergy()) {
  117. LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test.";
  118. return;
  119. }
  120. InitWithFakeAdapter();
  121. StartLowEnergyDiscoverySession();
  122. BluetoothDevice* device = SimulateLowEnergyDevice(1);
  123. // By default a device should not be paired.
  124. EXPECT_FALSE(device->IsPaired());
  125. // Connect to the device and simulate a paired state.
  126. ASSERT_TRUE(ConnectGatt(device));
  127. SimulateDevicePaired(device, true);
  128. EXPECT_TRUE(device->IsPaired());
  129. SimulateDevicePaired(device, false);
  130. EXPECT_FALSE(device->IsPaired());
  131. }
  132. // Tests that providing a correct pin code results in a paired device.
  133. TEST_P(BluetoothTestWinrtOnly, DevicePairRequestPinCodeCorrect) {
  134. if (!PlatformSupportsLowEnergy()) {
  135. LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test.";
  136. return;
  137. }
  138. InitWithFakeAdapter();
  139. StartLowEnergyDiscoverySession();
  140. BluetoothDevice* device = SimulateLowEnergyDevice(1);
  141. ASSERT_TRUE(ConnectGatt(device));
  142. EXPECT_FALSE(device->IsPaired());
  143. EXPECT_FALSE(device->ExpectingPinCode());
  144. SimulatePairingPinCode(device, "123456");
  145. StrictMock<MockPairingDelegate> pairing_delegate;
  146. EXPECT_CALL(pairing_delegate, RequestPinCode)
  147. .WillOnce([](BluetoothDevice* device) {
  148. ASSERT_NE(device, nullptr);
  149. device->SetPinCode("123456");
  150. });
  151. base::RunLoop run_loop;
  152. device->Pair(
  153. &pairing_delegate,
  154. base::BindLambdaForTesting(
  155. [&](absl::optional<BluetoothDevice::ConnectErrorCode> error_code) {
  156. EXPECT_FALSE(error_code.has_value());
  157. run_loop.Quit();
  158. }));
  159. run_loop.Run();
  160. EXPECT_TRUE(device->IsPaired());
  161. EXPECT_FALSE(device->ExpectingPinCode());
  162. }
  163. // Tests that providing a wrong pin code does not result in a paired device.
  164. TEST_P(BluetoothTestWinrtOnly, DevicePairRequestPinCodeWrong) {
  165. if (!PlatformSupportsLowEnergy()) {
  166. LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test.";
  167. return;
  168. }
  169. InitWithFakeAdapter();
  170. StartLowEnergyDiscoverySession();
  171. BluetoothDevice* device = SimulateLowEnergyDevice(1);
  172. ASSERT_TRUE(ConnectGatt(device));
  173. EXPECT_FALSE(device->IsPaired());
  174. EXPECT_FALSE(device->ExpectingPinCode());
  175. SimulatePairingPinCode(device, "123456");
  176. StrictMock<MockPairingDelegate> pairing_delegate;
  177. EXPECT_CALL(pairing_delegate, RequestPinCode)
  178. .WillOnce([](BluetoothDevice* device) {
  179. ASSERT_NE(device, nullptr);
  180. device->SetPinCode("000000");
  181. });
  182. base::RunLoop run_loop;
  183. device->Pair(
  184. &pairing_delegate,
  185. base::BindLambdaForTesting(
  186. [&](absl::optional<BluetoothDevice::ConnectErrorCode> error_code) {
  187. EXPECT_EQ(BluetoothDevice::ERROR_FAILED, error_code);
  188. run_loop.Quit();
  189. }));
  190. run_loop.Run();
  191. EXPECT_FALSE(device->IsPaired());
  192. EXPECT_FALSE(device->ExpectingPinCode());
  193. }
  194. // Tests that rejecting the pairing does not result in a paired device.
  195. TEST_P(BluetoothTestWinrtOnly, DevicePairRequestPinCodeRejectPairing) {
  196. if (!PlatformSupportsLowEnergy()) {
  197. LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test.";
  198. return;
  199. }
  200. InitWithFakeAdapter();
  201. StartLowEnergyDiscoverySession();
  202. BluetoothDevice* device = SimulateLowEnergyDevice(1);
  203. ASSERT_TRUE(ConnectGatt(device));
  204. EXPECT_FALSE(device->IsPaired());
  205. EXPECT_FALSE(device->ExpectingPinCode());
  206. SimulatePairingPinCode(device, "123456");
  207. StrictMock<MockPairingDelegate> pairing_delegate;
  208. EXPECT_CALL(pairing_delegate, RequestPinCode)
  209. .WillOnce([](BluetoothDevice* device) {
  210. ASSERT_NE(device, nullptr);
  211. ScheduleAsynchronousRejectPairing(device);
  212. });
  213. base::RunLoop run_loop;
  214. device->Pair(
  215. &pairing_delegate,
  216. base::BindLambdaForTesting(
  217. [&](absl::optional<BluetoothDevice::ConnectErrorCode> error_code) {
  218. EXPECT_EQ(BluetoothDevice::ERROR_AUTH_REJECTED, error_code);
  219. run_loop.Quit();
  220. }));
  221. run_loop.Run();
  222. EXPECT_FALSE(device->IsPaired());
  223. EXPECT_FALSE(device->ExpectingPinCode());
  224. }
  225. // Tests that cancelling the pairing does not result in a paired device.
  226. TEST_P(BluetoothTestWinrtOnly, DevicePairRequestPinCodeCancelPairing) {
  227. if (!PlatformSupportsLowEnergy()) {
  228. LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test.";
  229. return;
  230. }
  231. InitWithFakeAdapter();
  232. StartLowEnergyDiscoverySession();
  233. BluetoothDevice* device = SimulateLowEnergyDevice(1);
  234. ASSERT_TRUE(ConnectGatt(device));
  235. EXPECT_FALSE(device->IsPaired());
  236. EXPECT_FALSE(device->ExpectingPinCode());
  237. SimulatePairingPinCode(device, "123456");
  238. StrictMock<MockPairingDelegate> pairing_delegate;
  239. EXPECT_CALL(pairing_delegate, RequestPinCode)
  240. .WillOnce([](BluetoothDevice* device) {
  241. ASSERT_NE(device, nullptr);
  242. ScheduleAsynchronousCancelPairing(device);
  243. });
  244. base::RunLoop run_loop;
  245. device->Pair(
  246. &pairing_delegate,
  247. base::BindLambdaForTesting(
  248. [&](absl::optional<BluetoothDevice::ConnectErrorCode> error_code) {
  249. EXPECT_EQ(BluetoothDevice::ERROR_AUTH_CANCELED, error_code);
  250. run_loop.Quit();
  251. }));
  252. run_loop.Run();
  253. EXPECT_FALSE(device->IsPaired());
  254. EXPECT_FALSE(device->ExpectingPinCode());
  255. }
  256. TEST_P(BluetoothTestWinrtOnly, DevicePairRequestConfirmOnlyAccept) {
  257. if (!PlatformSupportsLowEnergy()) {
  258. LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test.";
  259. return;
  260. }
  261. InitWithFakeAdapter();
  262. StartLowEnergyDiscoverySession();
  263. BluetoothDevice* device = SimulateLowEnergyDevice(1);
  264. ASSERT_TRUE(ConnectGatt(device));
  265. EXPECT_FALSE(device->IsPaired());
  266. SimulateConfirmOnly(device);
  267. StrictMock<MockPairingDelegate> pairing_delegate;
  268. EXPECT_CALL(pairing_delegate, AuthorizePairing)
  269. .WillOnce([](BluetoothDevice* device) {
  270. ASSERT_NE(device, nullptr);
  271. device->ConfirmPairing();
  272. });
  273. base::test::TestFuture<absl::optional<BluetoothDevice::ConnectErrorCode>>
  274. error_code_future;
  275. device->Pair(&pairing_delegate, error_code_future.GetCallback());
  276. EXPECT_FALSE(error_code_future.Get().has_value());
  277. EXPECT_TRUE(device->IsPaired());
  278. }
  279. TEST_P(BluetoothTestWinrtOnly, DevicePairRequestConfirmOnlyCancel) {
  280. if (!PlatformSupportsLowEnergy()) {
  281. LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test.";
  282. return;
  283. }
  284. InitWithFakeAdapter();
  285. StartLowEnergyDiscoverySession();
  286. BluetoothDevice* device = SimulateLowEnergyDevice(1);
  287. ASSERT_TRUE(ConnectGatt(device));
  288. EXPECT_FALSE(device->IsPaired());
  289. SimulateConfirmOnly(device);
  290. StrictMock<MockPairingDelegate> pairing_delegate;
  291. EXPECT_CALL(pairing_delegate, AuthorizePairing)
  292. .WillOnce([](BluetoothDevice* device) {
  293. ASSERT_NE(device, nullptr);
  294. ScheduleAsynchronousCancelPairing(device);
  295. });
  296. base::test::TestFuture<absl::optional<BluetoothDevice::ConnectErrorCode>>
  297. error_code_future;
  298. device->Pair(&pairing_delegate, error_code_future.GetCallback());
  299. EXPECT_EQ(error_code_future.Get(), BluetoothDevice::ERROR_AUTH_CANCELED);
  300. EXPECT_FALSE(device->IsPaired());
  301. }
  302. TEST_P(BluetoothTestWinrtOnly, DevicePairRequestConfirmPinAccept) {
  303. if (!PlatformSupportsLowEnergy()) {
  304. LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test.";
  305. return;
  306. }
  307. InitWithFakeAdapter();
  308. StartLowEnergyDiscoverySession();
  309. BluetoothDevice* device = SimulateLowEnergyDevice(1);
  310. ASSERT_TRUE(ConnectGatt(device));
  311. EXPECT_FALSE(device->IsPaired());
  312. SimulateDisplayPin(device, "123456");
  313. StrictMock<MockPairingDelegate> pairing_delegate;
  314. EXPECT_CALL(pairing_delegate, ConfirmPasskey)
  315. .WillOnce([](BluetoothDevice* device, uint32_t passkey) {
  316. ASSERT_NE(device, nullptr);
  317. ASSERT_EQ(passkey, 123456u);
  318. device->ConfirmPairing();
  319. });
  320. base::test::TestFuture<absl::optional<BluetoothDevice::ConnectErrorCode>>
  321. error_code_future;
  322. device->Pair(&pairing_delegate, error_code_future.GetCallback());
  323. EXPECT_FALSE(error_code_future.Get().has_value());
  324. EXPECT_TRUE(device->IsPaired());
  325. }
  326. TEST_P(BluetoothTestWinrtOnly, DevicePairRequestConfirmPinCancel) {
  327. if (!PlatformSupportsLowEnergy()) {
  328. LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test.";
  329. return;
  330. }
  331. InitWithFakeAdapter();
  332. StartLowEnergyDiscoverySession();
  333. BluetoothDevice* device = SimulateLowEnergyDevice(1);
  334. ASSERT_TRUE(ConnectGatt(device));
  335. EXPECT_FALSE(device->IsPaired());
  336. SimulateDisplayPin(device, "123456");
  337. StrictMock<MockPairingDelegate> pairing_delegate;
  338. EXPECT_CALL(pairing_delegate, ConfirmPasskey)
  339. .WillOnce([](BluetoothDevice* device, uint32_t passkey) {
  340. ASSERT_NE(device, nullptr);
  341. ASSERT_EQ(passkey, 123456u);
  342. ScheduleAsynchronousCancelPairing(device);
  343. });
  344. base::test::TestFuture<absl::optional<BluetoothDevice::ConnectErrorCode>>
  345. error_code_future;
  346. device->Pair(&pairing_delegate, error_code_future.GetCallback());
  347. EXPECT_EQ(error_code_future.Get(), BluetoothDevice::ERROR_AUTH_CANCELED);
  348. EXPECT_FALSE(device->IsPaired());
  349. }
  350. TEST_P(BluetoothTestWinrtOnly, DevicePairRequestConfirmPinLeadingZeroAccept) {
  351. if (!PlatformSupportsLowEnergy()) {
  352. LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test.";
  353. return;
  354. }
  355. InitWithFakeAdapter();
  356. StartLowEnergyDiscoverySession();
  357. BluetoothDevice* device = SimulateLowEnergyDevice(1);
  358. ASSERT_TRUE(ConnectGatt(device));
  359. EXPECT_FALSE(device->IsPaired());
  360. SimulateDisplayPin(device, "000001");
  361. StrictMock<MockPairingDelegate> pairing_delegate;
  362. EXPECT_CALL(pairing_delegate, ConfirmPasskey)
  363. .WillOnce([](BluetoothDevice* device, uint32_t passkey) {
  364. ASSERT_NE(device, nullptr);
  365. ASSERT_EQ(passkey, 1u);
  366. device->ConfirmPairing();
  367. });
  368. base::test::TestFuture<absl::optional<BluetoothDevice::ConnectErrorCode>>
  369. error_code_future;
  370. device->Pair(&pairing_delegate, error_code_future.GetCallback());
  371. EXPECT_FALSE(error_code_future.Get().has_value());
  372. EXPECT_TRUE(device->IsPaired());
  373. }
  374. TEST_P(BluetoothTestWinrtOnly, DevicePairRequestConfirmPinInvalid) {
  375. if (!PlatformSupportsLowEnergy()) {
  376. LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test.";
  377. return;
  378. }
  379. InitWithFakeAdapter();
  380. StartLowEnergyDiscoverySession();
  381. BluetoothDevice* device = SimulateLowEnergyDevice(1);
  382. ASSERT_TRUE(ConnectGatt(device));
  383. EXPECT_FALSE(device->IsPaired());
  384. SimulateDisplayPin(device, "1000000");
  385. StrictMock<MockPairingDelegate> pairing_delegate;
  386. EXPECT_CALL(pairing_delegate, ConfirmPasskey).Times(0);
  387. base::test::TestFuture<absl::optional<BluetoothDevice::ConnectErrorCode>>
  388. error_code_future;
  389. device->Pair(&pairing_delegate, error_code_future.GetCallback());
  390. EXPECT_EQ(error_code_future.Get(), BluetoothDevice::ERROR_AUTH_FAILED);
  391. EXPECT_FALSE(device->IsPaired());
  392. }
  393. #endif // BUILDFLAG(IS_WIN)
  394. // Verifies basic device properties, e.g. GetAddress, GetName, ...
  395. #if BUILDFLAG(IS_WIN)
  396. TEST_P(BluetoothTestWinrt, LowEnergyDeviceProperties) {
  397. #else
  398. TEST_F(BluetoothTest, LowEnergyDeviceProperties) {
  399. #endif
  400. if (!PlatformSupportsLowEnergy()) {
  401. LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test.";
  402. return;
  403. }
  404. InitWithFakeAdapter();
  405. StartLowEnergyDiscoverySession();
  406. BluetoothDevice* device = SimulateLowEnergyDevice(1);
  407. ASSERT_TRUE(device);
  408. // Bluetooth class information for BLE device is not available on Windows.
  409. #if !BUILDFLAG(IS_WIN)
  410. EXPECT_EQ(0x1F00u, device->GetBluetoothClass());
  411. #endif
  412. EXPECT_EQ(kTestDeviceAddress1, device->GetAddress());
  413. EXPECT_EQ(BluetoothDevice::VENDOR_ID_UNKNOWN, device->GetVendorIDSource());
  414. EXPECT_EQ(0, device->GetVendorID());
  415. EXPECT_EQ(0, device->GetProductID());
  416. EXPECT_EQ(0, device->GetDeviceID());
  417. EXPECT_EQ(base::UTF8ToUTF16(kTestDeviceName), device->GetNameForDisplay());
  418. EXPECT_FALSE(device->IsPaired());
  419. UUIDSet uuids = device->GetUUIDs();
  420. EXPECT_TRUE(base::Contains(uuids, BluetoothUUID(kTestUUIDGenericAccess)));
  421. EXPECT_TRUE(base::Contains(uuids, BluetoothUUID(kTestUUIDGenericAttribute)));
  422. }
  423. // Verifies that the device name can be populated by later advertisement
  424. // packets and is persistent.
  425. #if BUILDFLAG(IS_WIN)
  426. TEST_P(BluetoothTestWinrt, LowEnergyDeviceNameDelayed) {
  427. #else
  428. // This test does not yet pass on any other platform.
  429. TEST_F(BluetoothTest, DISABLED_LowEnergyDeviceNameDelayed) {
  430. #endif
  431. if (!PlatformSupportsLowEnergy()) {
  432. LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test.";
  433. return;
  434. }
  435. InitWithFakeAdapter();
  436. StartLowEnergyDiscoverySession();
  437. BluetoothDevice* device = SimulateLowEnergyDevice(3);
  438. ASSERT_TRUE(device);
  439. // GetName() returns a absl::optional<std:string> however some backends still
  440. // return an empty string rather than nullopt when no name is available.
  441. EXPECT_TRUE(!device->GetName().has_value() || device->GetName()->empty());
  442. SimulateLowEnergyDevice(1);
  443. EXPECT_EQ(base::UTF8ToUTF16(kTestDeviceName), device->GetNameForDisplay());
  444. }
  445. // Device with no advertised Service UUIDs.
  446. #if BUILDFLAG(IS_WIN)
  447. TEST_P(BluetoothTestWinrt, LowEnergyDeviceNoUUIDs) {
  448. #else
  449. TEST_F(BluetoothTest, LowEnergyDeviceNoUUIDs) {
  450. #endif
  451. if (!PlatformSupportsLowEnergy()) {
  452. LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test.";
  453. return;
  454. }
  455. InitWithFakeAdapter();
  456. StartLowEnergyDiscoverySession();
  457. BluetoothDevice* device = SimulateLowEnergyDevice(3);
  458. ASSERT_TRUE(device);
  459. UUIDSet uuids = device->GetUUIDs();
  460. EXPECT_EQ(0u, uuids.size());
  461. }
  462. #if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_LINUX) || \
  463. BUILDFLAG(IS_ANDROID)
  464. #define MAYBE_GetServiceDataUUIDs_GetServiceDataForUUID \
  465. GetServiceDataUUIDs_GetServiceDataForUUID
  466. #else
  467. #define MAYBE_GetServiceDataUUIDs_GetServiceDataForUUID \
  468. DISABLED_GetServiceDataUUIDs_GetServiceDataForUUID
  469. #endif
  470. #if BUILDFLAG(IS_WIN)
  471. TEST_P(BluetoothTestWinrtOnly, GetServiceDataUUIDs_GetServiceDataForUUID) {
  472. #else
  473. TEST_F(BluetoothTest, MAYBE_GetServiceDataUUIDs_GetServiceDataForUUID) {
  474. #endif
  475. if (!PlatformSupportsLowEnergy()) {
  476. LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test.";
  477. return;
  478. }
  479. InitWithFakeAdapter();
  480. #if !BUILDFLAG(IS_LINUX) && !BUILDFLAG(IS_CHROMEOS)
  481. // TODO(crbug.com/706043): Remove #if once StartLowEnergyDiscoverySession is
  482. // implemented for bluez.
  483. StartLowEnergyDiscoverySession();
  484. #endif // !BUILDFLAG(IS_LINUX) && !BUILDFLAG(IS_CHROMEOS)
  485. // Receive Advertisement with empty service data.
  486. BluetoothDevice* device1 = SimulateLowEnergyDevice(4);
  487. EXPECT_FALSE(device1->GetAdvertisingDataFlags().has_value());
  488. EXPECT_TRUE(device1->GetServiceData().empty());
  489. EXPECT_TRUE(device1->GetServiceDataUUIDs().empty());
  490. EXPECT_TRUE(device1->GetManufacturerData().empty());
  491. // Receive Advertisement with service data.
  492. BluetoothDevice* device2 = SimulateLowEnergyDevice(1);
  493. #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_ANDROID)
  494. EXPECT_TRUE(device2->GetAdvertisingDataFlags().has_value());
  495. EXPECT_EQ(0x04, device2->GetAdvertisingDataFlags().value());
  496. #endif
  497. EXPECT_EQ(ServiceDataMap({{BluetoothUUID(kTestUUIDHeartRate), {1}}}),
  498. device2->GetServiceData());
  499. EXPECT_EQ(UUIDSet({BluetoothUUID(kTestUUIDHeartRate)}),
  500. device2->GetServiceDataUUIDs());
  501. EXPECT_EQ(std::vector<uint8_t>({1}),
  502. *device2->GetServiceDataForUUID(BluetoothUUID(kTestUUIDHeartRate)));
  503. EXPECT_EQ(std::vector<uint8_t>({1, 2, 3, 4}),
  504. *device2->GetManufacturerDataForID(kTestManufacturerId));
  505. // Receive Advertisement with no flags and no service and manufacturer data.
  506. SimulateLowEnergyDevice(3);
  507. // TODO(crbug.com/707039): Remove #if once the BlueZ caching behavior is
  508. // changed.
  509. #if (BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_LINUX)) && \
  510. !defined(USE_CAST_BLUETOOTH_ADAPTER)
  511. // On ChromeOS and Linux, BlueZ persists all service data meaning if
  512. // a device stops advertising service data for a UUID, BlueZ will
  513. // still return the cached value for that UUID.
  514. EXPECT_EQ(ServiceDataMap({{BluetoothUUID(kTestUUIDHeartRate), {1}}}),
  515. device2->GetServiceData());
  516. EXPECT_EQ(UUIDSet({BluetoothUUID(kTestUUIDHeartRate)}),
  517. device2->GetServiceDataUUIDs());
  518. EXPECT_EQ(std::vector<uint8_t>({1}),
  519. *device2->GetServiceDataForUUID(BluetoothUUID(kTestUUIDHeartRate)));
  520. #else
  521. EXPECT_FALSE(device2->GetAdvertisingDataFlags().has_value());
  522. EXPECT_TRUE(device2->GetServiceData().empty());
  523. EXPECT_TRUE(device2->GetServiceDataUUIDs().empty());
  524. EXPECT_TRUE(device2->GetManufacturerData().empty());
  525. EXPECT_EQ(nullptr,
  526. device2->GetServiceDataForUUID(BluetoothUUID(kTestUUIDHeartRate)));
  527. #endif
  528. // Receive Advertisement with new service data and empty manufacturer data.
  529. SimulateLowEnergyDevice(2);
  530. #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_ANDROID)
  531. EXPECT_TRUE(device2->GetAdvertisingDataFlags().has_value());
  532. EXPECT_EQ(0x05, device2->GetAdvertisingDataFlags().value());
  533. #endif
  534. EXPECT_EQ(ServiceDataMap(
  535. {{BluetoothUUID(kTestUUIDHeartRate), std::vector<uint8_t>({})},
  536. {BluetoothUUID(kTestUUIDImmediateAlert), {0, 2}}}),
  537. device2->GetServiceData());
  538. EXPECT_EQ(UUIDSet({BluetoothUUID(kTestUUIDHeartRate),
  539. BluetoothUUID(kTestUUIDImmediateAlert)}),
  540. device2->GetServiceDataUUIDs());
  541. EXPECT_EQ(std::vector<uint8_t>({}),
  542. *device2->GetServiceDataForUUID(BluetoothUUID(kTestUUIDHeartRate)));
  543. EXPECT_EQ(std::vector<uint8_t>({}),
  544. *device2->GetManufacturerDataForID(kTestManufacturerId));
  545. EXPECT_EQ(
  546. std::vector<uint8_t>({0, 2}),
  547. *device2->GetServiceDataForUUID(BluetoothUUID(kTestUUIDImmediateAlert)));
  548. #if !BUILDFLAG(IS_LINUX) && !BUILDFLAG(IS_CHROMEOS)
  549. // TODO(crbug.com/706043): Remove #if once StartLowEnergyDiscoverySession is
  550. // implemented for bluez.
  551. // Stop discovery.
  552. discovery_sessions_[0]->Stop(GetCallback(Call::EXPECTED),
  553. GetErrorCallback(Call::NOT_EXPECTED));
  554. base::RunLoop().RunUntilIdle();
  555. ASSERT_FALSE(adapter_->IsDiscovering());
  556. ASSERT_FALSE(discovery_sessions_[0]->IsActive());
  557. EXPECT_FALSE(device2->GetAdvertisingDataFlags().has_value());
  558. EXPECT_TRUE(device2->GetServiceData().empty());
  559. EXPECT_TRUE(device2->GetServiceDataUUIDs().empty());
  560. EXPECT_EQ(nullptr,
  561. device2->GetServiceDataForUUID(BluetoothUUID(kTestUUIDHeartRate)));
  562. EXPECT_EQ(nullptr, device2->GetServiceDataForUUID(
  563. BluetoothUUID(kTestUUIDImmediateAlert)));
  564. #endif // !BUILDFLAG(IS_LINUX) && !BUILDFLAG(IS_CHROMEOS)
  565. }
  566. #if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_MAC)
  567. #define MAYBE_AdvertisementData_Discovery AdvertisementData_Discovery
  568. #else
  569. #define MAYBE_AdvertisementData_Discovery DISABLED_AdvertisementData_Discovery
  570. #endif
  571. // Tests that the Advertisement Data fields are correctly updated during
  572. // discovery.
  573. #if BUILDFLAG(IS_WIN)
  574. TEST_P(BluetoothTestWinrtOnly, AdvertisementData_Discovery) {
  575. #else
  576. TEST_F(BluetoothTest, MAYBE_AdvertisementData_Discovery) {
  577. #endif
  578. if (!PlatformSupportsLowEnergy()) {
  579. LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test.";
  580. return;
  581. }
  582. InitWithFakeAdapter();
  583. TestBluetoothAdapterObserver observer(adapter_);
  584. // Start Discovery Session and receive Advertisement, should
  585. // not notify of device changed because the device is new.
  586. // - GetInquiryRSSI: Should return the packet's rssi.
  587. // - GetAdvertisingDataFlags: Should return advertised flags.
  588. // - GetUUIDs: Should return Advertised UUIDs.
  589. // - GetServiceData: Should return advertised Service Data.
  590. // - GetInquiryTxPower: Should return the packet's advertised Tx Power.
  591. StartLowEnergyDiscoverySession();
  592. BluetoothDevice* device = SimulateLowEnergyDevice(1);
  593. EXPECT_EQ(0, observer.device_changed_count());
  594. EXPECT_EQ(ToInt8(TestRSSI::LOWEST), device->GetInquiryRSSI().value());
  595. #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_ANDROID)
  596. EXPECT_TRUE(device->GetAdvertisingDataFlags().has_value());
  597. EXPECT_EQ(0x04, device->GetAdvertisingDataFlags().value());
  598. #endif
  599. EXPECT_EQ(UUIDSet({BluetoothUUID(kTestUUIDGenericAccess),
  600. BluetoothUUID(kTestUUIDGenericAttribute)}),
  601. device->GetUUIDs());
  602. EXPECT_EQ(ServiceDataMap({{BluetoothUUID(kTestUUIDHeartRate), {1}}}),
  603. device->GetServiceData());
  604. EXPECT_EQ(ManufacturerDataMap({{kTestManufacturerId, {1, 2, 3, 4}}}),
  605. device->GetManufacturerData());
  606. EXPECT_EQ(ToInt8(TestTxPower::LOWEST), device->GetInquiryTxPower().value());
  607. // Receive Advertisement with no flags, no UUIDs, Service Data, or Tx Power,
  608. // should notify device changed.
  609. // - GetInquiryRSSI: Should return packet's rssi.
  610. // - GetAdvertisingDataFlags: Should return nullopt because of no flags.
  611. // - GetUUIDs: Should return no UUIDs.
  612. // - GetServiceData: Should return empty map.
  613. // - GetInquiryTxPower: Should return nullopt because of no Tx Power.
  614. SimulateLowEnergyDevice(3);
  615. EXPECT_EQ(1, observer.device_changed_count());
  616. EXPECT_EQ(ToInt8(TestRSSI::LOW), device->GetInquiryRSSI().value());
  617. EXPECT_FALSE(device->GetAdvertisingDataFlags().has_value());
  618. EXPECT_TRUE(device->GetUUIDs().empty());
  619. EXPECT_TRUE(device->GetServiceData().empty());
  620. EXPECT_TRUE(device->GetManufacturerData().empty());
  621. EXPECT_FALSE(device->GetInquiryTxPower());
  622. // Receive Advertisement with different UUIDs, Service Data, and Tx Power,
  623. // should notify device changed.
  624. // - GetInquiryRSSI: Should return last packet's rssi.
  625. // - GetAdvertisingDataFlags: Should return last advertised flags.
  626. // - GetUUIDs: Should return latest Advertised UUIDs.
  627. // - GetServiceData: Should return last advertised Service Data.
  628. // - GetInquiryTxPower: Should return last advertised Tx Power.
  629. SimulateLowEnergyDevice(2);
  630. EXPECT_EQ(2, observer.device_changed_count());
  631. EXPECT_EQ(ToInt8(TestRSSI::LOWER), device->GetInquiryRSSI().value());
  632. #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_ANDROID)
  633. EXPECT_TRUE(device->GetAdvertisingDataFlags().has_value());
  634. EXPECT_EQ(0x05, device->GetAdvertisingDataFlags().value());
  635. #endif
  636. EXPECT_EQ(UUIDSet({BluetoothUUID(kTestUUIDImmediateAlert),
  637. BluetoothUUID(kTestUUIDLinkLoss)}),
  638. device->GetUUIDs());
  639. EXPECT_EQ(ServiceDataMap(
  640. {{BluetoothUUID(kTestUUIDHeartRate), std::vector<uint8_t>({})},
  641. {BluetoothUUID(kTestUUIDImmediateAlert), {0, 2}}}),
  642. device->GetServiceData());
  643. EXPECT_EQ(ManufacturerDataMap({{kTestManufacturerId, {}}}),
  644. device->GetManufacturerData());
  645. EXPECT_EQ(ToInt8(TestTxPower::LOWER), device->GetInquiryTxPower().value());
  646. // Stop discovery session, should notify of device changed.
  647. // - GetInquiryRSSI: Should return nullopt because we are no longer
  648. // discovering.
  649. // - GetAdvertisingDataFlags: Should return no flags.
  650. // - GetUUIDs: Should not return any UUIDs.
  651. // - GetServiceData: Should return empty map.
  652. // - GetMAnufacturerData: Should return empty map.
  653. // - GetInquiryTxPower: Should return nullopt because we are no longer
  654. // discovering.
  655. discovery_sessions_[0]->Stop(GetCallback(Call::EXPECTED),
  656. GetErrorCallback(Call::NOT_EXPECTED));
  657. base::RunLoop().RunUntilIdle();
  658. ASSERT_FALSE(adapter_->IsDiscovering());
  659. ASSERT_FALSE(discovery_sessions_[0]->IsActive());
  660. EXPECT_EQ(3, observer.device_changed_count());
  661. EXPECT_FALSE(device->GetInquiryRSSI());
  662. EXPECT_FALSE(device->GetAdvertisingDataFlags().has_value());
  663. EXPECT_TRUE(device->GetUUIDs().empty());
  664. EXPECT_TRUE(device->GetServiceData().empty());
  665. EXPECT_TRUE(device->GetManufacturerData().empty());
  666. EXPECT_FALSE(device->GetInquiryTxPower());
  667. // Discover the device again with different UUIDs, should notify of device
  668. // changed.
  669. // - GetInquiryRSSI: Should return last packet's rssi.
  670. // - GetAdvertisingDataFlags: Should return last advertised flags.
  671. // - GetUUIDs: Should return only the latest Advertised UUIDs.
  672. // - GetServiceData: Should return last advertise Service Data.
  673. // - GetInquiryTxPower: Should return last advertised Tx Power.
  674. StartLowEnergyDiscoverySession();
  675. device = SimulateLowEnergyDevice(1);
  676. EXPECT_EQ(4, observer.device_changed_count());
  677. EXPECT_EQ(ToInt8(TestRSSI::LOWEST), device->GetInquiryRSSI().value());
  678. #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_ANDROID)
  679. EXPECT_TRUE(device->GetAdvertisingDataFlags().has_value());
  680. EXPECT_EQ(0x04, device->GetAdvertisingDataFlags().value());
  681. #endif
  682. EXPECT_EQ(UUIDSet({BluetoothUUID(kTestUUIDGenericAccess),
  683. BluetoothUUID(kTestUUIDGenericAttribute)}),
  684. device->GetUUIDs());
  685. EXPECT_EQ(ServiceDataMap({{BluetoothUUID(kTestUUIDHeartRate), {1}}}),
  686. device->GetServiceData());
  687. EXPECT_EQ(ManufacturerDataMap({{kTestManufacturerId, {1, 2, 3, 4}}}),
  688. device->GetManufacturerData());
  689. EXPECT_EQ(ToInt8(TestTxPower::LOWEST), device->GetInquiryTxPower().value());
  690. }
  691. // TODO(dougt) As I turn on new platforms for WebBluetooth Scanning,
  692. // I will relax this #ifdef
  693. #if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_MAC) || BUILDFLAG(IS_WIN)
  694. #define MAYBE_DeviceAdvertisementReceived DeviceAdvertisementReceived
  695. #else
  696. #define MAYBE_DeviceAdvertisementReceived DISABLED_DeviceAdvertisementReceived
  697. #endif
  698. // Tests that the Bluetooth adapter observer is notified when a device
  699. // advertisement is received.
  700. #if BUILDFLAG(IS_WIN)
  701. TEST_P(BluetoothTestWinrtOnly, DeviceAdvertisementReceived) {
  702. #else
  703. TEST_F(BluetoothTest, MAYBE_DeviceAdvertisementReceived) {
  704. #endif
  705. if (!PlatformSupportsLowEnergy()) {
  706. LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test.";
  707. return;
  708. }
  709. InitWithFakeAdapter();
  710. TestBluetoothAdapterObserver observer(adapter_);
  711. StartLowEnergyDiscoverySession();
  712. SimulateLowEnergyDevice(1);
  713. ASSERT_EQ(1, observer.device_advertisement_raw_received_count());
  714. EXPECT_EQ(kTestDeviceName, observer.last_device_name().value_or(""));
  715. EXPECT_EQ(kTestDeviceName, observer.last_advertisement_name().value_or(""));
  716. EXPECT_EQ(static_cast<int>(TestRSSI::LOWEST),
  717. observer.last_rssi().value_or(-1));
  718. EXPECT_EQ(static_cast<int>(TestTxPower::LOWEST),
  719. observer.last_tx_power().value_or(-1));
  720. // BluetoothDevice::GetAppearance() is not implemented on all platforms.
  721. // TODO(crbug.com/588083): Check this property when it is implemented.
  722. const device::BluetoothDevice::UUIDList kTestAdvertisedUUIDs = {
  723. BluetoothUUID(kTestUUIDGenericAccess),
  724. BluetoothUUID(kTestUUIDGenericAttribute)};
  725. EXPECT_EQ(kTestAdvertisedUUIDs, observer.last_advertised_uuids());
  726. const device::BluetoothDevice::ServiceDataMap kTestServiceDataMap = {
  727. {BluetoothUUID(kTestUUIDHeartRate), {1}}};
  728. EXPECT_EQ(kTestServiceDataMap, observer.last_service_data_map());
  729. const device::BluetoothDevice::ManufacturerDataMap kTestManufacturerDataMap =
  730. {{kTestManufacturerId, {1, 2, 3, 4}}};
  731. EXPECT_EQ(kTestManufacturerDataMap, observer.last_manufacturer_data_map());
  732. // Double check that we can receive another advertisement.
  733. SimulateLowEnergyDevice(2);
  734. EXPECT_EQ(2, observer.device_advertisement_raw_received_count());
  735. }
  736. #if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_MAC)
  737. #define MAYBE_GetUUIDs_Connection GetUUIDs_Connection
  738. #else
  739. #define MAYBE_GetUUIDs_Connection DISABLED_GetUUIDs_Connection
  740. #endif
  741. // Tests Advertisement Data is updated correctly during a connection.
  742. #if BUILDFLAG(IS_WIN)
  743. TEST_P(BluetoothTestWinrtOnly, GetUUIDs_Connection) {
  744. #else
  745. TEST_F(BluetoothTest, MAYBE_GetUUIDs_Connection) {
  746. #endif
  747. if (!PlatformSupportsLowEnergy()) {
  748. LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test.";
  749. return;
  750. }
  751. InitWithFakeAdapter();
  752. TestBluetoothAdapterObserver observer(adapter_);
  753. StartLowEnergyDiscoverySession();
  754. BluetoothDevice* device = SimulateLowEnergyDevice(1);
  755. discovery_sessions_[0]->Stop(GetCallback(Call::EXPECTED),
  756. GetErrorCallback(Call::NOT_EXPECTED));
  757. // Connect to the device.
  758. // - GetUUIDs: Should return no UUIDs because Services have not been
  759. // discovered.
  760. ASSERT_TRUE(ConnectGatt(device));
  761. ASSERT_TRUE(device->IsConnected());
  762. EXPECT_TRUE(device->GetUUIDs().empty());
  763. observer.Reset();
  764. // Discover services, should notify of device changed.
  765. // - GetUUIDs: Should return the device's services' UUIDs.
  766. std::vector<std::string> services;
  767. services.push_back(kTestUUIDGenericAccess);
  768. SimulateGattServicesDiscovered(device, services);
  769. base::RunLoop().RunUntilIdle();
  770. EXPECT_EQ(1, observer.device_changed_count());
  771. EXPECT_EQ(UUIDSet({BluetoothUUID(kTestUUIDGenericAccess)}),
  772. device->GetUUIDs());
  773. #if BUILDFLAG(IS_MAC) || BUILDFLAG(IS_WIN)
  774. // TODO(ortuno): Enable in Android and classic Windows.
  775. // Android and Windows don't yet support service changed events.
  776. // http://crbug.com/548280
  777. // http://crbug.com/579202
  778. observer.Reset();
  779. // Notify of services changed, should notify of device changed.
  780. // - GetUUIDs: Should return no UUIDs because we no longer know what services
  781. // the device has.
  782. SimulateGattServicesChanged(device);
  783. ASSERT_FALSE(device->IsGattServicesDiscoveryComplete());
  784. EXPECT_EQ(1, observer.device_changed_count());
  785. EXPECT_TRUE(device->GetUUIDs().empty());
  786. // Services discovered again, should notify of device changed.
  787. // - GetUUIDs: Should return Service UUIDs.
  788. SimulateGattServicesDiscovered(device, {} /* services */);
  789. base::RunLoop().RunUntilIdle();
  790. EXPECT_EQ(2, observer.device_changed_count());
  791. EXPECT_EQ(UUIDSet({BluetoothUUID(kTestUUIDGenericAccess)}),
  792. device->GetUUIDs());
  793. #endif // BUILDFLAG(IS_MAC) || BUILDFLAG(IS_WIN)
  794. observer.Reset();
  795. // Disconnect, should notify device changed.
  796. // - GetUUIDs: Should return no UUIDs since we no longer know what services
  797. // the device holds and notify of device changed.
  798. gatt_connections_[0]->Disconnect();
  799. SimulateGattDisconnection(device);
  800. base::RunLoop().RunUntilIdle();
  801. ASSERT_FALSE(device->IsGattConnected());
  802. EXPECT_EQ(1, observer.device_changed_count());
  803. EXPECT_TRUE(device->GetUUIDs().empty());
  804. }
  805. #if BUILDFLAG(IS_MAC)
  806. // Tests that receiving 2 notifications in a row from macOS that services has
  807. // changed is handled correctly. Each notification should generate a
  808. // notification that the gatt device has changed, and each notification should
  809. // ask to macOS to scan for services. Only after the second service scan is
  810. // received, the device changed notification should be sent and the
  811. // characteristic discovery procedure should be started.
  812. // Android: This test doesn't apply to Android because there is no services
  813. // changed event that could arrive during a discovery procedure.
  814. TEST_F(BluetoothTest, TwoPendingServiceDiscoveryRequests) {
  815. if (!PlatformSupportsLowEnergy()) {
  816. LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test.";
  817. return;
  818. }
  819. InitWithFakeAdapter();
  820. TestBluetoothAdapterObserver observer(adapter_);
  821. BluetoothDevice* device = SimulateLowEnergyDevice(1);
  822. ASSERT_TRUE(ConnectGatt(device));
  823. EXPECT_EQ(1, observer.device_changed_count());
  824. EXPECT_FALSE(device->IsGattServicesDiscoveryComplete());
  825. observer.Reset();
  826. SimulateGattServicesChanged(device);
  827. EXPECT_EQ(1, observer.device_changed_count());
  828. EXPECT_FALSE(device->IsGattServicesDiscoveryComplete());
  829. // First system call to
  830. // -[id<CBPeripheralDelegate> peripheral:didDiscoverServices:] using
  831. // SimulateDidDiscoverServicesMac().
  832. observer.Reset();
  833. AddServicesToDeviceMac(device, {kTestUUIDHeartRate});
  834. SimulateDidDiscoverServicesMac(device);
  835. EXPECT_EQ(0, observer.device_changed_count());
  836. EXPECT_FALSE(device->IsGattServicesDiscoveryComplete());
  837. EXPECT_EQ(gatt_characteristic_discovery_attempts_, 0);
  838. // Second system call to
  839. // -[id<CBPeripheralDelegate> peripheral:didDiscoverServices:] using the
  840. // generic call to SimulateGattServicesDiscovered(). This method triggers
  841. // the full discovery cycles (services, characteristics and descriptors),
  842. // which includes -[id<CBPeripheralDelegate> peripheral:didDiscoverServices:].
  843. SimulateGattServicesDiscovered(
  844. device, std::vector<std::string>({kTestUUIDImmediateAlert}));
  845. base::RunLoop().RunUntilIdle();
  846. EXPECT_EQ(1, observer.device_changed_count());
  847. EXPECT_TRUE(device->IsGattServicesDiscoveryComplete());
  848. // Characteristics are discovered once for each service.
  849. EXPECT_EQ(gatt_characteristic_discovery_attempts_, 2);
  850. EXPECT_EQ(2u, device->GetGattServices().size());
  851. }
  852. // Simulate an unexpected call to -[id<CBPeripheralDelegate>
  853. // peripheral:didDiscoverServices:]. This should not happen, but if it does
  854. // (buggy device?), a discovery cycle should be done.
  855. TEST_F(BluetoothTest, ExtraDidDiscoverServicesCall) {
  856. if (!PlatformSupportsLowEnergy()) {
  857. LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test.";
  858. return;
  859. }
  860. InitWithFakeAdapter();
  861. TestBluetoothAdapterObserver observer(adapter_);
  862. BluetoothDevice* device = SimulateLowEnergyDevice(1);
  863. ASSERT_TRUE(ConnectGatt(device));
  864. EXPECT_EQ(1, observer.device_changed_count());
  865. EXPECT_FALSE(device->IsGattServicesDiscoveryComplete());
  866. // Legitimate system call to
  867. // -[id<CBPeripheralDelegate> peripheral:didDiscoverServices:].
  868. observer.Reset();
  869. SimulateGattServicesDiscovered(
  870. device, std::vector<std::string>({kTestUUIDHeartRate}));
  871. base::RunLoop().RunUntilIdle();
  872. EXPECT_EQ(1, observer.device_changed_count());
  873. EXPECT_TRUE(device->IsGattServicesDiscoveryComplete());
  874. EXPECT_EQ(gatt_characteristic_discovery_attempts_, 1);
  875. EXPECT_EQ(1u, device->GetGattServices().size());
  876. // Unexpected system call to
  877. // -[id<CBPeripheralDelegate> peripheral:didDiscoverServices:]:
  878. // This system call is expected only once after -[CBCentralManager
  879. // discoverServices:]. The call to -[CBCentralManager discoverServices:] and
  880. // its answer with -[id<CBPeripheralDelegate> peripheral:didDiscoverServices:]
  881. // is done with SimulateGattServicesDiscovered(). So a second system call to
  882. // -[id<CBPeripheralDelegate> peripheral:didDiscoverServices:] is not expected
  883. // and should be ignored.
  884. AddServicesToDeviceMac(device, {kTestUUIDImmediateAlert});
  885. SimulateDidDiscoverServicesMac(device);
  886. EXPECT_EQ(1, observer.device_changed_count());
  887. EXPECT_TRUE(device->IsGattServicesDiscoveryComplete());
  888. EXPECT_EQ(1u, device->GetGattServices().size());
  889. }
  890. #endif
  891. #if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_MAC)
  892. #define MAYBE_AdvertisementData_DiscoveryDuringConnection \
  893. AdvertisementData_DiscoveryDuringConnection
  894. #else
  895. #define MAYBE_AdvertisementData_DiscoveryDuringConnection \
  896. DISABLED_AdvertisementData_DiscoveryDuringConnection
  897. #endif
  898. // Tests Advertisement Data is updated correctly when we start discovery
  899. // during a connection.
  900. #if BUILDFLAG(IS_WIN)
  901. TEST_P(BluetoothTestWinrtOnly, AdvertisementData_DiscoveryDuringConnection) {
  902. #else
  903. TEST_F(BluetoothTest, MAYBE_AdvertisementData_DiscoveryDuringConnection) {
  904. #endif
  905. if (!PlatformSupportsLowEnergy()) {
  906. LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test.";
  907. return;
  908. }
  909. InitWithFakeAdapter();
  910. TestBluetoothAdapterObserver observer(adapter_);
  911. StartLowEnergyDiscoverySession();
  912. BluetoothDevice* device = SimulateLowEnergyDevice(1);
  913. EXPECT_EQ(UUIDSet({BluetoothUUID(kTestUUIDGenericAccess),
  914. BluetoothUUID(kTestUUIDGenericAttribute)}),
  915. device->GetUUIDs());
  916. discovery_sessions_[0]->Stop(GetCallback(Call::EXPECTED),
  917. GetErrorCallback(Call::NOT_EXPECTED));
  918. base::RunLoop().RunUntilIdle();
  919. ASSERT_FALSE(adapter_->IsDiscovering());
  920. ASSERT_FALSE(discovery_sessions_[0]->IsActive());
  921. ASSERT_EQ(0u, device->GetUUIDs().size());
  922. discovery_sessions_.clear();
  923. // Connect.
  924. ASSERT_TRUE(ConnectGatt(device));
  925. ASSERT_TRUE(device->IsConnected());
  926. observer.Reset();
  927. // Start Discovery and receive advertisement during connection,
  928. // should notify of device changed.
  929. // - GetInquiryRSSI: Should return the packet's rssi.
  930. // - GetAdvertisingDataFlags: Should return last advertised flags.
  931. // - GetUUIDs: Should return only Advertised UUIDs since services haven't
  932. // been discovered yet.
  933. // - GetServiceData: Should return last advertised Service Data.
  934. // - GetInquiryTxPower: Should return the packet's advertised Tx Power.
  935. StartLowEnergyDiscoverySession();
  936. ASSERT_TRUE(adapter_->IsDiscovering());
  937. ASSERT_TRUE(discovery_sessions_[0]->IsActive());
  938. device = SimulateLowEnergyDevice(1);
  939. EXPECT_EQ(1, observer.device_changed_count());
  940. EXPECT_EQ(ToInt8(TestRSSI::LOWEST), device->GetInquiryRSSI().value());
  941. EXPECT_EQ(UUIDSet({BluetoothUUID(kTestUUIDGenericAccess),
  942. BluetoothUUID(kTestUUIDGenericAttribute)}),
  943. device->GetUUIDs());
  944. #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_ANDROID)
  945. EXPECT_TRUE(device->GetAdvertisingDataFlags().has_value());
  946. EXPECT_EQ(0x04, device->GetAdvertisingDataFlags().value());
  947. #endif
  948. EXPECT_EQ(ServiceDataMap({{BluetoothUUID(kTestUUIDHeartRate), {1}}}),
  949. device->GetServiceData());
  950. EXPECT_EQ(ToInt8(TestTxPower::LOWEST), device->GetInquiryTxPower().value());
  951. // Discover services, should notify of device changed.
  952. // - GetUUIDs: Should return both Advertised UUIDs and Service UUIDs.
  953. std::vector<std::string> services;
  954. services.push_back(kTestUUIDHeartRate);
  955. SimulateGattServicesDiscovered(device, services);
  956. base::RunLoop().RunUntilIdle();
  957. EXPECT_EQ(2, observer.device_changed_count());
  958. EXPECT_EQ(UUIDSet({BluetoothUUID(kTestUUIDGenericAccess),
  959. BluetoothUUID(kTestUUIDGenericAttribute),
  960. BluetoothUUID(kTestUUIDHeartRate)}),
  961. device->GetUUIDs());
  962. // Receive advertisement again, notify of device changed.
  963. // - GetInquiryRSSI: Should return last packet's rssi.
  964. // - GetAdvertisingDataFlags: Should return last advertised flags.
  965. // - GetUUIDs: Should return only new Advertised UUIDs and Service UUIDs.
  966. // - GetServiceData: Should return last advertised Service Data.
  967. // - GetInquiryTxPower: Should return the last packet's advertised Tx Power.
  968. device = SimulateLowEnergyDevice(2);
  969. EXPECT_EQ(3, observer.device_changed_count());
  970. EXPECT_EQ(ToInt8(TestRSSI::LOWER), device->GetInquiryRSSI().value());
  971. #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_ANDROID)
  972. EXPECT_TRUE(device->GetAdvertisingDataFlags().has_value());
  973. EXPECT_EQ(0x05, device->GetAdvertisingDataFlags().value());
  974. #endif
  975. EXPECT_EQ(UUIDSet({BluetoothUUID(kTestUUIDLinkLoss),
  976. BluetoothUUID(kTestUUIDImmediateAlert),
  977. BluetoothUUID(kTestUUIDHeartRate)}),
  978. device->GetUUIDs());
  979. EXPECT_EQ(ServiceDataMap(
  980. {{BluetoothUUID(kTestUUIDHeartRate), std::vector<uint8_t>({})},
  981. {BluetoothUUID(kTestUUIDImmediateAlert), {0, 2}}}),
  982. device->GetServiceData());
  983. EXPECT_EQ(ToInt8(TestTxPower::LOWER), device->GetInquiryTxPower().value());
  984. // Stop discovery session, should notify of device changed.
  985. // - GetInquiryRSSI: Should return nullopt because we are no longer
  986. // discovering.
  987. // - GetAdvertisingDataFlags: Should return no flags since we are no longer
  988. // discovering.
  989. // - GetUUIDs: Should only return Service UUIDs.
  990. // - GetServiceData: Should return an empty map since we are no longer
  991. // discovering.
  992. // - GetInquiryTxPower: Should return nullopt because we are no longer
  993. // discovering.
  994. discovery_sessions_[0]->Stop(GetCallback(Call::EXPECTED),
  995. GetErrorCallback(Call::NOT_EXPECTED));
  996. base::RunLoop().RunUntilIdle();
  997. ASSERT_FALSE(adapter_->IsDiscovering());
  998. ASSERT_FALSE(discovery_sessions_[0]->IsActive());
  999. EXPECT_EQ(4, observer.device_changed_count());
  1000. EXPECT_FALSE(device->GetInquiryRSSI());
  1001. EXPECT_FALSE(device->GetAdvertisingDataFlags().has_value());
  1002. EXPECT_EQ(UUIDSet({BluetoothUUID(kTestUUIDHeartRate)}), device->GetUUIDs());
  1003. EXPECT_EQ(ServiceDataMap(), device->GetServiceData());
  1004. EXPECT_FALSE(device->GetInquiryTxPower());
  1005. // Disconnect device, should notify of device changed.
  1006. // - GetUUIDs: Should return no UUIDs.
  1007. gatt_connections_[0]->Disconnect();
  1008. SimulateGattDisconnection(device);
  1009. base::RunLoop().RunUntilIdle();
  1010. ASSERT_FALSE(device->IsGattConnected());
  1011. EXPECT_EQ(5, observer.device_changed_count());
  1012. EXPECT_TRUE(device->GetUUIDs().empty());
  1013. }
  1014. #if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_MAC)
  1015. #define MAYBE_AdvertisementData_ConnectionDuringDiscovery \
  1016. AdvertisementData_ConnectionDuringDiscovery
  1017. #else
  1018. #define MAYBE_AdvertisementData_ConnectionDuringDiscovery \
  1019. DISABLED_AdvertisementData_ConnectionDuringDiscovery
  1020. #endif
  1021. #if BUILDFLAG(IS_WIN)
  1022. TEST_P(BluetoothTestWinrtOnly, AdvertisementData_ConnectionDuringDiscovery) {
  1023. #else
  1024. TEST_F(BluetoothTest, MAYBE_AdvertisementData_ConnectionDuringDiscovery) {
  1025. #endif
  1026. // Tests that the Advertisement Data is correctly updated when
  1027. // the device connects during discovery.
  1028. if (!PlatformSupportsLowEnergy()) {
  1029. LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test.";
  1030. return;
  1031. }
  1032. InitWithFakeAdapter();
  1033. TestBluetoothAdapterObserver observer(adapter_);
  1034. // Start discovery session and receive and advertisement. No device changed
  1035. // notification because it's a new device.
  1036. // - GetInquiryRSSI: Should return the packet's rssi.
  1037. // - GetAdvertisingDataFlags: Should return advertised flags.
  1038. // - GetUUIDs: Should return Advertised UUIDs.
  1039. // - GetServiceData: Should return advertised Service Data.
  1040. // - GetInquiryTxPower: Should return the packet's advertised Tx Power.
  1041. StartLowEnergyDiscoverySession();
  1042. ASSERT_TRUE(adapter_->IsDiscovering());
  1043. ASSERT_TRUE(discovery_sessions_[0]->IsActive());
  1044. BluetoothDevice* device = SimulateLowEnergyDevice(1);
  1045. EXPECT_EQ(0, observer.device_changed_count());
  1046. EXPECT_EQ(ToInt8(TestRSSI::LOWEST), device->GetInquiryRSSI().value());
  1047. #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_ANDROID)
  1048. EXPECT_TRUE(device->GetAdvertisingDataFlags().has_value());
  1049. EXPECT_EQ(0x04, device->GetAdvertisingDataFlags().value());
  1050. #endif
  1051. EXPECT_EQ(UUIDSet({BluetoothUUID(kTestUUIDGenericAccess),
  1052. BluetoothUUID(kTestUUIDGenericAttribute)}),
  1053. device->GetUUIDs());
  1054. EXPECT_EQ(ServiceDataMap({{BluetoothUUID(kTestUUIDHeartRate), {1}}}),
  1055. device->GetServiceData());
  1056. EXPECT_EQ(ToInt8(TestTxPower::LOWEST), device->GetInquiryTxPower().value());
  1057. // Connect, should notify of device changed.
  1058. // - GetUUIDs: Should return Advertised UUIDs even before GATT Discovery.
  1059. ASSERT_TRUE(ConnectGatt(device));
  1060. ASSERT_TRUE(device->IsConnected());
  1061. observer.Reset();
  1062. EXPECT_EQ(UUIDSet({BluetoothUUID(kTestUUIDGenericAccess),
  1063. BluetoothUUID(kTestUUIDGenericAttribute)}),
  1064. device->GetUUIDs());
  1065. // Receive Advertisement with new UUIDs, should notify of device changed.
  1066. // - GetInquiryRSSI: Should return the packet's rssi.
  1067. // - GetAdvertisingDataFlags: Should return advertised flags.
  1068. // - GetUUIDs: Should return new Advertised UUIDs.
  1069. // - GetServiceData: Should return new advertised Service Data.
  1070. // - GetInquiryTxPower: Should return the packet's advertised Tx Power.
  1071. device = SimulateLowEnergyDevice(2);
  1072. EXPECT_EQ(1, observer.device_changed_count());
  1073. EXPECT_EQ(ToInt8(TestRSSI::LOWER), device->GetInquiryRSSI().value());
  1074. #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_ANDROID)
  1075. EXPECT_TRUE(device->GetAdvertisingDataFlags().has_value());
  1076. EXPECT_EQ(0x05, device->GetAdvertisingDataFlags().value());
  1077. #endif
  1078. EXPECT_EQ(UUIDSet({BluetoothUUID(kTestUUIDLinkLoss),
  1079. BluetoothUUID(kTestUUIDImmediateAlert)}),
  1080. device->GetUUIDs());
  1081. EXPECT_EQ(ServiceDataMap(
  1082. {{BluetoothUUID(kTestUUIDHeartRate), std::vector<uint8_t>({})},
  1083. {BluetoothUUID(kTestUUIDImmediateAlert), {0, 2}}}),
  1084. device->GetServiceData());
  1085. EXPECT_EQ(ToInt8(TestTxPower::LOWER), device->GetInquiryTxPower().value());
  1086. // Discover Services, should notify of device changed.
  1087. // - GetUUIDs: Should return Advertised UUIDs and Service UUIDs.
  1088. std::vector<std::string> services;
  1089. services.push_back(kTestUUIDHeartRate);
  1090. SimulateGattServicesDiscovered(device, services);
  1091. base::RunLoop().RunUntilIdle();
  1092. EXPECT_EQ(2, observer.device_changed_count());
  1093. EXPECT_EQ(UUIDSet({BluetoothUUID(kTestUUIDLinkLoss),
  1094. BluetoothUUID(kTestUUIDImmediateAlert),
  1095. BluetoothUUID(kTestUUIDHeartRate)}),
  1096. device->GetUUIDs());
  1097. // Disconnect, should notify of device changed.
  1098. // - GetInquiryRSSI: Should return last packet's rssi.
  1099. // - GetAdvertisingDataFlags: Should return same advertised flags.
  1100. // - GetUUIDs: Should return only Advertised UUIDs.
  1101. // - GetServiceData: Should still return same advertised Service Data.
  1102. // - GetInquiryTxPower: Should return the last packet's advertised Tx Power.
  1103. gatt_connections_[0]->Disconnect();
  1104. SimulateGattDisconnection(device);
  1105. base::RunLoop().RunUntilIdle();
  1106. ASSERT_FALSE(device->IsGattConnected());
  1107. EXPECT_EQ(3, observer.device_changed_count());
  1108. EXPECT_EQ(ToInt8(TestRSSI::LOWER), device->GetInquiryRSSI().value());
  1109. #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_ANDROID)
  1110. EXPECT_TRUE(device->GetAdvertisingDataFlags().has_value());
  1111. EXPECT_EQ(0x05, device->GetAdvertisingDataFlags().value());
  1112. #endif
  1113. EXPECT_EQ(UUIDSet({BluetoothUUID(kTestUUIDLinkLoss),
  1114. BluetoothUUID(kTestUUIDImmediateAlert)}),
  1115. device->GetUUIDs());
  1116. EXPECT_EQ(ServiceDataMap(
  1117. {{BluetoothUUID(kTestUUIDHeartRate), std::vector<uint8_t>({})},
  1118. {BluetoothUUID(kTestUUIDImmediateAlert), {0, 2}}}),
  1119. device->GetServiceData());
  1120. EXPECT_EQ(ToInt8(TestTxPower::LOWER), device->GetInquiryTxPower().value());
  1121. // Receive Advertisement with new UUIDs, should notify of device changed.
  1122. // - GetInquiryRSSI: Should return last packet's rssi.
  1123. // - GetAdvertisingDataFlags: Should return the new advertised flags.
  1124. // - GetUUIDs: Should return only new Advertised UUIDs.
  1125. // - GetServiceData: Should return only new advertised Service Data.
  1126. // - GetInquiryTxPower: Should return the last packet's advertised Tx Power.
  1127. device = SimulateLowEnergyDevice(1);
  1128. EXPECT_EQ(4, observer.device_changed_count());
  1129. EXPECT_EQ(ToInt8(TestRSSI::LOWEST), device->GetInquiryRSSI().value());
  1130. #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_ANDROID)
  1131. EXPECT_TRUE(device->GetAdvertisingDataFlags().has_value());
  1132. EXPECT_EQ(0x04, device->GetAdvertisingDataFlags().value());
  1133. #endif
  1134. EXPECT_EQ(UUIDSet({BluetoothUUID(kTestUUIDGenericAccess),
  1135. BluetoothUUID(kTestUUIDGenericAttribute)}),
  1136. device->GetUUIDs());
  1137. EXPECT_EQ(ServiceDataMap({{BluetoothUUID(kTestUUIDHeartRate), {1}}}),
  1138. device->GetServiceData());
  1139. EXPECT_EQ(ToInt8(TestTxPower::LOWEST), device->GetInquiryTxPower().value());
  1140. // Stop discovery session, should notify of device changed.
  1141. // - GetInquiryRSSI: Should return nullopt because we are no longer
  1142. // discovering.
  1143. // - GetAdvertisingDataFlags: Should return no advertised flags since we are
  1144. // no longer discovering.
  1145. // - GetUUIDs: Should return no UUIDs.
  1146. // - GetServiceData: Should return no UUIDs since we are no longer
  1147. // discovering.
  1148. // - GetInquiryTxPower: Should return nullopt because we are no longer
  1149. // discovering.
  1150. discovery_sessions_[0]->Stop(GetCallback(Call::EXPECTED),
  1151. GetErrorCallback(Call::NOT_EXPECTED));
  1152. base::RunLoop().RunUntilIdle();
  1153. EXPECT_EQ(5, observer.device_changed_count());
  1154. EXPECT_FALSE(device->GetInquiryRSSI());
  1155. EXPECT_FALSE(device->GetAdvertisingDataFlags().has_value());
  1156. EXPECT_TRUE(device->GetUUIDs().empty());
  1157. EXPECT_TRUE(device->GetServiceData().empty());
  1158. EXPECT_FALSE(device->GetInquiryTxPower());
  1159. }
  1160. #if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_MAC) || \
  1161. BUILDFLAG(IS_LINUX)
  1162. #define MAYBE_GetName_NullName GetName_NullName
  1163. #else
  1164. #define MAYBE_GetName_NullName DISABLED_GetName_NullName
  1165. #endif
  1166. // GetName for Device with no name.
  1167. TEST_F(BluetoothTest, MAYBE_GetName_NullName) {
  1168. if (!PlatformSupportsLowEnergy()) {
  1169. LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test.";
  1170. return;
  1171. }
  1172. InitWithFakeAdapter();
  1173. // StartLowEnergyDiscoverySession is not yet implemented on ChromeOS|bluez,
  1174. // and is non trivial to implement. On ChromeOS, it is not essential for
  1175. // this test to operate, and so it is simply skipped. Android at least
  1176. // does require this step.
  1177. #if !BUILDFLAG(IS_CHROMEOS)
  1178. StartLowEnergyDiscoverySession();
  1179. #endif // !BUILDFLAG(IS_CHROMEOS)
  1180. BluetoothDevice* device = SimulateLowEnergyDevice(5);
  1181. EXPECT_FALSE(device->GetName());
  1182. // The check below is not currently working on Android and Mac because the
  1183. // GetAppearance() method is not implemented on those platforms.
  1184. // TODO(https://crbug.com/588083): Enable the check below when GetAppearance()
  1185. // is implemented for Android and Mac.
  1186. #if !BUILDFLAG(IS_ANDROID) && !BUILDFLAG(IS_MAC)
  1187. EXPECT_EQ(device->GetNameForDisplay(),
  1188. u"Unknown or Unsupported Device (01:00:00:90:1E:BE)");
  1189. #endif
  1190. }
  1191. #if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_MAC)
  1192. #define MAYBE_CreateGattConnection CreateGattConnection
  1193. #else
  1194. #define MAYBE_CreateGattConnection DISABLED_CreateGattConnection
  1195. #endif
  1196. // Basic CreateGattConnection test.
  1197. #if BUILDFLAG(IS_WIN)
  1198. TEST_P(BluetoothTestWinrtOnly, CreateGattConnection) {
  1199. #else
  1200. TEST_F(BluetoothTest, MAYBE_CreateGattConnection) {
  1201. #endif
  1202. if (!PlatformSupportsLowEnergy()) {
  1203. LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test.";
  1204. return;
  1205. }
  1206. InitWithFakeAdapter();
  1207. StartLowEnergyDiscoverySession();
  1208. BluetoothDevice* device = SimulateLowEnergyDevice(3);
  1209. ResetEventCounts();
  1210. ASSERT_TRUE(ConnectGatt(device));
  1211. ASSERT_EQ(1u, gatt_connections_.size());
  1212. EXPECT_TRUE(device->IsGattConnected());
  1213. EXPECT_TRUE(gatt_connections_[0]->IsConnected());
  1214. }
  1215. #if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_MAC)
  1216. #define MAYBE_DisconnectionNotifiesDeviceChanged \
  1217. DisconnectionNotifiesDeviceChanged
  1218. #else
  1219. #define MAYBE_DisconnectionNotifiesDeviceChanged \
  1220. DISABLED_DisconnectionNotifiesDeviceChanged
  1221. #endif
  1222. #if BUILDFLAG(IS_WIN)
  1223. TEST_P(BluetoothTestWinrtOnly, DisconnectionNotifiesDeviceChanged) {
  1224. #else
  1225. TEST_F(BluetoothTest, MAYBE_DisconnectionNotifiesDeviceChanged) {
  1226. #endif
  1227. if (!PlatformSupportsLowEnergy()) {
  1228. LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test.";
  1229. return;
  1230. }
  1231. InitWithFakeAdapter();
  1232. TestBluetoothAdapterObserver observer(adapter_);
  1233. StartLowEnergyDiscoverySession();
  1234. BluetoothDevice* device = SimulateLowEnergyDevice(3);
  1235. ASSERT_TRUE(ConnectGatt(device));
  1236. EXPECT_EQ(1, observer.device_changed_count());
  1237. EXPECT_TRUE(device->IsConnected());
  1238. EXPECT_TRUE(device->IsGattConnected());
  1239. SimulateDeviceBreaksConnection(device);
  1240. base::RunLoop().RunUntilIdle();
  1241. EXPECT_EQ(2, observer.device_changed_count());
  1242. EXPECT_FALSE(device->IsConnected());
  1243. EXPECT_FALSE(device->IsGattConnected());
  1244. }
  1245. #if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_MAC)
  1246. #define MAYBE_BluetoothGattConnection BluetoothGattConnection
  1247. #else
  1248. #define MAYBE_BluetoothGattConnection DISABLED_BluetoothGattConnection
  1249. #endif
  1250. // Creates BluetoothGattConnection instances and tests that the interface
  1251. // functions even when some Disconnect and the BluetoothDevice is destroyed.
  1252. #if BUILDFLAG(IS_WIN)
  1253. TEST_P(BluetoothTestWinrtOnly, BluetoothGattConnection) {
  1254. #else
  1255. TEST_F(BluetoothTest, MAYBE_BluetoothGattConnection) {
  1256. #endif
  1257. if (!PlatformSupportsLowEnergy()) {
  1258. LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test.";
  1259. return;
  1260. }
  1261. InitWithFakeAdapter();
  1262. StartLowEnergyDiscoverySession();
  1263. BluetoothDevice* device = SimulateLowEnergyDevice(3);
  1264. std::string device_address = device->GetAddress();
  1265. // CreateGattConnection
  1266. ResetEventCounts();
  1267. ASSERT_TRUE(ConnectGatt(device));
  1268. ASSERT_EQ(1u, gatt_connections_.size());
  1269. EXPECT_TRUE(device->IsGattConnected());
  1270. EXPECT_TRUE(gatt_connections_[0]->IsConnected());
  1271. // Connect again once already connected.
  1272. ResetEventCounts();
  1273. ASSERT_TRUE(ConnectGatt(device));
  1274. ASSERT_TRUE(ConnectGatt(device));
  1275. EXPECT_EQ(0, gatt_connection_attempts_);
  1276. ASSERT_EQ(3u, gatt_connections_.size());
  1277. // Test GetDeviceAddress
  1278. EXPECT_EQ(device_address, gatt_connections_[0]->GetDeviceAddress());
  1279. // Test IsConnected
  1280. EXPECT_TRUE(gatt_connections_[0]->IsConnected());
  1281. EXPECT_TRUE(gatt_connections_[1]->IsConnected());
  1282. EXPECT_TRUE(gatt_connections_[2]->IsConnected());
  1283. // Disconnect & Delete connection objects. Device stays connected.
  1284. gatt_connections_[0]->Disconnect(); // Disconnect first.
  1285. gatt_connections_.pop_back(); // Delete last.
  1286. EXPECT_FALSE(gatt_connections_[0]->IsConnected());
  1287. EXPECT_TRUE(gatt_connections_[1]->IsConnected());
  1288. EXPECT_TRUE(device->IsGattConnected());
  1289. EXPECT_EQ(0, gatt_disconnection_attempts_);
  1290. // Delete device, connection objects should all be disconnected.
  1291. gatt_disconnection_attempts_ = 0;
  1292. DeleteDevice(device);
  1293. EXPECT_EQ(1, gatt_disconnection_attempts_);
  1294. EXPECT_FALSE(gatt_connections_[0]->IsConnected());
  1295. EXPECT_FALSE(gatt_connections_[1]->IsConnected());
  1296. // Test GetDeviceAddress after device deleted.
  1297. EXPECT_EQ(device_address, gatt_connections_[0]->GetDeviceAddress());
  1298. EXPECT_EQ(device_address, gatt_connections_[1]->GetDeviceAddress());
  1299. }
  1300. #if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_MAC)
  1301. #define MAYBE_BluetoothGattConnection_ConnectWithMultipleOSConnections \
  1302. BluetoothGattConnection_ConnectWithMultipleOSConnections
  1303. #else
  1304. #define MAYBE_BluetoothGattConnection_ConnectWithMultipleOSConnections \
  1305. DISABLED_BluetoothGattConnection_ConnectWithMultipleOSConnections
  1306. #endif
  1307. // Calls CreateGattConnection then simulates multiple connections from platform.
  1308. TEST_F(BluetoothTest,
  1309. MAYBE_BluetoothGattConnection_ConnectWithMultipleOSConnections) {
  1310. if (!PlatformSupportsLowEnergy()) {
  1311. LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test.";
  1312. return;
  1313. }
  1314. InitWithFakeAdapter();
  1315. TestBluetoothAdapterObserver observer(adapter_);
  1316. StartLowEnergyDiscoverySession();
  1317. BluetoothDevice* device = SimulateLowEnergyDevice(3);
  1318. // CreateGattConnection, & multiple connections from platform only invoke
  1319. // callbacks once:
  1320. ResetEventCounts();
  1321. ASSERT_TRUE(
  1322. ConnectGatt(device, /*service_uuid=*/absl::nullopt,
  1323. base::BindLambdaForTesting([this](BluetoothDevice* device) {
  1324. SimulateGattConnection(device);
  1325. SimulateGattConnection(device);
  1326. })));
  1327. EXPECT_EQ(1, gatt_discovery_attempts_);
  1328. EXPECT_EQ(1, observer.device_changed_count());
  1329. EXPECT_EQ(1, gatt_connection_attempts_);
  1330. EXPECT_TRUE(gatt_connections_[0]->IsConnected());
  1331. // Become disconnected:
  1332. SimulateGattDisconnection(device);
  1333. base::RunLoop().RunUntilIdle();
  1334. EXPECT_FALSE(gatt_connections_[0]->IsConnected());
  1335. }
  1336. #if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_MAC)
  1337. #define MAYBE_BluetoothGattConnection_AlreadyConnected \
  1338. BluetoothGattConnection_AlreadyConnected
  1339. #else
  1340. #define MAYBE_BluetoothGattConnection_AlreadyConnected \
  1341. DISABLED_BluetoothGattConnection_AlreadyConnected
  1342. #endif
  1343. // Calls CreateGattConnection after already connected.
  1344. #if BUILDFLAG(IS_WIN)
  1345. TEST_P(BluetoothTestWinrtOnly, BluetoothGattConnection_AlreadyConnected) {
  1346. #else
  1347. TEST_F(BluetoothTest, MAYBE_BluetoothGattConnection_AlreadyConnected) {
  1348. #endif
  1349. if (!PlatformSupportsLowEnergy()) {
  1350. LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test.";
  1351. return;
  1352. }
  1353. InitWithFakeAdapter();
  1354. StartLowEnergyDiscoverySession();
  1355. BluetoothDevice* device = SimulateLowEnergyDevice(3);
  1356. // Be already connected:
  1357. ASSERT_TRUE(ConnectGatt(device));
  1358. EXPECT_TRUE(gatt_connections_[0]->IsConnected());
  1359. // Then CreateGattConnection:
  1360. ResetEventCounts();
  1361. ASSERT_TRUE(ConnectGatt(device));
  1362. EXPECT_EQ(0, gatt_connection_attempts_);
  1363. EXPECT_TRUE(gatt_connections_[1]->IsConnected());
  1364. }
  1365. #if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_MAC)
  1366. #define MAYBE_BluetoothGattConnection_NewConnectionLeavesPreviousDisconnected \
  1367. BluetoothGattConnection_NewConnectionLeavesPreviousDisconnected
  1368. #else
  1369. #define MAYBE_BluetoothGattConnection_NewConnectionLeavesPreviousDisconnected \
  1370. DISABLED_BluetoothGattConnection_NewConnectionLeavesPreviousDisconnected
  1371. #endif
  1372. // Creates BluetoothGattConnection after one exists that has disconnected.
  1373. #if BUILDFLAG(IS_WIN)
  1374. TEST_P(BluetoothTestWinrtOnly,
  1375. BluetoothGattConnection_NewConnectionLeavesPreviousDisconnected) {
  1376. #else
  1377. TEST_F(BluetoothTest,
  1378. MAYBE_BluetoothGattConnection_NewConnectionLeavesPreviousDisconnected) {
  1379. #endif
  1380. if (!PlatformSupportsLowEnergy()) {
  1381. LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test.";
  1382. return;
  1383. }
  1384. InitWithFakeAdapter();
  1385. StartLowEnergyDiscoverySession();
  1386. BluetoothDevice* device = SimulateLowEnergyDevice(3);
  1387. // Create connection:
  1388. ASSERT_TRUE(ConnectGatt(device));
  1389. // Disconnect connection:
  1390. gatt_connections_[0]->Disconnect();
  1391. SimulateGattDisconnection(device);
  1392. base::RunLoop().RunUntilIdle();
  1393. // Create 2nd connection:
  1394. ASSERT_TRUE(ConnectGatt(device));
  1395. EXPECT_FALSE(gatt_connections_[0]->IsConnected())
  1396. << "The disconnected connection shouldn't become connected when another "
  1397. "connection is created.";
  1398. EXPECT_TRUE(gatt_connections_[1]->IsConnected());
  1399. }
  1400. #if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_MAC)
  1401. #define MAYBE_BluetoothGattConnection_DisconnectWhenObjectsDestroyed \
  1402. BluetoothGattConnection_DisconnectWhenObjectsDestroyed
  1403. #else
  1404. #define MAYBE_BluetoothGattConnection_DisconnectWhenObjectsDestroyed \
  1405. DISABLED_BluetoothGattConnection_DisconnectWhenObjectsDestroyed
  1406. #endif
  1407. // Deletes BluetoothGattConnection causing disconnection.
  1408. #if BUILDFLAG(IS_WIN)
  1409. TEST_P(BluetoothTestWinrtOnly,
  1410. BluetoothGattConnection_DisconnectWhenObjectsDestroyed) {
  1411. #else
  1412. TEST_F(BluetoothTest,
  1413. MAYBE_BluetoothGattConnection_DisconnectWhenObjectsDestroyed) {
  1414. #endif
  1415. if (!PlatformSupportsLowEnergy()) {
  1416. LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test.";
  1417. return;
  1418. }
  1419. InitWithFakeAdapter();
  1420. StartLowEnergyDiscoverySession();
  1421. BluetoothDevice* device = SimulateLowEnergyDevice(3);
  1422. // Create multiple connections and simulate connection complete:
  1423. ASSERT_TRUE(
  1424. ConnectGatt(device,
  1425. /*service_uuid=*/absl::nullopt,
  1426. base::BindLambdaForTesting([this](BluetoothDevice* device) {
  1427. ConnectGatt(device);
  1428. })));
  1429. EXPECT_EQ(2u, gatt_connections_.size());
  1430. // Delete all CreateGattConnection objects, observe disconnection:
  1431. ResetEventCounts();
  1432. gatt_connections_.clear();
  1433. EXPECT_EQ(1, gatt_disconnection_attempts_);
  1434. }
  1435. #if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_MAC)
  1436. #define MAYBE_BluetoothGattConnection_DisconnectInProgress \
  1437. BluetoothGattConnection_DisconnectInProgress
  1438. #else
  1439. #define MAYBE_BluetoothGattConnection_DisconnectInProgress \
  1440. DISABLED_BluetoothGattConnection_DisconnectInProgress
  1441. #endif
  1442. // Starts process of disconnecting and then calls BluetoothGattConnection.
  1443. #if BUILDFLAG(IS_WIN)
  1444. TEST_P(BluetoothTestWinrtOnly, BluetoothGattConnection_DisconnectInProgress) {
  1445. #else
  1446. TEST_F(BluetoothTest, MAYBE_BluetoothGattConnection_DisconnectInProgress) {
  1447. #endif
  1448. if (!PlatformSupportsLowEnergy()) {
  1449. LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test.";
  1450. return;
  1451. }
  1452. InitWithFakeAdapter();
  1453. StartLowEnergyDiscoverySession();
  1454. BluetoothDevice* device = SimulateLowEnergyDevice(3);
  1455. // Create multiple connections and simulate connection complete:
  1456. ASSERT_TRUE(
  1457. ConnectGatt(device,
  1458. /*service_uuid=*/absl::nullopt,
  1459. base::BindLambdaForTesting([this](BluetoothDevice* device) {
  1460. ConnectGatt(device);
  1461. })));
  1462. EXPECT_EQ(2u, gatt_connections_.size());
  1463. // Disconnect all CreateGattConnection objects & create a new connection.
  1464. // But, don't yet simulate the device disconnecting:
  1465. ResetEventCounts();
  1466. for (const auto& connection : gatt_connections_)
  1467. connection->Disconnect();
  1468. EXPECT_EQ(1, gatt_disconnection_attempts_);
  1469. // Create a connection.
  1470. ASSERT_TRUE(ConnectGatt(device));
  1471. EXPECT_EQ(0, gatt_connection_attempts_); // No connection attempt.
  1472. EXPECT_FALSE(gatt_connections_.front()->IsConnected());
  1473. EXPECT_TRUE(gatt_connections_.back()->IsConnected());
  1474. // Actually disconnect:
  1475. SimulateGattDisconnection(device);
  1476. base::RunLoop().RunUntilIdle();
  1477. for (const auto& connection : gatt_connections_)
  1478. EXPECT_FALSE(connection->IsConnected());
  1479. }
  1480. #if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_MAC)
  1481. #define MAYBE_BluetoothGattConnection_SimulateDisconnect \
  1482. BluetoothGattConnection_SimulateDisconnect
  1483. #else
  1484. #define MAYBE_BluetoothGattConnection_SimulateDisconnect \
  1485. DISABLED_BluetoothGattConnection_SimulateDisconnect
  1486. #endif
  1487. // Calls CreateGattConnection but receives notice that the device disconnected
  1488. // before it ever connects.
  1489. #if BUILDFLAG(IS_WIN)
  1490. TEST_P(BluetoothTestWinrtOnly, BluetoothGattConnection_SimulateDisconnect) {
  1491. #else
  1492. TEST_F(BluetoothTest, MAYBE_BluetoothGattConnection_SimulateDisconnect) {
  1493. #endif
  1494. if (!PlatformSupportsLowEnergy()) {
  1495. LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test.";
  1496. return;
  1497. }
  1498. InitWithFakeAdapter();
  1499. StartLowEnergyDiscoverySession();
  1500. BluetoothDevice* device = SimulateLowEnergyDevice(3);
  1501. ResetEventCounts();
  1502. EXPECT_FALSE(
  1503. ConnectGatt(device,
  1504. /*service_uuid=*/absl::nullopt,
  1505. base::BindLambdaForTesting([this](BluetoothDevice* device) {
  1506. SimulateGattDisconnection(device);
  1507. })));
  1508. EXPECT_EQ(BluetoothDevice::ERROR_FAILED, last_connect_error_code_);
  1509. for (const auto& connection : gatt_connections_)
  1510. EXPECT_FALSE(connection->IsConnected());
  1511. }
  1512. #if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_MAC)
  1513. #define MAYBE_BluetoothGattConnection_DisconnectGatt_SimulateConnect \
  1514. BluetoothGattConnection_DisconnectGatt_SimulateConnect
  1515. #else
  1516. #define MAYBE_BluetoothGattConnection_DisconnectGatt_SimulateConnect \
  1517. DISABLED_BluetoothGattConnection_DisconnectGatt_SimulateConnect
  1518. #endif
  1519. // Calls CreateGattConnection & DisconnectGatt, then simulates connection.
  1520. #if BUILDFLAG(IS_WIN)
  1521. TEST_P(BluetoothTestWinrtOnly,
  1522. BluetoothGattConnection_DisconnectGatt_SimulateConnect) {
  1523. #else
  1524. TEST_F(BluetoothTest,
  1525. MAYBE_BluetoothGattConnection_DisconnectGatt_SimulateConnect) {
  1526. #endif
  1527. if (!PlatformSupportsLowEnergy()) {
  1528. LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test.";
  1529. return;
  1530. }
  1531. InitWithFakeAdapter();
  1532. StartLowEnergyDiscoverySession();
  1533. BluetoothDevice* device = SimulateLowEnergyDevice(3);
  1534. ResetEventCounts();
  1535. EXPECT_TRUE(
  1536. ConnectGatt(device,
  1537. /*service_uuid=*/absl::nullopt,
  1538. base::BindLambdaForTesting([this](BluetoothDevice* device) {
  1539. #if !BUILDFLAG(IS_WIN)
  1540. // On Windows there is currently no way to cancel a
  1541. // pending GATT connection from the caller's side.
  1542. device->DisconnectGatt();
  1543. #endif
  1544. SimulateGattConnection(device);
  1545. })));
  1546. #if !BUILDFLAG(IS_WIN)
  1547. EXPECT_EQ(1, gatt_disconnection_attempts_);
  1548. #endif
  1549. EXPECT_EQ(1, gatt_connection_attempts_);
  1550. EXPECT_TRUE(gatt_connections_.back()->IsConnected());
  1551. ResetEventCounts();
  1552. SimulateGattDisconnection(device);
  1553. base::RunLoop().RunUntilIdle();
  1554. }
  1555. #if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_MAC)
  1556. #define MAYBE_BluetoothGattConnection_DisconnectGatt_SimulateDisconnect \
  1557. BluetoothGattConnection_DisconnectGatt_SimulateDisconnect
  1558. #else
  1559. #define MAYBE_BluetoothGattConnection_DisconnectGatt_SimulateDisconnect \
  1560. DISABLED_BluetoothGattConnection_DisconnectGatt_SimulateDisconnect
  1561. #endif
  1562. // Calls CreateGattConnection & DisconnectGatt, then simulates disconnection.
  1563. #if BUILDFLAG(IS_WIN)
  1564. TEST_P(BluetoothTestWinrtOnly,
  1565. BluetoothGattConnection_DisconnectGatt_SimulateDisconnect) {
  1566. #else
  1567. TEST_F(BluetoothTest,
  1568. MAYBE_BluetoothGattConnection_DisconnectGatt_SimulateDisconnect) {
  1569. #endif
  1570. if (!PlatformSupportsLowEnergy()) {
  1571. LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test.";
  1572. return;
  1573. }
  1574. InitWithFakeAdapter();
  1575. StartLowEnergyDiscoverySession();
  1576. BluetoothDevice* device = SimulateLowEnergyDevice(3);
  1577. ResetEventCounts();
  1578. ASSERT_FALSE(
  1579. ConnectGatt(device,
  1580. /*service_uuid=*/absl::nullopt,
  1581. base::BindLambdaForTesting([this](BluetoothDevice* device) {
  1582. device->DisconnectGatt();
  1583. SimulateGattDisconnection(device);
  1584. })));
  1585. EXPECT_EQ(1, gatt_connection_attempts_);
  1586. EXPECT_EQ(
  1587. #if BUILDFLAG(IS_ANDROID)
  1588. // Closing a GATT connection also disconnects on Android.
  1589. // TODO(crbug.com/1045648): this value probably shouldn't be different on
  1590. // Android.
  1591. 2,
  1592. #else
  1593. 1,
  1594. #endif
  1595. gatt_disconnection_attempts_);
  1596. EXPECT_EQ(BluetoothDevice::ERROR_FAILED, last_connect_error_code_);
  1597. for (const auto& connection : gatt_connections_)
  1598. EXPECT_FALSE(connection->IsConnected());
  1599. }
  1600. #if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_MAC)
  1601. #define MAYBE_BluetoothGattConnection_DisconnectGatt_Cleanup \
  1602. BluetoothGattConnection_DisconnectGatt_Cleanup
  1603. #else
  1604. #define MAYBE_BluetoothGattConnection_DisconnectGatt_Cleanup \
  1605. DISABLED_BluetoothGattConnection_DisconnectGatt_Cleanup
  1606. #endif
  1607. // Calls CreateGattConnection & DisconnectGatt, then checks that gatt services
  1608. // have been cleaned up.
  1609. #if BUILDFLAG(IS_WIN)
  1610. TEST_P(BluetoothTestWinrtOnly, BluetoothGattConnection_DisconnectGatt_Cleanup) {
  1611. #else
  1612. TEST_F(BluetoothTest, MAYBE_BluetoothGattConnection_DisconnectGatt_Cleanup) {
  1613. #endif
  1614. if (!PlatformSupportsLowEnergy()) {
  1615. LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test.";
  1616. return;
  1617. }
  1618. InitWithFakeAdapter();
  1619. StartLowEnergyDiscoverySession();
  1620. BluetoothDevice* device = SimulateLowEnergyDevice(3);
  1621. EXPECT_FALSE(device->IsConnected());
  1622. // Connect to the device
  1623. ResetEventCounts();
  1624. TestBluetoothAdapterObserver observer(adapter_);
  1625. ASSERT_TRUE(ConnectGatt(device));
  1626. EXPECT_TRUE(device->IsConnected());
  1627. // Discover services
  1628. SimulateGattServicesDiscovered(
  1629. device,
  1630. std::vector<std::string>({kTestUUIDGenericAccess, kTestUUIDHeartRate}));
  1631. base::RunLoop().RunUntilIdle();
  1632. EXPECT_TRUE(device->IsGattServicesDiscoveryComplete());
  1633. EXPECT_EQ(2u, device->GetGattServices().size());
  1634. EXPECT_EQ(1, observer.gatt_services_discovered_count());
  1635. // Disconnect from the device
  1636. device->DisconnectGatt();
  1637. SimulateGattDisconnection(device);
  1638. base::RunLoop().RunUntilIdle();
  1639. EXPECT_FALSE(device->IsConnected());
  1640. EXPECT_FALSE(device->IsGattServicesDiscoveryComplete());
  1641. EXPECT_EQ(0u, device->GetGattServices().size());
  1642. // Verify that the device can be connected to again
  1643. ASSERT_TRUE(ConnectGatt(device));
  1644. EXPECT_TRUE(device->IsConnected());
  1645. // Verify that service discovery can be done again
  1646. SimulateGattServicesDiscovered(
  1647. device, std::vector<std::string>({kTestUUIDGenericAttribute}));
  1648. base::RunLoop().RunUntilIdle();
  1649. EXPECT_TRUE(device->IsGattServicesDiscoveryComplete());
  1650. EXPECT_EQ(1u, device->GetGattServices().size());
  1651. EXPECT_EQ(2, observer.gatt_services_discovered_count());
  1652. }
  1653. #if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_MAC)
  1654. #define MAYBE_BluetoothGattConnection_ErrorAfterConnection \
  1655. BluetoothGattConnection_ErrorAfterConnection
  1656. #else
  1657. #define MAYBE_BluetoothGattConnection_ErrorAfterConnection \
  1658. DISABLED_BluetoothGattConnection_ErrorAfterConnection
  1659. #endif
  1660. // Calls CreateGattConnection, but simulate errors connecting. Also, verifies
  1661. // multiple errors should only invoke callbacks once.
  1662. #if BUILDFLAG(IS_WIN)
  1663. TEST_P(BluetoothTestWinrtOnly, BluetoothGattConnection_ErrorAfterConnection) {
  1664. #else
  1665. TEST_F(BluetoothTest, MAYBE_BluetoothGattConnection_ErrorAfterConnection) {
  1666. #endif
  1667. if (!PlatformSupportsLowEnergy()) {
  1668. LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test.";
  1669. return;
  1670. }
  1671. InitWithFakeAdapter();
  1672. StartLowEnergyDiscoverySession();
  1673. BluetoothDevice* device = SimulateLowEnergyDevice(3);
  1674. ResetEventCounts();
  1675. EXPECT_FALSE(ConnectGatt(
  1676. device,
  1677. /*service_uuid=*/absl::nullopt,
  1678. base::BindLambdaForTesting([this](BluetoothDevice* device) {
  1679. SimulateGattConnectionError(device, BluetoothDevice::ERROR_AUTH_FAILED);
  1680. SimulateGattConnectionError(device, BluetoothDevice::ERROR_FAILED);
  1681. })));
  1682. EXPECT_EQ(1, gatt_connection_attempts_);
  1683. #if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_WIN)
  1684. // TODO(crbug.com/578191): Change to ERROR_AUTH_FAILED. We should be getting a
  1685. // callback only with the first error, but our android framework doesn't yet
  1686. // support sending different errors.
  1687. // On Windows, any GattConnectionError will result in ERROR_FAILED.
  1688. EXPECT_EQ(BluetoothDevice::ERROR_FAILED, last_connect_error_code_);
  1689. #else
  1690. EXPECT_EQ(BluetoothDevice::ERROR_AUTH_FAILED, last_connect_error_code_);
  1691. #endif
  1692. for (const auto& connection : gatt_connections_)
  1693. EXPECT_FALSE(connection->IsConnected());
  1694. }
  1695. #if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC)
  1696. #define MAYBE_GattServices_ObserversCalls GattServices_ObserversCalls
  1697. #else
  1698. #define MAYBE_GattServices_ObserversCalls DISABLED_GattServices_ObserversCalls
  1699. #endif
  1700. #if BUILDFLAG(IS_WIN)
  1701. TEST_P(BluetoothTestWinrtOnly, GattServices_ObserversCalls) {
  1702. #else
  1703. TEST_F(BluetoothTest, MAYBE_GattServices_ObserversCalls) {
  1704. #endif
  1705. if (!PlatformSupportsLowEnergy()) {
  1706. LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test.";
  1707. return;
  1708. }
  1709. InitWithFakeAdapter();
  1710. StartLowEnergyDiscoverySession();
  1711. BluetoothDevice* device = SimulateLowEnergyDevice(3);
  1712. TestBluetoothAdapterObserver observer(adapter_);
  1713. ResetEventCounts();
  1714. ASSERT_TRUE(ConnectGatt(device));
  1715. EXPECT_EQ(1, gatt_discovery_attempts_);
  1716. SimulateGattServicesDiscovered(
  1717. device,
  1718. std::vector<std::string>({kTestUUIDGenericAccess, kTestUUIDHeartRate}));
  1719. base::RunLoop().RunUntilIdle();
  1720. EXPECT_EQ(1, observer.gatt_services_discovered_count());
  1721. }
  1722. #if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC)
  1723. #define MAYBE_GattServicesDiscovered_Success GattServicesDiscovered_Success
  1724. #else
  1725. #define MAYBE_GattServicesDiscovered_Success \
  1726. DISABLED_GattServicesDiscovered_Success
  1727. #endif
  1728. #if BUILDFLAG(IS_WIN)
  1729. TEST_P(BluetoothTestWinrtOnly, GattServicesDiscovered_Success) {
  1730. #else
  1731. TEST_F(BluetoothTest, MAYBE_GattServicesDiscovered_Success) {
  1732. #endif
  1733. if (!PlatformSupportsLowEnergy()) {
  1734. LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test.";
  1735. return;
  1736. }
  1737. InitWithFakeAdapter();
  1738. StartLowEnergyDiscoverySession();
  1739. TestBluetoothAdapterObserver observer(adapter_);
  1740. BluetoothDevice* device = SimulateLowEnergyDevice(3);
  1741. ResetEventCounts();
  1742. ASSERT_TRUE(ConnectGatt(device));
  1743. EXPECT_EQ(1, gatt_discovery_attempts_);
  1744. EXPECT_EQ(0, observer.gatt_services_discovered_count());
  1745. SimulateGattServicesDiscovered(
  1746. device,
  1747. std::vector<std::string>({kTestUUIDGenericAccess, kTestUUIDHeartRate}));
  1748. base::RunLoop().RunUntilIdle();
  1749. EXPECT_TRUE(device->IsGattServicesDiscoveryComplete());
  1750. EXPECT_EQ(1, observer.gatt_services_discovered_count());
  1751. EXPECT_EQ(2u, device->GetGattServices().size());
  1752. }
  1753. #if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_WIN)
  1754. #define MAYBE_GattServicesDiscovered_AfterDeleted \
  1755. GattServicesDiscovered_AfterDeleted
  1756. #else
  1757. #define MAYBE_GattServicesDiscovered_AfterDeleted \
  1758. DISABLED_GattServicesDiscovered_AfterDeleted
  1759. #endif
  1760. // macOS: Not applicable: This can never happen because when
  1761. // the device gets destroyed the CBPeripheralDelegate is also destroyed
  1762. // and no more events are dispatched.
  1763. TEST_F(BluetoothTest, MAYBE_GattServicesDiscovered_AfterDeleted) {
  1764. // Tests that we don't crash if services are discovered after
  1765. // the device object is deleted.
  1766. if (!PlatformSupportsLowEnergy()) {
  1767. LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test.";
  1768. return;
  1769. }
  1770. InitWithFakeAdapter();
  1771. StartLowEnergyDiscoverySession();
  1772. BluetoothDevice* device = SimulateLowEnergyDevice(3);
  1773. ResetEventCounts();
  1774. ASSERT_TRUE(ConnectGatt(device));
  1775. EXPECT_EQ(1, gatt_discovery_attempts_);
  1776. RememberDeviceForSubsequentAction(device);
  1777. DeleteDevice(device);
  1778. SimulateGattServicesDiscovered(
  1779. nullptr /* use remembered device */,
  1780. std::vector<std::string>({kTestUUIDGenericAccess, kTestUUIDHeartRate}));
  1781. }
  1782. #if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_WIN)
  1783. #define MAYBE_GattServicesDiscoveredError_AfterDeleted \
  1784. GattServicesDiscoveredError_AfterDeleted
  1785. #else
  1786. #define MAYBE_GattServicesDiscoveredError_AfterDeleted \
  1787. DISABLED_GattServicesDiscoveredError_AfterDeleted
  1788. #endif
  1789. // macOS: Not applicable: This can never happen because when
  1790. // the device gets destroyed the CBPeripheralDelegate is also destroyed
  1791. // and no more events are dispatched.
  1792. TEST_F(BluetoothTest, MAYBE_GattServicesDiscoveredError_AfterDeleted) {
  1793. // Tests that we don't crash if there was an error discoverying services
  1794. // after the device object is deleted.
  1795. if (!PlatformSupportsLowEnergy()) {
  1796. LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test.";
  1797. return;
  1798. }
  1799. InitWithFakeAdapter();
  1800. StartLowEnergyDiscoverySession();
  1801. BluetoothDevice* device = SimulateLowEnergyDevice(3);
  1802. ResetEventCounts();
  1803. ASSERT_TRUE(ConnectGatt(device));
  1804. EXPECT_EQ(1, gatt_discovery_attempts_);
  1805. RememberDeviceForSubsequentAction(device);
  1806. DeleteDevice(device);
  1807. SimulateGattServicesDiscoveryError(nullptr /* use remembered device */);
  1808. base::RunLoop().RunUntilIdle();
  1809. }
  1810. #if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_MAC)
  1811. #define MAYBE_GattServicesDiscovered_AfterDisconnection \
  1812. GattServicesDiscovered_AfterDisconnection
  1813. #else
  1814. #define MAYBE_GattServicesDiscovered_AfterDisconnection \
  1815. DISABLED_GattServicesDiscovered_AfterDisconnection
  1816. #endif
  1817. // Classic Windows does not support disconnection.
  1818. #if BUILDFLAG(IS_WIN)
  1819. TEST_P(BluetoothTestWinrtOnly, GattServicesDiscovered_AfterDisconnection) {
  1820. #else
  1821. TEST_F(BluetoothTest, MAYBE_GattServicesDiscovered_AfterDisconnection) {
  1822. #endif
  1823. // Tests that we don't crash if there was an error discovering services after
  1824. // the device disconnects.
  1825. if (!PlatformSupportsLowEnergy()) {
  1826. LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test.";
  1827. return;
  1828. }
  1829. InitWithFakeAdapter();
  1830. StartLowEnergyDiscoverySession();
  1831. BluetoothDevice* device = SimulateLowEnergyDevice(3);
  1832. ResetEventCounts();
  1833. ASSERT_TRUE(ConnectGatt(device));
  1834. EXPECT_EQ(1, gatt_discovery_attempts_);
  1835. SimulateDeviceBreaksConnection(device);
  1836. base::RunLoop().RunUntilIdle();
  1837. SimulateGattServicesDiscovered(
  1838. device,
  1839. std::vector<std::string>({kTestUUIDGenericAccess, kTestUUIDHeartRate}));
  1840. base::RunLoop().RunUntilIdle();
  1841. EXPECT_FALSE(device->IsGattServicesDiscoveryComplete());
  1842. EXPECT_EQ(0u, device->GetGattServices().size());
  1843. }
  1844. #if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_MAC)
  1845. #define MAYBE_GattServicesDiscoveredError_AfterDisconnection \
  1846. GattServicesDiscoveredError_AfterDisconnection
  1847. #else
  1848. #define MAYBE_GattServicesDiscoveredError_AfterDisconnection \
  1849. DISABLED_GattServicesDiscoveredError_AfterDisconnection
  1850. #endif
  1851. // Windows does not support disconnecting.
  1852. #if BUILDFLAG(IS_WIN)
  1853. TEST_P(BluetoothTestWinrtOnly, GattServicesDiscoveredError_AfterDisconnection) {
  1854. #else
  1855. TEST_F(BluetoothTest, MAYBE_GattServicesDiscoveredError_AfterDisconnection) {
  1856. #endif
  1857. // Tests that we don't crash if services are discovered after
  1858. // the device disconnects.
  1859. if (!PlatformSupportsLowEnergy()) {
  1860. LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test.";
  1861. return;
  1862. }
  1863. InitWithFakeAdapter();
  1864. StartLowEnergyDiscoverySession();
  1865. BluetoothDevice* device = SimulateLowEnergyDevice(3);
  1866. ResetEventCounts();
  1867. ASSERT_TRUE(ConnectGatt(device));
  1868. EXPECT_EQ(1, gatt_discovery_attempts_);
  1869. SimulateGattDisconnection(device);
  1870. base::RunLoop().RunUntilIdle();
  1871. SimulateGattServicesDiscoveryError(device);
  1872. base::RunLoop().RunUntilIdle();
  1873. EXPECT_FALSE(device->IsGattServicesDiscoveryComplete());
  1874. EXPECT_EQ(0u, device->GetGattServices().size());
  1875. }
  1876. #if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_MAC)
  1877. #define MAYBE_GetGattServices_and_GetGattService \
  1878. GetGattServices_and_GetGattService
  1879. #else
  1880. #define MAYBE_GetGattServices_and_GetGattService \
  1881. DISABLED_GetGattServices_and_GetGattService
  1882. #endif
  1883. #if BUILDFLAG(IS_WIN)
  1884. TEST_P(BluetoothTestWinrt, GetGattServices_and_GetGattService) {
  1885. #else
  1886. TEST_F(BluetoothTest, MAYBE_GetGattServices_and_GetGattService) {
  1887. #endif
  1888. if (!PlatformSupportsLowEnergy()) {
  1889. LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test.";
  1890. return;
  1891. }
  1892. InitWithFakeAdapter();
  1893. StartLowEnergyDiscoverySession();
  1894. BluetoothDevice* device = SimulateLowEnergyDevice(3);
  1895. ResetEventCounts();
  1896. ASSERT_TRUE(ConnectGatt(device));
  1897. EXPECT_EQ(1, gatt_discovery_attempts_);
  1898. // 2 duplicate UUIDs creating 2 instances.
  1899. SimulateGattServicesDiscovered(
  1900. device,
  1901. std::vector<std::string>(
  1902. {kTestUUIDGenericAccess, kTestUUIDHeartRate, kTestUUIDHeartRate}));
  1903. base::RunLoop().RunUntilIdle();
  1904. EXPECT_EQ(3u, device->GetGattServices().size());
  1905. // Test GetGattService:
  1906. std::string service_id1 = device->GetGattServices()[0]->GetIdentifier();
  1907. std::string service_id2 = device->GetGattServices()[1]->GetIdentifier();
  1908. std::string service_id3 = device->GetGattServices()[2]->GetIdentifier();
  1909. EXPECT_TRUE(device->GetGattService(service_id1));
  1910. EXPECT_TRUE(device->GetGattService(service_id2));
  1911. EXPECT_TRUE(device->GetGattService(service_id3));
  1912. }
  1913. #if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_MAC)
  1914. #define MAYBE_GetGattServices_FindNone GetGattServices_FindNone
  1915. #else
  1916. #define MAYBE_GetGattServices_FindNone DISABLED_GetGattServices_FindNone
  1917. #endif
  1918. #if BUILDFLAG(IS_WIN)
  1919. TEST_P(BluetoothTestWinrtOnly, GetGattServices_FindNone) {
  1920. #else
  1921. TEST_F(BluetoothTest, MAYBE_GetGattServices_FindNone) {
  1922. #endif
  1923. if (!PlatformSupportsLowEnergy()) {
  1924. LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test.";
  1925. return;
  1926. }
  1927. InitWithFakeAdapter();
  1928. StartLowEnergyDiscoverySession();
  1929. BluetoothDevice* device = SimulateLowEnergyDevice(3);
  1930. ResetEventCounts();
  1931. ASSERT_TRUE(ConnectGatt(device));
  1932. EXPECT_EQ(1, gatt_discovery_attempts_);
  1933. // Simulate an empty set of discovered services.
  1934. SimulateGattServicesDiscovered(device, {} /* uuids */);
  1935. base::RunLoop().RunUntilIdle();
  1936. EXPECT_EQ(0u, device->GetGattServices().size());
  1937. }
  1938. #if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_MAC)
  1939. #define MAYBE_GetGattServices_DiscoveryError GetGattServices_DiscoveryError
  1940. #else
  1941. #define MAYBE_GetGattServices_DiscoveryError \
  1942. DISABLED_GetGattServices_DiscoveryError
  1943. #endif
  1944. #if BUILDFLAG(IS_WIN)
  1945. TEST_P(BluetoothTestWinrtOnly, GetGattServices_DiscoveryError) {
  1946. #else
  1947. TEST_F(BluetoothTest, MAYBE_GetGattServices_DiscoveryError) {
  1948. #endif
  1949. if (!PlatformSupportsLowEnergy()) {
  1950. LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test.";
  1951. return;
  1952. }
  1953. InitWithFakeAdapter();
  1954. StartLowEnergyDiscoverySession();
  1955. BluetoothDevice* device = SimulateLowEnergyDevice(3);
  1956. ResetEventCounts();
  1957. ASSERT_TRUE(ConnectGatt(device));
  1958. EXPECT_EQ(1, gatt_discovery_attempts_);
  1959. SimulateGattServicesDiscoveryError(device);
  1960. base::RunLoop().RunUntilIdle();
  1961. EXPECT_EQ(0u, device->GetGattServices().size());
  1962. }
  1963. #if BUILDFLAG(IS_WIN)
  1964. TEST_P(BluetoothTestWinrtOnly, GattServicesDiscovered_SomeServicesBlocked) {
  1965. #else
  1966. TEST_F(BluetoothTest, DISABLED_GattServicesDiscovered_SomeServicesBlocked) {
  1967. #endif
  1968. if (!PlatformSupportsLowEnergy()) {
  1969. LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test.";
  1970. return;
  1971. }
  1972. InitWithFakeAdapter();
  1973. StartLowEnergyDiscoverySession();
  1974. TestBluetoothAdapterObserver observer(adapter_);
  1975. BluetoothDevice* device = SimulateLowEnergyDevice(3);
  1976. ResetEventCounts();
  1977. ASSERT_TRUE(ConnectGatt(device));
  1978. EXPECT_EQ(1, gatt_discovery_attempts_);
  1979. EXPECT_EQ(0, observer.gatt_services_discovered_count());
  1980. SimulateGattServicesDiscovered(
  1981. device,
  1982. /*uuids=*/{kTestUUIDGenericAccess, kTestUUIDHeartRate},
  1983. /*blocked_uuids=*/{kTestUUIDU2f});
  1984. base::RunLoop().RunUntilIdle();
  1985. EXPECT_TRUE(device->IsGattServicesDiscoveryComplete());
  1986. EXPECT_EQ(1, observer.gatt_services_discovered_count());
  1987. // Even though some services are blocked they should still appear in the list.
  1988. EXPECT_EQ(3u, device->GetGattServices().size());
  1989. }
  1990. #if BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_LINUX)
  1991. TEST_F(BluetoothTest, GetDeviceTransportType) {
  1992. if (!PlatformSupportsLowEnergy()) {
  1993. LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test.";
  1994. return;
  1995. }
  1996. InitWithFakeAdapter();
  1997. BluetoothDevice* device = SimulateLowEnergyDevice(1);
  1998. EXPECT_EQ(BLUETOOTH_TRANSPORT_LE, device->GetType());
  1999. #if !defined(USE_CAST_BLUETOOTH_ADAPTER)
  2000. BluetoothDevice* device2 = SimulateLowEnergyDevice(6);
  2001. EXPECT_EQ(BLUETOOTH_TRANSPORT_DUAL, device2->GetType());
  2002. BluetoothDevice* device3 = SimulateClassicDevice();
  2003. EXPECT_EQ(BLUETOOTH_TRANSPORT_CLASSIC, device3->GetType());
  2004. #endif // !defined(USE_CAST_BLUETOOTH_ADAPTER)
  2005. }
  2006. #endif // BUILDFLAG(IS_CHROMEOS) || BUILDFLAG(IS_LINUX)
  2007. #if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_MAC)
  2008. #define MAYBE_GetPrimaryServices GetPrimaryServices
  2009. #else
  2010. #define MAYBE_GetPrimaryServices DISABLED_GetPrimaryServices
  2011. #endif
  2012. #if BUILDFLAG(IS_WIN)
  2013. TEST_P(BluetoothTestWinrt, GetPrimaryServices) {
  2014. #else
  2015. TEST_F(BluetoothTest, MAYBE_GetPrimaryServices) {
  2016. #endif
  2017. if (!PlatformSupportsLowEnergy()) {
  2018. LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test.";
  2019. return;
  2020. }
  2021. InitWithFakeAdapter();
  2022. StartLowEnergyDiscoverySession();
  2023. BluetoothDevice* device = SimulateLowEnergyDevice(3);
  2024. EXPECT_FALSE(device->IsConnected());
  2025. // Connect to the device.
  2026. ResetEventCounts();
  2027. ASSERT_TRUE(ConnectGatt(device));
  2028. EXPECT_TRUE(device->IsGattConnected());
  2029. // Discover services: Two unique UUIDs, of which the second is duplicated.
  2030. SimulateGattServicesDiscovered(
  2031. device, {kTestUUIDGenericAccess, kTestUUIDHeartRate, kTestUUIDHeartRate});
  2032. base::RunLoop().RunUntilIdle();
  2033. EXPECT_TRUE(device->IsGattServicesDiscoveryComplete());
  2034. EXPECT_EQ(3u, device->GetPrimaryServices().size());
  2035. }
  2036. #if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_MAC)
  2037. #define MAYBE_GetPrimaryServicesByUUID GetPrimaryServicesByUUID
  2038. #else
  2039. #define MAYBE_GetPrimaryServicesByUUID DISABLED_GetPrimaryServicesByUUID
  2040. #endif
  2041. #if BUILDFLAG(IS_WIN)
  2042. TEST_P(BluetoothTestWinrt, GetPrimaryServicesByUUID) {
  2043. #else
  2044. TEST_F(BluetoothTest, MAYBE_GetPrimaryServicesByUUID) {
  2045. #endif
  2046. if (!PlatformSupportsLowEnergy()) {
  2047. LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test.";
  2048. return;
  2049. }
  2050. InitWithFakeAdapter();
  2051. StartLowEnergyDiscoverySession();
  2052. BluetoothDevice* device = SimulateLowEnergyDevice(3);
  2053. EXPECT_FALSE(device->IsConnected());
  2054. // Connect to the device.
  2055. ResetEventCounts();
  2056. ASSERT_TRUE(ConnectGatt(device));
  2057. EXPECT_TRUE(device->IsGattConnected());
  2058. // Discover services: Two unique UUIDs, of which the second is duplicated.
  2059. SimulateGattServicesDiscovered(
  2060. device, {kTestUUIDGenericAccess, kTestUUIDHeartRate, kTestUUIDHeartRate});
  2061. base::RunLoop().RunUntilIdle();
  2062. EXPECT_TRUE(device->IsGattServicesDiscoveryComplete());
  2063. {
  2064. const BluetoothUUID unique_service_uuid(kTestUUIDGenericAccess);
  2065. std::vector<BluetoothRemoteGattService*> services =
  2066. device->GetPrimaryServicesByUUID(unique_service_uuid);
  2067. EXPECT_EQ(1u, services.size());
  2068. EXPECT_EQ(unique_service_uuid, services[0]->GetUUID());
  2069. }
  2070. {
  2071. const BluetoothUUID duplicate_service_uuid(kTestUUIDHeartRate);
  2072. std::vector<BluetoothRemoteGattService*> services =
  2073. device->GetPrimaryServicesByUUID(duplicate_service_uuid);
  2074. EXPECT_EQ(2u, services.size());
  2075. EXPECT_EQ(duplicate_service_uuid, services[0]->GetUUID());
  2076. EXPECT_EQ(duplicate_service_uuid, services[1]->GetUUID());
  2077. EXPECT_TRUE(
  2078. device
  2079. ->GetPrimaryServicesByUUID(BluetoothUUID(kTestUUIDGenericAttribute))
  2080. .empty());
  2081. EXPECT_NE(services[0]->GetIdentifier(), services[1]->GetIdentifier());
  2082. }
  2083. }
  2084. #if BUILDFLAG(IS_WIN)
  2085. TEST_P(BluetoothTestWinrtOnly, GattConnectedNameChange) {
  2086. #else
  2087. // The SimulateGattNameChange() function is not yet available on other
  2088. // platforms.
  2089. TEST_F(BluetoothTest, DISABLED_GattConnectedNameChange) {
  2090. #endif
  2091. if (!PlatformSupportsLowEnergy()) {
  2092. LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test.";
  2093. return;
  2094. }
  2095. InitWithFakeAdapter();
  2096. StartLowEnergyDiscoverySession();
  2097. BluetoothDevice* device = SimulateLowEnergyDevice(3);
  2098. ASSERT_TRUE(ConnectGatt(device));
  2099. // GetName() returns a absl::optional<std:string> however some backends still
  2100. // return an empty string rather than nullopt when no name is available.
  2101. EXPECT_TRUE(!device->GetName() || device->GetName()->empty());
  2102. TestBluetoothAdapterObserver observer(adapter_);
  2103. SimulateGattNameChange(device, kTestDeviceName);
  2104. base::RunLoop().RunUntilIdle();
  2105. EXPECT_EQ(1, observer.device_changed_count());
  2106. EXPECT_EQ(base::UTF8ToUTF16(kTestDeviceName), device->GetNameForDisplay());
  2107. }
  2108. #if BUILDFLAG(IS_WIN)
  2109. // WinRT sometimes calls OnConnectionStatusChanged when the status is
  2110. // initialized and not when changed.
  2111. TEST_P(BluetoothTestWinrtOnly, FalseStatusChangedTest) {
  2112. if (!PlatformSupportsLowEnergy()) {
  2113. LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test.";
  2114. return;
  2115. }
  2116. InitWithFakeAdapter();
  2117. StartLowEnergyDiscoverySession();
  2118. BluetoothDevice* device = SimulateLowEnergyDevice(3);
  2119. EXPECT_FALSE(device->IsConnected());
  2120. device->CreateGattConnection(
  2121. GetGattConnectionCallback(Call::NOT_EXPECTED, Result::FAILURE));
  2122. SimulateStatusChangeToDisconnect(device);
  2123. base::RunLoop().RunUntilIdle();
  2124. }
  2125. #endif
  2126. #if BUILDFLAG(IS_ANDROID) || BUILDFLAG(IS_MAC)
  2127. #define MAYBE_ServiceSpecificDiscovery ServiceSpecificDiscovery
  2128. #else
  2129. #define MAYBE_ServiceSpecificDiscovery DISABLED_ServiceSpecificDiscovery
  2130. #endif
  2131. #if !BUILDFLAG(IS_WIN)
  2132. TEST_F(BluetoothTest, MAYBE_ServiceSpecificDiscovery) {
  2133. #else
  2134. TEST_P(BluetoothTestWinrtOnly, ServiceSpecificDiscovery) {
  2135. #endif
  2136. if (!PlatformSupportsLowEnergy()) {
  2137. LOG(WARNING) << "Low Energy Bluetooth unavailable, skipping unit test.";
  2138. return;
  2139. }
  2140. InitWithFakeAdapter();
  2141. StartLowEnergyDiscoverySession();
  2142. BluetoothDevice* device = SimulateLowEnergyDevice(1);
  2143. // Create a GATT connection and specify a specific UUID for discovery.
  2144. ASSERT_TRUE(ConnectGatt(device, BluetoothUUID(kTestUUIDGenericAccess)));
  2145. EXPECT_TRUE(device->IsGattConnected());
  2146. SimulateGattServicesDiscovered(device, {kTestUUIDGenericAccess});
  2147. base::RunLoop().RunUntilIdle();
  2148. EXPECT_EQ(1, gatt_connection_attempts_);
  2149. EXPECT_EQ(1, gatt_discovery_attempts_);
  2150. #if !BUILDFLAG(IS_WIN)
  2151. // Outside of WinRT, service-specific discovery should be ignored.
  2152. ASSERT_FALSE(device->supports_service_specific_discovery());
  2153. EXPECT_FALSE(GetTargetGattService(device).has_value());
  2154. EXPECT_TRUE(device->IsGattServicesDiscoveryComplete());
  2155. #else
  2156. ASSERT_TRUE(device->supports_service_specific_discovery());
  2157. absl::optional<BluetoothUUID> service_uuid = GetTargetGattService(device);
  2158. ASSERT_TRUE(service_uuid.has_value());
  2159. EXPECT_EQ(*service_uuid, BluetoothUUID(kTestUUIDGenericAccess));
  2160. EXPECT_FALSE(device->IsGattServicesDiscoveryComplete());
  2161. // Next, simulate a second GATT request that requests the same service.
  2162. // The connection request should be ignored because of the existing,
  2163. // compatible connection.
  2164. ASSERT_TRUE(ConnectGatt(device, BluetoothUUID(kTestUUIDGenericAccess)));
  2165. EXPECT_EQ(1, gatt_connection_attempts_);
  2166. EXPECT_EQ(1, gatt_discovery_attempts_);
  2167. // A third GATT request is same without any UUID.
  2168. ASSERT_TRUE(ConnectGatt(device));
  2169. // This should restart discovery.
  2170. EXPECT_EQ(2, gatt_discovery_attempts_);
  2171. SimulateGattServicesDiscovered(device, {kTestUUIDGenericAccess});
  2172. base::RunLoop().RunUntilIdle();
  2173. EXPECT_TRUE(device->IsGattServicesDiscoveryComplete());
  2174. // Another GATT request with a specific UUID should be ignored because any
  2175. // specific service is a subset of a complete discovery.
  2176. ASSERT_TRUE(ConnectGatt(device, BluetoothUUID(kTestUUIDGenericAccess)));
  2177. EXPECT_EQ(2, gatt_discovery_attempts_);
  2178. #endif
  2179. }
  2180. } // namespace device