File: download_item_notification_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 (453 lines) | stat: -rw-r--r-- 17,743 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
440
441
442
443
444
445
446
447
448
449
450
451
452
453
// Copyright 2015 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/download/notification/download_item_notification.h"

#include <stddef.h>

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

#include "base/containers/contains.h"
#include "base/files/file_path.h"
#include "base/json/json_reader.h"
#include "base/memory/raw_ptr.h"
#include "base/run_loop.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/test_simple_task_runner.h"
#include "base/uuid.h"
#include "build/build_config.h"
#include "chrome/browser/download/chrome_download_manager_delegate.h"
#include "chrome/browser/download/download_commands.h"
#include "chrome/browser/download/notification/download_notification_manager.h"
#include "chrome/browser/download/offline_item_utils.h"
#include "chrome/browser/enterprise/connectors/test/deep_scanning_test_utils.h"
#include "chrome/browser/notifications/notification_display_service.h"
#include "chrome/browser/notifications/notification_display_service_factory.h"
#include "chrome/browser/notifications/notification_display_service_tester.h"
#include "chrome/browser/notifications/notification_handler.h"
#include "chrome/browser/notifications/notification_test_util.h"
#include "chrome/browser/notifications/platform_notification_service_impl.h"
#include "chrome/test/base/testing_browser_process.h"
#include "chrome/test/base/testing_profile.h"
#include "chrome/test/base/testing_profile_manager.h"
#include "components/download/public/common/download_danger_type.h"
#include "components/download/public/common/download_item.h"
#include "components/download/public/common/mock_download_item.h"
#include "content/public/browser/download_item_utils.h"
#include "content/public/test/browser_task_environment.h"
#include "content/public/test/mock_download_manager.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"

#if BUILDFLAG(IS_CHROMEOS)
#include "chrome/browser/apps/app_service/app_service_proxy.h"
#include "chrome/browser/apps/app_service/app_service_proxy_factory.h"
#include "chrome/browser/apps/app_service/app_service_test.h"
#include "chrome/common/pref_names.h"
#include "components/services/app_service/public/cpp/app_types.h"
#include "components/sync_preferences/testing_pref_service_syncable.h"
#endif

using testing::_;
using testing::NiceMock;
using testing::Return;
using testing::ReturnRefOfCopy;
using testing::ValuesIn;

namespace {

const char kPdfMimeType[] = "application/pdf";
const char kMp3MimeType[] = "audio/mpeg";

const base::FilePath::CharType kDownloadItemTargetPathString[] =
    FILE_PATH_LITERAL("/tmp/TITLE.bin");

}  // anonymous namespace

namespace test {

class DownloadItemNotificationTest : public testing::Test {
 public:
  DownloadItemNotificationTest() : profile_(nullptr) {}

  void SetUp() override {
    testing::Test::SetUp();

    profile_manager_ = std::make_unique<TestingProfileManager>(
        TestingBrowserProcess::GetGlobal());
    ASSERT_TRUE(profile_manager_->SetUp());
    profile_ = profile_manager_->CreateTestingProfile("test-user");

    service_tester_ =
        std::make_unique<NotificationDisplayServiceTester>(profile_);

    download_notification_manager_ =
        std::make_unique<DownloadNotificationManager>(profile_);

    base::FilePath download_item_target_path(kDownloadItemTargetPathString);
    download_item_ = std::make_unique<NiceMock<download::MockDownloadItem>>();
    ON_CALL(*download_item_, GetId()).WillByDefault(Return(12345));
    ON_CALL(*download_item_, GetGuid())
        .WillByDefault(ReturnRefOfCopy(
            base::Uuid::GenerateRandomV4().AsLowercaseString()));
    ON_CALL(*download_item_, GetState())
        .WillByDefault(Return(download::DownloadItem::IN_PROGRESS));
    ON_CALL(*download_item_, IsDangerous()).WillByDefault(Return(false));
    ON_CALL(*download_item_, GetFileNameToReportUser())
        .WillByDefault(Return(base::FilePath("TITLE.bin")));
    ON_CALL(*download_item_, GetTargetFilePath())
        .WillByDefault(ReturnRefOfCopy(download_item_target_path));
    ON_CALL(*download_item_, GetDangerType())
        .WillByDefault(Return(download::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS));
    ON_CALL(*download_item_, IsDone()).WillByDefault(Return(false));
    ON_CALL(*download_item_, GetURL())
        .WillByDefault(
            ReturnRefOfCopy(GURL("http://www.example.com/download.bin")));
    content::DownloadItemUtils::AttachInfoForTesting(download_item_.get(),
                                                     profile_, nullptr);
  }

  void TearDown() override {
    download_item_notification_ = nullptr;  // will be free'd in the manager.
    download_notification_manager_.reset();
    profile_manager_.reset();
    testing::Test::TearDown();
  }

 protected:
  std::string notification_id() const {
    return download_item_notification_->notification_->id();
  }

  std::unique_ptr<message_center::Notification> LookUpNotification() const {
    std::vector<message_center::Notification> notifications =
        service_tester_->GetDisplayedNotificationsForType(
            NotificationHandler::Type::TRANSIENT);
    for (const auto& notification : notifications) {
      if (notification.id() == download_item_notification_->GetNotificationId())
        return std::make_unique<message_center::Notification>(notification);
    }
    return nullptr;
  }

  size_t NotificationCount() const {
    return service_tester_
        ->GetDisplayedNotificationsForType(NotificationHandler::Type::TRANSIENT)
        .size();
  }

  void RemoveNotification() {
    service_tester_->RemoveNotification(
        NotificationHandler::Type::TRANSIENT,
        download_item_notification_->GetNotificationId(), false);
  }

  void CreateDownloadItemNotification() {
    offline_items_collection::ContentId id(
        OfflineItemUtils::GetDownloadNamespacePrefix(
            profile_->IsOffTheRecord()),
        download_item_->GetGuid());
    download_notification_manager_->OnNewDownloadReady(download_item_.get());

    download_item_notification_ =
        download_notification_manager_->items_.at(id).get();
  }

  std::u16string GetStatusString() {
    return download_item_notification_->GetStatusString();
  }

  std::unique_ptr<std::vector<DownloadCommands::Command>> GetExtraActions() {
    return download_item_notification_->GetExtraActions();
  }

  std::u16string GetCommandLabel(DownloadCommands::Command command) const {
    return download_item_notification_->GetCommandLabel(command);
  }

#if BUILDFLAG(IS_CHROMEOS)
  void InstallChromeApp(const std::string& app_id) {
    apps::AppServiceProxy* proxy =
        apps::AppServiceProxyFactory::GetForProfile(profile_);
    WaitForAppServiceProxyReady(proxy);

    std::vector<apps::AppPtr> apps;
    apps::AppPtr app =
        std::make_unique<apps::App>(apps::AppType::kChromeApp, app_id);
    app->readiness = apps::Readiness::kReady;
    app->policy_ids = {app_id};
    apps.push_back(std::move(app));

    proxy->OnApps(std::move(apps), apps::AppType::kChromeApp,
                  /*should_notify_initialized=*/false);
  }
#endif

  content::BrowserTaskEnvironment task_environment_;

  std::unique_ptr<TestingProfileManager> profile_manager_;
  raw_ptr<TestingProfile, DanglingUntriaged> profile_;

  std::unique_ptr<NiceMock<download::MockDownloadItem>> download_item_;
  std::unique_ptr<DownloadNotificationManager> download_notification_manager_;
  raw_ptr<DownloadItemNotification> download_item_notification_;
  std::unique_ptr<NotificationDisplayServiceTester> service_tester_;
};

TEST_F(DownloadItemNotificationTest, ShowAndCloseNotification) {
  base::HistogramTester histograms;
  EXPECT_EQ(0u, NotificationCount());

  // Shows a notification.
  CreateDownloadItemNotification();
  download_item_->NotifyObserversDownloadOpened();
  EXPECT_EQ(1u, NotificationCount());

  // Makes sure the DownloadItem::Cancel() is not called.
  EXPECT_CALL(*download_item_, Cancel(_)).Times(0);
  // Closes it once.
  RemoveNotification();

  // Confirms that the notification is closed.
  EXPECT_EQ(0u, NotificationCount());

  // Makes sure the DownloadItem::Cancel() is never called.
  EXPECT_CALL(*download_item_, Cancel(_)).Times(0);

  // Not logged because the download is safe.
  histograms.ExpectTotalCount("Download.ShowedDownloadWarning", 0);
}

TEST_F(DownloadItemNotificationTest, ShowAndCloseDangerousNotification) {
  base::HistogramTester histograms;
  EXPECT_CALL(*download_item_, GetDangerType())
      .WillRepeatedly(Return(download::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT));
  EXPECT_CALL(*download_item_, IsDangerous()).WillRepeatedly(Return(true));

  // Shows a notification
  CreateDownloadItemNotification();
  download_item_->NotifyObserversDownloadOpened();
  EXPECT_EQ(1u, NotificationCount());

  // Closes it once.
  RemoveNotification();

  // Confirms that the notification is closed.
  EXPECT_EQ(0u, NotificationCount());

  // The download warning showed histogram is logged.
  histograms.ExpectBucketCount("Download.ShowedDownloadWarning",
                               download::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT,
                               1);
}

TEST_F(DownloadItemNotificationTest, PauseAndResumeNotification) {
  // Shows a notification
  CreateDownloadItemNotification();
  download_item_->NotifyObserversDownloadOpened();

  // Confirms that the notification is shown as a popup.
  EXPECT_EQ(1u, NotificationCount());

  // Pauses and makes sure the DownloadItem::Pause() is called.
  EXPECT_CALL(*download_item_, Pause()).Times(1);
  EXPECT_CALL(*download_item_, IsPaused()).WillRepeatedly(Return(true));
  download_item_notification_->Click(0, std::nullopt);
  download_item_->NotifyObserversDownloadUpdated();

  // Resumes and makes sure the DownloadItem::Resume() is called.
  EXPECT_CALL(*download_item_, Resume(true)).Times(1);
  EXPECT_CALL(*download_item_, IsPaused()).WillRepeatedly(Return(false));
  download_item_notification_->Click(0, std::nullopt);
  download_item_->NotifyObserversDownloadUpdated();
}

TEST_F(DownloadItemNotificationTest, OpenDownload) {
  EXPECT_CALL(*download_item_, GetState())
      .WillRepeatedly(Return(download::DownloadItem::COMPLETE));
  EXPECT_CALL(*download_item_, IsDone()).WillRepeatedly(Return(true));

  // Shows a notification.
  CreateDownloadItemNotification();
  download_item_->NotifyObserversDownloadOpened();
  download_item_->NotifyObserversDownloadUpdated();

  // Clicks and confirms that the OpenDownload() is called.
  EXPECT_CALL(*download_item_, OpenDownload()).Times(1);
  EXPECT_CALL(*download_item_, SetOpenWhenComplete(_)).Times(0);
  download_item_notification_->Click(std::nullopt, std::nullopt);
}

TEST_F(DownloadItemNotificationTest, OpenWhenComplete) {
  // Shows a notification
  CreateDownloadItemNotification();
  download_item_->NotifyObserversDownloadOpened();

  EXPECT_CALL(*download_item_, OpenDownload()).Times(0);

  // Toggles open-when-complete (new value: true).
  EXPECT_CALL(*download_item_, SetOpenWhenComplete(true))
      .Times(1)
      .WillOnce(Return());
  download_item_notification_->Click(std::nullopt, std::nullopt);
  EXPECT_CALL(*download_item_, GetOpenWhenComplete())
      .WillRepeatedly(Return(true));

  // Toggles open-when-complete (new value: false).
  EXPECT_CALL(*download_item_, SetOpenWhenComplete(false))
      .Times(1)
      .WillOnce(Return());
  download_item_notification_->Click(std::nullopt, std::nullopt);
  EXPECT_CALL(*download_item_, GetOpenWhenComplete())
      .WillRepeatedly(Return(false));

  // Sets open-when-complete.
  EXPECT_CALL(*download_item_, SetOpenWhenComplete(true))
      .Times(1)
      .WillOnce(Return());
  download_item_notification_->Click(std::nullopt, std::nullopt);
  EXPECT_CALL(*download_item_, GetOpenWhenComplete())
      .WillRepeatedly(Return(true));

  // Downloading is completed.
  EXPECT_CALL(*download_item_, GetState())
      .WillRepeatedly(Return(download::DownloadItem::COMPLETE));
  EXPECT_CALL(*download_item_, IsDone()).WillRepeatedly(Return(true));
  download_item_->NotifyObserversDownloadUpdated();

  // DownloadItem::OpenDownload must not be called since the file opens
  // automatically due to the open-when-complete flag.
}

TEST_F(DownloadItemNotificationTest, DisablePopup) {
  CreateDownloadItemNotification();
  download_item_->NotifyObserversDownloadOpened();

  EXPECT_EQ(message_center::DEFAULT_PRIORITY, LookUpNotification()->priority());

  download_item_notification_->DisablePopup();

  // Priority is low.
  EXPECT_EQ(message_center::LOW_PRIORITY, LookUpNotification()->priority());

  // Downloading is completed.
  EXPECT_CALL(*download_item_, GetState())
      .WillRepeatedly(Return(download::DownloadItem::COMPLETE));
  EXPECT_CALL(*download_item_, IsDone()).WillRepeatedly(Return(true));
  download_item_->NotifyObserversDownloadUpdated();

  // Priority is increased by the download's completion.
  EXPECT_GT(LookUpNotification()->priority(), message_center::LOW_PRIORITY);
}

TEST_F(DownloadItemNotificationTest, DeepScanning) {
  // Setup deep scanning in progress.
  EXPECT_CALL(*download_item_, GetDangerType())
      .WillRepeatedly(Return(download::DOWNLOAD_DANGER_TYPE_ASYNC_SCANNING));
  auto state =
      std::make_unique<ChromeDownloadManagerDelegate::SafeBrowsingState>();
  download_item_->SetUserData(&ChromeDownloadManagerDelegate::
                                  SafeBrowsingState::kSafeBrowsingUserDataKey,
                              std::move(state));
  CreateDownloadItemNotification();

  // Can't open while scanning.
  enterprise_connectors::test::SetAnalysisConnector(
      profile_->GetPrefs(), enterprise_connectors::FILE_DOWNLOADED,
      R"(
        {
          "service_provider": "google",
          "enable": [{"url_list": ["*"], "tags": ["malware"]}],
          "block_until_verdict": 1
        }
      )");
  EXPECT_CALL(*download_item_, OpenDownload()).Times(0);
  EXPECT_CALL(*download_item_, SetOpenWhenComplete(true)).Times(1);
  EXPECT_EQ(u"TITLE.bin is being scanned.", GetStatusString());
  download_item_notification_->Click(std::nullopt, std::nullopt);

  // Can be opened while scanning.
  enterprise_connectors::test::SetAnalysisConnector(
      profile_->GetPrefs(), enterprise_connectors::FILE_DOWNLOADED,
      R"(
        {
          "service_provider": "google",
          "enable": [{"url_list": ["*"], "tags": ["malware"]}],
          "block_until_verdict": 0
        }
      )");
  EXPECT_CALL(*download_item_, OpenDownload()).Times(1);
  EXPECT_EQ(u"TITLE.bin is being scanned.", GetStatusString());
  download_item_notification_->Click(std::nullopt, std::nullopt);

  // Scanning finished, warning.
  EXPECT_CALL(*download_item_, IsDangerous()).WillRepeatedly(Return(true));
  EXPECT_CALL(*download_item_, GetDangerType())
      .WillRepeatedly(
          Return(download::DOWNLOAD_DANGER_TYPE_SENSITIVE_CONTENT_WARNING));
  EXPECT_CALL(*download_item_, OpenDownload()).Times(0);
  EXPECT_CALL(*download_item_, SetOpenWhenComplete(true)).Times(0);
  download_item_notification_->Click(std::nullopt, std::nullopt);

  // Scanning finished, blocked.
  EXPECT_CALL(*download_item_, IsDangerous()).WillRepeatedly(Return(true));
  EXPECT_CALL(*download_item_, GetDangerType())
      .WillRepeatedly(
          Return(download::DOWNLOAD_DANGER_TYPE_SENSITIVE_CONTENT_BLOCK));
  EXPECT_CALL(*download_item_, OpenDownload()).Times(0);
  EXPECT_CALL(*download_item_, SetOpenWhenComplete(true)).Times(0);
  download_item_notification_->Click(std::nullopt, std::nullopt);

  // Scanning finished, safe.
  EXPECT_CALL(*download_item_, IsDangerous()).WillRepeatedly(Return(false));
  EXPECT_CALL(*download_item_, GetDangerType())
      .WillRepeatedly(Return(download::DOWNLOAD_DANGER_TYPE_DEEP_SCANNED_SAFE));
  EXPECT_CALL(*download_item_, GetState())
      .WillRepeatedly(Return(download::DownloadItem::COMPLETE));
  EXPECT_CALL(*download_item_, OpenDownload()).Times(1);
  download_item_notification_->Click(std::nullopt, std::nullopt);
}

// Test that EDIT_WITH_MEDIA_APP is added for pdf file on CHROMEOS.
// It should not be added for other build configs.
TEST_F(DownloadItemNotificationTest, NotificationActionsForPdf) {
  ON_CALL(*download_item_, GetState)
      .WillByDefault(Return(download::DownloadItem::COMPLETE));
  ON_CALL(*download_item_, IsDone).WillByDefault(Return(true));
  ON_CALL(*download_item_, GetMimeType).WillByDefault(Return(kPdfMimeType));

  CreateDownloadItemNotification();
  auto actions = GetExtraActions();

#if BUILDFLAG(IS_CHROMEOS)
  EXPECT_TRUE(base::Contains(*actions, DownloadCommands::EDIT_WITH_MEDIA_APP));
  EXPECT_EQ(u"Open and edit",
            GetCommandLabel(DownloadCommands::EDIT_WITH_MEDIA_APP));
#else
  EXPECT_FALSE(base::Contains(*actions, DownloadCommands::EDIT_WITH_MEDIA_APP));
#endif
}

// Test that OPEN_WITH_MEDIA_APP is added for audio file on CHROMEOS.
// It should not be added for other build configs.
TEST_F(DownloadItemNotificationTest, NotificationActionsForAudio) {
  ON_CALL(*download_item_, GetState)
      .WillByDefault(Return(download::DownloadItem::COMPLETE));
  ON_CALL(*download_item_, IsDone).WillByDefault(Return(true));
  ON_CALL(*download_item_, GetMimeType).WillByDefault(Return(kMp3MimeType));

  CreateDownloadItemNotification();
  auto actions = GetExtraActions();

#if BUILDFLAG(IS_CHROMEOS)
  EXPECT_TRUE(base::Contains(*actions, DownloadCommands::OPEN_WITH_MEDIA_APP));
  EXPECT_EQ(u"Open", GetCommandLabel(DownloadCommands::OPEN_WITH_MEDIA_APP));
#else
  EXPECT_FALSE(base::Contains(*actions, DownloadCommands::OPEN_WITH_MEDIA_APP));
#endif
}

}  // namespace test