Disable view source for Developer Tools.
[chromium-blink-merge.git] / chrome / browser / download / download_browsertest.cc
blobb1edde228eac8a0c0b645c3525d73be4784d1fe7
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include <sstream>
7 #include "base/bind.h"
8 #include "base/bind_helpers.h"
9 #include "base/command_line.h"
10 #include "base/file_util.h"
11 #include "base/files/file_path.h"
12 #include "base/files/scoped_temp_dir.h"
13 #include "base/memory/ref_counted.h"
14 #include "base/path_service.h"
15 #include "base/prefs/pref_service.h"
16 #include "base/stl_util.h"
17 #include "base/strings/string_split.h"
18 #include "base/strings/string_util.h"
19 #include "base/strings/stringprintf.h"
20 #include "base/strings/utf_string_conversions.h"
21 #include "base/sys_info.h"
22 #include "base/test/test_file_util.h"
23 #include "chrome/app/chrome_command_ids.h"
24 #include "chrome/browser/browser_process.h"
25 #include "chrome/browser/chrome_notification_types.h"
26 #include "chrome/browser/common/cancelable_request.h"
27 #include "chrome/browser/download/chrome_download_manager_delegate.h"
28 #include "chrome/browser/download/download_browsertest.h"
29 #include "chrome/browser/download/download_crx_util.h"
30 #include "chrome/browser/download/download_history.h"
31 #include "chrome/browser/download/download_item_model.h"
32 #include "chrome/browser/download/download_prefs.h"
33 #include "chrome/browser/download/download_request_limiter.h"
34 #include "chrome/browser/download/download_service.h"
35 #include "chrome/browser/download/download_service_factory.h"
36 #include "chrome/browser/download/download_shelf.h"
37 #include "chrome/browser/download/download_target_determiner.h"
38 #include "chrome/browser/download/download_test_file_activity_observer.h"
39 #include "chrome/browser/extensions/extension_install_prompt.h"
40 #include "chrome/browser/extensions/extension_service.h"
41 #include "chrome/browser/extensions/extension_system.h"
42 #include "chrome/browser/history/download_row.h"
43 #include "chrome/browser/history/history_service.h"
44 #include "chrome/browser/history/history_service_factory.h"
45 #include "chrome/browser/infobars/confirm_infobar_delegate.h"
46 #include "chrome/browser/infobars/infobar.h"
47 #include "chrome/browser/infobars/infobar_service.h"
48 #include "chrome/browser/net/url_request_mock_util.h"
49 #include "chrome/browser/profiles/profile.h"
50 #include "chrome/browser/tab_contents/render_view_context_menu.h"
51 #include "chrome/browser/ui/browser.h"
52 #include "chrome/browser/ui/browser_commands.h"
53 #include "chrome/browser/ui/browser_finder.h"
54 #include "chrome/browser/ui/browser_list.h"
55 #include "chrome/browser/ui/browser_tabstrip.h"
56 #include "chrome/browser/ui/browser_window.h"
57 #include "chrome/browser/ui/chrome_pages.h"
58 #include "chrome/browser/ui/host_desktop.h"
59 #include "chrome/browser/ui/tabs/tab_strip_model.h"
60 #include "chrome/common/chrome_paths.h"
61 #include "chrome/common/pref_names.h"
62 #include "chrome/common/url_constants.h"
63 #include "chrome/test/base/in_process_browser_test.h"
64 #include "chrome/test/base/test_switches.h"
65 #include "chrome/test/base/ui_test_utils.h"
66 #include "content/public/browser/download_interrupt_reasons.h"
67 #include "content/public/browser/download_item.h"
68 #include "content/public/browser/download_manager.h"
69 #include "content/public/browser/download_save_info.h"
70 #include "content/public/browser/download_url_parameters.h"
71 #include "content/public/browser/notification_source.h"
72 #include "content/public/browser/render_view_host.h"
73 #include "content/public/browser/resource_context.h"
74 #include "content/public/browser/web_contents.h"
75 #include "content/public/common/content_switches.h"
76 #include "content/public/common/context_menu_params.h"
77 #include "content/public/common/page_transition_types.h"
78 #include "content/public/test/browser_test_utils.h"
79 #include "content/public/test/download_test_observer.h"
80 #include "content/public/test/test_file_error_injector.h"
81 #include "content/public/test/test_navigation_observer.h"
82 #include "content/test/net/url_request_mock_http_job.h"
83 #include "content/test/net/url_request_slow_download_job.h"
84 #include "extensions/common/feature_switch.h"
85 #include "grit/generated_resources.h"
86 #include "net/base/net_util.h"
87 #include "net/test/spawned_test_server/spawned_test_server.h"
88 #include "testing/gtest/include/gtest/gtest.h"
89 #include "ui/base/l10n/l10n_util.h"
91 using content::BrowserContext;
92 using content::BrowserThread;
93 using content::DownloadItem;
94 using content::DownloadManager;
95 using content::DownloadUrlParameters;
96 using content::URLRequestMockHTTPJob;
97 using content::URLRequestSlowDownloadJob;
98 using content::WebContents;
99 using extensions::Extension;
100 using extensions::FeatureSwitch;
102 namespace {
104 class CreatedObserver : public content::DownloadManager::Observer {
105 public:
106 explicit CreatedObserver(content::DownloadManager* manager)
107 : manager_(manager),
108 waiting_(false) {
109 manager->AddObserver(this);
111 virtual ~CreatedObserver() {
112 if (manager_)
113 manager_->RemoveObserver(this);
116 void Wait() {
117 std::vector<DownloadItem*> downloads;
118 manager_->GetAllDownloads(&downloads);
119 if (!downloads.empty())
120 return;
121 waiting_ = true;
122 content::RunMessageLoop();
123 waiting_ = false;
126 private:
127 virtual void OnDownloadCreated(content::DownloadManager* manager,
128 content::DownloadItem* item) OVERRIDE {
129 DCHECK_EQ(manager_, manager);
130 if (waiting_)
131 base::MessageLoopForUI::current()->Quit();
134 content::DownloadManager* manager_;
135 bool waiting_;
137 DISALLOW_COPY_AND_ASSIGN(CreatedObserver);
140 class PercentWaiter : public content::DownloadItem::Observer {
141 public:
142 explicit PercentWaiter(DownloadItem* item)
143 : item_(item),
144 waiting_(false),
145 error_(false),
146 prev_percent_(0) {
147 item_->AddObserver(this);
149 virtual ~PercentWaiter() {
150 if (item_)
151 item_->RemoveObserver(this);
154 bool WaitForFinished() {
155 if (item_->GetState() == DownloadItem::COMPLETE) {
156 return item_->PercentComplete() == 100;
158 waiting_ = true;
159 content::RunMessageLoop();
160 waiting_ = false;
161 return !error_;
164 private:
165 virtual void OnDownloadUpdated(content::DownloadItem* item) OVERRIDE {
166 DCHECK_EQ(item_, item);
167 if (!error_ &&
168 ((prev_percent_ > item_->PercentComplete()) ||
169 (item_->GetState() == DownloadItem::COMPLETE &&
170 (item_->PercentComplete() != 100)))) {
171 error_ = true;
172 if (waiting_)
173 base::MessageLoopForUI::current()->Quit();
175 if (item_->GetState() == DownloadItem::COMPLETE && waiting_)
176 base::MessageLoopForUI::current()->Quit();
179 virtual void OnDownloadDestroyed(content::DownloadItem* item) OVERRIDE {
180 DCHECK_EQ(item_, item);
181 item_->RemoveObserver(this);
182 item_ = NULL;
185 content::DownloadItem* item_;
186 bool waiting_;
187 bool error_;
188 int prev_percent_;
190 DISALLOW_COPY_AND_ASSIGN(PercentWaiter);
193 // DownloadTestObserver subclass that observes one download until it transitions
194 // from a non-resumable state to a resumable state a specified number of
195 // times. Note that this observer can only observe a single download.
196 class DownloadTestObserverResumable : public content::DownloadTestObserver {
197 public:
198 // Construct a new observer. |transition_count| is the number of times the
199 // download should transition from a non-resumable state to a resumable state.
200 DownloadTestObserverResumable(DownloadManager* download_manager,
201 size_t transition_count)
202 : DownloadTestObserver(download_manager, 1,
203 ON_DANGEROUS_DOWNLOAD_FAIL),
204 was_previously_resumable_(false),
205 transitions_left_(transition_count) {
206 Init();
208 virtual ~DownloadTestObserverResumable() {}
210 private:
211 virtual bool IsDownloadInFinalState(DownloadItem* download) OVERRIDE {
212 bool is_resumable_now = download->CanResume();
213 if (!was_previously_resumable_ && is_resumable_now)
214 --transitions_left_;
215 was_previously_resumable_ = is_resumable_now;
216 return transitions_left_ == 0;
219 bool was_previously_resumable_;
220 size_t transitions_left_;
222 DISALLOW_COPY_AND_ASSIGN(DownloadTestObserverResumable);
225 // IDs and paths of CRX files used in tests.
226 const char kGoodCrxId[] = "ldnnhddmnhbkjipkidpdiheffobcpfmf";
227 const base::FilePath kGoodCrxPath(FILE_PATH_LITERAL("extensions/good.crx"));
229 const char kLargeThemeCrxId[] = "pjpgmfcmabopnnfonnhmdjglfpjjfkbf";
230 const base::FilePath kLargeThemePath(
231 FILE_PATH_LITERAL("extensions/theme2.crx"));
233 // Get History Information.
234 class DownloadsHistoryDataCollector {
235 public:
236 explicit DownloadsHistoryDataCollector(Profile* profile)
237 : profile_(profile), result_valid_(false) {}
239 bool WaitForDownloadInfo(
240 scoped_ptr<std::vector<history::DownloadRow> >* results) {
241 HistoryService* hs = HistoryServiceFactory::GetForProfile(
242 profile_, Profile::EXPLICIT_ACCESS);
243 DCHECK(hs);
244 hs->QueryDownloads(
245 base::Bind(&DownloadsHistoryDataCollector::OnQueryDownloadsComplete,
246 base::Unretained(this)));
248 content::RunMessageLoop();
249 if (result_valid_) {
250 *results = results_.Pass();
252 return result_valid_;
255 private:
256 void OnQueryDownloadsComplete(
257 scoped_ptr<std::vector<history::DownloadRow> > entries) {
258 result_valid_ = true;
259 results_ = entries.Pass();
260 base::MessageLoopForUI::current()->Quit();
263 Profile* profile_;
264 scoped_ptr<std::vector<history::DownloadRow> > results_;
265 bool result_valid_;
266 CancelableRequestConsumer callback_consumer_;
268 DISALLOW_COPY_AND_ASSIGN(DownloadsHistoryDataCollector);
271 // Mock that simulates a permissions dialog where the user denies
272 // permission to install. TODO(skerner): This could be shared with
273 // extensions tests. Find a common place for this class.
274 class MockAbortExtensionInstallPrompt : public ExtensionInstallPrompt {
275 public:
276 MockAbortExtensionInstallPrompt() :
277 ExtensionInstallPrompt(NULL) {
280 // Simulate a user abort on an extension installation.
281 virtual void ConfirmInstall(
282 Delegate* delegate,
283 const Extension* extension,
284 const ShowDialogCallback& show_dialog_callback) OVERRIDE {
285 delegate->InstallUIAbort(true);
286 base::MessageLoopForUI::current()->Quit();
289 virtual void OnInstallSuccess(const Extension* extension,
290 SkBitmap* icon) OVERRIDE {
292 virtual void OnInstallFailure(
293 const extensions::CrxInstallerError& error) OVERRIDE {
297 // Mock that simulates a permissions dialog where the user allows
298 // installation.
299 class MockAutoConfirmExtensionInstallPrompt : public ExtensionInstallPrompt {
300 public:
301 explicit MockAutoConfirmExtensionInstallPrompt(
302 content::WebContents* web_contents)
303 : ExtensionInstallPrompt(web_contents) {}
305 // Proceed without confirmation prompt.
306 virtual void ConfirmInstall(
307 Delegate* delegate,
308 const Extension* extension,
309 const ShowDialogCallback& show_dialog_callback) OVERRIDE {
310 delegate->InstallUIProceed();
313 virtual void OnInstallSuccess(const Extension* extension,
314 SkBitmap* icon) OVERRIDE {
316 virtual void OnInstallFailure(
317 const extensions::CrxInstallerError& error) OVERRIDE {
321 static DownloadManager* DownloadManagerForBrowser(Browser* browser) {
322 return BrowserContext::GetDownloadManager(browser->profile());
325 class TestRenderViewContextMenu : public RenderViewContextMenu {
326 public:
327 TestRenderViewContextMenu(WebContents* web_contents,
328 const content::ContextMenuParams& params)
329 : RenderViewContextMenu(web_contents, params) {
331 virtual ~TestRenderViewContextMenu() {}
333 private:
334 virtual void PlatformInit() OVERRIDE {}
335 virtual void PlatformCancel() OVERRIDE {}
336 virtual bool GetAcceleratorForCommandId(int, ui::Accelerator*) OVERRIDE {
337 return false;
340 DISALLOW_COPY_AND_ASSIGN(TestRenderViewContextMenu);
343 bool WasAutoOpened(DownloadItem* item) {
344 return item->GetAutoOpened();
347 // Called when a download starts. Marks the download as hidden.
348 void SetHiddenDownloadCallback(DownloadItem* item,
349 content::DownloadInterruptReason reason) {
350 DownloadItemModel(item).SetShouldShowInShelf(false);
353 // Callback for HistoryObserver; used in DownloadHistoryCheck
354 bool HasDataAndName(const history::DownloadRow& row) {
355 return row.received_bytes > 0 && !row.target_path.empty();
358 } // namespace
360 DownloadTestObserverNotInProgress::DownloadTestObserverNotInProgress(
361 DownloadManager* download_manager,
362 size_t count)
363 : DownloadTestObserver(download_manager, count, ON_DANGEROUS_DOWNLOAD_FAIL),
364 started_observing_(false) {
365 Init();
368 DownloadTestObserverNotInProgress::~DownloadTestObserverNotInProgress() {}
370 void DownloadTestObserverNotInProgress::StartObserving() {
371 started_observing_ = true;
374 bool DownloadTestObserverNotInProgress::IsDownloadInFinalState(
375 DownloadItem* download) {
376 return started_observing_ &&
377 download->GetState() != DownloadItem::IN_PROGRESS;
380 class HistoryObserver : public DownloadHistory::Observer {
381 public:
382 typedef base::Callback<bool(const history::DownloadRow&)> FilterCallback;
384 explicit HistoryObserver(Profile* profile)
385 : profile_(profile),
386 waiting_(false),
387 seen_stored_(false) {
388 DownloadServiceFactory::GetForBrowserContext(profile_)->
389 GetDownloadHistory()->AddObserver(this);
392 virtual ~HistoryObserver() {
393 DownloadService* service = DownloadServiceFactory::GetForBrowserContext(
394 profile_);
395 if (service && service->GetDownloadHistory())
396 service->GetDownloadHistory()->RemoveObserver(this);
399 void SetFilterCallback(const FilterCallback& callback) {
400 callback_ = callback;
403 virtual void OnDownloadStored(
404 content::DownloadItem* item,
405 const history::DownloadRow& info) OVERRIDE {
406 if (!callback_.is_null() && (!callback_.Run(info)))
407 return;
409 seen_stored_ = true;
410 if (waiting_)
411 base::MessageLoopForUI::current()->Quit();
414 virtual void OnDownloadHistoryDestroyed() OVERRIDE {
415 DownloadServiceFactory::GetForBrowserContext(profile_)->
416 GetDownloadHistory()->RemoveObserver(this);
419 void WaitForStored() {
420 if (seen_stored_)
421 return;
422 waiting_ = true;
423 content::RunMessageLoop();
424 waiting_ = false;
427 private:
428 Profile* profile_;
429 bool waiting_;
430 bool seen_stored_;
431 FilterCallback callback_;
433 DISALLOW_COPY_AND_ASSIGN(HistoryObserver);
436 class DownloadTest : public InProcessBrowserTest {
437 public:
438 // Choice of navigation or direct fetch. Used by |DownloadFileCheckErrors()|.
439 enum DownloadMethod {
440 DOWNLOAD_NAVIGATE,
441 DOWNLOAD_DIRECT
444 // Information passed in to |DownloadFileCheckErrors()|.
445 struct DownloadInfo {
446 const char* url_name; // URL for the download.
447 DownloadMethod download_method; // Navigation or Direct.
448 // Download interrupt reason (NONE is OK).
449 content::DownloadInterruptReason reason;
450 bool show_download_item; // True if the download item appears on the shelf.
451 bool should_redirect_to_documents; // True if we save it in "My Documents".
454 struct FileErrorInjectInfo {
455 DownloadInfo download_info;
456 content::TestFileErrorInjector::FileErrorInfo error_info;
459 DownloadTest() {}
461 virtual void SetUpOnMainThread() OVERRIDE {
462 BrowserThread::PostTask(
463 BrowserThread::IO, FROM_HERE,
464 base::Bind(&chrome_browser_net::SetUrlRequestMocksEnabled, true));
465 ASSERT_TRUE(InitialSetup());
468 virtual void CleanUpOnMainThread() OVERRIDE {
469 // Needs to be torn down on the main thread. file_activity_observer_ holds a
470 // reference to the ChromeDownloadManagerDelegate which should be destroyed
471 // on the UI thread.
472 file_activity_observer_.reset();
475 virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
476 command_line->AppendSwitch(switches::kDisablePluginsDiscovery);
479 // Returning false indicates a failure of the setup, and should be asserted
480 // in the caller.
481 virtual bool InitialSetup() {
482 bool have_test_dir = PathService::Get(chrome::DIR_TEST_DATA, &test_dir_);
483 EXPECT_TRUE(have_test_dir);
484 if (!have_test_dir)
485 return false;
487 // Sanity check default values for window / tab count and shelf visibility.
488 int window_count = chrome::GetTotalBrowserCount();
489 EXPECT_EQ(1, window_count);
490 EXPECT_EQ(1, browser()->tab_strip_model()->count());
491 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
493 // Set up the temporary download folder.
494 bool created_downloads_dir = CreateAndSetDownloadsDirectory(browser());
495 EXPECT_TRUE(created_downloads_dir);
496 if (!created_downloads_dir)
497 return false;
498 browser()->profile()->GetPrefs()->SetBoolean(
499 prefs::kPromptForDownload, false);
501 DownloadManager* manager = DownloadManagerForBrowser(browser());
502 DownloadPrefs::FromDownloadManager(manager)->ResetAutoOpen();
503 manager->RemoveAllDownloads();
505 file_activity_observer_.reset(
506 new DownloadTestFileActivityObserver(browser()->profile()));
508 return true;
511 protected:
512 enum SizeTestType {
513 SIZE_TEST_TYPE_KNOWN,
514 SIZE_TEST_TYPE_UNKNOWN,
517 base::FilePath GetDownloadsDirectory() {
518 return downloads_directory_.path();
521 // Location of the file source (the place from which it is downloaded).
522 base::FilePath OriginFile(base::FilePath file) {
523 return test_dir_.Append(file);
526 // Location of the file destination (place to which it is downloaded).
527 base::FilePath DestinationFile(Browser* browser, base::FilePath file) {
528 return GetDownloadDirectory(browser).Append(file.BaseName());
531 // Must be called after browser creation. Creates a temporary
532 // directory for downloads that is auto-deleted on destruction.
533 // Returning false indicates a failure of the function, and should be asserted
534 // in the caller.
535 bool CreateAndSetDownloadsDirectory(Browser* browser) {
536 if (!browser)
537 return false;
539 if (!downloads_directory_.CreateUniqueTempDir())
540 return false;
542 browser->profile()->GetPrefs()->SetFilePath(
543 prefs::kDownloadDefaultDirectory,
544 downloads_directory_.path());
545 browser->profile()->GetPrefs()->SetFilePath(
546 prefs::kSaveFileDefaultDirectory,
547 downloads_directory_.path());
549 return true;
552 DownloadPrefs* GetDownloadPrefs(Browser* browser) {
553 return DownloadPrefs::FromDownloadManager(
554 DownloadManagerForBrowser(browser));
557 base::FilePath GetDownloadDirectory(Browser* browser) {
558 return GetDownloadPrefs(browser)->DownloadPath();
561 // Create a DownloadTestObserverTerminal that will wait for the
562 // specified number of downloads to finish.
563 content::DownloadTestObserver* CreateWaiter(
564 Browser* browser, int num_downloads) {
565 DownloadManager* download_manager = DownloadManagerForBrowser(browser);
566 return new content::DownloadTestObserverTerminal(
567 download_manager, num_downloads,
568 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL);
571 // Create a DownloadTestObserverInProgress that will wait for the
572 // specified number of downloads to start.
573 content::DownloadTestObserver* CreateInProgressWaiter(
574 Browser* browser, int num_downloads) {
575 DownloadManager* download_manager = DownloadManagerForBrowser(browser);
576 return new content::DownloadTestObserverInProgress(
577 download_manager, num_downloads);
580 // Create a DownloadTestObserverTerminal that will wait for the
581 // specified number of downloads to finish, or for
582 // a dangerous download warning to be shown.
583 content::DownloadTestObserver* DangerousDownloadWaiter(
584 Browser* browser,
585 int num_downloads,
586 content::DownloadTestObserver::DangerousDownloadAction
587 dangerous_download_action) {
588 DownloadManager* download_manager = DownloadManagerForBrowser(browser);
589 return new content::DownloadTestObserverTerminal(
590 download_manager, num_downloads,
591 dangerous_download_action);
594 void CheckDownloadStatesForBrowser(Browser* browser,
595 size_t num,
596 DownloadItem::DownloadState state) {
597 std::vector<DownloadItem*> download_items;
598 GetDownloads(browser, &download_items);
600 EXPECT_EQ(num, download_items.size());
602 for (size_t i = 0; i < download_items.size(); ++i) {
603 EXPECT_EQ(state, download_items[i]->GetState()) << " Item " << i;
607 void CheckDownloadStates(size_t num, DownloadItem::DownloadState state) {
608 CheckDownloadStatesForBrowser(browser(), num, state);
611 // Download |url|, then wait for the download to finish.
612 // |disposition| indicates where the navigation occurs (current tab, new
613 // foreground tab, etc).
614 // |browser_test_flags| indicate what to wait for, and is an OR of 0 or more
615 // values in the ui_test_utils::BrowserTestWaitFlags enum.
616 void DownloadAndWaitWithDisposition(Browser* browser,
617 const GURL& url,
618 WindowOpenDisposition disposition,
619 int browser_test_flags) {
620 // Setup notification, navigate, and block.
621 scoped_ptr<content::DownloadTestObserver> observer(
622 CreateWaiter(browser, 1));
623 // This call will block until the condition specified by
624 // |browser_test_flags|, but will not wait for the download to finish.
625 ui_test_utils::NavigateToURLWithDisposition(browser,
626 url,
627 disposition,
628 browser_test_flags);
629 // Waits for the download to complete.
630 observer->WaitForFinished();
631 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::COMPLETE));
632 // We don't expect a file chooser to be shown.
633 EXPECT_FALSE(DidShowFileChooser());
636 // Download a file in the current tab, then wait for the download to finish.
637 void DownloadAndWait(Browser* browser,
638 const GURL& url) {
639 DownloadAndWaitWithDisposition(
640 browser,
641 url,
642 CURRENT_TAB,
643 ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
646 // Should only be called when the download is known to have finished
647 // (in error or not).
648 // Returning false indicates a failure of the function, and should be asserted
649 // in the caller.
650 bool CheckDownload(Browser* browser,
651 const base::FilePath& downloaded_filename,
652 const base::FilePath& origin_filename) {
653 // Find the path to which the data will be downloaded.
654 base::FilePath downloaded_file(
655 DestinationFile(browser, downloaded_filename));
657 // Find the origin path (from which the data comes).
658 base::FilePath origin_file(OriginFile(origin_filename));
659 return CheckDownloadFullPaths(browser, downloaded_file, origin_file);
662 // A version of CheckDownload that allows complete path specification.
663 bool CheckDownloadFullPaths(Browser* browser,
664 const base::FilePath& downloaded_file,
665 const base::FilePath& origin_file) {
666 bool origin_file_exists = base::PathExists(origin_file);
667 EXPECT_TRUE(origin_file_exists) << origin_file.value();
668 if (!origin_file_exists)
669 return false;
671 // Confirm the downloaded data file exists.
672 bool downloaded_file_exists = base::PathExists(downloaded_file);
673 EXPECT_TRUE(downloaded_file_exists) << downloaded_file.value();
674 if (!downloaded_file_exists)
675 return false;
677 int64 origin_file_size = 0;
678 EXPECT_TRUE(base::GetFileSize(origin_file, &origin_file_size));
679 std::string original_file_contents;
680 EXPECT_TRUE(base::ReadFileToString(origin_file, &original_file_contents));
681 EXPECT_TRUE(
682 VerifyFile(downloaded_file, original_file_contents, origin_file_size));
684 // Delete the downloaded copy of the file.
685 bool downloaded_file_deleted =
686 file_util::DieFileDie(downloaded_file, false);
687 EXPECT_TRUE(downloaded_file_deleted);
688 return downloaded_file_deleted;
691 content::DownloadTestObserver* CreateInProgressDownloadObserver(
692 size_t download_count) {
693 DownloadManager* manager = DownloadManagerForBrowser(browser());
694 return new content::DownloadTestObserverInProgress(
695 manager, download_count);
698 DownloadItem* CreateSlowTestDownload() {
699 scoped_ptr<content::DownloadTestObserver> observer(
700 CreateInProgressDownloadObserver(1));
701 GURL slow_download_url(URLRequestSlowDownloadJob::kUnknownSizeUrl);
702 DownloadManager* manager = DownloadManagerForBrowser(browser());
704 EXPECT_EQ(0, manager->NonMaliciousInProgressCount());
705 EXPECT_EQ(0, manager->InProgressCount());
706 if (manager->InProgressCount() != 0)
707 return NULL;
709 ui_test_utils::NavigateToURLWithDisposition(
710 browser(), slow_download_url, CURRENT_TAB,
711 ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
713 observer->WaitForFinished();
714 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::IN_PROGRESS));
716 DownloadManager::DownloadVector items;
717 manager->GetAllDownloads(&items);
719 DownloadItem* new_item = NULL;
720 for (DownloadManager::DownloadVector::iterator iter = items.begin();
721 iter != items.end(); ++iter) {
722 if ((*iter)->GetState() == DownloadItem::IN_PROGRESS) {
723 // There should be only one IN_PROGRESS item.
724 EXPECT_EQ(NULL, new_item);
725 new_item = *iter;
728 return new_item;
731 bool RunSizeTest(Browser* browser,
732 SizeTestType type,
733 const std::string& partial_indication,
734 const std::string& total_indication) {
735 EXPECT_TRUE(type == SIZE_TEST_TYPE_UNKNOWN || type == SIZE_TEST_TYPE_KNOWN);
736 if (type != SIZE_TEST_TYPE_KNOWN && type != SIZE_TEST_TYPE_UNKNOWN)
737 return false;
738 GURL url(type == SIZE_TEST_TYPE_KNOWN ?
739 URLRequestSlowDownloadJob::kKnownSizeUrl :
740 URLRequestSlowDownloadJob::kUnknownSizeUrl);
742 // TODO(ahendrickson) -- |expected_title_in_progress| and
743 // |expected_title_finished| need to be checked.
744 base::FilePath filename;
745 net::FileURLToFilePath(url, &filename);
746 base::string16 expected_title_in_progress(
747 base::ASCIIToUTF16(partial_indication) + filename.LossyDisplayName());
748 base::string16 expected_title_finished(
749 base::ASCIIToUTF16(total_indication) + filename.LossyDisplayName());
751 // Download a partial web page in a background tab and wait.
752 // The mock system will not complete until it gets a special URL.
753 scoped_ptr<content::DownloadTestObserver> observer(
754 CreateWaiter(browser, 1));
755 ui_test_utils::NavigateToURL(browser, url);
757 // TODO(ahendrickson): check download status text before downloading.
758 // Need to:
759 // - Add a member function to the |DownloadShelf| interface class, that
760 // indicates how many members it has.
761 // - Add a member function to |DownloadShelf| to get the status text
762 // of a given member (for example, via the name in |DownloadItemView|'s
763 // GetAccessibleState() member function), by index.
764 // - Iterate over browser->window()->GetDownloadShelf()'s members
765 // to see if any match the status text we want. Start with the last one.
767 // Allow the request to finish. We do this by loading a second URL in a
768 // separate tab.
769 GURL finish_url(URLRequestSlowDownloadJob::kFinishDownloadUrl);
770 ui_test_utils::NavigateToURLWithDisposition(
771 browser,
772 finish_url,
773 NEW_FOREGROUND_TAB,
774 ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
775 observer->WaitForFinished();
776 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::COMPLETE));
777 CheckDownloadStatesForBrowser(browser, 1, DownloadItem::COMPLETE);
779 EXPECT_EQ(2, browser->tab_strip_model()->count());
781 // TODO(ahendrickson): check download status text after downloading.
783 base::FilePath basefilename(filename.BaseName());
784 net::FileURLToFilePath(url, &filename);
785 base::FilePath download_path =
786 downloads_directory_.path().Append(basefilename);
787 EXPECT_TRUE(browser->window()->IsDownloadShelfVisible());
789 bool downloaded_path_exists = base::PathExists(download_path);
790 EXPECT_TRUE(downloaded_path_exists);
791 if (!downloaded_path_exists)
792 return false;
794 // Check the file contents.
795 size_t file_size = URLRequestSlowDownloadJob::kFirstDownloadSize +
796 URLRequestSlowDownloadJob::kSecondDownloadSize;
797 std::string expected_contents(file_size, '*');
798 EXPECT_TRUE(VerifyFile(download_path, expected_contents, file_size));
800 // Delete the file we just downloaded.
801 EXPECT_TRUE(file_util::DieFileDie(download_path, true));
802 EXPECT_FALSE(base::PathExists(download_path));
804 return true;
807 void GetDownloads(Browser* browser, std::vector<DownloadItem*>* downloads) {
808 DCHECK(downloads);
809 DownloadManager* manager = DownloadManagerForBrowser(browser);
810 manager->GetAllDownloads(downloads);
813 static void ExpectWindowCountAfterDownload(size_t expected) {
814 EXPECT_EQ(expected, chrome::GetTotalBrowserCount());
817 void EnableFileChooser(bool enable) {
818 file_activity_observer_->EnableFileChooser(enable);
821 bool DidShowFileChooser() {
822 return file_activity_observer_->TestAndResetDidShowFileChooser();
825 // Checks that |path| is has |file_size| bytes, and matches the |value|
826 // string.
827 bool VerifyFile(const base::FilePath& path,
828 const std::string& value,
829 const int64 file_size) {
830 std::string file_contents;
832 bool read = base::ReadFileToString(path, &file_contents);
833 EXPECT_TRUE(read) << "Failed reading file: " << path.value() << std::endl;
834 if (!read)
835 return false; // Couldn't read the file.
837 // Note: we don't handle really large files (more than size_t can hold)
838 // so we will fail in that case.
839 size_t expected_size = static_cast<size_t>(file_size);
841 // Check the size.
842 EXPECT_EQ(expected_size, file_contents.size());
843 if (expected_size != file_contents.size())
844 return false;
846 // Check the contents.
847 EXPECT_EQ(value, file_contents);
848 if (memcmp(file_contents.c_str(), value.c_str(), expected_size) != 0)
849 return false;
851 return true;
854 // Attempts to download a file, based on information in |download_info|.
855 // If a Select File dialog opens, will automatically choose the default.
856 void DownloadFilesCheckErrorsSetup() {
857 ASSERT_TRUE(test_server()->Start());
858 std::vector<DownloadItem*> download_items;
859 GetDownloads(browser(), &download_items);
860 ASSERT_TRUE(download_items.empty());
862 EnableFileChooser(true);
865 void DownloadFilesCheckErrorsLoopBody(const DownloadInfo& download_info,
866 size_t i) {
867 std::stringstream s;
868 s << " " << __FUNCTION__ << "()"
869 << " index = " << i
870 << " url = '" << download_info.url_name << "'"
871 << " method = "
872 << ((download_info.download_method == DOWNLOAD_DIRECT) ?
873 "DOWNLOAD_DIRECT" : "DOWNLOAD_NAVIGATE")
874 << " show_item = " << download_info.show_download_item
875 << " reason = " << DownloadInterruptReasonToString(download_info.reason);
877 std::vector<DownloadItem*> download_items;
878 GetDownloads(browser(), &download_items);
879 size_t downloads_expected = download_items.size();
881 std::string server_path = "files/downloads/";
882 server_path += download_info.url_name;
883 GURL url = test_server()->GetURL(server_path);
884 ASSERT_TRUE(url.is_valid()) << s.str();
886 DownloadManager* download_manager = DownloadManagerForBrowser(browser());
887 WebContents* web_contents =
888 browser()->tab_strip_model()->GetActiveWebContents();
889 ASSERT_TRUE(web_contents) << s.str();
891 scoped_ptr<content::DownloadTestObserver> observer(
892 new content::DownloadTestObserverTerminal(
893 download_manager,
895 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL));
897 if (download_info.download_method == DOWNLOAD_DIRECT) {
898 // Go directly to download. Don't wait for navigation.
899 scoped_refptr<content::DownloadTestItemCreationObserver>
900 creation_observer(new content::DownloadTestItemCreationObserver);
902 scoped_ptr<DownloadUrlParameters> params(
903 DownloadUrlParameters::FromWebContents(web_contents, url));
904 params->set_callback(creation_observer->callback());
905 DownloadManagerForBrowser(browser())->DownloadUrl(params.Pass());
907 // Wait until the item is created, or we have determined that it
908 // won't be.
909 creation_observer->WaitForDownloadItemCreation();
911 EXPECT_EQ(download_info.show_download_item,
912 creation_observer->succeeded());
913 if (download_info.show_download_item) {
914 EXPECT_EQ(content::DOWNLOAD_INTERRUPT_REASON_NONE,
915 creation_observer->interrupt_reason());
916 EXPECT_NE(content::DownloadItem::kInvalidId,
917 creation_observer->download_id());
918 } else {
919 EXPECT_NE(content::DOWNLOAD_INTERRUPT_REASON_NONE,
920 creation_observer->interrupt_reason());
921 EXPECT_EQ(content::DownloadItem::kInvalidId,
922 creation_observer->download_id());
924 } else {
925 // Navigate to URL normally, wait until done.
926 ui_test_utils::NavigateToURLBlockUntilNavigationsComplete(browser(),
927 url,
931 if (download_info.show_download_item) {
932 downloads_expected++;
933 observer->WaitForFinished();
934 DownloadItem::DownloadState final_state =
935 (download_info.reason == content::DOWNLOAD_INTERRUPT_REASON_NONE) ?
936 DownloadItem::COMPLETE :
937 DownloadItem::INTERRUPTED;
938 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(final_state));
941 // Wait till the |DownloadFile|s are destroyed.
942 content::RunAllPendingInMessageLoop(content::BrowserThread::FILE);
943 content::RunAllPendingInMessageLoop(content::BrowserThread::UI);
945 // Validate that the correct files were downloaded.
946 download_items.clear();
947 GetDownloads(browser(), &download_items);
948 ASSERT_EQ(downloads_expected, download_items.size()) << s.str();
950 if (download_info.show_download_item) {
951 // Find the last download item.
952 DownloadItem* item = download_items[0];
953 for (size_t d = 1; d < downloads_expected; ++d) {
954 if (download_items[d]->GetStartTime() > item->GetStartTime())
955 item = download_items[d];
958 ASSERT_EQ(url, item->GetOriginalUrl()) << s.str();
960 ASSERT_EQ(download_info.reason, item->GetLastReason()) << s.str();
962 if (item->GetState() == content::DownloadItem::COMPLETE) {
963 // Clean up the file, in case it ended up in the My Documents folder.
964 base::FilePath destination_folder = GetDownloadDirectory(browser());
965 base::FilePath my_downloaded_file = item->GetTargetFilePath();
966 EXPECT_TRUE(base::PathExists(my_downloaded_file));
967 EXPECT_TRUE(base::DeleteFile(my_downloaded_file, false));
969 EXPECT_EQ(download_info.should_redirect_to_documents ?
970 std::string::npos :
972 my_downloaded_file.value().find(destination_folder.value()));
973 if (download_info.should_redirect_to_documents) {
974 // If it's not where we asked it to be, it should be in the
975 // My Documents folder.
976 base::FilePath my_docs_folder;
977 EXPECT_TRUE(PathService::Get(chrome::DIR_USER_DOCUMENTS,
978 &my_docs_folder));
979 EXPECT_EQ(0u,
980 my_downloaded_file.value().find(my_docs_folder.value()));
986 // Attempts to download a set of files, based on information in the
987 // |download_info| array. |count| is the number of files.
988 // If a Select File dialog appears, it will choose the default and return
989 // immediately.
990 void DownloadFilesCheckErrors(size_t count, DownloadInfo* download_info) {
991 DownloadFilesCheckErrorsSetup();
993 for (size_t i = 0; i < count; ++i) {
994 DownloadFilesCheckErrorsLoopBody(download_info[i], i);
998 void DownloadInsertFilesErrorCheckErrorsLoopBody(
999 scoped_refptr<content::TestFileErrorInjector> injector,
1000 const FileErrorInjectInfo& info,
1001 size_t i) {
1002 std::stringstream s;
1003 s << " " << __FUNCTION__ << "()"
1004 << " index = " << i
1005 << " url = " << info.error_info.url
1006 << " operation code = "
1007 << content::TestFileErrorInjector::DebugString(info.error_info.code)
1008 << " instance = " << info.error_info.operation_instance
1009 << " error = "
1010 << content::DownloadInterruptReasonToString(info.error_info.error);
1012 injector->ClearErrors();
1013 injector->AddError(info.error_info);
1015 injector->InjectErrors();
1017 DownloadFilesCheckErrorsLoopBody(info.download_info, i);
1019 size_t expected_successes = info.download_info.show_download_item ? 1u : 0u;
1020 EXPECT_EQ(expected_successes, injector->TotalFileCount()) << s.str();
1021 EXPECT_EQ(0u, injector->CurrentFileCount()) << s.str();
1023 if (info.download_info.show_download_item)
1024 EXPECT_TRUE(injector->HadFile(GURL(info.error_info.url))) << s.str();
1027 void DownloadInsertFilesErrorCheckErrors(size_t count,
1028 FileErrorInjectInfo* info) {
1029 DownloadFilesCheckErrorsSetup();
1031 // Set up file failures.
1032 scoped_refptr<content::TestFileErrorInjector> injector(
1033 content::TestFileErrorInjector::Create(
1034 DownloadManagerForBrowser(browser())));
1036 for (size_t i = 0; i < count; ++i) {
1037 // Set up the full URL, for download file tracking.
1038 std::string server_path = "files/downloads/";
1039 server_path += info[i].download_info.url_name;
1040 GURL url = test_server()->GetURL(server_path);
1041 info[i].error_info.url = url.spec();
1043 DownloadInsertFilesErrorCheckErrorsLoopBody(injector, info[i], i);
1047 // Attempts to download a file to a read-only folder, based on information
1048 // in |download_info|.
1049 void DownloadFilesToReadonlyFolder(size_t count,
1050 DownloadInfo* download_info) {
1051 DownloadFilesCheckErrorsSetup();
1053 // Make the test folder unwritable.
1054 base::FilePath destination_folder = GetDownloadDirectory(browser());
1055 DVLOG(1) << " " << __FUNCTION__ << "()"
1056 << " folder = '" << destination_folder.value() << "'";
1057 file_util::PermissionRestorer permission_restorer(destination_folder);
1058 EXPECT_TRUE(file_util::MakeFileUnwritable(destination_folder));
1060 for (size_t i = 0; i < count; ++i) {
1061 DownloadFilesCheckErrorsLoopBody(download_info[i], i);
1065 // A mock install prompt that simulates the user allowing an install request.
1066 void SetAllowMockInstallPrompt() {
1067 download_crx_util::SetMockInstallPromptForTesting(
1068 scoped_ptr<ExtensionInstallPrompt>(
1069 new MockAutoConfirmExtensionInstallPrompt(
1070 browser()->tab_strip_model()->GetActiveWebContents())));
1073 // This method:
1074 // * Starts a mock download by navigating browser() to a URLRequestMockHTTPJob
1075 // mock URL.
1076 // * Injects |error| on the first write using |error_injector|.
1077 // * Waits for the download to be interrupted.
1078 // * Clears the errors on |error_injector|.
1079 // * Returns the resulting interrupted download.
1080 DownloadItem* StartMockDownloadAndInjectError(
1081 content::TestFileErrorInjector* error_injector,
1082 content::DownloadInterruptReason error) {
1083 base::FilePath file_path(FILE_PATH_LITERAL("download-test1.lib"));
1084 GURL url = URLRequestMockHTTPJob::GetMockUrl(file_path);
1086 content::TestFileErrorInjector::FileErrorInfo error_info;
1087 error_info.url = url.spec();
1088 error_info.code = content::TestFileErrorInjector::FILE_OPERATION_WRITE;
1089 error_info.operation_instance = 0;
1090 error_info.error = error;
1091 error_injector->ClearErrors();
1092 error_injector->AddError(error_info);
1093 error_injector->InjectErrors();
1095 scoped_ptr<content::DownloadTestObserver> observer(
1096 new DownloadTestObserverResumable(
1097 DownloadManagerForBrowser(browser()), 1));
1098 ui_test_utils::NavigateToURL(browser(), url);
1099 observer->WaitForFinished();
1101 content::DownloadManager::DownloadVector downloads;
1102 DownloadManagerForBrowser(browser())->GetAllDownloads(&downloads);
1103 EXPECT_EQ(1u, downloads.size());
1105 if (downloads.size() != 1)
1106 return NULL;
1108 error_injector->ClearErrors();
1109 error_injector->InjectErrors();
1110 DownloadItem* download = downloads[0];
1111 EXPECT_EQ(DownloadItem::INTERRUPTED, download->GetState());
1112 EXPECT_EQ(error, download->GetLastReason());
1113 return download;
1116 private:
1117 static void EnsureNoPendingDownloadJobsOnIO(bool* result) {
1118 if (URLRequestSlowDownloadJob::NumberOutstandingRequests())
1119 *result = false;
1120 BrowserThread::PostTask(
1121 BrowserThread::UI, FROM_HERE, base::MessageLoop::QuitClosure());
1124 // Location of the test data.
1125 base::FilePath test_dir_;
1127 // Location of the downloads directory for these tests
1128 base::ScopedTempDir downloads_directory_;
1130 scoped_ptr<DownloadTestFileActivityObserver> file_activity_observer_;
1133 // NOTES:
1135 // Files for these tests are found in DIR_TEST_DATA (currently
1136 // "chrome\test\data\", see chrome_paths.cc).
1137 // Mock responses have extension .mock-http-headers appended to the file name.
1139 // Download a file due to the associated MIME type.
1140 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadMimeType) {
1141 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
1142 GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
1144 // Download the file and wait. We do not expect the Select File dialog.
1145 DownloadAndWait(browser(), url);
1147 // Check state.
1148 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1149 CheckDownload(browser(), file, file);
1150 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
1153 #if defined(OS_WIN)
1154 // Download a file and confirm that the zone identifier (on windows)
1155 // is set to internet.
1156 IN_PROC_BROWSER_TEST_F(DownloadTest, CheckInternetZone) {
1157 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
1158 GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
1160 // Download the file and wait. We do not expect the Select File dialog.
1161 DownloadAndWait(browser(), url);
1163 // Check state. Special file state must be checked before CheckDownload,
1164 // as CheckDownload will delete the output file.
1165 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1166 base::FilePath downloaded_file(DestinationFile(browser(), file));
1167 if (file_util::VolumeSupportsADS(downloaded_file))
1168 EXPECT_TRUE(file_util::HasInternetZoneIdentifier(downloaded_file));
1169 CheckDownload(browser(), file, file);
1170 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
1172 #endif
1174 // Put up a Select File dialog when the file is downloaded, due to
1175 // downloads preferences settings.
1176 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadMimeTypeSelect) {
1177 // Re-enable prompting.
1178 browser()->profile()->GetPrefs()->SetBoolean(
1179 prefs::kPromptForDownload, true);
1180 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
1181 GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
1183 EnableFileChooser(true);
1185 // Download the file and wait. We expect the Select File dialog to appear
1186 // due to the MIME type, but we still wait until the download completes.
1187 scoped_ptr<content::DownloadTestObserver> observer(
1188 new content::DownloadTestObserverTerminal(
1189 DownloadManagerForBrowser(browser()),
1191 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL));
1192 ui_test_utils::NavigateToURLWithDisposition(
1193 browser(), url, CURRENT_TAB,
1194 ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
1195 observer->WaitForFinished();
1196 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::COMPLETE));
1197 CheckDownloadStates(1, DownloadItem::COMPLETE);
1198 EXPECT_TRUE(DidShowFileChooser());
1200 // Check state.
1201 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1202 CheckDownload(browser(), file, file);
1203 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
1206 // Access a file with a viewable mime-type, verify that a download
1207 // did not initiate.
1208 IN_PROC_BROWSER_TEST_F(DownloadTest, NoDownload) {
1209 base::FilePath file(FILE_PATH_LITERAL("download-test2.html"));
1210 GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
1211 base::FilePath file_path(DestinationFile(browser(), file));
1213 // Open a web page and wait.
1214 ui_test_utils::NavigateToURL(browser(), url);
1216 // Check that we did not download the web page.
1217 EXPECT_FALSE(base::PathExists(file_path));
1219 // Check state.
1220 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1221 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
1224 IN_PROC_BROWSER_TEST_F(DownloadTest, MimeTypesToShowNotDownload) {
1225 ASSERT_TRUE(test_server()->Start());
1227 // These files should all be displayed in the browser.
1228 const char* mime_types[] = {
1229 // It is unclear whether to display text/css or download it.
1230 // Firefox 3: Display
1231 // Internet Explorer 7: Download
1232 // Safari 3.2: Download
1233 // We choose to match Firefox due to the lot of complains
1234 // from the users if css files are downloaded:
1235 // http://code.google.com/p/chromium/issues/detail?id=7192
1236 "text/css",
1237 "text/javascript",
1238 "text/plain",
1239 "application/x-javascript",
1240 "text/html",
1241 "text/xml",
1242 "text/xsl",
1243 "application/xhtml+xml",
1244 "image/png",
1245 "image/gif",
1246 "image/jpeg",
1247 "image/bmp",
1249 for (size_t i = 0; i < arraysize(mime_types); ++i) {
1250 const char* mime_type = mime_types[i];
1251 std::string path("contenttype?");
1252 GURL url(test_server()->GetURL(path + mime_type));
1253 ui_test_utils::NavigateToURL(browser(), url);
1255 // Check state.
1256 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1257 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
1261 // Verify that when the DownloadResourceThrottle cancels a download, the
1262 // download never makes it to the downloads system.
1263 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadResourceThrottleCancels) {
1264 // Navigate to a page with the same domain as the file to download. We can't
1265 // navigate directly to the file we don't want to download because cross-site
1266 // navigations reset the TabDownloadState.
1267 base::FilePath same_site_path(FILE_PATH_LITERAL("download_script.html"));
1268 GURL same_site_url(URLRequestMockHTTPJob::GetMockUrl(same_site_path));
1269 ui_test_utils::NavigateToURL(browser(), same_site_url);
1271 // Make sure the initial navigation didn't trigger a download.
1272 std::vector<content::DownloadItem*> items;
1273 DownloadManagerForBrowser(browser())->GetAllDownloads(&items);
1274 EXPECT_EQ(0u, items.size());
1276 // Disable downloads for the tab.
1277 WebContents* web_contents =
1278 browser()->tab_strip_model()->GetActiveWebContents();
1279 DownloadRequestLimiter::TabDownloadState* tab_download_state =
1280 g_browser_process->download_request_limiter()->GetDownloadState(
1281 web_contents, web_contents, true);
1282 ASSERT_TRUE(tab_download_state);
1283 tab_download_state->set_download_status(
1284 DownloadRequestLimiter::DOWNLOADS_NOT_ALLOWED);
1286 // Try to start the download via Javascript and wait for the corresponding
1287 // load stop event.
1288 content::TestNavigationObserver observer(web_contents);
1289 bool download_assempted;
1290 ASSERT_TRUE(content::ExecuteScriptAndExtractBool(
1291 browser()->tab_strip_model()->GetActiveWebContents(),
1292 "window.domAutomationController.send(startDownload());",
1293 &download_assempted));
1294 ASSERT_TRUE(download_assempted);
1295 observer.Wait();
1297 // Check that we did not download the file.
1298 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
1299 base::FilePath file_path(DestinationFile(browser(), file));
1300 EXPECT_FALSE(base::PathExists(file_path));
1302 // Check state.
1303 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1304 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
1306 // Verify that there's no pending download. The resource throttle
1307 // should have deleted it before it created a download item, so it
1308 // shouldn't be available as a cancelled download either.
1309 DownloadManagerForBrowser(browser())->GetAllDownloads(&items);
1310 EXPECT_EQ(0u, items.size());
1313 // Download a 0-size file with a content-disposition header, verify that the
1314 // download tab opened and the file exists as the filename specified in the
1315 // header. This also ensures we properly handle empty file downloads.
1316 // The download shelf should be visible in the current tab.
1317 IN_PROC_BROWSER_TEST_F(DownloadTest, ContentDisposition) {
1318 base::FilePath file(FILE_PATH_LITERAL("download-test3.gif"));
1319 GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
1320 base::FilePath download_file(
1321 FILE_PATH_LITERAL("download-test3-attachment.gif"));
1323 // Download a file and wait.
1324 DownloadAndWait(browser(), url);
1326 CheckDownload(browser(), download_file, file);
1328 // Check state.
1329 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1330 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
1333 // Test that the download shelf is per-window by starting a download in one
1334 // tab, opening a second tab, closing the shelf, going back to the first tab,
1335 // and checking that the shelf is closed.
1336 IN_PROC_BROWSER_TEST_F(DownloadTest, PerWindowShelf) {
1337 base::FilePath file(FILE_PATH_LITERAL("download-test3.gif"));
1338 GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
1339 base::FilePath download_file(
1340 FILE_PATH_LITERAL("download-test3-attachment.gif"));
1342 // Download a file and wait.
1343 DownloadAndWait(browser(), url);
1345 CheckDownload(browser(), download_file, file);
1347 // Check state.
1348 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1349 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
1351 // Open a second tab and wait.
1352 EXPECT_NE(static_cast<WebContents*>(NULL),
1353 chrome::AddSelectedTabWithURL(browser(), GURL(),
1354 content::PAGE_TRANSITION_TYPED));
1355 EXPECT_EQ(2, browser()->tab_strip_model()->count());
1356 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
1358 // Hide the download shelf.
1359 browser()->window()->GetDownloadShelf()->Close(DownloadShelf::AUTOMATIC);
1360 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
1362 // Go to the first tab.
1363 browser()->tab_strip_model()->ActivateTabAt(0, true);
1364 EXPECT_EQ(2, browser()->tab_strip_model()->count());
1366 // The download shelf should not be visible.
1367 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
1370 // Check whether the downloads shelf is closed when the downloads tab is
1371 // invoked.
1372 IN_PROC_BROWSER_TEST_F(DownloadTest, CloseShelfOnDownloadsTab) {
1373 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
1374 GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
1376 // Download the file and wait. We do not expect the Select File dialog.
1377 DownloadAndWait(browser(), url);
1379 // Check state.
1380 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1381 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
1383 // Open the downloads tab.
1384 chrome::ShowDownloads(browser());
1385 // The shelf should now be closed.
1386 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
1389 // UnknownSize and KnownSize are tests which depend on
1390 // URLRequestSlowDownloadJob to serve content in a certain way. Data will be
1391 // sent in two chunks where the first chunk is 35K and the second chunk is 10K.
1392 // The test will first attempt to download a file; but the server will "pause"
1393 // in the middle until the server receives a second request for
1394 // "download-finish". At that time, the download will finish.
1395 // These tests don't currently test much due to holes in |RunSizeTest()|. See
1396 // comments in that routine for details.
1397 IN_PROC_BROWSER_TEST_F(DownloadTest, UnknownSize) {
1398 ASSERT_TRUE(RunSizeTest(browser(), SIZE_TEST_TYPE_UNKNOWN,
1399 "32.0 KB - ", "100% - "));
1402 IN_PROC_BROWSER_TEST_F(DownloadTest, KnownSize) {
1403 ASSERT_TRUE(RunSizeTest(browser(), SIZE_TEST_TYPE_KNOWN,
1404 "71% - ", "100% - "));
1407 // Test that when downloading an item in Incognito mode, we don't crash when
1408 // closing the last Incognito window (http://crbug.com/13983).
1409 // Also check that the download shelf is not visible after closing the
1410 // Incognito window.
1411 IN_PROC_BROWSER_TEST_F(DownloadTest, IncognitoDownload) {
1412 Browser* incognito = CreateIncognitoBrowser();
1413 ASSERT_TRUE(incognito);
1414 int window_count = chrome::GetTotalBrowserCount();
1415 EXPECT_EQ(2, window_count);
1417 // Download a file in the Incognito window and wait.
1418 CreateAndSetDownloadsDirectory(incognito);
1419 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
1420 GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
1421 // Since |incognito| is a separate browser, we have to set it up explicitly.
1422 incognito->profile()->GetPrefs()->SetBoolean(prefs::kPromptForDownload,
1423 false);
1424 DownloadAndWait(incognito, url);
1426 // We should still have 2 windows.
1427 ExpectWindowCountAfterDownload(2);
1429 // Verify that the download shelf is showing for the Incognito window.
1430 EXPECT_TRUE(incognito->window()->IsDownloadShelfVisible());
1432 #if !defined(OS_MACOSX)
1433 // On Mac OS X, the UI window close is delayed until the outermost
1434 // message loop runs. So it isn't possible to get a BROWSER_CLOSED
1435 // notification inside of a test.
1436 content::WindowedNotificationObserver signal(
1437 chrome::NOTIFICATION_BROWSER_CLOSED,
1438 content::Source<Browser>(incognito));
1439 #endif
1441 // Close the Incognito window and don't crash.
1442 chrome::CloseWindow(incognito);
1444 #if !defined(OS_MACOSX)
1445 signal.Wait();
1446 ExpectWindowCountAfterDownload(1);
1447 #endif
1449 // Verify that the regular window does not have a download shelf.
1450 // On ChromeOS, the download panel is common to both profiles, so
1451 // it is still visible.
1452 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
1454 CheckDownload(browser(), file, file);
1457 // Download one file on-record, then download the same file off-record, and test
1458 // that the filename is deduplicated. The previous test tests for a specific
1459 // bug; this next test tests that filename deduplication happens independently
1460 // of DownloadManager/CDMD.
1461 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadTest_IncognitoRegular) {
1462 ASSERT_TRUE(test_server()->Start());
1463 GURL url(test_server()->GetURL("files/downloads/a_zip_file.zip"));
1465 // Read the origin file now so that we can compare the downloaded files to it
1466 // later.
1467 base::FilePath origin(OriginFile(base::FilePath(FILE_PATH_LITERAL(
1468 "downloads/a_zip_file.zip"))));
1469 ASSERT_TRUE(base::PathExists(origin));
1470 int64 origin_file_size = 0;
1471 EXPECT_TRUE(base::GetFileSize(origin, &origin_file_size));
1472 std::string original_contents;
1473 EXPECT_TRUE(base::ReadFileToString(origin, &original_contents));
1475 std::vector<DownloadItem*> download_items;
1476 GetDownloads(browser(), &download_items);
1477 ASSERT_TRUE(download_items.empty());
1479 // Download a file in the on-record browser and check that it was downloaded
1480 // correctly.
1481 DownloadAndWaitWithDisposition(browser(),
1482 url,
1483 CURRENT_TAB,
1484 ui_test_utils::BROWSER_TEST_NONE);
1485 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
1486 GetDownloads(browser(), &download_items);
1487 ASSERT_EQ(1UL, download_items.size());
1488 ASSERT_EQ(base::FilePath(FILE_PATH_LITERAL("a_zip_file.zip")),
1489 download_items[0]->GetTargetFilePath().BaseName());
1490 ASSERT_TRUE(base::PathExists(download_items[0]->GetTargetFilePath()));
1491 EXPECT_TRUE(VerifyFile(download_items[0]->GetTargetFilePath(),
1492 original_contents, origin_file_size));
1494 // Setup an incognito window.
1495 Browser* incognito = CreateIncognitoBrowser();
1496 ASSERT_TRUE(incognito);
1497 int window_count = BrowserList::GetInstance(
1498 browser()->host_desktop_type())->size();
1499 EXPECT_EQ(2, window_count);
1500 incognito->profile()->GetPrefs()->SetFilePath(
1501 prefs::kDownloadDefaultDirectory,
1502 GetDownloadsDirectory());
1503 incognito->profile()->GetPrefs()->SetFilePath(
1504 prefs::kSaveFileDefaultDirectory,
1505 GetDownloadsDirectory());
1507 download_items.clear();
1508 GetDownloads(incognito, &download_items);
1509 ASSERT_TRUE(download_items.empty());
1511 // Download a file in the incognito browser and check that it was downloaded
1512 // correctly.
1513 DownloadAndWaitWithDisposition(incognito,
1514 url,
1515 CURRENT_TAB,
1516 ui_test_utils::BROWSER_TEST_NONE);
1517 EXPECT_TRUE(incognito->window()->IsDownloadShelfVisible());
1518 GetDownloads(incognito, &download_items);
1519 ASSERT_EQ(1UL, download_items.size());
1520 ASSERT_EQ(base::FilePath(FILE_PATH_LITERAL("a_zip_file (1).zip")),
1521 download_items[0]->GetTargetFilePath().BaseName());
1522 ASSERT_TRUE(base::PathExists(download_items[0]->GetTargetFilePath()));
1523 EXPECT_TRUE(VerifyFile(download_items[0]->GetTargetFilePath(),
1524 original_contents, origin_file_size));
1527 // Navigate to a new background page, but don't download. Confirm that the
1528 // download shelf is not visible and that we have two tabs.
1529 IN_PROC_BROWSER_TEST_F(DownloadTest, DontCloseNewTab1) {
1530 // Because it's an HTML link, it should open a web page rather than
1531 // downloading.
1532 base::FilePath file1(FILE_PATH_LITERAL("download-test2.html"));
1533 GURL url(URLRequestMockHTTPJob::GetMockUrl(file1));
1535 // Open a web page and wait.
1536 ui_test_utils::NavigateToURLWithDisposition(
1537 browser(),
1538 url,
1539 NEW_BACKGROUND_TAB,
1540 ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
1542 // We should have two tabs now.
1543 EXPECT_EQ(2, browser()->tab_strip_model()->count());
1544 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
1547 // Download a file in a background tab. Verify that the tab is closed
1548 // automatically, and that the download shelf is visible in the current tab.
1549 IN_PROC_BROWSER_TEST_F(DownloadTest, CloseNewTab1) {
1550 // Download a file in a new background tab and wait. The tab is automatically
1551 // closed when the download begins.
1552 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
1553 GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
1554 DownloadAndWaitWithDisposition(
1555 browser(),
1556 url,
1557 NEW_BACKGROUND_TAB,
1560 // When the download finishes, we should still have one tab.
1561 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
1562 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1564 CheckDownload(browser(), file, file);
1567 // Open a web page in the current tab, then download a file in another tab via
1568 // a Javascript call.
1569 // Verify that we have 2 tabs, and the download shelf is visible in the current
1570 // tab.
1572 // The download_page1.html page contains an openNew() function that opens a
1573 // tab and then downloads download-test1.lib.
1574 IN_PROC_BROWSER_TEST_F(DownloadTest, DontCloseNewTab2) {
1575 // Because it's an HTML link, it should open a web page rather than
1576 // downloading.
1577 base::FilePath file1(FILE_PATH_LITERAL("download_page1.html"));
1578 GURL url(URLRequestMockHTTPJob::GetMockUrl(file1));
1580 // Open a web page and wait.
1581 ui_test_utils::NavigateToURL(browser(), url);
1583 // Download a file in a new tab and wait (via Javascript).
1584 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
1585 DownloadAndWaitWithDisposition(browser(),
1586 GURL("javascript:openNew()"),
1587 CURRENT_TAB,
1588 ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
1590 // When the download finishes, we should have two tabs.
1591 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
1592 EXPECT_EQ(2, browser()->tab_strip_model()->count());
1594 CheckDownload(browser(), file, file);
1597 // Open a web page in the current tab, open another tab via a Javascript call,
1598 // then download a file in the new tab.
1599 // Verify that we have 2 tabs, and the download shelf is visible in the current
1600 // tab.
1602 // The download_page2.html page contains an openNew() function that opens a
1603 // tab.
1604 IN_PROC_BROWSER_TEST_F(DownloadTest, DontCloseNewTab3) {
1605 // Because it's an HTML link, it should open a web page rather than
1606 // downloading.
1607 base::FilePath file1(FILE_PATH_LITERAL("download_page2.html"));
1608 GURL url1(URLRequestMockHTTPJob::GetMockUrl(file1));
1610 // Open a web page and wait.
1611 ui_test_utils::NavigateToURL(browser(), url1);
1613 // Open a new tab and wait.
1614 ui_test_utils::NavigateToURLWithDisposition(
1615 browser(),
1616 GURL("javascript:openNew()"),
1617 CURRENT_TAB,
1618 ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
1620 EXPECT_EQ(2, browser()->tab_strip_model()->count());
1622 // Download a file and wait.
1623 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
1624 GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
1625 DownloadAndWaitWithDisposition(browser(),
1626 url,
1627 CURRENT_TAB,
1628 ui_test_utils::BROWSER_TEST_NONE);
1630 // When the download finishes, we should have two tabs.
1631 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
1632 EXPECT_EQ(2, browser()->tab_strip_model()->count());
1634 CheckDownload(browser(), file, file);
1637 // Open a web page in the current tab, then download a file via Javascript,
1638 // which will do so in a temporary tab.
1639 // Verify that we have 1 tab, and the download shelf is visible.
1641 // The download_page3.html page contains an openNew() function that opens a
1642 // tab with download-test1.lib in the URL. When the URL is determined to be
1643 // a download, the tab is closed automatically.
1644 IN_PROC_BROWSER_TEST_F(DownloadTest, CloseNewTab2) {
1645 // Because it's an HTML link, it should open a web page rather than
1646 // downloading.
1647 base::FilePath file1(FILE_PATH_LITERAL("download_page3.html"));
1648 GURL url(URLRequestMockHTTPJob::GetMockUrl(file1));
1650 // Open a web page and wait.
1651 ui_test_utils::NavigateToURL(browser(), url);
1653 // Download a file and wait.
1654 // The file to download is "download-test1.lib".
1655 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
1656 DownloadAndWaitWithDisposition(browser(),
1657 GURL("javascript:openNew()"),
1658 CURRENT_TAB,
1659 ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
1661 // When the download finishes, we should still have one tab.
1662 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
1663 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1665 CheckDownload(browser(), file, file);
1668 // Open a web page in the current tab, then call Javascript via a button to
1669 // download a file in a new tab, which is closed automatically when the
1670 // download begins.
1671 // Verify that we have 1 tab, and the download shelf is visible.
1673 // The download_page4.html page contains a form with download-test1.lib as the
1674 // action.
1675 IN_PROC_BROWSER_TEST_F(DownloadTest, CloseNewTab3) {
1676 // Because it's an HTML link, it should open a web page rather than
1677 // downloading.
1678 base::FilePath file1(FILE_PATH_LITERAL("download_page4.html"));
1679 GURL url(URLRequestMockHTTPJob::GetMockUrl(file1));
1681 // Open a web page and wait.
1682 ui_test_utils::NavigateToURL(browser(), url);
1684 // Download a file in a new tab and wait. The tab will automatically close
1685 // when the download begins.
1686 // The file to download is "download-test1.lib".
1687 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
1688 DownloadAndWaitWithDisposition(
1689 browser(),
1690 GURL("javascript:document.getElementById('form').submit()"),
1691 CURRENT_TAB,
1692 ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
1694 // When the download finishes, we should still have one tab.
1695 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
1696 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1698 CheckDownload(browser(), file, file);
1701 // Download a file in a new window.
1702 // Verify that we have 2 windows, and the download shelf is not visible in the
1703 // first window, but is visible in the second window.
1704 // Close the new window.
1705 // Verify that we have 1 window, and the download shelf is not visible.
1707 // Regression test for http://crbug.com/44454
1708 IN_PROC_BROWSER_TEST_F(DownloadTest, NewWindow) {
1709 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
1710 GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
1711 #if !defined(OS_MACOSX)
1712 // See below.
1713 Browser* first_browser = browser();
1714 #endif
1716 // Download a file in a new window and wait.
1717 DownloadAndWaitWithDisposition(browser(),
1718 url,
1719 NEW_WINDOW,
1720 ui_test_utils::BROWSER_TEST_NONE);
1722 // When the download finishes, the download shelf SHOULD NOT be visible in
1723 // the first window.
1724 ExpectWindowCountAfterDownload(2);
1725 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1726 // Download shelf should close. Download panel stays open on ChromeOS.
1727 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
1729 // The download shelf SHOULD be visible in the second window.
1730 std::set<Browser*> original_browsers;
1731 original_browsers.insert(browser());
1732 Browser* download_browser =
1733 ui_test_utils::GetBrowserNotInSet(original_browsers);
1734 ASSERT_TRUE(download_browser != NULL);
1735 EXPECT_NE(download_browser, browser());
1736 EXPECT_EQ(1, download_browser->tab_strip_model()->count());
1737 EXPECT_TRUE(download_browser->window()->IsDownloadShelfVisible());
1739 #if !defined(OS_MACOSX)
1740 // On Mac OS X, the UI window close is delayed until the outermost
1741 // message loop runs. So it isn't possible to get a BROWSER_CLOSED
1742 // notification inside of a test.
1743 content::WindowedNotificationObserver signal(
1744 chrome::NOTIFICATION_BROWSER_CLOSED,
1745 content::Source<Browser>(download_browser));
1746 #endif
1748 // Close the new window.
1749 chrome::CloseWindow(download_browser);
1751 #if !defined(OS_MACOSX)
1752 signal.Wait();
1753 EXPECT_EQ(first_browser, browser());
1754 ExpectWindowCountAfterDownload(1);
1755 #endif
1757 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1758 // Download shelf should close. Download panel stays open on ChromeOS.
1759 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
1761 CheckDownload(browser(), file, file);
1764 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadHistoryCheck) {
1765 GURL download_url(URLRequestSlowDownloadJob::kKnownSizeUrl);
1766 base::FilePath file(net::GenerateFileName(download_url,
1767 std::string(),
1768 std::string(),
1769 std::string(),
1770 std::string(),
1771 std::string()));
1773 // We use the server so that we can get a redirect and test url_chain
1774 // persistence.
1775 ASSERT_TRUE(test_server()->Start());
1776 GURL redirect_url = test_server()->GetURL(
1777 "server-redirect?" + download_url.spec());
1779 // Download the url and wait until the object has been stored.
1780 base::Time start(base::Time::Now());
1781 HistoryObserver observer(browser()->profile());
1782 observer.SetFilterCallback(base::Bind(&HasDataAndName));
1783 ui_test_utils::NavigateToURL(browser(), redirect_url);
1784 observer.WaitForStored();
1786 // Get the details on what was stored into the history.
1787 scoped_ptr<std::vector<history::DownloadRow> > downloads_in_database;
1788 ASSERT_TRUE(DownloadsHistoryDataCollector(
1789 browser()->profile()).WaitForDownloadInfo(&downloads_in_database));
1790 ASSERT_EQ(1u, downloads_in_database->size());
1792 // Confirm history storage is what you expect for a partially completed
1793 // slow download job.
1794 history::DownloadRow& row(downloads_in_database->at(0));
1795 EXPECT_EQ(DestinationFile(browser(), file), row.target_path);
1796 EXPECT_EQ(DownloadTargetDeterminer::GetCrDownloadPath(
1797 DestinationFile(browser(), file)),
1798 row.current_path);
1799 ASSERT_EQ(2u, row.url_chain.size());
1800 EXPECT_EQ(redirect_url.spec(), row.url_chain[0].spec());
1801 EXPECT_EQ(download_url.spec(), row.url_chain[1].spec());
1802 EXPECT_EQ(content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, row.danger_type);
1803 EXPECT_LE(start, row.start_time);
1804 EXPECT_EQ(URLRequestSlowDownloadJob::kFirstDownloadSize, row.received_bytes);
1805 EXPECT_EQ(URLRequestSlowDownloadJob::kFirstDownloadSize
1806 + URLRequestSlowDownloadJob::kSecondDownloadSize, row.total_bytes);
1807 EXPECT_EQ(content::DownloadItem::IN_PROGRESS, row.state);
1808 EXPECT_FALSE(row.opened);
1810 // Finish the download. We're ok relying on the history to be flushed
1811 // at this point as our queries will be behind the history updates
1812 // invoked by completion.
1813 scoped_ptr<content::DownloadTestObserver> download_observer(
1814 CreateWaiter(browser(), 1));
1815 ui_test_utils::NavigateToURL(browser(),
1816 GURL(URLRequestSlowDownloadJob::kErrorDownloadUrl));
1817 download_observer->WaitForFinished();
1818 EXPECT_EQ(1u, download_observer->NumDownloadsSeenInState(
1819 DownloadItem::INTERRUPTED));
1820 base::Time end(base::Time::Now());
1822 // Get what was stored in the history.
1823 ASSERT_TRUE(DownloadsHistoryDataCollector(
1824 browser()->profile()).WaitForDownloadInfo(&downloads_in_database));
1825 ASSERT_EQ(1u, downloads_in_database->size());
1827 // Confirm history storage is what you expect for an interrupted slow download
1828 // job. The download isn't continuable, so there's no intermediate file.
1829 history::DownloadRow& row1(downloads_in_database->at(0));
1830 EXPECT_EQ(DestinationFile(browser(), file), row1.target_path);
1831 EXPECT_TRUE(row1.current_path.empty());
1832 ASSERT_EQ(2u, row1.url_chain.size());
1833 EXPECT_EQ(redirect_url.spec(), row1.url_chain[0].spec());
1834 EXPECT_EQ(download_url.spec(), row1.url_chain[1].spec());
1835 EXPECT_EQ(content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, row1.danger_type);
1836 EXPECT_LE(start, row1.start_time);
1837 EXPECT_GE(end, row1.end_time);
1838 EXPECT_EQ(URLRequestSlowDownloadJob::kFirstDownloadSize,
1839 row1.received_bytes);
1840 EXPECT_EQ(URLRequestSlowDownloadJob::kFirstDownloadSize
1841 + URLRequestSlowDownloadJob::kSecondDownloadSize, row1.total_bytes);
1842 EXPECT_EQ(content::DownloadItem::INTERRUPTED, row1.state);
1843 EXPECT_EQ(content::DOWNLOAD_INTERRUPT_REASON_NETWORK_FAILED,
1844 row1.interrupt_reason);
1845 EXPECT_FALSE(row1.opened);
1848 // Make sure a dangerous file shows up properly in the history.
1849 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadHistoryDangerCheck) {
1850 #if defined(OS_WIN) && defined(USE_ASH)
1851 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
1852 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshBrowserTests))
1853 return;
1854 #endif
1856 // .swf file so that it's dangerous on all platforms (including CrOS).
1857 base::FilePath file(FILE_PATH_LITERAL("downloads/dangerous/dangerous.swf"));
1858 GURL download_url(URLRequestMockHTTPJob::GetMockUrl(file));
1860 // Download the url and wait until the object has been stored.
1861 scoped_ptr<content::DownloadTestObserver> download_observer(
1862 new content::DownloadTestObserverTerminal(
1863 DownloadManagerForBrowser(browser()), 1,
1864 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_IGNORE));
1865 base::Time start(base::Time::Now());
1866 HistoryObserver observer(browser()->profile());
1867 observer.SetFilterCallback(base::Bind(&HasDataAndName));
1868 ui_test_utils::NavigateToURL(browser(), download_url);
1869 observer.WaitForStored();
1871 // Get the details on what was stored into the history.
1872 scoped_ptr<std::vector<history::DownloadRow> > downloads_in_database;
1873 ASSERT_TRUE(DownloadsHistoryDataCollector(
1874 browser()->profile()).WaitForDownloadInfo(&downloads_in_database));
1875 ASSERT_EQ(1u, downloads_in_database->size());
1877 // Confirm history storage is what you expect for an unvalidated
1878 // dangerous file.
1879 history::DownloadRow& row(downloads_in_database->at(0));
1880 EXPECT_EQ(DestinationFile(browser(), file), row.target_path);
1881 EXPECT_NE(DownloadTargetDeterminer::GetCrDownloadPath(
1882 DestinationFile(browser(), file)),
1883 row.current_path);
1884 EXPECT_EQ(content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE, row.danger_type);
1885 EXPECT_LE(start, row.start_time);
1886 EXPECT_EQ(content::DownloadItem::IN_PROGRESS, row.state);
1887 EXPECT_FALSE(row.opened);
1889 // Validate the download and wait for it to finish.
1890 std::vector<DownloadItem*> downloads;
1891 DownloadManagerForBrowser(browser())->GetAllDownloads(&downloads);
1892 ASSERT_EQ(1u, downloads.size());
1893 downloads[0]->ValidateDangerousDownload();
1894 download_observer->WaitForFinished();
1896 // Get history details and confirm it's what you expect.
1897 downloads_in_database->clear();
1898 ASSERT_TRUE(DownloadsHistoryDataCollector(
1899 browser()->profile()).WaitForDownloadInfo(&downloads_in_database));
1900 ASSERT_EQ(1u, downloads_in_database->size());
1901 history::DownloadRow& row1(downloads_in_database->at(0));
1902 EXPECT_EQ(DestinationFile(browser(), file), row1.target_path);
1903 EXPECT_EQ(DestinationFile(browser(), file), row1.current_path);
1904 EXPECT_EQ(content::DOWNLOAD_DANGER_TYPE_USER_VALIDATED, row1.danger_type);
1905 EXPECT_LE(start, row1.start_time);
1906 EXPECT_EQ(content::DownloadItem::COMPLETE, row1.state);
1907 EXPECT_FALSE(row1.opened);
1908 // Not checking file size--not relevant to the point of the test, and
1909 // the file size is actually different on Windows and other platforms,
1910 // because for source control simplicity it's actually a text file, and
1911 // there are CRLF transformations for those files.
1914 IN_PROC_BROWSER_TEST_F(DownloadTest, PRE_DownloadTest_History) {
1915 // Download a file and wait for it to be stored.
1916 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
1917 GURL download_url(URLRequestMockHTTPJob::GetMockUrl(file));
1918 HistoryObserver observer(browser()->profile());
1919 DownloadAndWait(browser(), download_url);
1920 observer.WaitForStored();
1921 HistoryServiceFactory::GetForProfile(
1922 browser()->profile(), Profile::IMPLICIT_ACCESS)->FlushForTest(
1923 base::Bind(&base::MessageLoop::Quit,
1924 base::Unretained(base::MessageLoop::current()->current())));
1925 content::RunMessageLoop();
1928 #if defined(OS_CHROMEOS)
1929 #define MAYBE_DownloadTest_History DISABLED_DownloadTest_History
1930 #else
1931 #define MAYBE_DownloadTest_History DownloadTest_History
1932 #endif
1933 IN_PROC_BROWSER_TEST_F(DownloadTest, MAYBE_DownloadTest_History) {
1934 // This starts up right after PRE_DownloadTest_History and shares the same
1935 // profile directory.
1936 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
1937 GURL download_url(URLRequestMockHTTPJob::GetMockUrl(file));
1938 std::vector<DownloadItem*> downloads;
1939 content::DownloadManager* manager = DownloadManagerForBrowser(browser());
1941 // Wait for the history to be loaded with a single DownloadItem. Check that
1942 // it's the file that was downloaded in PRE_DownloadTest_History.
1943 CreatedObserver created_observer(manager);
1944 created_observer.Wait();
1945 manager->GetAllDownloads(&downloads);
1946 ASSERT_EQ(1UL, downloads.size());
1947 DownloadItem* item = downloads[0];
1948 EXPECT_EQ(file.value(), item->GetFullPath().BaseName().value());
1949 EXPECT_EQ(file.value(), item->GetTargetFilePath().BaseName().value());
1950 EXPECT_EQ(download_url, item->GetURL());
1951 // The following are set by download-test1.lib.mock-http-headers.
1952 std::string etag = item->GetETag();
1953 TrimWhitespaceASCII(etag, TRIM_ALL, &etag);
1954 EXPECT_EQ("abracadabra", etag);
1956 std::string last_modified = item->GetLastModifiedTime();
1957 TrimWhitespaceASCII(last_modified, TRIM_ALL, &last_modified);
1958 EXPECT_EQ("Mon, 13 Nov 2006 20:31:09 GMT", last_modified);
1961 // Test for crbug.com/14505. This tests that chrome:// urls are still functional
1962 // after download of a file while viewing another chrome://.
1963 IN_PROC_BROWSER_TEST_F(DownloadTest, ChromeURLAfterDownload) {
1964 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
1965 GURL download_url(URLRequestMockHTTPJob::GetMockUrl(file));
1966 GURL flags_url(chrome::kChromeUIFlagsURL);
1967 GURL extensions_url(chrome::kChromeUIExtensionsFrameURL);
1969 ui_test_utils::NavigateToURL(browser(), flags_url);
1970 DownloadAndWait(browser(), download_url);
1971 ui_test_utils::NavigateToURL(browser(), extensions_url);
1972 WebContents* contents =
1973 browser()->tab_strip_model()->GetActiveWebContents();
1974 ASSERT_TRUE(contents);
1975 bool webui_responded = false;
1976 EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
1977 contents,
1978 "window.domAutomationController.send(window.webuiResponded);",
1979 &webui_responded));
1980 EXPECT_TRUE(webui_responded);
1983 // Test for crbug.com/12745. This tests that if a download is initiated from
1984 // a chrome:// page that has registered and onunload handler, the browser
1985 // will be able to close.
1986 IN_PROC_BROWSER_TEST_F(DownloadTest, BrowserCloseAfterDownload) {
1987 GURL downloads_url(chrome::kChromeUIFlagsURL);
1988 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
1989 GURL download_url(URLRequestMockHTTPJob::GetMockUrl(file));
1991 ui_test_utils::NavigateToURL(browser(), downloads_url);
1992 WebContents* contents = browser()->tab_strip_model()->GetActiveWebContents();
1993 ASSERT_TRUE(contents);
1994 bool result = false;
1995 EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
1996 contents,
1997 "window.onunload = function() { var do_nothing = 0; }; "
1998 "window.domAutomationController.send(true);",
1999 &result));
2000 EXPECT_TRUE(result);
2002 DownloadAndWait(browser(), download_url);
2004 content::WindowedNotificationObserver signal(
2005 chrome::NOTIFICATION_BROWSER_CLOSED,
2006 content::Source<Browser>(browser()));
2007 chrome::CloseWindow(browser());
2008 signal.Wait();
2011 // Test to make sure the 'download' attribute in anchor tag is respected.
2012 IN_PROC_BROWSER_TEST_F(DownloadTest, AnchorDownloadTag) {
2013 base::FilePath file(FILE_PATH_LITERAL("download-anchor-attrib.html"));
2014 GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
2016 // Create a download, wait until it's complete, and confirm
2017 // we're in the expected state.
2018 scoped_ptr<content::DownloadTestObserver> observer(
2019 CreateWaiter(browser(), 1));
2020 ui_test_utils::NavigateToURL(browser(), url);
2021 observer->WaitForFinished();
2022 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::COMPLETE));
2023 CheckDownloadStates(1, DownloadItem::COMPLETE);
2025 // Confirm the downloaded data exists.
2026 base::FilePath downloaded_file = GetDownloadDirectory(browser());
2027 downloaded_file = downloaded_file.Append(FILE_PATH_LITERAL("a_red_dot.png"));
2028 EXPECT_TRUE(base::PathExists(downloaded_file));
2031 // Test to make sure auto-open works.
2032 IN_PROC_BROWSER_TEST_F(DownloadTest, AutoOpen) {
2033 base::FilePath file(FILE_PATH_LITERAL("download-autoopen.txt"));
2034 GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
2036 ASSERT_TRUE(
2037 GetDownloadPrefs(browser())->EnableAutoOpenBasedOnExtension(file));
2039 DownloadAndWait(browser(), url);
2041 // Find the download and confirm it was opened.
2042 std::vector<DownloadItem*> downloads;
2043 DownloadManagerForBrowser(browser())->GetAllDownloads(&downloads);
2044 ASSERT_EQ(1u, downloads.size());
2045 EXPECT_EQ(DownloadItem::COMPLETE, downloads[0]->GetState());
2047 // Unfortunately, this will block forever, causing a timeout, if
2048 // the download is never opened.
2049 content::DownloadUpdatedObserver(
2050 downloads[0], base::Bind(&WasAutoOpened)).WaitForEvent();
2051 EXPECT_TRUE(downloads[0]->GetOpened()); // Confirm it anyway.
2053 // As long as we're here, confirmed everything else is good.
2054 EXPECT_EQ(1, browser()->tab_strip_model()->count());
2055 CheckDownload(browser(), file, file);
2056 // Download shelf should close. Download panel stays open on ChromeOS.
2057 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
2060 // Download an extension. Expect a dangerous download warning.
2061 // Deny the download.
2062 IN_PROC_BROWSER_TEST_F(DownloadTest, CrxDenyInstall) {
2063 FeatureSwitch::ScopedOverride enable_easy_off_store_install(
2064 FeatureSwitch::easy_off_store_install(), true);
2066 GURL extension_url(URLRequestMockHTTPJob::GetMockUrl(kGoodCrxPath));
2068 scoped_ptr<content::DownloadTestObserver> observer(
2069 DangerousDownloadWaiter(
2070 browser(), 1,
2071 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_DENY));
2072 ui_test_utils::NavigateToURL(browser(), extension_url);
2074 observer->WaitForFinished();
2075 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::CANCELLED));
2076 EXPECT_EQ(1u, observer->NumDangerousDownloadsSeen());
2078 // Download shelf should close.
2079 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
2081 // Check that the CRX is not installed.
2082 ExtensionService* extension_service = extensions::ExtensionSystem::Get(
2083 browser()->profile())->extension_service();
2084 ASSERT_FALSE(extension_service->GetExtensionById(kGoodCrxId, false));
2087 // Download an extension. Expect a dangerous download warning.
2088 // Allow the download, deny the install.
2089 IN_PROC_BROWSER_TEST_F(DownloadTest, CrxInstallDenysPermissions) {
2090 FeatureSwitch::ScopedOverride enable_easy_off_store_install(
2091 FeatureSwitch::easy_off_store_install(), true);
2093 GURL extension_url(URLRequestMockHTTPJob::GetMockUrl(kGoodCrxPath));
2095 // Install a mock install UI that simulates a user denying permission to
2096 // finish the install.
2097 download_crx_util::SetMockInstallPromptForTesting(
2098 scoped_ptr<ExtensionInstallPrompt>(
2099 new MockAbortExtensionInstallPrompt()));
2101 scoped_ptr<content::DownloadTestObserver> observer(
2102 DangerousDownloadWaiter(
2103 browser(), 1,
2104 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_ACCEPT));
2105 ui_test_utils::NavigateToURL(browser(), extension_url);
2107 observer->WaitForFinished();
2108 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::COMPLETE));
2109 CheckDownloadStates(1, DownloadItem::COMPLETE);
2110 EXPECT_EQ(1u, observer->NumDangerousDownloadsSeen());
2112 // Download shelf should close from auto-open.
2113 content::DownloadManager::DownloadVector downloads;
2114 DownloadManagerForBrowser(browser())->GetAllDownloads(&downloads);
2115 ASSERT_EQ(1u, downloads.size());
2116 content::DownloadUpdatedObserver(
2117 downloads[0], base::Bind(&WasAutoOpened)).WaitForEvent();
2118 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
2120 // Check that the extension was not installed.
2121 ExtensionService* extension_service = extensions::ExtensionSystem::Get(
2122 browser()->profile())->extension_service();
2123 ASSERT_FALSE(extension_service->GetExtensionById(kGoodCrxId, false));
2126 // Download an extension. Expect a dangerous download warning.
2127 // Allow the download, and the install.
2128 IN_PROC_BROWSER_TEST_F(DownloadTest, CrxInstallAcceptPermissions) {
2129 FeatureSwitch::ScopedOverride enable_easy_off_store_install(
2130 FeatureSwitch::easy_off_store_install(), true);
2132 GURL extension_url(URLRequestMockHTTPJob::GetMockUrl(kGoodCrxPath));
2134 // Install a mock install UI that simulates a user allowing permission to
2135 // finish the install.
2136 SetAllowMockInstallPrompt();
2138 scoped_ptr<content::DownloadTestObserver> observer(
2139 DangerousDownloadWaiter(
2140 browser(), 1,
2141 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_ACCEPT));
2142 ui_test_utils::NavigateToURL(browser(), extension_url);
2144 observer->WaitForFinished();
2145 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::COMPLETE));
2146 CheckDownloadStates(1, DownloadItem::COMPLETE);
2147 EXPECT_EQ(1u, observer->NumDangerousDownloadsSeen());
2149 // Download shelf should close from auto-open.
2150 content::DownloadManager::DownloadVector downloads;
2151 DownloadManagerForBrowser(browser())->GetAllDownloads(&downloads);
2152 ASSERT_EQ(1u, downloads.size());
2153 content::DownloadUpdatedObserver(
2154 downloads[0], base::Bind(&WasAutoOpened)).WaitForEvent();
2155 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
2157 // Check that the extension was installed.
2158 ExtensionService* extension_service = extensions::ExtensionSystem::Get(
2159 browser()->profile())->extension_service();
2160 ASSERT_TRUE(extension_service->GetExtensionById(kGoodCrxId, false));
2163 // Test installing a CRX that fails integrity checks.
2164 IN_PROC_BROWSER_TEST_F(DownloadTest, CrxInvalid) {
2165 base::FilePath file(FILE_PATH_LITERAL("extensions/bad_signature.crx"));
2166 GURL extension_url(URLRequestMockHTTPJob::GetMockUrl(file));
2168 // Install a mock install UI that simulates a user allowing permission to
2169 // finish the install, and dismisses any error message. We check that the
2170 // install failed below.
2171 SetAllowMockInstallPrompt();
2173 scoped_ptr<content::DownloadTestObserver> observer(
2174 DangerousDownloadWaiter(
2175 browser(), 1,
2176 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_ACCEPT));
2177 ui_test_utils::NavigateToURL(browser(), extension_url);
2179 observer->WaitForFinished();
2180 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::COMPLETE));
2181 CheckDownloadStates(1, DownloadItem::COMPLETE);
2183 // Check that the extension was not installed.
2184 ExtensionService* extension_service = extensions::ExtensionSystem::Get(
2185 browser()->profile())->extension_service();
2186 ASSERT_FALSE(extension_service->GetExtensionById(kGoodCrxId, false));
2189 // Install a large (100kb) theme.
2190 IN_PROC_BROWSER_TEST_F(DownloadTest, CrxLargeTheme) {
2191 FeatureSwitch::ScopedOverride enable_easy_off_store_install(
2192 FeatureSwitch::easy_off_store_install(), true);
2194 GURL extension_url(URLRequestMockHTTPJob::GetMockUrl(kLargeThemePath));
2196 // Install a mock install UI that simulates a user allowing permission to
2197 // finish the install.
2198 SetAllowMockInstallPrompt();
2200 scoped_ptr<content::DownloadTestObserver> observer(
2201 DangerousDownloadWaiter(
2202 browser(), 1,
2203 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_ACCEPT));
2204 ui_test_utils::NavigateToURL(browser(), extension_url);
2206 observer->WaitForFinished();
2207 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::COMPLETE));
2208 CheckDownloadStates(1, DownloadItem::COMPLETE);
2209 EXPECT_EQ(1u, observer->NumDangerousDownloadsSeen());
2211 // Download shelf should close from auto-open.
2212 content::DownloadManager::DownloadVector downloads;
2213 DownloadManagerForBrowser(browser())->GetAllDownloads(&downloads);
2214 ASSERT_EQ(1u, downloads.size());
2215 content::DownloadUpdatedObserver(
2216 downloads[0], base::Bind(&WasAutoOpened)).WaitForEvent();
2217 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
2219 // Check that the extension was installed.
2220 ExtensionService* extension_service = extensions::ExtensionSystem::Get(
2221 browser()->profile())->extension_service();
2222 ASSERT_TRUE(extension_service->GetExtensionById(kLargeThemeCrxId, false));
2225 // Tests for download initiation functions.
2226 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadUrl) {
2227 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
2228 GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
2230 // DownloadUrl always prompts; return acceptance of whatever it prompts.
2231 EnableFileChooser(true);
2233 WebContents* web_contents =
2234 browser()->tab_strip_model()->GetActiveWebContents();
2235 ASSERT_TRUE(web_contents);
2237 content::DownloadTestObserver* observer(
2238 new content::DownloadTestObserverTerminal(
2239 DownloadManagerForBrowser(browser()), 1,
2240 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL));
2241 scoped_ptr<DownloadUrlParameters> params(
2242 DownloadUrlParameters::FromWebContents(web_contents, url));
2243 params->set_prompt(true);
2244 DownloadManagerForBrowser(browser())->DownloadUrl(params.Pass());
2245 observer->WaitForFinished();
2246 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::COMPLETE));
2247 CheckDownloadStates(1, DownloadItem::COMPLETE);
2248 EXPECT_TRUE(DidShowFileChooser());
2250 // Check state.
2251 EXPECT_EQ(1, browser()->tab_strip_model()->count());
2252 ASSERT_TRUE(CheckDownload(browser(), file, file));
2253 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
2256 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadUrlToPath) {
2257 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
2258 GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
2260 WebContents* web_contents =
2261 browser()->tab_strip_model()->GetActiveWebContents();
2262 ASSERT_TRUE(web_contents);
2264 base::ScopedTempDir other_directory;
2265 ASSERT_TRUE(other_directory.CreateUniqueTempDir());
2266 base::FilePath target_file_full_path
2267 = other_directory.path().Append(file.BaseName());
2268 content::DownloadTestObserver* observer(CreateWaiter(browser(), 1));
2269 scoped_ptr<DownloadUrlParameters> params(
2270 DownloadUrlParameters::FromWebContents(web_contents, url));
2271 params->set_file_path(target_file_full_path);
2272 DownloadManagerForBrowser(browser())->DownloadUrl(params.Pass());
2273 observer->WaitForFinished();
2274 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::COMPLETE));
2276 // Check state.
2277 EXPECT_EQ(1, browser()->tab_strip_model()->count());
2278 ASSERT_TRUE(CheckDownloadFullPaths(browser(),
2279 target_file_full_path,
2280 OriginFile(file)));
2282 // Temporary are treated as auto-opened, and after that open won't be
2283 // visible; wait for auto-open and confirm not visible.
2284 std::vector<DownloadItem*> downloads;
2285 DownloadManagerForBrowser(browser())->GetAllDownloads(&downloads);
2286 ASSERT_EQ(1u, downloads.size());
2287 content::DownloadUpdatedObserver(
2288 downloads[0], base::Bind(&WasAutoOpened)).WaitForEvent();
2289 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
2292 IN_PROC_BROWSER_TEST_F(DownloadTest, SavePageNonHTMLViaGet) {
2293 // Do initial setup.
2294 ASSERT_TRUE(test_server()->Start());
2295 EnableFileChooser(true);
2296 std::vector<DownloadItem*> download_items;
2297 GetDownloads(browser(), &download_items);
2298 ASSERT_TRUE(download_items.empty());
2300 // Navigate to a non-HTML resource. The resource also has
2301 // Cache-Control: no-cache set, which normally requires revalidation
2302 // each time.
2303 GURL url = test_server()->GetURL("files/downloads/image.jpg");
2304 ASSERT_TRUE(url.is_valid());
2305 ui_test_utils::NavigateToURL(browser(), url);
2307 // Stop the test server, and then try to save the page. If cache validation
2308 // is not bypassed then this will fail since the server is no longer
2309 // reachable.
2310 ASSERT_TRUE(test_server()->Stop());
2311 scoped_ptr<content::DownloadTestObserver> waiter(
2312 new content::DownloadTestObserverTerminal(
2313 DownloadManagerForBrowser(browser()), 1,
2314 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL));
2315 chrome::SavePage(browser());
2316 waiter->WaitForFinished();
2317 EXPECT_EQ(1u, waiter->NumDownloadsSeenInState(DownloadItem::COMPLETE));
2318 CheckDownloadStates(1, DownloadItem::COMPLETE);
2320 // Validate that the correct file was downloaded.
2321 GetDownloads(browser(), &download_items);
2322 EXPECT_TRUE(DidShowFileChooser());
2323 ASSERT_EQ(1u, download_items.size());
2324 ASSERT_EQ(url, download_items[0]->GetOriginalUrl());
2326 // Try to download it via a context menu.
2327 scoped_ptr<content::DownloadTestObserver> waiter_context_menu(
2328 new content::DownloadTestObserverTerminal(
2329 DownloadManagerForBrowser(browser()), 1,
2330 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL));
2331 content::ContextMenuParams context_menu_params;
2332 context_menu_params.media_type = blink::WebContextMenuData::MediaTypeImage;
2333 context_menu_params.src_url = url;
2334 context_menu_params.page_url = url;
2335 TestRenderViewContextMenu menu(
2336 browser()->tab_strip_model()->GetActiveWebContents(),
2337 context_menu_params);
2338 menu.Init();
2339 menu.ExecuteCommand(IDC_CONTENT_CONTEXT_SAVEIMAGEAS, 0);
2340 waiter_context_menu->WaitForFinished();
2341 EXPECT_EQ(
2342 1u, waiter_context_menu->NumDownloadsSeenInState(DownloadItem::COMPLETE));
2343 CheckDownloadStates(2, DownloadItem::COMPLETE);
2345 // Validate that the correct file was downloaded via the context menu.
2346 download_items.clear();
2347 GetDownloads(browser(), &download_items);
2348 EXPECT_TRUE(DidShowFileChooser());
2349 ASSERT_EQ(2u, download_items.size());
2350 ASSERT_EQ(url, download_items[0]->GetOriginalUrl());
2351 ASSERT_EQ(url, download_items[1]->GetOriginalUrl());
2354 IN_PROC_BROWSER_TEST_F(DownloadTest, SavePageNonHTMLViaPost) {
2355 // Do initial setup.
2356 ASSERT_TRUE(test_server()->Start());
2357 EnableFileChooser(true);
2358 std::vector<DownloadItem*> download_items;
2359 GetDownloads(browser(), &download_items);
2360 ASSERT_TRUE(download_items.empty());
2362 // Navigate to a form page.
2363 GURL form_url = test_server()->GetURL(
2364 "files/downloads/form_page_to_post.html");
2365 ASSERT_TRUE(form_url.is_valid());
2366 ui_test_utils::NavigateToURL(browser(), form_url);
2368 // Submit the form. This will send a POST reqeuest, and the response is a
2369 // JPEG image. The resource also has Cache-Control: no-cache set,
2370 // which normally requires revalidation each time.
2371 GURL jpeg_url = test_server()->GetURL("files/post/downloads/image.jpg");
2372 ASSERT_TRUE(jpeg_url.is_valid());
2373 WebContents* web_contents =
2374 browser()->tab_strip_model()->GetActiveWebContents();
2375 ASSERT_TRUE(web_contents != NULL);
2376 content::WindowedNotificationObserver observer(
2377 content::NOTIFICATION_NAV_ENTRY_COMMITTED,
2378 content::Source<content::NavigationController>(
2379 &web_contents->GetController()));
2380 content::RenderViewHost* render_view_host = web_contents->GetRenderViewHost();
2381 ASSERT_TRUE(render_view_host != NULL);
2382 render_view_host->ExecuteJavascriptInWebFrame(
2383 base::string16(), base::ASCIIToUTF16("SubmitForm()"));
2384 observer.Wait();
2385 EXPECT_EQ(jpeg_url, web_contents->GetURL());
2387 // Stop the test server, and then try to save the page. If cache validation
2388 // is not bypassed then this will fail since the server is no longer
2389 // reachable. This will also fail if it tries to be retrieved via "GET"
2390 // rather than "POST".
2391 ASSERT_TRUE(test_server()->Stop());
2392 scoped_ptr<content::DownloadTestObserver> waiter(
2393 new content::DownloadTestObserverTerminal(
2394 DownloadManagerForBrowser(browser()), 1,
2395 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL));
2396 chrome::SavePage(browser());
2397 waiter->WaitForFinished();
2398 EXPECT_EQ(1u, waiter->NumDownloadsSeenInState(DownloadItem::COMPLETE));
2399 CheckDownloadStates(1, DownloadItem::COMPLETE);
2401 // Validate that the correct file was downloaded.
2402 GetDownloads(browser(), &download_items);
2403 EXPECT_TRUE(DidShowFileChooser());
2404 ASSERT_EQ(1u, download_items.size());
2405 ASSERT_EQ(jpeg_url, download_items[0]->GetOriginalUrl());
2407 // Try to download it via a context menu.
2408 scoped_ptr<content::DownloadTestObserver> waiter_context_menu(
2409 new content::DownloadTestObserverTerminal(
2410 DownloadManagerForBrowser(browser()), 1,
2411 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL));
2412 content::ContextMenuParams context_menu_params;
2413 context_menu_params.media_type = blink::WebContextMenuData::MediaTypeImage;
2414 context_menu_params.src_url = jpeg_url;
2415 context_menu_params.page_url = jpeg_url;
2416 TestRenderViewContextMenu menu(web_contents, context_menu_params);
2417 menu.Init();
2418 menu.ExecuteCommand(IDC_CONTENT_CONTEXT_SAVEIMAGEAS, 0);
2419 waiter_context_menu->WaitForFinished();
2420 EXPECT_EQ(
2421 1u, waiter_context_menu->NumDownloadsSeenInState(DownloadItem::COMPLETE));
2422 CheckDownloadStates(2, DownloadItem::COMPLETE);
2424 // Validate that the correct file was downloaded via the context menu.
2425 download_items.clear();
2426 GetDownloads(browser(), &download_items);
2427 EXPECT_TRUE(DidShowFileChooser());
2428 ASSERT_EQ(2u, download_items.size());
2429 ASSERT_EQ(jpeg_url, download_items[0]->GetOriginalUrl());
2430 ASSERT_EQ(jpeg_url, download_items[1]->GetOriginalUrl());
2433 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadErrorsServer) {
2434 DownloadInfo download_info[] = {
2435 { // Normal navigated download.
2436 "a_zip_file.zip",
2437 DOWNLOAD_NAVIGATE,
2438 content::DOWNLOAD_INTERRUPT_REASON_NONE,
2439 true,
2440 false
2442 { // Normal direct download.
2443 "a_zip_file.zip",
2444 DOWNLOAD_DIRECT,
2445 content::DOWNLOAD_INTERRUPT_REASON_NONE,
2446 true,
2447 false
2449 { // Direct download with 404 error.
2450 "there_IS_no_spoon.zip",
2451 DOWNLOAD_DIRECT,
2452 content::DOWNLOAD_INTERRUPT_REASON_SERVER_BAD_CONTENT,
2453 true,
2454 false
2456 { // Navigated download with 404 error.
2457 "there_IS_no_spoon.zip",
2458 DOWNLOAD_NAVIGATE,
2459 content::DOWNLOAD_INTERRUPT_REASON_SERVER_BAD_CONTENT,
2460 false,
2461 false
2463 { // Direct download with 400 error.
2464 "zip_file_not_found.zip",
2465 DOWNLOAD_DIRECT,
2466 content::DOWNLOAD_INTERRUPT_REASON_SERVER_FAILED,
2467 true,
2468 false
2470 { // Navigated download with 400 error.
2471 "zip_file_not_found.zip",
2472 DOWNLOAD_NAVIGATE,
2473 content::DOWNLOAD_INTERRUPT_REASON_SERVER_FAILED,
2474 false,
2475 false
2479 DownloadFilesCheckErrors(ARRAYSIZE_UNSAFE(download_info), download_info);
2482 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadErrorsFile) {
2483 FileErrorInjectInfo error_info[] = {
2484 { // Navigated download with injected "Disk full" error in Initialize().
2485 { "a_zip_file.zip",
2486 DOWNLOAD_NAVIGATE,
2487 content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE,
2492 content::TestFileErrorInjector::FILE_OPERATION_INITIALIZE,
2494 content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE,
2497 { // Direct download with injected "Disk full" error in Initialize().
2498 { "a_zip_file.zip",
2499 DOWNLOAD_DIRECT,
2500 content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE,
2505 content::TestFileErrorInjector::FILE_OPERATION_INITIALIZE,
2507 content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE,
2510 { // Navigated download with injected "Disk full" error in Write().
2511 { "a_zip_file.zip",
2512 DOWNLOAD_NAVIGATE,
2513 content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE,
2518 content::TestFileErrorInjector::FILE_OPERATION_WRITE,
2520 content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE,
2523 { // Direct download with injected "Disk full" error in Write().
2524 { "a_zip_file.zip",
2525 DOWNLOAD_DIRECT,
2526 content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE,
2531 content::TestFileErrorInjector::FILE_OPERATION_WRITE,
2533 content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE,
2536 { // Navigated download with injected "Failed" error in Initialize().
2537 { "a_zip_file.zip",
2538 DOWNLOAD_NAVIGATE,
2539 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED,
2544 content::TestFileErrorInjector::FILE_OPERATION_INITIALIZE,
2546 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED,
2549 { // Direct download with injected "Failed" error in Initialize().
2550 { "a_zip_file.zip",
2551 DOWNLOAD_DIRECT,
2552 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED,
2557 content::TestFileErrorInjector::FILE_OPERATION_INITIALIZE,
2559 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED,
2562 { // Navigated download with injected "Failed" error in Write().
2563 { "a_zip_file.zip",
2564 DOWNLOAD_NAVIGATE,
2565 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED,
2570 content::TestFileErrorInjector::FILE_OPERATION_WRITE,
2572 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED,
2575 { // Direct download with injected "Failed" error in Write().
2576 { "a_zip_file.zip",
2577 DOWNLOAD_DIRECT,
2578 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED,
2583 content::TestFileErrorInjector::FILE_OPERATION_WRITE,
2585 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED,
2588 { // Navigated download with injected "Name too long" error in
2589 // Initialize().
2590 { "a_zip_file.zip",
2591 DOWNLOAD_NAVIGATE,
2592 content::DOWNLOAD_INTERRUPT_REASON_FILE_NAME_TOO_LONG,
2597 content::TestFileErrorInjector::FILE_OPERATION_INITIALIZE,
2599 content::DOWNLOAD_INTERRUPT_REASON_FILE_NAME_TOO_LONG,
2602 { // Direct download with injected "Name too long" error in Initialize().
2603 { "a_zip_file.zip",
2604 DOWNLOAD_DIRECT,
2605 content::DOWNLOAD_INTERRUPT_REASON_FILE_NAME_TOO_LONG,
2610 content::TestFileErrorInjector::FILE_OPERATION_INITIALIZE,
2612 content::DOWNLOAD_INTERRUPT_REASON_FILE_NAME_TOO_LONG,
2615 { // Navigated download with injected "Name too long" error in Write().
2616 { "a_zip_file.zip",
2617 DOWNLOAD_NAVIGATE,
2618 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED,
2623 content::TestFileErrorInjector::FILE_OPERATION_WRITE,
2625 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED,
2628 { // Direct download with injected "Name too long" error in Write().
2629 { "a_zip_file.zip",
2630 DOWNLOAD_DIRECT,
2631 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED,
2636 content::TestFileErrorInjector::FILE_OPERATION_WRITE,
2638 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED,
2641 { // Direct download with injected "Disk full" error in 2nd Write().
2642 { "06bESSE21Evolution.ppt",
2643 DOWNLOAD_DIRECT,
2644 content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE,
2649 content::TestFileErrorInjector::FILE_OPERATION_WRITE,
2651 content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE,
2656 DownloadInsertFilesErrorCheckErrors(ARRAYSIZE_UNSAFE(error_info), error_info);
2659 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadErrorReadonlyFolder) {
2660 DownloadInfo download_info[] = {
2662 "a_zip_file.zip",
2663 DOWNLOAD_DIRECT,
2664 // This passes because we switch to the My Documents folder.
2665 content::DOWNLOAD_INTERRUPT_REASON_NONE,
2666 true,
2667 true
2670 "a_zip_file.zip",
2671 DOWNLOAD_NAVIGATE,
2672 // This passes because we switch to the My Documents folder.
2673 content::DOWNLOAD_INTERRUPT_REASON_NONE,
2674 true,
2675 true
2679 DownloadFilesToReadonlyFolder(ARRAYSIZE_UNSAFE(download_info), download_info);
2682 // Test that we show a dangerous downloads warning for a dangerous file
2683 // downloaded through a blob: URL.
2684 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadDangerousBlobData) {
2685 #if defined(OS_WIN)
2686 // On Windows, if SafeBrowsing is enabled, certain file types (.exe, .cab,
2687 // .msi) will be handled by the DownloadProtectionService. However, if the URL
2688 // is non-standard (e.g. blob:) then those files won't be handled by the
2689 // DPS. We should be showing the dangerous download warning for any file
2690 // considered dangerous and isn't handled by the DPS.
2691 const char kFilename[] = "foo.exe";
2692 #else
2693 const char kFilename[] = "foo.swf";
2694 #endif
2696 std::string path("files/downloads/download-dangerous-blob.html?filename=");
2697 path += kFilename;
2699 // Need to use http urls because the blob js doesn't work on file urls for
2700 // security reasons.
2701 ASSERT_TRUE(test_server()->Start());
2702 GURL url(test_server()->GetURL(path));
2704 content::DownloadTestObserver* observer(DangerousDownloadWaiter(
2705 browser(), 1,
2706 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_ACCEPT));
2707 ui_test_utils::NavigateToURL(browser(), url);
2708 observer->WaitForFinished();
2710 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::COMPLETE));
2711 EXPECT_EQ(1u, observer->NumDangerousDownloadsSeen());
2714 IN_PROC_BROWSER_TEST_F(DownloadTest, LoadURLExternallyReferrerPolicy) {
2715 // Do initial setup.
2716 ASSERT_TRUE(test_server()->Start());
2717 EnableFileChooser(true);
2718 std::vector<DownloadItem*> download_items;
2719 GetDownloads(browser(), &download_items);
2720 ASSERT_TRUE(download_items.empty());
2722 // Navigate to a page with a referrer policy and a link on it. The link points
2723 // to testserver's /echoheader.
2724 GURL url = test_server()->GetURL("files/downloads/referrer_policy.html");
2725 ASSERT_TRUE(url.is_valid());
2726 ui_test_utils::NavigateToURL(browser(), url);
2728 scoped_ptr<content::DownloadTestObserver> waiter(
2729 new content::DownloadTestObserverTerminal(
2730 DownloadManagerForBrowser(browser()), 1,
2731 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL));
2733 // Click on the link with the alt key pressed. This will download the link
2734 // target.
2735 WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
2736 blink::WebMouseEvent mouse_event;
2737 mouse_event.type = blink::WebInputEvent::MouseDown;
2738 mouse_event.button = blink::WebMouseEvent::ButtonLeft;
2739 mouse_event.x = 15;
2740 mouse_event.y = 15;
2741 mouse_event.clickCount = 1;
2742 mouse_event.modifiers = blink::WebInputEvent::AltKey;
2743 tab->GetRenderViewHost()->ForwardMouseEvent(mouse_event);
2744 mouse_event.type = blink::WebInputEvent::MouseUp;
2745 tab->GetRenderViewHost()->ForwardMouseEvent(mouse_event);
2747 waiter->WaitForFinished();
2748 EXPECT_EQ(1u, waiter->NumDownloadsSeenInState(DownloadItem::COMPLETE));
2749 CheckDownloadStates(1, DownloadItem::COMPLETE);
2751 // Validate that the correct file was downloaded.
2752 GetDownloads(browser(), &download_items);
2753 ASSERT_EQ(1u, download_items.size());
2754 ASSERT_EQ(test_server()->GetURL("echoheader?Referer"),
2755 download_items[0]->GetOriginalUrl());
2757 // Check that the file contains the expected referrer.
2758 base::FilePath file(download_items[0]->GetTargetFilePath());
2759 std::string expected_contents = test_server()->GetURL(std::string()).spec();
2760 ASSERT_TRUE(VerifyFile(file, expected_contents, expected_contents.length()));
2763 IN_PROC_BROWSER_TEST_F(DownloadTest, HiddenDownload) {
2764 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
2765 GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
2767 DownloadManager* download_manager = DownloadManagerForBrowser(browser());
2768 scoped_ptr<content::DownloadTestObserver> observer(
2769 new content::DownloadTestObserverTerminal(
2770 download_manager,
2772 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL));
2774 // Download and set IsHiddenDownload to true.
2775 WebContents* web_contents =
2776 browser()->tab_strip_model()->GetActiveWebContents();
2777 scoped_ptr<DownloadUrlParameters> params(
2778 DownloadUrlParameters::FromWebContents(web_contents, url));
2779 params->set_callback(base::Bind(&SetHiddenDownloadCallback));
2780 download_manager->DownloadUrl(params.Pass());
2781 observer->WaitForFinished();
2783 // Verify that download shelf is not shown.
2784 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
2787 // Verify the multiple downloads infobar.
2788 IN_PROC_BROWSER_TEST_F(DownloadTest, TestMultipleDownloadsInfobar) {
2789 #if defined(OS_WIN) && defined(USE_ASH)
2790 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
2791 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshBrowserTests))
2792 return;
2793 #endif
2795 ASSERT_TRUE(test_server()->Start());
2797 // Create a downloads observer.
2798 scoped_ptr<content::DownloadTestObserver> downloads_observer(
2799 CreateWaiter(browser(), 2));
2801 // Create an infobar observer.
2802 content::WindowedNotificationObserver infobar_added_1(
2803 chrome::NOTIFICATION_TAB_CONTENTS_INFOBAR_ADDED,
2804 content::NotificationService::AllSources());
2805 ui_test_utils::NavigateToURL(
2806 browser(),
2807 test_server()->GetURL("files/downloads/download-a_zip_file.html"));
2808 infobar_added_1.Wait();
2810 InfoBarService* infobar_service = InfoBarService::FromWebContents(
2811 browser()->tab_strip_model()->GetActiveWebContents());
2812 // Verify that there is only one infobar.
2813 ASSERT_EQ(1u, infobar_service->infobar_count());
2815 // Get the infobar at index 0.
2816 InfoBar* infobar = infobar_service->infobar_at(0);
2817 ConfirmInfoBarDelegate* confirm_infobar =
2818 infobar->delegate()->AsConfirmInfoBarDelegate();
2819 ASSERT_TRUE(confirm_infobar != NULL);
2821 // Verify multi download warning infobar message.
2822 EXPECT_EQ(confirm_infobar->GetMessageText(),
2823 l10n_util::GetStringUTF16(IDS_MULTI_DOWNLOAD_WARNING));
2825 // Click on the "Allow" button to allow multiple downloads.
2826 if (confirm_infobar->Accept())
2827 infobar_service->RemoveInfoBar(infobar);
2828 // Verify that there are no more infobars.
2829 EXPECT_EQ(0u, infobar_service->infobar_count());
2831 // Waits for the download to complete.
2832 downloads_observer->WaitForFinished();
2833 EXPECT_EQ(2u, downloads_observer->NumDownloadsSeenInState(
2834 DownloadItem::COMPLETE));
2837 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadTest_Renaming) {
2838 ASSERT_TRUE(test_server()->Start());
2839 GURL url(test_server()->GetURL("files/downloads/a_zip_file.zip"));
2840 content::DownloadManager* manager = DownloadManagerForBrowser(browser());
2841 base::FilePath origin_file(OriginFile(base::FilePath(FILE_PATH_LITERAL(
2842 "downloads/a_zip_file.zip"))));
2843 ASSERT_TRUE(base::PathExists(origin_file));
2844 std::string origin_contents;
2845 ASSERT_TRUE(base::ReadFileToString(origin_file, &origin_contents));
2847 // Download the same url several times and expect that all downloaded files
2848 // after the zero-th contain a deduplication counter.
2849 for (int index = 0; index < 5; ++index) {
2850 DownloadAndWait(browser(), url);
2851 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
2852 content::DownloadItem* item = manager->GetDownload(
2853 content::DownloadItem::kInvalidId + 1 + index);
2854 ASSERT_TRUE(item);
2855 ASSERT_EQ(DownloadItem::COMPLETE, item->GetState());
2856 base::FilePath target_path(item->GetTargetFilePath());
2857 EXPECT_EQ(std::string("a_zip_file") +
2858 (index == 0 ? std::string(".zip") :
2859 base::StringPrintf(" (%d).zip", index)),
2860 target_path.BaseName().AsUTF8Unsafe());
2861 ASSERT_TRUE(base::PathExists(target_path));
2862 ASSERT_TRUE(VerifyFile(target_path, origin_contents,
2863 origin_contents.size()));
2867 // Test that the entire download pipeline handles unicode correctly.
2868 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadTest_CrazyFilenames) {
2869 const wchar_t* kCrazyFilenames[] = {
2870 L"a_file_name.zip",
2871 L"\u89c6\u9891\u76f4\u64ad\u56fe\u7247.zip", // chinese chars
2872 L"\u0412\u043e \u0424\u043b\u043e\u0440\u0438\u0434\u0435\u043e\u0431\u044a"
2873 L"\u044f\u0432\u043b\u0435\u043d\u0440\u0435\u0436\u0438\u043c \u0427"
2874 L"\u041f \u0438\u0437-\u0437\u0430 \u0443\u0442\u0435\u0447\u043a\u0438 "
2875 L"\u043d\u0435\u0444\u0442\u0438.zip", // russian
2876 L"Desocupa\xe7\xe3o est\xe1vel.zip",
2877 // arabic:
2878 L"\u0638\u2026\u0638\u02c6\u0637\xa7\u0638\u201a\u0637\xb9 \u0638\u201e"
2879 L"\u0638\u201e\u0637\xb2\u0638\u0679\u0637\xa7\u0637\xb1\u0637\xa9.zip",
2880 L"\u05d4\u05e2\u05d3\u05e4\u05d5\u05ea.zip", // hebrew
2881 L"\u092d\u093e\u0930\u0924.zip", // hindi
2882 L"d\xe9stabilis\xe9.zip", // french
2883 // korean
2884 L"\u97d3-\u4e2d \uc815\uc0c1, \ucc9c\uc548\ud568 \uc758\uacac.zip",
2885 L"jiho....tiho...miho.zip",
2886 L"jiho!@#$tiho$%^&-()_+=miho copy.zip", // special chars
2887 L"Wohoo-to hoo+I.zip",
2888 L"Picture 1.zip",
2889 L"This is a very very long english sentence with spaces and , and +.zip",
2892 std::vector<DownloadItem*> download_items;
2893 static const int kFlags = (base::PLATFORM_FILE_CREATE |
2894 base::PLATFORM_FILE_WRITE);
2895 base::FilePath origin(FILE_PATH_LITERAL("origin"));
2896 ASSERT_TRUE(base::CreateDirectory(DestinationFile(browser(), origin)));
2898 for (size_t index = 0; index < arraysize(kCrazyFilenames); ++index) {
2899 base::string16 crazy16;
2900 std::string crazy8;
2901 const wchar_t* crazy_w = kCrazyFilenames[index];
2902 ASSERT_TRUE(base::WideToUTF8(crazy_w, wcslen(crazy_w), &crazy8));
2903 ASSERT_TRUE(base::WideToUTF16(crazy_w, wcslen(crazy_w), &crazy16));
2904 base::FilePath file_path(DestinationFile(browser(), origin.Append(
2905 #if defined(OS_WIN)
2906 crazy16
2907 #elif defined(OS_POSIX)
2908 crazy8
2909 #endif
2910 )));
2912 // Create the file.
2913 bool created = false;
2914 base::PlatformFileError error = base::PLATFORM_FILE_ERROR_MAX;
2915 base::PlatformFile fd = base::CreatePlatformFile(
2916 file_path, kFlags, &created, &error);
2917 EXPECT_EQ(static_cast<int>(crazy8.size()),
2918 base::WritePlatformFileAtCurrentPos(
2919 fd, crazy8.c_str(), crazy8.size()));
2920 EXPECT_TRUE(base::ClosePlatformFile(fd));
2921 fd = base::kInvalidPlatformFileValue;
2922 GURL file_url(net::FilePathToFileURL(file_path));
2924 // Download the file and check that the filename is correct.
2925 DownloadAndWait(browser(), file_url);
2926 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
2927 GetDownloads(browser(), &download_items);
2928 ASSERT_EQ(1UL, download_items.size());
2929 base::FilePath downloaded(download_items[0]->GetTargetFilePath());
2930 download_items[0]->Remove();
2931 download_items.clear();
2932 ASSERT_TRUE(CheckDownloadFullPaths(
2933 browser(),
2934 downloaded,
2935 file_path));
2939 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadTest_Remove) {
2940 ASSERT_TRUE(test_server()->Start());
2941 GURL url(test_server()->GetURL("files/downloads/a_zip_file.zip"));
2942 std::vector<DownloadItem*> download_items;
2943 GetDownloads(browser(), &download_items);
2944 ASSERT_TRUE(download_items.empty());
2946 // Download a file.
2947 DownloadAndWaitWithDisposition(browser(),
2948 url,
2949 CURRENT_TAB,
2950 ui_test_utils::BROWSER_TEST_NONE);
2951 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
2952 GetDownloads(browser(), &download_items);
2953 ASSERT_EQ(1UL, download_items.size());
2954 base::FilePath downloaded(download_items[0]->GetTargetFilePath());
2956 // Remove the DownloadItem but not the file, then check that the file still
2957 // exists.
2958 download_items[0]->Remove();
2959 download_items.clear();
2960 GetDownloads(browser(), &download_items);
2961 ASSERT_EQ(0UL, download_items.size());
2962 ASSERT_TRUE(CheckDownloadFullPaths(
2963 browser(), downloaded, OriginFile(base::FilePath(
2964 FILE_PATH_LITERAL("downloads/a_zip_file.zip")))));
2968 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadTest_PauseResumeCancel) {
2969 DownloadItem* download_item = CreateSlowTestDownload();
2970 ASSERT_TRUE(download_item);
2971 ASSERT_FALSE(download_item->GetTargetFilePath().empty());
2972 EXPECT_FALSE(download_item->IsPaused());
2973 EXPECT_NE(DownloadItem::CANCELLED, download_item->GetState());
2974 download_item->Pause();
2975 EXPECT_TRUE(download_item->IsPaused());
2976 download_item->Resume();
2977 EXPECT_FALSE(download_item->IsPaused());
2978 EXPECT_NE(DownloadItem::CANCELLED, download_item->GetState());
2979 download_item->Cancel(true);
2980 EXPECT_EQ(DownloadItem::CANCELLED, download_item->GetState());
2983 // The Mac downloaded files quarantine feature is implemented by the
2984 // Contents/Info.plist file in cocoa apps. browser_tests cannot test
2985 // quarantining files on Mac because it is not a cocoa app.
2986 // TODO(benjhayden) test the equivalents on other platforms.
2988 #if defined(OS_LINUX) && !defined(OS_CHROMEOS) && defined(ARCH_CPU_ARM_FAMILY)
2989 // Timing out on ARM linux: http://crbug.com/238459
2990 #define MAYBE_DownloadTest_PercentComplete DISABLED_DownloadTest_PercentComplete
2991 #elif defined(OS_MACOSX)
2992 // Disable on mac: http://crbug.com/238831
2993 #define MAYBE_DownloadTest_PercentComplete DISABLED_DownloadTest_PercentComplete
2994 #else
2995 #define MAYBE_DownloadTest_PercentComplete DownloadTest_PercentComplete
2996 #endif
2997 IN_PROC_BROWSER_TEST_F(DownloadTest, MAYBE_DownloadTest_PercentComplete) {
2998 // Write a huge file.
2999 base::FilePath file_path(DestinationFile(
3000 browser(), base::FilePath(FILE_PATH_LITERAL("DownloadTest_BigZip.zip"))));
3001 int flags = (base::PLATFORM_FILE_CREATE |
3002 base::PLATFORM_FILE_WRITE);
3003 bool created = false;
3004 base::PlatformFileError error = base::PLATFORM_FILE_ERROR_MAX;
3005 base::PlatformFile fd = base::CreatePlatformFile(
3006 file_path, flags, &created, &error);
3007 int64 size = 1 << 29;
3008 EXPECT_EQ(size, base::SeekPlatformFile(
3009 fd, base::PLATFORM_FILE_FROM_BEGIN, size));
3010 EXPECT_EQ(1, base::WritePlatformFileAtCurrentPos(fd, "a", 1));
3011 EXPECT_TRUE(base::ClosePlatformFile(fd));
3012 fd = base::kInvalidPlatformFileValue;
3013 #if defined(OS_POSIX)
3014 // Make it readable by chronos on chromeos
3015 base::SetPosixFilePermissions(file_path, 0755);
3016 #endif
3018 // Ensure that we have enough disk space.
3019 int64 free_space = base::SysInfo::AmountOfFreeDiskSpace(
3020 GetDownloadDirectory(browser()));
3021 ASSERT_LE(size, free_space) << "Not enough disk space to download. Got "
3022 << free_space;
3023 GURL file_url(net::FilePathToFileURL(file_path));
3024 scoped_ptr<content::DownloadTestObserver> progress_waiter(
3025 CreateInProgressWaiter(browser(), 1));
3027 // Start downloading a file, wait for it to be created.
3028 ui_test_utils::NavigateToURLWithDisposition(
3029 browser(), file_url, CURRENT_TAB, ui_test_utils::BROWSER_TEST_NONE);
3030 progress_waiter->WaitForFinished();
3031 EXPECT_EQ(1u, progress_waiter->NumDownloadsSeenInState(
3032 DownloadItem::IN_PROGRESS));
3033 std::vector<DownloadItem*> download_items;
3034 GetDownloads(browser(), &download_items);
3035 ASSERT_EQ(1UL, download_items.size());
3037 // Wait for the download to complete, checking along the way that the
3038 // PercentComplete() never regresses.
3039 PercentWaiter waiter(download_items[0]);
3040 EXPECT_TRUE(waiter.WaitForFinished());
3041 EXPECT_EQ(DownloadItem::COMPLETE, download_items[0]->GetState());
3042 ASSERT_EQ(100, download_items[0]->PercentComplete());
3043 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
3045 // Check that the file downloaded correctly.
3046 ASSERT_TRUE(base::PathExists(download_items[0]->GetTargetFilePath()));
3047 int64 downloaded_size = 0;
3048 ASSERT_TRUE(base::GetFileSize(
3049 download_items[0]->GetTargetFilePath(), &downloaded_size));
3050 #if defined(OS_WIN)
3051 ASSERT_EQ(1, downloaded_size);
3052 #else
3053 ASSERT_EQ(size + 1, downloaded_size);
3054 #endif
3055 ASSERT_TRUE(file_util::DieFileDie(file_path, false));
3056 ASSERT_TRUE(file_util::DieFileDie(download_items[0]->GetTargetFilePath(),
3057 false));
3060 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadTest_DenyDanger) {
3061 ASSERT_TRUE(test_server()->Start());
3062 GURL url(test_server()->GetURL("files/downloads/dangerous/dangerous.crx"));
3063 scoped_ptr<content::DownloadTestObserver> observer(
3064 DangerousDownloadWaiter(
3065 browser(), 1,
3066 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_DENY));
3067 ui_test_utils::NavigateToURL(browser(), url);
3068 observer->WaitForFinished();
3069 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::CANCELLED));
3070 EXPECT_EQ(1u, observer->NumDangerousDownloadsSeen());
3071 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
3074 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadPrefs_SaveFilePath) {
3075 DownloadPrefs* on_prefs = DownloadServiceFactory::GetForBrowserContext(
3076 browser()->profile())->GetDownloadManagerDelegate()->download_prefs();
3077 DownloadPrefs* off_prefs = DownloadServiceFactory::GetForBrowserContext(
3078 browser()->profile()->GetOffTheRecordProfile())
3079 ->GetDownloadManagerDelegate()->download_prefs();
3080 base::FilePath dir(on_prefs->SaveFilePath());
3081 EXPECT_EQ(dir.value(), off_prefs->SaveFilePath().value());
3083 on_prefs->SetSaveFilePath(dir.AppendASCII("on"));
3084 EXPECT_EQ(dir.AppendASCII("on").value(), on_prefs->SaveFilePath().value());
3085 EXPECT_EQ(dir.AppendASCII("on").value(), off_prefs->SaveFilePath().value());
3087 on_prefs->SetSaveFilePath(dir);
3088 EXPECT_EQ(dir.value(), on_prefs->SaveFilePath().value());
3089 EXPECT_EQ(dir.value(), off_prefs->SaveFilePath().value());
3091 off_prefs->SetSaveFilePath(dir.AppendASCII("off"));
3092 EXPECT_EQ(dir.value(), on_prefs->SaveFilePath().value());
3093 EXPECT_EQ(dir.AppendASCII("off").value(), off_prefs->SaveFilePath().value());
3095 on_prefs->SetSaveFilePath(dir.AppendASCII("on"));
3096 EXPECT_EQ(dir.AppendASCII("on").value(), on_prefs->SaveFilePath().value());
3097 EXPECT_EQ(dir.AppendASCII("off").value(), off_prefs->SaveFilePath().value());
3100 // A download that is interrupted due to a file error should be able to be
3101 // resumed.
3102 IN_PROC_BROWSER_TEST_F(DownloadTest, Resumption_NoPrompt) {
3103 CommandLine::ForCurrentProcess()->AppendSwitch(
3104 switches::kEnableDownloadResumption);
3105 scoped_refptr<content::TestFileErrorInjector> error_injector(
3106 content::TestFileErrorInjector::Create(
3107 DownloadManagerForBrowser(browser())));
3108 scoped_ptr<content::DownloadTestObserver> completion_observer(
3109 CreateWaiter(browser(), 1));
3110 EnableFileChooser(true);
3112 DownloadItem* download = StartMockDownloadAndInjectError(
3113 error_injector,
3114 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED);
3115 ASSERT_TRUE(download);
3117 download->Resume();
3118 completion_observer->WaitForFinished();
3120 EXPECT_EQ(
3121 1u, completion_observer->NumDownloadsSeenInState(DownloadItem::COMPLETE));
3122 EXPECT_FALSE(DidShowFileChooser());
3125 // A download that's interrupted due to a reason that indicates that the target
3126 // path is invalid or unusable should cause a prompt to be displayed on
3127 // resumption.
3128 IN_PROC_BROWSER_TEST_F(DownloadTest, Resumption_WithPrompt) {
3129 CommandLine::ForCurrentProcess()->AppendSwitch(
3130 switches::kEnableDownloadResumption);
3131 scoped_refptr<content::TestFileErrorInjector> error_injector(
3132 content::TestFileErrorInjector::Create(
3133 DownloadManagerForBrowser(browser())));
3134 scoped_ptr<content::DownloadTestObserver> completion_observer(
3135 CreateWaiter(browser(), 1));
3136 EnableFileChooser(true);
3138 DownloadItem* download = StartMockDownloadAndInjectError(
3139 error_injector,
3140 content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE);
3141 ASSERT_TRUE(download);
3143 download->Resume();
3144 completion_observer->WaitForFinished();
3146 EXPECT_EQ(
3147 1u, completion_observer->NumDownloadsSeenInState(DownloadItem::COMPLETE));
3148 EXPECT_TRUE(DidShowFileChooser());
3151 // The user shouldn't be prompted on a resumed download unless a prompt is
3152 // necessary due to the interrupt reason.
3153 IN_PROC_BROWSER_TEST_F(DownloadTest, Resumption_WithPromptAlways) {
3154 CommandLine::ForCurrentProcess()->AppendSwitch(
3155 switches::kEnableDownloadResumption);
3156 browser()->profile()->GetPrefs()->SetBoolean(
3157 prefs::kPromptForDownload, true);
3158 scoped_refptr<content::TestFileErrorInjector> error_injector(
3159 content::TestFileErrorInjector::Create(
3160 DownloadManagerForBrowser(browser())));
3161 scoped_ptr<content::DownloadTestObserver> completion_observer(
3162 CreateWaiter(browser(), 1));
3163 EnableFileChooser(true);
3165 DownloadItem* download = StartMockDownloadAndInjectError(
3166 error_injector,
3167 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED);
3168 ASSERT_TRUE(download);
3170 // Prompts the user initially because of the kPromptForDownload preference.
3171 EXPECT_TRUE(DidShowFileChooser());
3173 download->Resume();
3174 completion_observer->WaitForFinished();
3176 EXPECT_EQ(
3177 1u, completion_observer->NumDownloadsSeenInState(DownloadItem::COMPLETE));
3178 // Shouldn't prompt for resumption.
3179 EXPECT_FALSE(DidShowFileChooser());
3182 // A download that is interrupted due to a transient error should be resumed
3183 // automatically.
3184 IN_PROC_BROWSER_TEST_F(DownloadTest, Resumption_Automatic) {
3185 CommandLine::ForCurrentProcess()->AppendSwitch(
3186 switches::kEnableDownloadResumption);
3187 scoped_refptr<content::TestFileErrorInjector> error_injector(
3188 content::TestFileErrorInjector::Create(
3189 DownloadManagerForBrowser(browser())));
3191 DownloadItem* download = StartMockDownloadAndInjectError(
3192 error_injector,
3193 content::DOWNLOAD_INTERRUPT_REASON_FILE_TRANSIENT_ERROR);
3194 ASSERT_TRUE(download);
3196 // The number of times this the download is resumed automatically is defined
3197 // in DownloadItemImpl::kMaxAutoResumeAttempts. The number of DownloadFiles
3198 // created should be that number + 1 (for the original download request). We
3199 // only care that it is greater than 1.
3200 EXPECT_GT(1u, error_injector->TotalFileCount());
3203 // An interrupting download should be resumable multiple times.
3204 IN_PROC_BROWSER_TEST_F(DownloadTest, Resumption_MultipleAttempts) {
3205 CommandLine::ForCurrentProcess()->AppendSwitch(
3206 switches::kEnableDownloadResumption);
3207 scoped_refptr<content::TestFileErrorInjector> error_injector(
3208 content::TestFileErrorInjector::Create(
3209 DownloadManagerForBrowser(browser())));
3210 scoped_ptr<DownloadTestObserverNotInProgress> completion_observer(
3211 new DownloadTestObserverNotInProgress(
3212 DownloadManagerForBrowser(browser()), 1));
3213 // Wait for two transitions to a resumable state
3214 scoped_ptr<content::DownloadTestObserver> resumable_observer(
3215 new DownloadTestObserverResumable(
3216 DownloadManagerForBrowser(browser()), 2));
3218 EnableFileChooser(true);
3219 DownloadItem* download = StartMockDownloadAndInjectError(
3220 error_injector,
3221 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED);
3222 ASSERT_TRUE(download);
3224 content::TestFileErrorInjector::FileErrorInfo error_info;
3225 error_info.url = download->GetOriginalUrl().spec();
3226 error_info.code = content::TestFileErrorInjector::FILE_OPERATION_WRITE;
3227 error_info.operation_instance = 0;
3228 error_info.error = content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED;
3229 error_injector->AddError(error_info);
3230 error_injector->InjectErrors();
3232 // Resuming should cause the download to be interrupted again due to the
3233 // errors we are injecting.
3234 download->Resume();
3235 resumable_observer->WaitForFinished();
3236 ASSERT_EQ(DownloadItem::INTERRUPTED, download->GetState());
3237 ASSERT_EQ(content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED,
3238 download->GetLastReason());
3240 error_injector->ClearErrors();
3241 error_injector->InjectErrors();
3243 // No errors this time. The download should complete successfully.
3244 EXPECT_FALSE(completion_observer->IsFinished());
3245 completion_observer->StartObserving();
3246 download->Resume();
3247 completion_observer->WaitForFinished();
3248 EXPECT_EQ(DownloadItem::COMPLETE, download->GetState());
3250 EXPECT_FALSE(DidShowFileChooser());