File: ash_test_base.h

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (444 lines) | stat: -rw-r--r-- 16,477 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
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
// Copyright 2012 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#ifndef ASH_TEST_ASH_TEST_BASE_H_
#define ASH_TEST_ASH_TEST_BASE_H_

#include <stdint.h>

#include <memory>
#include <string>
#include <utility>

#include "ash/public/cpp/shell_window_ids.h"
#include "ash/session/test_session_controller_client.h"
#include "ash/system/privacy_hub/sensor_disabled_notification_delegate.h"
#include "ash/test/ash_test_helper.h"
#include "ash/test/login_info.h"
#include "ash/test/pixel/ash_pixel_test_init_params.h"
#include "ash/wm/desks/desks_util.h"
#include "ash/wm/overview/overview_types.h"
#include "base/compiler_specific.h"
#include "base/test/task_environment.h"
#include "base/threading/thread.h"
#include "base/traits_bag.h"
#include "chromeos/ui/base/app_types.h"
#include "components/prefs/testing_pref_service.h"
#include "components/user_manager/user_type.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/skia/include/core/SkColor.h"
#include "ui/aura/client/window_types.h"
#include "ui/aura/env.h"
#include "ui/compositor/test/test_context_factories.h"
#include "ui/display/display.h"
#include "ui/events/event_constants.h"
#include "ui/events/test/event_generator.h"
#include "ui/views/widget/widget.h"

namespace aura {
class Window;
class WindowDelegate;
}  // namespace aura

namespace base {
namespace test {
class TaskEnvironment;
}
}  // namespace base

namespace chromeos {
class FakePowerManagerClient;
}

namespace display {
class Display;
class DisplayManager;

namespace test {
class DisplayManagerTestApi;
}  // namespace test
}  // namespace display

namespace gfx {
class Rect;
}

namespace ash {

class AmbientAshTestHelper;
class AppListTestHelper;
class AshPixelDiffer;
class AshPixelTestHelper;
class AshTestHelper;
class NotificationCenterTray;
class Shelf;
class TestAppListClient;
class TestSystemTrayClient;
class UnifiedSystemTray;
class WorkAreaInsets;

// Base class for most tests in //ash. Constructs ash::Shell and all its
// dependencies. Provides a user login session (use NoSessionAshTestBase for
// tests that start at the login screen or need unusual user types). Sets
// animation durations to zero via AshTestHelper/AuraTestHelper.
class AshTestBase : public testing::Test {
 public:
  // Constructs an AshTestBase with |traits| being forwarded to its
  // TaskEnvironment. MainThreadType always defaults to UI and must not be
  // specified.
  template <typename... TaskEnvironmentTraits>
  NOINLINE explicit AshTestBase(TaskEnvironmentTraits&&... traits)
      : AshTestBase(std::make_unique<base::test::TaskEnvironment>(
            base::test::TaskEnvironment::MainThreadType::UI,
            std::forward<TaskEnvironmentTraits>(traits)...)) {}

  // Alternatively a subclass may pass a TaskEnvironment directly.
  explicit AshTestBase(
      std::unique_ptr<base::test::TaskEnvironment> task_environment);

  AshTestBase(const AshTestBase&) = delete;
  AshTestBase& operator=(const AshTestBase&) = delete;

  ~AshTestBase() override;

  // testing::Test:
  void SetUp() override;
  void TearDown() override;

  // Returns the notification center tray on the primary display.
  static NotificationCenterTray* GetPrimaryNotificationCenterTray();

  // Returns the Shelf for the primary display.
  static Shelf* GetPrimaryShelf();

  // Returns the unified system tray on the primary display.
  static UnifiedSystemTray* GetPrimaryUnifiedSystemTray();

  // Returns WorkAreaInsets for the primary display.
  static WorkAreaInsets* GetPrimaryWorkAreaInsets();

  // Update the display configuration as given in |display_specs|.
  // See ash::DisplayManagerTestApi::UpdateDisplay for more details.
  // Note: To properly specify the radii of display's panel upon startup, set it
  // via specifying the command line switch `ash-host-window-bounds`.
  void UpdateDisplay(const std::string& display_specs,
                     bool from_native_platform = false,
                     bool generate_new_ids = false);

  // Returns a root Window. Usually this is the active root Window, but that
  // method can return NULL sometimes, and in those cases, we fall back on the
  // primary root Window.
  aura::Window* GetContext();

  // Creates and shows a widget. See ash/public/cpp/shell_window_ids.h for
  // values for |container_id|.
  static std::unique_ptr<views::Widget> CreateTestWidget(
      views::Widget::InitParams::Ownership ownership,
      views::WidgetDelegate* delegate = nullptr,
      int container_id = desks_util::GetActiveDeskContainerId(),
      const gfx::Rect& bounds = gfx::Rect(),
      bool show = true);

  // Creates a frameless widget for testing.
  // TODO(crbug.com/339619005) - Make the ownership parameter required.
  static std::unique_ptr<views::Widget> CreateFramelessTestWidget(
      views::Widget::InitParams::Ownership ownership =
          views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET);

  // Creates a widget with a visible WINDOW_TYPE_NORMAL window with the given
  // |app_type|. If |app_type| is chromeos::AppType::NON_APP, this window is
  // considered a non-app window. If |bounds_in_screen| is empty the window is
  // added to the primary root window, otherwise the window is added to the
  // display matching |bounds_in_screen|. |shell_window_id| is the shell window
  // id to give to the new window. If |delegate| is empty, a new
  // |TestWidgetDelegate| instance will be set as this widget's delegate.
  std::unique_ptr<aura::Window> CreateAppWindow(
      const gfx::Rect& bounds_in_screen = gfx::Rect(),
      chromeos::AppType app_type = chromeos::AppType::SYSTEM_APP,
      int shell_window_id = kShellWindowId_Invalid,
      views::WidgetDelegate* delegate = nullptr);

  // Creates a visible window in the appropriate container. If
  // |bounds_in_screen| is empty the window is added to the primary root
  // window, otherwise the window is added to the display matching
  // |bounds_in_screen|. |shell_window_id| is the shell window id to give to
  // the new window.
  // If |type| is WINDOW_TYPE_NORMAL this creates a views::Widget, otherwise
  // this creates an aura::Window.
  std::unique_ptr<aura::Window> CreateTestWindow(
      const gfx::Rect& bounds_in_screen = gfx::Rect(),
      aura::client::WindowType type = aura::client::WINDOW_TYPE_NORMAL,
      int shell_window_id = kShellWindowId_Invalid);

  // Creates a visible top-level window with a delegate.
  std::unique_ptr<aura::Window> CreateToplevelTestWindow(
      const gfx::Rect& bounds_in_screen = gfx::Rect(),
      int shell_window_id = kShellWindowId_Invalid);

  // Versions of the functions in aura::test:: that go through our shell
  // StackingController instead of taking a parent.
  aura::Window* CreateTestWindowInShellWithId(int id);
  aura::Window* CreateTestWindowInShellWithBounds(const gfx::Rect& bounds);
  aura::Window* CreateTestWindowInShellWithDelegate(
      aura::WindowDelegate* delegate,
      int id,
      const gfx::Rect& bounds);
  aura::Window* CreateTestWindowInShellWithDelegateAndType(
      aura::WindowDelegate* delegate,
      aura::client::WindowType type,
      int id,
      const gfx::Rect& bounds);

  // Attach |window| to the current shell's root window.
  void ParentWindowInPrimaryRootWindow(aura::Window* window);

  // Returns the raw pointer carried by `pixel_differ_`.
  AshPixelDiffer* GetPixelDiffer();

  // Returns the EventGenerator that uses screen coordinates and works
  // across multiple displays. It creates a new generator if it
  // hasn't been created yet.
  ui::test::EventGenerator* GetEventGenerator();

  // Convenience method to return the DisplayManager.
  display::DisplayManager* display_manager();

  // Convenience method to return the FakePowerManagerClient.
  chromeos::FakePowerManagerClient* power_manager_client() const;

  // Test if moving a mouse to |point_in_screen| warps it to another
  // display.
  bool TestIfMouseWarpsAt(ui::test::EventGenerator* event_generator,
                          const gfx::Point& point_in_screen);

  // Presses and releases a key to simulate typing one character.
  void PressAndReleaseKey(ui::KeyboardCode key_code, int flags = ui::EF_NONE);

  // Moves the mouse to the center of the view and generates a left mouse button
  // click event.
  void LeftClickOn(const views::View* view);

  // Moves the mouse to the center of the view and generates a right mouse
  // button click event.
  void RightClickOn(const views::View* view);

  // Generates a tap event on the center of `view`.
  void GestureTapOn(const views::View* view);

  // Enters/Exits overview mode with the given animation type `type`.
  bool EnterOverview(
      OverviewEnterExitType type = OverviewEnterExitType::kNormal);
  bool ExitOverview(
      OverviewEnterExitType type = OverviewEnterExitType::kNormal);

  // Sets shelf animation duration for all displays.
  void SetShelfAnimationDuration(base::TimeDelta duration);

  // Waits for shelf animation in all displays.
  void WaitForShelfAnimation();

  // Execute a list of tasks during a drag and drop sequence in the apps grid.
  // This method should be called after the drag is initiated by long pressing
  // over an app but before actually moving the pointer to drag the item. When
  // the drag and drop sequence is not handled by DragDropController, the list
  // of tasks is just run sequentially outside the loop
  void MaybeRunDragAndDropSequenceForAppList(
      std::list<base::OnceClosure>* tasks,
      bool is_touch);

  // Called when AshTestHelper will be soon destroyed.
  virtual void OnHelperWillBeDestroyed() {}

 protected:
  enum UserSessionBlockReason {
    FIRST_BLOCK_REASON,
    BLOCKED_BY_LOCK_SCREEN = FIRST_BLOCK_REASON,
    BLOCKED_BY_LOGIN_SCREEN,
    BLOCKED_BY_USER_ADDING_SCREEN,
    NUMBER_OF_BLOCK_REASONS
  };

  // Returns the rotation currentl active for the display |id|.
  static display::Display::Rotation GetActiveDisplayRotation(int64_t id);

  // Returns the rotation currently active for the internal display.
  static display::Display::Rotation GetCurrentInternalDisplayRotation();

  // Creates init params to set up a pixel test. If the test is not pixel
  // related, returns `std::nullopt`. This function should be overridden by ash
  // pixel tests.
  virtual std::optional<pixel_test::InitParams> CreatePixelTestInitParams()
      const;

  void set_start_session(bool start_session) {
    CHECK(init_params_) << "start_session must set before calling SetUp()";
    init_params_->start_session = start_session;
  }

  void set_create_signin_pref_service(bool create_signin_pref_service) {
    CHECK(init_params_)
        << "create_create_signin_pref_service must set before calling SetUp()";
    init_params_->create_signin_pref_service = create_signin_pref_service;
  }

  void set_create_global_cras_audio_handler(
      bool create_global_cras_audio_handler) {
    CHECK(init_params_)
        << "create_global_cras_audio_handler must set before calling SetUp()";
    init_params_->create_global_cras_audio_handler =
        create_global_cras_audio_handler;
  }

  void set_create_quick_pair_mediator(bool create_quick_pair_mediator) {
    CHECK(init_params_)
        << "create_quick_pair_mediator must set before calling SetUp()";
    init_params_->create_quick_pair_mediator = create_quick_pair_mediator;
  }

  void set_shell_delegate(std::unique_ptr<ShellDelegate> shell_delegate) {
    CHECK(init_params_) << "shell_delegate mustset before calling SetUp()";
    CHECK(!init_params_->delegate);
    init_params_->delegate = std::move(shell_delegate);
  }

  base::test::TaskEnvironment* task_environment() {
    return task_environment_.get();
  }
  TestingPrefServiceSimple* local_state() { return &local_state_; }
  AshTestHelper* ash_test_helper() { return ash_test_helper_.get(); }

  // Returns nullptr before SetUp() is called.
  ui::InProcessContextFactory* GetContextFactory() {
    return test_context_factories_
               ? test_context_factories_->GetContextFactory()
               : nullptr;
  }

  void SetUserPref(const std::string& user_email,
                   const std::string& path,
                   const base::Value& value);

  TestSessionControllerClient* GetSessionControllerClient();

  TestSystemTrayClient* GetSystemTrayClient();

  AppListTestHelper* GetAppListTestHelper();

  TestAppListClient* GetTestAppListClient();

  AmbientAshTestHelper* GetAmbientAshTestHelper();

  // Simulates a user sign-in, and returns an AccountId used to sign in.
  // Please see `AshTestHelper::SimulateUserLogin` for more details.
  AccountId SimulateUserLogin(
      LoginInfo login_info,
      std::optional<AccountId> opt_account_id = std::nullopt,
      std::unique_ptr<PrefService> pref_service = nullptr);

  // Similar to above, but it uses AccountId with default values.
  void SimulateUserLogin(const AccountId& account_id);

  // Simular to SimulateUserLogin but for a newly created user first ever login.
  AccountId SimulateNewUserFirstLogin(const std::string& user_email);

  // Similar to SimulateUserLogin but for a guest user.
  AccountId SimulateGuestLogin();

  // Simulates kiosk mode. |user_type| must correlate to a kiosk type user.
  AccountId SimulateKioskMode(user_manager::UserType user_type);

  // Switches the active user to `account_id`;
  void SwitchActiveUser(const AccountId& account_id);

  // Returns true if the session is in `state`.
  bool IsInSessionState(session_manager::SessionState state) const;

  // Simulates setting height of the accessibility panel.
  // Note: Accessibility panel widget needs to be setup first.
  void SetAccessibilityPanelHeight(int panel_height);

  // Clears all user sessions and resets to the primary login screen state.
  void ClearLogin();

  // Emulates whether the active user can lock screen.
  void SetCanLockScreen(bool can_lock);

  // Emulates whether the screen should be locked automatically.
  void SetShouldLockScreenAutomatically(bool should_lock);

  // Emulates whether the user adding screen is running.
  void SetUserAddingScreenRunning(bool user_adding_screen_running);

  // Methods to emulate blocking and unblocking user session with given
  // |block_reason|.
  // TODO(crbug.com/383770001): Deprecate these methods.
  void BlockUserSession(UserSessionBlockReason block_reason);
  void UnblockUserSession();

  // Enable or disable the virtual on-screen keyboard and run the message loop
  // to allow observer operations to complete.
  void SetVirtualKeyboardEnabled(bool enabled);

  void DisableIME();

  // Swap the primary display with the secondary.
  void SwapPrimaryDisplay();

  display::Display GetPrimaryDisplay() const;
  display::Display GetSecondaryDisplay() const;

 private:
  void CreateWindowTreeIfNecessary();

  // Prepares for pixel tests by enabling related flags and building
  // `ash_test_helper_`.
  void PrepareForPixelDiffTest();

  bool setup_called_ = false;
  bool teardown_called_ = false;

  // AshTestHelper's init params.
  std::unique_ptr<AshTestHelper::InitParams> init_params_ =
      std::make_unique<AshTestHelper::InitParams>();

  // |task_environment_| is initialized-once at construction time but
  // subclasses may elect to provide their own.
  std::unique_ptr<base::test::TaskEnvironment> task_environment_;

  // A pref service used for local state.
  TestingPrefServiceSimple local_state_;

  // A helper class to take screen shots then compare with benchmarks. Set by
  // `PrepareForPixelDiffTest()`.
  std::unique_ptr<AshPixelDiffer> pixel_differ_;

  std::unique_ptr<ui::TestContextFactories> test_context_factories_;

  // Must be constructed after |task_environment_|.
  std::unique_ptr<AshTestHelper> ash_test_helper_;

  // Used only for pixel tests.
  std::unique_ptr<AshPixelTestHelper> pixel_test_helper_;

  std::unique_ptr<ui::test::EventGenerator> event_generator_;

  std::unique_ptr<ScopedSensorDisabledNotificationDelegateForTest>
      scoped_disabled_notification_delegate_;
};

class NoSessionAshTestBase : public AshTestBase {
 public:
  NoSessionAshTestBase();
  explicit NoSessionAshTestBase(
      base::test::TaskEnvironment::TimeSource time_source);

  NoSessionAshTestBase(const NoSessionAshTestBase&) = delete;
  NoSessionAshTestBase& operator=(const NoSessionAshTestBase&) = delete;

  ~NoSessionAshTestBase() override;
};

}  // namespace ash

#endif  // ASH_TEST_ASH_TEST_BASE_H_