File: ash_web_view_impl_browsertest.cc

package info (click to toggle)
chromium 138.0.7204.183-1~deb12u1
  • links: PTS, VCS
  • area: main
  • in suites: bookworm-proposed-updates
  • size: 6,080,960 kB
  • sloc: cpp: 34,937,079; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,954; asm: 946,768; xml: 739,971; pascal: 187,324; sh: 89,623; perl: 88,663; objc: 79,944; sql: 50,304; cs: 41,786; fortran: 24,137; makefile: 21,811; php: 13,980; tcl: 13,166; yacc: 8,925; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (360 lines) | stat: -rw-r--r-- 15,348 bytes parent folder | download | duplicates (4)
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
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
// Copyright 2020 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "chrome/browser/ui/ash/web_view/ash_web_view_impl.h"

#include <memory>
#include <string>

#include "ash/public/cpp/ash_web_view.h"
#include "ash/public/cpp/ash_web_view_factory.h"
#include "base/run_loop.h"
#include "base/scoped_observation.h"
#include "base/strings/stringprintf.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/test/base/in_process_browser_test.h"
#include "content/public/browser/host_zoom_map.h"
#include "content/public/browser/render_frame_host.h"
#include "content/public/browser/render_view_host.h"
#include "content/public/test/browser_test.h"
#include "content/public/test/test_navigation_observer.h"
#include "content/public/test/test_utils.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/views/controls/webview/webview.h"
#include "ui/views/view.h"
#include "ui/views/view_observer.h"
#include "ui/views/widget/widget.h"

namespace {

using ash::AshWebView;
using ash::AshWebViewFactory;

// Macros ----------------------------------------------------------------------

#define EXPECT_PREFERRED_SIZE(web_view_, expected_preferred_size_)         \
  {                                                                        \
    MockViewObserver mock;                                                 \
    base::ScopedObservation<views::View, views::ViewObserver> observation{ \
        &mock};                                                            \
    observation.Observe(static_cast<views::View*>(web_view_));             \
                                                                           \
    constexpr int max_change_count = 3;                                    \
    int change_count = 0;                                                  \
    base::RunLoop run_loop;                                                \
    EXPECT_CALL(mock, OnViewPreferredSizeChanged)                          \
        .WillRepeatedly(testing::Invoke([&](views::View* view) {           \
          if (expected_preferred_size_ != view->GetPreferredSize()) {      \
            ++change_count;                                                \
            if (change_count <= max_change_count) {                        \
              return;                                                      \
            }                                                              \
          }                                                                \
          EXPECT_EQ(expected_preferred_size_, view->GetPreferredSize());   \
          run_loop.QuitClosure().Run();                                    \
        }));                                                               \
    run_loop.Run();                                                        \
  }

#define EXPECT_DID_STOP_LOADING(web_view_)                                     \
  {                                                                            \
    MockAshWebViewObserver mock;                                               \
    base::ScopedObservation<AshWebView, AshWebView::Observer> obs{&mock};      \
    obs.Observe(web_view_);                                                    \
                                                                               \
    base::RunLoop run_loop;                                                    \
    EXPECT_CALL(mock, DidStopLoading).WillOnce(testing::Invoke([&run_loop]() { \
      run_loop.QuitClosure().Run();                                            \
    }));                                                                       \
    run_loop.Run();                                                            \
  }

#define EXPECT_DID_SUPPRESS_NAVIGATION(web_view_, expected_url_,          \
                                       expected_disposition_,             \
                                       expected_from_user_gesture_)       \
  {                                                                       \
    MockAshWebViewObserver mock;                                          \
    base::ScopedObservation<AshWebView, AshWebView::Observer> obs{&mock}; \
    obs.Observe(web_view_);                                               \
                                                                          \
    base::RunLoop run_loop;                                               \
    EXPECT_CALL(mock, DidSuppressNavigation)                              \
        .WillOnce(testing::Invoke([&](const GURL& url,                    \
                                      WindowOpenDisposition disposition,  \
                                      bool from_user_gesture) {           \
          EXPECT_EQ(expected_url_, url);                                  \
          EXPECT_EQ(expected_disposition_, disposition);                  \
          EXPECT_EQ(expected_from_user_gesture_, from_user_gesture);      \
          run_loop.QuitClosure().Run();                                   \
        }));                                                              \
    run_loop.Run();                                                       \
  }

#define EXPECT_DID_CHANGE_CAN_GO_BACK(web_view_, expected_can_go_back_)   \
  {                                                                       \
    MockAshWebViewObserver mock;                                          \
    base::ScopedObservation<AshWebView, AshWebView::Observer> obs{&mock}; \
    obs.Observe(web_view_);                                               \
                                                                          \
    base::RunLoop run_loop;                                               \
    EXPECT_CALL(mock, DidChangeCanGoBack)                                 \
        .WillOnce(testing::Invoke([&](bool can_go_back) {                 \
          EXPECT_EQ(expected_can_go_back_, can_go_back);                  \
          run_loop.QuitClosure().Run();                                   \
        }));                                                              \
    run_loop.Run();                                                       \
  }

// Helpers ---------------------------------------------------------------------

std::unique_ptr<views::Widget> CreateWidget(bool activatable = true) {
  auto widget = std::make_unique<views::Widget>();

  views::Widget::InitParams params(
      views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET,
      views::Widget::InitParams::TYPE_WINDOW_FRAMELESS);
  params.activatable = activatable
                           ? views::Widget::InitParams::Activatable::kDefault
                           : views::Widget::InitParams::Activatable::kNo;

  widget->Init(std::move(params));
  return widget;
}

GURL CreateDataUrlWithBody(const std::string& body) {
  return GURL(base::StringPrintf(R"(data:text/html,
      <html>
        <body>
          <style>
            * {
              margin: 0;
              padding: 0;
            }
          </style>
          %s
        </body>
      </html>
    )",
                                 body.c_str()));
}

GURL CreateDataUrl() {
  return CreateDataUrlWithBody(std::string());
}

// Mocks -----------------------------------------------------------------------

class MockViewObserver : public testing::NiceMock<views::ViewObserver> {
 public:
  // views::ViewObserver:
  MOCK_METHOD(void,
              OnViewPreferredSizeChanged,
              (views::View * view),
              (override));
};

class MockAshWebViewObserver : public testing::NiceMock<AshWebView::Observer> {
 public:
  // AshWebView::Observer:
  MOCK_METHOD(void, DidStopLoading, (), (override));

  MOCK_METHOD(void,
              DidSuppressNavigation,
              (const GURL& url,
               WindowOpenDisposition disposition,
               bool from_user_gesture),
              (override));

  MOCK_METHOD(void, DidChangeCanGoBack, (bool can_go_back), (override));
};

}  // namespace

// AshWebViewImplBrowserTest
// -------------AshWebViewImpl--------------------------------

class AshWebViewImplBrowserTest : public InProcessBrowserTest {
 public:
  AshWebViewImplBrowserTest() = default;
  AshWebViewImplBrowserTest(const AshWebViewImplBrowserTest&) = delete;
  AshWebViewImplBrowserTest& operator=(const AshWebViewImplBrowserTest&) =
      delete;
  ~AshWebViewImplBrowserTest() override = default;
};

// Tests -----------------------------------------------------------------------

// Tests that AshWebViewImpl will automatically update its preferred size
// to match the desired size of its hosted contents.
IN_PROC_BROWSER_TEST_F(AshWebViewImplBrowserTest, ShouldAutoResize) {
  AshWebView::InitParams params;
  params.enable_auto_resize = true;
  params.min_size = gfx::Size(600, 400);
  params.max_size = gfx::Size(800, 600);

  auto widget = CreateWidget();
  AshWebView* web_view =
      widget->SetContentsView(AshWebViewFactory::Get()->Create(params));

  // Verify auto-resizing within min/max bounds.
  web_view->Navigate(
      CreateDataUrlWithBody("<div style='width:700px; height:500px'></div>"));
  EXPECT_PREFERRED_SIZE(web_view, gfx::Size(700, 500));

  // Verify auto-resizing clamps to min bounds.
  web_view->Navigate(
      CreateDataUrlWithBody("<div style='width:0; height:0'></div>"));
  EXPECT_PREFERRED_SIZE(web_view, gfx::Size(600, 400));

  // Verify auto-resizing clamps to max bounds.
  web_view->Navigate(
      CreateDataUrlWithBody("<div style='width:1000px; height:1000px'></div>"));
  EXPECT_PREFERRED_SIZE(web_view, gfx::Size(800, 600));
}

// Tests that AshWebViewImpl will notify DidStopLoading() events.
IN_PROC_BROWSER_TEST_F(AshWebViewImplBrowserTest, ShouldNotifyDidStopLoading) {
  auto widget = CreateWidget();
  AshWebView* web_view = widget->SetContentsView(
      AshWebViewFactory::Get()->Create(AshWebView::InitParams()));

  web_view->Navigate(CreateDataUrl());
  EXPECT_DID_STOP_LOADING(web_view);
}

// Tests that AshWebViewImpl will notify DidSuppressNavigation() events.
IN_PROC_BROWSER_TEST_F(AshWebViewImplBrowserTest,
                       ShouldNotifyDidSuppressNavigation) {
  AshWebView::InitParams params;
  params.suppress_navigation = true;

  auto widget = CreateWidget();
  AshWebView* web_view = widget->SetContentsView(
      AshWebViewFactory::Get()->Create(std::move(params)));

  web_view->Navigate(CreateDataUrlWithBody(R"(
      <script>
        // Wait until window has finished loading.
        window.addEventListener("load", () => {

          // Perform simple click on an anchor within the same target.
          const anchor = document.createElement("a");
          anchor.href = "https://google.com/";
          anchor.click();

          // Wait for first click event to be flushed.
          setTimeout(() => {

            // Perform simple click on an anchor with "_blank" target.
            const anchor = document.createElement("a");
            anchor.href = "https://assistant.google.com/";
            anchor.target = "_blank";
            anchor.click();
          }, 0);
        });
      </script>
    )"));

  // Expect suppression of the first click event.
  EXPECT_DID_SUPPRESS_NAVIGATION(
      web_view, /*url=*/GURL("https://google.com/"),
      /*disposition=*/WindowOpenDisposition::CURRENT_TAB,
      /*from_user_gesture=*/false);

  // Expect suppression of the second click event.
  EXPECT_DID_SUPPRESS_NAVIGATION(
      web_view, /*url=*/GURL("https://assistant.google.com/"),
      /*disposition=*/WindowOpenDisposition::NEW_FOREGROUND_TAB,
      /*from_user_gesture=*/true);
}

// Tests that AshWebViewImpl will notify DidChangeCanGoBack() events.
IN_PROC_BROWSER_TEST_F(AshWebViewImplBrowserTest,
                       ShouldNotifyDidChangeCanGoBack) {
  auto widget = CreateWidget();
  AshWebView* web_view = widget->SetContentsView(
      AshWebViewFactory::Get()->Create(AshWebView::InitParams()));

  web_view->Navigate(CreateDataUrlWithBody("<div>First Page</div>"));
  EXPECT_DID_STOP_LOADING(web_view);

  web_view->Navigate(CreateDataUrlWithBody("<div>Second Page</div>"));
  EXPECT_DID_CHANGE_CAN_GO_BACK(web_view, /*can_go_back=*/true);

  web_view->GoBack();
  EXPECT_DID_CHANGE_CAN_GO_BACK(web_view, /*can_go_back=*/false);
}

IN_PROC_BROWSER_TEST_F(AshWebViewImplBrowserTest,
                       ShouldSetTemporaryZoomLevelToOne) {
  auto widget = CreateWidget();
  AshWebView::InitParams init_params;
  init_params.fix_zoom_level_to_one = true;

  AshWebView* web_view =
      widget->SetContentsView(AshWebViewFactory::Get()->Create(init_params));
  AshWebViewImpl* web_view_impl = static_cast<AshWebViewImpl*>(web_view);

  web_view->Navigate(CreateDataUrlWithBody("Hello"));
  EXPECT_DID_STOP_LOADING(web_view);

  // Confirm that temporary zoom level is set to 1.
  content::HostZoomMap* zoom_map =
      content::HostZoomMap::GetForWebContents(web_view_impl->web_contents());
  content::RenderFrameHost* render_frame_host =
      web_view_impl->web_contents()->GetPrimaryMainFrame();
  EXPECT_TRUE(
      zoom_map->UsesTemporaryZoomLevel(render_frame_host->GetGlobalId()));
  EXPECT_DOUBLE_EQ(
      1.0, content::HostZoomMap::GetZoomLevel(web_view_impl->web_contents()));

  // Navigate to a different url to trigger a RenderFrameHost change.
  web_view->Navigate(CreateDataUrlWithBody("World"));
  EXPECT_DID_STOP_LOADING(web_view);
  ASSERT_NE(render_frame_host,
            web_view_impl->web_contents()->GetPrimaryMainFrame());

  // Confirm that temporary zoom level is still applied even if RenderFrameHost
  // gets changed.
  zoom_map =
      content::HostZoomMap::GetForWebContents(web_view_impl->web_contents());
  render_frame_host = web_view_impl->web_contents()->GetPrimaryMainFrame();
  EXPECT_TRUE(
      zoom_map->UsesTemporaryZoomLevel(render_frame_host->GetGlobalId()));
  EXPECT_DOUBLE_EQ(
      1.0, content::HostZoomMap::GetZoomLevel(web_view_impl->web_contents()));
}

// Tests that AshWebViewImpl will open a browser window if the AshWebView is
// activated (while the widget is not activatable) and provided an
// `activation_url`.
IN_PROC_BROWSER_TEST_F(AshWebViewImplBrowserTest, ShouldOpenNewWindow) {
  auto widget = CreateWidget(/*activatable=*/false);
  AshWebView::InitParams init_params;
  const GURL destination_url("https://www.google.com");
  init_params.activation_url = destination_url;

  AshWebView* web_view =
      widget->SetContentsView(AshWebViewFactory::Get()->Create(init_params));
  AshWebViewImpl* web_view_impl = static_cast<AshWebViewImpl*>(web_view);

  web_view->Navigate(CreateDataUrl());
  EXPECT_DID_STOP_LOADING(web_view);

  // Activate the web contents and wait for the browser tab to load.
  ASSERT_TRUE(browser());
  content::TestNavigationObserver navigation_observer(
      browser()->tab_strip_model()->GetActiveWebContents());
  navigation_observer.StartWatchingNewWebContents();
  content::WebContents* web_contents = web_view_impl->web_contents();
  web_contents->GetDelegate()->ActivateContents(web_contents);
  navigation_observer.Wait();

  // Verify that the browser was launched with the correct url as the active
  // tab.
  EXPECT_EQ(
      destination_url,
      browser()->tab_strip_model()->GetActiveWebContents()->GetVisibleURL());
}