File: background_download_service_impl_unittest.cc

package info (click to toggle)
chromium 139.0.7258.127-2
  • links: PTS, VCS
  • area: main
  • in suites: forky
  • size: 6,122,156 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 (293 lines) | stat: -rw-r--r-- 12,271 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
// 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 "components/download/internal/background_service/ios/background_download_service_impl.h"

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

#include "base/files/scoped_temp_dir.h"
#include "base/test/gmock_callback_support.h"
#include "base/test/metrics/histogram_tester.h"
#include "base/test/mock_callback.h"
#include "base/test/simple_test_clock.h"
#include "base/test/task_environment.h"
#include "components/download/internal/background_service/client_set.h"
#include "components/download/internal/background_service/ios/background_download_task_helper.h"
#include "components/download/internal/background_service/test/black_hole_log_sink.h"
#include "components/download/internal/background_service/test/mock_file_monitor.h"
#include "components/download/internal/background_service/test/test_store.h"
#include "components/download/public/background_service/test/empty_logger.h"
#include "components/download/public/background_service/test/mock_client.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "testing/platform_test.h"

using ::base::test::RunCallback;
using ::base::test::RunOnceCallback;
using ::testing::_;
using ::testing::NiceMock;
using ServiceStatus = download::BackgroundDownloadService::ServiceStatus;
using StartResult = download::DownloadParams::StartResult;

const char kURL[] = "https://www.example.com/test";
const char kGuid[] = "1234";
const char kGuid1[] = "5678";
const char kGuid2[] = "aabb";
const char kGuid3[] = "yyds";
const base::FilePath::CharType kFilePath[] =
    FILE_PATH_LITERAL("downloaded_file.zip");
const char kCompletionHistogram[] = "Download.Service.Finish.Type";
const char kStartResultHistogram[] = "Download.Service.Request.StartResult";
const char kServiceStartUpResultHistogram[] =
    "Download.Service.StartUpStatus.Initialization";

namespace download {
namespace {

MATCHER_P(CompletionInfoIs, file_path, "") {
  return arg.path == file_path;
}

class MockBackgroundDownloadTaskHelper : public BackgroundDownloadTaskHelper {
 public:
  MockBackgroundDownloadTaskHelper() = default;
  ~MockBackgroundDownloadTaskHelper() override = default;
  MOCK_METHOD(void,
              StartDownload,
              (const std::string& guid,
               const base::FilePath& target_path,
               const RequestParams&,
               const SchedulingParams&,
               CompletionCallback,
               UpdateCallback),
              (override));
};

// Test fixture for BackgroundDownloadServiceImpl.
class BackgroundDownloadServiceImplTest : public PlatformTest {
 protected:
  BackgroundDownloadServiceImplTest() = default;
  ~BackgroundDownloadServiceImplTest() override = default;

  void SetUp() override {
    ASSERT_TRUE(dir_.CreateUniqueTempDir());
    auto store = std::make_unique<test::TestStore>();
    store_ = store.get();
    auto model = std::make_unique<ModelImpl>(std::move(store));
    model_ = model.get();
    auto client = std::make_unique<NiceMock<test::MockClient>>();
    client_ = client.get();
    auto clients = std::make_unique<DownloadClientMap>();
    clients->insert(std::make_pair(DownloadClient::TEST, std::move(client)));
    auto client_set = std::make_unique<ClientSet>(std::move(clients));
    auto download_helper = std::make_unique<MockBackgroundDownloadTaskHelper>();
    download_helper_ = download_helper.get();
    auto file_monitor = std::make_unique<NiceMock<MockFileMonitor>>();
    file_monitor_ = file_monitor.get();
    auto logger = std::make_unique<test::EmptyLogger>();
    service_ = std::make_unique<BackgroundDownloadServiceImpl>(
        std::move(client_set), std::move(model), std::move(download_helper),
        std::move(file_monitor), dir_.GetPath(), std::move(logger), &log_sink_,
        &clock_);
    ON_CALL(*file_monitor_, DeleteUnknownFiles(_, _, _))
        .WillByDefault(base::test::RunOnceCallbackRepeatedly<2>());
    service_->Initialize(base::DoNothing());
  }

  InitializableBackgroundDownloadService* service() { return service_.get(); }
  std::unique_ptr<std::vector<Entry>> empty_entries() {
    return std::make_unique<std::vector<Entry>>();
  }
  DownloadParams CreateDownloadParams(const std::string& url) {
    DownloadParams download_params;
    download_params.client = DownloadClient::TEST;
    download_params.guid = kGuid;
    download_params.callback = start_callback_.Get();
    download_params.request_params.url = GURL(url);
    download_params.custom_data["foo"] = "foobar";
    return download_params;
  }

  void Init() { InitWithData(empty_entries()); }

  // Initializes with preloaded |entries| from the database.
  void InitWithData(std::unique_ptr<std::vector<Entry>> entries) {
    store_->TriggerInit(/*success=*/true, std::move(entries));
    file_monitor_->TriggerInit(/*success=*/true);
  }

  base::test::TaskEnvironment task_environment_;
  base::ScopedTempDir dir_;
  base::SimpleTestClock clock_;
  MockBackgroundDownloadTaskHelper* download_helper_;
  test::TestStore* store_;
  Model* model_;
  test::MockClient* client_;
  base::MockCallback<DownloadParams::StartCallback> start_callback_;
  MockFileMonitor* file_monitor_;
  base::HistogramTester histogram_tester_;

 private:
  test::BlackHoleLogSink log_sink_;
  std::unique_ptr<InitializableBackgroundDownloadService> service_;
};

TEST_F(BackgroundDownloadServiceImplTest, InitSuccess) {
  EXPECT_EQ(ServiceStatus::STARTING_UP, service()->GetStatus());
  EXPECT_CALL(*client_, OnServiceInitialized(false, _));
  Init();
  EXPECT_EQ(ServiceStatus::READY, service()->GetStatus());
  histogram_tester_.ExpectBucketCount(kServiceStartUpResultHistogram,
                                      stats::StartUpResult::SUCCESS, 1);
}

TEST_F(BackgroundDownloadServiceImplTest, InitDbFailure) {
  EXPECT_EQ(ServiceStatus::STARTING_UP, service()->GetStatus());
  EXPECT_CALL(*client_, OnServiceUnavailable());
  store_->TriggerInit(/*success=*/false, empty_entries());
  task_environment_.RunUntilIdle();
  EXPECT_EQ(ServiceStatus::UNAVAILABLE, service()->GetStatus());
  histogram_tester_.ExpectBucketCount(
      kServiceStartUpResultHistogram,
      stats::StartUpResult::FAILURE_REASON_MODEL, 1);
}

TEST_F(BackgroundDownloadServiceImplTest, InitFileMonitorFailure) {
  EXPECT_EQ(ServiceStatus::STARTING_UP, service()->GetStatus());
  EXPECT_CALL(*client_, OnServiceUnavailable());
  store_->TriggerInit(/*success=*/true, empty_entries());
  file_monitor_->TriggerInit(/*success=*/false);
  task_environment_.RunUntilIdle();
  EXPECT_EQ(ServiceStatus::UNAVAILABLE, service()->GetStatus());
  histogram_tester_.ExpectBucketCount(
      kServiceStartUpResultHistogram,
      stats::StartUpResult::FAILURE_REASON_FILE_MONITOR, 1);
}

// Db records that are not associated with any registered clients or unfinished
// downloads should be pruned.
TEST_F(BackgroundDownloadServiceImplTest, InitDbPruned) {
  EXPECT_EQ(ServiceStatus::STARTING_UP, service()->GetStatus());
  EXPECT_CALL(*client_, OnServiceInitialized(false, _));
  std::unique_ptr<std::vector<Entry>> entries =
      std::make_unique<std::vector<Entry>>();

  // Build an entry without a valid client.
  Entry entry_invalid_client;
  entry_invalid_client.state = Entry::State::COMPLETE;
  entry_invalid_client.guid = kGuid;
  entry_invalid_client.create_time = clock_.Now();
  entries->emplace_back(std::move(entry_invalid_client));

  // Build unfinished entry.
  Entry entry_unfinished;
  entry_unfinished.client = DownloadClient::TEST;
  entry_unfinished.state = Entry::State::ACTIVE;
  entry_unfinished.guid = kGuid1;
  entry_unfinished.create_time = clock_.Now();
  entries->emplace_back(std::move(entry_unfinished));

  // Build an expired entry.
  Entry entry_expired;
  entry_expired.client = DownloadClient::TEST;
  entry_expired.state = Entry::State::COMPLETE;
  entry_expired.guid = kGuid2;
  entry_expired.create_time = clock_.Now() - base::Days(300);
  entries->emplace_back(std::move(entry_expired));

  // Build a completed entry that should be kept.
  Entry entry;
  entry.client = DownloadClient::TEST;
  entry.state = Entry::State::COMPLETE;
  entry.guid = kGuid3;
  entry.create_time = clock_.Now();
  entries->emplace_back(std::move(entry));

  InitWithData(std::move(entries));
  EXPECT_EQ(ServiceStatus::READY, service()->GetStatus());
  EXPECT_FALSE(model_->Get(kGuid))
      << "Entry with invalid client should be pruned.";
  EXPECT_FALSE(model_->Get(kGuid1)) << "Unfinished entry should be pruned.";
  EXPECT_FALSE(model_->Get(kGuid2)) << "Expired entry should be pruned.";
  EXPECT_TRUE(model_->Get(kGuid3)) << "This entry should be kept.";
}

TEST_F(BackgroundDownloadServiceImplTest, StartDownloadDbFailure) {
  Init();
  EXPECT_CALL(start_callback_, Run(kGuid, StartResult::INTERNAL_ERROR));
  auto download_params = CreateDownloadParams(kURL);
  service()->StartDownload(std::move(download_params));
  store_->TriggerUpdate(/*success=*/false);
  EXPECT_EQ(kGuid, store_->LastUpdatedEntry()->guid);
  task_environment_.RunUntilIdle();
  histogram_tester_.ExpectBucketCount(
      kStartResultHistogram, DownloadParams::StartResult::INTERNAL_ERROR, 1);
}

// Verifies the case for failure in platform api.
TEST_F(BackgroundDownloadServiceImplTest, StartDownloadHelperFailure) {
  Init();
  EXPECT_CALL(start_callback_, Run(kGuid, StartResult::ACCEPTED));
  EXPECT_CALL(*download_helper_, StartDownload(_, _, _, _, _, _))
      .WillOnce(RunOnceCallback<4>(/*success=*/false, base::FilePath(), 0));
  EXPECT_CALL(*client_,
              OnDownloadFailed(kGuid, CompletionInfoIs(base::FilePath()),
                               download::Client::FailureReason::UNKNOWN));
  auto download_params = CreateDownloadParams(kURL);
  service()->StartDownload(std::move(download_params));
  store_->TriggerUpdate(/*success=*/true);
  EXPECT_EQ(kGuid, store_->LastRemovedEntry());
  task_environment_.RunUntilIdle();
  histogram_tester_.ExpectBucketCount(kCompletionHistogram,
                                      CompletionType::FAIL, 1);
}

// Verifies the case for a successful download.
TEST_F(BackgroundDownloadServiceImplTest, StartDownloadSuccess) {
  Init();
  EXPECT_CALL(start_callback_, Run(kGuid, StartResult::ACCEPTED));
  EXPECT_CALL(*download_helper_, StartDownload(_, _, _, _, _, _))
      .WillOnce(
          RunOnceCallback<4>(/*success=*/true, base::FilePath(kFilePath), 0));
  EXPECT_CALL(
      *client_,
      OnDownloadSucceeded(kGuid, CompletionInfoIs(base::FilePath(kFilePath))));
  auto download_params = CreateDownloadParams(kURL);
  service()->StartDownload(std::move(download_params));
  store_->TriggerUpdate(/*success=*/true);
  EXPECT_EQ(kGuid, store_->LastUpdatedEntry()->guid);
  EXPECT_EQ(clock_.Now(), store_->LastUpdatedEntry()->create_time);
  EXPECT_EQ(clock_.Now(), store_->LastUpdatedEntry()->completion_time);
  EXPECT_EQ(Entry::State::COMPLETE, store_->LastUpdatedEntry()->state);
  EXPECT_EQ(dir_.GetPath().AppendASCII(kGuid),
            store_->LastUpdatedEntry()->target_file_path);
  EXPECT_EQ("foobar", store_->LastUpdatedEntry()->custom_data.at("foo"));
  task_environment_.RunUntilIdle();
  histogram_tester_.ExpectBucketCount(kCompletionHistogram,
                                      CompletionType::SUCCEED, 1);
}

// Verifies Client::OnDownloadUpdated() is called.
TEST_F(BackgroundDownloadServiceImplTest, OnDownloadUpdated) {
  Init();
  EXPECT_CALL(start_callback_, Run(kGuid, StartResult::ACCEPTED));
  EXPECT_CALL(*download_helper_, StartDownload(_, _, _, _, _, _))
      .WillOnce(RunCallback<5>(10u));
  EXPECT_CALL(*client_, OnDownloadUpdated(kGuid, 0u, 10u));
  auto download_params = CreateDownloadParams(kURL);
  service()->StartDownload(std::move(download_params));

  // Advance the time to make sure the update is not throttled.
  clock_.Advance(base::Seconds(11));
  store_->TriggerUpdate(/*success=*/true);
  EXPECT_EQ(kGuid, store_->LastUpdatedEntry()->guid);
  EXPECT_EQ(10u, store_->LastUpdatedEntry()->bytes_downloaded);
  EXPECT_EQ("foobar", store_->LastUpdatedEntry()->custom_data.at("foo"));
  task_environment_.RunUntilIdle();
}

}  // namespace
}  // namespace download