summaryrefslogtreecommitdiff
path: root/chromium/extensions/browser/api/bluetooth/bluetooth_private_apitest.cc
blob: 65adb8a379e27cb6bb80cb570c46f2f0d036124f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <utility>

#include "base/command_line.h"
#include "base/memory/ref_counted.h"
#include "base/memory/scoped_ptr.h"
#include "build/build_config.h"
#include "chrome/browser/extensions/extension_apitest.h"
#include "device/bluetooth/test/mock_bluetooth_adapter.h"
#include "device/bluetooth/test/mock_bluetooth_device.h"
#include "device/bluetooth/test/mock_bluetooth_discovery_session.h"
#include "extensions/browser/api/bluetooth/bluetooth_api.h"
#include "extensions/browser/api/bluetooth/bluetooth_event_router.h"
#include "extensions/browser/event_router.h"
#include "extensions/common/api/bluetooth_private.h"
#include "extensions/common/switches.h"
#include "testing/gmock/include/gmock/gmock.h"

using device::BluetoothDiscoveryFilter;
using device::BluetoothUUID;
using device::MockBluetoothAdapter;
using device::MockBluetoothDevice;
using device::MockBluetoothDiscoverySession;
using testing::_;
using testing::Eq;
using testing::InSequence;
using testing::NiceMock;
using testing::Return;
using testing::ReturnPointee;
using testing::SaveArg;
using testing::WithArgs;
using testing::WithoutArgs;

namespace bt = extensions::api::bluetooth;
namespace bt_private = extensions::api::bluetooth_private;

namespace extensions {

namespace {
const char kTestExtensionId[] = "jofgjdphhceggjecimellaapdjjadibj";
const char kAdapterName[] = "Helix";
const char kDeviceName[] = "Red";
const char kDeviceAddress[] = "11:12:13:14:15:16";

MATCHER_P(IsFilterEqual, a, "") {
  return arg->Equals(*a);
}
}

class BluetoothPrivateApiTest : public ExtensionApiTest {
 public:
  BluetoothPrivateApiTest()
      : adapter_name_(kAdapterName),
        adapter_powered_(false),
        adapter_discoverable_(false) {}

  ~BluetoothPrivateApiTest() override {}

  void SetUpOnMainThread() override {
    base::CommandLine::ForCurrentProcess()->AppendSwitchASCII(
        switches::kWhitelistedExtensionID, kTestExtensionId);
    mock_adapter_ = new NiceMock<MockBluetoothAdapter>();
    event_router()->SetAdapterForTest(mock_adapter_.get());
    mock_device_.reset(new NiceMock<MockBluetoothDevice>(
        mock_adapter_.get(), 0, kDeviceName, kDeviceAddress, false, false));
    ON_CALL(*mock_adapter_.get(), GetDevice(kDeviceAddress))
        .WillByDefault(Return(mock_device_.get()));
    ON_CALL(*mock_adapter_.get(), IsPresent()).WillByDefault(Return(true));
  }

  void TearDownOnMainThread() override {}

  BluetoothEventRouter* event_router() {
    return BluetoothAPI::Get(browser()->profile())->event_router();
  }

  void SetName(const std::string& name, const base::Closure& callback) {
    adapter_name_ = name;
    callback.Run();
  }

  void SetPowered(bool powered, const base::Closure& callback) {
    adapter_powered_ = powered;
    callback.Run();
  }

  void ForgetDevice(const base::Closure& callback) {
    mock_device_.reset();
    event_router()->SetAdapterForTest(nullptr);
    callback.Run();
  }

  void SetDiscoverable(bool discoverable, const base::Closure& callback) {
    adapter_discoverable_ = discoverable;
    callback.Run();
  }

  void DispatchPairingEvent(bt_private::PairingEventType pairing_event_type) {
    bt_private::PairingEvent pairing_event;
    pairing_event.pairing = pairing_event_type;
    pairing_event.device.name.reset(new std::string(kDeviceName));
    pairing_event.device.address = mock_device_->GetAddress();
    pairing_event.device.vendor_id_source = bt::VENDOR_ID_SOURCE_USB;
    pairing_event.device.type = bt::DEVICE_TYPE_PHONE;

    scoped_ptr<base::ListValue> args =
        bt_private::OnPairing::Create(pairing_event);
    scoped_ptr<Event> event(new Event(events::BLUETOOTH_PRIVATE_ON_PAIRING,
                                      bt_private::OnPairing::kEventName,
                                      std::move(args)));
    EventRouter::Get(browser()->profile())
        ->DispatchEventToExtension(kTestExtensionId, std::move(event));
  }

  void DispatchAuthorizePairingEvent() {
    DispatchPairingEvent(bt_private::PAIRING_EVENT_TYPE_REQUESTAUTHORIZATION);
  }

  void DispatchPincodePairingEvent() {
    DispatchPairingEvent(bt_private::PAIRING_EVENT_TYPE_REQUESTPINCODE);
  }

  void DispatchPasskeyPairingEvent() {
    DispatchPairingEvent(bt_private::PAIRING_EVENT_TYPE_REQUESTPASSKEY);
  }

  void DispatchConfirmPasskeyPairingEvent() {
    DispatchPairingEvent(bt_private::PAIRING_EVENT_TYPE_CONFIRMPASSKEY);
  }

  void CallSetDiscoveryFilterCallback(
      device::BluetoothAdapter::DiscoverySessionCallback callback) {
    auto session_ptr = scoped_ptr<NiceMock<MockBluetoothDiscoverySession>>(
        mock_discovery_session_);

    callback.Run(std::move(session_ptr));
  }

 protected:
  std::string adapter_name_;
  bool adapter_powered_;
  bool adapter_discoverable_;

  scoped_refptr<NiceMock<MockBluetoothAdapter> > mock_adapter_;
  scoped_ptr<NiceMock<MockBluetoothDevice> > mock_device_;

  // This discovery session will be owned by EventRouter, we'll only keep
  // pointer to it.
  NiceMock<MockBluetoothDiscoverySession>* mock_discovery_session_;
};

ACTION_TEMPLATE(InvokeCallbackArgument,
                HAS_1_TEMPLATE_PARAMS(int, k),
                AND_0_VALUE_PARAMS()) {
  ::std::tr1::get<k>(args).Run();
}

IN_PROC_BROWSER_TEST_F(BluetoothPrivateApiTest, SetAdapterState) {
  ON_CALL(*mock_adapter_.get(), GetName())
      .WillByDefault(ReturnPointee(&adapter_name_));
  ON_CALL(*mock_adapter_.get(), IsPowered())
      .WillByDefault(ReturnPointee(&adapter_powered_));
  ON_CALL(*mock_adapter_.get(), IsDiscoverable())
      .WillByDefault(ReturnPointee(&adapter_discoverable_));

  EXPECT_CALL(*mock_adapter_.get(), SetName("Dome", _, _)).WillOnce(
      WithArgs<0, 1>(Invoke(this, &BluetoothPrivateApiTest::SetName)));
  EXPECT_CALL(*mock_adapter_.get(), SetPowered(true, _, _)).WillOnce(
      WithArgs<0, 1>(Invoke(this, &BluetoothPrivateApiTest::SetPowered)));
  EXPECT_CALL(*mock_adapter_.get(), SetDiscoverable(true, _, _)).WillOnce(
      WithArgs<0, 1>(Invoke(this, &BluetoothPrivateApiTest::SetDiscoverable)));

  ASSERT_TRUE(RunComponentExtensionTest("bluetooth_private/adapter_state"))
      << message_;
}

IN_PROC_BROWSER_TEST_F(BluetoothPrivateApiTest, NoBluetoothAdapter) {
  ON_CALL(*mock_adapter_.get(), IsPresent()).WillByDefault(Return(false));
  ASSERT_TRUE(RunComponentExtensionTest("bluetooth_private/no_adapter"))
      << message_;
}

IN_PROC_BROWSER_TEST_F(BluetoothPrivateApiTest, CancelPairing) {
  InSequence s;
  EXPECT_CALL(*mock_adapter_.get(),
              AddPairingDelegate(
                  _, device::BluetoothAdapter::PAIRING_DELEGATE_PRIORITY_HIGH))
      .WillOnce(WithoutArgs(Invoke(
          this, &BluetoothPrivateApiTest::DispatchAuthorizePairingEvent)));
  EXPECT_CALL(*mock_device_, ExpectingConfirmation())
      .WillRepeatedly(Return(true));
  EXPECT_CALL(*mock_device_, CancelPairing());
  ASSERT_TRUE(RunComponentExtensionTest("bluetooth_private/cancel_pairing"))
      << message_;
}

IN_PROC_BROWSER_TEST_F(BluetoothPrivateApiTest, PincodePairing) {
  EXPECT_CALL(*mock_adapter_.get(),
              AddPairingDelegate(
                  _, device::BluetoothAdapter::PAIRING_DELEGATE_PRIORITY_HIGH))
      .WillOnce(WithoutArgs(
          Invoke(this, &BluetoothPrivateApiTest::DispatchPincodePairingEvent)));
  EXPECT_CALL(*mock_device_, ExpectingPinCode()).WillRepeatedly(Return(true));
  EXPECT_CALL(*mock_device_, SetPinCode("abbbbbbk"));
  ASSERT_TRUE(RunComponentExtensionTest("bluetooth_private/pincode_pairing"))
      << message_;
}

IN_PROC_BROWSER_TEST_F(BluetoothPrivateApiTest, PasskeyPairing) {
  EXPECT_CALL(*mock_adapter_.get(),
              AddPairingDelegate(
                  _, device::BluetoothAdapter::PAIRING_DELEGATE_PRIORITY_HIGH))
      .WillOnce(WithoutArgs(
          Invoke(this, &BluetoothPrivateApiTest::DispatchPasskeyPairingEvent)));
  EXPECT_CALL(*mock_device_, ExpectingPasskey()).WillRepeatedly(Return(true));
  EXPECT_CALL(*mock_device_, SetPasskey(900531));
  ASSERT_TRUE(RunComponentExtensionTest("bluetooth_private/passkey_pairing"))
      << message_;
}

IN_PROC_BROWSER_TEST_F(BluetoothPrivateApiTest, DisconnectAll) {
  EXPECT_CALL(*mock_device_, IsConnected())
      .Times(6)
      .WillOnce(Return(false))
      .WillOnce(Return(true))
      .WillOnce(Return(false))
      .WillRepeatedly(Return(true));
  EXPECT_CALL(*mock_device_, Disconnect(_, _))
      .Times(3)
      .WillOnce(InvokeCallbackArgument<1>())
      .WillOnce(InvokeCallbackArgument<1>())
      .WillOnce(InvokeCallbackArgument<0>());
  ASSERT_TRUE(RunComponentExtensionTest("bluetooth_private/disconnect"))
      << message_;
}

// Device::Forget not implemented on OSX.
#if !defined(OS_MACOSX)
IN_PROC_BROWSER_TEST_F(BluetoothPrivateApiTest, ForgetDevice) {
  EXPECT_CALL(*mock_device_.get(), Forget(_, _))
      .WillOnce(
          WithArgs<0>(Invoke(this, &BluetoothPrivateApiTest::ForgetDevice)));
  ASSERT_TRUE(RunComponentExtensionTest("bluetooth_private/forget_device"))
      << message_;
}
#endif

IN_PROC_BROWSER_TEST_F(BluetoothPrivateApiTest, DiscoveryFilter) {
  mock_discovery_session_ = new NiceMock<MockBluetoothDiscoverySession>();

  BluetoothDiscoveryFilter discovery_filter(
      BluetoothDiscoveryFilter::Transport::TRANSPORT_LE);
  discovery_filter.SetPathloss(50);
  discovery_filter.AddUUID(BluetoothUUID("cafe"));
  discovery_filter.AddUUID(
      BluetoothUUID("0000bebe-0000-1000-8000-00805f9b34fb"));

  EXPECT_CALL(*mock_adapter_.get(), StartDiscoverySessionWithFilterRaw(
                                        IsFilterEqual(&discovery_filter), _, _))
      .Times(1)
      .WillOnce(WithArgs<1>(Invoke(
          this, &BluetoothPrivateApiTest::CallSetDiscoveryFilterCallback)));
  EXPECT_CALL(*mock_discovery_session_, IsActive())
      .Times(1)
      .WillOnce(Return(true));
  EXPECT_CALL(*mock_discovery_session_,
              SetDiscoveryFilterRaw(Eq(nullptr), _, _))
      .Times(1)
      .WillOnce(InvokeCallbackArgument<1>());
  ASSERT_TRUE(RunComponentExtensionTest("bluetooth_private/discovery_filter"))
      << message_;
}

IN_PROC_BROWSER_TEST_F(BluetoothPrivateApiTest, Connect) {
  EXPECT_CALL(*mock_device_.get(), IsConnected())
      .Times(2)
      .WillOnce(Return(false))
      .WillOnce(Return(true));
  EXPECT_CALL(*mock_device_.get(), Connect(_, _, _))
      .WillOnce(InvokeCallbackArgument<1>());
  ASSERT_TRUE(RunComponentExtensionTest("bluetooth_private/connect"))
      << message_;
}

IN_PROC_BROWSER_TEST_F(BluetoothPrivateApiTest, Pair) {
  EXPECT_CALL(*mock_adapter_.get(),
              AddPairingDelegate(
                  _, device::BluetoothAdapter::PAIRING_DELEGATE_PRIORITY_HIGH));
  EXPECT_CALL(*mock_device_, ExpectingConfirmation())
      .WillRepeatedly(Return(true));
  EXPECT_CALL(*mock_device_.get(), Pair(_, _, _))
      .WillOnce(DoAll(
          WithoutArgs(Invoke(
              this,
              &BluetoothPrivateApiTest::DispatchConfirmPasskeyPairingEvent)),
          InvokeCallbackArgument<1>()));
  ASSERT_TRUE(RunComponentExtensionTest("bluetooth_private/pair")) << message_;
}

}  // namespace extensions