File: chrome_serial_realtarget_browsertest.cc

package info (click to toggle)
chromium 140.0.7339.185-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 6,193,740 kB
  • sloc: cpp: 35,093,945; ansic: 7,161,670; javascript: 4,199,694; python: 1,441,797; asm: 949,904; xml: 747,515; pascal: 187,748; perl: 88,691; sh: 88,248; objc: 79,953; sql: 52,714; cs: 44,599; fortran: 24,137; makefile: 22,114; tcl: 15,277; php: 13,980; yacc: 9,000; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (259 lines) | stat: -rw-r--r-- 9,854 bytes parent folder | download | duplicates (5)
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
// Copyright 2025 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <memory>

#include "base/strings/stringprintf.h"
#include "base/test/bind.h"
#include "base/test/test_future.h"
#include "chrome/browser/serial/chrome_serial_delegate.h"
#include "chrome/browser/serial/web_serial_chooser.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/serial/serial_chooser_controller.h"
#include "chrome/browser/ui/tabs/tab_strip_model.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "chrome/test/base/ui_test_utils.h"
#include "content/public/browser/content_browser_client.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/common/content_client.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/browser_test_utils.h"
#include "device/bluetooth/bluetooth_adapter.h"
#include "device/bluetooth/bluetooth_adapter_factory.h"
#include "device/bluetooth/bluetooth_device.h"
#include "device/bluetooth/bluetooth_socket.h"
#include "device/bluetooth/public/cpp/bluetooth_uuid.h"

namespace {

constexpr int kMicroBitVendorId = 0x0d28;
constexpr int kMicroBitProductId = 0x0204;
constexpr std::string_view kPixelBudsProSerialPortUuid =
    "25e97ff7-24ce-4c4c-8951-f764a708f7b5";

// The chooser view that will select the first device in the list upon the list
// initialization or the first device added.
class SerialRealTargetTestChooserView
    : public permissions::ChooserController::View {
 public:
  explicit SerialRealTargetTestChooserView(
      std::unique_ptr<permissions::ChooserController> controller)
      : controller_(std::move(controller)) {
    controller_->set_view(this);
  }
  SerialRealTargetTestChooserView(const SerialRealTargetTestChooserView&) =
      delete;
  SerialRealTargetTestChooserView& operator=(
      const SerialRealTargetTestChooserView&) = delete;

  ~SerialRealTargetTestChooserView() override {
    controller_->set_view(nullptr);
  }

  void OnOptionsInitialized() override {
    if (!selected_ && controller_->NumOptions() > 0) {
      controller_->Select({0});
      selected_ = true;
    }
  }

  void OnOptionAdded(size_t index) override {
    if (!selected_ && controller_->NumOptions() > 0) {
      controller_->Select({0});
      selected_ = true;
    }
  }
  void OnOptionRemoved(size_t index) override {}
  void OnOptionUpdated(size_t index) override {}
  void OnAdapterEnabledChanged(bool enabled) override {}
  void OnRefreshStateChanged(bool refreshing) override {}

 private:
  std::unique_ptr<permissions::ChooserController> controller_;
  bool selected_ = false;
};

class SerialRealTargetTestChooser : public WebSerialChooser {
 public:
  SerialRealTargetTestChooser() = default;
  SerialRealTargetTestChooser(const SerialRealTargetTestChooser&) = delete;
  SerialRealTargetTestChooser& operator=(const SerialRealTargetTestChooser&) =
      delete;
  ~SerialRealTargetTestChooser() override = default;

  void ShowChooser(
      content::RenderFrameHost* frame,
      std::unique_ptr<SerialChooserController> controller) override {
    view_ = std::make_unique<SerialRealTargetTestChooserView>(
        std::move(controller));
  }

 private:
  std::unique_ptr<SerialRealTargetTestChooserView> view_;
};

class SerialRealTargetTestDelegate : public ChromeSerialDelegate {
 public:
  SerialRealTargetTestDelegate() = default;
  ~SerialRealTargetTestDelegate() override = default;

  std::unique_ptr<content::SerialChooser> RunChooser(
      content::RenderFrameHost* frame,
      std::vector<blink::mojom::SerialPortFilterPtr> filters,
      std::vector<device::BluetoothUUID> allowed_bluetooth_service_class_ids,
      content::SerialChooser::Callback callback) override {
    auto chooser = std::make_unique<SerialRealTargetTestChooser>();
    chooser->ShowChooser(frame,
                         std::make_unique<SerialChooserController>(
                             frame, std::move(filters),
                             std::move(allowed_bluetooth_service_class_ids),
                             std::move(callback)));
    return chooser;
  }
};

class TestContentBrowserClient : public content::ContentBrowserClient {
 public:
  TestContentBrowserClient()
      : serial_delegate_(std::make_unique<SerialRealTargetTestDelegate>()) {}
  ~TestContentBrowserClient() override = default;

  content::SerialDelegate* GetSerialDelegate() override {
    return serial_delegate_.get();
  }

  void SetAsBrowserClient() {
    original_content_browser_client_ =
        content::SetBrowserClientForTesting(this);
  }

  void UnsetAsBrowserClient() {
    content::SetBrowserClientForTesting(original_content_browser_client_);
    serial_delegate_.reset();
  }

 private:
  std::unique_ptr<SerialRealTargetTestDelegate> serial_delegate_;
  raw_ptr<content::ContentBrowserClient> original_content_browser_client_ =
      nullptr;
};

class SerialRealTargetTest : public InProcessBrowserTest {
 public:
  void SetUpOnMainThread() override {
    embedded_test_server()->ServeFilesFromSourceDirectory("content/test/data");
    ASSERT_TRUE(embedded_test_server()->Start());

    test_content_browser_client_.SetAsBrowserClient();

    GURL url = embedded_test_server()->GetURL("localhost", "/simple_page.html");
    EXPECT_TRUE(ui_test_utils::NavigateToURL(browser(), url));

    content::RenderFrameHost* render_frame_host = browser()
                                                      ->tab_strip_model()
                                                      ->GetActiveWebContents()
                                                      ->GetPrimaryMainFrame();
    EXPECT_EQ(url.DeprecatedGetOriginAsURL(),
              render_frame_host->GetLastCommittedOrigin().GetURL());
  }

  void TearDownOnMainThread() override {
    test_content_browser_client_.UnsetAsBrowserClient();
  }

  // Attempt socket connection with `uuid_string` to all bluetooth devices known
  // to the adapter.
  void AttemptSocketConnectionToBluetoothDevices(std::string uuid_string) {
    base::test::TestFuture<scoped_refptr<device::BluetoothAdapter>>
        adapter_future;
    device::BluetoothAdapterFactory::Get()->GetAdapter(
        adapter_future.GetCallback());

    scoped_refptr<device::BluetoothAdapter> adapter = adapter_future.Get();
    ASSERT_TRUE(adapter);
    for (auto* device : adapter->GetDevices()) {
      base::test::TestFuture<scoped_refptr<device::BluetoothSocket>>
          socket_future;
      auto split_callback =
          base::SplitOnceCallback(socket_future.GetCallback());

      LOG(INFO) << "Attempt socket connection with " << uuid_string
                << " to device " << device->GetNameForDisplay();
      // The purpose of this function is to make the system to talk to bluetooth
      // devices so UUIDs of the devices will be known to the system, which
      // avoid issue like empty UUIDs in BluetoothDevice when testing after
      // system reboot.
      device->ConnectToService(
          device::BluetoothUUID(uuid_string), std::move(split_callback.first),
          base::BindLambdaForTesting([&](const std::string& message) {
            std::move(split_callback.second).Run(nullptr);
          }));
      scoped_refptr<device::BluetoothSocket> socket = socket_future.Get();
      if (socket) {
        base::test::TestFuture<void> disconnect_future;
        socket->Disconnect(disconnect_future.GetCallback());
        ASSERT_TRUE(disconnect_future.Wait());
      }
    }
  }

 private:
  TestContentBrowserClient test_content_browser_client_;
};

IN_PROC_BROWSER_TEST_F(SerialRealTargetTest, SerialOpenAndClosePort) {
  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  auto test_script = base::StringPrintf(
      R"((async () => {
            let port = await navigator.serial.requestPort(
              {filters: [{ usbVendorId: %d, usbProductId: %d }]}
            );
            await port.open({ baudRate: 115200 });
            let result = port.connected;
            await port.close();
            return result;
      })())",
      kMicroBitVendorId, kMicroBitProductId);
  EXPECT_EQ(true, EvalJs(web_contents, test_script));
}

IN_PROC_BROWSER_TEST_F(SerialRealTargetTest, BluetoothSerialOpenAndClosePort) {
  // This step is to make the target bluetooth device connected to the system,
  // to reduce flaky when running Serial Bluetooth test.
  AttemptSocketConnectionToBluetoothDevices(
      std::string(kPixelBudsProSerialPortUuid));
  content::WebContents* web_contents =
      browser()->tab_strip_model()->GetActiveWebContents();
  auto test_script = base::StringPrintf(
      R"((async () => {
            const uuids=['%s'];
            let port = await navigator.serial.requestPort({
              allowedBluetoothServiceClassIds:uuids, filters:[
                {bluetoothServiceClassId:uuids[0]}
              ]
            });
            // The retry here is because the pixel bud in the lab is in the case
            // with lid opened, where the first open attempt would fail.
            async function openPortWithRetry(port, maxRetries = 2) {
              for (let retry = 0; retry < maxRetries; retry++) {
                try {
                  await port.open({ baudRate: 115200 });
                  return;
                } catch (error) {
                  await new Promise(resolve => setTimeout(resolve, 1000));
                }
              }
              throw new Error('Failed to open port after multiple attempts.');
            }
            await openPortWithRetry(port);
            let result = port.connected;
            await port.close();
            return result;
      })())",
      kPixelBudsProSerialPortUuid);
  EXPECT_EQ(true, EvalJs(web_contents, test_script));
}

}  // namespace