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

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: correct handling of connection close 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
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 // most_recent_instance_ will be obsolete after the connection class
221 // destructs. Do not use if that's the case.
222 MockBluetoothLowEnergyWeavePacketGenerator* GetMostRecentInstance() {
223 return most_recent_instance_;
224 }
225
226 private:
227 std::unique_ptr<BluetoothLowEnergyWeavePacketGenerator> BuildInstance()
228 override {
229 most_recent_instance_ = new MockBluetoothLowEnergyWeavePacketGenerator();
230 return std::unique_ptr<BluetoothLowEnergyWeavePacketGenerator>(
231 most_recent_instance_);
232 }
233
234 MockBluetoothLowEnergyWeavePacketGenerator* most_recent_instance_;
235 };
236
237 class MockBluetoothLowEnergyWeavePacketReceiverFactory
238 : public BluetoothLowEnergyWeavePacketReceiver::Factory {
239 public:
240 // most_recent_instance_ will be obsolete after the connection class
241 // destructs. Do not use if that's the case.
242 MockBluetoothLowEnergyWeavePacketReceiver* GetMostRecentInstance() {
243 return most_recent_instance_;
244 }
245
246 private:
247 std::unique_ptr<BluetoothLowEnergyWeavePacketReceiver> BuildInstance(
248 ReceiverType receiver_type) override {
249 most_recent_instance_ = new MockBluetoothLowEnergyWeavePacketReceiver();
250 return std::unique_ptr<BluetoothLowEnergyWeavePacketReceiver>(
251 most_recent_instance_);
252 }
253
254 MockBluetoothLowEnergyWeavePacketReceiver* most_recent_instance_;
255 };
256
257 class TestBluetoothLowEnergyWeaveClientConnection
258 : public BluetoothLowEnergyWeaveClientConnection {
259 public:
260 TestBluetoothLowEnergyWeaveClientConnection(
261 const RemoteDevice& remote_device,
262 scoped_refptr<device::BluetoothAdapter> adapter,
263 const device::BluetoothUUID remote_service_uuid,
264 BluetoothThrottler* bluetooth_throttler,
265 int max_number_of_write_attempts)
266 : BluetoothLowEnergyWeaveClientConnection(remote_device,
267 adapter,
268 remote_service_uuid,
269 bluetooth_throttler,
270 max_number_of_write_attempts) {}
271
272 ~TestBluetoothLowEnergyWeaveClientConnection() override {}
273
274 MOCK_METHOD2(
275 CreateCharacteristicsFinder,
276 BluetoothLowEnergyCharacteristicsFinder*(
277 const BluetoothLowEnergyCharacteristicsFinder::SuccessCallback&
278 success,
279 const BluetoothLowEnergyCharacteristicsFinder::ErrorCallback& error));
280
281 MOCK_METHOD2(OnDidSendMessage,
282 void(const WireMessage& message, bool success));
283 MOCK_METHOD1(OnBytesReceived, void(const std::string& bytes));
284
285 // Exposing inherited protected methods for testing.
286 using BluetoothLowEnergyWeaveClientConnection::GattCharacteristicValueChanged;
287 using BluetoothLowEnergyWeaveClientConnection::SetTaskRunnerForTesting;
288 using BluetoothLowEnergyWeaveClientConnection::DestroyConnection;
289
290 // Exposing inherited protected fields for testing.
291 using BluetoothLowEnergyWeaveClientConnection::status;
292 using BluetoothLowEnergyWeaveClientConnection::sub_status;
293
294 private:
295 DISALLOW_COPY_AND_ASSIGN(TestBluetoothLowEnergyWeaveClientConnection);
296 };
297
298 } // namespace
299
300 class ProximityAuthBluetoothLowEnergyWeaveClientConnectionTest
301 : public testing::Test {
302 public:
303 ProximityAuthBluetoothLowEnergyWeaveClientConnectionTest()
304 : adapter_(new NiceMock<device::MockBluetoothAdapter>),
305 remote_device_(CreateLERemoteDeviceForTest()),
306 service_uuid_(device::BluetoothUUID(kServiceUUID)),
307 tx_characteristic_uuid_(device::BluetoothUUID(kTXCharacteristicUUID)),
308 rx_characteristic_uuid_(device::BluetoothUUID(kRXCharacteristicUUID)),
309 notify_session_alias_(NULL),
310 bluetooth_throttler_(new NiceMock<MockBluetoothThrottler>),
311 task_runner_(new base::TestSimpleTaskRunner) {
312 BluetoothLowEnergyWeavePacketGenerator::Factory::SetInstanceForTesting(
313 &generator_factory_);
314 BluetoothLowEnergyWeavePacketReceiver::Factory::SetInstanceForTesting(
315 &receiver_factory_);
316 }
317
318 void SetUp() override {
319 device_ = base::WrapUnique(new NiceMock<device::MockBluetoothDevice>(
320 adapter_.get(), 0, kTestRemoteDeviceName,
321 kTestRemoteDeviceBluetoothAddress, false, false));
322
323 service_ = base::WrapUnique(new NiceMock<device::MockBluetoothGattService>(
324 device_.get(), kServiceID, service_uuid_, true, false));
325 tx_characteristic_ =
326 base::WrapUnique(new NiceMock<device::MockBluetoothGattCharacteristic>(
327 service_.get(), kTXCharacteristicID, tx_characteristic_uuid_, false,
328 kCharacteristicProperties,
329 device::BluetoothRemoteGattCharacteristic::PERMISSION_NONE));
330
331 rx_characteristic_ =
332 base::WrapUnique(new NiceMock<device::MockBluetoothGattCharacteristic>(
333 service_.get(), kRXCharacteristicID, rx_characteristic_uuid_, false,
334 kCharacteristicProperties,
335 device::BluetoothRemoteGattCharacteristic::PERMISSION_NONE));
336
337 device::BluetoothAdapterFactory::SetAdapterForTesting(adapter_);
338
339 std::vector<const device::BluetoothDevice*> devices;
340 devices.push_back(device_.get());
341 ON_CALL(*adapter_, GetDevices()).WillByDefault(Return(devices));
342 ON_CALL(*adapter_, GetDevice(kTestRemoteDeviceBluetoothAddress))
343 .WillByDefault(Return(device_.get()));
344 ON_CALL(*device_, GetGattService(kServiceID))
345 .WillByDefault(Return(service_.get()));
346 ON_CALL(*service_, GetCharacteristic(kRXCharacteristicID))
347 .WillByDefault(Return(rx_characteristic_.get()));
348 ON_CALL(*service_, GetCharacteristic(kTXCharacteristicID))
349 .WillByDefault(Return(tx_characteristic_.get()));
350 }
351
352 // Creates a BluetoothLowEnergyWeaveClientConnection and verifies it's in
353 // DISCONNECTED state.
354 std::unique_ptr<TestBluetoothLowEnergyWeaveClientConnection>
355 CreateConnection() {
356 EXPECT_CALL(*adapter_, AddObserver(_));
357 EXPECT_CALL(*adapter_, RemoveObserver(_));
358
359 std::unique_ptr<TestBluetoothLowEnergyWeaveClientConnection> connection(
360 new TestBluetoothLowEnergyWeaveClientConnection(
361 remote_device_, adapter_, service_uuid_, bluetooth_throttler_.get(),
362 kMaxNumberOfTries));
363
364 EXPECT_EQ(connection->sub_status(), SubStatus::DISCONNECTED);
365 EXPECT_EQ(connection->status(), Connection::DISCONNECTED);
366
367 connection->SetTaskRunnerForTesting(task_runner_);
368
369 return connection;
370 }
371
372 // Transitions |connection| from DISCONNECTED to WAITING_CHARACTERISTICS
373 // state, without an existing GATT connection.
374 void ConnectGatt(TestBluetoothLowEnergyWeaveClientConnection* connection) {
375 // Preparing |connection| for a CreateGattConnection call.
376 EXPECT_CALL(*device_, CreateGattConnection(_, _))
377 .WillOnce(DoAll(SaveArg<0>(&create_gatt_connection_success_callback_),
378 SaveArg<1>(&create_gatt_connection_error_callback_)));
379
380 // No throttling by default
381 EXPECT_CALL(*bluetooth_throttler_, GetDelay())
382 .WillOnce(Return(base::TimeDelta()));
383
384 connection->Connect();
385
386 EXPECT_EQ(connection->sub_status(), SubStatus::WAITING_GATT_CONNECTION);
387 EXPECT_EQ(connection->status(), Connection::IN_PROGRESS);
388
389 // Preparing |connection| to run |create_gatt_connection_success_callback_|.
390 EXPECT_FALSE(create_gatt_connection_error_callback_.is_null());
391 ASSERT_FALSE(create_gatt_connection_success_callback_.is_null());
392 EXPECT_CALL(*connection, CreateCharacteristicsFinder(_, _))
393 .WillOnce(DoAll(
394 SaveArg<0>(&characteristics_finder_success_callback_),
395 SaveArg<1>(&characteristics_finder_error_callback_),
396 Return(new NiceMock<MockBluetoothLowEnergyCharacteristicsFinder>)));
397
398 create_gatt_connection_success_callback_.Run(
399 base::WrapUnique(new NiceMock<device::MockBluetoothGattConnection>(
400 adapter_, kTestRemoteDeviceBluetoothAddress)));
401
402 EXPECT_EQ(connection->sub_status(), SubStatus::WAITING_CHARACTERISTICS);
403 EXPECT_EQ(connection->status(), Connection::IN_PROGRESS);
404 }
405
406 // Transitions |connection| from WAITING_CHARACTERISTICS to
407 // WAITING_NOTIFY_SESSION state.
408 void CharacteristicsFound(
409 TestBluetoothLowEnergyWeaveClientConnection* connection) {
410 EXPECT_CALL(*rx_characteristic_, StartNotifySession(_, _))
411 .WillOnce(DoAll(SaveArg<0>(&notify_session_success_callback_),
412 SaveArg<1>(&notify_session_error_callback_)));
413 EXPECT_FALSE(characteristics_finder_error_callback_.is_null());
414 ASSERT_FALSE(characteristics_finder_success_callback_.is_null());
415
416 characteristics_finder_success_callback_.Run(
417 {service_uuid_, kServiceID},
418 {tx_characteristic_uuid_, kTXCharacteristicID},
419 {rx_characteristic_uuid_, kRXCharacteristicID});
420
421 EXPECT_EQ(connection->sub_status(), SubStatus::WAITING_NOTIFY_SESSION);
422 EXPECT_EQ(connection->status(), Connection::IN_PROGRESS);
423 }
424
425 // Transitions |connection| from WAITING_NOTIFY_SESSION to
426 // WAITING_CONNECTION_RESPONSE state.
427 void NotifySessionStarted(
428 TestBluetoothLowEnergyWeaveClientConnection* connection) {
429 EXPECT_CALL(*tx_characteristic_, WriteRemoteCharacteristic(_, _, _))
430 .WillOnce(
431 DoAll(SaveArg<0>(&last_value_written_on_tx_characteristic_),
432 SaveArg<1>(&write_remote_characteristic_success_callback_),
433 SaveArg<2>(&write_remote_characteristic_error_callback_)));
434 EXPECT_FALSE(notify_session_error_callback_.is_null());
435 ASSERT_FALSE(notify_session_success_callback_.is_null());
436
437 // Store an alias for the notify session passed |connection|.
438 std::unique_ptr<device::MockBluetoothGattNotifySession> notify_session(
439 new NiceMock<device::MockBluetoothGattNotifySession>(
440 kTXCharacteristicID));
441 notify_session_alias_ = notify_session.get();
442
443 notify_session_success_callback_.Run(std::move(notify_session));
444 task_runner_->RunUntilIdle();
445
446 // Written value contains only the mock Connection Request.
447 EXPECT_EQ(last_value_written_on_tx_characteristic_, kConnectionRequest);
448
449 EXPECT_EQ(connection->sub_status(), SubStatus::WAITING_CONNECTION_RESPONSE);
450 EXPECT_EQ(connection->status(), Connection::IN_PROGRESS);
451 }
452
453 // Transitions |connection| from WAITING_CONNECTION_RESPONSE to CONNECTED.
454 void ConnectionResponseReceived(
455 TestBluetoothLowEnergyWeaveClientConnection* connection,
456 uint16_t selected_packet_size) {
457 // Written value contains only the mock Connection Request.
458 EXPECT_EQ(last_value_written_on_tx_characteristic_, kConnectionRequest);
459
460 EXPECT_CALL(*connection, OnDidSendMessage(_, _)).Times(0);
461 RunWriteCharacteristicSuccessCallback();
462
463 // Received Connection Response.
464 if (selected_packet_size == kDefaultMaxPacketSize) {
465 connection->GattCharacteristicValueChanged(
466 adapter_.get(), rx_characteristic_.get(), kSmallConnectionResponse);
467 EXPECT_EQ(receiver_factory_.GetMostRecentInstance()->GetMaxPacketSize(),
468 kDefaultMaxPacketSize);
469 EXPECT_EQ(generator_factory_.GetMostRecentInstance()->GetMaxPacketSize(),
470 kDefaultMaxPacketSize);
471 } else if (selected_packet_size == kLargeMaxPacketSize) {
472 connection->GattCharacteristicValueChanged(
473 adapter_.get(), rx_characteristic_.get(), kLargeConnectionResponse);
474 EXPECT_EQ(receiver_factory_.GetMostRecentInstance()->GetMaxPacketSize(),
475 kLargeMaxPacketSize);
476 EXPECT_EQ(generator_factory_.GetMostRecentInstance()->GetMaxPacketSize(),
477 kLargeMaxPacketSize);
478 } else {
479 NOTREACHED();
480 }
481
482 EXPECT_EQ(connection->sub_status(), SubStatus::CONNECTED);
483 EXPECT_EQ(connection->status(), Connection::CONNECTED);
484 }
485
486 // Transitions |connection| to a DISCONNECTED state regardless of its initial
487 // state.
488 void Disconnect(TestBluetoothLowEnergyWeaveClientConnection* connection) {
489 // A notify session was previously set.
490 if (notify_session_alias_)
491 EXPECT_CALL(*notify_session_alias_, Stop(_));
492
493 if (connection->sub_status() == SubStatus::CONNECTED) {
494 EXPECT_CALL(*tx_characteristic_, WriteRemoteCharacteristic(_, _, _))
495 .WillOnce(
496 DoAll(SaveArg<0>(&last_value_written_on_tx_characteristic_),
497 SaveArg<1>(&write_remote_characteristic_success_callback_),
498 SaveArg<2>(&write_remote_characteristic_error_callback_)));
499 }
500
501 connection->Disconnect();
502
503 if (connection->sub_status() == SubStatus::CONNECTED) {
504 connection->DestroyConnection();
505 }
506
507 EXPECT_EQ(connection->sub_status(), SubStatus::DISCONNECTED);
508 EXPECT_EQ(connection->status(), Connection::DISCONNECTED);
509 }
510
511 void InitializeConnection(
512 TestBluetoothLowEnergyWeaveClientConnection* connection,
513 uint32_t selected_packet_size) {
514 ConnectGatt(connection);
515 CharacteristicsFound(connection);
516 NotifySessionStarted(connection);
517 ConnectionResponseReceived(connection, selected_packet_size);
518 }
519
520 void RunWriteCharacteristicSuccessCallback() {
521 EXPECT_FALSE(write_remote_characteristic_error_callback_.is_null());
522 ASSERT_FALSE(write_remote_characteristic_success_callback_.is_null());
523 write_remote_characteristic_success_callback_.Run();
524 }
525
526 protected:
527 scoped_refptr<device::MockBluetoothAdapter> adapter_;
528 RemoteDevice remote_device_;
529 device::BluetoothUUID service_uuid_;
530 device::BluetoothUUID tx_characteristic_uuid_;
531 device::BluetoothUUID rx_characteristic_uuid_;
532 std::unique_ptr<device::MockBluetoothDevice> device_;
533 std::unique_ptr<device::MockBluetoothGattService> service_;
534 std::unique_ptr<device::MockBluetoothGattCharacteristic> tx_characteristic_;
535 std::unique_ptr<device::MockBluetoothGattCharacteristic> rx_characteristic_;
536 std::vector<uint8_t> last_value_written_on_tx_characteristic_;
537 device::MockBluetoothGattNotifySession* notify_session_alias_;
538 std::unique_ptr<MockBluetoothThrottler> bluetooth_throttler_;
539 scoped_refptr<base::TestSimpleTaskRunner> task_runner_;
540 base::MessageLoop message_loop_;
541
542 // Callbacks
543 device::BluetoothDevice::GattConnectionCallback
544 create_gatt_connection_success_callback_;
545 device::BluetoothDevice::ConnectErrorCallback
546 create_gatt_connection_error_callback_;
547
548 BluetoothLowEnergyCharacteristicsFinder::SuccessCallback
549 characteristics_finder_success_callback_;
550 BluetoothLowEnergyCharacteristicsFinder::ErrorCallback
551 characteristics_finder_error_callback_;
552
553 device::BluetoothRemoteGattCharacteristic::NotifySessionCallback
554 notify_session_success_callback_;
555 device::BluetoothRemoteGattCharacteristic::ErrorCallback
556 notify_session_error_callback_;
557
558 base::Closure write_remote_characteristic_success_callback_;
559 device::BluetoothRemoteGattCharacteristic::ErrorCallback
560 write_remote_characteristic_error_callback_;
561
562 MockBluetoothLowEnergyWeavePacketGeneratorFactory generator_factory_;
563 MockBluetoothLowEnergyWeavePacketReceiverFactory receiver_factory_;
564 };
565
566 TEST_F(ProximityAuthBluetoothLowEnergyWeaveClientConnectionTest,
567 CreateAndDestroyWithoutConnectCallDoesntCrash) {
568 BluetoothLowEnergyWeaveClientConnection connection(
569 remote_device_, adapter_, service_uuid_, bluetooth_throttler_.get(),
570 kMaxNumberOfTries);
571 }
572
573 TEST_F(ProximityAuthBluetoothLowEnergyWeaveClientConnectionTest,
574 DisconectWithoutConnectDoesntCrash) {
575 std::unique_ptr<TestBluetoothLowEnergyWeaveClientConnection> connection(
576 CreateConnection());
577 Disconnect(connection.get());
578 }
579
580 TEST_F(ProximityAuthBluetoothLowEnergyWeaveClientConnectionTest,
581 ConnectSuccess) {
582 std::unique_ptr<TestBluetoothLowEnergyWeaveClientConnection> connection(
583 CreateConnection());
584 ConnectGatt(connection.get());
585 CharacteristicsFound(connection.get());
586 NotifySessionStarted(connection.get());
587 ConnectionResponseReceived(connection.get(), kDefaultMaxPacketSize);
588 }
589
590 TEST_F(ProximityAuthBluetoothLowEnergyWeaveClientConnectionTest,
591 ConnectSuccessDisconnect) {
592 std::unique_ptr<TestBluetoothLowEnergyWeaveClientConnection> connection(
593 CreateConnection());
594 InitializeConnection(connection.get(), kDefaultMaxPacketSize);
595 Disconnect(connection.get());
596 }
597
598 TEST_F(ProximityAuthBluetoothLowEnergyWeaveClientConnectionTest,
599 ConnectIncompleteDisconnectFromWaitingCharacteristicsState) {
600 std::unique_ptr<TestBluetoothLowEnergyWeaveClientConnection> connection(
601 CreateConnection());
602 ConnectGatt(connection.get());
603 Disconnect(connection.get());
604 }
605
606 TEST_F(ProximityAuthBluetoothLowEnergyWeaveClientConnectionTest,
607 ConnectIncompleteDisconnectFromWaitingNotifySessionState) {
608 std::unique_ptr<TestBluetoothLowEnergyWeaveClientConnection> connection(
609 CreateConnection());
610 ConnectGatt(connection.get());
611 CharacteristicsFound(connection.get());
612 Disconnect(connection.get());
613 }
614
615 TEST_F(ProximityAuthBluetoothLowEnergyWeaveClientConnectionTest,
616 ConnectIncompleteDisconnectFromWaitingConnectionResponseState) {
617 std::unique_ptr<TestBluetoothLowEnergyWeaveClientConnection> connection(
618 CreateConnection());
619 ConnectGatt(connection.get());
620 CharacteristicsFound(connection.get());
621 NotifySessionStarted(connection.get());
622 Disconnect(connection.get());
623 }
624
625 TEST_F(ProximityAuthBluetoothLowEnergyWeaveClientConnectionTest,
626 ConnectFailsCharacteristicsNotFound) {
627 std::unique_ptr<TestBluetoothLowEnergyWeaveClientConnection> connection(
628 CreateConnection());
629 ConnectGatt(connection.get());
630
631 EXPECT_CALL(*rx_characteristic_, StartNotifySession(_, _)).Times(0);
632 EXPECT_FALSE(characteristics_finder_success_callback_.is_null());
633 ASSERT_FALSE(characteristics_finder_error_callback_.is_null());
634
635 characteristics_finder_error_callback_.Run(
636 {tx_characteristic_uuid_, kTXCharacteristicID},
637 {rx_characteristic_uuid_, kRXCharacteristicID});
638
639 EXPECT_EQ(connection->sub_status(), SubStatus::DISCONNECTED);
640 EXPECT_EQ(connection->status(), Connection::DISCONNECTED);
641 }
642
643 TEST_F(ProximityAuthBluetoothLowEnergyWeaveClientConnectionTest,
644 ConnectFailsNotifySessionError) {
645 std::unique_ptr<TestBluetoothLowEnergyWeaveClientConnection> connection(
646 CreateConnection());
647 ConnectGatt(connection.get());
648 CharacteristicsFound(connection.get());
649
650 EXPECT_CALL(*tx_characteristic_, WriteRemoteCharacteristic(_, _, _)).Times(0);
651 EXPECT_FALSE(notify_session_success_callback_.is_null());
652 ASSERT_FALSE(notify_session_error_callback_.is_null());
653
654 notify_session_error_callback_.Run(
655 device::BluetoothRemoteGattService::GATT_ERROR_UNKNOWN);
656
657 EXPECT_EQ(connection->sub_status(), SubStatus::DISCONNECTED);
658 EXPECT_EQ(connection->status(), Connection::DISCONNECTED);
659 }
660
661 TEST_F(ProximityAuthBluetoothLowEnergyWeaveClientConnectionTest,
662 ConnectFailsErrorSendingConnectionRequest) {
663 std::unique_ptr<TestBluetoothLowEnergyWeaveClientConnection> connection(
664 CreateConnection());
665 ConnectGatt(connection.get());
666 CharacteristicsFound(connection.get());
667 NotifySessionStarted(connection.get());
668
669 // |connection| will call WriteRemoteCharacteristics(_,_) to try to send the
670 // message |kMaxNumberOfTries| times. There is alredy one EXPECTA_CALL for
671 // WriteRemoteCharacteristic(_,_,_) in NotifySessionStated, that's why we use
672 // |kMaxNumberOfTries-1| in the EXPECT_CALL statement.
673 EXPECT_CALL(*connection, OnDidSendMessage(_, _)).Times(0);
674 EXPECT_CALL(*tx_characteristic_, WriteRemoteCharacteristic(_, _, _))
675 .Times(kMaxNumberOfTries - 1)
676 .WillRepeatedly(
677 DoAll(SaveArg<0>(&last_value_written_on_tx_characteristic_),
678 SaveArg<1>(&write_remote_characteristic_success_callback_),
679 SaveArg<2>(&write_remote_characteristic_error_callback_)));
680
681 for (int i = 0; i < kMaxNumberOfTries; i++) {
682 EXPECT_EQ(last_value_written_on_tx_characteristic_, kConnectionRequest);
683 ASSERT_FALSE(write_remote_characteristic_error_callback_.is_null());
684 EXPECT_FALSE(write_remote_characteristic_success_callback_.is_null());
685 write_remote_characteristic_error_callback_.Run(
686 device::BluetoothRemoteGattService::GATT_ERROR_UNKNOWN);
687 }
688
689 EXPECT_EQ(connection->sub_status(), SubStatus::DISCONNECTED);
690 EXPECT_EQ(connection->status(), Connection::DISCONNECTED);
691 }
692
693 TEST_F(ProximityAuthBluetoothLowEnergyWeaveClientConnectionTest,
694 ReceiveMessageSmallerThanCharacteristicSize) {
695 std::unique_ptr<TestBluetoothLowEnergyWeaveClientConnection> connection(
696 CreateConnection());
697 InitializeConnection(connection.get(), kDefaultMaxPacketSize);
698
699 std::string received_bytes;
700 EXPECT_CALL(*connection, OnBytesReceived(_))
701 .WillOnce(SaveArg<0>(&received_bytes));
702
703 connection->GattCharacteristicValueChanged(
704 adapter_.get(), rx_characteristic_.get(), kSmallPackets0);
705
706 EXPECT_EQ(received_bytes, kSmallMessage);
707 }
708
709 TEST_F(ProximityAuthBluetoothLowEnergyWeaveClientConnectionTest,
710 ReceiveMessageLargerThanCharacteristicSize) {
711 std::unique_ptr<TestBluetoothLowEnergyWeaveClientConnection> connection(
712 CreateConnection());
713
714 InitializeConnection(connection.get(), kLargeMaxPacketSize);
715
716 std::string received_bytes;
717 EXPECT_CALL(*connection, OnBytesReceived(_))
718 .WillOnce(SaveArg<0>(&received_bytes));
719
720 std::vector<Packet> packets = kLargePackets;
721
722 for (auto packet : packets) {
723 connection->GattCharacteristicValueChanged(
724 adapter_.get(), rx_characteristic_.get(), packet);
725 }
726 EXPECT_EQ(received_bytes, kLargeMessage);
727 }
728
729 TEST_F(ProximityAuthBluetoothLowEnergyWeaveClientConnectionTest,
730 SendMessageSmallerThanCharacteristicSize) {
731 std::unique_ptr<TestBluetoothLowEnergyWeaveClientConnection> connection(
732 CreateConnection());
733 InitializeConnection(connection.get(), kDefaultMaxPacketSize);
734
735 // Expecting a first call of WriteRemoteCharacteristic, after SendMessage is
736 // called.
737 EXPECT_CALL(*tx_characteristic_, WriteRemoteCharacteristic(_, _, _))
738 .WillOnce(
739 DoAll(SaveArg<0>(&last_value_written_on_tx_characteristic_),
740 SaveArg<1>(&write_remote_characteristic_success_callback_),
741 SaveArg<2>(&write_remote_characteristic_error_callback_)));
742
743 connection->SendMessage(base::WrapUnique(new FakeWireMessage(kSmallMessage)));
744
745 EXPECT_EQ(last_value_written_on_tx_characteristic_, kSmallPackets0);
746 EXPECT_CALL(*connection, OnDidSendMessage(_, _));
747
748 RunWriteCharacteristicSuccessCallback();
749 }
750
751 TEST_F(ProximityAuthBluetoothLowEnergyWeaveClientConnectionTest,
752 SendMessageLargerThanCharacteristicSize) {
753 std::unique_ptr<TestBluetoothLowEnergyWeaveClientConnection> connection(
754 CreateConnection());
755
756 InitializeConnection(connection.get(), kLargeMaxPacketSize);
757
758 // Expecting a first call of WriteRemoteCharacteristic, after SendMessage is
759 // called.
760 EXPECT_CALL(*tx_characteristic_, WriteRemoteCharacteristic(_, _, _))
761 .WillOnce(
762 DoAll(SaveArg<0>(&last_value_written_on_tx_characteristic_),
763 SaveArg<1>(&write_remote_characteristic_success_callback_),
764 SaveArg<2>(&write_remote_characteristic_error_callback_)));
765
766 connection->SendMessage(base::WrapUnique(new FakeWireMessage(kLargeMessage)));
767
768 EXPECT_EQ(last_value_written_on_tx_characteristic_, kLargePackets0);
769 std::vector<uint8_t> bytes_received(
770 last_value_written_on_tx_characteristic_.begin() + 1,
771 last_value_written_on_tx_characteristic_.end());
772
773 EXPECT_CALL(*tx_characteristic_, WriteRemoteCharacteristic(_, _, _))
774 .WillOnce(
775 DoAll(SaveArg<0>(&last_value_written_on_tx_characteristic_),
776 SaveArg<1>(&write_remote_characteristic_success_callback_),
777 SaveArg<2>(&write_remote_characteristic_error_callback_)));
778
779 RunWriteCharacteristicSuccessCallback();
780 bytes_received.insert(bytes_received.end(),
781 last_value_written_on_tx_characteristic_.begin() + 1,
782 last_value_written_on_tx_characteristic_.end());
783
784 std::vector<uint8_t> expected(kLargeMessage.begin(), kLargeMessage.end());
785 EXPECT_EQ(expected, bytes_received);
786
787 EXPECT_CALL(*connection, OnDidSendMessage(_, _));
788 RunWriteCharacteristicSuccessCallback();
789 }
790
791 TEST_F(ProximityAuthBluetoothLowEnergyWeaveClientConnectionTest,
792 CloseConnectionTest) {
793 std::unique_ptr<TestBluetoothLowEnergyWeaveClientConnection> connection(
794 CreateConnection());
795 InitializeConnection(connection.get(), kDefaultMaxPacketSize);
796
797 connection->GattCharacteristicValueChanged(
798 adapter_.get(), rx_characteristic_.get(), kConnectionClose);
799
800 EXPECT_EQ(receiver_factory_.GetMostRecentInstance()->GetReasonForClose(),
801 ReasonForClose::UNKNOWN_ERROR);
802 EXPECT_EQ(connection->sub_status(), SubStatus::DISCONNECTED);
803 EXPECT_EQ(connection->status(), Connection::DISCONNECTED);
804 }
805
806 TEST_F(ProximityAuthBluetoothLowEnergyWeaveClientConnectionTest,
807 ConnectAfterADelayWhenThrottled) {
808 std::unique_ptr<TestBluetoothLowEnergyWeaveClientConnection> connection(
809 CreateConnection());
810
811 EXPECT_CALL(*bluetooth_throttler_, GetDelay())
812 .WillOnce(Return(base::TimeDelta(base::TimeDelta::FromSeconds(1))));
813 EXPECT_CALL(*device_, CreateGattConnection(_, _))
814 .WillOnce(DoAll(SaveArg<0>(&create_gatt_connection_success_callback_),
815 SaveArg<1>(&create_gatt_connection_error_callback_)));
816
817 // No GATT connection should be created before the delay.
818 connection->Connect();
819 EXPECT_EQ(connection->sub_status(), SubStatus::WAITING_GATT_CONNECTION);
820 EXPECT_EQ(connection->status(), Connection::IN_PROGRESS);
821 EXPECT_TRUE(create_gatt_connection_error_callback_.is_null());
822 EXPECT_TRUE(create_gatt_connection_success_callback_.is_null());
823
824 // A GATT connection should be created after the delay.
825 task_runner_->RunUntilIdle();
826 EXPECT_FALSE(create_gatt_connection_error_callback_.is_null());
827 ASSERT_FALSE(create_gatt_connection_success_callback_.is_null());
828
829 // Preparing |connection| to run |create_gatt_connection_success_callback_|.
830 EXPECT_CALL(*connection, CreateCharacteristicsFinder(_, _))
831 .WillOnce(DoAll(
832 SaveArg<0>(&characteristics_finder_success_callback_),
833 SaveArg<1>(&characteristics_finder_error_callback_),
834 Return(new NiceMock<MockBluetoothLowEnergyCharacteristicsFinder>)));
835
836 create_gatt_connection_success_callback_.Run(
837 base::WrapUnique(new NiceMock<device::MockBluetoothGattConnection>(
838 adapter_, kTestRemoteDeviceBluetoothAddress)));
839
840 CharacteristicsFound(connection.get());
841 NotifySessionStarted(connection.get());
842 ConnectionResponseReceived(connection.get(), kDefaultMaxPacketSize);
843 }
844
845 } // namespace weave
846
847 } // namespace proximity_auth
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698