File: notification_dispatcher_mojo_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 (439 lines) | stat: -rw-r--r-- 17,032 bytes parent folder | download | duplicates (6)
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
// Copyright 2021 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/mac/notification_dispatcher_mojo.h"

#include <memory>
#include <optional>

#include "base/functional/bind.h"
#include "base/functional/callback.h"
#include "base/functional/callback_helpers.h"
#include "base/memory/raw_ptr.h"
#include "base/path_service.h"
#include "base/process/process_handle.h"
#include "base/test/gmock_callback_support.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/mock_callback.h"
#include "base/time/time.h"
#include "chrome/browser/notifications/mac/mac_notification_provider_factory.h"
#include "chrome/browser/profiles/profile.h"
#include "chrome/common/chrome_paths.h"
#include "chrome/common/notifications/notification_operation.h"
#include "chrome/services/mac_notifications/public/mojom/mac_notifications.mojom.h"
#include "chrome/test/base/testing_browser_process.h"
#include "chrome/test/base/testing_profile_manager.h"
#include "content/public/test/browser_task_environment.h"
#include "mojo/public/cpp/bindings/pending_receiver.h"
#include "mojo/public/cpp/bindings/pending_remote.h"
#include "mojo/public/cpp/bindings/receiver.h"
#include "mojo/public/cpp/bindings/remote.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace {

const char kNotificationId[] = "notification-id";
const char kProfileId[] = "profile-id";

class MockNotificationService
    : public mac_notifications::mojom::MacNotificationService {
 public:
  MOCK_METHOD(void,
              DisplayNotification,
              (mac_notifications::mojom::NotificationPtr),
              (override));
  MOCK_METHOD(void,
              GetDisplayedNotifications,
              (mac_notifications::mojom::ProfileIdentifierPtr,
               const std::optional<GURL>& origin,
               GetDisplayedNotificationsCallback),
              (override));
  MOCK_METHOD(void,
              CloseNotification,
              (mac_notifications::mojom::NotificationIdentifierPtr),
              (override));
  MOCK_METHOD(void,
              CloseNotificationsForProfile,
              (mac_notifications::mojom::ProfileIdentifierPtr),
              (override));
  MOCK_METHOD(void, CloseAllNotifications, (), (override));
  MOCK_METHOD(void,
              OkayToTerminateService,
              (OkayToTerminateServiceCallback),
              (override));
};

class MockNotificationProvider
    : public mac_notifications::mojom::MacNotificationProvider {
 public:
  MOCK_METHOD(
      void,
      BindNotificationService,
      (mojo::PendingReceiver<mac_notifications::mojom::MacNotificationService>,
       mojo::PendingRemote<
           mac_notifications::mojom::MacNotificationActionHandler>),
      (override));
};

class FakeMacNotificationProviderFactory
    : public MacNotificationProviderFactory,
      public mac_notifications::mojom::MacNotificationProvider {
 public:
  explicit FakeMacNotificationProviderFactory(
      base::RepeatingClosure on_disconnect)
      : MacNotificationProviderFactory(
            mac_notifications::NotificationStyle::kAlert),
        on_disconnect_(std::move(on_disconnect)) {}
  ~FakeMacNotificationProviderFactory() override = default;

  // MacNotificationProviderFactory:
  mojo::Remote<mac_notifications::mojom::MacNotificationProvider>
  LaunchProvider() override {
    mojo::Remote<mac_notifications::mojom::MacNotificationProvider> remote;
    provider_receiver_.Bind(remote.BindNewPipeAndPassReceiver());
    provider_receiver_.set_disconnect_handler(
        base::BindOnce(&FakeMacNotificationProviderFactory::Disconnect,
                       base::Unretained(this)));
    return remote;
  }

  // mac_notifications::mojom::MacNotificationProvider:
  void BindNotificationService(
      mojo::PendingReceiver<mac_notifications::mojom::MacNotificationService>
          service,
      mojo::PendingRemote<
          mac_notifications::mojom::MacNotificationActionHandler> handler)
      override {
    service_receiver_.Bind(std::move(service));
    handler_remote_.Bind(std::move(handler));
  }

  MockNotificationService& service() { return mock_service_; }

  mac_notifications::mojom::MacNotificationActionHandler* handler() {
    return handler_remote_.get();
  }

  void Disconnect() {
    handler_remote_.reset();
    service_receiver_.reset();
    provider_receiver_.reset();
    on_disconnect_.Run();
  }

  bool is_service_connected() { return service_receiver_.is_bound(); }

 private:
  base::RepeatingClosure on_disconnect_;
  mojo::Receiver<mac_notifications::mojom::MacNotificationProvider>
      provider_receiver_{this};
  MockNotificationService mock_service_;
  mojo::Receiver<mac_notifications::mojom::MacNotificationService>
      service_receiver_{&mock_service_};
  mojo::Remote<mac_notifications::mojom::MacNotificationActionHandler>
      handler_remote_;
};

message_center::Notification CreateNotification() {
  return message_center::Notification(
      message_center::NOTIFICATION_TYPE_SIMPLE, kNotificationId, u"title",
      u"message", /*icon=*/ui::ImageModel(),
      /*display_source=*/std::u16string(), /*origin_url=*/GURL(),
      message_center::NotifierId(), message_center::RichNotificationData(),
      base::MakeRefCounted<message_center::NotificationDelegate>());
}

mac_notifications::mojom::NotificationMetadataPtr CreateNotificationMetadata() {
  auto profile_identifier = mac_notifications::mojom::ProfileIdentifier::New(
      kProfileId, /*incognito=*/true);
  auto notification_identifier =
      mac_notifications::mojom::NotificationIdentifier::New(
          kNotificationId, std::move(profile_identifier));
  base::FilePath user_data_dir;
  EXPECT_TRUE(base::PathService::Get(chrome::DIR_USER_DATA, &user_data_dir));
  return mac_notifications::mojom::NotificationMetadata::New(
      std::move(notification_identifier), /*notification_type=*/0,
      /*origin_url=*/GURL("https://example.com"), user_data_dir.value());
}

mac_notifications::mojom::NotificationActionInfoPtr
CreateNotificationActionInfo() {
  auto meta = CreateNotificationMetadata();
  return mac_notifications::mojom::NotificationActionInfo::New(
      std::move(meta), NotificationOperation::kClick,
      /*button_index=*/-1, /*reply=*/std::nullopt);
}

}  // namespace

class NotificationDispatcherMojoTest : public testing::Test {
 public:
  NotificationDispatcherMojoTest() = default;

  ~NotificationDispatcherMojoTest() override {
    base::RunLoop run_loop;
    ExpectDisconnect(run_loop.QuitClosure());
    provider_factory_->Disconnect();
    run_loop.Run();
  }

  // testing::Test:
  void SetUp() override {
    ASSERT_TRUE(testing_profile_manager_.SetUp());
    profile_ = testing_profile_manager_.CreateTestingProfile("profile");

    auto provider_factory =
        std::make_unique<FakeMacNotificationProviderFactory>(
            on_disconnect_.Get());
    provider_factory_ = provider_factory.get();

    // NotificationDispatcherMojo will query if it can terminate the service
    // at startup. Once that finishes it should disconnect due to inactivity.
    base::RunLoop run_loop;
    EmulateOkayToTerminate(/*can_terminate=*/true);
    ExpectDisconnect(run_loop.QuitClosure());

    notification_dispatcher_ = std::make_unique<NotificationDispatcherMojo>(
        std::move(provider_factory));
    run_loop.Run();
  }

  MockNotificationService& service() { return provider_factory_->service(); }

  mac_notifications::mojom::MacNotificationActionHandler* handler() {
    return provider_factory_->handler();
  }

 protected:
  void ExpectDisconnect(base::OnceClosure callback) {
    EXPECT_CALL(on_disconnect_, Run())
        .WillOnce(base::test::RunOnceClosure(std::move(callback)))
        .WillRepeatedly(testing::DoDefault());
  }

  void ExpectKeepConnected() {
    EXPECT_CALL(on_disconnect_, Run()).Times(0);
    // Run remaining tasks to see if we get disconnected.
    task_environment_.RunUntilIdle();
  }

  void EmulateOkayToTerminate(bool can_terminate,
                              base::OnceClosure callback = base::DoNothing()) {
    EXPECT_CALL(service(), OkayToTerminateService)
        .WillRepeatedly(testing::DoAll(
            base::test::RunOnceClosure(std::move(callback)),
            [can_terminate](
                MockNotificationService::OkayToTerminateServiceCallback
                    callback) { std::move(callback).Run(can_terminate); }));
  }

  void DisplayNotificationSync() {
    base::RunLoop run_loop;
    EXPECT_CALL(service(), DisplayNotification)
        .WillOnce(base::test::RunOnceClosure(run_loop.QuitClosure()));
    notification_dispatcher_->DisplayNotification(
        NotificationHandler::Type::WEB_PERSISTENT, profile_,
        CreateNotification());
    run_loop.Run();
  }

  content::BrowserTaskEnvironment task_environment_{
      base::test::TaskEnvironment::TimeSource::MOCK_TIME};
  TestingProfileManager testing_profile_manager_{
      TestingBrowserProcess::GetGlobal()};
  raw_ptr<Profile> profile_;
  base::MockRepeatingClosure on_disconnect_;
  std::unique_ptr<NotificationDispatcherMojo> notification_dispatcher_;
  raw_ptr<FakeMacNotificationProviderFactory> provider_factory_ = nullptr;
};

TEST_F(NotificationDispatcherMojoTest, CloseNotificationAndDisconnect) {
  DisplayNotificationSync();

  base::RunLoop run_loop;
  // Expect that we disconnect after closing the last notification.
  ExpectDisconnect(run_loop.QuitClosure());
  EXPECT_CALL(service(), CloseNotification)
      .WillOnce(
          [](mac_notifications::mojom::NotificationIdentifierPtr identifier) {
            EXPECT_EQ(kNotificationId, identifier->id);
            EXPECT_EQ(kProfileId, identifier->profile->id);
            EXPECT_TRUE(identifier->profile->incognito);
          });
  EmulateOkayToTerminate(/*can_terminate=*/true);
  notification_dispatcher_->CloseNotificationWithId(
      {kNotificationId, kProfileId, /*incognito=*/true});
  run_loop.Run();
}

TEST_F(NotificationDispatcherMojoTest, CloseNotificationAndKeepConnected) {
  DisplayNotificationSync();

  base::RunLoop run_loop;
  // Expect that we continue running if there are remaining notifications.
  EXPECT_CALL(service(), CloseNotification);
  EmulateOkayToTerminate(/*can_terminate=*/false, run_loop.QuitClosure());
  notification_dispatcher_->CloseNotificationWithId(
      {kNotificationId, kProfileId, /*incognito=*/true});
  run_loop.Run();
  ExpectKeepConnected();
}

TEST_F(NotificationDispatcherMojoTest,
       CloseThenDispatchNotificationAndKeepConnected) {
  base::RunLoop run_loop;
  DisplayNotificationSync();

  // Expect that we continue running when showing a new notification just after
  // closing the last one.
  EXPECT_CALL(service(), CloseNotification);
  EmulateOkayToTerminate(/*can_terminate=*/true);
  notification_dispatcher_->CloseNotificationWithId(
      {kNotificationId, kProfileId, /*incognito=*/true});

  EXPECT_CALL(service(), DisplayNotification)
      .WillOnce(base::test::RunOnceClosure(run_loop.QuitClosure()));
  notification_dispatcher_->DisplayNotification(
      NotificationHandler::Type::WEB_PERSISTENT, profile_,
      CreateNotification());

  run_loop.Run();
  ExpectKeepConnected();

  base::RunLoop run_loop2;
  // Expect that we disconnect after closing all notifications.
  ExpectDisconnect(run_loop2.QuitClosure());
  EXPECT_CALL(service(), CloseAllNotifications);
  notification_dispatcher_->CloseAllNotifications();
  run_loop2.Run();
}

TEST_F(NotificationDispatcherMojoTest, CloseProfileNotificationsAndDisconnect) {
  DisplayNotificationSync();

  base::RunLoop run_loop;
  // Expect that we disconnect after closing the last notification.
  ExpectDisconnect(run_loop.QuitClosure());
  EXPECT_CALL(service(), CloseNotificationsForProfile)
      .WillOnce([](mac_notifications::mojom::ProfileIdentifierPtr profile) {
        EXPECT_EQ(kProfileId, profile->id);
        EXPECT_TRUE(profile->incognito);
      });
  EmulateOkayToTerminate(/*can_terminate=*/true);
  notification_dispatcher_->CloseNotificationsWithProfileId(kProfileId,
                                                            /*incognito=*/true);
  run_loop.Run();
}

TEST_F(NotificationDispatcherMojoTest, CloseAndDisconnectTiming) {
  base::HistogramTester histograms;
  // Show a new notification.
  EXPECT_CALL(service(), DisplayNotification);
  notification_dispatcher_->DisplayNotification(
      NotificationHandler::Type::WEB_PERSISTENT, profile_,
      CreateNotification());

  // Wait for 30 seconds and close the notification.
  auto delay = base::Seconds(30);
  task_environment_.FastForwardBy(delay);

  // Expect that we disconnect after closing the last notification.
  base::RunLoop run_loop;
  ExpectDisconnect(run_loop.QuitClosure());
  EmulateOkayToTerminate(/*can_terminate=*/true);
  EXPECT_CALL(service(), CloseNotification);
  notification_dispatcher_->CloseNotificationWithId(
      {kNotificationId, kProfileId, /*incognito=*/true});

  // Verify that we log the runtime length and no unexpected kill.
  run_loop.Run();
  histograms.ExpectUniqueTimeSample("Notifications.macOS.ServiceProcessRuntime",
                                    delay, /*expected_count=*/1);
  histograms.ExpectTotalCount("Notifications.macOS.ServiceProcessKilled",
                              /*count=*/0);
}

TEST_F(NotificationDispatcherMojoTest, KillServiceTiming) {
  base::HistogramTester histograms;
  // Show a new notification.
  EXPECT_CALL(service(), DisplayNotification);
  notification_dispatcher_->DisplayNotification(
      NotificationHandler::Type::WEB_PERSISTENT, profile_,
      CreateNotification());

  // Wait for 30 seconds and terminate the service.
  auto delay = base::Seconds(30);
  task_environment_.FastForwardBy(delay);
  // Simulate a dying service process.
  provider_factory_->Disconnect();

  // Run remaining tasks as we can't observe the disconnect callback.
  task_environment_.RunUntilIdle();
  // Verify that we log the runtime length and an unexpected kill.
  histograms.ExpectUniqueTimeSample("Notifications.macOS.ServiceProcessRuntime",
                                    delay, /*expected_count=*/1);
  histograms.ExpectUniqueTimeSample("Notifications.macOS.ServiceProcessKilled",
                                    delay, /*expected_count=*/1);
}

TEST_F(NotificationDispatcherMojoTest, DidActivateNotification) {
  base::HistogramTester histograms;
  // Show a new notification.
  EmulateOkayToTerminate(/*can_terminate=*/true);
  EXPECT_CALL(service(), DisplayNotification);
  notification_dispatcher_->DisplayNotification(
      NotificationHandler::Type::WEB_PERSISTENT, profile_,
      CreateNotification());

  // Wait until the action handler has been bound.
  task_environment_.RunUntilIdle();
  handler()->OnNotificationAction(CreateNotificationActionInfo());

  // Handling responses is async, make sure we wait for all tasks to complete.
  task_environment_.RunUntilIdle();
}

TEST_F(NotificationDispatcherMojoTest, TestUnexpectedDisconnectReconnects) {
  // Display a notification and verify that the service is running.
  DisplayNotificationSync();
  EXPECT_TRUE(provider_factory_->is_service_connected());

  // Disconnect after 30 seconds while there is still a notification on screen.
  task_environment_.FastForwardBy(base::Seconds(30));
  provider_factory_->Disconnect();
  EXPECT_FALSE(provider_factory_->is_service_connected());

  // Expect the service to be restarted after a short timeout.
  EmulateOkayToTerminate(/*can_terminate=*/false);
  task_environment_.FastForwardBy(base::Milliseconds(500));
  EXPECT_TRUE(provider_factory_->is_service_connected());
}

TEST_F(NotificationDispatcherMojoTest, TestReconnectBackoff) {
  // Display a notification and verify that the service is running.
  DisplayNotificationSync();
  // Disconnect after 30 seconds while there is still a notification on screen.
  task_environment_.FastForwardBy(base::Seconds(30));
  provider_factory_->Disconnect();

  // Verify the service hasn't restarted if not enough time has passed.
  task_environment_.FastForwardBy(base::Milliseconds(499));
  EXPECT_FALSE(provider_factory_->is_service_connected());
  // Expect the service to be restarted after a short timeout.
  EmulateOkayToTerminate(/*can_terminate=*/false);
  task_environment_.FastForwardBy(base::Milliseconds(1));
  EXPECT_TRUE(provider_factory_->is_service_connected());

  // Disconnect again immediately which should double the restart timeout.
  provider_factory_->Disconnect();

  // Verify the service hasn't restarted if not enough time has passed.
  task_environment_.FastForwardBy(base::Milliseconds(999));
  EXPECT_FALSE(provider_factory_->is_service_connected());
  // Expect the service to be restarted after a short timeout.
  EmulateOkayToTerminate(/*can_terminate=*/false);
  task_environment_.FastForwardBy(base::Milliseconds(1));
  EXPECT_TRUE(provider_factory_->is_service_connected());
}