Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(251)

Side by Side Diff: content/browser/background_fetch/background_fetch_service_unittest.cc

Issue 2796973002: Unify the two overridden DownloadManagers used by Background Fetch (Closed)
Patch Set: Created 3 years, 8 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch
OLDNEW
1 // Copyright 2017 The Chromium Authors. All rights reserved. 1 // Copyright 2017 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 #include <map> 5 #include <map>
6 #include <memory> 6 #include <memory>
7 #include <utility> 7 #include <utility>
8 8
9 #include "base/files/file_util.h"
10 #include "base/files/scoped_temp_dir.h"
11 #include "base/guid.h"
12 #include "base/macros.h" 9 #include "base/macros.h"
13 #include "base/memory/ptr_util.h" 10 #include "base/memory/ptr_util.h"
14 #include "base/memory/weak_ptr.h"
15 #include "base/run_loop.h" 11 #include "base/run_loop.h"
16 #include "base/time/time.h" 12 #include "base/time/time.h"
17 #include "content/browser/background_fetch/background_fetch_context.h" 13 #include "content/browser/background_fetch/background_fetch_context.h"
18 #include "content/browser/background_fetch/background_fetch_embedded_worker_test _helper.h" 14 #include "content/browser/background_fetch/background_fetch_embedded_worker_test _helper.h"
19 #include "content/browser/background_fetch/background_fetch_registration_id.h" 15 #include "content/browser/background_fetch/background_fetch_registration_id.h"
20 #include "content/browser/background_fetch/background_fetch_service_impl.h" 16 #include "content/browser/background_fetch/background_fetch_service_impl.h"
21 #include "content/browser/background_fetch/background_fetch_test_base.h" 17 #include "content/browser/background_fetch/background_fetch_test_base.h"
22 #include "content/browser/service_worker/service_worker_context_wrapper.h" 18 #include "content/browser/service_worker/service_worker_context_wrapper.h"
23 #include "content/browser/storage_partition_impl.h" 19 #include "content/browser/storage_partition_impl.h"
24 #include "content/common/service_worker/service_worker_types.h" 20 #include "content/common/service_worker/service_worker_types.h"
25 #include "content/public/test/fake_download_item.h"
26 #include "content/public/test/mock_download_manager.h"
27 21
28 namespace content { 22 namespace content {
29 namespace { 23 namespace {
30 24
31 const char kExampleTag[] = "my-background-fetch"; 25 const char kExampleTag[] = "my-background-fetch";
32 const char kAlternativeTag[] = "my-alternative-fetch"; 26 const char kAlternativeTag[] = "my-alternative-fetch";
33 27
34 // Faked download manager that will respond to known HTTP requests with a test-
35 // defined response. See CreateRequestWithProvidedResponse().
36 class RespondingDownloadManager : public MockDownloadManager {
37 public:
38 RespondingDownloadManager() : weak_ptr_factory_(this) {}
39 ~RespondingDownloadManager() override = default;
40
41 // Responds to requests to |url| with the |status_code| and |response_text|.
42 void RegisterResponse(const GURL& url,
43 int status_code,
44 const std::string& response_text) {
45 DCHECK_EQ(registered_responses_.count(url), 0u);
46 registered_responses_[url] = std::make_pair(status_code, response_text);
47 }
48
49 // Called when the Background Fetch system starts a download, all information
50 // for which is contained in the |params|.
51 void DownloadUrl(std::unique_ptr<DownloadUrlParameters> params) override {
52 auto iter = registered_responses_.find(params->url());
53 if (iter == registered_responses_.end())
54 return;
55
56 std::unique_ptr<FakeDownloadItem> download_item =
57 base::MakeUnique<FakeDownloadItem>();
58
59 download_item->SetURL(params->url());
60 download_item->SetUrlChain({params->url()});
61 download_item->SetState(DownloadItem::DownloadState::IN_PROGRESS);
62 download_item->SetGuid(base::GenerateGUID());
63 download_item->SetStartTime(base::Time::Now());
64
65 // Asynchronously invoke the callback set on the |params|, and then continue
66 // dealing with the response in this class.
67 BrowserThread::PostTaskAndReply(
68 BrowserThread::UI, FROM_HERE,
69 base::Bind(params->callback(), download_item.get(),
70 DOWNLOAD_INTERRUPT_REASON_NONE),
71 base::Bind(&RespondingDownloadManager::DidStartDownload,
72 weak_ptr_factory_.GetWeakPtr(), download_item.get()));
73
74 download_items_.push_back(std::move(download_item));
75 }
76
77 private:
78 // Called when the download has been "started" by the download manager. This
79 // is where we finish the download by sending a single update.
80 void DidStartDownload(FakeDownloadItem* download_item) {
81 auto iter = registered_responses_.find(download_item->GetURL());
82 DCHECK(iter != registered_responses_.end());
83
84 const ResponseInfo& response_info = iter->second;
85
86 download_item->SetState(DownloadItem::DownloadState::COMPLETE);
87 download_item->SetEndTime(base::Time::Now());
88
89 base::FilePath response_path;
90 if (!temp_directory_.IsValid())
91 ASSERT_TRUE(temp_directory_.CreateUniqueTempDir());
92
93 // Write the |response_info|'s response_text to a temporary file.
94 ASSERT_TRUE(base::CreateTemporaryFileInDir(temp_directory_.GetPath(),
95 &response_path));
96
97 ASSERT_NE(-1 /* error */,
98 base::WriteFile(response_path, response_info.second.c_str(),
99 response_info.second.size()));
100
101 download_item->SetTargetFilePath(response_path);
102 download_item->SetReceivedBytes(response_info.second.size());
103
104 // Notify the Job Controller about the download having been updated.
105 download_item->NotifyDownloadUpdated();
106 }
107
108 using ResponseInfo =
109 std::pair<int /* status_code */, std::string /* response_text */>;
110
111 // Map of URL to the response information associated with that URL.
112 std::map<GURL, ResponseInfo> registered_responses_;
113
114 // Only used to guarantee the lifetime of the created FakeDownloadItems.
115 std::vector<std::unique_ptr<FakeDownloadItem>> download_items_;
116
117 // Temporary directory in which successfully downloaded files will be stored.
118 base::ScopedTempDir temp_directory_;
119
120 base::WeakPtrFactory<RespondingDownloadManager> weak_ptr_factory_;
121
122 DISALLOW_COPY_AND_ASSIGN(RespondingDownloadManager);
123 };
124
125 IconDefinition CreateIcon(std::string src, 28 IconDefinition CreateIcon(std::string src,
126 std::string sizes, 29 std::string sizes,
127 std::string type) { 30 std::string type) {
128 IconDefinition icon; 31 IconDefinition icon;
129 icon.src = std::move(src); 32 icon.src = std::move(src);
130 icon.sizes = std::move(sizes); 33 icon.sizes = std::move(sizes);
131 icon.type = std::move(type); 34 icon.type = std::move(type);
132 35
133 return icon; 36 return icon;
134 } 37 }
(...skipping 72 matching lines...) Expand 10 before | Expand all | Expand 10 after
207 base::RunLoop run_loop; 110 base::RunLoop run_loop;
208 service_->GetTags(registration_id.service_worker_registration_id(), 111 service_->GetTags(registration_id.service_worker_registration_id(),
209 registration_id.origin(), 112 registration_id.origin(),
210 base::Bind(&BackgroundFetchServiceTest::DidGetTags, 113 base::Bind(&BackgroundFetchServiceTest::DidGetTags,
211 base::Unretained(this), run_loop.QuitClosure(), 114 base::Unretained(this), run_loop.QuitClosure(),
212 out_error, out_tags)); 115 out_error, out_tags));
213 116
214 run_loop.Run(); 117 run_loop.Run();
215 } 118 }
216 119
217 // Creates a ServiceWorkerFetchRequest instance for the given details and
218 // provides a faked response with |status_code| and |response_text| to the
219 // download manager, that will resolve the download with that information.
220 ServiceWorkerFetchRequest CreateRequestWithProvidedResponse(
221 const std::string& method,
222 const std::string& url_string,
223 int status_code,
224 const std::string& response_text) {
225 GURL url(url_string);
226
227 // Register the |status_code| and |response_text| with the download manager.
228 download_manager_->RegisterResponse(GURL(url_string), status_code,
229 response_text);
230
231 // Create a ServiceWorkerFetchRequest request with the same information.
232 return ServiceWorkerFetchRequest(url, method, ServiceWorkerHeaderMap(),
233 Referrer(), false /* is_reload */);
234 }
235
236 // BackgroundFetchTestBase overrides: 120 // BackgroundFetchTestBase overrides:
237 void SetUp() override { 121 void SetUp() override {
238 BackgroundFetchTestBase::SetUp(); 122 BackgroundFetchTestBase::SetUp();
239 123
240 download_manager_ = new RespondingDownloadManager();
241
242 // The |download_manager_| ownership is given to the BrowserContext, and the
243 // BrowserContext will take care of deallocating it.
244 BrowserContext::SetDownloadManagerForTesting(browser_context(),
245 download_manager_);
246
247 StoragePartitionImpl* storage_partition = 124 StoragePartitionImpl* storage_partition =
248 static_cast<StoragePartitionImpl*>( 125 static_cast<StoragePartitionImpl*>(
249 BrowserContext::GetDefaultStoragePartition(browser_context())); 126 BrowserContext::GetDefaultStoragePartition(browser_context()));
250 127
251 context_ = new BackgroundFetchContext( 128 context_ = new BackgroundFetchContext(
252 browser_context(), storage_partition, 129 browser_context(), storage_partition,
253 make_scoped_refptr(embedded_worker_test_helper()->context_wrapper())); 130 make_scoped_refptr(embedded_worker_test_helper()->context_wrapper()));
254 service_ = base::MakeUnique<BackgroundFetchServiceImpl>( 131 service_ = base::MakeUnique<BackgroundFetchServiceImpl>(
255 0 /* render_process_id */, context_); 132 0 /* render_process_id */, context_);
256 } 133 }
257 134
258 void TearDown() override { 135 void TearDown() override {
136 BackgroundFetchTestBase::TearDown();
137
259 service_.reset(); 138 service_.reset();
260 139
261 EXPECT_CALL(*download_manager_, Shutdown()).Times(1);
262
263 context_->Shutdown(); 140 context_->Shutdown();
264 context_ = nullptr; 141 context_ = nullptr;
265 142
266 // Give pending shutdown operations a chance to finish. 143 // Give pending shutdown operations a chance to finish.
267 base::RunLoop().RunUntilIdle(); 144 base::RunLoop().RunUntilIdle();
268
269 BackgroundFetchTestBase::TearDown();
270 } 145 }
271 146
272 private: 147 private:
273 void DidGetRegistration( 148 void DidGetRegistration(
274 base::Closure quit_closure, 149 base::Closure quit_closure,
275 blink::mojom::BackgroundFetchError* out_error, 150 blink::mojom::BackgroundFetchError* out_error,
276 BackgroundFetchRegistration* out_registration, 151 BackgroundFetchRegistration* out_registration,
277 blink::mojom::BackgroundFetchError error, 152 blink::mojom::BackgroundFetchError error,
278 const base::Optional<content::BackgroundFetchRegistration>& 153 const base::Optional<content::BackgroundFetchRegistration>&
279 registration) { 154 registration) {
(...skipping 19 matching lines...) Expand all
299 const std::vector<std::string>& tags) { 174 const std::vector<std::string>& tags) {
300 *out_error = error; 175 *out_error = error;
301 *out_tags = tags; 176 *out_tags = tags;
302 177
303 quit_closure.Run(); 178 quit_closure.Run();
304 } 179 }
305 180
306 scoped_refptr<BackgroundFetchContext> context_; 181 scoped_refptr<BackgroundFetchContext> context_;
307 std::unique_ptr<BackgroundFetchServiceImpl> service_; 182 std::unique_ptr<BackgroundFetchServiceImpl> service_;
308 183
309 RespondingDownloadManager* download_manager_; // BrowserContext owned
310
311 DISALLOW_COPY_AND_ASSIGN(BackgroundFetchServiceTest); 184 DISALLOW_COPY_AND_ASSIGN(BackgroundFetchServiceTest);
312 }; 185 };
313 186
314 TEST_F(BackgroundFetchServiceTest, FetchInvalidArguments) { 187 TEST_F(BackgroundFetchServiceTest, FetchInvalidArguments) {
315 // This test verifies that the Fetch() function will kill the renderer and 188 // This test verifies that the Fetch() function will kill the renderer and
316 // return INVALID_ARGUMENT when invalid data is send over the Mojo channel. 189 // return INVALID_ARGUMENT when invalid data is send over the Mojo channel.
317 190
318 BackgroundFetchOptions options; 191 BackgroundFetchOptions options;
319 192
320 // The `tag` must be a non-empty string. 193 // The `tag` must be a non-empty string.
(...skipping 328 matching lines...) Expand 10 before | Expand all | Expand 10 after
649 const bool has_alternative_tag = 522 const bool has_alternative_tag =
650 tags[0] == kAlternativeTag || tags[1] == kAlternativeTag; 523 tags[0] == kAlternativeTag || tags[1] == kAlternativeTag;
651 524
652 EXPECT_TRUE(has_example_tag); 525 EXPECT_TRUE(has_example_tag);
653 EXPECT_TRUE(has_alternative_tag); 526 EXPECT_TRUE(has_alternative_tag);
654 } 527 }
655 } 528 }
656 529
657 } // namespace 530 } // namespace
658 } // namespace content 531 } // namespace content
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698