• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //
2 //  Copyright 2015 Google, Inc.
3 //
4 //  Licensed under the Apache License, Version 2.0 (the "License");
5 //  you may not use this file except in compliance with the License.
6 //  You may obtain a copy of the License at:
7 //
8 //  http://www.apache.org/licenses/LICENSE-2.0
9 //
10 //  Unless required by applicable law or agreed to in writing, software
11 //  distributed under the License is distributed on an "AS IS" BASIS,
12 //  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 //  See the License for the specific language governing permissions and
14 //  limitations under the License.
15 //
16 
17 #include <base/macros.h>
18 #include <gmock/gmock.h>
19 #include <gtest/gtest.h>
20 
21 #include "service/adapter.h"
22 #include "service/hal/fake_bluetooth_gatt_interface.h"
23 #include "service/low_energy_client.h"
24 #include "stack/include/bt_types.h"
25 #include "stack/include/hcidefs.h"
26 #include "test/mock_adapter.h"
27 #include "types/bt_transport.h"
28 
29 using ::testing::_;
30 using ::testing::Return;
31 using ::testing::Pointee;
32 using ::testing::DoAll;
33 using ::testing::Invoke;
34 
35 namespace bluetooth {
36 namespace {
37 
38 class MockGattHandler
39     : public hal::FakeBluetoothGattInterface::TestClientHandler {
40  public:
MockGattHandler()41   MockGattHandler(){};
42   ~MockGattHandler() override = default;
43 
44   MOCK_METHOD2(RegisterClient,
45                bt_status_t(const bluetooth::Uuid&, bool eatt_support));
46   MOCK_METHOD1(UnregisterClient, bt_status_t(int));
47   MOCK_METHOD4(Connect, bt_status_t(int, const RawAddress&, bool, int));
48   MOCK_METHOD3(Disconnect, bt_status_t(int, const RawAddress&, int));
49 
50  private:
51   DISALLOW_COPY_AND_ASSIGN(MockGattHandler);
52 };
53 
54 class TestDelegate : public LowEnergyClient::Delegate {
55  public:
TestDelegate()56   TestDelegate() : connection_state_count_(0), last_mtu_(0) {}
57 
58   ~TestDelegate() override = default;
59 
connection_state_count() const60   int connection_state_count() const { return connection_state_count_; }
61 
OnConnectionState(LowEnergyClient * client,int status,const char * address,bool connected)62   void OnConnectionState(LowEnergyClient* client, int status,
63                          const char* address, bool connected) override {
64     ASSERT_TRUE(client);
65     connection_state_count_++;
66   }
67 
OnMtuChanged(LowEnergyClient * client,int status,const char * address,int mtu)68   void OnMtuChanged(LowEnergyClient* client, int status, const char* address,
69                     int mtu) override {
70     ASSERT_TRUE(client);
71     last_mtu_ = mtu;
72   }
73 
74  private:
75   int connection_state_count_;
76 
77   int last_mtu_;
78 
79   DISALLOW_COPY_AND_ASSIGN(TestDelegate);
80 };
81 
82 class LowEnergyClientTest : public ::testing::Test {
83  public:
84   LowEnergyClientTest() = default;
85   ~LowEnergyClientTest() override = default;
86 
SetUp()87   void SetUp() override {
88     // Only set |mock_handler_| if a test hasn't set it.
89     if (!mock_handler_) mock_handler_.reset(new MockGattHandler());
90     fake_hal_gatt_iface_ = new hal::FakeBluetoothGattInterface(
91         nullptr, nullptr,
92         std::static_pointer_cast<
93             hal::FakeBluetoothGattInterface::TestClientHandler>(mock_handler_),
94         nullptr);
95     hal::BluetoothGattInterface::InitializeForTesting(fake_hal_gatt_iface_);
96     ble_factory_.reset(new LowEnergyClientFactory(mock_adapter_));
97   }
98 
TearDown()99   void TearDown() override {
100     ble_factory_.reset();
101     hal::BluetoothGattInterface::CleanUp();
102   }
103 
104  protected:
105   hal::FakeBluetoothGattInterface* fake_hal_gatt_iface_;
106   testing::MockAdapter mock_adapter_;
107   std::shared_ptr<MockGattHandler> mock_handler_;
108   std::unique_ptr<LowEnergyClientFactory> ble_factory_;
109 
110  private:
111   DISALLOW_COPY_AND_ASSIGN(LowEnergyClientTest);
112 };
113 
114 // Used for tests that operate on a pre-registered client.
115 class LowEnergyClientPostRegisterTest : public LowEnergyClientTest {
116  public:
LowEnergyClientPostRegisterTest()117   LowEnergyClientPostRegisterTest() : next_client_id_(0) {}
118   ~LowEnergyClientPostRegisterTest() override = default;
119 
SetUp()120   void SetUp() override {
121     LowEnergyClientTest::SetUp();
122     auto callback = [&](std::unique_ptr<LowEnergyClient> client) {
123       le_client_ = std::move(client);
124     };
125     RegisterTestClient(callback);
126   }
127 
TearDown()128   void TearDown() override {
129     EXPECT_CALL(*mock_handler_, UnregisterClient(_))
130         .Times(1)
131         .WillOnce(Return(BT_STATUS_SUCCESS));
132     le_client_.reset();
133     LowEnergyClientTest::TearDown();
134   }
135 
RegisterTestClient(const std::function<void (std::unique_ptr<LowEnergyClient> client)> callback)136   void RegisterTestClient(
137       const std::function<void(std::unique_ptr<LowEnergyClient> client)>
138           callback) {
139     Uuid uuid = Uuid::GetRandom();
140     auto api_callback = [&](BLEStatus status, const Uuid& in_uuid,
141                             std::unique_ptr<BluetoothInstance> in_client) {
142       CHECK(in_uuid == uuid);
143       CHECK(in_client.get());
144       CHECK(status == BLE_STATUS_SUCCESS);
145 
146       callback(std::unique_ptr<LowEnergyClient>(
147           static_cast<LowEnergyClient*>(in_client.release())));
148     };
149 
150     EXPECT_CALL(*mock_handler_, RegisterClient(_, _))
151         .Times(1)
152         .WillOnce(Return(BT_STATUS_SUCCESS));
153 
154     ble_factory_->RegisterInstance(uuid, api_callback);
155 
156     fake_hal_gatt_iface_->NotifyRegisterClientCallback(0, next_client_id_++,
157                                                        uuid);
158     ::testing::Mock::VerifyAndClearExpectations(mock_handler_.get());
159   }
160 
161  protected:
162   std::unique_ptr<LowEnergyClient> le_client_;
163 
164  private:
165   int next_client_id_;
166 
167   DISALLOW_COPY_AND_ASSIGN(LowEnergyClientPostRegisterTest);
168 };
169 
TEST_F(LowEnergyClientTest,RegisterInstance)170 TEST_F(LowEnergyClientTest, RegisterInstance) {
171   EXPECT_CALL(*mock_handler_, RegisterClient(_, _))
172       .Times(2)
173       .WillOnce(Return(BT_STATUS_FAIL))
174       .WillOnce(Return(BT_STATUS_SUCCESS));
175 
176   // These will be asynchronously populated with a result when the callback
177   // executes.
178   BLEStatus status = BLE_STATUS_SUCCESS;
179   Uuid cb_uuid;
180   std::unique_ptr<LowEnergyClient> client;
181   int callback_count = 0;
182 
183   auto callback = [&](BLEStatus in_status, const Uuid& uuid,
184                       std::unique_ptr<BluetoothInstance> in_client) {
185     status = in_status;
186     cb_uuid = uuid;
187     client = std::unique_ptr<LowEnergyClient>(
188         static_cast<LowEnergyClient*>(in_client.release()));
189     callback_count++;
190   };
191 
192   Uuid uuid0 = Uuid::GetRandom();
193 
194   // HAL returns failure.
195   EXPECT_FALSE(ble_factory_->RegisterInstance(uuid0, callback));
196   EXPECT_EQ(0, callback_count);
197 
198   // HAL returns success.
199   EXPECT_TRUE(ble_factory_->RegisterInstance(uuid0, callback));
200   EXPECT_EQ(0, callback_count);
201 
202   // Calling twice with the same Uuid should fail with no additional call into
203   // the stack.
204   EXPECT_FALSE(ble_factory_->RegisterInstance(uuid0, callback));
205 
206   ::testing::Mock::VerifyAndClearExpectations(mock_handler_.get());
207 
208   // Call with a different Uuid while one is pending.
209   Uuid uuid1 = Uuid::GetRandom();
210   EXPECT_CALL(*mock_handler_, RegisterClient(_, _))
211       .Times(1)
212       .WillOnce(Return(BT_STATUS_SUCCESS));
213   EXPECT_TRUE(ble_factory_->RegisterInstance(uuid1, callback));
214 
215   // Trigger callback with an unknown Uuid. This should get ignored.
216   Uuid uuid2 = Uuid::GetRandom();
217   fake_hal_gatt_iface_->NotifyRegisterClientCallback(0, 0, uuid2);
218   EXPECT_EQ(0, callback_count);
219 
220   // |uuid0| succeeds.
221   int client_if0 = 2;  // Pick something that's not 0.
222   fake_hal_gatt_iface_->NotifyRegisterClientCallback(BT_STATUS_SUCCESS,
223                                                      client_if0, uuid0);
224 
225   EXPECT_EQ(1, callback_count);
226   ASSERT_TRUE(client.get() != nullptr);  // Assert to terminate in case of error
227   EXPECT_EQ(BLE_STATUS_SUCCESS, status);
228   EXPECT_EQ(client_if0, client->GetInstanceId());
229   EXPECT_EQ(uuid0, client->GetAppIdentifier());
230   EXPECT_EQ(uuid0, cb_uuid);
231 
232   // The client should unregister itself when deleted.
233   EXPECT_CALL(*mock_handler_, UnregisterClient(client_if0))
234       .Times(1)
235       .WillOnce(Return(BT_STATUS_SUCCESS));
236   client.reset();
237   ::testing::Mock::VerifyAndClearExpectations(mock_handler_.get());
238 
239   // |uuid1| fails.
240   int client_if1 = 3;
241   fake_hal_gatt_iface_->NotifyRegisterClientCallback(BT_STATUS_FAIL, client_if1,
242                                                      uuid1);
243 
244   EXPECT_EQ(2, callback_count);
245   ASSERT_TRUE(client.get() == nullptr);  // Assert to terminate in case of error
246   EXPECT_EQ(BLE_STATUS_FAILURE, status);
247   EXPECT_EQ(uuid1, cb_uuid);
248 }
249 
250 MATCHER_P(BitEq, x, std::string(negation ? "isn't" : "is") +
251                         " bitwise equal to " + ::testing::PrintToString(x)) {
252   static_assert(sizeof(x) == sizeof(arg), "Size mismatch");
253   return std::memcmp(&arg, &x, sizeof(x)) == 0;
254 }
255 
TEST_F(LowEnergyClientPostRegisterTest,Connect)256 TEST_F(LowEnergyClientPostRegisterTest, Connect) {
257   const RawAddress kTestAddress = {{0x01, 0x02, 0x03, 0x0A, 0x0B, 0x0C}};
258   const char kTestAddressStr[] = "01:02:03:0A:0B:0C";
259   const bool kTestDirect = false;
260   const int connId = 12;
261 
262   TestDelegate delegate;
263   le_client_->SetDelegate(&delegate);
264 
265   // TODO(jpawlowski): NotifyConnectCallback should be called after returning
266   // success, fix it when it becomes important.
267   // These should succeed and result in a HAL call
268   EXPECT_CALL(*mock_handler_,
269               Connect(le_client_->GetInstanceId(), BitEq(kTestAddress),
270                       kTestDirect, BT_TRANSPORT_LE))
271       .Times(1)
272       .WillOnce(DoAll(Invoke([&](int client_id, const RawAddress& bd_addr,
273                                  bool is_direct, int transport) {
274                         fake_hal_gatt_iface_->NotifyConnectCallback(
275                             connId, BT_STATUS_SUCCESS, client_id, bd_addr);
276                       }),
277                       Return(BT_STATUS_SUCCESS)));
278 
279   EXPECT_TRUE(le_client_->Connect(kTestAddressStr, kTestDirect));
280   EXPECT_EQ(1, delegate.connection_state_count());
281 
282   // TODO(jpawlowski): same as above
283   // These should succeed and result in a HAL call
284   EXPECT_CALL(*mock_handler_, Disconnect(le_client_->GetInstanceId(),
285                                          BitEq(kTestAddress), connId))
286       .Times(1)
287       .WillOnce(DoAll(
288           Invoke([&](int client_id, const RawAddress& bd_addr, int connId) {
289             fake_hal_gatt_iface_->NotifyDisconnectCallback(
290                 connId, BT_STATUS_SUCCESS, client_id, bd_addr);
291           }),
292           Return(BT_STATUS_SUCCESS)));
293 
294   EXPECT_TRUE(le_client_->Disconnect(kTestAddressStr));
295   EXPECT_EQ(2, delegate.connection_state_count());
296 
297   le_client_->SetDelegate(nullptr);
298   ::testing::Mock::VerifyAndClearExpectations(mock_handler_.get());
299 }
300 
301 }  // namespace
302 }  // namespace bluetooth
303