bluetooth_adapter_unittest.cc 79 KB

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