File: chrome_ash_message_center_client_unittest.cc

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 (303 lines) | stat: -rw-r--r-- 12,093 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
// Copyright 2013 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/notifications/chrome_ash_message_center_client.h"

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

#include "ash/public/cpp/notifier_metadata.h"
#include "ash/public/cpp/notifier_settings_observer.h"
#include "base/command_line.h"
#include "base/functional/bind.h"
#include "base/strings/utf_string_conversions.h"
#include "build/build_config.h"
#include "chrome/browser/ash/login/users/fake_chrome_user_manager.h"
#include "chrome/browser/content_settings/host_content_settings_map_factory.h"
#include "chrome/browser/extensions/extension_service.h"
#include "chrome/browser/extensions/test_extension_system.h"
#include "chrome/browser/profiles/profile_manager.h"
#include "chrome/test/base/testing_browser_process.h"
#include "chrome/test/base/testing_profile_manager.h"
#include "components/content_settings/core/browser/host_content_settings_map.h"
#include "components/content_settings/core/common/content_settings_types.h"
#include "components/permissions/test/permission_test_util.h"
#include "components/user_manager/scoped_user_manager.h"
#include "content/public/browser/permission_controller.h"
#include "content/public/browser/permission_descriptor_util.h"
#include "content/public/browser/permission_result.h"
#include "content/public/test/browser_task_environment.h"
#include "extensions/browser/extension_registrar.h"
#include "extensions/common/extension.h"
#include "extensions/common/extension_builder.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "third_party/blink/public/common/permissions/permission_utils.h"
#include "ui/message_center/message_center.h"
#include "ui/message_center/public/cpp/notifier_id.h"

namespace {

class ChromeAshMessageCenterClientTest : public testing::Test,
                                         public ash::NotifierSettingsObserver {
 public:
  ChromeAshMessageCenterClientTest(const ChromeAshMessageCenterClientTest&) =
      delete;
  ChromeAshMessageCenterClientTest& operator=(
      const ChromeAshMessageCenterClientTest&) = delete;

 protected:
  ChromeAshMessageCenterClientTest()
      : testing_profile_manager_(TestingBrowserProcess::GetGlobal()) {}
  ~ChromeAshMessageCenterClientTest() override = default;

  // testing::Test:
  void SetUp() override {
    ASSERT_TRUE(testing_profile_manager_.SetUp());

    // Initialize the UserManager singleton to a fresh FakeUserManager instance.
    user_manager_enabler_ = std::make_unique<user_manager::ScopedUserManager>(
        std::make_unique<ash::FakeChromeUserManager>());

    message_center::MessageCenter::Initialize();
  }

  void TearDown() override {
    client_.reset();
    message_center::MessageCenter::Shutdown();
  }

  // ash::NotifierSettingsObserver:
  void OnNotifiersUpdated(
      const std::vector<ash::NotifierMetadata>& notifiers) override {
    notifiers_ = notifiers;
  }

  TestingProfile* CreateProfile(const std::string& name) {
    TestingProfile* profile =
        testing_profile_manager_.CreateTestingProfile(name);

    GetFakeUserManager()->AddUser(AccountId::FromUserEmail(name));
    GetFakeUserManager()->LoginUser(AccountId::FromUserEmail(name));
    return profile;
  }

  base::FilePath GetProfilePath(const std::string& base_name) {
    return testing_profile_manager_.profile_manager()
        ->user_data_dir()
        .AppendASCII(base_name);
  }

  void SwitchActiveUser(const std::string& name) {
    GetFakeUserManager()->SwitchActiveUser(AccountId::FromUserEmail(name));
  }

  void CreateClient() {
    client_ = std::make_unique<ChromeAshMessageCenterClient>(nullptr);
    client_->AddNotifierSettingsObserver(this);
  }

  ChromeAshMessageCenterClient* message_center_client() {
    return client_.get();
  }

 protected:
  void RefreshNotifierList() { message_center_client()->GetNotifiers(); }

  std::vector<ash::NotifierMetadata> notifiers_;

 private:
  ash::FakeChromeUserManager* GetFakeUserManager() {
    return static_cast<ash::FakeChromeUserManager*>(
        user_manager::UserManager::Get());
  }

  content::BrowserTaskEnvironment task_environment_;
  TestingProfileManager testing_profile_manager_;
  std::unique_ptr<ChromeAshMessageCenterClient> client_;
  std::unique_ptr<user_manager::ScopedUserManager> user_manager_enabler_;
};

// TODO(mukai): write a test case to reproduce the actual guest session scenario
// in ChromeOS.

TEST_F(ChromeAshMessageCenterClientTest, NotifierSortOrder) {
  TestingProfile* profile = CreateProfile("profile1@gmail.com");
  extensions::TestExtensionSystem* test_extension_system =
      static_cast<extensions::TestExtensionSystem*>(
          extensions::ExtensionSystem::Get(profile));
  base::CommandLine command_line(base::CommandLine::NO_PROGRAM);
  test_extension_system->CreateExtensionService(
      &command_line, base::FilePath() /* install_directory */,
      false /* autoupdate_enabled*/);

  extensions::ExtensionBuilder foo_app;
  // Foo is an app with name Foo and should appear second.
  const std::string kFooId = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";

  // Bar is an app with name Bar and should appear first.
  const std::string kBarId = "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb";

  // Baz is an app with name Baz and should not appear in the notifier list
  // since it doesn't have notifications permission.
  const std::string kBazId = "cccccccccccccccccccccccccccccccc";

  // Baf is a hosted app which should not appear in the notifier list.
  const std::string kBafId = "dddddddddddddddddddddddddddddddd";

  foo_app.SetManifest(
      base::Value::Dict()
          .Set("name", "Foo")
          .Set("version", "1.0.0")
          .Set("manifest_version", 2)
          .Set("app",
               base::Value::Dict().Set(
                   "background",
                   base::Value::Dict().Set(
                       "scripts", base::Value::List().Append("background.js"))))
          .Set("permissions", base::Value::List().Append("notifications")));
  foo_app.SetID(kFooId);
  extensions::ExtensionRegistrar::Get(profile)->AddExtension(foo_app.Build());

  extensions::ExtensionBuilder bar_app;
  bar_app.SetManifest(
      base::Value::Dict()
          .Set("name", "Bar")
          .Set("version", "1.0.0")
          .Set("manifest_version", 2)
          .Set("app",
               base::Value::Dict().Set(
                   "background",
                   base::Value::Dict().Set(
                       "scripts", base::Value::List().Append("background.js"))))
          .Set("permissions", base::Value::List().Append("notifications")));
  bar_app.SetID(kBarId);
  extensions::ExtensionRegistrar::Get(profile)->AddExtension(bar_app.Build());

  extensions::ExtensionBuilder baz_app;
  baz_app.SetManifest(
      base::Value::Dict()
          .Set("name", "baz")
          .Set("version", "1.0.0")
          .Set("manifest_version", 2)
          .Set("app", base::Value::Dict().Set(
                          "background",
                          base::Value::Dict().Set(
                              "scripts",
                              base::Value::List().Append("background.js")))));
  baz_app.SetID(kBazId);
  extensions::ExtensionRegistrar::Get(profile)->AddExtension(baz_app.Build());

  extensions::ExtensionBuilder baf_app;
  baf_app.SetManifest(
      base::Value::Dict()
          .Set("name", "baf")
          .Set("version", "1.0.0")
          .Set("manifest_version", 2)
          .Set("app", base::Value::Dict().Set("urls",
                                              base::Value::List().Append(
                                                  "http://localhost/extensions/"
                                                  "hosted_app/main.html")))
          .Set("launch", base::Value::Dict().Set(
                             "urls", base::Value::List().Append(
                                         "http://localhost/extensions/"
                                         "hosted_app/main.html"))));

  baf_app.SetID(kBafId);
  extensions::ExtensionRegistrar::Get(profile)->AddExtension(baf_app.Build());
  CreateClient();

  RefreshNotifierList();
  ASSERT_EQ(2u, notifiers_.size());
  EXPECT_EQ(kBarId, notifiers_[0].notifier_id.id);
  EXPECT_EQ(kFooId, notifiers_[1].notifier_id.id);
}

TEST_F(ChromeAshMessageCenterClientTest, SetWebPageNotifierEnabled) {
  TestingProfile* profile = CreateProfile("myprofile@gmail.com");
  const auto notification_permission_descriptor = content::
      PermissionDescriptorUtil::CreatePermissionDescriptorForPermissionType(
          blink::PermissionType::NOTIFICATIONS);
  CreateClient();

  GURL origin("https://example.com/");

  message_center::NotifierId notifier_id(origin);

  ContentSetting default_setting =
      HostContentSettingsMapFactory::GetForProfile(profile)
          ->GetDefaultContentSetting(ContentSettingsType::NOTIFICATIONS,
                                     nullptr);
  ASSERT_EQ(CONTENT_SETTING_ASK, default_setting);

  profile->SetPermissionControllerDelegate(
      permissions::GetPermissionControllerDelegate(profile));

  // (1) Enable the permission when the default is to ask (expected to set).
  message_center_client()->SetNotifierEnabled(notifier_id, true);
  EXPECT_EQ(
      blink::mojom::PermissionStatus::GRANTED,
      profile->GetPermissionController()
          ->GetPermissionResultForOriginWithoutContext(
              notification_permission_descriptor, url::Origin::Create(origin))
          .status);

  // (2) Disable the permission when the default is to ask (expected to clear).
  message_center_client()->SetNotifierEnabled(notifier_id, false);
  EXPECT_EQ(
      blink::mojom::PermissionStatus::ASK,
      profile->GetPermissionController()
          ->GetPermissionResultForOriginWithoutContext(
              notification_permission_descriptor, url::Origin::Create(origin))
          .status);

  // Change the default content setting vaule for notifications to ALLOW.
  HostContentSettingsMapFactory::GetForProfile(profile)
      ->SetDefaultContentSetting(ContentSettingsType::NOTIFICATIONS,
                                 CONTENT_SETTING_ALLOW);

  // (3) Disable the permission when the default is allowed (expected to set).
  message_center_client()->SetNotifierEnabled(notifier_id, false);
  EXPECT_EQ(
      blink::mojom::PermissionStatus::DENIED,
      profile->GetPermissionController()
          ->GetPermissionResultForOriginWithoutContext(
              notification_permission_descriptor, url::Origin::Create(origin))
          .status);

  // (4) Enable the permission when the default is allowed (expected to clear).
  message_center_client()->SetNotifierEnabled(notifier_id, true);

  EXPECT_EQ(
      blink::mojom::PermissionStatus::GRANTED,
      profile->GetPermissionController()
          ->GetPermissionResultForOriginWithoutContext(
              notification_permission_descriptor, url::Origin::Create(origin))
          .status);

  // Now change the default content setting value to BLOCK.
  HostContentSettingsMapFactory::GetForProfile(profile)
      ->SetDefaultContentSetting(ContentSettingsType::NOTIFICATIONS,
                                 CONTENT_SETTING_BLOCK);

  // (5) Enable the permission when the default is blocked (expected to set).
  message_center_client()->SetNotifierEnabled(notifier_id, true);
  EXPECT_EQ(
      blink::mojom::PermissionStatus::GRANTED,
      profile->GetPermissionController()
          ->GetPermissionResultForOriginWithoutContext(
              notification_permission_descriptor, url::Origin::Create(origin))
          .status);

  // (6) Disable the permission when the default is blocked (expected to clear).
  message_center_client()->SetNotifierEnabled(notifier_id, false);
  EXPECT_EQ(
      blink::mojom::PermissionStatus::DENIED,
      profile->GetPermissionController()
          ->GetPermissionResultForOriginWithoutContext(
              notification_permission_descriptor, url::Origin::Create(origin))
          .status);
}

}  // namespace