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

Side by Side Diff: content/browser/download/download_manager_impl_unittest.cc

Issue 10344024: Rewrite download manager unit to be actual unit tests. (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: Incorporate PS7 comment. Created 8 years, 6 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 | Annotate | Revision Log
« no previous file with comments | « content/browser/download/download_manager_impl.cc ('k') | content/content_browser.gypi » ('j') | no next file with comments »
Toggle Intra-line Diffs ('i') | Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
OLDNEW
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 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 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 <set> 5 #include <set>
6 #include <string> 6 #include <string>
7 7
8 #include "base/bind.h" 8 #include "base/bind.h"
9 #include "base/file_util.h" 9 #include "base/file_util.h"
10 #include "base/memory/scoped_ptr.h" 10 #include "base/memory/scoped_ptr.h"
11 #include "base/memory/weak_ptr.h"
11 #include "base/message_loop.h" 12 #include "base/message_loop.h"
12 #include "base/memory/scoped_ptr.h"
13 #include "base/scoped_temp_dir.h" 13 #include "base/scoped_temp_dir.h"
14 #include "base/stl_util.h" 14 #include "base/stl_util.h"
15 #include "base/string16.h" 15 #include "base/string16.h"
16 #include "base/string_util.h" 16 #include "base/string_util.h"
17 #include "base/utf_string_conversions.h" 17 #include "base/utf_string_conversions.h"
18 #include "build/build_config.h" 18 #include "build/build_config.h"
19 #include "content/browser/download/byte_stream.h"
19 #include "content/browser/download/download_create_info.h" 20 #include "content/browser/download/download_create_info.h"
20 #include "content/browser/download/download_file_impl.h"
21 #include "content/browser/download/download_file_manager.h" 21 #include "content/browser/download/download_file_manager.h"
22 #include "content/browser/download/download_item_factory.h"
22 #include "content/browser/download/download_manager_impl.h" 23 #include "content/browser/download/download_manager_impl.h"
23 #include "content/browser/download/download_request_handle.h" 24 #include "content/browser/download/download_request_handle.h"
24 #include "content/browser/download/mock_download_file.h" 25 #include "content/browser/download/mock_download_file.h"
25 #include "content/browser/power_save_blocker.h" 26 #include "content/public/browser/browser_context.h"
26 #include "content/public/browser/download_interrupt_reasons.h" 27 #include "content/public/browser/download_interrupt_reasons.h"
27 #include "content/public/browser/download_item.h" 28 #include "content/public/browser/download_item.h"
28 #include "content/public/browser/download_manager_delegate.h" 29 #include "content/public/browser/download_manager_delegate.h"
29 #include "content/public/test/mock_download_manager.h" 30 #include "content/public/test/mock_download_item.h"
30 #include "content/public/test/test_browser_context.h" 31 #include "content/public/test/test_browser_context.h"
31 #include "content/public/test/test_browser_thread.h" 32 #include "content/public/test/test_browser_thread.h"
32 #include "net/base/io_buffer.h"
33 #include "net/base/net_util.h" 33 #include "net/base/net_util.h"
34 #include "testing/gmock/include/gmock/gmock.h" 34 #include "testing/gmock/include/gmock/gmock.h"
35 #include "testing/gmock_mutant.h" 35 #include "testing/gmock_mutant.h"
36 #include "testing/gtest/include/gtest/gtest.h" 36 #include "testing/gtest/include/gtest/gtest.h"
37 37
38 #if defined(USE_AURA) && defined(OS_WIN) 38 using ::testing::DoAll;
39 // http://crbug.com/105200 39 using ::testing::Ref;
40 #define MAYBE_StartDownload DISABLED_StartDownload 40 using ::testing::Return;
41 #define MAYBE_DownloadOverwriteTest DISABLED_DownloadOverwriteTest 41 using ::testing::ReturnRef;
42 #define MAYBE_DownloadRemoveTest DISABLED_DownloadRemoveTest 42 using ::testing::SetArgPointee;
43 #define MAYBE_DownloadFileErrorTest DownloadFileErrorTest 43 using ::testing::StrictMock;
44 #elif defined(OS_LINUX) 44 using ::testing::_;
45 // http://crbug.com/110886 for Linux
46 #define MAYBE_StartDownload DISABLED_StartDownload
47 #define MAYBE_DownloadOverwriteTest DISABLED_DownloadOverwriteTest
48 #define MAYBE_DownloadRemoveTest DISABLED_DownloadRemoveTest
49 #define MAYBE_DownloadFileErrorTest DISABLED_DownloadFileErrorTest
50 #else
51 #define MAYBE_StartDownload StartDownload
52 #define MAYBE_DownloadOverwriteTest DownloadOverwriteTest
53 #define MAYBE_DownloadRemoveTest DownloadRemoveTest
54 #define MAYBE_DownloadFileErrorTest DownloadFileErrorTest
55 #endif
56
57 using content::BrowserContext;
58 using content::BrowserThread;
59 using content::DownloadFile;
60 using content::DownloadId;
61 using content::DownloadItem; 45 using content::DownloadItem;
62 using content::DownloadManager; 46 using content::DownloadManager;
63 using content::WebContents; 47 using content::WebContents;
64 using ::testing::NiceMock;
65 using ::testing::ReturnRef;
66 using ::testing::Return;
67 48
68 namespace content { 49 namespace content {
69 class ByteStreamReader; 50 class ByteStreamReader;
70 } 51 }
71 52
72 namespace { 53 namespace {
73 54
74 FilePath GetTempDownloadPath(const FilePath& suggested_path) { 55 class MockDownloadManagerDelegate : public content::DownloadManagerDelegate {
75 return FilePath(suggested_path.value() + FILE_PATH_LITERAL(".temp"));
76 }
77
78 class MockDownloadFileFactory
79 : public DownloadFileManager::DownloadFileFactory {
80 public: 56 public:
81 MockDownloadFileFactory() {} 57 MockDownloadManagerDelegate();
82 58 virtual ~MockDownloadManagerDelegate();
83 virtual DownloadFile* CreateFile( 59
84 DownloadCreateInfo* info, 60 MOCK_METHOD0(Shutdown, void());
61 MOCK_METHOD0(GetNextId, content::DownloadId());
62 MOCK_METHOD1(ShouldStartDownload, bool(int32));
63 MOCK_METHOD3(ChooseDownloadPath, void(WebContents*, const FilePath&, int32));
64 MOCK_METHOD2(GetIntermediatePath, FilePath(const DownloadItem&, bool*));
65 MOCK_METHOD0(GetAlternativeWebContentsToNotifyForDownload, WebContents*());
66 MOCK_METHOD1(ShouldOpenFileBasedOnExtension, bool(const FilePath&));
67 MOCK_METHOD2(ShouldCompleteDownload, bool(
68 DownloadItem*, const base::Closure&));
69 MOCK_METHOD1(ShouldOpenDownload, bool(DownloadItem*));
70 MOCK_METHOD0(GenerateFileHash, bool());
71 MOCK_METHOD1(AddItemToPersistentStore, void(DownloadItem*));
72 MOCK_METHOD1(UpdateItemInPersistentStore, void(DownloadItem*));
73 MOCK_METHOD2(UpdatePathForItemInPersistentStore,
74 void(DownloadItem*, const FilePath&));
75 MOCK_METHOD1(RemoveItemFromPersistentStore, void(DownloadItem*));
76 MOCK_METHOD2(RemoveItemsFromPersistentStoreBetween, void(
77 base::Time remove_begin, base::Time remove_end));
78 MOCK_METHOD3(GetSaveDir, void(WebContents*, FilePath*, FilePath*));
79 MOCK_METHOD5(ChooseSavePath, void(
80 WebContents*, const FilePath&, const FilePath::StringType&,
81 bool, const content::SavePackagePathPickedCallback&));
82 };
83
84 MockDownloadManagerDelegate::MockDownloadManagerDelegate() { }
85
86 MockDownloadManagerDelegate::~MockDownloadManagerDelegate() { }
87
88 class MockDownloadFileManager : public DownloadFileManager {
89 public:
90 MockDownloadFileManager();
91
92 MOCK_METHOD0(Shutdown, void());
93 MOCK_METHOD3(MockStartDownload,
94 content::DownloadId(DownloadCreateInfo*,
95 content::ByteStreamReader* stream,
96 const DownloadRequestHandle&));
97
98 virtual content::DownloadId StartDownload(
99 scoped_ptr<DownloadCreateInfo> info,
85 scoped_ptr<content::ByteStreamReader> stream, 100 scoped_ptr<content::ByteStreamReader> stream,
86 const DownloadRequestHandle& request_handle, 101 const DownloadRequestHandle& request_handle) OVERRIDE {
87 DownloadManager* download_manager, 102 return MockStartDownload(info.get(), stream.get(), request_handle);
88 bool calculate_hash, 103 }
104
105 MOCK_METHOD1(CancelDownload, void(content::DownloadId));
106 MOCK_METHOD1(CompleteDownload, void(content::DownloadId));
107 MOCK_METHOD1(OnDownloadManagerShutdown, void(content::DownloadManager*));
108 MOCK_METHOD4(RenameInProgressDownloadFile,
109 void(content::DownloadId,
110 const FilePath&,
111 bool,
112 const RenameCompletionCallback&));
113 MOCK_METHOD4(RenameCompletingDownloadFile,
114 void(content::DownloadId,
115 const FilePath&,
116 bool,
117 const RenameCompletionCallback&));
118 MOCK_CONST_METHOD0(NumberOfActiveDownloads, int());
119 protected:
120 virtual ~MockDownloadFileManager();
121 };
122
123 MockDownloadFileManager::MockDownloadFileManager()
124 : DownloadFileManager(NULL) { }
125
126 MockDownloadFileManager::~MockDownloadFileManager() { }
127
128 class MockDownloadItemFactory
129 : public content::DownloadItemFactory,
130 public base::SupportsWeakPtr<MockDownloadItemFactory> {
131 public:
132 explicit MockDownloadItemFactory();
asanka 2012/06/08 22:14:18 Minor nit: no need for 'explicit' for 0 argument c
Randy Smith (Not in Mondays) 2012/06/09 17:32:39 Done.
133 virtual ~MockDownloadItemFactory();
134
135 // Access to map of created items.
136 // TODO(rdsmith): Could add type (save page, persisted, etc.)
137 // functionality if it's ever needed by consumers.
138
139 // Returns NULL if no item of that id is present.
140 content::MockDownloadItem* GetItem(int id);
141
142 // Returns a vector of currently active ids.
143 std::vector<int> Ids() const;
144
145 // Should be called when the item of this id is removed so that
146 // we don't keep dangling pointers.
147 void RemoveItem(int id);
148
149 // Overridden methods from DownloadItemFactory.
150 virtual content::DownloadItem* CreatePersistedItem(
151 DownloadItemImpl::Delegate* delegate,
152 content::DownloadId download_id,
153 const content::DownloadPersistentStoreInfo& info,
89 const net::BoundNetLog& bound_net_log) OVERRIDE; 154 const net::BoundNetLog& bound_net_log) OVERRIDE;
155 virtual content::DownloadItem* CreateActiveItem(
156 DownloadItemImpl::Delegate* delegate,
157 const DownloadCreateInfo& info,
158 DownloadRequestHandleInterface* request_handle,
159 bool is_otr,
160 const net::BoundNetLog& bound_net_log) OVERRIDE;
161 virtual content::DownloadItem* CreateSavePageItem(
162 DownloadItemImpl::Delegate* delegate,
163 const FilePath& path,
164 const GURL& url,
165 bool is_otr,
166 content::DownloadId download_id,
167 const std::string& mime_type,
168 const net::BoundNetLog& bound_net_log) OVERRIDE;
169
170 private:
171 std::map<int32, content::MockDownloadItem*> items_;
172
173 DISALLOW_COPY_AND_ASSIGN(MockDownloadItemFactory);
90 }; 174 };
91 175
92 DownloadFile* MockDownloadFileFactory::CreateFile( 176 MockDownloadItemFactory::MockDownloadItemFactory() {}
93 DownloadCreateInfo* info, 177
94 scoped_ptr<content::ByteStreamReader> stream, 178 MockDownloadItemFactory::~MockDownloadItemFactory() {}
95 const DownloadRequestHandle& request_handle, 179
96 DownloadManager* download_manager, 180 content::MockDownloadItem* MockDownloadItemFactory::GetItem(int id) {
97 bool calculate_hash, 181 if (items_.find(id) == items_.end())
182 return NULL;
183 return items_[id];
184 }
185
186 std::vector<int> MockDownloadItemFactory::Ids() const {
187 std::vector<int> result;
188 for (std::map<int32, content::MockDownloadItem*>::const_iterator it =
189 items_.begin(); it != items_.end(); it++)
190 result.push_back(it->first);
Randy Smith (Not in Mondays) 2012/06/07 23:27:21 I'm sure there's an STL-fancy way to do this, but
191 return result;
192 }
193
194 void MockDownloadItemFactory::RemoveItem(int id) {
195 DCHECK(items_.find(id) != items_.end());
196 items_.erase(id);
197 }
198
199 content::DownloadItem* MockDownloadItemFactory::CreatePersistedItem(
200 DownloadItemImpl::Delegate* delegate,
201 content::DownloadId download_id,
202 const content::DownloadPersistentStoreInfo& info,
98 const net::BoundNetLog& bound_net_log) { 203 const net::BoundNetLog& bound_net_log) {
99 NOTREACHED(); 204 int local_id = download_id.local();
100 return NULL; 205 DCHECK(items_.find(local_id) == items_.end());
101 } 206
102 207 content::MockDownloadItem* result =
103 class TestDownloadManagerDelegate : public content::DownloadManagerDelegate { 208 new StrictMock<content::MockDownloadItem>;
209 EXPECT_CALL(*result, GetId())
210 .WillRepeatedly(Return(local_id));
211 items_[local_id] = result;
212
213 return result;
214 }
215
216 content::DownloadItem* MockDownloadItemFactory::CreateActiveItem(
217 DownloadItemImpl::Delegate* delegate,
218 const DownloadCreateInfo& info,
219 DownloadRequestHandleInterface* request_handle,
220 bool is_otr,
221 const net::BoundNetLog& bound_net_log) {
222 int local_id = info.download_id.local();
223 DCHECK(items_.find(local_id) == items_.end());
224
225 content::MockDownloadItem* result =
226 new StrictMock<content::MockDownloadItem>;
227 EXPECT_CALL(*result, GetId())
228 .WillRepeatedly(Return(local_id));
229 items_[local_id] = result;
230
231 return result;
232 }
233
234 content::DownloadItem* MockDownloadItemFactory::CreateSavePageItem(
235 DownloadItemImpl::Delegate* delegate,
236 const FilePath& path,
237 const GURL& url,
238 bool is_otr,
239 content::DownloadId download_id,
240 const std::string& mime_type,
241 const net::BoundNetLog& bound_net_log) {
242 int local_id = download_id.local();
243 DCHECK(items_.find(local_id) == items_.end());
244
245 content::MockDownloadItem* result =
246 new StrictMock<content::MockDownloadItem>;
247 EXPECT_CALL(*result, GetId())
248 .WillRepeatedly(Return(local_id));
249 items_[local_id] = result;
250
251 return result;
252 }
253
254 class MockBrowserContext : public content::BrowserContext {
104 public: 255 public:
105 explicit TestDownloadManagerDelegate(content::DownloadManager* dm) 256 MockBrowserContext() { }
106 : mark_content_dangerous_(false), 257 ~MockBrowserContext() { }
107 prompt_user_for_save_location_(false), 258
108 should_complete_download_(true), 259 MOCK_METHOD0(GetPath, FilePath());
109 download_manager_(dm) { 260 MOCK_CONST_METHOD0(IsOffTheRecord, bool());
110 } 261 MOCK_METHOD0(GetRequestContext, net::URLRequestContextGetter*());
111 262 MOCK_METHOD1(GetRequestContextForRenderProcess,
112 void set_download_directory(const FilePath& path) { 263 net::URLRequestContextGetter*(int renderer_child_id));
113 download_directory_ = path; 264 MOCK_METHOD0(GetRequestContextForMedia, net::URLRequestContextGetter*());
114 } 265 MOCK_METHOD0(GetResourceContext, content::ResourceContext*());
115 266 MOCK_METHOD0(GetDownloadManagerDelegate, content::DownloadManagerDelegate*());
116 void set_prompt_user_for_save_location(bool value) { 267 MOCK_METHOD0(GetGeolocationPermissionContext,
117 prompt_user_for_save_location_ = value; 268 content::GeolocationPermissionContext* ());
118 } 269 MOCK_METHOD0(GetSpeechRecognitionPreferences,
119 270 content::SpeechRecognitionPreferences* ());
120 virtual bool ShouldStartDownload(int32 download_id) OVERRIDE { 271 MOCK_METHOD0(DidLastSessionExitCleanly, bool());
121 DownloadItem* item = download_manager_->GetActiveDownloadItem(download_id); 272 MOCK_METHOD0(GetSpecialStoragePolicy, quota::SpecialStoragePolicy*());
122 FilePath path = net::GenerateFileName(item->GetURL(),
123 item->GetContentDisposition(),
124 item->GetReferrerCharset(),
125 item->GetSuggestedFilename(),
126 item->GetMimeType(),
127 std::string());
128 DownloadItem::TargetDisposition disposition = item->GetTargetDisposition();
129 if (!ShouldOpenFileBasedOnExtension(path) && prompt_user_for_save_location_)
130 disposition = DownloadItem::TARGET_DISPOSITION_PROMPT;
131 item->OnTargetPathDetermined(download_directory_.Append(path),
132 disposition,
133 content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS);
134 return true;
135 }
136
137 virtual FilePath GetIntermediatePath(const DownloadItem& item,
138 bool* ok_to_overwrite) OVERRIDE {
139 if (intermediate_path_.empty()) {
140 *ok_to_overwrite = true;
141 return GetTempDownloadPath(item.GetTargetFilePath());
142 } else {
143 *ok_to_overwrite = overwrite_intermediate_path_;
144 return intermediate_path_;
145 }
146 }
147
148 virtual void ChooseDownloadPath(WebContents* web_contents,
149 const FilePath& suggested_path,
150 int32 download_id) OVERRIDE {
151 if (!expected_suggested_path_.empty()) {
152 EXPECT_STREQ(expected_suggested_path_.value().c_str(),
153 suggested_path.value().c_str());
154 }
155 if (file_selection_response_.empty()) {
156 BrowserThread::PostTask(
157 BrowserThread::UI, FROM_HERE,
158 base::Bind(&DownloadManager::FileSelectionCanceled,
159 download_manager_,
160 download_id));
161 } else {
162 BrowserThread::PostTask(
163 BrowserThread::UI, FROM_HERE,
164 base::Bind(&DownloadManager::FileSelected,
165 download_manager_,
166 file_selection_response_,
167 download_id));
168 }
169 expected_suggested_path_.clear();
170 file_selection_response_.clear();
171 }
172
173 virtual bool ShouldOpenFileBasedOnExtension(const FilePath& path) OVERRIDE {
174 return path.Extension() == FilePath::StringType(FILE_PATH_LITERAL(".pdf"));
175 }
176
177 virtual void AddItemToPersistentStore(DownloadItem* item) OVERRIDE {
178 static int64 db_handle = DownloadItem::kUninitializedHandle;
179 download_manager_->OnItemAddedToPersistentStore(item->GetId(), --db_handle);
180 }
181
182 void SetFileSelectionExpectation(const FilePath& suggested_path,
183 const FilePath& response) {
184 expected_suggested_path_ = suggested_path;
185 file_selection_response_ = response;
186 }
187
188 void SetMarkContentsDangerous(bool dangerous) {
189 mark_content_dangerous_ = dangerous;
190 }
191
192 void SetIntermediatePath(const FilePath& intermediate_path,
193 bool overwrite_intermediate_path) {
194 intermediate_path_ = intermediate_path;
195 overwrite_intermediate_path_ = overwrite_intermediate_path;
196 }
197
198 void SetShouldCompleteDownload(bool value) {
199 should_complete_download_ = value;
200 }
201
202 void InvokeDownloadCompletionCallback() {
203 EXPECT_FALSE(download_completion_callback_.is_null());
204 download_completion_callback_.Run();
205 download_completion_callback_.Reset();
206 }
207
208 virtual bool ShouldCompleteDownload(
209 DownloadItem* item,
210 const base::Closure& complete_callback) OVERRIDE {
211 download_completion_callback_ = complete_callback;
212 if (mark_content_dangerous_) {
213 CHECK(!complete_callback.is_null());
214 BrowserThread::PostTask(
215 BrowserThread::UI, FROM_HERE,
216 base::Bind(&TestDownloadManagerDelegate::MarkContentDangerous,
217 base::Unretained(this), item->GetId()));
218 mark_content_dangerous_ = false;
219 return false;
220 } else {
221 return should_complete_download_;
222 }
223 }
224
225 private:
226 void MarkContentDangerous(
227 int32 download_id) {
228 DownloadItem* item = download_manager_->GetActiveDownloadItem(download_id);
229 if (!item)
230 return;
231 item->OnContentCheckCompleted(
232 content::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT);
233 InvokeDownloadCompletionCallback();
234 }
235
236 FilePath download_directory_;
237 FilePath expected_suggested_path_;
238 FilePath file_selection_response_;
239 FilePath intermediate_path_;
240 bool overwrite_intermediate_path_;
241 bool mark_content_dangerous_;
242 bool prompt_user_for_save_location_;
243 bool should_complete_download_;
244 DownloadManager* download_manager_;
245 base::Closure download_completion_callback_;
246
247 DISALLOW_COPY_AND_ASSIGN(TestDownloadManagerDelegate);
248 }; 273 };
249 274
250 } // namespace 275 } // namespace
251 276
252 class DownloadManagerTest : public testing::Test { 277 class DownloadManagerTest : public testing::Test {
253 public: 278 public:
254 static const char* kTestData; 279 static const char* kTestData;
255 static const size_t kTestDataLen; 280 static const size_t kTestDataLen;
256 281
257 DownloadManagerTest() 282 DownloadManagerTest()
258 : browser_context(new content::TestBrowserContext()), 283 : ui_thread_(content::BrowserThread::UI, &message_loop_),
259 download_manager_(new DownloadManagerImpl(NULL)), 284 file_thread_(content::BrowserThread::FILE, &message_loop_),
260 ui_thread_(BrowserThread::UI, &message_loop_), 285 next_download_id_(0) {
261 file_thread_(BrowserThread::FILE, &message_loop_) { 286 }
262 download_manager_delegate_.reset( 287
263 new TestDownloadManagerDelegate(download_manager_.get())); 288 // We tear down everything in TearDown().
264 download_manager_->SetDelegate(download_manager_delegate_.get()); 289 ~DownloadManagerTest() {}
265 download_manager_->Init(browser_context.get()); 290
266 } 291 // Create a MockDownloadItemFactory, MockDownloadManagerDelegate,
267 292 // and MockDownloadFileManager, then create a DownloadManager that points
268 ~DownloadManagerTest() { 293 // at all of those.
294 virtual void SetUp() {
295 DCHECK(!download_manager_.get());
296
297 mock_download_item_factory_ = (new MockDownloadItemFactory())->AsWeakPtr();
298 mock_download_manager_delegate_.reset(
299 new StrictMock<MockDownloadManagerDelegate>);
300 EXPECT_CALL(*mock_download_manager_delegate_.get(), Shutdown())
301 .WillOnce(Return());
302 mock_download_file_manager_ = new StrictMock<MockDownloadFileManager>;
303 EXPECT_CALL(*mock_download_file_manager_.get(),
304 OnDownloadManagerShutdown(_));
305 mock_browser_context_.reset(new StrictMock<MockBrowserContext>);
306 EXPECT_CALL(*mock_browser_context_.get(), IsOffTheRecord())
307 .WillRepeatedly(Return(false));
308
309 download_manager_ = new DownloadManagerImpl(
310 mock_download_file_manager_.get(),
311 scoped_ptr<content::DownloadItemFactory>(
312 mock_download_item_factory_.get()).Pass(), NULL);
313 download_manager_->SetDelegate(mock_download_manager_delegate_.get());
314 download_manager_->Init(mock_browser_context_.get());
315 }
316
317 virtual void TearDown() {
318 std::vector<int> active_ids(mock_download_item_factory_->Ids());
asanka 2012/06/08 22:14:18 It seems something like mock_download_item_factory
Randy Smith (Not in Mondays) 2012/06/09 17:32:39 Done.
319 for (std::vector<int>::iterator it = active_ids.begin();
320 it != active_ids.end(); ++it) {
321 content::MockDownloadItem& item(
322 *mock_download_item_factory_->GetItem(*it));
323 EXPECT_CALL(item, GetSafetyState())
324 .WillOnce(Return(content::DownloadItem::SAFE));
325 EXPECT_CALL(item, IsPartialDownload())
326 .WillOnce(Return(false));
327 mock_download_item_factory_->RemoveItem(*it);
328 }
329
269 download_manager_->Shutdown(); 330 download_manager_->Shutdown();
270 // browser_context must outlive download_manager_, so we explicitly delete
271 // download_manager_ first.
272 download_manager_ = NULL; 331 download_manager_ = NULL;
273 download_manager_delegate_.reset();
274 browser_context.reset(NULL);
275 message_loop_.RunAllPending(); 332 message_loop_.RunAllPending();
276 } 333 ASSERT_EQ(NULL, mock_download_item_factory_.get());
277 334 message_loop_.RunAllPending();
278 // Create a temporary directory as the downloads directory. 335 mock_download_manager_delegate_.reset();
279 bool CreateTempDownloadsDirectory() { 336 mock_download_file_manager_ = NULL;
280 if (!scoped_download_dir_.CreateUniqueTempDir()) 337 mock_browser_context_.reset();
281 return false; 338 }
282 download_manager_delegate_->set_download_directory( 339
283 scoped_download_dir_.path()); 340 // Returns download id.
284 return true; 341 content::MockDownloadItem& AddItemToManager() {
285 } 342 DownloadCreateInfo info;
286 343 DownloadRequestHandle handle;
287 void AddDownloadToFileManager(DownloadId id, DownloadFile* download_file) { 344
288 file_manager()->downloads_[id] = 345 static const char* kDownloadIdDomain = "Test download id domain";
289 download_file; 346
290 } 347 // Args are ignored except for download id, so everything else can be
291 348 // null.
292 void AddMockDownloadToFileManager(DownloadId id, 349 int id = next_download_id_;
293 MockDownloadFile* download_file) { 350 ++next_download_id_;
294 AddDownloadToFileManager(id, download_file); 351 info.download_id = content::DownloadId(kDownloadIdDomain, id);
295 EXPECT_CALL(*download_file, GetDownloadManager()) 352 download_manager_->CreateDownloadItem(&info, handle);
296 .WillRepeatedly(Return(download_manager_)); 353
297 } 354 DCHECK(mock_download_item_factory_->GetItem(id));
298 355 content::MockDownloadItem& item(*mock_download_item_factory_->GetItem(id));
299 void OnResponseCompleted(DownloadId download_id, int64 size, 356 ON_CALL(item, GetId())
300 const std::string& hash) { 357 .WillByDefault(Return(id));
301 download_manager_->OnResponseCompleted(download_id.local(), size, hash); 358
302 } 359 return item;
303 360 }
304 void ContinueDownloadWithPath(DownloadItem* download, const FilePath& path) { 361
305 download->OnTargetPathDetermined( 362 content::MockDownloadItem& GetMockDownloadItem(int id) {
306 path, DownloadItem::TARGET_DISPOSITION_OVERWRITE, 363 content::MockDownloadItem* itemp = mock_download_item_factory_->GetItem(id);
307 content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS); 364
308 download_manager_->OnTargetPathAvailable(download); 365 DCHECK(itemp);
309 } 366 return *itemp;
310 367 }
311 void OnDownloadInterrupted(DownloadId download_id, int64 size, 368
312 const std::string& hash_state, 369 void RemoveMockDownloadItem(int id) {
313 content::DownloadInterruptReason reason) { 370 // Owned by DownloadManager; should be deleted there.
314 download_manager_->OnDownloadInterrupted(download_id.local(), size, 371 mock_download_item_factory_->RemoveItem(id);
315 hash_state, reason); 372 }
316 } 373
317 374 MockDownloadManagerDelegate& GetMockDownloadManagerDelegate() {
318 // Get the download item with ID |id|. 375 return *mock_download_manager_delegate_;
319 DownloadItem* GetActiveDownloadItem(DownloadId id) { 376 }
320 return download_manager_->GetActiveDownload(id.local()); 377
321 } 378 MockDownloadFileManager& GetMockDownloadFileManager() {
322 379 return *mock_download_file_manager_;
323 FilePath GetPathInDownloadsDir(const FilePath::StringType& fragment) { 380 }
324 DCHECK(scoped_download_dir_.IsValid()); 381
325 FilePath full_path(scoped_download_dir_.path().Append(fragment)); 382 // Probe at private internals.
326 return full_path.NormalizePathSeparators(); 383 DownloadItem* GetActiveDownloadItem(int32 id) {
384 return download_manager_->GetActiveDownload(id);
385 }
386
387 void AddItemToHistory(content::MockDownloadItem& item, int64 db_handle) {
388 // For DCHECK in AddDownloadItemToHistory. Don't want to use
389 // WillRepeatedly as it may have to return true after this.
390 if (DCHECK_IS_ON())
391 EXPECT_CALL(item, IsPersisted())
392 .WillOnce(Return(false));
393
394 EXPECT_CALL(item, SetDbHandle(db_handle));
395 EXPECT_CALL(item, SetIsPersisted());
396 EXPECT_CALL(item, GetDbHandle())
397 .WillRepeatedly(Return(db_handle));
398
399 // Null out ShowDownloadInBrowser
400 EXPECT_CALL(item, GetWebContents())
401 .WillOnce(Return(static_cast<WebContents*>(NULL)));
402 EXPECT_CALL(GetMockDownloadManagerDelegate(),
403 GetAlternativeWebContentsToNotifyForDownload())
404 .WillOnce(Return(static_cast<WebContents*>(NULL)));
405
406 EXPECT_CALL(item, IsInProgress())
407 .WillOnce(Return(true));
408
409 // Null out MaybeCompleteDownload
410 EXPECT_CALL(item, AllDataSaved())
411 .WillOnce(Return(false));
412
413 download_manager_->OnItemAddedToPersistentStore(item.GetId(), db_handle);
327 } 414 }
328 415
329 protected: 416 protected:
330 scoped_ptr<content::TestBrowserContext> browser_context; 417 // Key test variable; we'll keep it available to sub-classes.
331 scoped_ptr<TestDownloadManagerDelegate> download_manager_delegate_;
332 scoped_refptr<DownloadManagerImpl> download_manager_; 418 scoped_refptr<DownloadManagerImpl> download_manager_;
333 scoped_refptr<DownloadFileManager> file_manager_; 419
420 private:
334 MessageLoopForUI message_loop_; 421 MessageLoopForUI message_loop_;
335 content::TestBrowserThread ui_thread_; 422 content::TestBrowserThread ui_thread_;
336 content::TestBrowserThread file_thread_; 423 content::TestBrowserThread file_thread_;
337 ScopedTempDir scoped_download_dir_; 424 base::WeakPtr<MockDownloadItemFactory> mock_download_item_factory_;
338 425 scoped_ptr<MockDownloadManagerDelegate> mock_download_manager_delegate_;
339 DownloadFileManager* file_manager() { 426 scoped_refptr<MockDownloadFileManager> mock_download_file_manager_;
340 if (!file_manager_) { 427 scoped_ptr<MockBrowserContext> mock_browser_context_;
341 file_manager_ = new DownloadFileManager(new MockDownloadFileFactory); 428 int next_download_id_;
342 download_manager_->SetFileManagerForTesting(file_manager_);
343 }
344 return file_manager_;
345 }
346 429
347 DISALLOW_COPY_AND_ASSIGN(DownloadManagerTest); 430 DISALLOW_COPY_AND_ASSIGN(DownloadManagerTest);
348 }; 431 };
349 432
350 const char* DownloadManagerTest::kTestData = "a;sdlfalsdfjalsdkfjad"; 433 // Does the DownloadManager prompt when requested?
351 const size_t DownloadManagerTest::kTestDataLen = 434 TEST_F(DownloadManagerTest, RestartDownload) {
352 strlen(DownloadManagerTest::kTestData); 435 // Put a mock we have a handle to on the download manager.
353 436 content::MockDownloadItem& item(AddItemToManager());
354 // A DownloadFile that we can inject errors into. 437 int download_id = item.GetId();
355 class DownloadFileWithErrors : public DownloadFileImpl { 438
356 public: 439 // Confirm we're internally consistent.
357 DownloadFileWithErrors(DownloadCreateInfo* info, 440 EXPECT_EQ(&item, GetActiveDownloadItem(download_id));
358 scoped_ptr<content::ByteStreamReader> stream, 441
359 DownloadManager* manager, 442 ScopedTempDir download_dir;
360 bool calculate_hash); 443 ASSERT_TRUE(download_dir.CreateUniqueTempDir());
361 virtual ~DownloadFileWithErrors() {} 444 FilePath expected_path(download_dir.path().Append(
362 445 FILE_PATH_LITERAL("location")));
363 // BaseFile delegated functions. 446
364 virtual net::Error Initialize() OVERRIDE; 447 EXPECT_CALL(item, GetTargetDisposition())
365 virtual net::Error AppendDataToFile(const char* data, 448 .WillOnce(Return(DownloadItem::TARGET_DISPOSITION_PROMPT));
366 size_t data_len) OVERRIDE; 449 EXPECT_CALL(item, GetWebContents())
367 virtual net::Error Rename(const FilePath& full_path) OVERRIDE; 450 .WillOnce(Return(reinterpret_cast<WebContents*>(0x44)));
368 451 EXPECT_CALL(item, GetTargetFilePath())
369 void set_forced_error(net::Error error) { forced_error_ = error; } 452 .WillOnce(ReturnRef(expected_path));
370 void clear_forced_error() { forced_error_ = net::OK; } 453 EXPECT_CALL(GetMockDownloadManagerDelegate(), ChooseDownloadPath(
371 net::Error forced_error() const { return forced_error_; } 454 reinterpret_cast<WebContents*>(0x44), expected_path, download_id));
372 455 download_manager_->RestartDownload(download_id);
373 private: 456
374 net::Error ReturnError(net::Error function_error) { 457 // The alternative pathway goes straight to OnTargetPathAvailable,
375 if (forced_error_ != net::OK) { 458 // so it more naturally belongs below.
376 net::Error ret = forced_error_; 459 }
377 clear_forced_error(); 460
378 return ret; 461 // Do the results of GetIntermediatePath get passed through to the
379 } 462 // download? Note that this path is tested from RestartDownload
380 463 // to test the non-prompting path in RestartDownload as well.
381 return function_error; 464 TEST_F(DownloadManagerTest, OnTargetPathAvailable) {
382 } 465 // Put a mock we have a handle to on the download manager.
383 466 content::MockDownloadItem& item(AddItemToManager());
384 net::Error forced_error_; 467
385 }; 468 ScopedTempDir download_dir;
386 469 ASSERT_TRUE(download_dir.CreateUniqueTempDir());
387 DownloadFileWithErrors::DownloadFileWithErrors( 470 FilePath target_path(download_dir.path().Append(
388 DownloadCreateInfo* info, 471 FILE_PATH_LITERAL("location")));
389 scoped_ptr<content::ByteStreamReader> stream, 472 FilePath intermediate_path(download_dir.path().Append(
390 DownloadManager* manager, 473 FILE_PATH_LITERAL("location.crdownload")));
391 bool calculate_hash) 474
392 : DownloadFileImpl(info, 475 EXPECT_CALL(item, GetTargetDisposition())
393 stream.Pass(), 476 .WillOnce(Return(DownloadItem::TARGET_DISPOSITION_UNIQUIFY));
394 new DownloadRequestHandle(), 477 EXPECT_CALL(GetMockDownloadManagerDelegate(),
395 manager, 478 GetIntermediatePath(Ref(item), _))
396 calculate_hash, 479 .WillOnce(DoAll(SetArgPointee<1>(true), Return(intermediate_path)));
397 scoped_ptr<PowerSaveBlocker>(NULL).Pass(), 480 // Finesse DCHECK with WillRepeatedly.
398 net::BoundNetLog()), 481 EXPECT_CALL(item, GetTargetFilePath())
399 forced_error_(net::OK) { 482 .WillRepeatedly(ReturnRef(target_path));
400 } 483 EXPECT_CALL(item, OnIntermediatePathDetermined(
401 484 &GetMockDownloadFileManager(), intermediate_path, true));
402 net::Error DownloadFileWithErrors::Initialize() { 485 download_manager_->RestartDownload(item.GetId());
403 return ReturnError(DownloadFileImpl::Initialize()); 486 }
404 } 487
405 488 // Do the results of an OnDownloadInterrupted get passed through properly
406 net::Error DownloadFileWithErrors::AppendDataToFile(const char* data, 489 // to the DownloadItem? This test tests non-persisted downloads.
407 size_t data_len) { 490 TEST_F(DownloadManagerTest, OnDownloadInterrupted_NonPersisted) {
408 return ReturnError(DownloadFileImpl::AppendDataToFile(data, data_len)); 491 // Put a mock we have a handle to on the download manager.
409 } 492 content::MockDownloadItem& item(AddItemToManager());
410 493 int download_id = item.GetId();
411 net::Error DownloadFileWithErrors::Rename(const FilePath& full_path) { 494
412 return ReturnError(DownloadFileImpl::Rename(full_path)); 495 int64 size = 0xdeadbeef;
413 } 496 const std::string hash_state("Undead beef");
414 497 content::DownloadInterruptReason reason(
415 namespace { 498 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED);
416 499
417 const struct { 500 EXPECT_CALL(item, Interrupted(size, hash_state, reason));
418 const char* url; 501 EXPECT_CALL(item, OffThreadCancel(&GetMockDownloadFileManager()));
419 const char* mime_type; 502 EXPECT_CALL(item, IsPersisted())
420 bool save_as; 503 .WillOnce(Return(false));
421 bool prompt_for_download; 504 download_manager_->OnDownloadInterrupted(
422 bool expected_save_as; 505 download_id, size, hash_state, reason);
423 } kStartDownloadCases[] = { 506 EXPECT_EQ(&item, GetActiveDownloadItem(download_id));
424 { "http://www.foo.com/dont-open.html", 507 }
425 "text/html", 508
426 false, 509 // Do the results of an OnDownloadInterrupted get passed through properly
427 false, 510 // to the DownloadItem? This test tests persisted downloads.
428 false, }, 511 TEST_F(DownloadManagerTest, OnDownloadInterrupted_Persisted) {
429 { "http://www.foo.com/save-as.html", 512 // Put a mock we have a handle to on the download manager.
430 "text/html", 513 content::MockDownloadItem& item(AddItemToManager());
431 true, 514 int download_id = item.GetId();
432 false, 515 int64 db_handle = 0x7;
433 true, }, 516 AddItemToHistory(item, db_handle);
434 { "http://www.foo.com/always-prompt.html", 517
435 "text/html", 518 int64 size = 0xdeadbeef;
436 false, 519 const std::string hash_state("Undead beef");
437 true, 520 content::DownloadInterruptReason reason(
438 true, }, 521 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED);
439 { "http://www.foo.com/user-script-text-html-mimetype.user.js", 522
440 "text/html", 523 EXPECT_CALL(item, Interrupted(size, hash_state, reason));
441 false, 524 EXPECT_CALL(item, OffThreadCancel(&GetMockDownloadFileManager()));
442 false, 525 EXPECT_CALL(item, IsPersisted())
443 false, }, 526 .WillOnce(Return(true));
444 { "http://www.foo.com/extensionless-extension", 527 EXPECT_CALL(GetMockDownloadManagerDelegate(),
445 "application/x-chrome-extension", 528 UpdateItemInPersistentStore(&item));
446 true, 529 download_manager_->OnDownloadInterrupted(
447 false, 530 download_id, size, hash_state, reason);
448 true, }, 531 EXPECT_EQ(NULL, GetActiveDownloadItem(download_id));
449 { "http://www.foo.com/save-as.pdf", 532
450 "application/pdf", 533 // Remove so we don't get errors on shutdown.
451 true, 534 EXPECT_CALL(GetMockDownloadManagerDelegate(),
452 false, 535 RemoveItemFromPersistentStore(&item));
453 true, }, 536 download_manager_->DownloadRemoved(&item);
454 { "http://www.foo.com/sometimes_prompt.pdf", 537 RemoveMockDownloadItem(download_id);
455 "application/pdf", 538 }
456 false, 539
457 true, 540 // Does DownloadCancelled remove Download from appropriate queues?
458 false, }, 541 // This test tests non-persisted downloads.
459 { "http://www.foo.com/always_prompt.jar", 542 TEST_F(DownloadManagerTest, OnDownloadCancelled_NonPersisted) {
460 "application/jar", 543 // Put a mock we have a handle to on the download manager.
461 false, 544 content::MockDownloadItem& item(AddItemToManager());
462 true, 545
463 true, }, 546 EXPECT_CALL(item, IsPersisted())
464 }; 547 .WillRepeatedly(Return(false));
465 548 EXPECT_CALL(item, GetState())
466 // This is an observer that records what download IDs have opened a select 549 .WillRepeatedly(Return(DownloadItem::CANCELLED));
467 // file dialog. 550 EXPECT_CALL(item, GetDbHandle())
468 class SelectFileObserver : public DownloadManager::Observer { 551 .WillRepeatedly(Return(DownloadItem::kUninitializedHandle));
469 public: 552
470 explicit SelectFileObserver(DownloadManager* download_manager) 553 EXPECT_CALL(item, OffThreadCancel(&GetMockDownloadFileManager()));
471 : download_manager_(download_manager) { 554 download_manager_->DownloadCancelled(&item);
472 DCHECK(download_manager_.get()); 555 // TODO(rdsmith): Confirm that the download item is no longer on the
473 download_manager_->AddObserver(this); 556 // active list by calling GetActiveDownloadItem(id). Currently, the
474 } 557 // item is left on the active list for rendez-vous with the history
475 558 // system :-{.
476 ~SelectFileObserver() { 559 }
477 download_manager_->RemoveObserver(this); 560
478 } 561 // Does DownloadCancelled remove Download from appropriate queues?
479 562 // This test tests persisted downloads.
480 // Downloadmanager::Observer functions. 563 TEST_F(DownloadManagerTest, OnDownloadCancelled_Persisted) {
481 virtual void ModelChanged(DownloadManager* manager) OVERRIDE {} 564 // Put a mock we have a handle to on the download manager.
482 virtual void ManagerGoingDown(DownloadManager* manager) OVERRIDE {} 565 content::MockDownloadItem& item(AddItemToManager());
483 virtual void SelectFileDialogDisplayed( 566 int download_id = item.GetId();
484 DownloadManager* manager, int32 id) OVERRIDE { 567 int64 db_handle = 0x7;
485 file_dialog_ids_.insert(id); 568 AddItemToHistory(item, db_handle);
486 } 569
487 570 EXPECT_CALL(item, IsPersisted())
488 bool ShowedFileDialogForId(int32 id) { 571 .WillRepeatedly(Return(true));
489 return file_dialog_ids_.find(id) != file_dialog_ids_.end(); 572 EXPECT_CALL(GetMockDownloadManagerDelegate(),
490 } 573 UpdateItemInPersistentStore(&item));
491 574 EXPECT_CALL(item, GetState())
492 private: 575 .WillRepeatedly(Return(DownloadItem::CANCELLED));
493 std::set<int32> file_dialog_ids_; 576 EXPECT_CALL(item, GetDbHandle())
494 scoped_refptr<DownloadManager> download_manager_; 577 .WillRepeatedly(Return(db_handle));
495 }; 578
496 579 EXPECT_CALL(item, OffThreadCancel(&GetMockDownloadFileManager()));
497 // This observer tracks the progress of |DownloadItem|s. 580 download_manager_->DownloadCancelled(&item);
498 class ItemObserver : public DownloadItem::Observer { 581 EXPECT_EQ(NULL, GetActiveDownloadItem(download_id));
499 public: 582 }
500 explicit ItemObserver(DownloadItem* tracked)
501 : tracked_(tracked), states_hit_(0),
502 was_updated_(false), was_opened_(false) {
503 DCHECK(tracked_);
504 tracked_->AddObserver(this);
505 // Record the initial state.
506 OnDownloadUpdated(tracked_);
507 }
508 ~ItemObserver() {
509 tracked_->RemoveObserver(this);
510 }
511
512 bool hit_state(int state) const {
513 return (1 << state) & states_hit_;
514 }
515 bool was_updated() const { return was_updated_; }
516 bool was_opened() const { return was_opened_; }
517
518 private:
519 // DownloadItem::Observer methods
520 virtual void OnDownloadUpdated(DownloadItem* download) OVERRIDE {
521 DCHECK_EQ(tracked_, download);
522 states_hit_ |= (1 << download->GetState());
523 was_updated_ = true;
524 }
525 virtual void OnDownloadOpened(DownloadItem* download) OVERRIDE{
526 DCHECK_EQ(tracked_, download);
527 states_hit_ |= (1 << download->GetState());
528 was_opened_ = true;
529 }
530
531 DownloadItem* tracked_;
532 int states_hit_;
533 bool was_updated_;
534 bool was_opened_;
535 };
536
537 } // namespace
538
539 TEST_F(DownloadManagerTest, MAYBE_StartDownload) {
540 content::TestBrowserThread io_thread(BrowserThread::IO, &message_loop_);
541 ASSERT_TRUE(CreateTempDownloadsDirectory());
542 for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kStartDownloadCases); ++i) {
543 DVLOG(1) << "Test case " << i;
544 download_manager_delegate_->set_prompt_user_for_save_location(
545 kStartDownloadCases[i].prompt_for_download);
546
547 SelectFileObserver observer(download_manager_);
548 // Normally, the download system takes ownership of info, and is
549 // responsible for deleting it. In these unit tests, however, we
550 // don't call the function that deletes it, so we do so ourselves.
551 scoped_ptr<DownloadCreateInfo> info(new DownloadCreateInfo);
552 info->prompt_user_for_save_location = kStartDownloadCases[i].save_as;
553 info->url_chain.push_back(GURL(kStartDownloadCases[i].url));
554 info->mime_type = kStartDownloadCases[i].mime_type;
555 download_manager_->CreateDownloadItem(info.get(), DownloadRequestHandle());
556
557 scoped_ptr<content::ByteStreamWriter> stream_writer;
558 scoped_ptr<content::ByteStreamReader> stream_reader;
559 content::CreateByteStream(message_loop_.message_loop_proxy(),
560 message_loop_.message_loop_proxy(),
561 kTestDataLen, &stream_writer, &stream_reader);
562
563 DownloadFile* download_file(
564 new DownloadFileImpl(info.get(),
565 stream_reader.Pass(),
566 new DownloadRequestHandle(),
567 download_manager_, false,
568 scoped_ptr<PowerSaveBlocker>(NULL).Pass(),
569 net::BoundNetLog()));
570 AddDownloadToFileManager(info->download_id, download_file);
571 download_file->Initialize();
572 download_manager_->StartDownload(info->download_id.local());
573 message_loop_.RunAllPending();
574
575 // SelectFileObserver will have recorded any attempt to open the
576 // select file dialog.
577 // Note that DownloadManager::FileSelectionCanceled() is never called.
578 EXPECT_EQ(kStartDownloadCases[i].expected_save_as,
579 observer.ShowedFileDialogForId(info->download_id.local()));
580
581 file_manager()->CancelDownload(info->download_id);
582 }
583 }
584
585 namespace {
586
587 enum OverwriteDownloadPath {
588 DONT_OVERWRITE,
589 OVERWRITE
590 };
591
592 enum ResponseCompletionTime {
593 COMPLETES_BEFORE_RENAME,
594 COMPLETES_AFTER_RENAME
595 };
596
597 // Test cases to be used with DownloadFilenameTest. The paths are relative to
598 // the temporary downloads directory used for testing.
599 const struct DownloadFilenameTestCase {
600 // DownloadItem properties prior to calling RestartDownload().
601 const FilePath::CharType* target_path;
602 DownloadItem::TargetDisposition target_disposition;
603
604 // If we receive a ChooseDownloadPath() call to prompt the user for a download
605 // location, |expected_prompt_path| is the expected prompt path. The
606 // TestDownloadManagerDelegate will respond with |chosen_path|. If
607 // |chosen_path| is empty, then the file choose dialog be cancelled.
608 const FilePath::CharType* expected_prompt_path;
609 const FilePath::CharType* chosen_path;
610
611 // Response to GetIntermediatePath(). If |intermediate_path| is empty, then a
612 // temporary path is constructed with
613 // GetTempDownloadPath(item->GetTargetFilePath()).
614 const FilePath::CharType* intermediate_path;
615 OverwriteDownloadPath overwrite_intermediate_path;
616
617 // Determines when OnResponseCompleted() is called. If this is
618 // COMPLETES_BEFORE_RENAME, then the response completes before the filename is
619 // determines.
620 ResponseCompletionTime completion;
621
622 // The expected intermediate path for the download.
623 const FilePath::CharType* expected_intermediate_path;
624
625 // The expected final path for the download.
626 const FilePath::CharType* expected_final_path;
627 } kDownloadFilenameTestCases[] = {
628
629 #define TARGET FILE_PATH_LITERAL
630 #define INTERMEDIATE FILE_PATH_LITERAL
631 #define EXPECTED_PROMPT FILE_PATH_LITERAL
632 #define PROMPT_RESPONSE FILE_PATH_LITERAL
633 #define EXPECTED_INTERMEDIATE FILE_PATH_LITERAL
634 #define EXPECTED_FINAL FILE_PATH_LITERAL
635
636 {
637 // 0: No prompting.
638 TARGET("foo.txt"),
639 DownloadItem::TARGET_DISPOSITION_OVERWRITE,
640
641 EXPECTED_PROMPT(""),
642 PROMPT_RESPONSE(""),
643
644 INTERMEDIATE("foo.txt.intermediate"),
645 OVERWRITE,
646
647 COMPLETES_AFTER_RENAME,
648 EXPECTED_INTERMEDIATE("foo.txt.intermediate"),
649 EXPECTED_FINAL("foo.txt"),
650 },
651 {
652 // 1: With prompting. No rename.
653 TARGET("foo.txt"),
654 DownloadItem::TARGET_DISPOSITION_OVERWRITE,
655
656 EXPECTED_PROMPT("foo.txt"),
657 PROMPT_RESPONSE("foo.txt"),
658
659 INTERMEDIATE("foo.txt.intermediate"),
660 OVERWRITE,
661
662 COMPLETES_AFTER_RENAME,
663 EXPECTED_INTERMEDIATE("foo.txt.intermediate"),
664 EXPECTED_FINAL("foo.txt"),
665 },
666 {
667 // 2: With prompting. Download is renamed.
668 TARGET("foo.txt"),
669 DownloadItem::TARGET_DISPOSITION_PROMPT,
670
671 EXPECTED_PROMPT("foo.txt"),
672 PROMPT_RESPONSE("bar.txt"),
673
674 INTERMEDIATE("bar.txt.intermediate"),
675 OVERWRITE,
676
677 COMPLETES_AFTER_RENAME,
678 EXPECTED_INTERMEDIATE("bar.txt.intermediate"),
679 EXPECTED_FINAL("bar.txt"),
680 },
681 {
682 // 3: With prompting. Download path is changed.
683 TARGET("foo.txt"),
684 DownloadItem::TARGET_DISPOSITION_PROMPT,
685
686 EXPECTED_PROMPT("foo.txt"),
687 PROMPT_RESPONSE("Foo/bar.txt"),
688
689 INTERMEDIATE("Foo/bar.txt.intermediate"),
690 OVERWRITE,
691
692 COMPLETES_AFTER_RENAME,
693 EXPECTED_INTERMEDIATE("Foo/bar.txt.intermediate"),
694 EXPECTED_FINAL("Foo/bar.txt"),
695 },
696 {
697 // 4: No prompting. Intermediate path exists. Doesn't overwrite
698 // intermediate path.
699 TARGET("exists.png"),
700 DownloadItem::TARGET_DISPOSITION_OVERWRITE,
701
702 EXPECTED_PROMPT(""),
703 PROMPT_RESPONSE(""),
704
705 INTERMEDIATE("exists.png.temp"),
706 DONT_OVERWRITE,
707
708 COMPLETES_AFTER_RENAME,
709 EXPECTED_INTERMEDIATE("exists.png (1).temp"),
710 EXPECTED_FINAL("exists.png"),
711 },
712 {
713 // 5: No prompting. Intermediate path exists. Overwrites.
714 TARGET("exists.png"),
715 DownloadItem::TARGET_DISPOSITION_OVERWRITE,
716
717 EXPECTED_PROMPT(""),
718 PROMPT_RESPONSE(""),
719
720 INTERMEDIATE("exists.png.temp"),
721 OVERWRITE,
722
723 COMPLETES_AFTER_RENAME,
724 EXPECTED_INTERMEDIATE("exists.png.temp"),
725 EXPECTED_FINAL("exists.png"),
726 },
727 {
728 // 6: No prompting. Final path exists. Doesn't overwrite.
729 TARGET("exists.txt"),
730 DownloadItem::TARGET_DISPOSITION_UNIQUIFY,
731
732 EXPECTED_PROMPT(""),
733 PROMPT_RESPONSE(""),
734
735 INTERMEDIATE("exists.txt.temp"),
736 OVERWRITE,
737
738 COMPLETES_AFTER_RENAME,
739 EXPECTED_INTERMEDIATE("exists.txt.temp"),
740 EXPECTED_FINAL("exists (1).txt"),
741 },
742 {
743 // 7: No prompting. Final path exists. Overwrites.
744 TARGET("exists.txt"),
745 DownloadItem::TARGET_DISPOSITION_OVERWRITE,
746
747 EXPECTED_PROMPT(""),
748 PROMPT_RESPONSE(""),
749
750 INTERMEDIATE("exists.txt.temp"),
751 OVERWRITE,
752
753 COMPLETES_AFTER_RENAME,
754 EXPECTED_INTERMEDIATE("exists.txt.temp"),
755 EXPECTED_FINAL("exists.txt"),
756 },
757 {
758 // 8: No prompting. Response completes before filename determination.
759 TARGET("foo.txt"),
760 DownloadItem::TARGET_DISPOSITION_OVERWRITE,
761
762 EXPECTED_PROMPT(""),
763 PROMPT_RESPONSE(""),
764
765 INTERMEDIATE("foo.txt.intermediate"),
766 OVERWRITE,
767
768 COMPLETES_BEFORE_RENAME,
769 EXPECTED_INTERMEDIATE("foo.txt.intermediate"),
770 EXPECTED_FINAL("foo.txt"),
771 },
772 {
773 // 9: With prompting. Download path is changed. Response completes before
774 // filename determination.
775 TARGET("foo.txt"),
776 DownloadItem::TARGET_DISPOSITION_PROMPT,
777
778 EXPECTED_PROMPT("foo.txt"),
779 PROMPT_RESPONSE("Foo/bar.txt"),
780
781 INTERMEDIATE("Foo/bar.txt.intermediate"),
782 OVERWRITE,
783
784 COMPLETES_BEFORE_RENAME,
785 EXPECTED_INTERMEDIATE("Foo/bar.txt.intermediate"),
786 EXPECTED_FINAL("Foo/bar.txt"),
787 },
788
789 #undef TARGET
790 #undef INTERMEDIATE
791 #undef EXPECTED_PROMPT
792 #undef PROMPT_RESPONSE
793 #undef EXPECTED_INTERMEDIATE
794 #undef EXPECTED_FINAL
795 };
796
797 } // namespace
798
799 TEST_F(DownloadManagerTest, DownloadFilenameTest) {
800 ASSERT_TRUE(CreateTempDownloadsDirectory());
801
802 // We create a known file to test file uniquification.
803 ASSERT_TRUE(file_util::WriteFile(
804 GetPathInDownloadsDir(FILE_PATH_LITERAL("exists.txt")), "", 0) == 0);
805 ASSERT_TRUE(file_util::WriteFile(
806 GetPathInDownloadsDir(FILE_PATH_LITERAL("exists.png.temp")), "", 0) == 0);
807
808 for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kDownloadFilenameTestCases); ++i) {
809 const DownloadFilenameTestCase& test_case = kDownloadFilenameTestCases[i];
810 scoped_ptr<DownloadCreateInfo> info(new DownloadCreateInfo);
811
812 SCOPED_TRACE(testing::Message() << "Running test case " << i);
813 info->url_chain.push_back(GURL());
814
815 MockDownloadFile* download_file(
816 new ::testing::StrictMock<MockDownloadFile>());
817 FilePath target_path = GetPathInDownloadsDir(test_case.target_path);
818 FilePath expected_prompt_path =
819 GetPathInDownloadsDir(test_case.expected_prompt_path);
820 FilePath chosen_path = GetPathInDownloadsDir(test_case.chosen_path);
821 FilePath intermediate_path =
822 GetPathInDownloadsDir(test_case.intermediate_path);
823 FilePath expected_intermediate_path =
824 GetPathInDownloadsDir(test_case.expected_intermediate_path);
825 FilePath expected_final_path =
826 GetPathInDownloadsDir(test_case.expected_final_path);
827
828 EXPECT_CALL(*download_file, Rename(expected_intermediate_path))
829 .WillOnce(Return(net::OK));
830 EXPECT_CALL(*download_file, Rename(expected_final_path))
831 .WillOnce(Return(net::OK));
832 #if defined(OS_MACOSX)
833 EXPECT_CALL(*download_file, AnnotateWithSourceInformation());
834 #endif
835 EXPECT_CALL(*download_file, Detach());
836
837 download_manager_->CreateDownloadItem(info.get(), DownloadRequestHandle());
838 AddMockDownloadToFileManager(info->download_id, download_file);
839 DownloadItem* download = GetActiveDownloadItem(info->download_id);
840 ASSERT_TRUE(download != NULL);
841
842 if (test_case.completion == COMPLETES_BEFORE_RENAME)
843 OnResponseCompleted(info->download_id, 1024, std::string("fake_hash"));
844
845 download->OnTargetPathDetermined(
846 target_path, test_case.target_disposition,
847 content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS);
848 download_manager_delegate_->SetFileSelectionExpectation(
849 expected_prompt_path, chosen_path);
850 download_manager_delegate_->SetIntermediatePath(
851 intermediate_path, test_case.overwrite_intermediate_path);
852 download_manager_delegate_->SetShouldCompleteDownload(false);
853 download_manager_->RestartDownload(info->download_id.local());
854 message_loop_.RunAllPending();
855
856 if (test_case.completion == COMPLETES_AFTER_RENAME) {
857 OnResponseCompleted(info->download_id, 1024, std::string("fake_hash"));
858 message_loop_.RunAllPending();
859 }
860
861 EXPECT_EQ(expected_intermediate_path.value(),
862 download->GetFullPath().value());
863 download_manager_delegate_->SetShouldCompleteDownload(true);
864 download_manager_delegate_->InvokeDownloadCompletionCallback();
865 message_loop_.RunAllPending();
866 EXPECT_EQ(expected_final_path.value(),
867 download->GetTargetFilePath().value());
868 }
869 }
870
871 void WriteCopyToStream(const char *source,
872 size_t len, content::ByteStreamWriter* stream) {
873 scoped_refptr<net::IOBuffer> copy(new net::IOBuffer(len));
874 memcpy(copy.get()->data(), source, len);
875 stream->Write(copy, len);
876 }
877
878 TEST_F(DownloadManagerTest, DownloadInterruptTest) {
879 using ::testing::_;
880 using ::testing::CreateFunctor;
881 using ::testing::Invoke;
882 using ::testing::Return;
883
884 // Normally, the download system takes ownership of info, and is
885 // responsible for deleting it. In these unit tests, however, we
886 // don't call the function that deletes it, so we do so ourselves.
887 scoped_ptr<DownloadCreateInfo> info(new DownloadCreateInfo);
888 info->prompt_user_for_save_location = false;
889 info->url_chain.push_back(GURL());
890 info->total_bytes = static_cast<int64>(kTestDataLen);
891 const FilePath new_path(FILE_PATH_LITERAL("foo.zip"));
892 const FilePath cr_path(GetTempDownloadPath(new_path));
893
894 MockDownloadFile* download_file(new NiceMock<MockDownloadFile>());
895
896 EXPECT_CALL(*download_file, Rename(cr_path))
897 .WillOnce(Return(net::OK));
898 EXPECT_CALL(*download_file, Cancel());
899
900 download_manager_->CreateDownloadItem(info.get(), DownloadRequestHandle());
901 // |download_file| is owned by DownloadFileManager.
902 AddMockDownloadToFileManager(info->download_id, download_file);
903
904 DownloadItem* download = GetActiveDownloadItem(info->download_id);
905 ASSERT_TRUE(download != NULL);
906 EXPECT_EQ(DownloadItem::IN_PROGRESS, download->GetState());
907 scoped_ptr<ItemObserver> observer(new ItemObserver(download));
908
909 ContinueDownloadWithPath(download, new_path);
910 message_loop_.RunAllPending();
911 EXPECT_TRUE(GetActiveDownloadItem(info->download_id) != NULL);
912
913 int64 error_size = 3;
914 OnDownloadInterrupted(info->download_id, error_size, "",
915 content::DOWNLOAD_INTERRUPT_REASON_FILE_ACCESS_DENIED);
916 message_loop_.RunAllPending();
917
918 EXPECT_TRUE(GetActiveDownloadItem(info->download_id) == NULL);
919 EXPECT_TRUE(observer->hit_state(DownloadItem::IN_PROGRESS));
920 EXPECT_TRUE(observer->hit_state(DownloadItem::INTERRUPTED));
921 EXPECT_FALSE(observer->hit_state(DownloadItem::COMPLETE));
922 EXPECT_FALSE(observer->hit_state(DownloadItem::CANCELLED));
923 EXPECT_FALSE(observer->hit_state(DownloadItem::REMOVING));
924 EXPECT_TRUE(observer->was_updated());
925 EXPECT_FALSE(observer->was_opened());
926 EXPECT_FALSE(download->GetFileExternallyRemoved());
927 EXPECT_EQ(DownloadItem::INTERRUPTED, download->GetState());
928
929 download->Cancel(true);
930
931 EXPECT_TRUE(observer->hit_state(DownloadItem::IN_PROGRESS));
932 EXPECT_TRUE(observer->hit_state(DownloadItem::INTERRUPTED));
933 EXPECT_FALSE(observer->hit_state(DownloadItem::COMPLETE));
934 EXPECT_FALSE(observer->hit_state(DownloadItem::CANCELLED));
935 EXPECT_FALSE(observer->hit_state(DownloadItem::REMOVING));
936 EXPECT_TRUE(observer->was_updated());
937 EXPECT_FALSE(observer->was_opened());
938 EXPECT_FALSE(download->GetFileExternallyRemoved());
939 EXPECT_EQ(DownloadItem::INTERRUPTED, download->GetState());
940 EXPECT_EQ(download->GetReceivedBytes(), error_size);
941 EXPECT_EQ(download->GetTotalBytes(), static_cast<int64>(kTestDataLen));
942 }
943
944 // Test the behavior of DownloadFileManager and DownloadManager in the event
945 // of a file error while writing the download to disk.
946 TEST_F(DownloadManagerTest, MAYBE_DownloadFileErrorTest) {
947 // Create a temporary file and a mock stream.
948 FilePath path;
949 ASSERT_TRUE(file_util::CreateTemporaryFile(&path));
950
951 // This file stream will be used, until the first rename occurs.
952 net::FileStream* stream = new net::FileStream(NULL);
953 ASSERT_EQ(0, stream->OpenSync(
954 path,
955 base::PLATFORM_FILE_OPEN_ALWAYS | base::PLATFORM_FILE_WRITE));
956
957 // Make sure the DFM exists; we'll need it later.
958 // TODO(rdsmith): This is ugly and should be rewritten, but a large
959 // rewrite of this test is in progress in a different CL, so doing it
960 // the hacky way for now.
961 (void) file_manager();
962
963 // Normally, the download system takes ownership of info, and is
964 // responsible for deleting it. In these unit tests, however, we
965 // don't call the function that deletes it, so we do so ourselves.
966 scoped_ptr<DownloadCreateInfo> info(new DownloadCreateInfo);
967 info->prompt_user_for_save_location = false;
968 info->url_chain.push_back(GURL());
969 info->total_bytes = static_cast<int64>(kTestDataLen * 3);
970 info->save_info.file_path = path;
971 info->save_info.file_stream.reset(stream);
972 scoped_ptr<content::ByteStreamWriter> stream_input;
973 scoped_ptr<content::ByteStreamReader> stream_output;
974 content::CreateByteStream(message_loop_.message_loop_proxy(),
975 message_loop_.message_loop_proxy(),
976 kTestDataLen, &stream_input, &stream_output);
977
978 download_manager_->CreateDownloadItem(info.get(), DownloadRequestHandle());
979
980 // Create a download file that we can insert errors into.
981 scoped_ptr<DownloadFileWithErrors> download_file(new DownloadFileWithErrors(
982 info.get(), stream_output.Pass(), download_manager_, false));
983 download_file->Initialize();
984
985 DownloadItem* download = GetActiveDownloadItem(info->download_id);
986 ASSERT_TRUE(download != NULL);
987
988 EXPECT_EQ(DownloadItem::IN_PROGRESS, download->GetState());
989 scoped_ptr<ItemObserver> observer(new ItemObserver(download));
990
991 // Add some data before finalizing the file name.
992 WriteCopyToStream(kTestData, kTestDataLen, stream_input.get());
993
994 // Finalize the file name.
995 ContinueDownloadWithPath(download, path);
996 message_loop_.RunAllPending();
997 EXPECT_TRUE(GetActiveDownloadItem(info->download_id) != NULL);
998
999 // Add more data.
1000 WriteCopyToStream(kTestData, kTestDataLen, stream_input.get());
1001
1002 // Add more data, but an error occurs.
1003 download_file->set_forced_error(net::ERR_FAILED);
1004 WriteCopyToStream(kTestData, kTestDataLen, stream_input.get());
1005 message_loop_.RunAllPending();
1006
1007 // Check the state. The download should have been interrupted.
1008 EXPECT_TRUE(GetActiveDownloadItem(info->download_id) == NULL);
1009 EXPECT_TRUE(observer->hit_state(DownloadItem::IN_PROGRESS));
1010 EXPECT_TRUE(observer->hit_state(DownloadItem::INTERRUPTED));
1011 EXPECT_FALSE(observer->hit_state(DownloadItem::COMPLETE));
1012 EXPECT_FALSE(observer->hit_state(DownloadItem::CANCELLED));
1013 EXPECT_FALSE(observer->hit_state(DownloadItem::REMOVING));
1014 EXPECT_TRUE(observer->was_updated());
1015 EXPECT_FALSE(observer->was_opened());
1016 EXPECT_FALSE(download->GetFileExternallyRemoved());
1017 EXPECT_EQ(DownloadItem::INTERRUPTED, download->GetState());
1018
1019 // Clean up.
1020 download->Cancel(true);
1021 message_loop_.RunAllPending();
1022 }
1023
1024 TEST_F(DownloadManagerTest, DownloadCancelTest) {
1025 using ::testing::_;
1026 using ::testing::CreateFunctor;
1027 using ::testing::Invoke;
1028 using ::testing::Return;
1029
1030 // Normally, the download system takes ownership of info, and is
1031 // responsible for deleting it. In these unit tests, however, we
1032 // don't call the function that deletes it, so we do so ourselves.
1033 scoped_ptr<DownloadCreateInfo> info(new DownloadCreateInfo);
1034 info->prompt_user_for_save_location = false;
1035 info->url_chain.push_back(GURL());
1036 const FilePath new_path(FILE_PATH_LITERAL("foo.zip"));
1037 const FilePath cr_path(GetTempDownloadPath(new_path));
1038
1039 MockDownloadFile* download_file(new NiceMock<MockDownloadFile>());
1040
1041 // |download_file| is owned by DownloadFileManager.
1042 EXPECT_CALL(*download_file, Rename(cr_path))
1043 .WillOnce(Return(net::OK));
1044 EXPECT_CALL(*download_file, Cancel());
1045
1046 download_manager_->CreateDownloadItem(info.get(), DownloadRequestHandle());
1047 AddMockDownloadToFileManager(info->download_id, download_file);
1048
1049 DownloadItem* download = GetActiveDownloadItem(info->download_id);
1050 ASSERT_TRUE(download != NULL);
1051
1052 EXPECT_EQ(DownloadItem::IN_PROGRESS, download->GetState());
1053 scoped_ptr<ItemObserver> observer(new ItemObserver(download));
1054
1055 ContinueDownloadWithPath(download, new_path);
1056 message_loop_.RunAllPending();
1057 EXPECT_TRUE(GetActiveDownloadItem(info->download_id) != NULL);
1058
1059 download->Cancel(false);
1060 message_loop_.RunAllPending();
1061
1062 EXPECT_TRUE(GetActiveDownloadItem(info->download_id) != NULL);
1063 EXPECT_TRUE(observer->hit_state(DownloadItem::IN_PROGRESS));
1064 EXPECT_TRUE(observer->hit_state(DownloadItem::CANCELLED));
1065 EXPECT_FALSE(observer->hit_state(DownloadItem::INTERRUPTED));
1066 EXPECT_FALSE(observer->hit_state(DownloadItem::COMPLETE));
1067 EXPECT_FALSE(observer->hit_state(DownloadItem::REMOVING));
1068 EXPECT_TRUE(observer->was_updated());
1069 EXPECT_FALSE(observer->was_opened());
1070 EXPECT_FALSE(download->GetFileExternallyRemoved());
1071 EXPECT_EQ(DownloadItem::CANCELLED, download->GetState());
1072
1073 file_manager()->CancelDownload(info->download_id);
1074
1075 EXPECT_FALSE(file_util::PathExists(new_path));
1076 EXPECT_FALSE(file_util::PathExists(cr_path));
1077 }
1078
1079 TEST_F(DownloadManagerTest, MAYBE_DownloadOverwriteTest) {
1080 using ::testing::_;
1081 using ::testing::CreateFunctor;
1082 using ::testing::Invoke;
1083 using ::testing::Return;
1084
1085 ASSERT_TRUE(CreateTempDownloadsDirectory());
1086 // File names we're using.
1087 const FilePath new_path(GetPathInDownloadsDir(FILE_PATH_LITERAL("foo.txt")));
1088 const FilePath cr_path(GetTempDownloadPath(new_path));
1089 EXPECT_FALSE(file_util::PathExists(new_path));
1090
1091 // Create the file that we will overwrite. Will be automatically cleaned
1092 // up when temp_dir_ is destroyed.
1093 FILE* fp = file_util::OpenFile(new_path, "w");
1094 file_util::CloseFile(fp);
1095 EXPECT_TRUE(file_util::PathExists(new_path));
1096
1097 // Construct the unique file name that normally would be created, but
1098 // which we will override.
1099 int uniquifier =
1100 file_util::GetUniquePathNumber(new_path, FILE_PATH_LITERAL(""));
1101 FilePath unique_new_path = new_path;
1102 EXPECT_NE(0, uniquifier);
1103 unique_new_path = unique_new_path.InsertBeforeExtensionASCII(
1104 StringPrintf(" (%d)", uniquifier));
1105
1106 // Normally, the download system takes ownership of info, and is
1107 // responsible for deleting it. In these unit tests, however, we
1108 // don't call the function that deletes it, so we do so ourselves.
1109 scoped_ptr<DownloadCreateInfo> info(new DownloadCreateInfo);
1110 info->prompt_user_for_save_location = true;
1111 info->url_chain.push_back(GURL());
1112 scoped_ptr<content::ByteStreamWriter> stream_input;
1113 scoped_ptr<content::ByteStreamReader> stream_output;
1114 content::CreateByteStream(message_loop_.message_loop_proxy(),
1115 message_loop_.message_loop_proxy(),
1116 kTestDataLen, &stream_input, &stream_output);
1117
1118 download_manager_->CreateDownloadItem(info.get(), DownloadRequestHandle());
1119
1120 DownloadItem* download = GetActiveDownloadItem(info->download_id);
1121 ASSERT_TRUE(download != NULL);
1122
1123 EXPECT_EQ(DownloadItem::IN_PROGRESS, download->GetState());
1124 scoped_ptr<ItemObserver> observer(new ItemObserver(download));
1125
1126 // Create and initialize the download file. We're bypassing the first part
1127 // of the download process and skipping to the part after the final file
1128 // name has been chosen, so we need to initialize the download file
1129 // properly.
1130 DownloadFile* download_file(
1131 new DownloadFileImpl(info.get(), stream_output.Pass(),
1132 new DownloadRequestHandle(),
1133 download_manager_, false,
1134 scoped_ptr<PowerSaveBlocker>(NULL).Pass(),
1135 net::BoundNetLog()));
1136 download_file->Rename(cr_path);
1137 // This creates the .temp version of the file.
1138 download_file->Initialize();
1139 // |download_file| is owned by DownloadFileManager.
1140 AddDownloadToFileManager(info->download_id, download_file);
1141
1142 ContinueDownloadWithPath(download, new_path);
1143 message_loop_.RunAllPending();
1144 EXPECT_TRUE(GetActiveDownloadItem(info->download_id) != NULL);
1145
1146 WriteCopyToStream(kTestData, kTestDataLen, stream_input.get());
1147
1148 // Finish the download.
1149 OnResponseCompleted(info->download_id, kTestDataLen, "");
1150 message_loop_.RunAllPending();
1151
1152 // Download is complete.
1153 EXPECT_TRUE(GetActiveDownloadItem(info->download_id) == NULL);
1154 EXPECT_TRUE(observer->hit_state(DownloadItem::IN_PROGRESS));
1155 EXPECT_FALSE(observer->hit_state(DownloadItem::CANCELLED));
1156 EXPECT_FALSE(observer->hit_state(DownloadItem::INTERRUPTED));
1157 EXPECT_TRUE(observer->hit_state(DownloadItem::COMPLETE));
1158 EXPECT_FALSE(observer->hit_state(DownloadItem::REMOVING));
1159 EXPECT_TRUE(observer->was_updated());
1160 EXPECT_FALSE(observer->was_opened());
1161 EXPECT_FALSE(download->GetFileExternallyRemoved());
1162 EXPECT_EQ(DownloadItem::COMPLETE, download->GetState());
1163
1164 EXPECT_TRUE(file_util::PathExists(new_path));
1165 EXPECT_FALSE(file_util::PathExists(cr_path));
1166 EXPECT_FALSE(file_util::PathExists(unique_new_path));
1167 std::string file_contents;
1168 EXPECT_TRUE(file_util::ReadFileToString(new_path, &file_contents));
1169 EXPECT_EQ(std::string(kTestData), file_contents);
1170 }
1171
1172 TEST_F(DownloadManagerTest, MAYBE_DownloadRemoveTest) {
1173 using ::testing::_;
1174 using ::testing::CreateFunctor;
1175 using ::testing::Invoke;
1176 using ::testing::Return;
1177
1178 ASSERT_TRUE(CreateTempDownloadsDirectory());
1179
1180 // File names we're using.
1181 const FilePath new_path(GetPathInDownloadsDir(FILE_PATH_LITERAL("foo.txt")));
1182 const FilePath cr_path(GetTempDownloadPath(new_path));
1183 EXPECT_FALSE(file_util::PathExists(new_path));
1184
1185 // Normally, the download system takes ownership of info, and is
1186 // responsible for deleting it. In these unit tests, however, we
1187 // don't call the function that deletes it, so we do so ourselves.
1188 scoped_ptr<DownloadCreateInfo> info(new DownloadCreateInfo);
1189 info->prompt_user_for_save_location = true;
1190 info->url_chain.push_back(GURL());
1191 scoped_ptr<content::ByteStreamWriter> stream_input;
1192 scoped_ptr<content::ByteStreamReader> stream_output;
1193 content::CreateByteStream(message_loop_.message_loop_proxy(),
1194 message_loop_.message_loop_proxy(),
1195 kTestDataLen, &stream_input, &stream_output);
1196
1197 download_manager_->CreateDownloadItem(info.get(), DownloadRequestHandle());
1198
1199 DownloadItem* download = GetActiveDownloadItem(info->download_id);
1200 ASSERT_TRUE(download != NULL);
1201
1202 EXPECT_EQ(DownloadItem::IN_PROGRESS, download->GetState());
1203 scoped_ptr<ItemObserver> observer(new ItemObserver(download));
1204
1205 // Create and initialize the download file. We're bypassing the first part
1206 // of the download process and skipping to the part after the final file
1207 // name has been chosen, so we need to initialize the download file
1208 // properly.
1209 DownloadFile* download_file(
1210 new DownloadFileImpl(info.get(), stream_output.Pass(),
1211 new DownloadRequestHandle(),
1212 download_manager_, false,
1213 scoped_ptr<PowerSaveBlocker>(NULL).Pass(),
1214 net::BoundNetLog()));
1215 download_file->Rename(cr_path);
1216 // This creates the .temp version of the file.
1217 download_file->Initialize();
1218 // |download_file| is owned by DownloadFileManager.
1219 AddDownloadToFileManager(info->download_id, download_file);
1220
1221 ContinueDownloadWithPath(download, new_path);
1222 message_loop_.RunAllPending();
1223 EXPECT_TRUE(GetActiveDownloadItem(info->download_id) != NULL);
1224
1225 WriteCopyToStream(kTestData, kTestDataLen, stream_input.get());
1226
1227 // Finish the download.
1228 OnResponseCompleted(info->download_id, kTestDataLen, "");
1229 message_loop_.RunAllPending();
1230
1231 // Download is complete.
1232 EXPECT_TRUE(GetActiveDownloadItem(info->download_id) == NULL);
1233 EXPECT_TRUE(observer->hit_state(DownloadItem::IN_PROGRESS));
1234 EXPECT_FALSE(observer->hit_state(DownloadItem::CANCELLED));
1235 EXPECT_FALSE(observer->hit_state(DownloadItem::INTERRUPTED));
1236 EXPECT_TRUE(observer->hit_state(DownloadItem::COMPLETE));
1237 EXPECT_FALSE(observer->hit_state(DownloadItem::REMOVING));
1238 EXPECT_TRUE(observer->was_updated());
1239 EXPECT_FALSE(observer->was_opened());
1240 EXPECT_FALSE(download->GetFileExternallyRemoved());
1241 EXPECT_EQ(DownloadItem::COMPLETE, download->GetState());
1242
1243 EXPECT_TRUE(file_util::PathExists(new_path));
1244 EXPECT_FALSE(file_util::PathExists(cr_path));
1245
1246 // Remove the downloaded file.
1247 ASSERT_TRUE(file_util::Delete(new_path, false));
1248 download->OnDownloadedFileRemoved();
1249 message_loop_.RunAllPending();
1250
1251 EXPECT_TRUE(GetActiveDownloadItem(info->download_id) == NULL);
1252 EXPECT_TRUE(observer->hit_state(DownloadItem::IN_PROGRESS));
1253 EXPECT_FALSE(observer->hit_state(DownloadItem::CANCELLED));
1254 EXPECT_FALSE(observer->hit_state(DownloadItem::INTERRUPTED));
1255 EXPECT_TRUE(observer->hit_state(DownloadItem::COMPLETE));
1256 EXPECT_FALSE(observer->hit_state(DownloadItem::REMOVING));
1257 EXPECT_TRUE(observer->was_updated());
1258 EXPECT_FALSE(observer->was_opened());
1259 EXPECT_TRUE(download->GetFileExternallyRemoved());
1260 EXPECT_EQ(DownloadItem::COMPLETE, download->GetState());
1261
1262 EXPECT_FALSE(file_util::PathExists(new_path));
1263 }
OLDNEW
« no previous file with comments | « content/browser/download/download_manager_impl.cc ('k') | content/content_browser.gypi » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698