Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(48)

Side by Side Diff: components/proximity_auth/ble/bluetooth_low_energy_weave_client_connection_unittest.cc

Issue 2075313002: Substituting legacy protocol with uWeave protocol (Closed) Base URL: https://chromium.googlesource.com/chromium/src.git@master
Patch Set: saved reference to generator/receiver Created 4 years, 5 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
« no previous file with comments | « components/proximity_auth/ble/bluetooth_low_energy_weave_client_connection.cc ('k') | no next file » | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
(Empty)
1 // Copyright 2016 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
5 #include "components/proximity_auth/ble/bluetooth_low_energy_weave_client_connec tion.h"
6
7 #include <stdint.h>
8
9 #include <memory>
10 #include <utility>
11
12 #include "base/bind.h"
13 #include "base/memory/ptr_util.h"
14 #include "base/message_loop/message_loop.h"
15 #include "base/run_loop.h"
16 #include "base/test/test_simple_task_runner.h"
17 #include "components/proximity_auth/bluetooth_throttler.h"
18 #include "components/proximity_auth/connection_finder.h"
19 #include "components/proximity_auth/proximity_auth_test_util.h"
20 #include "components/proximity_auth/remote_device.h"
21 #include "components/proximity_auth/wire_message.h"
22 #include "device/bluetooth/bluetooth_adapter_factory.h"
23 #include "device/bluetooth/test/mock_bluetooth_adapter.h"
24 #include "device/bluetooth/test/mock_bluetooth_device.h"
25 #include "device/bluetooth/test/mock_bluetooth_discovery_session.h"
26 #include "device/bluetooth/test/mock_bluetooth_gatt_characteristic.h"
27 #include "device/bluetooth/test/mock_bluetooth_gatt_connection.h"
28 #include "device/bluetooth/test/mock_bluetooth_gatt_notify_session.h"
29 #include "testing/gmock/include/gmock/gmock.h"
30 #include "testing/gtest/include/gtest/gtest.h"
31
32 using testing::_;
33 using testing::AtLeast;
34 using testing::NiceMock;
35 using testing::Return;
36 using testing::StrictMock;
37 using testing::SaveArg;
38
39 namespace proximity_auth {
40 namespace {
41
42 class MockBluetoothThrottler : public BluetoothThrottler {
43 public:
44 MockBluetoothThrottler() {}
45 ~MockBluetoothThrottler() override {}
46
47 MOCK_CONST_METHOD0(GetDelay, base::TimeDelta());
48 MOCK_METHOD1(OnConnection, void(Connection* connection));
49
50 private:
51 DISALLOW_COPY_AND_ASSIGN(MockBluetoothThrottler);
52 };
53
54 class MockBluetoothLowEnergyCharacteristicsFinder
55 : public BluetoothLowEnergyCharacteristicsFinder {
56 public:
57 MockBluetoothLowEnergyCharacteristicsFinder() {}
58 ~MockBluetoothLowEnergyCharacteristicsFinder() override {}
59
60 private:
61 DISALLOW_COPY_AND_ASSIGN(MockBluetoothLowEnergyCharacteristicsFinder);
62 };
63
64 } // namespace
65
66 namespace weave {
67 namespace {
68
69 typedef BluetoothLowEnergyWeaveClientConnection::SubStatus SubStatus;
70 typedef BluetoothLowEnergyWeavePacketReceiver::State ReceiverState;
71 typedef BluetoothLowEnergyWeavePacketReceiver::ReceiverError ReceiverError;
72 typedef BluetoothLowEnergyWeavePacketReceiver::ReceiverType ReceiverType;
73
74 const char kServiceUUID[] = "DEADBEEF-CAFE-FEED-FOOD-D15EA5EBEEEF";
75 const char kTXCharacteristicUUID[] = "977c6674-1239-4e72-993b-502369b8bb5a";
76 const char kRXCharacteristicUUID[] = "f4b904a2-a030-43b3-98a8-221c536c03cb";
77
78 const char kServiceID[] = "service id";
79 const char kTXCharacteristicID[] = "TX characteristic id";
80 const char kRXCharacteristicID[] = "RX characteristic id";
81
82 const device::BluetoothRemoteGattCharacteristic::Properties
83 kCharacteristicProperties =
84 device::BluetoothRemoteGattCharacteristic::PROPERTY_BROADCAST |
85 device::BluetoothRemoteGattCharacteristic::PROPERTY_READ |
86 device::BluetoothRemoteGattCharacteristic::
87 PROPERTY_WRITE_WITHOUT_RESPONSE |
88 device::BluetoothRemoteGattCharacteristic::PROPERTY_INDICATE;
89
90 const int kMaxNumberOfTries = 3;
91 const uint16_t kLargeMaxPacketSize = 30;
92
93 const uint8_t kDataHeader = 0;
94 const uint8_t kConnectionRequestHeader = 1;
95 const uint8_t kSmallConnectionResponseHeader = 2;
96 const uint8_t kLargeConnectionResponseHeader = 3;
97 const uint8_t kConnectionCloseHeader = 4;
98
99 const std::string kSmallMessage = "bb";
100 const std::string kLargeMessage = "aaabbb";
101 const std::string kLargeMessage0 = "aaa";
102 const std::string kLargeMessage1 = "bbb";
103
104 const Packet kConnectionRequest{kConnectionRequestHeader};
105 const Packet kSmallConnectionResponse{kSmallConnectionResponseHeader};
106 const Packet kLargeConnectionResponse{kLargeConnectionResponseHeader};
107 const Packet kConnectionClose{kConnectionCloseHeader,
108 ReasonForClose::UNKNOWN_ERROR};
109
110 const Packet kSmallPackets0 = Packet{kDataHeader, 'b', 'b'};
111 const Packet kLargePackets0 = Packet{kDataHeader, 'a', 'a', 'a'};
112 const Packet kLargePackets1 = Packet{kDataHeader, 'b', 'b', 'b'};
113
114 const std::vector<Packet> kSmallPackets{kSmallPackets0};
115 const std::vector<Packet> kLargePackets{kLargePackets0, kLargePackets1};
116
117 class MockBluetoothLowEnergyWeavePacketGenerator
118 : public BluetoothLowEnergyWeavePacketGenerator {
119 public:
120 MockBluetoothLowEnergyWeavePacketGenerator()
121 : max_packet_size_(kDefaultMaxPacketSize) {}
122
123 Packet CreateConnectionRequest() override { return kConnectionRequest; }
124
125 Packet CreateConnectionResponse() override {
126 NOTIMPLEMENTED();
127 return Packet();
128 }
129
130 Packet CreateConnectionClose(ReasonForClose reason_for_close) override {
131 return Packet{kConnectionCloseHeader,
132 static_cast<uint8_t>(reason_for_close)};
133 }
134
135 void SetMaxPacketSize(uint16_t size) override { max_packet_size_ = size; }
136
137 std::vector<Packet> EncodeDataMessage(std::string message) override {
138 if (message == kSmallMessage && max_packet_size_ == kDefaultMaxPacketSize) {
139 return kSmallPackets;
140 } else if (message == kLargeMessage &&
141 max_packet_size_ == kLargeMaxPacketSize) {
142 return kLargePackets;
143 } else {
144 NOTREACHED();
145 return std::vector<Packet>();
146 }
147 }
148
149 uint16_t GetMaxPacketSize() { return max_packet_size_; }
150
151 private:
152 uint16_t max_packet_size_;
153 };
154
155 class MockBluetoothLowEnergyWeavePacketReceiver
156 : public BluetoothLowEnergyWeavePacketReceiver {
157 public:
158 MockBluetoothLowEnergyWeavePacketReceiver()
159 : BluetoothLowEnergyWeavePacketReceiver(ReceiverType::CLIENT),
160 state_(State::CONNECTING),
161 max_packet_size_(kDefaultMaxPacketSize) {}
162
163 ReceiverState GetState() override { return state_; }
164
165 uint16_t GetMaxPacketSize() override { return max_packet_size_; }
166
167 ReasonForClose GetReasonForClose() override { return reason_for_close_; }
168
169 // TODO(jingxuy): change it to reason_to_close_ when error state is resolved
170 ReasonForClose GetReasonToClose() override { return reason_for_close_; }
171
172 std::string GetDataMessage() override {
173 if (max_packet_size_ == kDefaultMaxPacketSize) {
174 return kSmallMessage;
175 } else {
176 return kLargeMessage;
177 }
178 }
179
180 ReceiverError GetReceiverError() override {
181 return ReceiverError::NO_ERROR_DETECTED;
182 }
183
184 ReceiverState ReceivePacket(const Packet& packet) override {
185 switch (packet[0]) {
186 case kSmallConnectionResponseHeader:
187 max_packet_size_ = kDefaultMaxPacketSize;
188 state_ = ReceiverState::WAITING;
189 break;
190 case kLargeConnectionResponseHeader:
191 max_packet_size_ = kLargeMaxPacketSize;
192 state_ = ReceiverState::WAITING;
193 break;
194 case kConnectionCloseHeader:
195 state_ = ReceiverState::CONNECTION_CLOSED;
196 reason_for_close_ = static_cast<ReasonForClose>(packet[1]);
197 break;
198 case kDataHeader:
199 if (packet == kSmallPackets0 || packet == kLargePackets1) {
200 state_ = ReceiverState::DATA_READY;
201 } else {
202 state_ = ReceiverState::RECEIVING_DATA;
203 }
204 break;
205 default:
206 NOTREACHED();
207 }
208 return state_;
209 }
210
211 private:
212 ReceiverState state_;
213 uint16_t max_packet_size_;
214 ReasonForClose reason_for_close_;
215 };
216
217 class MockBluetoothLowEnergyWeavePacketGeneratorFactory
218 : public BluetoothLowEnergyWeavePacketGenerator::Factory {
219 public:
220 MockBluetoothLowEnergyWeavePacketGenerator* GetMostRecentInstance() {
221 return most_recent_instance_;
Kyle Horimoto 2016/07/01 17:23:21 Hmm, most_recent_instance_ will be deleted once th
jingxuy 2016/07/01 19:28:08 yes we are guaranteed
222 }
223
224 private:
225 std::unique_ptr<BluetoothLowEnergyWeavePacketGenerator> BuildInstance()
226 override {
227 most_recent_instance_ = new MockBluetoothLowEnergyWeavePacketGenerator();
228 return std::unique_ptr<BluetoothLowEnergyWeavePacketGenerator>(
229 most_recent_instance_);
230 }
231
232 MockBluetoothLowEnergyWeavePacketGenerator* most_recent_instance_;
233 };
234
235 class MockBluetoothLowEnergyWeavePacketReceiverFactory
236 : public BluetoothLowEnergyWeavePacketReceiver::Factory {
237 public:
238 MockBluetoothLowEnergyWeavePacketReceiver* GetMostRecentInstance() {
239 return most_recent_instance_;
240 }
241
242 private:
243 std::unique_ptr<BluetoothLowEnergyWeavePacketReceiver> BuildInstance(
244 ReceiverType receiver_type) override {
245 most_recent_instance_ = new MockBluetoothLowEnergyWeavePacketReceiver();
246 return std::unique_ptr<BluetoothLowEnergyWeavePacketReceiver>(
247 most_recent_instance_);
248 }
249
250 MockBluetoothLowEnergyWeavePacketReceiver* most_recent_instance_;
251 };
252
253 class TestBluetoothLowEnergyWeaveClientConnection
254 : public BluetoothLowEnergyWeaveClientConnection {
255 public:
256 TestBluetoothLowEnergyWeaveClientConnection(
257 const RemoteDevice& remote_device,
258 scoped_refptr<device::BluetoothAdapter> adapter,
259 const device::BluetoothUUID remote_service_uuid,
260 BluetoothThrottler* bluetooth_throttler,
261 int max_number_of_write_attempts)
262 : BluetoothLowEnergyWeaveClientConnection(remote_device,
263 adapter,
264 remote_service_uuid,
265 bluetooth_throttler,
266 max_number_of_write_attempts) {}
267
268 ~TestBluetoothLowEnergyWeaveClientConnection() override {}
269
270 MOCK_METHOD2(
271 CreateCharacteristicsFinder,
272 BluetoothLowEnergyCharacteristicsFinder*(
273 const BluetoothLowEnergyCharacteristicsFinder::SuccessCallback&
274 success,
275 const BluetoothLowEnergyCharacteristicsFinder::ErrorCallback& error));
276
277 MOCK_METHOD2(OnDidSendMessage,
278 void(const WireMessage& message, bool success));
279 MOCK_METHOD1(OnBytesReceived, void(const std::string& bytes));
280
281 // Exposing inherited protected methods for testing.
282 using BluetoothLowEnergyWeaveClientConnection::GattCharacteristicValueChanged;
283 using BluetoothLowEnergyWeaveClientConnection::SetTaskRunnerForTesting;
284
285 // Exposing inherited protected fields for testing.
286 using BluetoothLowEnergyWeaveClientConnection::status;
287 using BluetoothLowEnergyWeaveClientConnection::sub_status;
288
289 private:
290 DISALLOW_COPY_AND_ASSIGN(TestBluetoothLowEnergyWeaveClientConnection);
291 };
292
293 } // namespace
294
295 class ProximityAuthBluetoothLowEnergyWeaveClientConnectionTest
296 : public testing::Test {
297 public:
298 ProximityAuthBluetoothLowEnergyWeaveClientConnectionTest()
299 : adapter_(new NiceMock<device::MockBluetoothAdapter>),
300 remote_device_(CreateLERemoteDeviceForTest()),
301 service_uuid_(device::BluetoothUUID(kServiceUUID)),
302 tx_characteristic_uuid_(device::BluetoothUUID(kTXCharacteristicUUID)),
303 rx_characteristic_uuid_(device::BluetoothUUID(kRXCharacteristicUUID)),
304 notify_session_alias_(NULL),
305 bluetooth_throttler_(new NiceMock<MockBluetoothThrottler>),
306 task_runner_(new base::TestSimpleTaskRunner) {
307 BluetoothLowEnergyWeavePacketGenerator::Factory::SetInstanceForTesting(
308 &generator_factory_);
309 BluetoothLowEnergyWeavePacketReceiver::Factory::SetInstanceForTesting(
310 &receiver_factory_);
311 }
312
313 void SetUp() override {
314 device_ = base::WrapUnique(new NiceMock<device::MockBluetoothDevice>(
315 adapter_.get(), 0, kTestRemoteDeviceName,
316 kTestRemoteDeviceBluetoothAddress, false, false));
317
318 service_ = base::WrapUnique(new NiceMock<device::MockBluetoothGattService>(
319 device_.get(), kServiceID, service_uuid_, true, false));
320 tx_characteristic_ =
321 base::WrapUnique(new NiceMock<device::MockBluetoothGattCharacteristic>(
322 service_.get(), kTXCharacteristicID, tx_characteristic_uuid_, false,
323 kCharacteristicProperties,
324 device::BluetoothRemoteGattCharacteristic::PERMISSION_NONE));
325
326 rx_characteristic_ =
327 base::WrapUnique(new NiceMock<device::MockBluetoothGattCharacteristic>(
328 service_.get(), kRXCharacteristicID, rx_characteristic_uuid_, false,
329 kCharacteristicProperties,
330 device::BluetoothRemoteGattCharacteristic::PERMISSION_NONE));
331
332 device::BluetoothAdapterFactory::SetAdapterForTesting(adapter_);
333
334 std::vector<const device::BluetoothDevice*> devices;
335 devices.push_back(device_.get());
336 ON_CALL(*adapter_, GetDevices()).WillByDefault(Return(devices));
337 ON_CALL(*adapter_, GetDevice(kTestRemoteDeviceBluetoothAddress))
338 .WillByDefault(Return(device_.get()));
339 ON_CALL(*device_, GetGattService(kServiceID))
340 .WillByDefault(Return(service_.get()));
341 ON_CALL(*service_, GetCharacteristic(kRXCharacteristicID))
342 .WillByDefault(Return(rx_characteristic_.get()));
343 ON_CALL(*service_, GetCharacteristic(kTXCharacteristicID))
344 .WillByDefault(Return(tx_characteristic_.get()));
345 }
346
347 // Creates a BluetoothLowEnergyWeaveClientConnection and verifies it's in
348 // DISCONNECTED state.
349 std::unique_ptr<TestBluetoothLowEnergyWeaveClientConnection>
350 CreateConnection() {
351 EXPECT_CALL(*adapter_, AddObserver(_));
352 EXPECT_CALL(*adapter_, RemoveObserver(_));
353
354 std::unique_ptr<TestBluetoothLowEnergyWeaveClientConnection> connection(
355 new TestBluetoothLowEnergyWeaveClientConnection(
356 remote_device_, adapter_, service_uuid_, bluetooth_throttler_.get(),
357 kMaxNumberOfTries));
358
359 EXPECT_EQ(connection->sub_status(), SubStatus::DISCONNECTED);
360 EXPECT_EQ(connection->status(), Connection::DISCONNECTED);
361
362 connection->SetTaskRunnerForTesting(task_runner_);
363
364 return connection;
365 }
366
367 // Transitions |connection| from DISCONNECTED to WAITING_CHARACTERISTICS
368 // state, without an existing GATT connection.
369 void ConnectGatt(TestBluetoothLowEnergyWeaveClientConnection* connection) {
370 // Preparing |connection| for a CreateGattConnection call.
371 EXPECT_CALL(*device_, CreateGattConnection(_, _))
372 .WillOnce(DoAll(SaveArg<0>(&create_gatt_connection_success_callback_),
373 SaveArg<1>(&create_gatt_connection_error_callback_)));
374
375 // No throttling by default
376 EXPECT_CALL(*bluetooth_throttler_, GetDelay())
377 .WillOnce(Return(base::TimeDelta()));
378
379 connection->Connect();
380
381 EXPECT_EQ(connection->sub_status(), SubStatus::WAITING_GATT_CONNECTION);
382 EXPECT_EQ(connection->status(), Connection::IN_PROGRESS);
383
384 // Preparing |connection| to run |create_gatt_connection_success_callback_|.
385 EXPECT_FALSE(create_gatt_connection_error_callback_.is_null());
386 ASSERT_FALSE(create_gatt_connection_success_callback_.is_null());
387 EXPECT_CALL(*connection, CreateCharacteristicsFinder(_, _))
388 .WillOnce(DoAll(
389 SaveArg<0>(&characteristics_finder_success_callback_),
390 SaveArg<1>(&characteristics_finder_error_callback_),
391 Return(new NiceMock<MockBluetoothLowEnergyCharacteristicsFinder>)));
392
393 create_gatt_connection_success_callback_.Run(
394 base::WrapUnique(new NiceMock<device::MockBluetoothGattConnection>(
395 adapter_, kTestRemoteDeviceBluetoothAddress)));
396
397 EXPECT_EQ(connection->sub_status(), SubStatus::WAITING_CHARACTERISTICS);
398 EXPECT_EQ(connection->status(), Connection::IN_PROGRESS);
399 }
400
401 // Transitions |connection| from WAITING_CHARACTERISTICS to
402 // WAITING_NOTIFY_SESSION state.
403 void CharacteristicsFound(
404 TestBluetoothLowEnergyWeaveClientConnection* connection) {
405 EXPECT_CALL(*rx_characteristic_, StartNotifySession(_, _))
406 .WillOnce(DoAll(SaveArg<0>(&notify_session_success_callback_),
407 SaveArg<1>(&notify_session_error_callback_)));
408 EXPECT_FALSE(characteristics_finder_error_callback_.is_null());
409 ASSERT_FALSE(characteristics_finder_success_callback_.is_null());
410
411 characteristics_finder_success_callback_.Run(
412 {service_uuid_, kServiceID},
413 {tx_characteristic_uuid_, kTXCharacteristicID},
414 {rx_characteristic_uuid_, kRXCharacteristicID});
415
416 EXPECT_EQ(connection->sub_status(), SubStatus::WAITING_NOTIFY_SESSION);
417 EXPECT_EQ(connection->status(), Connection::IN_PROGRESS);
418 }
419
420 // Transitions |connection| from WAITING_NOTIFY_SESSION to
421 // WAITING_CONNECTION_RESPONSE state.
422 void NotifySessionStarted(
423 TestBluetoothLowEnergyWeaveClientConnection* connection) {
424 EXPECT_CALL(*tx_characteristic_, WriteRemoteCharacteristic(_, _, _))
425 .WillOnce(
426 DoAll(SaveArg<0>(&last_value_written_on_tx_characteristic_),
427 SaveArg<1>(&write_remote_characteristic_success_callback_),
428 SaveArg<2>(&write_remote_characteristic_error_callback_)));
429 EXPECT_FALSE(notify_session_error_callback_.is_null());
430 ASSERT_FALSE(notify_session_success_callback_.is_null());
431
432 // Store an alias for the notify session passed |connection|.
433 std::unique_ptr<device::MockBluetoothGattNotifySession> notify_session(
434 new NiceMock<device::MockBluetoothGattNotifySession>(
435 kTXCharacteristicID));
436 notify_session_alias_ = notify_session.get();
437
438 notify_session_success_callback_.Run(std::move(notify_session));
439 task_runner_->RunUntilIdle();
440
441 EXPECT_EQ(connection->sub_status(), SubStatus::WAITING_CONNECTION_RESPONSE);
442 EXPECT_EQ(connection->status(), Connection::IN_PROGRESS);
443 }
444
445 // Transitions |connection| from WAITING_CONNECTION_RESPONSE to CONNECTED.
446 void ConnectionResponseReceived(
447 TestBluetoothLowEnergyWeaveClientConnection* connection,
448 uint16_t selected_packet_size) {
449 // Written value contains only the mock Connection Request.
450 EXPECT_EQ(last_value_written_on_tx_characteristic_, kConnectionRequest);
451
452 EXPECT_CALL(*connection, OnDidSendMessage(_, _)).Times(0);
453 RunWriteCharacteristicSuccessCallback();
454
455 // Received Connection Response.
456 if (selected_packet_size == kDefaultMaxPacketSize) {
457 connection->GattCharacteristicValueChanged(
458 adapter_.get(), rx_characteristic_.get(), kSmallConnectionResponse);
459 EXPECT_EQ(receiver_factory_.GetMostRecentInstance()->GetMaxPacketSize(),
460 kDefaultMaxPacketSize);
461 EXPECT_EQ(generator_factory_.GetMostRecentInstance()->GetMaxPacketSize(),
462 kDefaultMaxPacketSize);
463 } else if (selected_packet_size == kLargeMaxPacketSize) {
464 connection->GattCharacteristicValueChanged(
465 adapter_.get(), rx_characteristic_.get(), kLargeConnectionResponse);
466 EXPECT_EQ(receiver_factory_.GetMostRecentInstance()->GetMaxPacketSize(),
467 kLargeMaxPacketSize);
468 EXPECT_EQ(generator_factory_.GetMostRecentInstance()->GetMaxPacketSize(),
469 kLargeMaxPacketSize);
470 } else {
471 NOTREACHED();
472 }
473
474 EXPECT_EQ(connection->sub_status(), SubStatus::CONNECTED);
475 EXPECT_EQ(connection->status(), Connection::CONNECTED);
476 }
477
478 // Transitions |connection| to a DISCONNECTED state regardless of its initial
479 // state.
480 void Disconnect(TestBluetoothLowEnergyWeaveClientConnection* connection) {
481 // A notify session was previously set.
482 if (notify_session_alias_)
483 EXPECT_CALL(*notify_session_alias_, Stop(_));
484
485 connection->Disconnect();
486
487 EXPECT_EQ(connection->sub_status(), SubStatus::DISCONNECTED);
488 EXPECT_EQ(connection->status(), Connection::DISCONNECTED);
489 }
490
491 void InitializeConnection(
492 TestBluetoothLowEnergyWeaveClientConnection* connection,
493 uint32_t selected_packet_size) {
494 ConnectGatt(connection);
495 CharacteristicsFound(connection);
496 NotifySessionStarted(connection);
497 ConnectionResponseReceived(connection, selected_packet_size);
498 }
499
500 void RunWriteCharacteristicSuccessCallback() {
501 EXPECT_FALSE(write_remote_characteristic_error_callback_.is_null());
502 ASSERT_FALSE(write_remote_characteristic_success_callback_.is_null());
503 write_remote_characteristic_success_callback_.Run();
504 }
505
506 protected:
507 scoped_refptr<device::MockBluetoothAdapter> adapter_;
508 RemoteDevice remote_device_;
509 device::BluetoothUUID service_uuid_;
510 device::BluetoothUUID tx_characteristic_uuid_;
511 device::BluetoothUUID rx_characteristic_uuid_;
512 std::unique_ptr<device::MockBluetoothDevice> device_;
513 std::unique_ptr<device::MockBluetoothGattService> service_;
514 std::unique_ptr<device::MockBluetoothGattCharacteristic> tx_characteristic_;
515 std::unique_ptr<device::MockBluetoothGattCharacteristic> rx_characteristic_;
516 std::vector<uint8_t> last_value_written_on_tx_characteristic_;
517 device::MockBluetoothGattNotifySession* notify_session_alias_;
518 std::unique_ptr<MockBluetoothThrottler> bluetooth_throttler_;
519 scoped_refptr<base::TestSimpleTaskRunner> task_runner_;
520 base::MessageLoop message_loop_;
521
522 // Callbacks
523 device::BluetoothDevice::GattConnectionCallback
524 create_gatt_connection_success_callback_;
525 device::BluetoothDevice::ConnectErrorCallback
526 create_gatt_connection_error_callback_;
527
528 BluetoothLowEnergyCharacteristicsFinder::SuccessCallback
529 characteristics_finder_success_callback_;
530 BluetoothLowEnergyCharacteristicsFinder::ErrorCallback
531 characteristics_finder_error_callback_;
532
533 device::BluetoothRemoteGattCharacteristic::NotifySessionCallback
534 notify_session_success_callback_;
535 device::BluetoothRemoteGattCharacteristic::ErrorCallback
536 notify_session_error_callback_;
537
538 base::Closure write_remote_characteristic_success_callback_;
539 device::BluetoothRemoteGattCharacteristic::ErrorCallback
540 write_remote_characteristic_error_callback_;
541
542 MockBluetoothLowEnergyWeavePacketGeneratorFactory generator_factory_;
543 MockBluetoothLowEnergyWeavePacketReceiverFactory receiver_factory_;
544 };
545
546 TEST_F(ProximityAuthBluetoothLowEnergyWeaveClientConnectionTest,
547 CreateAndDestroyWithoutConnectCallDoesntCrash) {
548 BluetoothLowEnergyWeaveClientConnection connection(
549 remote_device_, adapter_, service_uuid_, bluetooth_throttler_.get(),
550 kMaxNumberOfTries);
551 }
552
553 TEST_F(ProximityAuthBluetoothLowEnergyWeaveClientConnectionTest,
554 DisconectWithoutConnectDoesntCrash) {
555 std::unique_ptr<TestBluetoothLowEnergyWeaveClientConnection> connection(
556 CreateConnection());
557 Disconnect(connection.get());
558 }
559
560 TEST_F(ProximityAuthBluetoothLowEnergyWeaveClientConnectionTest,
561 ConnectSuccess) {
562 std::unique_ptr<TestBluetoothLowEnergyWeaveClientConnection> connection(
563 CreateConnection());
564 ConnectGatt(connection.get());
565 CharacteristicsFound(connection.get());
566 NotifySessionStarted(connection.get());
567 ConnectionResponseReceived(connection.get(), kDefaultMaxPacketSize);
568 }
569
570 TEST_F(ProximityAuthBluetoothLowEnergyWeaveClientConnectionTest,
571 ConnectSuccessDisconnect) {
572 std::unique_ptr<TestBluetoothLowEnergyWeaveClientConnection> connection(
573 CreateConnection());
574 InitializeConnection(connection.get(), kDefaultMaxPacketSize);
575 Disconnect(connection.get());
576 }
577
578 TEST_F(ProximityAuthBluetoothLowEnergyWeaveClientConnectionTest,
579 ConnectIncompleteDisconnectFromWaitingCharacteristicsState) {
580 std::unique_ptr<TestBluetoothLowEnergyWeaveClientConnection> connection(
581 CreateConnection());
582 ConnectGatt(connection.get());
583 Disconnect(connection.get());
584 }
585
586 TEST_F(ProximityAuthBluetoothLowEnergyWeaveClientConnectionTest,
587 ConnectIncompleteDisconnectFromWaitingNotifySessionState) {
588 std::unique_ptr<TestBluetoothLowEnergyWeaveClientConnection> connection(
589 CreateConnection());
590 ConnectGatt(connection.get());
591 CharacteristicsFound(connection.get());
592 Disconnect(connection.get());
593 }
594
595 TEST_F(ProximityAuthBluetoothLowEnergyWeaveClientConnectionTest,
596 ConnectIncompleteDisconnectFromWaitingConnectionResponseState) {
597 std::unique_ptr<TestBluetoothLowEnergyWeaveClientConnection> connection(
598 CreateConnection());
599 ConnectGatt(connection.get());
600 CharacteristicsFound(connection.get());
601 NotifySessionStarted(connection.get());
602 Disconnect(connection.get());
603 }
604
605 TEST_F(ProximityAuthBluetoothLowEnergyWeaveClientConnectionTest,
606 ConnectFailsCharacteristicsNotFound) {
607 std::unique_ptr<TestBluetoothLowEnergyWeaveClientConnection> connection(
608 CreateConnection());
609 ConnectGatt(connection.get());
610
611 EXPECT_CALL(*rx_characteristic_, StartNotifySession(_, _)).Times(0);
612 EXPECT_FALSE(characteristics_finder_success_callback_.is_null());
613 ASSERT_FALSE(characteristics_finder_error_callback_.is_null());
614
615 characteristics_finder_error_callback_.Run(
616 {tx_characteristic_uuid_, kTXCharacteristicID},
617 {rx_characteristic_uuid_, kRXCharacteristicID});
618
619 EXPECT_EQ(connection->sub_status(), SubStatus::DISCONNECTED);
620 EXPECT_EQ(connection->status(), Connection::DISCONNECTED);
621 }
622
623 TEST_F(ProximityAuthBluetoothLowEnergyWeaveClientConnectionTest,
624 ConnectFailsNotifySessionError) {
625 std::unique_ptr<TestBluetoothLowEnergyWeaveClientConnection> connection(
626 CreateConnection());
627 ConnectGatt(connection.get());
628 CharacteristicsFound(connection.get());
629
630 EXPECT_CALL(*tx_characteristic_, WriteRemoteCharacteristic(_, _, _)).Times(0);
631 EXPECT_FALSE(notify_session_success_callback_.is_null());
632 ASSERT_FALSE(notify_session_error_callback_.is_null());
633
634 notify_session_error_callback_.Run(
635 device::BluetoothRemoteGattService::GATT_ERROR_UNKNOWN);
636
637 EXPECT_EQ(connection->sub_status(), SubStatus::DISCONNECTED);
638 EXPECT_EQ(connection->status(), Connection::DISCONNECTED);
639 }
640
641 TEST_F(ProximityAuthBluetoothLowEnergyWeaveClientConnectionTest,
642 ConnectFailsErrorSendingConnectionRequest) {
643 std::unique_ptr<TestBluetoothLowEnergyWeaveClientConnection> connection(
644 CreateConnection());
645 ConnectGatt(connection.get());
646 CharacteristicsFound(connection.get());
647 NotifySessionStarted(connection.get());
648
649 // |connection| will call WriteRemoteCharacteristics(_,_) to try to send the
650 // message |kMaxNumberOfTries| times. There is alredy one EXPECTA_CALL for
651 // WriteRemoteCharacteristic(_,_,_) in NotifySessionStated, that's why we use
652 // |kMaxNumberOfTries-1| in the EXPECT_CALL statement.
653 EXPECT_CALL(*connection, OnDidSendMessage(_, _)).Times(0);
654 EXPECT_CALL(*tx_characteristic_, WriteRemoteCharacteristic(_, _, _))
655 .Times(kMaxNumberOfTries - 1)
656 .WillRepeatedly(
657 DoAll(SaveArg<0>(&last_value_written_on_tx_characteristic_),
658 SaveArg<1>(&write_remote_characteristic_success_callback_),
659 SaveArg<2>(&write_remote_characteristic_error_callback_)));
660
661 for (int i = 0; i < kMaxNumberOfTries; i++) {
662 EXPECT_EQ(last_value_written_on_tx_characteristic_, kConnectionRequest);
663 ASSERT_FALSE(write_remote_characteristic_error_callback_.is_null());
664 EXPECT_FALSE(write_remote_characteristic_success_callback_.is_null());
665 write_remote_characteristic_error_callback_.Run(
666 device::BluetoothRemoteGattService::GATT_ERROR_UNKNOWN);
667 }
668
669 EXPECT_EQ(connection->sub_status(), SubStatus::DISCONNECTED);
670 EXPECT_EQ(connection->status(), Connection::DISCONNECTED);
671 }
672
673 TEST_F(ProximityAuthBluetoothLowEnergyWeaveClientConnectionTest,
674 ReceiveMessageSmallerThanCharacteristicSize) {
675 std::unique_ptr<TestBluetoothLowEnergyWeaveClientConnection> connection(
676 CreateConnection());
677 InitializeConnection(connection.get(), kDefaultMaxPacketSize);
678
679 std::string received_bytes;
680 EXPECT_CALL(*connection, OnBytesReceived(_))
681 .WillOnce(SaveArg<0>(&received_bytes));
682
683 connection->GattCharacteristicValueChanged(
684 adapter_.get(), rx_characteristic_.get(), kSmallPackets0);
685
686 EXPECT_EQ(received_bytes, kSmallMessage);
687 }
688
689 TEST_F(ProximityAuthBluetoothLowEnergyWeaveClientConnectionTest,
690 ReceiveMessageLargerThanCharacteristicSize) {
691 std::unique_ptr<TestBluetoothLowEnergyWeaveClientConnection> connection(
692 CreateConnection());
693
694 InitializeConnection(connection.get(), kLargeMaxPacketSize);
695
696 std::string received_bytes;
697 EXPECT_CALL(*connection, OnBytesReceived(_))
698 .WillOnce(SaveArg<0>(&received_bytes));
699
700 std::vector<Packet> packets = kLargePackets;
701
702 for (auto packet : packets) {
703 connection->GattCharacteristicValueChanged(
704 adapter_.get(), rx_characteristic_.get(), packet);
705 }
706 EXPECT_EQ(received_bytes, kLargeMessage);
707 }
708
709 TEST_F(ProximityAuthBluetoothLowEnergyWeaveClientConnectionTest,
710 SendMessageSmallerThanCharacteristicSize) {
711 std::unique_ptr<TestBluetoothLowEnergyWeaveClientConnection> connection(
712 CreateConnection());
713 InitializeConnection(connection.get(), kDefaultMaxPacketSize);
714
715 // Expecting a first call of WriteRemoteCharacteristic, after SendMessage is
716 // called.
717 EXPECT_CALL(*tx_characteristic_, WriteRemoteCharacteristic(_, _, _))
718 .WillOnce(
719 DoAll(SaveArg<0>(&last_value_written_on_tx_characteristic_),
720 SaveArg<1>(&write_remote_characteristic_success_callback_),
721 SaveArg<2>(&write_remote_characteristic_error_callback_)));
722
723 connection->SendMessage(base::WrapUnique(new FakeWireMessage(kSmallMessage)));
724
725 EXPECT_EQ(last_value_written_on_tx_characteristic_, kSmallPackets0);
726 EXPECT_CALL(*connection, OnDidSendMessage(_, _));
727
728 RunWriteCharacteristicSuccessCallback();
729 }
730
731 TEST_F(ProximityAuthBluetoothLowEnergyWeaveClientConnectionTest,
732 SendMessageLargerThanCharacteristicSize) {
733 std::unique_ptr<TestBluetoothLowEnergyWeaveClientConnection> connection(
734 CreateConnection());
735
736 InitializeConnection(connection.get(), kLargeMaxPacketSize);
737
738 // Expecting a first call of WriteRemoteCharacteristic, after SendMessage is
739 // called.
740 EXPECT_CALL(*tx_characteristic_, WriteRemoteCharacteristic(_, _, _))
741 .WillOnce(
742 DoAll(SaveArg<0>(&last_value_written_on_tx_characteristic_),
743 SaveArg<1>(&write_remote_characteristic_success_callback_),
744 SaveArg<2>(&write_remote_characteristic_error_callback_)));
745
746 connection->SendMessage(base::WrapUnique(new FakeWireMessage(kLargeMessage)));
747
748 EXPECT_EQ(last_value_written_on_tx_characteristic_, kLargePackets0);
749 std::vector<uint8_t> bytes_received(
750 last_value_written_on_tx_characteristic_.begin() + 1,
751 last_value_written_on_tx_characteristic_.end());
752
753 EXPECT_CALL(*tx_characteristic_, WriteRemoteCharacteristic(_, _, _))
754 .WillOnce(
755 DoAll(SaveArg<0>(&last_value_written_on_tx_characteristic_),
756 SaveArg<1>(&write_remote_characteristic_success_callback_),
757 SaveArg<2>(&write_remote_characteristic_error_callback_)));
758
759 RunWriteCharacteristicSuccessCallback();
760 bytes_received.insert(bytes_received.end(),
761 last_value_written_on_tx_characteristic_.begin() + 1,
762 last_value_written_on_tx_characteristic_.end());
763
764 std::vector<uint8_t> expected(kLargeMessage.begin(), kLargeMessage.end());
765 EXPECT_EQ(expected, bytes_received);
766
767 EXPECT_CALL(*connection, OnDidSendMessage(_, _));
768 RunWriteCharacteristicSuccessCallback();
769 }
770
771 TEST_F(ProximityAuthBluetoothLowEnergyWeaveClientConnectionTest,
772 CloseConnectionTest) {
773 std::unique_ptr<TestBluetoothLowEnergyWeaveClientConnection> connection(
774 CreateConnection());
775 InitializeConnection(connection.get(), kDefaultMaxPacketSize);
776
777 connection->GattCharacteristicValueChanged(
778 adapter_.get(), rx_characteristic_.get(), kConnectionClose);
779
780 EXPECT_EQ(receiver_factory_.GetMostRecentInstance()->GetReasonForClose(),
781 ReasonForClose::UNKNOWN_ERROR);
782 EXPECT_EQ(connection->sub_status(), SubStatus::DISCONNECTED);
783 EXPECT_EQ(connection->status(), Connection::DISCONNECTED);
784 }
785
786 TEST_F(ProximityAuthBluetoothLowEnergyWeaveClientConnectionTest,
787 ConnectAfterADelayWhenThrottled) {
788 std::unique_ptr<TestBluetoothLowEnergyWeaveClientConnection> connection(
789 CreateConnection());
790
791 EXPECT_CALL(*bluetooth_throttler_, GetDelay())
792 .WillOnce(Return(base::TimeDelta(base::TimeDelta::FromSeconds(1))));
793 EXPECT_CALL(*device_, CreateGattConnection(_, _))
794 .WillOnce(DoAll(SaveArg<0>(&create_gatt_connection_success_callback_),
795 SaveArg<1>(&create_gatt_connection_error_callback_)));
796
797 // No GATT connection should be created before the delay.
798 connection->Connect();
799 EXPECT_EQ(connection->sub_status(), SubStatus::WAITING_GATT_CONNECTION);
800 EXPECT_EQ(connection->status(), Connection::IN_PROGRESS);
801 EXPECT_TRUE(create_gatt_connection_error_callback_.is_null());
802 EXPECT_TRUE(create_gatt_connection_success_callback_.is_null());
803
804 // A GATT connection should be created after the delay.
805 task_runner_->RunUntilIdle();
806 EXPECT_FALSE(create_gatt_connection_error_callback_.is_null());
807 ASSERT_FALSE(create_gatt_connection_success_callback_.is_null());
808
809 // Preparing |connection| to run |create_gatt_connection_success_callback_|.
810 EXPECT_CALL(*connection, CreateCharacteristicsFinder(_, _))
811 .WillOnce(DoAll(
812 SaveArg<0>(&characteristics_finder_success_callback_),
813 SaveArg<1>(&characteristics_finder_error_callback_),
814 Return(new NiceMock<MockBluetoothLowEnergyCharacteristicsFinder>)));
815
816 create_gatt_connection_success_callback_.Run(
817 base::WrapUnique(new NiceMock<device::MockBluetoothGattConnection>(
818 adapter_, kTestRemoteDeviceBluetoothAddress)));
819
820 CharacteristicsFound(connection.get());
821 NotifySessionStarted(connection.get());
822 ConnectionResponseReceived(connection.get(), kDefaultMaxPacketSize);
823 }
824
825 } // namespace weave
826
827 } // namespace proximity_auth
OLDNEW
« no previous file with comments | « components/proximity_auth/ble/bluetooth_low_energy_weave_client_connection.cc ('k') | no next file » | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698