Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / content / browser / download / download_manager_impl_unittest.cc
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.
4
5 #include <set>
6 #include <string>
7
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/test/mock_download_item.h"
32 #include "content/public/test/test_browser_context.h"
33 #include "content/public/test/test_browser_thread.h"
34 #include "net/base/net_log.h"
35 #include "net/base/net_util.h"
36 #include "testing/gmock/include/gmock/gmock.h"
37 #include "testing/gmock_mutant.h"
38 #include "testing/gtest/include/gtest/gtest.h"
39
40 using ::testing::AllOf;
41 using ::testing::DoAll;
42 using ::testing::Eq;
43 using ::testing::Ref;
44 using ::testing::Return;
45 using ::testing::ReturnRef;
46 using ::testing::SetArgPointee;
47 using ::testing::StrictMock;
48 using ::testing::_;
49
50 ACTION_TEMPLATE(RunCallback,
51                 HAS_1_TEMPLATE_PARAMS(int, k),
52                 AND_1_VALUE_PARAMS(p0)) {
53   return ::std::tr1::get<k>(args).Run(p0);
54 }
55
56 namespace content {
57 class ByteStreamReader;
58
59 namespace {
60
61 // Matches a DownloadCreateInfo* that points to the same object as |info| and
62 // has a |default_download_directory| that matches |download_directory|.
63 MATCHER_P2(DownloadCreateInfoWithDefaultPath, info, download_directory, "") {
64   return arg == info &&
65       arg->default_download_directory == download_directory;
66 }
67
68 class MockDownloadItemImpl : public DownloadItemImpl {
69  public:
70   // Use history constructor for minimal base object.
71   explicit MockDownloadItemImpl(DownloadItemImplDelegate* delegate)
72       : DownloadItemImpl(
73           delegate,
74           content::DownloadItem::kInvalidId,
75           base::FilePath(),
76           base::FilePath(),
77           std::vector<GURL>(),
78           GURL(),
79           base::Time(),
80           base::Time(),
81           std::string(),
82           std::string(),
83           0,
84           0,
85           DownloadItem::COMPLETE,
86           DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS,
87           DOWNLOAD_INTERRUPT_REASON_NONE,
88           false,
89           net::BoundNetLog()) {}
90   virtual ~MockDownloadItemImpl() {}
91
92   MOCK_METHOD4(OnDownloadTargetDetermined,
93                void(const base::FilePath&, TargetDisposition,
94                     DownloadDangerType, const base::FilePath&));
95   MOCK_METHOD1(AddObserver, void(DownloadItem::Observer*));
96   MOCK_METHOD1(RemoveObserver, void(DownloadItem::Observer*));
97   MOCK_METHOD0(UpdateObservers, void());
98   MOCK_METHOD0(CanShowInFolder, bool());
99   MOCK_METHOD0(CanOpenDownload, bool());
100   MOCK_METHOD0(ShouldOpenFileBasedOnExtension, bool());
101   MOCK_METHOD0(OpenDownload, void());
102   MOCK_METHOD0(ShowDownloadInShell, void());
103   MOCK_METHOD0(ValidateDangerousDownload, void());
104   MOCK_METHOD1(StealDangerousDownload, void(const AcquireFileCallback&));
105   MOCK_METHOD3(UpdateProgress, void(int64, int64, const std::string&));
106   MOCK_METHOD1(Cancel, void(bool));
107   MOCK_METHOD0(MarkAsComplete, void());
108   MOCK_METHOD1(OnAllDataSaved, void(const std::string&));
109   MOCK_METHOD0(OnDownloadedFileRemoved, void());
110   virtual void Start(
111       scoped_ptr<DownloadFile> download_file,
112       scoped_ptr<DownloadRequestHandleInterface> req_handle) OVERRIDE {
113     MockStart(download_file.get(), req_handle.get());
114   }
115
116   MOCK_METHOD2(MockStart, void(DownloadFile*, DownloadRequestHandleInterface*));
117
118   MOCK_METHOD0(Remove, void());
119   MOCK_CONST_METHOD1(TimeRemaining, bool(base::TimeDelta*));
120   MOCK_CONST_METHOD0(CurrentSpeed, int64());
121   MOCK_CONST_METHOD0(PercentComplete, int());
122   MOCK_CONST_METHOD0(AllDataSaved, bool());
123   MOCK_CONST_METHOD1(MatchesQuery, bool(const base::string16& query));
124   MOCK_CONST_METHOD0(IsDone, bool());
125   MOCK_CONST_METHOD0(GetFullPath, const base::FilePath&());
126   MOCK_CONST_METHOD0(GetTargetFilePath, const base::FilePath&());
127   MOCK_CONST_METHOD0(GetTargetDisposition, TargetDisposition());
128   MOCK_METHOD1(OnContentCheckCompleted, void(DownloadDangerType));
129   MOCK_CONST_METHOD0(GetState, DownloadState());
130   MOCK_CONST_METHOD0(GetUrlChain, const std::vector<GURL>&());
131   MOCK_METHOD1(SetTotalBytes, void(int64));
132   MOCK_CONST_METHOD0(GetURL, const GURL&());
133   MOCK_CONST_METHOD0(GetOriginalUrl, const GURL&());
134   MOCK_CONST_METHOD0(GetReferrerUrl, const GURL&());
135   MOCK_CONST_METHOD0(GetTabUrl, const GURL&());
136   MOCK_CONST_METHOD0(GetTabReferrerUrl, const GURL&());
137   MOCK_CONST_METHOD0(GetSuggestedFilename, std::string());
138   MOCK_CONST_METHOD0(GetContentDisposition, std::string());
139   MOCK_CONST_METHOD0(GetMimeType, std::string());
140   MOCK_CONST_METHOD0(GetOriginalMimeType, std::string());
141   MOCK_CONST_METHOD0(GetReferrerCharset, std::string());
142   MOCK_CONST_METHOD0(GetRemoteAddress, std::string());
143   MOCK_CONST_METHOD0(GetTotalBytes, int64());
144   MOCK_CONST_METHOD0(GetReceivedBytes, int64());
145   MOCK_CONST_METHOD0(GetHashState, const std::string&());
146   MOCK_CONST_METHOD0(GetHash, const std::string&());
147   MOCK_CONST_METHOD0(GetId, uint32());
148   MOCK_CONST_METHOD0(GetStartTime, base::Time());
149   MOCK_CONST_METHOD0(GetEndTime, base::Time());
150   MOCK_METHOD0(GetDownloadManager, DownloadManager*());
151   MOCK_CONST_METHOD0(IsPaused, bool());
152   MOCK_CONST_METHOD0(GetOpenWhenComplete, bool());
153   MOCK_METHOD1(SetOpenWhenComplete, void(bool));
154   MOCK_CONST_METHOD0(GetFileExternallyRemoved, bool());
155   MOCK_CONST_METHOD0(GetDangerType, DownloadDangerType());
156   MOCK_CONST_METHOD0(IsDangerous, bool());
157   MOCK_METHOD0(GetAutoOpened, bool());
158   MOCK_CONST_METHOD0(GetForcedFilePath, const base::FilePath&());
159   MOCK_CONST_METHOD0(HasUserGesture, bool());
160   MOCK_CONST_METHOD0(GetTransitionType, PageTransition());
161   MOCK_CONST_METHOD0(IsTemporary, bool());
162   MOCK_METHOD1(SetIsTemporary, void(bool));
163   MOCK_METHOD1(SetOpened, void(bool));
164   MOCK_CONST_METHOD0(GetOpened, bool());
165   MOCK_CONST_METHOD0(GetLastModifiedTime, const std::string&());
166   MOCK_CONST_METHOD0(GetETag, const std::string&());
167   MOCK_CONST_METHOD0(GetLastReason, DownloadInterruptReason());
168   MOCK_CONST_METHOD0(GetBrowserContext, BrowserContext*());
169   MOCK_CONST_METHOD0(GetWebContents, WebContents*());
170   MOCK_CONST_METHOD0(GetFileNameToReportUser, base::FilePath());
171   MOCK_METHOD1(SetDisplayName, void(const base::FilePath&));
172   MOCK_METHOD0(NotifyRemoved, void());
173   // May be called when vlog is on.
174   virtual std::string DebugString(bool verbose) const OVERRIDE {
175     return std::string();
176   }
177 };
178
179 class MockDownloadManagerDelegate : public DownloadManagerDelegate {
180  public:
181   MockDownloadManagerDelegate();
182   virtual ~MockDownloadManagerDelegate();
183
184   MOCK_METHOD0(Shutdown, void());
185   MOCK_METHOD1(GetNextId, void(const DownloadIdCallback&));
186   MOCK_METHOD2(DetermineDownloadTarget,
187                bool(DownloadItem* item,
188                     const DownloadTargetCallback&));
189   MOCK_METHOD1(ShouldOpenFileBasedOnExtension, bool(const base::FilePath&));
190   MOCK_METHOD2(ShouldCompleteDownload,
191                bool(DownloadItem*, const base::Closure&));
192   MOCK_METHOD2(ShouldOpenDownload,
193                bool(DownloadItem*, const DownloadOpenDelayedCallback&));
194   MOCK_METHOD0(GenerateFileHash, bool());
195   MOCK_METHOD4(GetSaveDir, void(BrowserContext*,
196                                 base::FilePath*, base::FilePath*, bool*));
197   MOCK_METHOD5(ChooseSavePath, void(
198       WebContents*, const base::FilePath&, const base::FilePath::StringType&,
199       bool, const SavePackagePathPickedCallback&));
200   MOCK_CONST_METHOD0(ApplicationClientIdForFileScanning, std::string());
201 };
202
203 MockDownloadManagerDelegate::MockDownloadManagerDelegate() {}
204
205 MockDownloadManagerDelegate::~MockDownloadManagerDelegate() {}
206
207 class MockDownloadItemFactory
208     : public DownloadItemFactory,
209       public base::SupportsWeakPtr<MockDownloadItemFactory> {
210  public:
211   MockDownloadItemFactory();
212   virtual ~MockDownloadItemFactory();
213
214   // Access to map of created items.
215   // TODO(rdsmith): Could add type (save page, persisted, etc.)
216   // functionality if it's ever needed by consumers.
217
218   // Returns NULL if no item of that id is present.
219   MockDownloadItemImpl* GetItem(int id);
220
221   // Remove and return an item made by the factory.
222   // Generally used during teardown.
223   MockDownloadItemImpl* PopItem();
224
225   // Should be called when the item of this id is removed so that
226   // we don't keep dangling pointers.
227   void RemoveItem(int id);
228
229   // Overridden methods from DownloadItemFactory.
230   virtual DownloadItemImpl* CreatePersistedItem(
231       DownloadItemImplDelegate* delegate,
232       uint32 download_id,
233       const base::FilePath& current_path,
234       const base::FilePath& target_path,
235       const std::vector<GURL>& url_chain,
236       const GURL& referrer_url,
237       const base::Time& start_time,
238       const base::Time& end_time,
239       const std::string& etag,
240       const std::string& last_modofied,
241       int64 received_bytes,
242       int64 total_bytes,
243       DownloadItem::DownloadState state,
244       DownloadDangerType danger_type,
245       DownloadInterruptReason interrupt_reason,
246       bool opened,
247       const net::BoundNetLog& bound_net_log) OVERRIDE;
248   virtual DownloadItemImpl* CreateActiveItem(
249       DownloadItemImplDelegate* delegate,
250       uint32 download_id,
251       const DownloadCreateInfo& info,
252       const net::BoundNetLog& bound_net_log) OVERRIDE;
253   virtual DownloadItemImpl* CreateSavePageItem(
254       DownloadItemImplDelegate* delegate,
255       uint32 download_id,
256       const base::FilePath& path,
257       const GURL& url,
258         const std::string& mime_type,
259       scoped_ptr<DownloadRequestHandleInterface> request_handle,
260       const net::BoundNetLog& bound_net_log) OVERRIDE;
261
262  private:
263   std::map<uint32, MockDownloadItemImpl*> items_;
264   DownloadItemImplDelegate item_delegate_;
265
266   DISALLOW_COPY_AND_ASSIGN(MockDownloadItemFactory);
267 };
268
269 MockDownloadItemFactory::MockDownloadItemFactory() {}
270
271 MockDownloadItemFactory::~MockDownloadItemFactory() {}
272
273 MockDownloadItemImpl* MockDownloadItemFactory::GetItem(int id) {
274   if (items_.find(id) == items_.end())
275     return NULL;
276   return items_[id];
277 }
278
279 MockDownloadItemImpl* MockDownloadItemFactory::PopItem() {
280   if (items_.empty())
281     return NULL;
282
283   std::map<uint32, MockDownloadItemImpl*>::iterator first_item
284       = items_.begin();
285   MockDownloadItemImpl* result = first_item->second;
286   items_.erase(first_item);
287   return result;
288 }
289
290 void MockDownloadItemFactory::RemoveItem(int id) {
291   DCHECK(items_.find(id) != items_.end());
292   items_.erase(id);
293 }
294
295 DownloadItemImpl* MockDownloadItemFactory::CreatePersistedItem(
296     DownloadItemImplDelegate* delegate,
297     uint32 download_id,
298     const base::FilePath& current_path,
299     const base::FilePath& target_path,
300     const std::vector<GURL>& url_chain,
301     const GURL& referrer_url,
302     const base::Time& start_time,
303     const base::Time& end_time,
304     const std::string& etag,
305     const std::string& last_modified,
306     int64 received_bytes,
307     int64 total_bytes,
308     DownloadItem::DownloadState state,
309     DownloadDangerType danger_type,
310     DownloadInterruptReason interrupt_reason,
311     bool opened,
312     const net::BoundNetLog& bound_net_log) {
313   DCHECK(items_.find(download_id) == items_.end());
314   MockDownloadItemImpl* result =
315       new StrictMock<MockDownloadItemImpl>(&item_delegate_);
316   EXPECT_CALL(*result, GetId())
317       .WillRepeatedly(Return(download_id));
318   items_[download_id] = result;
319   return result;
320 }
321
322 DownloadItemImpl* MockDownloadItemFactory::CreateActiveItem(
323     DownloadItemImplDelegate* delegate,
324     uint32 download_id,
325     const DownloadCreateInfo& info,
326     const net::BoundNetLog& bound_net_log) {
327   DCHECK(items_.find(download_id) == items_.end());
328
329   MockDownloadItemImpl* result =
330       new StrictMock<MockDownloadItemImpl>(&item_delegate_);
331   EXPECT_CALL(*result, GetId())
332       .WillRepeatedly(Return(download_id));
333   items_[download_id] = result;
334
335   // Active items are created and then immediately are called to start
336   // the download.
337   EXPECT_CALL(*result, MockStart(_, _));
338
339   return result;
340 }
341
342 DownloadItemImpl* MockDownloadItemFactory::CreateSavePageItem(
343     DownloadItemImplDelegate* delegate,
344     uint32 download_id,
345     const base::FilePath& path,
346     const GURL& url,
347     const std::string& mime_type,
348     scoped_ptr<DownloadRequestHandleInterface> request_handle,
349     const net::BoundNetLog& bound_net_log) {
350   DCHECK(items_.find(download_id) == items_.end());
351
352   MockDownloadItemImpl* result =
353       new StrictMock<MockDownloadItemImpl>(&item_delegate_);
354   EXPECT_CALL(*result, GetId())
355       .WillRepeatedly(Return(download_id));
356   items_[download_id] = result;
357
358   return result;
359 }
360
361 class MockDownloadFileFactory
362     : public DownloadFileFactory,
363       public base::SupportsWeakPtr<MockDownloadFileFactory> {
364  public:
365   MockDownloadFileFactory() {}
366   virtual ~MockDownloadFileFactory() {}
367
368   // Overridden method from DownloadFileFactory
369   MOCK_METHOD8(MockCreateFile, MockDownloadFile*(
370     const DownloadSaveInfo&,
371     const base::FilePath&,
372     const GURL&, const GURL&, bool,
373     ByteStreamReader*,
374     const net::BoundNetLog&,
375     base::WeakPtr<DownloadDestinationObserver>));
376
377   virtual DownloadFile* CreateFile(
378       scoped_ptr<DownloadSaveInfo> save_info,
379       const base::FilePath& default_download_directory,
380       const GURL& url,
381       const GURL& referrer_url,
382       bool calculate_hash,
383       scoped_ptr<ByteStreamReader> stream,
384       const net::BoundNetLog& bound_net_log,
385       base::WeakPtr<DownloadDestinationObserver> observer) {
386     return MockCreateFile(*save_info.get(), default_download_directory, url,
387                           referrer_url, calculate_hash,
388                           stream.get(), bound_net_log, observer);
389   }
390 };
391
392 class MockBrowserContext : public BrowserContext {
393  public:
394   MockBrowserContext() {}
395   ~MockBrowserContext() {}
396
397   MOCK_CONST_METHOD0(GetPath, base::FilePath());
398   MOCK_CONST_METHOD0(IsOffTheRecord, bool());
399   MOCK_METHOD0(GetRequestContext, net::URLRequestContextGetter*());
400   MOCK_METHOD1(GetRequestContextForRenderProcess,
401                net::URLRequestContextGetter*(int renderer_child_id));
402   MOCK_METHOD0(GetMediaRequestContext,
403                net::URLRequestContextGetter*());
404   MOCK_METHOD1(GetMediaRequestContextForRenderProcess,
405                net::URLRequestContextGetter*(int renderer_child_id));
406   MOCK_METHOD2(GetMediaRequestContextForStoragePartition,
407                net::URLRequestContextGetter*(
408                    const base::FilePath& partition_path, bool in_memory));
409   MOCK_METHOD6(RequestMidiSysExPermission,
410                void(int render_process_id,
411                     int render_view_id,
412                     int bridge_id,
413                     const GURL& requesting_frame,
414                     bool user_gesture,
415                     const MidiSysExPermissionCallback& callback));
416   MOCK_METHOD4(CancelMidiSysExPermissionRequest,
417                void(int render_process_id,
418                     int render_view_id,
419                     int bridge_id,
420                     const GURL& requesting_frame));
421   MOCK_METHOD6(RequestProtectedMediaIdentifierPermission,
422                void(int render_process_id,
423                     int render_view_id,
424                     int bridge_id,
425                     int group_id,
426                     const GURL& requesting_frame,
427                     const ProtectedMediaIdentifierPermissionCallback&
428                         callback));
429   MOCK_METHOD1(CancelProtectedMediaIdentifierPermissionRequests,
430                void(int group_id));
431   MOCK_METHOD0(GetResourceContext, ResourceContext*());
432   MOCK_METHOD0(GetDownloadManagerDelegate, DownloadManagerDelegate*());
433   MOCK_METHOD0(GetGeolocationPermissionContext,
434                GeolocationPermissionContext* ());
435   MOCK_METHOD0(GetGuestManagerDelegate,
436                BrowserPluginGuestManagerDelegate* ());
437   MOCK_METHOD0(GetSpecialStoragePolicy, quota::SpecialStoragePolicy*());
438 };
439
440 class MockDownloadManagerObserver : public DownloadManager::Observer {
441  public:
442   MockDownloadManagerObserver() {}
443   ~MockDownloadManagerObserver() {}
444   MOCK_METHOD2(OnDownloadCreated, void(
445         DownloadManager*, DownloadItem*));
446   MOCK_METHOD1(ManagerGoingDown, void(DownloadManager*));
447   MOCK_METHOD2(SelectFileDialogDisplayed, void(
448         DownloadManager*, int32));
449 };
450
451 }  // namespace
452
453 class DownloadManagerTest : public testing::Test {
454  public:
455   static const char* kTestData;
456   static const size_t kTestDataLen;
457
458   DownloadManagerTest()
459       : callback_called_(false),
460         ui_thread_(BrowserThread::UI, &message_loop_),
461         file_thread_(BrowserThread::FILE, &message_loop_),
462         next_download_id_(0) {
463   }
464
465   // We tear down everything in TearDown().
466   virtual ~DownloadManagerTest() {}
467
468   // Create a MockDownloadItemFactory and MockDownloadManagerDelegate,
469   // then create a DownloadManager that points
470   // at all of those.
471   virtual void SetUp() {
472     DCHECK(!download_manager_);
473
474     mock_download_item_factory_ = (new MockDownloadItemFactory())->AsWeakPtr();
475     mock_download_file_factory_ = (new MockDownloadFileFactory())->AsWeakPtr();
476     mock_download_manager_delegate_.reset(
477         new StrictMock<MockDownloadManagerDelegate>);
478     EXPECT_CALL(*mock_download_manager_delegate_.get(), Shutdown())
479         .WillOnce(Return());
480     mock_browser_context_.reset(new StrictMock<MockBrowserContext>);
481     EXPECT_CALL(*mock_browser_context_.get(), IsOffTheRecord())
482         .WillRepeatedly(Return(false));
483
484     download_manager_.reset(new DownloadManagerImpl(
485                                 NULL, mock_browser_context_.get()));
486     download_manager_->SetDownloadItemFactoryForTesting(
487         scoped_ptr<DownloadItemFactory>(
488             mock_download_item_factory_.get()).Pass());
489     download_manager_->SetDownloadFileFactoryForTesting(
490         scoped_ptr<DownloadFileFactory>(
491             mock_download_file_factory_.get()).Pass());
492     observer_.reset(new MockDownloadManagerObserver());
493     download_manager_->AddObserver(observer_.get());
494     download_manager_->SetDelegate(mock_download_manager_delegate_.get());
495   }
496
497   virtual void TearDown() {
498     while (MockDownloadItemImpl*
499            item = mock_download_item_factory_->PopItem()) {
500       EXPECT_CALL(*item, GetState())
501           .WillOnce(Return(DownloadItem::CANCELLED));
502     }
503     EXPECT_CALL(GetMockObserver(), ManagerGoingDown(download_manager_.get()))
504         .WillOnce(Return());
505
506     download_manager_->Shutdown();
507     download_manager_.reset();
508     message_loop_.RunUntilIdle();
509     ASSERT_EQ(NULL, mock_download_item_factory_.get());
510     ASSERT_EQ(NULL, mock_download_file_factory_.get());
511     message_loop_.RunUntilIdle();
512     mock_download_manager_delegate_.reset();
513     mock_browser_context_.reset();
514   }
515
516   // Returns download id.
517   MockDownloadItemImpl& AddItemToManager() {
518     DownloadCreateInfo info;
519
520     // Args are ignored except for download id, so everything else can be
521     // null.
522     uint32 id = next_download_id_;
523     ++next_download_id_;
524     info.request_handle = DownloadRequestHandle();
525     download_manager_->CreateActiveItem(id, info);
526     DCHECK(mock_download_item_factory_->GetItem(id));
527     MockDownloadItemImpl& item(*mock_download_item_factory_->GetItem(id));
528     // Satisfy expectation.  If the item is created in StartDownload(),
529     // we call Start on it immediately, so we need to set that expectation
530     // in the factory.
531     scoped_ptr<DownloadRequestHandleInterface> req_handle;
532     item.Start(scoped_ptr<DownloadFile>(), req_handle.Pass());
533
534     return item;
535   }
536
537   MockDownloadItemImpl& GetMockDownloadItem(int id) {
538     MockDownloadItemImpl* itemp = mock_download_item_factory_->GetItem(id);
539
540     DCHECK(itemp);
541     return *itemp;
542   }
543
544   void RemoveMockDownloadItem(int id) {
545     // Owned by DownloadManager; should be deleted there.
546     mock_download_item_factory_->RemoveItem(id);
547   }
548
549   MockDownloadManagerDelegate& GetMockDownloadManagerDelegate() {
550     return *mock_download_manager_delegate_;
551   }
552
553   MockDownloadManagerObserver& GetMockObserver() {
554     return *observer_;
555   }
556
557   void DownloadTargetDeterminedCallback(
558       const base::FilePath& target_path,
559       DownloadItem::TargetDisposition disposition,
560       DownloadDangerType danger_type,
561       const base::FilePath& intermediate_path) {
562     callback_called_ = true;
563     target_path_ = target_path;
564     target_disposition_ = disposition;
565     danger_type_ = danger_type;
566     intermediate_path_ = intermediate_path;
567   }
568
569   void DetermineDownloadTarget(DownloadItemImpl* item) {
570     download_manager_->DetermineDownloadTarget(
571         item, base::Bind(
572             &DownloadManagerTest::DownloadTargetDeterminedCallback,
573             base::Unretained(this)));
574   }
575
576  protected:
577   // Key test variable; we'll keep it available to sub-classes.
578   scoped_ptr<DownloadManagerImpl> download_manager_;
579   base::WeakPtr<MockDownloadFileFactory> mock_download_file_factory_;
580
581   // Target detetermined callback.
582   bool callback_called_;
583   base::FilePath target_path_;
584   DownloadItem::TargetDisposition target_disposition_;
585   DownloadDangerType danger_type_;
586   base::FilePath intermediate_path_;
587
588  private:
589   base::MessageLoopForUI message_loop_;
590   TestBrowserThread ui_thread_;
591   TestBrowserThread file_thread_;
592   base::WeakPtr<MockDownloadItemFactory> mock_download_item_factory_;
593   scoped_ptr<MockDownloadManagerDelegate> mock_download_manager_delegate_;
594   scoped_ptr<MockBrowserContext> mock_browser_context_;
595   scoped_ptr<MockDownloadManagerObserver> observer_;
596   uint32 next_download_id_;
597
598   DISALLOW_COPY_AND_ASSIGN(DownloadManagerTest);
599 };
600
601 // Confirm the appropriate invocations occur when you start a download.
602 TEST_F(DownloadManagerTest, StartDownload) {
603   scoped_ptr<DownloadCreateInfo> info(new DownloadCreateInfo);
604   scoped_ptr<ByteStreamReader> stream;
605   uint32 local_id(5);  // Random value
606   base::FilePath download_path(FILE_PATH_LITERAL("download/path"));
607
608   EXPECT_FALSE(download_manager_->GetDownload(local_id));
609
610   EXPECT_CALL(GetMockObserver(), OnDownloadCreated(download_manager_.get(), _))
611       .WillOnce(Return());
612   EXPECT_CALL(GetMockDownloadManagerDelegate(), GetNextId(_))
613       .WillOnce(RunCallback<0>(local_id));
614
615   // Doing nothing will set the default download directory to null.
616   EXPECT_CALL(GetMockDownloadManagerDelegate(), GetSaveDir(_, _, _, _));
617   EXPECT_CALL(GetMockDownloadManagerDelegate(), GenerateFileHash())
618       .WillOnce(Return(true));
619   EXPECT_CALL(GetMockDownloadManagerDelegate(),
620               ApplicationClientIdForFileScanning())
621       .WillRepeatedly(Return("client-id"));
622   MockDownloadFile* mock_file = new MockDownloadFile;
623   EXPECT_CALL(*mock_file, SetClientGuid("client-id"));
624   EXPECT_CALL(*mock_download_file_factory_.get(),
625               MockCreateFile(Ref(*info->save_info.get()), _, _, _, true,
626                              stream.get(), _, _))
627       .WillOnce(Return(mock_file));
628
629   download_manager_->StartDownload(
630       info.Pass(), stream.Pass(), DownloadUrlParameters::OnStartedCallback());
631   EXPECT_TRUE(download_manager_->GetDownload(local_id));
632 }
633
634 // Confirm that calling DetermineDownloadTarget behaves properly if the delegate
635 // blocks starting.
636 TEST_F(DownloadManagerTest, DetermineDownloadTarget_True) {
637   // Put a mock we have a handle to on the download manager.
638   MockDownloadItemImpl& item(AddItemToManager());
639   EXPECT_CALL(item, GetState())
640       .WillRepeatedly(Return(DownloadItem::IN_PROGRESS));
641
642   EXPECT_CALL(GetMockDownloadManagerDelegate(),
643               DetermineDownloadTarget(&item, _))
644       .WillOnce(Return(true));
645   DetermineDownloadTarget(&item);
646 }
647
648 // Confirm that calling DetermineDownloadTarget behaves properly if the delegate
649 // allows starting.  This also tests OnDownloadTargetDetermined.
650 TEST_F(DownloadManagerTest, DetermineDownloadTarget_False) {
651   // Put a mock we have a handle to on the download manager.
652   MockDownloadItemImpl& item(AddItemToManager());
653
654   base::FilePath path(FILE_PATH_LITERAL("random_filepath.txt"));
655   EXPECT_CALL(GetMockDownloadManagerDelegate(),
656               DetermineDownloadTarget(&item, _))
657       .WillOnce(Return(false));
658   EXPECT_CALL(item, GetForcedFilePath())
659       .WillOnce(ReturnRef(path));
660
661   // Confirm that the callback was called with the right values in this case.
662   callback_called_ = false;
663   DetermineDownloadTarget(&item);
664   EXPECT_TRUE(callback_called_);
665   EXPECT_EQ(path, target_path_);
666   EXPECT_EQ(DownloadItem::TARGET_DISPOSITION_OVERWRITE, target_disposition_);
667   EXPECT_EQ(DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, danger_type_);
668   EXPECT_EQ(path, intermediate_path_);
669 }
670
671 // Confirm the DownloadManagerImpl::RemoveAllDownloads() functionality
672 TEST_F(DownloadManagerTest, RemoveAllDownloads) {
673   base::Time now(base::Time::Now());
674   for (uint32 i = 0; i < 4; ++i) {
675     MockDownloadItemImpl& item(AddItemToManager());
676     EXPECT_EQ(i, item.GetId());
677     EXPECT_CALL(item, GetStartTime())
678         .WillRepeatedly(Return(now));
679   }
680
681   // Specify states for each.
682   EXPECT_CALL(GetMockDownloadItem(0), GetState())
683       .WillRepeatedly(Return(DownloadItem::COMPLETE));
684   EXPECT_CALL(GetMockDownloadItem(1), GetState())
685       .WillRepeatedly(Return(DownloadItem::CANCELLED));
686   EXPECT_CALL(GetMockDownloadItem(2), GetState())
687       .WillRepeatedly(Return(DownloadItem::INTERRUPTED));
688   EXPECT_CALL(GetMockDownloadItem(3), GetState())
689       .WillRepeatedly(Return(DownloadItem::IN_PROGRESS));
690
691   // Expectations for whether or not they'll actually be removed.
692   EXPECT_CALL(GetMockDownloadItem(0), Remove())
693       .WillOnce(Return());
694   EXPECT_CALL(GetMockDownloadItem(1), Remove())
695       .WillOnce(Return());
696   EXPECT_CALL(GetMockDownloadItem(2), Remove())
697       .WillOnce(Return());
698   EXPECT_CALL(GetMockDownloadItem(3), Remove())
699       .Times(0);
700
701   download_manager_->RemoveAllDownloads();
702   // Because we're mocking the download item, the Remove call doesn't
703   // result in them being removed from the DownloadManager list.
704 }
705
706 }  // namespace content