Add ICU message format support
[chromium-blink-merge.git] / content / browser / download / download_manager_impl_unittest.cc
blobd4f923370b6afffbcd57d66548f1891b277ad8ae
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include <set>
6 #include <string>
8 #include "base/bind.h"
9 #include "base/files/scoped_temp_dir.h"
10 #include "base/memory/scoped_ptr.h"
11 #include "base/memory/weak_ptr.h"
12 #include "base/message_loop/message_loop.h"
13 #include "base/stl_util.h"
14 #include "base/strings/string16.h"
15 #include "base/strings/string_util.h"
16 #include "base/strings/utf_string_conversions.h"
17 #include "build/build_config.h"
18 #include "content/browser/byte_stream.h"
19 #include "content/browser/download/download_create_info.h"
20 #include "content/browser/download/download_file_factory.h"
21 #include "content/browser/download/download_item_factory.h"
22 #include "content/browser/download/download_item_impl.h"
23 #include "content/browser/download/download_item_impl_delegate.h"
24 #include "content/browser/download/download_manager_impl.h"
25 #include "content/browser/download/download_request_handle.h"
26 #include "content/browser/download/mock_download_file.h"
27 #include "content/public/browser/browser_context.h"
28 #include "content/public/browser/download_interrupt_reasons.h"
29 #include "content/public/browser/download_item.h"
30 #include "content/public/browser/download_manager_delegate.h"
31 #include "content/public/browser/zoom_level_delegate.h"
32 #include "content/public/test/mock_download_item.h"
33 #include "content/public/test/test_browser_context.h"
34 #include "content/public/test/test_browser_thread.h"
35 #include "net/base/net_util.h"
36 #include "net/log/net_log.h"
37 #include "testing/gmock/include/gmock/gmock.h"
38 #include "testing/gmock_mutant.h"
39 #include "testing/gtest/include/gtest/gtest.h"
40 #include "url/origin.h"
42 using ::testing::AllOf;
43 using ::testing::DoAll;
44 using ::testing::Eq;
45 using ::testing::Ref;
46 using ::testing::Return;
47 using ::testing::ReturnRef;
48 using ::testing::SetArgPointee;
49 using ::testing::StrictMock;
50 using ::testing::_;
52 ACTION_TEMPLATE(RunCallback,
53 HAS_1_TEMPLATE_PARAMS(int, k),
54 AND_1_VALUE_PARAMS(p0)) {
55 return ::std::tr1::get<k>(args).Run(p0);
58 namespace content {
59 class ByteStreamReader;
61 namespace {
63 // Matches a DownloadCreateInfo* that points to the same object as |info| and
64 // has a |default_download_directory| that matches |download_directory|.
65 MATCHER_P2(DownloadCreateInfoWithDefaultPath, info, download_directory, "") {
66 return arg == info &&
67 arg->default_download_directory == download_directory;
70 class MockDownloadItemImpl : public DownloadItemImpl {
71 public:
72 // Use history constructor for minimal base object.
73 explicit MockDownloadItemImpl(DownloadItemImplDelegate* delegate)
74 : DownloadItemImpl(
75 delegate,
76 content::DownloadItem::kInvalidId,
77 base::FilePath(),
78 base::FilePath(),
79 std::vector<GURL>(),
80 GURL(),
81 "application/octet-stream",
82 "application/octet-stream",
83 base::Time(),
84 base::Time(),
85 std::string(),
86 std::string(),
89 DownloadItem::COMPLETE,
90 DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS,
91 DOWNLOAD_INTERRUPT_REASON_NONE,
92 false,
93 net::BoundNetLog()) {}
94 virtual ~MockDownloadItemImpl() {}
96 MOCK_METHOD4(OnDownloadTargetDetermined,
97 void(const base::FilePath&, TargetDisposition,
98 DownloadDangerType, const base::FilePath&));
99 MOCK_METHOD1(AddObserver, void(DownloadItem::Observer*));
100 MOCK_METHOD1(RemoveObserver, void(DownloadItem::Observer*));
101 MOCK_METHOD0(UpdateObservers, void());
102 MOCK_METHOD0(CanShowInFolder, bool());
103 MOCK_METHOD0(CanOpenDownload, bool());
104 MOCK_METHOD0(ShouldOpenFileBasedOnExtension, bool());
105 MOCK_METHOD0(OpenDownload, void());
106 MOCK_METHOD0(ShowDownloadInShell, void());
107 MOCK_METHOD0(ValidateDangerousDownload, void());
108 MOCK_METHOD1(StealDangerousDownload, void(const AcquireFileCallback&));
109 MOCK_METHOD3(UpdateProgress, void(int64, int64, const std::string&));
110 MOCK_METHOD1(Cancel, void(bool));
111 MOCK_METHOD0(MarkAsComplete, void());
112 MOCK_METHOD1(OnAllDataSaved, void(const std::string&));
113 MOCK_METHOD0(OnDownloadedFileRemoved, void());
114 void Start(scoped_ptr<DownloadFile> download_file,
115 scoped_ptr<DownloadRequestHandleInterface> req_handle) override {
116 MockStart(download_file.get(), req_handle.get());
119 MOCK_METHOD2(MockStart, void(DownloadFile*, DownloadRequestHandleInterface*));
121 MOCK_METHOD0(Remove, void());
122 MOCK_CONST_METHOD1(TimeRemaining, bool(base::TimeDelta*));
123 MOCK_CONST_METHOD0(CurrentSpeed, int64());
124 MOCK_CONST_METHOD0(PercentComplete, int());
125 MOCK_CONST_METHOD0(AllDataSaved, bool());
126 MOCK_CONST_METHOD1(MatchesQuery, bool(const base::string16& query));
127 MOCK_CONST_METHOD0(IsDone, bool());
128 MOCK_CONST_METHOD0(GetFullPath, const base::FilePath&());
129 MOCK_CONST_METHOD0(GetTargetFilePath, const base::FilePath&());
130 MOCK_CONST_METHOD0(GetTargetDisposition, TargetDisposition());
131 MOCK_METHOD1(OnContentCheckCompleted, void(DownloadDangerType));
132 MOCK_CONST_METHOD0(GetState, DownloadState());
133 MOCK_CONST_METHOD0(GetUrlChain, const std::vector<GURL>&());
134 MOCK_METHOD1(SetTotalBytes, void(int64));
135 MOCK_CONST_METHOD0(GetURL, const GURL&());
136 MOCK_CONST_METHOD0(GetOriginalUrl, const GURL&());
137 MOCK_CONST_METHOD0(GetReferrerUrl, const GURL&());
138 MOCK_CONST_METHOD0(GetTabUrl, const GURL&());
139 MOCK_CONST_METHOD0(GetTabReferrerUrl, const GURL&());
140 MOCK_CONST_METHOD0(GetSuggestedFilename, std::string());
141 MOCK_CONST_METHOD0(GetContentDisposition, std::string());
142 MOCK_CONST_METHOD0(GetMimeType, std::string());
143 MOCK_CONST_METHOD0(GetOriginalMimeType, std::string());
144 MOCK_CONST_METHOD0(GetReferrerCharset, std::string());
145 MOCK_CONST_METHOD0(GetRemoteAddress, std::string());
146 MOCK_CONST_METHOD0(GetTotalBytes, int64());
147 MOCK_CONST_METHOD0(GetReceivedBytes, int64());
148 MOCK_CONST_METHOD0(GetHashState, const std::string&());
149 MOCK_CONST_METHOD0(GetHash, const std::string&());
150 MOCK_CONST_METHOD0(GetId, uint32());
151 MOCK_CONST_METHOD0(GetStartTime, base::Time());
152 MOCK_CONST_METHOD0(GetEndTime, base::Time());
153 MOCK_METHOD0(GetDownloadManager, DownloadManager*());
154 MOCK_CONST_METHOD0(IsPaused, bool());
155 MOCK_CONST_METHOD0(GetOpenWhenComplete, bool());
156 MOCK_METHOD1(SetOpenWhenComplete, void(bool));
157 MOCK_CONST_METHOD0(GetFileExternallyRemoved, bool());
158 MOCK_CONST_METHOD0(GetDangerType, DownloadDangerType());
159 MOCK_CONST_METHOD0(IsDangerous, bool());
160 MOCK_METHOD0(GetAutoOpened, bool());
161 MOCK_CONST_METHOD0(GetForcedFilePath, const base::FilePath&());
162 MOCK_CONST_METHOD0(HasUserGesture, bool());
163 MOCK_CONST_METHOD0(GetTransitionType, ui::PageTransition());
164 MOCK_CONST_METHOD0(IsTemporary, bool());
165 MOCK_METHOD1(SetIsTemporary, void(bool));
166 MOCK_METHOD1(SetOpened, void(bool));
167 MOCK_CONST_METHOD0(GetOpened, bool());
168 MOCK_CONST_METHOD0(GetLastModifiedTime, const std::string&());
169 MOCK_CONST_METHOD0(GetETag, const std::string&());
170 MOCK_CONST_METHOD0(GetLastReason, DownloadInterruptReason());
171 MOCK_CONST_METHOD0(GetBrowserContext, BrowserContext*());
172 MOCK_CONST_METHOD0(GetWebContents, WebContents*());
173 MOCK_CONST_METHOD0(GetFileNameToReportUser, base::FilePath());
174 MOCK_METHOD1(SetDisplayName, void(const base::FilePath&));
175 MOCK_METHOD0(NotifyRemoved, void());
176 // May be called when vlog is on.
177 std::string DebugString(bool verbose) const override {
178 return std::string();
182 class MockDownloadManagerDelegate : public DownloadManagerDelegate {
183 public:
184 MockDownloadManagerDelegate();
185 virtual ~MockDownloadManagerDelegate();
187 MOCK_METHOD0(Shutdown, void());
188 MOCK_METHOD1(GetNextId, void(const DownloadIdCallback&));
189 MOCK_METHOD2(DetermineDownloadTarget,
190 bool(DownloadItem* item,
191 const DownloadTargetCallback&));
192 MOCK_METHOD1(ShouldOpenFileBasedOnExtension, bool(const base::FilePath&));
193 MOCK_METHOD2(ShouldCompleteDownload,
194 bool(DownloadItem*, const base::Closure&));
195 MOCK_METHOD2(ShouldOpenDownload,
196 bool(DownloadItem*, const DownloadOpenDelayedCallback&));
197 MOCK_METHOD0(GenerateFileHash, bool());
198 MOCK_METHOD4(GetSaveDir, void(BrowserContext*,
199 base::FilePath*, base::FilePath*, bool*));
200 MOCK_METHOD5(ChooseSavePath, void(
201 WebContents*, const base::FilePath&, const base::FilePath::StringType&,
202 bool, const SavePackagePathPickedCallback&));
203 MOCK_CONST_METHOD0(ApplicationClientIdForFileScanning, std::string());
206 MockDownloadManagerDelegate::MockDownloadManagerDelegate() {}
208 MockDownloadManagerDelegate::~MockDownloadManagerDelegate() {}
210 class MockDownloadItemFactory
211 : public DownloadItemFactory,
212 public base::SupportsWeakPtr<MockDownloadItemFactory> {
213 public:
214 MockDownloadItemFactory();
215 ~MockDownloadItemFactory() override;
217 // Access to map of created items.
218 // TODO(rdsmith): Could add type (save page, persisted, etc.)
219 // functionality if it's ever needed by consumers.
221 // Returns NULL if no item of that id is present.
222 MockDownloadItemImpl* GetItem(int id);
224 // Remove and return an item made by the factory.
225 // Generally used during teardown.
226 MockDownloadItemImpl* PopItem();
228 // Should be called when the item of this id is removed so that
229 // we don't keep dangling pointers.
230 void RemoveItem(int id);
232 // Overridden methods from DownloadItemFactory.
233 DownloadItemImpl* CreatePersistedItem(
234 DownloadItemImplDelegate* delegate,
235 uint32 download_id,
236 const base::FilePath& current_path,
237 const base::FilePath& target_path,
238 const std::vector<GURL>& url_chain,
239 const GURL& referrer_url,
240 const std::string& mime_type,
241 const std::string& original_mime_type,
242 const base::Time& start_time,
243 const base::Time& end_time,
244 const std::string& etag,
245 const std::string& last_modofied,
246 int64 received_bytes,
247 int64 total_bytes,
248 DownloadItem::DownloadState state,
249 DownloadDangerType danger_type,
250 DownloadInterruptReason interrupt_reason,
251 bool opened,
252 const net::BoundNetLog& bound_net_log) override;
253 DownloadItemImpl* CreateActiveItem(
254 DownloadItemImplDelegate* delegate,
255 uint32 download_id,
256 const DownloadCreateInfo& info,
257 const net::BoundNetLog& bound_net_log) override;
258 DownloadItemImpl* CreateSavePageItem(
259 DownloadItemImplDelegate* delegate,
260 uint32 download_id,
261 const base::FilePath& path,
262 const GURL& url,
263 const std::string& mime_type,
264 scoped_ptr<DownloadRequestHandleInterface> request_handle,
265 const net::BoundNetLog& bound_net_log) override;
267 private:
268 std::map<uint32, MockDownloadItemImpl*> items_;
269 DownloadItemImplDelegate item_delegate_;
271 DISALLOW_COPY_AND_ASSIGN(MockDownloadItemFactory);
274 MockDownloadItemFactory::MockDownloadItemFactory() {}
276 MockDownloadItemFactory::~MockDownloadItemFactory() {}
278 MockDownloadItemImpl* MockDownloadItemFactory::GetItem(int id) {
279 if (items_.find(id) == items_.end())
280 return NULL;
281 return items_[id];
284 MockDownloadItemImpl* MockDownloadItemFactory::PopItem() {
285 if (items_.empty())
286 return NULL;
288 std::map<uint32, MockDownloadItemImpl*>::iterator first_item
289 = items_.begin();
290 MockDownloadItemImpl* result = first_item->second;
291 items_.erase(first_item);
292 return result;
295 void MockDownloadItemFactory::RemoveItem(int id) {
296 DCHECK(items_.find(id) != items_.end());
297 items_.erase(id);
300 DownloadItemImpl* MockDownloadItemFactory::CreatePersistedItem(
301 DownloadItemImplDelegate* delegate,
302 uint32 download_id,
303 const base::FilePath& current_path,
304 const base::FilePath& target_path,
305 const std::vector<GURL>& url_chain,
306 const GURL& referrer_url,
307 const std::string& mime_type,
308 const std::string& original_mime_type,
309 const base::Time& start_time,
310 const base::Time& end_time,
311 const std::string& etag,
312 const std::string& last_modified,
313 int64 received_bytes,
314 int64 total_bytes,
315 DownloadItem::DownloadState state,
316 DownloadDangerType danger_type,
317 DownloadInterruptReason interrupt_reason,
318 bool opened,
319 const net::BoundNetLog& bound_net_log) {
320 DCHECK(items_.find(download_id) == items_.end());
321 MockDownloadItemImpl* result =
322 new StrictMock<MockDownloadItemImpl>(&item_delegate_);
323 EXPECT_CALL(*result, GetId())
324 .WillRepeatedly(Return(download_id));
325 items_[download_id] = result;
326 return result;
329 DownloadItemImpl* MockDownloadItemFactory::CreateActiveItem(
330 DownloadItemImplDelegate* delegate,
331 uint32 download_id,
332 const DownloadCreateInfo& info,
333 const net::BoundNetLog& bound_net_log) {
334 DCHECK(items_.find(download_id) == items_.end());
336 MockDownloadItemImpl* result =
337 new StrictMock<MockDownloadItemImpl>(&item_delegate_);
338 EXPECT_CALL(*result, GetId())
339 .WillRepeatedly(Return(download_id));
340 items_[download_id] = result;
342 // Active items are created and then immediately are called to start
343 // the download.
344 EXPECT_CALL(*result, MockStart(_, _));
346 return result;
349 DownloadItemImpl* MockDownloadItemFactory::CreateSavePageItem(
350 DownloadItemImplDelegate* delegate,
351 uint32 download_id,
352 const base::FilePath& path,
353 const GURL& url,
354 const std::string& mime_type,
355 scoped_ptr<DownloadRequestHandleInterface> request_handle,
356 const net::BoundNetLog& bound_net_log) {
357 DCHECK(items_.find(download_id) == items_.end());
359 MockDownloadItemImpl* result =
360 new StrictMock<MockDownloadItemImpl>(&item_delegate_);
361 EXPECT_CALL(*result, GetId())
362 .WillRepeatedly(Return(download_id));
363 items_[download_id] = result;
365 return result;
368 class MockDownloadFileFactory
369 : public DownloadFileFactory,
370 public base::SupportsWeakPtr<MockDownloadFileFactory> {
371 public:
372 MockDownloadFileFactory() {}
373 virtual ~MockDownloadFileFactory() {}
375 // Overridden method from DownloadFileFactory
376 MOCK_METHOD8(MockCreateFile, MockDownloadFile*(
377 const DownloadSaveInfo&,
378 const base::FilePath&,
379 const GURL&, const GURL&, bool,
380 ByteStreamReader*,
381 const net::BoundNetLog&,
382 base::WeakPtr<DownloadDestinationObserver>));
384 virtual DownloadFile* CreateFile(
385 scoped_ptr<DownloadSaveInfo> save_info,
386 const base::FilePath& default_download_directory,
387 const GURL& url,
388 const GURL& referrer_url,
389 bool calculate_hash,
390 scoped_ptr<ByteStreamReader> stream,
391 const net::BoundNetLog& bound_net_log,
392 base::WeakPtr<DownloadDestinationObserver> observer) {
393 return MockCreateFile(*save_info.get(), default_download_directory, url,
394 referrer_url, calculate_hash,
395 stream.get(), bound_net_log, observer);
399 class MockBrowserContext : public BrowserContext {
400 public:
401 MockBrowserContext() {}
402 ~MockBrowserContext() {}
404 MOCK_CONST_METHOD0(GetPath, base::FilePath());
405 MOCK_METHOD1(CreateZoomLevelDelegateMock,
406 ZoomLevelDelegate*(const base::FilePath&));
407 MOCK_CONST_METHOD0(IsOffTheRecord, bool());
408 MOCK_METHOD0(GetRequestContext, net::URLRequestContextGetter*());
409 MOCK_METHOD1(GetRequestContextForRenderProcess,
410 net::URLRequestContextGetter*(int renderer_child_id));
411 MOCK_METHOD0(GetMediaRequestContext,
412 net::URLRequestContextGetter*());
413 MOCK_METHOD1(GetMediaRequestContextForRenderProcess,
414 net::URLRequestContextGetter*(int renderer_child_id));
415 MOCK_METHOD2(GetMediaRequestContextForStoragePartition,
416 net::URLRequestContextGetter*(
417 const base::FilePath& partition_path, bool in_memory));
418 MOCK_METHOD0(GetResourceContext, ResourceContext*());
419 MOCK_METHOD0(GetDownloadManagerDelegate, DownloadManagerDelegate*());
420 MOCK_METHOD0(GetGuestManager, BrowserPluginGuestManager* ());
421 MOCK_METHOD0(GetSpecialStoragePolicy, storage::SpecialStoragePolicy*());
422 MOCK_METHOD0(GetPushMessagingService, PushMessagingService*());
423 MOCK_METHOD0(GetSSLHostStateDelegate, SSLHostStateDelegate*());
424 MOCK_METHOD0(GetPermissionManager, PermissionManager*());
426 scoped_ptr<ZoomLevelDelegate> CreateZoomLevelDelegate(
427 const base::FilePath& path) override {
428 return scoped_ptr<ZoomLevelDelegate>(CreateZoomLevelDelegateMock(path));
432 class MockDownloadManagerObserver : public DownloadManager::Observer {
433 public:
434 MockDownloadManagerObserver() {}
435 ~MockDownloadManagerObserver() {}
436 MOCK_METHOD2(OnDownloadCreated, void(
437 DownloadManager*, DownloadItem*));
438 MOCK_METHOD1(ManagerGoingDown, void(DownloadManager*));
439 MOCK_METHOD2(SelectFileDialogDisplayed, void(
440 DownloadManager*, int32));
443 } // namespace
445 class DownloadManagerTest : public testing::Test {
446 public:
447 static const char* kTestData;
448 static const size_t kTestDataLen;
450 DownloadManagerTest()
451 : callback_called_(false),
452 ui_thread_(BrowserThread::UI, &message_loop_),
453 file_thread_(BrowserThread::FILE, &message_loop_),
454 next_download_id_(0) {
457 // We tear down everything in TearDown().
458 ~DownloadManagerTest() override {}
460 // Create a MockDownloadItemFactory and MockDownloadManagerDelegate,
461 // then create a DownloadManager that points
462 // at all of those.
463 void SetUp() override {
464 DCHECK(!download_manager_);
466 mock_download_item_factory_ = (new MockDownloadItemFactory())->AsWeakPtr();
467 mock_download_file_factory_ = (new MockDownloadFileFactory())->AsWeakPtr();
468 mock_download_manager_delegate_.reset(
469 new StrictMock<MockDownloadManagerDelegate>);
470 EXPECT_CALL(*mock_download_manager_delegate_.get(), Shutdown())
471 .WillOnce(Return());
472 mock_browser_context_.reset(new StrictMock<MockBrowserContext>);
473 EXPECT_CALL(*mock_browser_context_.get(), IsOffTheRecord())
474 .WillRepeatedly(Return(false));
476 download_manager_.reset(new DownloadManagerImpl(
477 NULL, mock_browser_context_.get()));
478 download_manager_->SetDownloadItemFactoryForTesting(
479 scoped_ptr<DownloadItemFactory>(
480 mock_download_item_factory_.get()).Pass());
481 download_manager_->SetDownloadFileFactoryForTesting(
482 scoped_ptr<DownloadFileFactory>(
483 mock_download_file_factory_.get()).Pass());
484 observer_.reset(new MockDownloadManagerObserver());
485 download_manager_->AddObserver(observer_.get());
486 download_manager_->SetDelegate(mock_download_manager_delegate_.get());
487 download_urls_.push_back(GURL("http://www.url1.com"));
488 download_urls_.push_back(GURL("http://www.url2.com"));
489 download_urls_.push_back(GURL("http://www.url3.com"));
490 download_urls_.push_back(GURL("http://www.url4.com"));
493 void TearDown() override {
494 while (MockDownloadItemImpl*
495 item = mock_download_item_factory_->PopItem()) {
496 EXPECT_CALL(*item, GetState())
497 .WillOnce(Return(DownloadItem::CANCELLED));
499 EXPECT_CALL(GetMockObserver(), ManagerGoingDown(download_manager_.get()))
500 .WillOnce(Return());
502 download_manager_->Shutdown();
503 download_manager_.reset();
504 message_loop_.RunUntilIdle();
505 ASSERT_EQ(NULL, mock_download_item_factory_.get());
506 ASSERT_EQ(NULL, mock_download_file_factory_.get());
507 message_loop_.RunUntilIdle();
508 mock_download_manager_delegate_.reset();
509 mock_browser_context_.reset();
510 download_urls_.clear();
513 // Returns download id.
514 MockDownloadItemImpl& AddItemToManager() {
515 DownloadCreateInfo info;
517 // Args are ignored except for download id, so everything else can be
518 // null.
519 uint32 id = next_download_id_;
520 ++next_download_id_;
521 info.request_handle = DownloadRequestHandle();
522 download_manager_->CreateActiveItem(id, info);
523 DCHECK(mock_download_item_factory_->GetItem(id));
524 MockDownloadItemImpl& item(*mock_download_item_factory_->GetItem(id));
525 // Satisfy expectation. If the item is created in StartDownload(),
526 // we call Start on it immediately, so we need to set that expectation
527 // in the factory.
528 scoped_ptr<DownloadRequestHandleInterface> req_handle;
529 item.Start(scoped_ptr<DownloadFile>(), req_handle.Pass());
530 DCHECK(id < download_urls_.size());
531 EXPECT_CALL(item, GetURL()).WillRepeatedly(ReturnRef(download_urls_[id]));
533 return item;
536 MockDownloadItemImpl& GetMockDownloadItem(int id) {
537 MockDownloadItemImpl* itemp = mock_download_item_factory_->GetItem(id);
539 DCHECK(itemp);
540 return *itemp;
543 void RemoveMockDownloadItem(int id) {
544 // Owned by DownloadManager; should be deleted there.
545 mock_download_item_factory_->RemoveItem(id);
548 MockDownloadManagerDelegate& GetMockDownloadManagerDelegate() {
549 return *mock_download_manager_delegate_;
552 MockDownloadManagerObserver& GetMockObserver() {
553 return *observer_;
556 void DownloadTargetDeterminedCallback(
557 const base::FilePath& target_path,
558 DownloadItem::TargetDisposition disposition,
559 DownloadDangerType danger_type,
560 const base::FilePath& intermediate_path) {
561 callback_called_ = true;
562 target_path_ = target_path;
563 target_disposition_ = disposition;
564 danger_type_ = danger_type;
565 intermediate_path_ = intermediate_path;
568 void DetermineDownloadTarget(DownloadItemImpl* item) {
569 download_manager_->DetermineDownloadTarget(
570 item, base::Bind(
571 &DownloadManagerTest::DownloadTargetDeterminedCallback,
572 base::Unretained(this)));
575 protected:
576 // Key test variable; we'll keep it available to sub-classes.
577 scoped_ptr<DownloadManagerImpl> download_manager_;
578 base::WeakPtr<MockDownloadFileFactory> mock_download_file_factory_;
580 // Target detetermined callback.
581 bool callback_called_;
582 base::FilePath target_path_;
583 DownloadItem::TargetDisposition target_disposition_;
584 DownloadDangerType danger_type_;
585 base::FilePath intermediate_path_;
587 std::vector<GURL> download_urls_;
589 private:
590 base::MessageLoopForUI message_loop_;
591 TestBrowserThread ui_thread_;
592 TestBrowserThread file_thread_;
593 base::WeakPtr<MockDownloadItemFactory> mock_download_item_factory_;
594 scoped_ptr<MockDownloadManagerDelegate> mock_download_manager_delegate_;
595 scoped_ptr<MockBrowserContext> mock_browser_context_;
596 scoped_ptr<MockDownloadManagerObserver> observer_;
597 uint32 next_download_id_;
599 DISALLOW_COPY_AND_ASSIGN(DownloadManagerTest);
602 // Confirm the appropriate invocations occur when you start a download.
603 TEST_F(DownloadManagerTest, StartDownload) {
604 scoped_ptr<DownloadCreateInfo> info(new DownloadCreateInfo);
605 scoped_ptr<ByteStreamReader> stream;
606 uint32 local_id(5); // Random value
607 base::FilePath download_path(FILE_PATH_LITERAL("download/path"));
609 EXPECT_FALSE(download_manager_->GetDownload(local_id));
611 EXPECT_CALL(GetMockObserver(), OnDownloadCreated(download_manager_.get(), _))
612 .WillOnce(Return());
613 EXPECT_CALL(GetMockDownloadManagerDelegate(), GetNextId(_))
614 .WillOnce(RunCallback<0>(local_id));
616 // Doing nothing will set the default download directory to null.
617 EXPECT_CALL(GetMockDownloadManagerDelegate(), GetSaveDir(_, _, _, _));
618 EXPECT_CALL(GetMockDownloadManagerDelegate(), GenerateFileHash())
619 .WillOnce(Return(true));
620 EXPECT_CALL(GetMockDownloadManagerDelegate(),
621 ApplicationClientIdForFileScanning())
622 .WillRepeatedly(Return("client-id"));
623 MockDownloadFile* mock_file = new MockDownloadFile;
624 EXPECT_CALL(*mock_file, SetClientGuid("client-id"));
625 EXPECT_CALL(*mock_download_file_factory_.get(),
626 MockCreateFile(Ref(*info->save_info.get()), _, _, _, true,
627 stream.get(), _, _))
628 .WillOnce(Return(mock_file));
630 download_manager_->StartDownload(
631 info.Pass(), stream.Pass(), DownloadUrlParameters::OnStartedCallback());
632 EXPECT_TRUE(download_manager_->GetDownload(local_id));
635 // Confirm that calling DetermineDownloadTarget behaves properly if the delegate
636 // blocks starting.
637 TEST_F(DownloadManagerTest, DetermineDownloadTarget_True) {
638 // Put a mock we have a handle to on the download manager.
639 MockDownloadItemImpl& item(AddItemToManager());
640 EXPECT_CALL(item, GetState())
641 .WillRepeatedly(Return(DownloadItem::IN_PROGRESS));
643 EXPECT_CALL(GetMockDownloadManagerDelegate(),
644 DetermineDownloadTarget(&item, _))
645 .WillOnce(Return(true));
646 DetermineDownloadTarget(&item);
649 // Confirm that calling DetermineDownloadTarget behaves properly if the delegate
650 // allows starting. This also tests OnDownloadTargetDetermined.
651 TEST_F(DownloadManagerTest, DetermineDownloadTarget_False) {
652 // Put a mock we have a handle to on the download manager.
653 MockDownloadItemImpl& item(AddItemToManager());
655 base::FilePath path(FILE_PATH_LITERAL("random_filepath.txt"));
656 EXPECT_CALL(GetMockDownloadManagerDelegate(),
657 DetermineDownloadTarget(&item, _))
658 .WillOnce(Return(false));
659 EXPECT_CALL(item, GetForcedFilePath())
660 .WillOnce(ReturnRef(path));
662 // Confirm that the callback was called with the right values in this case.
663 callback_called_ = false;
664 DetermineDownloadTarget(&item);
665 EXPECT_TRUE(callback_called_);
666 EXPECT_EQ(path, target_path_);
667 EXPECT_EQ(DownloadItem::TARGET_DISPOSITION_OVERWRITE, target_disposition_);
668 EXPECT_EQ(DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, danger_type_);
669 EXPECT_EQ(path, intermediate_path_);
672 // Confirm the DownloadManagerImpl::RemoveAllDownloads() functionality
673 TEST_F(DownloadManagerTest, RemoveAllDownloads) {
674 base::Time now(base::Time::Now());
675 for (uint32 i = 0; i < 4; ++i) {
676 MockDownloadItemImpl& item(AddItemToManager());
677 EXPECT_EQ(i, item.GetId());
678 EXPECT_CALL(item, GetStartTime())
679 .WillRepeatedly(Return(now));
682 // Specify states for each.
683 EXPECT_CALL(GetMockDownloadItem(0), GetState())
684 .WillRepeatedly(Return(DownloadItem::COMPLETE));
685 EXPECT_CALL(GetMockDownloadItem(1), GetState())
686 .WillRepeatedly(Return(DownloadItem::CANCELLED));
687 EXPECT_CALL(GetMockDownloadItem(2), GetState())
688 .WillRepeatedly(Return(DownloadItem::INTERRUPTED));
689 EXPECT_CALL(GetMockDownloadItem(3), GetState())
690 .WillRepeatedly(Return(DownloadItem::IN_PROGRESS));
692 // Expectations for whether or not they'll actually be removed.
693 EXPECT_CALL(GetMockDownloadItem(0), Remove())
694 .WillOnce(Return());
695 EXPECT_CALL(GetMockDownloadItem(1), Remove())
696 .WillOnce(Return());
697 EXPECT_CALL(GetMockDownloadItem(2), Remove())
698 .WillOnce(Return());
699 EXPECT_CALL(GetMockDownloadItem(3), Remove())
700 .Times(0);
702 download_manager_->RemoveAllDownloads();
703 // Because we're mocking the download item, the Remove call doesn't
704 // result in them being removed from the DownloadManager list.
707 // Confirm that only downloads with same origin are removed.
708 TEST_F(DownloadManagerTest, RemoveSameOriginDownloads) {
709 base::Time now(base::Time::Now());
710 for (uint32 i = 0; i < 2; ++i) {
711 MockDownloadItemImpl& item(AddItemToManager());
712 EXPECT_CALL(item, GetStartTime()).WillRepeatedly(Return(now));
713 EXPECT_CALL(item, GetState())
714 .WillRepeatedly(Return(DownloadItem::COMPLETE));
717 EXPECT_CALL(GetMockDownloadItem(0), Remove());
718 EXPECT_CALL(GetMockDownloadItem(1), Remove()).Times(0);
720 url::Origin origin_to_clear(download_urls_[0]);
721 int remove_count = download_manager_->RemoveDownloadsByOriginAndTime(
722 origin_to_clear, base::Time(), base::Time::Max());
723 EXPECT_EQ(remove_count, 1);
726 } // namespace content