File: interaction_test_util_browser.cc

package info (click to toggle)
chromium 138.0.7204.183-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 6,071,908 kB
  • sloc: cpp: 34,937,088; ansic: 7,176,967; javascript: 4,110,704; python: 1,419,953; 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,806; 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 (398 lines) | stat: -rw-r--r-- 15,907 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
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
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
// Copyright 2022 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/test/interaction/interaction_test_util_browser.h"

#include <memory>

#include "base/command_line.h"
#include "base/strings/strcat.h"
#include "build/build_config.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/browser/ui/browser_list.h"
#include "chrome/browser/ui/browser_window.h"
#include "chrome/browser/ui/test/test_browser_ui.h"
#include "chrome/browser/ui/views/frame/browser_view.h"
#include "chrome/browser/ui/views/omnibox/omnibox_view_views.h"
#include "chrome/browser/ui/views/tabs/tab.h"
#include "chrome/browser/ui/views/tabs/tab_strip.h"
#include "chrome/test/base/interactive_test_utils.h"
#include "chrome/test/interaction/tracked_element_webcontents.h"
#include "chrome/test/interaction/webcontents_interaction_test_util.h"
#include "content/public/browser/render_widget_host_view.h"
#include "content/public/common/content_switches.h"
#include "content/public/test/update_user_activation_state_interceptor.h"
#include "ui/base/interaction/element_tracker.h"
#include "ui/base/interaction/interaction_test_util.h"
#include "ui/base/test/ui_controls.h"
#include "ui/events/event.h"
#include "ui/events/keycodes/keyboard_codes.h"
#include "ui/events/types/event_type.h"
#include "ui/views/controls/webview/webview.h"
#include "ui/views/interaction/element_tracker_views.h"
#include "ui/views/interaction/interaction_test_util_views.h"
#include "ui/views/test/widget_test.h"
#include "ui/views/view.h"
#include "ui/views/view_utils.h"

#if BUILDFLAG(IS_MAC)
#include "ui/base/interaction/interaction_test_util_mac.h"
#endif

namespace {

// Facilitates pixel testing with more versatile naming than TestBrowserUi.
class PixelTestUi : public TestBrowserUi {
 public:
  PixelTestUi(views::View* view,
              const std::string& screenshot_name,
              const std::string& baseline)
      : view_(view), screenshot_name_(screenshot_name), baseline_(baseline) {}
  ~PixelTestUi() override = default;

  // TestBrowserUi:
  void ShowUi(const std::string& name) override { NOTREACHED(); }
  void WaitForUserDismissal() override { NOTREACHED(); }

  bool VerifyUi() override {
    return VerifyUiWithResult() != ui::test::ActionResult::kFailed;
  }

  ui::test::ActionResult VerifyUiWithResult() {
    auto* const test_info =
        testing::UnitTest::GetInstance()->current_test_info();
    const std::string test_name =
        base::StrCat({test_info->test_suite_name(), "_", test_info->name()});
    const std::string screenshot_name =
        screenshot_name_.empty()
            ? baseline_
            : base::StrCat({screenshot_name_, "_", baseline_});
    return VerifyPixelUi(view_, test_name, screenshot_name);
  }

 private:
  raw_ptr<views::View> view_ = nullptr;
  std::string screenshot_name_;
  std::string baseline_;
};

views::View* GetScreenshotTargetView(ui::TrackedElement* element) {
  if (auto* const view_el = element->AsA<views::TrackedElementViews>()) {
    return view_el->view();
  } else if (auto* const page_el = element->AsA<TrackedElementWebContents>()) {
    return page_el->owner()->GetWebView();
  }
  return nullptr;
}

ui::test::ActionResult CompareScreenshotCommon(
    views::View* view,
    const std::string& screenshot_name,
    const std::string& baseline_cl) {
  // pixel_browser_tests and pixel_interactive_ui_tests specify this command
  // line, which is checked by TestBrowserUi before attempting any screen
  // capture; otherwise screenshotting is a silent no-op.
  if (!base::CommandLine::ForCurrentProcess()->HasSwitch(
          switches::kVerifyPixels)) {
    LOG(WARNING)
        << "Cannot take screenshot: pixel test command line not set. This is "
           "normal for non-pixel-test jobs such as vanilla browser_tests.";
    return ui::test::ActionResult::kKnownIncompatible;
  }

  PixelTestUi pixel_test_ui(view, screenshot_name, baseline_cl);
  ui::test::ActionResult result = pixel_test_ui.VerifyUiWithResult();
  if (result == ui::test::ActionResult::kKnownIncompatible) {
    LOG(WARNING) << "Current platform does not support pixel tests.";
  }
  return result;
}

// Special handler for browsers and browser tab strips that enables SelectTab().
class InteractionTestUtilSimulatorBrowser
    : public ui::test::InteractionTestUtil::Simulator {
 public:
  InteractionTestUtilSimulatorBrowser() = default;
  ~InteractionTestUtilSimulatorBrowser() override = default;

  ui::test::ActionResult SendAccelerator(ui::TrackedElement* element,
                                         ui::Accelerator accelerator) override {
#if BUILDFLAG(IS_MAC)
    // Browser accelerators must be sent via key events to the window on Mac or
    // they don't work properly. Dialog accelerators still appear to work the
    // same as on other platforms.
    if (Browser* const browser =
            InteractionTestUtilBrowser::GetBrowserFromContext(
                element->context())) {
      if (!ui_controls::SendKeyPress(
              browser->window()->GetNativeWindow(), accelerator.key_code(),
              accelerator.IsCtrlDown(), accelerator.IsShiftDown(),
              accelerator.IsAltDown(), accelerator.IsCmdDown())) {
        LOG(ERROR) << "Failed to send accelerator"
                   << accelerator.GetShortcutText() << " to " << *element;
        return ui::test::ActionResult::kFailed;
      }
      return ui::test::ActionResult::kSucceeded;
    }
#endif  // BUILDFLAG(IS_MAC)

    if (auto* const tracked_contents =
            element->AsA<TrackedElementWebContents>()) {
      if (auto* const view = tracked_contents->owner()->GetWebView()) {
        // There are two possibilities:
        //  1. This is a legitimate accelerator, which must be handled by the
        //     focus manager.
        //  2. This is a control key that will be processed by Blink (e.g.
        //     pressing enter or space to "click" an HTML button), and therefore
        //     must be injected as a keypress.
        bool result = view->GetFocusManager()->ProcessAccelerator(accelerator);
        if (!result) {
          result = ui_controls::SendKeyPress(
              tracked_contents->owner()
                  ->web_contents()
                  ->GetTopLevelNativeWindow(),
              accelerator.key_code(), accelerator.IsCtrlDown(),
              accelerator.IsShiftDown(), accelerator.IsAltDown(),
              accelerator.IsCmdDown());
        }
        return result ? ui::test::ActionResult::kSucceeded
                      : ui::test::ActionResult::kFailed;
      } else {
        LOG(ERROR) << "No associated view to send accelerators to.";
        return ui::test::ActionResult::kFailed;
      }
    }

    return ui::test::ActionResult::kNotAttempted;
  }

  // Handle sending key presses to web contents. All other cases are handled by
  // the Views simulator.
  ui::test::ActionResult SendKeyPress(ui::TrackedElement* element,
                                      ui::KeyboardCode key,
                                      int flags) override {
    if (auto* const tracked_contents =
            element->AsA<TrackedElementWebContents>()) {
      auto native_window =
          tracked_contents->owner()->web_contents()->GetTopLevelNativeWindow();
      const bool result = ui_test_utils::SendKeyPressToWindowSync(
          native_window, key, flags & ui::EF_CONTROL_DOWN,
          flags & ui::EF_SHIFT_DOWN, flags & ui::EF_ALT_DOWN,
          flags & ui::EF_COMMAND_DOWN);
      return result ? ui::test::ActionResult::kSucceeded
                    : ui::test::ActionResult::kFailed;
    }

    return ui::test::ActionResult::kNotAttempted;
  }

  // Chrome has better and more thorough functionality for bringing a browser
  // window to the front, but it's expensive, so only actually use it for
  // browser windows on platforms where activation requires extra steps.
  ui::test::ActionResult ActivateSurface(ui::TrackedElement* el) override {
    views::View* view = nullptr;
    bool is_web_contents = false;
    if (auto* view_el = el->AsA<views::TrackedElementViews>()) {
      view = view_el->view();
    } else if (auto* contents_el = el->AsA<TrackedElementWebContents>()) {
      is_web_contents = true;
      view = contents_el->owner()->GetWebView();
      if (!view) {
        LOG(ERROR) << "WebContents not associated with any UI element.";
        return ui::test::ActionResult::kFailed;
      }
    }
    if (!view) {
      return ui::test::ActionResult::kNotAttempted;
    }

    // Get the browser and browser window associated with the current context.
    // If there is none, or it is not the same widget as the view, do not use
    // this implementation.
    if (auto* const browser =
            InteractionTestUtilBrowser::GetBrowserFromContext(el->context())) {
      if (auto* const browser_view =
              BrowserView::GetBrowserViewForBrowser(browser)) {
        if (browser_view->GetWidget() == view->GetWidget()) {
#if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC)
          // Bring the browser window to the front using the most aggressive
          // method for the current platform. If this is not done, then mouse
          // events might not get routed to the correct surface.
          if (!ui_test_utils::BringBrowserWindowToFront(browser)) {
            LOG(ERROR) << "BringBrowserWindowToFront() failed.";
            return ui::test::ActionResult::kFailed;
          }
          return ui::test::ActionResult::kSucceeded;
#else
          // Use the default logic to activate the browser.
          return views::test::InteractionTestUtilSimulatorViews::ActivateWidget(
              view->GetWidget());
#endif  // BUILDFLAG(IS_WIN) || BUILDFLAG(IS_MAC)
        }
      }
    }

    // Because the fallback Views handler doesn't know about WebContents, handle
    // activation here.
    if (is_web_contents) {
      return views::test::InteractionTestUtilSimulatorViews::ActivateWidget(
          view->GetWidget());
    }

    return ui::test::ActionResult::kNotAttempted;
  }

  ui::test::ActionResult FocusElement(ui::TrackedElement* element) override {
    auto* const instrumented = element->AsA<TrackedElementWebContents>();
    if (!instrumented) {
      return ui::test::ActionResult::kNotAttempted;
    }

    auto* const contents = instrumented->owner()->web_contents();
    if (!contents) {
      LOG(ERROR) << "WebContents not present.";
      return ui::test::ActionResult::kFailed;
    }

    // Focus the renderer.
    if (!contents->GetRenderWidgetHostView()) {
      LOG(ERROR) << "No render widget host.";
      return ui::test::ActionResult::kFailed;
    }
    contents->GetRenderWidgetHostView()->Focus();

    // Prepare the renderer for input.
    if (!contents->GetPrimaryMainFrame()) {
      LOG(ERROR) << "No main frame.";
      return ui::test::ActionResult::kFailed;
    }
    content::UpdateUserActivationStateInterceptor user_activation_interceptor(
        contents->GetPrimaryMainFrame());
    user_activation_interceptor.UpdateUserActivationState(
        blink::mojom::UserActivationUpdateType::kNotifyActivation,
        blink::mojom::UserActivationNotificationType::kTest);

    // Ensure the correct WebView is focused before returning.
    auto* web_view = instrumented->owner()->GetWebView();
    if (!web_view) {
      LOG(ERROR) << "No web view.";
      return ui::test::ActionResult::kFailed;
    }
    views::test::ViewFocusedWaiter focus_waiter(*web_view);
    focus_waiter.Wait();

    return ui::test::ActionResult::kSucceeded;
  }

  ui::test::ActionResult SelectTab(
      ui::TrackedElement* tab_collection,
      size_t index,
      InputType input_type,
      std::optional<size_t> expected_index_after_selection) override {
    // This handler *explicitly* only handles Browser and TabStrip; it will
    // reject any other element or View type.
    if (!tab_collection->IsA<views::TrackedElementViews>())
      return ui::test::ActionResult::kNotAttempted;
    auto* const view =
        tab_collection->AsA<views::TrackedElementViews>()->view();
    TabStrip* tab_strip = nullptr;
    if (auto* const browser_view = views::AsViewClass<BrowserView>(view)) {
      tab_strip = browser_view->tabstrip();
    } else {
      tab_strip = views::AsViewClass<TabStrip>(view);
    }
    if (!tab_strip)
      return ui::test::ActionResult::kNotAttempted;

    // Verify that the tab index is in range; at this point it's a fatal error
    // if it's out of bounds.
    if (static_cast<int>(index) >= tab_strip->GetTabCount()) {
      LOG(ERROR) << "Tabstrip index " << index
                 << " is out of bounds, there are " << tab_strip->GetTabCount()
                 << " tabs.";
      return ui::test::ActionResult::kFailed;
    }

    // Tabs can be selected using a default action; no special input logic is
    // needed.
    Tab* const tab = tab_strip->tab_at(index);
    views::test::InteractionTestUtilSimulatorViews::DoDefaultAction(tab,
                                                                    input_type);

    const int expected =
        static_cast<int>(expected_index_after_selection.value_or(index));
    if (expected != tab_strip->GetActiveIndex()) {
      LOG(ERROR) << "Failed to select tabstrip tab " << index;
      return ui::test::ActionResult::kFailed;
    }
    return ui::test::ActionResult::kSucceeded;
  }

  ui::test::ActionResult Confirm(ui::TrackedElement* element) override {
    // This handler *explicitly* only handles OmniboxView; it will reject any
    // other element or View type.
    if (!element->IsA<views::TrackedElementViews>())
      return ui::test::ActionResult::kNotAttempted;
    auto* const view = element->AsA<views::TrackedElementViews>()->view();
    if (auto* const omnibox = views::AsViewClass<OmniboxViewViews>(view)) {
      ui::KeyEvent press(ui::EventType::kKeyPressed, ui::VKEY_RETURN,
                         ui::EF_NONE);
      omnibox->OnKeyEvent(&press);
      ui::KeyEvent release(ui::EventType::kKeyReleased, ui::VKEY_RETURN,
                           ui::EF_NONE);
      omnibox->OnKeyEvent(&release);
      return ui::test::ActionResult::kSucceeded;
    }
    return ui::test::ActionResult::kNotAttempted;
  }
};

}  // namespace

InteractionTestUtilBrowser::InteractionTestUtilBrowser() {
  AddSimulator(std::make_unique<InteractionTestUtilSimulatorBrowser>());
  AddSimulator(
      std::make_unique<views::test::InteractionTestUtilSimulatorViews>());
#if BUILDFLAG(IS_MAC)
  AddSimulator(std::make_unique<ui::test::InteractionTestUtilSimulatorMac>());
#endif
}

InteractionTestUtilBrowser::~InteractionTestUtilBrowser() = default;

// static
Browser* InteractionTestUtilBrowser::GetBrowserFromContext(
    ui::ElementContext context) {
  BrowserList* const browsers = BrowserList::GetInstance();
  for (Browser* const browser : *browsers) {
    if (browser->window()->GetElementContext() == context)
      return browser;
  }
  return nullptr;
}

// static
ui::test::ActionResult InteractionTestUtilBrowser::CompareScreenshot(
    ui::TrackedElement* element,
    const std::string& screenshot_name,
    const std::string& baseline_cl) {
  views::View* const view = GetScreenshotTargetView(element);
  if (!view) {
    return ui::test::ActionResult::kNotAttempted;
  }
  return CompareScreenshotCommon(view, screenshot_name, baseline_cl);
}

// static
ui::test::ActionResult InteractionTestUtilBrowser::CompareSurfaceScreenshot(
    ui::TrackedElement* element_in_surface,
    const std::string& screenshot_name,
    const std::string& baseline_cl) {
  views::View* const view = GetScreenshotTargetView(element_in_surface);
  if (!view || !view->GetWidget()) {
    return ui::test::ActionResult::kNotAttempted;
  }
  return CompareScreenshotCommon(view->GetWidget()->GetRootView(),
                                 screenshot_name, baseline_cl);
}