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.
8 #include "base/bind_helpers.h"
9 #include "base/command_line.h"
10 #include "base/file_util.h"
11 #include "base/files/file.h"
12 #include "base/files/file_path.h"
13 #include "base/files/scoped_temp_dir.h"
14 #include "base/memory/ref_counted.h"
15 #include "base/path_service.h"
16 #include "base/prefs/pref_service.h"
17 #include "base/stl_util.h"
18 #include "base/strings/string_split.h"
19 #include "base/strings/string_util.h"
20 #include "base/strings/stringprintf.h"
21 #include "base/strings/utf_string_conversions.h"
22 #include "base/sys_info.h"
23 #include "base/test/test_file_util.h"
24 #include "chrome/app/chrome_command_ids.h"
25 #include "chrome/browser/browser_process.h"
26 #include "chrome/browser/chrome_notification_types.h"
27 #include "chrome/browser/common/cancelable_request.h"
28 #include "chrome/browser/download/chrome_download_manager_delegate.h"
29 #include "chrome/browser/download/download_browsertest.h"
30 #include "chrome/browser/download/download_crx_util.h"
31 #include "chrome/browser/download/download_history.h"
32 #include "chrome/browser/download/download_item_model.h"
33 #include "chrome/browser/download/download_prefs.h"
34 #include "chrome/browser/download/download_request_limiter.h"
35 #include "chrome/browser/download/download_service.h"
36 #include "chrome/browser/download/download_service_factory.h"
37 #include "chrome/browser/download/download_shelf.h"
38 #include "chrome/browser/download/download_target_determiner.h"
39 #include "chrome/browser/download/download_test_file_activity_observer.h"
40 #include "chrome/browser/extensions/extension_install_prompt.h"
41 #include "chrome/browser/extensions/extension_service.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_service.h"
47 #include "chrome/browser/net/url_request_mock_util.h"
48 #include "chrome/browser/profiles/profile.h"
49 #include "chrome/browser/renderer_context_menu/render_view_context_menu_test_util.h"
50 #include "chrome/browser/ui/browser.h"
51 #include "chrome/browser/ui/browser_commands.h"
52 #include "chrome/browser/ui/browser_finder.h"
53 #include "chrome/browser/ui/browser_list.h"
54 #include "chrome/browser/ui/browser_tabstrip.h"
55 #include "chrome/browser/ui/browser_window.h"
56 #include "chrome/browser/ui/chrome_pages.h"
57 #include "chrome/browser/ui/host_desktop.h"
58 #include "chrome/browser/ui/tabs/tab_strip_model.h"
59 #include "chrome/common/chrome_paths.h"
60 #include "chrome/common/pref_names.h"
61 #include "chrome/common/url_constants.h"
62 #include "chrome/test/base/in_process_browser_test.h"
63 #include "chrome/test/base/test_switches.h"
64 #include "chrome/test/base/ui_test_utils.h"
65 #include "components/infobars/core/infobar.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_frame_host.h"
73 #include "content/public/browser/render_view_host.h"
74 #include "content/public/browser/resource_context.h"
75 #include "content/public/browser/web_contents.h"
76 #include "content/public/common/content_switches.h"
77 #include "content/public/common/context_menu_params.h"
78 #include "content/public/common/page_transition_types.h"
79 #include "content/public/test/browser_test_utils.h"
80 #include "content/public/test/download_test_observer.h"
81 #include "content/public/test/test_file_error_injector.h"
82 #include "content/public/test/test_navigation_observer.h"
83 #include "content/test/net/url_request_mock_http_job.h"
84 #include "content/test/net/url_request_slow_download_job.h"
85 #include "extensions/browser/extension_system.h"
86 #include "extensions/common/feature_switch.h"
87 #include "grit/generated_resources.h"
88 #include "net/base/filename_util.h"
89 #include "net/test/spawned_test_server/spawned_test_server.h"
90 #include "testing/gtest/include/gtest/gtest.h"
91 #include "ui/base/l10n/l10n_util.h"
93 using content::BrowserContext;
94 using content::BrowserThread;
95 using content::DownloadItem;
96 using content::DownloadManager;
97 using content::DownloadUrlParameters;
98 using content::URLRequestMockHTTPJob;
99 using content::URLRequestSlowDownloadJob;
100 using content::WebContents;
101 using extensions::Extension;
102 using extensions::FeatureSwitch;
106 class CreatedObserver : public content::DownloadManager::Observer {
108 explicit CreatedObserver(content::DownloadManager* manager)
111 manager->AddObserver(this);
113 virtual ~CreatedObserver() {
115 manager_->RemoveObserver(this);
119 std::vector<DownloadItem*> downloads;
120 manager_->GetAllDownloads(&downloads);
121 if (!downloads.empty())
124 content::RunMessageLoop();
129 virtual void OnDownloadCreated(content::DownloadManager* manager,
130 content::DownloadItem* item) OVERRIDE {
131 DCHECK_EQ(manager_, manager);
133 base::MessageLoopForUI::current()->Quit();
136 content::DownloadManager* manager_;
139 DISALLOW_COPY_AND_ASSIGN(CreatedObserver);
142 class PercentWaiter : public content::DownloadItem::Observer {
144 explicit PercentWaiter(DownloadItem* item)
149 item_->AddObserver(this);
151 virtual ~PercentWaiter() {
153 item_->RemoveObserver(this);
156 bool WaitForFinished() {
157 if (item_->GetState() == DownloadItem::COMPLETE) {
158 return item_->PercentComplete() == 100;
161 content::RunMessageLoop();
167 virtual void OnDownloadUpdated(content::DownloadItem* item) OVERRIDE {
168 DCHECK_EQ(item_, item);
170 ((prev_percent_ > item_->PercentComplete()) ||
171 (item_->GetState() == DownloadItem::COMPLETE &&
172 (item_->PercentComplete() != 100)))) {
175 base::MessageLoopForUI::current()->Quit();
177 if (item_->GetState() == DownloadItem::COMPLETE && waiting_)
178 base::MessageLoopForUI::current()->Quit();
181 virtual void OnDownloadDestroyed(content::DownloadItem* item) OVERRIDE {
182 DCHECK_EQ(item_, item);
183 item_->RemoveObserver(this);
187 content::DownloadItem* item_;
192 DISALLOW_COPY_AND_ASSIGN(PercentWaiter);
195 // DownloadTestObserver subclass that observes one download until it transitions
196 // from a non-resumable state to a resumable state a specified number of
197 // times. Note that this observer can only observe a single download.
198 class DownloadTestObserverResumable : public content::DownloadTestObserver {
200 // Construct a new observer. |transition_count| is the number of times the
201 // download should transition from a non-resumable state to a resumable state.
202 DownloadTestObserverResumable(DownloadManager* download_manager,
203 size_t transition_count)
204 : DownloadTestObserver(download_manager, 1,
205 ON_DANGEROUS_DOWNLOAD_FAIL),
206 was_previously_resumable_(false),
207 transitions_left_(transition_count) {
210 virtual ~DownloadTestObserverResumable() {}
213 virtual bool IsDownloadInFinalState(DownloadItem* download) OVERRIDE {
214 bool is_resumable_now = download->CanResume();
215 if (!was_previously_resumable_ && is_resumable_now)
217 was_previously_resumable_ = is_resumable_now;
218 return transitions_left_ == 0;
221 bool was_previously_resumable_;
222 size_t transitions_left_;
224 DISALLOW_COPY_AND_ASSIGN(DownloadTestObserverResumable);
227 // IDs and paths of CRX files used in tests.
228 const char kGoodCrxId[] = "ldnnhddmnhbkjipkidpdiheffobcpfmf";
229 const base::FilePath kGoodCrxPath(FILE_PATH_LITERAL("extensions/good.crx"));
231 const char kLargeThemeCrxId[] = "pjpgmfcmabopnnfonnhmdjglfpjjfkbf";
232 const base::FilePath kLargeThemePath(
233 FILE_PATH_LITERAL("extensions/theme2.crx"));
235 // Get History Information.
236 class DownloadsHistoryDataCollector {
238 explicit DownloadsHistoryDataCollector(Profile* profile)
239 : profile_(profile), result_valid_(false) {}
241 bool WaitForDownloadInfo(
242 scoped_ptr<std::vector<history::DownloadRow> >* results) {
243 HistoryService* hs = HistoryServiceFactory::GetForProfile(
244 profile_, Profile::EXPLICIT_ACCESS);
247 base::Bind(&DownloadsHistoryDataCollector::OnQueryDownloadsComplete,
248 base::Unretained(this)));
250 content::RunMessageLoop();
252 *results = results_.Pass();
254 return result_valid_;
258 void OnQueryDownloadsComplete(
259 scoped_ptr<std::vector<history::DownloadRow> > entries) {
260 result_valid_ = true;
261 results_ = entries.Pass();
262 base::MessageLoopForUI::current()->Quit();
266 scoped_ptr<std::vector<history::DownloadRow> > results_;
268 CancelableRequestConsumer callback_consumer_;
270 DISALLOW_COPY_AND_ASSIGN(DownloadsHistoryDataCollector);
273 // Mock that simulates a permissions dialog where the user denies
274 // permission to install. TODO(skerner): This could be shared with
275 // extensions tests. Find a common place for this class.
276 class MockAbortExtensionInstallPrompt : public ExtensionInstallPrompt {
278 MockAbortExtensionInstallPrompt() :
279 ExtensionInstallPrompt(NULL) {
282 // Simulate a user abort on an extension installation.
283 virtual void ConfirmInstall(
285 const Extension* extension,
286 const ShowDialogCallback& show_dialog_callback) OVERRIDE {
287 delegate->InstallUIAbort(true);
288 base::MessageLoopForUI::current()->Quit();
291 virtual void OnInstallSuccess(const Extension* extension,
292 SkBitmap* icon) OVERRIDE {
294 virtual void OnInstallFailure(
295 const extensions::CrxInstallerError& error) OVERRIDE {
299 // Mock that simulates a permissions dialog where the user allows
301 class MockAutoConfirmExtensionInstallPrompt : public ExtensionInstallPrompt {
303 explicit MockAutoConfirmExtensionInstallPrompt(
304 content::WebContents* web_contents)
305 : ExtensionInstallPrompt(web_contents) {}
307 // Proceed without confirmation prompt.
308 virtual void ConfirmInstall(
310 const Extension* extension,
311 const ShowDialogCallback& show_dialog_callback) OVERRIDE {
312 delegate->InstallUIProceed();
315 virtual void OnInstallSuccess(const Extension* extension,
316 SkBitmap* icon) OVERRIDE {
318 virtual void OnInstallFailure(
319 const extensions::CrxInstallerError& error) OVERRIDE {
323 static DownloadManager* DownloadManagerForBrowser(Browser* browser) {
324 return BrowserContext::GetDownloadManager(browser->profile());
327 bool WasAutoOpened(DownloadItem* item) {
328 return item->GetAutoOpened();
331 // Called when a download starts. Marks the download as hidden.
332 void SetHiddenDownloadCallback(DownloadItem* item,
333 content::DownloadInterruptReason reason) {
334 DownloadItemModel(item).SetShouldShowInShelf(false);
337 // Callback for HistoryObserver; used in DownloadHistoryCheck
338 bool HasDataAndName(const history::DownloadRow& row) {
339 return row.received_bytes > 0 && !row.target_path.empty();
344 DownloadTestObserverNotInProgress::DownloadTestObserverNotInProgress(
345 DownloadManager* download_manager,
347 : DownloadTestObserver(download_manager, count, ON_DANGEROUS_DOWNLOAD_FAIL),
348 started_observing_(false) {
352 DownloadTestObserverNotInProgress::~DownloadTestObserverNotInProgress() {}
354 void DownloadTestObserverNotInProgress::StartObserving() {
355 started_observing_ = true;
358 bool DownloadTestObserverNotInProgress::IsDownloadInFinalState(
359 DownloadItem* download) {
360 return started_observing_ &&
361 download->GetState() != DownloadItem::IN_PROGRESS;
364 class HistoryObserver : public DownloadHistory::Observer {
366 typedef base::Callback<bool(const history::DownloadRow&)> FilterCallback;
368 explicit HistoryObserver(Profile* profile)
371 seen_stored_(false) {
372 DownloadServiceFactory::GetForBrowserContext(profile_)->
373 GetDownloadHistory()->AddObserver(this);
376 virtual ~HistoryObserver() {
377 DownloadService* service = DownloadServiceFactory::GetForBrowserContext(
379 if (service && service->GetDownloadHistory())
380 service->GetDownloadHistory()->RemoveObserver(this);
383 void SetFilterCallback(const FilterCallback& callback) {
384 callback_ = callback;
387 virtual void OnDownloadStored(
388 content::DownloadItem* item,
389 const history::DownloadRow& info) OVERRIDE {
390 if (!callback_.is_null() && (!callback_.Run(info)))
395 base::MessageLoopForUI::current()->Quit();
398 virtual void OnDownloadHistoryDestroyed() OVERRIDE {
399 DownloadServiceFactory::GetForBrowserContext(profile_)->
400 GetDownloadHistory()->RemoveObserver(this);
403 void WaitForStored() {
407 content::RunMessageLoop();
415 FilterCallback callback_;
417 DISALLOW_COPY_AND_ASSIGN(HistoryObserver);
420 class DownloadTest : public InProcessBrowserTest {
422 // Choice of navigation or direct fetch. Used by |DownloadFileCheckErrors()|.
423 enum DownloadMethod {
428 // Information passed in to |DownloadFileCheckErrors()|.
429 struct DownloadInfo {
430 const char* url_name; // URL for the download.
431 DownloadMethod download_method; // Navigation or Direct.
432 // Download interrupt reason (NONE is OK).
433 content::DownloadInterruptReason reason;
434 bool show_download_item; // True if the download item appears on the shelf.
435 bool should_redirect_to_documents; // True if we save it in "My Documents".
438 struct FileErrorInjectInfo {
439 DownloadInfo download_info;
440 content::TestFileErrorInjector::FileErrorInfo error_info;
445 virtual void SetUpOnMainThread() OVERRIDE {
446 BrowserThread::PostTask(
447 BrowserThread::IO, FROM_HERE,
448 base::Bind(&chrome_browser_net::SetUrlRequestMocksEnabled, true));
449 ASSERT_TRUE(InitialSetup());
452 virtual void CleanUpOnMainThread() OVERRIDE {
453 // Needs to be torn down on the main thread. file_activity_observer_ holds a
454 // reference to the ChromeDownloadManagerDelegate which should be destroyed
456 file_activity_observer_.reset();
459 virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
460 command_line->AppendSwitch(switches::kDisablePluginsDiscovery);
463 // Returning false indicates a failure of the setup, and should be asserted
465 virtual bool InitialSetup() {
466 bool have_test_dir = PathService::Get(chrome::DIR_TEST_DATA, &test_dir_);
467 EXPECT_TRUE(have_test_dir);
471 // Sanity check default values for window / tab count and shelf visibility.
472 int window_count = chrome::GetTotalBrowserCount();
473 EXPECT_EQ(1, window_count);
474 EXPECT_EQ(1, browser()->tab_strip_model()->count());
475 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
477 // Set up the temporary download folder.
478 bool created_downloads_dir = CreateAndSetDownloadsDirectory(browser());
479 EXPECT_TRUE(created_downloads_dir);
480 if (!created_downloads_dir)
482 browser()->profile()->GetPrefs()->SetBoolean(
483 prefs::kPromptForDownload, false);
485 DownloadManager* manager = DownloadManagerForBrowser(browser());
486 DownloadPrefs::FromDownloadManager(manager)->ResetAutoOpen();
487 manager->RemoveAllDownloads();
489 file_activity_observer_.reset(
490 new DownloadTestFileActivityObserver(browser()->profile()));
497 SIZE_TEST_TYPE_KNOWN,
498 SIZE_TEST_TYPE_UNKNOWN,
501 base::FilePath GetDownloadsDirectory() {
502 return downloads_directory_.path();
505 // Location of the file source (the place from which it is downloaded).
506 base::FilePath OriginFile(base::FilePath file) {
507 return test_dir_.Append(file);
510 // Location of the file destination (place to which it is downloaded).
511 base::FilePath DestinationFile(Browser* browser, base::FilePath file) {
512 return GetDownloadDirectory(browser).Append(file.BaseName());
515 // Must be called after browser creation. Creates a temporary
516 // directory for downloads that is auto-deleted on destruction.
517 // Returning false indicates a failure of the function, and should be asserted
519 bool CreateAndSetDownloadsDirectory(Browser* browser) {
523 if (!downloads_directory_.CreateUniqueTempDir())
526 browser->profile()->GetPrefs()->SetFilePath(
527 prefs::kDownloadDefaultDirectory,
528 downloads_directory_.path());
529 browser->profile()->GetPrefs()->SetFilePath(
530 prefs::kSaveFileDefaultDirectory,
531 downloads_directory_.path());
536 DownloadPrefs* GetDownloadPrefs(Browser* browser) {
537 return DownloadPrefs::FromDownloadManager(
538 DownloadManagerForBrowser(browser));
541 base::FilePath GetDownloadDirectory(Browser* browser) {
542 return GetDownloadPrefs(browser)->DownloadPath();
545 // Create a DownloadTestObserverTerminal that will wait for the
546 // specified number of downloads to finish.
547 content::DownloadTestObserver* CreateWaiter(
548 Browser* browser, int num_downloads) {
549 DownloadManager* download_manager = DownloadManagerForBrowser(browser);
550 return new content::DownloadTestObserverTerminal(
551 download_manager, num_downloads,
552 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL);
555 // Create a DownloadTestObserverInProgress that will wait for the
556 // specified number of downloads to start.
557 content::DownloadTestObserver* CreateInProgressWaiter(
558 Browser* browser, int num_downloads) {
559 DownloadManager* download_manager = DownloadManagerForBrowser(browser);
560 return new content::DownloadTestObserverInProgress(
561 download_manager, num_downloads);
564 // Create a DownloadTestObserverTerminal that will wait for the
565 // specified number of downloads to finish, or for
566 // a dangerous download warning to be shown.
567 content::DownloadTestObserver* DangerousDownloadWaiter(
570 content::DownloadTestObserver::DangerousDownloadAction
571 dangerous_download_action) {
572 DownloadManager* download_manager = DownloadManagerForBrowser(browser);
573 return new content::DownloadTestObserverTerminal(
574 download_manager, num_downloads,
575 dangerous_download_action);
578 void CheckDownloadStatesForBrowser(Browser* browser,
580 DownloadItem::DownloadState state) {
581 std::vector<DownloadItem*> download_items;
582 GetDownloads(browser, &download_items);
584 EXPECT_EQ(num, download_items.size());
586 for (size_t i = 0; i < download_items.size(); ++i) {
587 EXPECT_EQ(state, download_items[i]->GetState()) << " Item " << i;
591 void CheckDownloadStates(size_t num, DownloadItem::DownloadState state) {
592 CheckDownloadStatesForBrowser(browser(), num, state);
595 // Download |url|, then wait for the download to finish.
596 // |disposition| indicates where the navigation occurs (current tab, new
597 // foreground tab, etc).
598 // |browser_test_flags| indicate what to wait for, and is an OR of 0 or more
599 // values in the ui_test_utils::BrowserTestWaitFlags enum.
600 void DownloadAndWaitWithDisposition(Browser* browser,
602 WindowOpenDisposition disposition,
603 int browser_test_flags) {
604 // Setup notification, navigate, and block.
605 scoped_ptr<content::DownloadTestObserver> observer(
606 CreateWaiter(browser, 1));
607 // This call will block until the condition specified by
608 // |browser_test_flags|, but will not wait for the download to finish.
609 ui_test_utils::NavigateToURLWithDisposition(browser,
613 // Waits for the download to complete.
614 observer->WaitForFinished();
615 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::COMPLETE));
616 // We don't expect a file chooser to be shown.
617 EXPECT_FALSE(DidShowFileChooser());
620 // Download a file in the current tab, then wait for the download to finish.
621 void DownloadAndWait(Browser* browser,
623 DownloadAndWaitWithDisposition(
627 ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
630 // Should only be called when the download is known to have finished
631 // (in error or not).
632 // Returning false indicates a failure of the function, and should be asserted
634 bool CheckDownload(Browser* browser,
635 const base::FilePath& downloaded_filename,
636 const base::FilePath& origin_filename) {
637 // Find the path to which the data will be downloaded.
638 base::FilePath downloaded_file(
639 DestinationFile(browser, downloaded_filename));
641 // Find the origin path (from which the data comes).
642 base::FilePath origin_file(OriginFile(origin_filename));
643 return CheckDownloadFullPaths(browser, downloaded_file, origin_file);
646 // A version of CheckDownload that allows complete path specification.
647 bool CheckDownloadFullPaths(Browser* browser,
648 const base::FilePath& downloaded_file,
649 const base::FilePath& origin_file) {
650 bool origin_file_exists = base::PathExists(origin_file);
651 EXPECT_TRUE(origin_file_exists) << origin_file.value();
652 if (!origin_file_exists)
655 // Confirm the downloaded data file exists.
656 bool downloaded_file_exists = base::PathExists(downloaded_file);
657 EXPECT_TRUE(downloaded_file_exists) << downloaded_file.value();
658 if (!downloaded_file_exists)
661 int64 origin_file_size = 0;
662 EXPECT_TRUE(base::GetFileSize(origin_file, &origin_file_size));
663 std::string original_file_contents;
664 EXPECT_TRUE(base::ReadFileToString(origin_file, &original_file_contents));
666 VerifyFile(downloaded_file, original_file_contents, origin_file_size));
668 // Delete the downloaded copy of the file.
669 bool downloaded_file_deleted = base::DieFileDie(downloaded_file, false);
670 EXPECT_TRUE(downloaded_file_deleted);
671 return downloaded_file_deleted;
674 content::DownloadTestObserver* CreateInProgressDownloadObserver(
675 size_t download_count) {
676 DownloadManager* manager = DownloadManagerForBrowser(browser());
677 return new content::DownloadTestObserverInProgress(
678 manager, download_count);
681 DownloadItem* CreateSlowTestDownload() {
682 scoped_ptr<content::DownloadTestObserver> observer(
683 CreateInProgressDownloadObserver(1));
684 GURL slow_download_url(URLRequestSlowDownloadJob::kUnknownSizeUrl);
685 DownloadManager* manager = DownloadManagerForBrowser(browser());
687 EXPECT_EQ(0, manager->NonMaliciousInProgressCount());
688 EXPECT_EQ(0, manager->InProgressCount());
689 if (manager->InProgressCount() != 0)
692 ui_test_utils::NavigateToURLWithDisposition(
693 browser(), slow_download_url, CURRENT_TAB,
694 ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
696 observer->WaitForFinished();
697 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::IN_PROGRESS));
699 DownloadManager::DownloadVector items;
700 manager->GetAllDownloads(&items);
702 DownloadItem* new_item = NULL;
703 for (DownloadManager::DownloadVector::iterator iter = items.begin();
704 iter != items.end(); ++iter) {
705 if ((*iter)->GetState() == DownloadItem::IN_PROGRESS) {
706 // There should be only one IN_PROGRESS item.
707 EXPECT_EQ(NULL, new_item);
714 bool RunSizeTest(Browser* browser,
716 const std::string& partial_indication,
717 const std::string& total_indication) {
718 EXPECT_TRUE(type == SIZE_TEST_TYPE_UNKNOWN || type == SIZE_TEST_TYPE_KNOWN);
719 if (type != SIZE_TEST_TYPE_KNOWN && type != SIZE_TEST_TYPE_UNKNOWN)
721 GURL url(type == SIZE_TEST_TYPE_KNOWN ?
722 URLRequestSlowDownloadJob::kKnownSizeUrl :
723 URLRequestSlowDownloadJob::kUnknownSizeUrl);
725 // TODO(ahendrickson) -- |expected_title_in_progress| and
726 // |expected_title_finished| need to be checked.
727 base::FilePath filename;
728 net::FileURLToFilePath(url, &filename);
729 base::string16 expected_title_in_progress(
730 base::ASCIIToUTF16(partial_indication) + filename.LossyDisplayName());
731 base::string16 expected_title_finished(
732 base::ASCIIToUTF16(total_indication) + filename.LossyDisplayName());
734 // Download a partial web page in a background tab and wait.
735 // The mock system will not complete until it gets a special URL.
736 scoped_ptr<content::DownloadTestObserver> observer(
737 CreateWaiter(browser, 1));
738 ui_test_utils::NavigateToURL(browser, url);
740 // TODO(ahendrickson): check download status text before downloading.
742 // - Add a member function to the |DownloadShelf| interface class, that
743 // indicates how many members it has.
744 // - Add a member function to |DownloadShelf| to get the status text
745 // of a given member (for example, via the name in |DownloadItemView|'s
746 // GetAccessibleState() member function), by index.
747 // - Iterate over browser->window()->GetDownloadShelf()'s members
748 // to see if any match the status text we want. Start with the last one.
750 // Allow the request to finish. We do this by loading a second URL in a
752 GURL finish_url(URLRequestSlowDownloadJob::kFinishDownloadUrl);
753 ui_test_utils::NavigateToURLWithDisposition(
757 ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
758 observer->WaitForFinished();
759 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::COMPLETE));
760 CheckDownloadStatesForBrowser(browser, 1, DownloadItem::COMPLETE);
762 EXPECT_EQ(2, browser->tab_strip_model()->count());
764 // TODO(ahendrickson): check download status text after downloading.
766 base::FilePath basefilename(filename.BaseName());
767 net::FileURLToFilePath(url, &filename);
768 base::FilePath download_path =
769 downloads_directory_.path().Append(basefilename);
770 EXPECT_TRUE(browser->window()->IsDownloadShelfVisible());
772 bool downloaded_path_exists = base::PathExists(download_path);
773 EXPECT_TRUE(downloaded_path_exists);
774 if (!downloaded_path_exists)
777 // Check the file contents.
778 size_t file_size = URLRequestSlowDownloadJob::kFirstDownloadSize +
779 URLRequestSlowDownloadJob::kSecondDownloadSize;
780 std::string expected_contents(file_size, '*');
781 EXPECT_TRUE(VerifyFile(download_path, expected_contents, file_size));
783 // Delete the file we just downloaded.
784 EXPECT_TRUE(base::DieFileDie(download_path, true));
785 EXPECT_FALSE(base::PathExists(download_path));
790 void GetDownloads(Browser* browser, std::vector<DownloadItem*>* downloads) {
792 DownloadManager* manager = DownloadManagerForBrowser(browser);
793 manager->GetAllDownloads(downloads);
796 static void ExpectWindowCountAfterDownload(size_t expected) {
797 EXPECT_EQ(expected, chrome::GetTotalBrowserCount());
800 void EnableFileChooser(bool enable) {
801 file_activity_observer_->EnableFileChooser(enable);
804 bool DidShowFileChooser() {
805 return file_activity_observer_->TestAndResetDidShowFileChooser();
808 // Checks that |path| is has |file_size| bytes, and matches the |value|
810 bool VerifyFile(const base::FilePath& path,
811 const std::string& value,
812 const int64 file_size) {
813 std::string file_contents;
815 bool read = base::ReadFileToString(path, &file_contents);
816 EXPECT_TRUE(read) << "Failed reading file: " << path.value() << std::endl;
818 return false; // Couldn't read the file.
820 // Note: we don't handle really large files (more than size_t can hold)
821 // so we will fail in that case.
822 size_t expected_size = static_cast<size_t>(file_size);
825 EXPECT_EQ(expected_size, file_contents.size());
826 if (expected_size != file_contents.size())
829 // Check the contents.
830 EXPECT_EQ(value, file_contents);
831 if (memcmp(file_contents.c_str(), value.c_str(), expected_size) != 0)
837 // Attempts to download a file, based on information in |download_info|.
838 // If a Select File dialog opens, will automatically choose the default.
839 void DownloadFilesCheckErrorsSetup() {
840 ASSERT_TRUE(test_server()->Start());
841 std::vector<DownloadItem*> download_items;
842 GetDownloads(browser(), &download_items);
843 ASSERT_TRUE(download_items.empty());
845 EnableFileChooser(true);
848 void DownloadFilesCheckErrorsLoopBody(const DownloadInfo& download_info,
851 s << " " << __FUNCTION__ << "()"
853 << " url = '" << download_info.url_name << "'"
855 << ((download_info.download_method == DOWNLOAD_DIRECT) ?
856 "DOWNLOAD_DIRECT" : "DOWNLOAD_NAVIGATE")
857 << " show_item = " << download_info.show_download_item
858 << " reason = " << DownloadInterruptReasonToString(download_info.reason);
860 std::vector<DownloadItem*> download_items;
861 GetDownloads(browser(), &download_items);
862 size_t downloads_expected = download_items.size();
864 std::string server_path = "files/downloads/";
865 server_path += download_info.url_name;
866 GURL url = test_server()->GetURL(server_path);
867 ASSERT_TRUE(url.is_valid()) << s.str();
869 DownloadManager* download_manager = DownloadManagerForBrowser(browser());
870 WebContents* web_contents =
871 browser()->tab_strip_model()->GetActiveWebContents();
872 ASSERT_TRUE(web_contents) << s.str();
874 scoped_ptr<content::DownloadTestObserver> observer(
875 new content::DownloadTestObserverTerminal(
878 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL));
880 if (download_info.download_method == DOWNLOAD_DIRECT) {
881 // Go directly to download. Don't wait for navigation.
882 scoped_refptr<content::DownloadTestItemCreationObserver>
883 creation_observer(new content::DownloadTestItemCreationObserver);
885 scoped_ptr<DownloadUrlParameters> params(
886 DownloadUrlParameters::FromWebContents(web_contents, url));
887 params->set_callback(creation_observer->callback());
888 DownloadManagerForBrowser(browser())->DownloadUrl(params.Pass());
890 // Wait until the item is created, or we have determined that it
892 creation_observer->WaitForDownloadItemCreation();
894 EXPECT_EQ(download_info.show_download_item,
895 creation_observer->succeeded());
896 if (download_info.show_download_item) {
897 EXPECT_EQ(content::DOWNLOAD_INTERRUPT_REASON_NONE,
898 creation_observer->interrupt_reason());
899 EXPECT_NE(content::DownloadItem::kInvalidId,
900 creation_observer->download_id());
902 EXPECT_NE(content::DOWNLOAD_INTERRUPT_REASON_NONE,
903 creation_observer->interrupt_reason());
904 EXPECT_EQ(content::DownloadItem::kInvalidId,
905 creation_observer->download_id());
908 // Navigate to URL normally, wait until done.
909 ui_test_utils::NavigateToURLBlockUntilNavigationsComplete(browser(),
914 if (download_info.show_download_item) {
915 downloads_expected++;
916 observer->WaitForFinished();
917 DownloadItem::DownloadState final_state =
918 (download_info.reason == content::DOWNLOAD_INTERRUPT_REASON_NONE) ?
919 DownloadItem::COMPLETE :
920 DownloadItem::INTERRUPTED;
921 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(final_state));
924 // Wait till the |DownloadFile|s are destroyed.
925 content::RunAllPendingInMessageLoop(content::BrowserThread::FILE);
926 content::RunAllPendingInMessageLoop(content::BrowserThread::UI);
928 // Validate that the correct files were downloaded.
929 download_items.clear();
930 GetDownloads(browser(), &download_items);
931 ASSERT_EQ(downloads_expected, download_items.size()) << s.str();
933 if (download_info.show_download_item) {
934 // Find the last download item.
935 DownloadItem* item = download_items[0];
936 for (size_t d = 1; d < downloads_expected; ++d) {
937 if (download_items[d]->GetStartTime() > item->GetStartTime())
938 item = download_items[d];
941 ASSERT_EQ(url, item->GetOriginalUrl()) << s.str();
943 ASSERT_EQ(download_info.reason, item->GetLastReason()) << s.str();
945 if (item->GetState() == content::DownloadItem::COMPLETE) {
946 // Clean up the file, in case it ended up in the My Documents folder.
947 base::FilePath destination_folder = GetDownloadDirectory(browser());
948 base::FilePath my_downloaded_file = item->GetTargetFilePath();
949 EXPECT_TRUE(base::PathExists(my_downloaded_file));
950 EXPECT_TRUE(base::DeleteFile(my_downloaded_file, false));
952 EXPECT_EQ(download_info.should_redirect_to_documents ?
955 my_downloaded_file.value().find(destination_folder.value()));
956 if (download_info.should_redirect_to_documents) {
957 // If it's not where we asked it to be, it should be in the
958 // My Documents folder.
959 base::FilePath my_docs_folder;
960 EXPECT_TRUE(PathService::Get(chrome::DIR_USER_DOCUMENTS,
963 my_downloaded_file.value().find(my_docs_folder.value()));
969 // Attempts to download a set of files, based on information in the
970 // |download_info| array. |count| is the number of files.
971 // If a Select File dialog appears, it will choose the default and return
973 void DownloadFilesCheckErrors(size_t count, DownloadInfo* download_info) {
974 DownloadFilesCheckErrorsSetup();
976 for (size_t i = 0; i < count; ++i) {
977 DownloadFilesCheckErrorsLoopBody(download_info[i], i);
981 void DownloadInsertFilesErrorCheckErrorsLoopBody(
982 scoped_refptr<content::TestFileErrorInjector> injector,
983 const FileErrorInjectInfo& info,
986 s << " " << __FUNCTION__ << "()"
988 << " url = " << info.error_info.url
989 << " operation code = "
990 << content::TestFileErrorInjector::DebugString(info.error_info.code)
991 << " instance = " << info.error_info.operation_instance
993 << content::DownloadInterruptReasonToString(info.error_info.error);
995 injector->ClearErrors();
996 injector->AddError(info.error_info);
998 injector->InjectErrors();
1000 DownloadFilesCheckErrorsLoopBody(info.download_info, i);
1002 size_t expected_successes = info.download_info.show_download_item ? 1u : 0u;
1003 EXPECT_EQ(expected_successes, injector->TotalFileCount()) << s.str();
1004 EXPECT_EQ(0u, injector->CurrentFileCount()) << s.str();
1006 if (info.download_info.show_download_item)
1007 EXPECT_TRUE(injector->HadFile(GURL(info.error_info.url))) << s.str();
1010 void DownloadInsertFilesErrorCheckErrors(size_t count,
1011 FileErrorInjectInfo* info) {
1012 DownloadFilesCheckErrorsSetup();
1014 // Set up file failures.
1015 scoped_refptr<content::TestFileErrorInjector> injector(
1016 content::TestFileErrorInjector::Create(
1017 DownloadManagerForBrowser(browser())));
1019 for (size_t i = 0; i < count; ++i) {
1020 // Set up the full URL, for download file tracking.
1021 std::string server_path = "files/downloads/";
1022 server_path += info[i].download_info.url_name;
1023 GURL url = test_server()->GetURL(server_path);
1024 info[i].error_info.url = url.spec();
1026 DownloadInsertFilesErrorCheckErrorsLoopBody(injector, info[i], i);
1030 // Attempts to download a file to a read-only folder, based on information
1031 // in |download_info|.
1032 void DownloadFilesToReadonlyFolder(size_t count,
1033 DownloadInfo* download_info) {
1034 DownloadFilesCheckErrorsSetup();
1036 // Make the test folder unwritable.
1037 base::FilePath destination_folder = GetDownloadDirectory(browser());
1038 DVLOG(1) << " " << __FUNCTION__ << "()"
1039 << " folder = '" << destination_folder.value() << "'";
1040 file_util::PermissionRestorer permission_restorer(destination_folder);
1041 EXPECT_TRUE(file_util::MakeFileUnwritable(destination_folder));
1043 for (size_t i = 0; i < count; ++i) {
1044 DownloadFilesCheckErrorsLoopBody(download_info[i], i);
1048 // A mock install prompt that simulates the user allowing an install request.
1049 void SetAllowMockInstallPrompt() {
1050 download_crx_util::SetMockInstallPromptForTesting(
1051 scoped_ptr<ExtensionInstallPrompt>(
1052 new MockAutoConfirmExtensionInstallPrompt(
1053 browser()->tab_strip_model()->GetActiveWebContents())));
1057 // * Starts a mock download by navigating browser() to a URLRequestMockHTTPJob
1059 // * Injects |error| on the first write using |error_injector|.
1060 // * Waits for the download to be interrupted.
1061 // * Clears the errors on |error_injector|.
1062 // * Returns the resulting interrupted download.
1063 DownloadItem* StartMockDownloadAndInjectError(
1064 content::TestFileErrorInjector* error_injector,
1065 content::DownloadInterruptReason error) {
1066 base::FilePath file_path(FILE_PATH_LITERAL("download-test1.lib"));
1067 GURL url = URLRequestMockHTTPJob::GetMockUrl(file_path);
1069 content::TestFileErrorInjector::FileErrorInfo error_info;
1070 error_info.url = url.spec();
1071 error_info.code = content::TestFileErrorInjector::FILE_OPERATION_WRITE;
1072 error_info.operation_instance = 0;
1073 error_info.error = error;
1074 error_injector->ClearErrors();
1075 error_injector->AddError(error_info);
1076 error_injector->InjectErrors();
1078 scoped_ptr<content::DownloadTestObserver> observer(
1079 new DownloadTestObserverResumable(
1080 DownloadManagerForBrowser(browser()), 1));
1081 ui_test_utils::NavigateToURL(browser(), url);
1082 observer->WaitForFinished();
1084 content::DownloadManager::DownloadVector downloads;
1085 DownloadManagerForBrowser(browser())->GetAllDownloads(&downloads);
1086 EXPECT_EQ(1u, downloads.size());
1088 if (downloads.size() != 1)
1091 error_injector->ClearErrors();
1092 error_injector->InjectErrors();
1093 DownloadItem* download = downloads[0];
1094 EXPECT_EQ(DownloadItem::INTERRUPTED, download->GetState());
1095 EXPECT_EQ(error, download->GetLastReason());
1100 static void EnsureNoPendingDownloadJobsOnIO(bool* result) {
1101 if (URLRequestSlowDownloadJob::NumberOutstandingRequests())
1103 BrowserThread::PostTask(
1104 BrowserThread::UI, FROM_HERE, base::MessageLoop::QuitClosure());
1107 // Location of the test data.
1108 base::FilePath test_dir_;
1110 // Location of the downloads directory for these tests
1111 base::ScopedTempDir downloads_directory_;
1113 scoped_ptr<DownloadTestFileActivityObserver> file_activity_observer_;
1118 // Files for these tests are found in DIR_TEST_DATA (currently
1119 // "chrome\test\data\", see chrome_paths.cc).
1120 // Mock responses have extension .mock-http-headers appended to the file name.
1122 // Download a file due to the associated MIME type.
1123 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadMimeType) {
1124 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
1125 GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
1127 // Download the file and wait. We do not expect the Select File dialog.
1128 DownloadAndWait(browser(), url);
1131 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1132 CheckDownload(browser(), file, file);
1133 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
1137 // Download a file and confirm that the zone identifier (on windows)
1138 // is set to internet.
1139 IN_PROC_BROWSER_TEST_F(DownloadTest, CheckInternetZone) {
1140 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
1141 GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
1143 // Download the file and wait. We do not expect the Select File dialog.
1144 DownloadAndWait(browser(), url);
1146 // Check state. Special file state must be checked before CheckDownload,
1147 // as CheckDownload will delete the output file.
1148 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1149 base::FilePath downloaded_file(DestinationFile(browser(), file));
1150 if (base::VolumeSupportsADS(downloaded_file))
1151 EXPECT_TRUE(base::HasInternetZoneIdentifier(downloaded_file));
1152 CheckDownload(browser(), file, file);
1153 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
1157 // Put up a Select File dialog when the file is downloaded, due to
1158 // downloads preferences settings.
1159 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadMimeTypeSelect) {
1160 // Re-enable prompting.
1161 browser()->profile()->GetPrefs()->SetBoolean(
1162 prefs::kPromptForDownload, true);
1163 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
1164 GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
1166 EnableFileChooser(true);
1168 // Download the file and wait. We expect the Select File dialog to appear
1169 // due to the MIME type, but we still wait until the download completes.
1170 scoped_ptr<content::DownloadTestObserver> observer(
1171 new content::DownloadTestObserverTerminal(
1172 DownloadManagerForBrowser(browser()),
1174 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL));
1175 ui_test_utils::NavigateToURLWithDisposition(
1176 browser(), url, CURRENT_TAB,
1177 ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
1178 observer->WaitForFinished();
1179 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::COMPLETE));
1180 CheckDownloadStates(1, DownloadItem::COMPLETE);
1181 EXPECT_TRUE(DidShowFileChooser());
1184 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1185 CheckDownload(browser(), file, file);
1186 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
1189 // Access a file with a viewable mime-type, verify that a download
1190 // did not initiate.
1191 IN_PROC_BROWSER_TEST_F(DownloadTest, NoDownload) {
1192 base::FilePath file(FILE_PATH_LITERAL("download-test2.html"));
1193 GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
1194 base::FilePath file_path(DestinationFile(browser(), file));
1196 // Open a web page and wait.
1197 ui_test_utils::NavigateToURL(browser(), url);
1199 // Check that we did not download the web page.
1200 EXPECT_FALSE(base::PathExists(file_path));
1203 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1204 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
1207 IN_PROC_BROWSER_TEST_F(DownloadTest, MimeTypesToShowNotDownload) {
1208 ASSERT_TRUE(test_server()->Start());
1210 // These files should all be displayed in the browser.
1211 const char* mime_types[] = {
1212 // It is unclear whether to display text/css or download it.
1213 // Firefox 3: Display
1214 // Internet Explorer 7: Download
1215 // Safari 3.2: Download
1216 // We choose to match Firefox due to the lot of complains
1217 // from the users if css files are downloaded:
1218 // http://code.google.com/p/chromium/issues/detail?id=7192
1222 "application/x-javascript",
1226 "application/xhtml+xml",
1232 for (size_t i = 0; i < arraysize(mime_types); ++i) {
1233 const char* mime_type = mime_types[i];
1234 std::string path("contenttype?");
1235 GURL url(test_server()->GetURL(path + mime_type));
1236 ui_test_utils::NavigateToURL(browser(), url);
1239 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1240 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
1244 // Verify that when the DownloadResourceThrottle cancels a download, the
1245 // download never makes it to the downloads system.
1246 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadResourceThrottleCancels) {
1247 // Navigate to a page with the same domain as the file to download. We can't
1248 // navigate directly to the file we don't want to download because cross-site
1249 // navigations reset the TabDownloadState.
1250 base::FilePath same_site_path(FILE_PATH_LITERAL("download_script.html"));
1251 GURL same_site_url(URLRequestMockHTTPJob::GetMockUrl(same_site_path));
1252 ui_test_utils::NavigateToURL(browser(), same_site_url);
1254 // Make sure the initial navigation didn't trigger a download.
1255 std::vector<content::DownloadItem*> items;
1256 DownloadManagerForBrowser(browser())->GetAllDownloads(&items);
1257 EXPECT_EQ(0u, items.size());
1259 // Disable downloads for the tab.
1260 WebContents* web_contents =
1261 browser()->tab_strip_model()->GetActiveWebContents();
1262 DownloadRequestLimiter::TabDownloadState* tab_download_state =
1263 g_browser_process->download_request_limiter()->GetDownloadState(
1264 web_contents, web_contents, true);
1265 ASSERT_TRUE(tab_download_state);
1266 tab_download_state->set_download_status(
1267 DownloadRequestLimiter::DOWNLOADS_NOT_ALLOWED);
1269 // Try to start the download via Javascript and wait for the corresponding
1271 content::TestNavigationObserver observer(web_contents);
1272 bool download_assempted;
1273 ASSERT_TRUE(content::ExecuteScriptAndExtractBool(
1274 browser()->tab_strip_model()->GetActiveWebContents(),
1275 "window.domAutomationController.send(startDownload());",
1276 &download_assempted));
1277 ASSERT_TRUE(download_assempted);
1280 // Check that we did not download the file.
1281 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
1282 base::FilePath file_path(DestinationFile(browser(), file));
1283 EXPECT_FALSE(base::PathExists(file_path));
1286 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1287 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
1289 // Verify that there's no pending download. The resource throttle
1290 // should have deleted it before it created a download item, so it
1291 // shouldn't be available as a cancelled download either.
1292 DownloadManagerForBrowser(browser())->GetAllDownloads(&items);
1293 EXPECT_EQ(0u, items.size());
1296 // Download a 0-size file with a content-disposition header, verify that the
1297 // download tab opened and the file exists as the filename specified in the
1298 // header. This also ensures we properly handle empty file downloads.
1299 // The download shelf should be visible in the current tab.
1300 IN_PROC_BROWSER_TEST_F(DownloadTest, ContentDisposition) {
1301 base::FilePath file(FILE_PATH_LITERAL("download-test3.gif"));
1302 GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
1303 base::FilePath download_file(
1304 FILE_PATH_LITERAL("download-test3-attachment.gif"));
1306 // Download a file and wait.
1307 DownloadAndWait(browser(), url);
1309 CheckDownload(browser(), download_file, file);
1312 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1313 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
1316 // Test that the download shelf is per-window by starting a download in one
1317 // tab, opening a second tab, closing the shelf, going back to the first tab,
1318 // and checking that the shelf is closed.
1319 IN_PROC_BROWSER_TEST_F(DownloadTest, PerWindowShelf) {
1320 base::FilePath file(FILE_PATH_LITERAL("download-test3.gif"));
1321 GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
1322 base::FilePath download_file(
1323 FILE_PATH_LITERAL("download-test3-attachment.gif"));
1325 // Download a file and wait.
1326 DownloadAndWait(browser(), url);
1328 CheckDownload(browser(), download_file, file);
1331 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1332 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
1334 // Open a second tab and wait.
1335 EXPECT_NE(static_cast<WebContents*>(NULL),
1336 chrome::AddSelectedTabWithURL(browser(), GURL(),
1337 content::PAGE_TRANSITION_TYPED));
1338 EXPECT_EQ(2, browser()->tab_strip_model()->count());
1339 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
1341 // Hide the download shelf.
1342 browser()->window()->GetDownloadShelf()->Close(DownloadShelf::AUTOMATIC);
1343 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
1345 // Go to the first tab.
1346 browser()->tab_strip_model()->ActivateTabAt(0, true);
1347 EXPECT_EQ(2, browser()->tab_strip_model()->count());
1349 // The download shelf should not be visible.
1350 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
1353 // Check whether the downloads shelf is closed when the downloads tab is
1355 IN_PROC_BROWSER_TEST_F(DownloadTest, CloseShelfOnDownloadsTab) {
1356 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
1357 GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
1359 // Download the file and wait. We do not expect the Select File dialog.
1360 DownloadAndWait(browser(), url);
1363 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1364 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
1366 // Open the downloads tab.
1367 chrome::ShowDownloads(browser());
1368 // The shelf should now be closed.
1369 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
1372 // UnknownSize and KnownSize are tests which depend on
1373 // URLRequestSlowDownloadJob to serve content in a certain way. Data will be
1374 // sent in two chunks where the first chunk is 35K and the second chunk is 10K.
1375 // The test will first attempt to download a file; but the server will "pause"
1376 // in the middle until the server receives a second request for
1377 // "download-finish". At that time, the download will finish.
1378 // These tests don't currently test much due to holes in |RunSizeTest()|. See
1379 // comments in that routine for details.
1380 IN_PROC_BROWSER_TEST_F(DownloadTest, UnknownSize) {
1381 ASSERT_TRUE(RunSizeTest(browser(), SIZE_TEST_TYPE_UNKNOWN,
1382 "32.0 KB - ", "100% - "));
1385 IN_PROC_BROWSER_TEST_F(DownloadTest, KnownSize) {
1386 ASSERT_TRUE(RunSizeTest(browser(), SIZE_TEST_TYPE_KNOWN,
1387 "71% - ", "100% - "));
1390 // Test that when downloading an item in Incognito mode, we don't crash when
1391 // closing the last Incognito window (http://crbug.com/13983).
1392 // Also check that the download shelf is not visible after closing the
1393 // Incognito window.
1394 IN_PROC_BROWSER_TEST_F(DownloadTest, IncognitoDownload) {
1395 Browser* incognito = CreateIncognitoBrowser();
1396 ASSERT_TRUE(incognito);
1397 int window_count = chrome::GetTotalBrowserCount();
1398 EXPECT_EQ(2, window_count);
1400 // Download a file in the Incognito window and wait.
1401 CreateAndSetDownloadsDirectory(incognito);
1402 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
1403 GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
1404 // Since |incognito| is a separate browser, we have to set it up explicitly.
1405 incognito->profile()->GetPrefs()->SetBoolean(prefs::kPromptForDownload,
1407 DownloadAndWait(incognito, url);
1409 // We should still have 2 windows.
1410 ExpectWindowCountAfterDownload(2);
1412 // Verify that the download shelf is showing for the Incognito window.
1413 EXPECT_TRUE(incognito->window()->IsDownloadShelfVisible());
1415 #if !defined(OS_MACOSX)
1416 // On Mac OS X, the UI window close is delayed until the outermost
1417 // message loop runs. So it isn't possible to get a BROWSER_CLOSED
1418 // notification inside of a test.
1419 content::WindowedNotificationObserver signal(
1420 chrome::NOTIFICATION_BROWSER_CLOSED,
1421 content::Source<Browser>(incognito));
1424 // Close the Incognito window and don't crash.
1425 chrome::CloseWindow(incognito);
1427 #if !defined(OS_MACOSX)
1429 ExpectWindowCountAfterDownload(1);
1432 // Verify that the regular window does not have a download shelf.
1433 // On ChromeOS, the download panel is common to both profiles, so
1434 // it is still visible.
1435 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
1437 CheckDownload(browser(), file, file);
1440 // Download one file on-record, then download the same file off-record, and test
1441 // that the filename is deduplicated. The previous test tests for a specific
1442 // bug; this next test tests that filename deduplication happens independently
1443 // of DownloadManager/CDMD.
1444 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadTest_IncognitoRegular) {
1445 ASSERT_TRUE(test_server()->Start());
1446 GURL url(test_server()->GetURL("files/downloads/a_zip_file.zip"));
1448 // Read the origin file now so that we can compare the downloaded files to it
1450 base::FilePath origin(OriginFile(base::FilePath(FILE_PATH_LITERAL(
1451 "downloads/a_zip_file.zip"))));
1452 ASSERT_TRUE(base::PathExists(origin));
1453 int64 origin_file_size = 0;
1454 EXPECT_TRUE(base::GetFileSize(origin, &origin_file_size));
1455 std::string original_contents;
1456 EXPECT_TRUE(base::ReadFileToString(origin, &original_contents));
1458 std::vector<DownloadItem*> download_items;
1459 GetDownloads(browser(), &download_items);
1460 ASSERT_TRUE(download_items.empty());
1462 // Download a file in the on-record browser and check that it was downloaded
1464 DownloadAndWaitWithDisposition(browser(),
1467 ui_test_utils::BROWSER_TEST_NONE);
1468 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
1469 GetDownloads(browser(), &download_items);
1470 ASSERT_EQ(1UL, download_items.size());
1471 ASSERT_EQ(base::FilePath(FILE_PATH_LITERAL("a_zip_file.zip")),
1472 download_items[0]->GetTargetFilePath().BaseName());
1473 ASSERT_TRUE(base::PathExists(download_items[0]->GetTargetFilePath()));
1474 EXPECT_TRUE(VerifyFile(download_items[0]->GetTargetFilePath(),
1475 original_contents, origin_file_size));
1477 // Setup an incognito window.
1478 Browser* incognito = CreateIncognitoBrowser();
1479 ASSERT_TRUE(incognito);
1480 int window_count = BrowserList::GetInstance(
1481 browser()->host_desktop_type())->size();
1482 EXPECT_EQ(2, window_count);
1483 incognito->profile()->GetPrefs()->SetFilePath(
1484 prefs::kDownloadDefaultDirectory,
1485 GetDownloadsDirectory());
1486 incognito->profile()->GetPrefs()->SetFilePath(
1487 prefs::kSaveFileDefaultDirectory,
1488 GetDownloadsDirectory());
1490 download_items.clear();
1491 GetDownloads(incognito, &download_items);
1492 ASSERT_TRUE(download_items.empty());
1494 // Download a file in the incognito browser and check that it was downloaded
1496 DownloadAndWaitWithDisposition(incognito,
1499 ui_test_utils::BROWSER_TEST_NONE);
1500 EXPECT_TRUE(incognito->window()->IsDownloadShelfVisible());
1501 GetDownloads(incognito, &download_items);
1502 ASSERT_EQ(1UL, download_items.size());
1503 ASSERT_EQ(base::FilePath(FILE_PATH_LITERAL("a_zip_file (1).zip")),
1504 download_items[0]->GetTargetFilePath().BaseName());
1505 ASSERT_TRUE(base::PathExists(download_items[0]->GetTargetFilePath()));
1506 EXPECT_TRUE(VerifyFile(download_items[0]->GetTargetFilePath(),
1507 original_contents, origin_file_size));
1510 // Navigate to a new background page, but don't download. Confirm that the
1511 // download shelf is not visible and that we have two tabs.
1512 IN_PROC_BROWSER_TEST_F(DownloadTest, DontCloseNewTab1) {
1513 // Because it's an HTML link, it should open a web page rather than
1515 base::FilePath file1(FILE_PATH_LITERAL("download-test2.html"));
1516 GURL url(URLRequestMockHTTPJob::GetMockUrl(file1));
1518 // Open a web page and wait.
1519 ui_test_utils::NavigateToURLWithDisposition(
1523 ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
1525 // We should have two tabs now.
1526 EXPECT_EQ(2, browser()->tab_strip_model()->count());
1527 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
1530 // Download a file in a background tab. Verify that the tab is closed
1531 // automatically, and that the download shelf is visible in the current tab.
1532 IN_PROC_BROWSER_TEST_F(DownloadTest, CloseNewTab1) {
1533 // Download a file in a new background tab and wait. The tab is automatically
1534 // closed when the download begins.
1535 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
1536 GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
1537 DownloadAndWaitWithDisposition(
1543 // When the download finishes, we should still have one tab.
1544 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
1545 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1547 CheckDownload(browser(), file, file);
1550 // Open a web page in the current tab, then download a file in another tab via
1551 // a Javascript call.
1552 // Verify that we have 2 tabs, and the download shelf is visible in the current
1555 // The download_page1.html page contains an openNew() function that opens a
1556 // tab and then downloads download-test1.lib.
1557 IN_PROC_BROWSER_TEST_F(DownloadTest, DontCloseNewTab2) {
1558 // Because it's an HTML link, it should open a web page rather than
1560 base::FilePath file1(FILE_PATH_LITERAL("download_page1.html"));
1561 GURL url(URLRequestMockHTTPJob::GetMockUrl(file1));
1563 // Open a web page and wait.
1564 ui_test_utils::NavigateToURL(browser(), url);
1566 // Download a file in a new tab and wait (via Javascript).
1567 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
1568 DownloadAndWaitWithDisposition(browser(),
1569 GURL("javascript:openNew()"),
1571 ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
1573 // When the download finishes, we should have two tabs.
1574 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
1575 EXPECT_EQ(2, browser()->tab_strip_model()->count());
1577 CheckDownload(browser(), file, file);
1580 // Open a web page in the current tab, open another tab via a Javascript call,
1581 // then download a file in the new tab.
1582 // Verify that we have 2 tabs, and the download shelf is visible in the current
1585 // The download_page2.html page contains an openNew() function that opens a
1587 IN_PROC_BROWSER_TEST_F(DownloadTest, DontCloseNewTab3) {
1588 // Because it's an HTML link, it should open a web page rather than
1590 base::FilePath file1(FILE_PATH_LITERAL("download_page2.html"));
1591 GURL url1(URLRequestMockHTTPJob::GetMockUrl(file1));
1593 // Open a web page and wait.
1594 ui_test_utils::NavigateToURL(browser(), url1);
1596 // Open a new tab and wait.
1597 ui_test_utils::NavigateToURLWithDisposition(
1599 GURL("javascript:openNew()"),
1601 ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
1603 EXPECT_EQ(2, browser()->tab_strip_model()->count());
1605 // Download a file and wait.
1606 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
1607 GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
1608 DownloadAndWaitWithDisposition(browser(),
1611 ui_test_utils::BROWSER_TEST_NONE);
1613 // When the download finishes, we should have two tabs.
1614 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
1615 EXPECT_EQ(2, browser()->tab_strip_model()->count());
1617 CheckDownload(browser(), file, file);
1620 // Open a web page in the current tab, then download a file via Javascript,
1621 // which will do so in a temporary tab.
1622 // Verify that we have 1 tab, and the download shelf is visible.
1624 // The download_page3.html page contains an openNew() function that opens a
1625 // tab with download-test1.lib in the URL. When the URL is determined to be
1626 // a download, the tab is closed automatically.
1627 IN_PROC_BROWSER_TEST_F(DownloadTest, CloseNewTab2) {
1628 // Because it's an HTML link, it should open a web page rather than
1630 base::FilePath file1(FILE_PATH_LITERAL("download_page3.html"));
1631 GURL url(URLRequestMockHTTPJob::GetMockUrl(file1));
1633 // Open a web page and wait.
1634 ui_test_utils::NavigateToURL(browser(), url);
1636 // Download a file and wait.
1637 // The file to download is "download-test1.lib".
1638 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
1639 DownloadAndWaitWithDisposition(browser(),
1640 GURL("javascript:openNew()"),
1642 ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
1644 // When the download finishes, we should still have one tab.
1645 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
1646 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1648 CheckDownload(browser(), file, file);
1651 // Open a web page in the current tab, then call Javascript via a button to
1652 // download a file in a new tab, which is closed automatically when the
1654 // Verify that we have 1 tab, and the download shelf is visible.
1656 // The download_page4.html page contains a form with download-test1.lib as the
1658 IN_PROC_BROWSER_TEST_F(DownloadTest, CloseNewTab3) {
1659 // Because it's an HTML link, it should open a web page rather than
1661 base::FilePath file1(FILE_PATH_LITERAL("download_page4.html"));
1662 GURL url(URLRequestMockHTTPJob::GetMockUrl(file1));
1664 // Open a web page and wait.
1665 ui_test_utils::NavigateToURL(browser(), url);
1667 // Download a file in a new tab and wait. The tab will automatically close
1668 // when the download begins.
1669 // The file to download is "download-test1.lib".
1670 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
1671 DownloadAndWaitWithDisposition(
1673 GURL("javascript:document.getElementById('form').submit()"),
1675 ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
1677 // When the download finishes, we should still have one tab.
1678 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
1679 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1681 CheckDownload(browser(), file, file);
1684 // Download a file in a new window.
1685 // Verify that we have 2 windows, and the download shelf is not visible in the
1686 // first window, but is visible in the second window.
1687 // Close the new window.
1688 // Verify that we have 1 window, and the download shelf is not visible.
1690 // Regression test for http://crbug.com/44454
1691 IN_PROC_BROWSER_TEST_F(DownloadTest, NewWindow) {
1692 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
1693 GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
1694 #if !defined(OS_MACOSX)
1696 Browser* first_browser = browser();
1699 // Download a file in a new window and wait.
1700 DownloadAndWaitWithDisposition(browser(),
1703 ui_test_utils::BROWSER_TEST_NONE);
1705 // When the download finishes, the download shelf SHOULD NOT be visible in
1706 // the first window.
1707 ExpectWindowCountAfterDownload(2);
1708 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1709 // Download shelf should close. Download panel stays open on ChromeOS.
1710 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
1712 // The download shelf SHOULD be visible in the second window.
1713 std::set<Browser*> original_browsers;
1714 original_browsers.insert(browser());
1715 Browser* download_browser =
1716 ui_test_utils::GetBrowserNotInSet(original_browsers);
1717 ASSERT_TRUE(download_browser != NULL);
1718 EXPECT_NE(download_browser, browser());
1719 EXPECT_EQ(1, download_browser->tab_strip_model()->count());
1720 EXPECT_TRUE(download_browser->window()->IsDownloadShelfVisible());
1722 #if !defined(OS_MACOSX)
1723 // On Mac OS X, the UI window close is delayed until the outermost
1724 // message loop runs. So it isn't possible to get a BROWSER_CLOSED
1725 // notification inside of a test.
1726 content::WindowedNotificationObserver signal(
1727 chrome::NOTIFICATION_BROWSER_CLOSED,
1728 content::Source<Browser>(download_browser));
1731 // Close the new window.
1732 chrome::CloseWindow(download_browser);
1734 #if !defined(OS_MACOSX)
1736 EXPECT_EQ(first_browser, browser());
1737 ExpectWindowCountAfterDownload(1);
1740 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1741 // Download shelf should close. Download panel stays open on ChromeOS.
1742 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
1744 CheckDownload(browser(), file, file);
1747 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadHistoryCheck) {
1748 GURL download_url(URLRequestSlowDownloadJob::kKnownSizeUrl);
1749 base::FilePath file(net::GenerateFileName(download_url,
1756 // We use the server so that we can get a redirect and test url_chain
1758 ASSERT_TRUE(test_server()->Start());
1759 GURL redirect_url = test_server()->GetURL(
1760 "server-redirect?" + download_url.spec());
1762 // Download the url and wait until the object has been stored.
1763 base::Time start(base::Time::Now());
1764 HistoryObserver observer(browser()->profile());
1765 observer.SetFilterCallback(base::Bind(&HasDataAndName));
1766 ui_test_utils::NavigateToURL(browser(), redirect_url);
1767 observer.WaitForStored();
1769 // Get the details on what was stored into the history.
1770 scoped_ptr<std::vector<history::DownloadRow> > downloads_in_database;
1771 ASSERT_TRUE(DownloadsHistoryDataCollector(
1772 browser()->profile()).WaitForDownloadInfo(&downloads_in_database));
1773 ASSERT_EQ(1u, downloads_in_database->size());
1775 // Confirm history storage is what you expect for a partially completed
1776 // slow download job.
1777 history::DownloadRow& row(downloads_in_database->at(0));
1778 EXPECT_EQ(DestinationFile(browser(), file), row.target_path);
1779 EXPECT_EQ(DownloadTargetDeterminer::GetCrDownloadPath(
1780 DestinationFile(browser(), file)),
1782 ASSERT_EQ(2u, row.url_chain.size());
1783 EXPECT_EQ(redirect_url.spec(), row.url_chain[0].spec());
1784 EXPECT_EQ(download_url.spec(), row.url_chain[1].spec());
1785 EXPECT_EQ(content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, row.danger_type);
1786 EXPECT_LE(start, row.start_time);
1787 EXPECT_EQ(URLRequestSlowDownloadJob::kFirstDownloadSize, row.received_bytes);
1788 EXPECT_EQ(URLRequestSlowDownloadJob::kFirstDownloadSize
1789 + URLRequestSlowDownloadJob::kSecondDownloadSize, row.total_bytes);
1790 EXPECT_EQ(content::DownloadItem::IN_PROGRESS, row.state);
1791 EXPECT_FALSE(row.opened);
1793 // Finish the download. We're ok relying on the history to be flushed
1794 // at this point as our queries will be behind the history updates
1795 // invoked by completion.
1796 scoped_ptr<content::DownloadTestObserver> download_observer(
1797 CreateWaiter(browser(), 1));
1798 ui_test_utils::NavigateToURL(browser(),
1799 GURL(URLRequestSlowDownloadJob::kErrorDownloadUrl));
1800 download_observer->WaitForFinished();
1801 EXPECT_EQ(1u, download_observer->NumDownloadsSeenInState(
1802 DownloadItem::INTERRUPTED));
1803 base::Time end(base::Time::Now());
1805 // Get what was stored in the history.
1806 ASSERT_TRUE(DownloadsHistoryDataCollector(
1807 browser()->profile()).WaitForDownloadInfo(&downloads_in_database));
1808 ASSERT_EQ(1u, downloads_in_database->size());
1810 // Confirm history storage is what you expect for an interrupted slow download
1811 // job. The download isn't continuable, so there's no intermediate file.
1812 history::DownloadRow& row1(downloads_in_database->at(0));
1813 EXPECT_EQ(DestinationFile(browser(), file), row1.target_path);
1814 EXPECT_TRUE(row1.current_path.empty());
1815 ASSERT_EQ(2u, row1.url_chain.size());
1816 EXPECT_EQ(redirect_url.spec(), row1.url_chain[0].spec());
1817 EXPECT_EQ(download_url.spec(), row1.url_chain[1].spec());
1818 EXPECT_EQ(content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, row1.danger_type);
1819 EXPECT_LE(start, row1.start_time);
1820 EXPECT_GE(end, row1.end_time);
1821 EXPECT_EQ(URLRequestSlowDownloadJob::kFirstDownloadSize,
1822 row1.received_bytes);
1823 EXPECT_EQ(URLRequestSlowDownloadJob::kFirstDownloadSize
1824 + URLRequestSlowDownloadJob::kSecondDownloadSize, row1.total_bytes);
1825 EXPECT_EQ(content::DownloadItem::INTERRUPTED, row1.state);
1826 EXPECT_EQ(content::DOWNLOAD_INTERRUPT_REASON_NETWORK_FAILED,
1827 row1.interrupt_reason);
1828 EXPECT_FALSE(row1.opened);
1831 // Make sure a dangerous file shows up properly in the history.
1832 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadHistoryDangerCheck) {
1833 #if defined(OS_WIN) && defined(USE_ASH)
1834 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
1835 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshBrowserTests))
1839 // .swf file so that it's dangerous on all platforms (including CrOS).
1840 base::FilePath file(FILE_PATH_LITERAL("downloads/dangerous/dangerous.swf"));
1841 GURL download_url(URLRequestMockHTTPJob::GetMockUrl(file));
1843 // Download the url and wait until the object has been stored.
1844 scoped_ptr<content::DownloadTestObserver> download_observer(
1845 new content::DownloadTestObserverTerminal(
1846 DownloadManagerForBrowser(browser()), 1,
1847 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_IGNORE));
1848 base::Time start(base::Time::Now());
1849 HistoryObserver observer(browser()->profile());
1850 observer.SetFilterCallback(base::Bind(&HasDataAndName));
1851 ui_test_utils::NavigateToURL(browser(), download_url);
1852 observer.WaitForStored();
1854 // Get the details on what was stored into the history.
1855 scoped_ptr<std::vector<history::DownloadRow> > downloads_in_database;
1856 ASSERT_TRUE(DownloadsHistoryDataCollector(
1857 browser()->profile()).WaitForDownloadInfo(&downloads_in_database));
1858 ASSERT_EQ(1u, downloads_in_database->size());
1860 // Confirm history storage is what you expect for an unvalidated
1862 history::DownloadRow& row(downloads_in_database->at(0));
1863 EXPECT_EQ(DestinationFile(browser(), file), row.target_path);
1864 EXPECT_NE(DownloadTargetDeterminer::GetCrDownloadPath(
1865 DestinationFile(browser(), file)),
1867 EXPECT_EQ(content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE, row.danger_type);
1868 EXPECT_LE(start, row.start_time);
1869 EXPECT_EQ(content::DownloadItem::IN_PROGRESS, row.state);
1870 EXPECT_FALSE(row.opened);
1872 // Validate the download and wait for it to finish.
1873 std::vector<DownloadItem*> downloads;
1874 DownloadManagerForBrowser(browser())->GetAllDownloads(&downloads);
1875 ASSERT_EQ(1u, downloads.size());
1876 downloads[0]->ValidateDangerousDownload();
1877 download_observer->WaitForFinished();
1879 // Get history details and confirm it's what you expect.
1880 downloads_in_database->clear();
1881 ASSERT_TRUE(DownloadsHistoryDataCollector(
1882 browser()->profile()).WaitForDownloadInfo(&downloads_in_database));
1883 ASSERT_EQ(1u, downloads_in_database->size());
1884 history::DownloadRow& row1(downloads_in_database->at(0));
1885 EXPECT_EQ(DestinationFile(browser(), file), row1.target_path);
1886 EXPECT_EQ(DestinationFile(browser(), file), row1.current_path);
1887 EXPECT_EQ(content::DOWNLOAD_DANGER_TYPE_USER_VALIDATED, row1.danger_type);
1888 EXPECT_LE(start, row1.start_time);
1889 EXPECT_EQ(content::DownloadItem::COMPLETE, row1.state);
1890 EXPECT_FALSE(row1.opened);
1891 // Not checking file size--not relevant to the point of the test, and
1892 // the file size is actually different on Windows and other platforms,
1893 // because for source control simplicity it's actually a text file, and
1894 // there are CRLF transformations for those files.
1897 IN_PROC_BROWSER_TEST_F(DownloadTest, PRE_DownloadTest_History) {
1898 // Download a file and wait for it to be stored.
1899 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
1900 GURL download_url(URLRequestMockHTTPJob::GetMockUrl(file));
1901 HistoryObserver observer(browser()->profile());
1902 DownloadAndWait(browser(), download_url);
1903 observer.WaitForStored();
1904 HistoryServiceFactory::GetForProfile(
1905 browser()->profile(), Profile::IMPLICIT_ACCESS)->FlushForTest(
1906 base::Bind(&base::MessageLoop::Quit,
1907 base::Unretained(base::MessageLoop::current()->current())));
1908 content::RunMessageLoop();
1911 #if defined(OS_CHROMEOS)
1912 #define MAYBE_DownloadTest_History DISABLED_DownloadTest_History
1914 #define MAYBE_DownloadTest_History DownloadTest_History
1916 IN_PROC_BROWSER_TEST_F(DownloadTest, MAYBE_DownloadTest_History) {
1917 // This starts up right after PRE_DownloadTest_History and shares the same
1918 // profile directory.
1919 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
1920 GURL download_url(URLRequestMockHTTPJob::GetMockUrl(file));
1921 std::vector<DownloadItem*> downloads;
1922 content::DownloadManager* manager = DownloadManagerForBrowser(browser());
1924 // Wait for the history to be loaded with a single DownloadItem. Check that
1925 // it's the file that was downloaded in PRE_DownloadTest_History.
1926 CreatedObserver created_observer(manager);
1927 created_observer.Wait();
1928 manager->GetAllDownloads(&downloads);
1929 ASSERT_EQ(1UL, downloads.size());
1930 DownloadItem* item = downloads[0];
1931 EXPECT_EQ(file.value(), item->GetFullPath().BaseName().value());
1932 EXPECT_EQ(file.value(), item->GetTargetFilePath().BaseName().value());
1933 EXPECT_EQ(download_url, item->GetURL());
1934 // The following are set by download-test1.lib.mock-http-headers.
1935 std::string etag = item->GetETag();
1936 base::TrimWhitespaceASCII(etag, base::TRIM_ALL, &etag);
1937 EXPECT_EQ("abracadabra", etag);
1939 std::string last_modified = item->GetLastModifiedTime();
1940 base::TrimWhitespaceASCII(last_modified, base::TRIM_ALL, &last_modified);
1941 EXPECT_EQ("Mon, 13 Nov 2006 20:31:09 GMT", last_modified);
1944 // Test for crbug.com/14505. This tests that chrome:// urls are still functional
1945 // after download of a file while viewing another chrome://.
1946 IN_PROC_BROWSER_TEST_F(DownloadTest, ChromeURLAfterDownload) {
1947 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
1948 GURL download_url(URLRequestMockHTTPJob::GetMockUrl(file));
1949 GURL flags_url(chrome::kChromeUIFlagsURL);
1950 GURL extensions_url(chrome::kChromeUIExtensionsFrameURL);
1952 ui_test_utils::NavigateToURL(browser(), flags_url);
1953 DownloadAndWait(browser(), download_url);
1954 ui_test_utils::NavigateToURL(browser(), extensions_url);
1955 WebContents* contents =
1956 browser()->tab_strip_model()->GetActiveWebContents();
1957 ASSERT_TRUE(contents);
1958 bool webui_responded = false;
1959 EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
1961 "window.domAutomationController.send(window.webuiResponded);",
1963 EXPECT_TRUE(webui_responded);
1966 // Test for crbug.com/12745. This tests that if a download is initiated from
1967 // a chrome:// page that has registered and onunload handler, the browser
1968 // will be able to close.
1969 IN_PROC_BROWSER_TEST_F(DownloadTest, BrowserCloseAfterDownload) {
1970 GURL downloads_url(chrome::kChromeUIFlagsURL);
1971 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
1972 GURL download_url(URLRequestMockHTTPJob::GetMockUrl(file));
1974 ui_test_utils::NavigateToURL(browser(), downloads_url);
1975 WebContents* contents = browser()->tab_strip_model()->GetActiveWebContents();
1976 ASSERT_TRUE(contents);
1977 bool result = false;
1978 EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
1980 "window.onunload = function() { var do_nothing = 0; }; "
1981 "window.domAutomationController.send(true);",
1983 EXPECT_TRUE(result);
1985 DownloadAndWait(browser(), download_url);
1987 content::WindowedNotificationObserver signal(
1988 chrome::NOTIFICATION_BROWSER_CLOSED,
1989 content::Source<Browser>(browser()));
1990 chrome::CloseWindow(browser());
1994 // Test to make sure the 'download' attribute in anchor tag is respected.
1995 IN_PROC_BROWSER_TEST_F(DownloadTest, AnchorDownloadTag) {
1996 base::FilePath file(FILE_PATH_LITERAL("download-anchor-attrib.html"));
1997 GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
1999 // Create a download, wait until it's complete, and confirm
2000 // we're in the expected state.
2001 scoped_ptr<content::DownloadTestObserver> observer(
2002 CreateWaiter(browser(), 1));
2003 ui_test_utils::NavigateToURL(browser(), url);
2004 observer->WaitForFinished();
2005 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::COMPLETE));
2006 CheckDownloadStates(1, DownloadItem::COMPLETE);
2008 // Confirm the downloaded data exists.
2009 base::FilePath downloaded_file = GetDownloadDirectory(browser());
2010 downloaded_file = downloaded_file.Append(FILE_PATH_LITERAL("a_red_dot.png"));
2011 EXPECT_TRUE(base::PathExists(downloaded_file));
2014 // Test to make sure auto-open works.
2015 IN_PROC_BROWSER_TEST_F(DownloadTest, AutoOpen) {
2016 base::FilePath file(FILE_PATH_LITERAL("download-autoopen.txt"));
2017 GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
2020 GetDownloadPrefs(browser())->EnableAutoOpenBasedOnExtension(file));
2022 DownloadAndWait(browser(), url);
2024 // Find the download and confirm it was opened.
2025 std::vector<DownloadItem*> downloads;
2026 DownloadManagerForBrowser(browser())->GetAllDownloads(&downloads);
2027 ASSERT_EQ(1u, downloads.size());
2028 EXPECT_EQ(DownloadItem::COMPLETE, downloads[0]->GetState());
2030 // Unfortunately, this will block forever, causing a timeout, if
2031 // the download is never opened.
2032 content::DownloadUpdatedObserver(
2033 downloads[0], base::Bind(&WasAutoOpened)).WaitForEvent();
2034 EXPECT_TRUE(downloads[0]->GetOpened()); // Confirm it anyway.
2036 // As long as we're here, confirmed everything else is good.
2037 EXPECT_EQ(1, browser()->tab_strip_model()->count());
2038 CheckDownload(browser(), file, file);
2039 // Download shelf should close. Download panel stays open on ChromeOS.
2040 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
2043 // Download an extension. Expect a dangerous download warning.
2044 // Deny the download.
2045 IN_PROC_BROWSER_TEST_F(DownloadTest, CrxDenyInstall) {
2046 FeatureSwitch::ScopedOverride enable_easy_off_store_install(
2047 FeatureSwitch::easy_off_store_install(), true);
2049 GURL extension_url(URLRequestMockHTTPJob::GetMockUrl(kGoodCrxPath));
2051 scoped_ptr<content::DownloadTestObserver> observer(
2052 DangerousDownloadWaiter(
2054 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_DENY));
2055 ui_test_utils::NavigateToURL(browser(), extension_url);
2057 observer->WaitForFinished();
2058 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::CANCELLED));
2059 EXPECT_EQ(1u, observer->NumDangerousDownloadsSeen());
2061 // Download shelf should close.
2062 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
2064 // Check that the CRX is not installed.
2065 ExtensionService* extension_service = extensions::ExtensionSystem::Get(
2066 browser()->profile())->extension_service();
2067 ASSERT_FALSE(extension_service->GetExtensionById(kGoodCrxId, false));
2070 // Download an extension. Expect a dangerous download warning.
2071 // Allow the download, deny the install.
2072 IN_PROC_BROWSER_TEST_F(DownloadTest, CrxInstallDenysPermissions) {
2073 FeatureSwitch::ScopedOverride enable_easy_off_store_install(
2074 FeatureSwitch::easy_off_store_install(), true);
2076 GURL extension_url(URLRequestMockHTTPJob::GetMockUrl(kGoodCrxPath));
2078 // Install a mock install UI that simulates a user denying permission to
2079 // finish the install.
2080 download_crx_util::SetMockInstallPromptForTesting(
2081 scoped_ptr<ExtensionInstallPrompt>(
2082 new MockAbortExtensionInstallPrompt()));
2084 scoped_ptr<content::DownloadTestObserver> observer(
2085 DangerousDownloadWaiter(
2087 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_ACCEPT));
2088 ui_test_utils::NavigateToURL(browser(), extension_url);
2090 observer->WaitForFinished();
2091 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::COMPLETE));
2092 CheckDownloadStates(1, DownloadItem::COMPLETE);
2093 EXPECT_EQ(1u, observer->NumDangerousDownloadsSeen());
2095 // Download shelf should close from auto-open.
2096 content::DownloadManager::DownloadVector downloads;
2097 DownloadManagerForBrowser(browser())->GetAllDownloads(&downloads);
2098 ASSERT_EQ(1u, downloads.size());
2099 content::DownloadUpdatedObserver(
2100 downloads[0], base::Bind(&WasAutoOpened)).WaitForEvent();
2101 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
2103 // Check that the extension was not installed.
2104 ExtensionService* extension_service = extensions::ExtensionSystem::Get(
2105 browser()->profile())->extension_service();
2106 ASSERT_FALSE(extension_service->GetExtensionById(kGoodCrxId, false));
2109 // Download an extension. Expect a dangerous download warning.
2110 // Allow the download, and the install.
2111 IN_PROC_BROWSER_TEST_F(DownloadTest, CrxInstallAcceptPermissions) {
2112 FeatureSwitch::ScopedOverride enable_easy_off_store_install(
2113 FeatureSwitch::easy_off_store_install(), true);
2115 GURL extension_url(URLRequestMockHTTPJob::GetMockUrl(kGoodCrxPath));
2117 // Install a mock install UI that simulates a user allowing permission to
2118 // finish the install.
2119 SetAllowMockInstallPrompt();
2121 scoped_ptr<content::DownloadTestObserver> observer(
2122 DangerousDownloadWaiter(
2124 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_ACCEPT));
2125 ui_test_utils::NavigateToURL(browser(), extension_url);
2127 observer->WaitForFinished();
2128 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::COMPLETE));
2129 CheckDownloadStates(1, DownloadItem::COMPLETE);
2130 EXPECT_EQ(1u, observer->NumDangerousDownloadsSeen());
2132 // Download shelf should close from auto-open.
2133 content::DownloadManager::DownloadVector downloads;
2134 DownloadManagerForBrowser(browser())->GetAllDownloads(&downloads);
2135 ASSERT_EQ(1u, downloads.size());
2136 content::DownloadUpdatedObserver(
2137 downloads[0], base::Bind(&WasAutoOpened)).WaitForEvent();
2138 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
2140 // Check that the extension was installed.
2141 ExtensionService* extension_service = extensions::ExtensionSystem::Get(
2142 browser()->profile())->extension_service();
2143 ASSERT_TRUE(extension_service->GetExtensionById(kGoodCrxId, false));
2146 // Test installing a CRX that fails integrity checks.
2147 IN_PROC_BROWSER_TEST_F(DownloadTest, CrxInvalid) {
2148 base::FilePath file(FILE_PATH_LITERAL("extensions/bad_signature.crx"));
2149 GURL extension_url(URLRequestMockHTTPJob::GetMockUrl(file));
2151 // Install a mock install UI that simulates a user allowing permission to
2152 // finish the install, and dismisses any error message. We check that the
2153 // install failed below.
2154 SetAllowMockInstallPrompt();
2156 scoped_ptr<content::DownloadTestObserver> observer(
2157 DangerousDownloadWaiter(
2159 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_ACCEPT));
2160 ui_test_utils::NavigateToURL(browser(), extension_url);
2162 observer->WaitForFinished();
2163 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::COMPLETE));
2164 CheckDownloadStates(1, DownloadItem::COMPLETE);
2166 // Check that the extension was not installed.
2167 ExtensionService* extension_service = extensions::ExtensionSystem::Get(
2168 browser()->profile())->extension_service();
2169 ASSERT_FALSE(extension_service->GetExtensionById(kGoodCrxId, false));
2172 // Install a large (100kb) theme.
2173 IN_PROC_BROWSER_TEST_F(DownloadTest, CrxLargeTheme) {
2174 FeatureSwitch::ScopedOverride enable_easy_off_store_install(
2175 FeatureSwitch::easy_off_store_install(), true);
2177 GURL extension_url(URLRequestMockHTTPJob::GetMockUrl(kLargeThemePath));
2179 // Install a mock install UI that simulates a user allowing permission to
2180 // finish the install.
2181 SetAllowMockInstallPrompt();
2183 scoped_ptr<content::DownloadTestObserver> observer(
2184 DangerousDownloadWaiter(
2186 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_ACCEPT));
2187 ui_test_utils::NavigateToURL(browser(), extension_url);
2189 observer->WaitForFinished();
2190 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::COMPLETE));
2191 CheckDownloadStates(1, DownloadItem::COMPLETE);
2192 EXPECT_EQ(1u, observer->NumDangerousDownloadsSeen());
2194 // Download shelf should close from auto-open.
2195 content::DownloadManager::DownloadVector downloads;
2196 DownloadManagerForBrowser(browser())->GetAllDownloads(&downloads);
2197 ASSERT_EQ(1u, downloads.size());
2198 content::DownloadUpdatedObserver(
2199 downloads[0], base::Bind(&WasAutoOpened)).WaitForEvent();
2200 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
2202 // Check that the extension was installed.
2203 ExtensionService* extension_service = extensions::ExtensionSystem::Get(
2204 browser()->profile())->extension_service();
2205 ASSERT_TRUE(extension_service->GetExtensionById(kLargeThemeCrxId, false));
2208 // Tests for download initiation functions.
2209 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadUrl) {
2210 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
2211 GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
2213 // DownloadUrl always prompts; return acceptance of whatever it prompts.
2214 EnableFileChooser(true);
2216 WebContents* web_contents =
2217 browser()->tab_strip_model()->GetActiveWebContents();
2218 ASSERT_TRUE(web_contents);
2220 content::DownloadTestObserver* observer(
2221 new content::DownloadTestObserverTerminal(
2222 DownloadManagerForBrowser(browser()), 1,
2223 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL));
2224 scoped_ptr<DownloadUrlParameters> params(
2225 DownloadUrlParameters::FromWebContents(web_contents, url));
2226 params->set_prompt(true);
2227 DownloadManagerForBrowser(browser())->DownloadUrl(params.Pass());
2228 observer->WaitForFinished();
2229 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::COMPLETE));
2230 CheckDownloadStates(1, DownloadItem::COMPLETE);
2231 EXPECT_TRUE(DidShowFileChooser());
2234 EXPECT_EQ(1, browser()->tab_strip_model()->count());
2235 ASSERT_TRUE(CheckDownload(browser(), file, file));
2236 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
2239 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadUrlToPath) {
2240 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
2241 GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
2243 WebContents* web_contents =
2244 browser()->tab_strip_model()->GetActiveWebContents();
2245 ASSERT_TRUE(web_contents);
2247 base::ScopedTempDir other_directory;
2248 ASSERT_TRUE(other_directory.CreateUniqueTempDir());
2249 base::FilePath target_file_full_path
2250 = other_directory.path().Append(file.BaseName());
2251 content::DownloadTestObserver* observer(CreateWaiter(browser(), 1));
2252 scoped_ptr<DownloadUrlParameters> params(
2253 DownloadUrlParameters::FromWebContents(web_contents, url));
2254 params->set_file_path(target_file_full_path);
2255 DownloadManagerForBrowser(browser())->DownloadUrl(params.Pass());
2256 observer->WaitForFinished();
2257 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::COMPLETE));
2260 EXPECT_EQ(1, browser()->tab_strip_model()->count());
2261 ASSERT_TRUE(CheckDownloadFullPaths(browser(),
2262 target_file_full_path,
2265 // Temporary are treated as auto-opened, and after that open won't be
2266 // visible; wait for auto-open and confirm not visible.
2267 std::vector<DownloadItem*> downloads;
2268 DownloadManagerForBrowser(browser())->GetAllDownloads(&downloads);
2269 ASSERT_EQ(1u, downloads.size());
2270 content::DownloadUpdatedObserver(
2271 downloads[0], base::Bind(&WasAutoOpened)).WaitForEvent();
2272 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
2275 IN_PROC_BROWSER_TEST_F(DownloadTest, SavePageNonHTMLViaGet) {
2276 // Do initial setup.
2277 ASSERT_TRUE(test_server()->Start());
2278 EnableFileChooser(true);
2279 std::vector<DownloadItem*> download_items;
2280 GetDownloads(browser(), &download_items);
2281 ASSERT_TRUE(download_items.empty());
2283 // Navigate to a non-HTML resource. The resource also has
2284 // Cache-Control: no-cache set, which normally requires revalidation
2286 GURL url = test_server()->GetURL("files/downloads/image.jpg");
2287 ASSERT_TRUE(url.is_valid());
2288 ui_test_utils::NavigateToURL(browser(), url);
2290 // Stop the test server, and then try to save the page. If cache validation
2291 // is not bypassed then this will fail since the server is no longer
2293 ASSERT_TRUE(test_server()->Stop());
2294 scoped_ptr<content::DownloadTestObserver> waiter(
2295 new content::DownloadTestObserverTerminal(
2296 DownloadManagerForBrowser(browser()), 1,
2297 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL));
2298 chrome::SavePage(browser());
2299 waiter->WaitForFinished();
2300 EXPECT_EQ(1u, waiter->NumDownloadsSeenInState(DownloadItem::COMPLETE));
2301 CheckDownloadStates(1, DownloadItem::COMPLETE);
2303 // Validate that the correct file was downloaded.
2304 GetDownloads(browser(), &download_items);
2305 EXPECT_TRUE(DidShowFileChooser());
2306 ASSERT_EQ(1u, download_items.size());
2307 ASSERT_EQ(url, download_items[0]->GetOriginalUrl());
2309 // Try to download it via a context menu.
2310 scoped_ptr<content::DownloadTestObserver> waiter_context_menu(
2311 new content::DownloadTestObserverTerminal(
2312 DownloadManagerForBrowser(browser()), 1,
2313 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL));
2314 content::ContextMenuParams context_menu_params;
2315 context_menu_params.media_type = blink::WebContextMenuData::MediaTypeImage;
2316 context_menu_params.src_url = url;
2317 context_menu_params.page_url = url;
2318 TestRenderViewContextMenu menu(
2319 browser()->tab_strip_model()->GetActiveWebContents()->GetMainFrame(),
2320 context_menu_params);
2322 menu.ExecuteCommand(IDC_CONTENT_CONTEXT_SAVEIMAGEAS, 0);
2323 waiter_context_menu->WaitForFinished();
2325 1u, waiter_context_menu->NumDownloadsSeenInState(DownloadItem::COMPLETE));
2326 CheckDownloadStates(2, DownloadItem::COMPLETE);
2328 // Validate that the correct file was downloaded via the context menu.
2329 download_items.clear();
2330 GetDownloads(browser(), &download_items);
2331 EXPECT_TRUE(DidShowFileChooser());
2332 ASSERT_EQ(2u, download_items.size());
2333 ASSERT_EQ(url, download_items[0]->GetOriginalUrl());
2334 ASSERT_EQ(url, download_items[1]->GetOriginalUrl());
2337 IN_PROC_BROWSER_TEST_F(DownloadTest, SavePageNonHTMLViaPost) {
2338 // Do initial setup.
2339 ASSERT_TRUE(test_server()->Start());
2340 EnableFileChooser(true);
2341 std::vector<DownloadItem*> download_items;
2342 GetDownloads(browser(), &download_items);
2343 ASSERT_TRUE(download_items.empty());
2345 // Navigate to a form page.
2346 GURL form_url = test_server()->GetURL(
2347 "files/downloads/form_page_to_post.html");
2348 ASSERT_TRUE(form_url.is_valid());
2349 ui_test_utils::NavigateToURL(browser(), form_url);
2351 // Submit the form. This will send a POST reqeuest, and the response is a
2352 // JPEG image. The resource also has Cache-Control: no-cache set,
2353 // which normally requires revalidation each time.
2354 GURL jpeg_url = test_server()->GetURL("files/post/downloads/image.jpg");
2355 ASSERT_TRUE(jpeg_url.is_valid());
2356 WebContents* web_contents =
2357 browser()->tab_strip_model()->GetActiveWebContents();
2358 ASSERT_TRUE(web_contents != NULL);
2359 content::WindowedNotificationObserver observer(
2360 content::NOTIFICATION_NAV_ENTRY_COMMITTED,
2361 content::Source<content::NavigationController>(
2362 &web_contents->GetController()));
2363 content::RenderFrameHost* render_frame_host = web_contents->GetMainFrame();
2364 ASSERT_TRUE(render_frame_host != NULL);
2365 render_frame_host->ExecuteJavaScript(base::ASCIIToUTF16("SubmitForm()"));
2367 EXPECT_EQ(jpeg_url, web_contents->GetURL());
2369 // Stop the test server, and then try to save the page. If cache validation
2370 // is not bypassed then this will fail since the server is no longer
2371 // reachable. This will also fail if it tries to be retrieved via "GET"
2372 // rather than "POST".
2373 ASSERT_TRUE(test_server()->Stop());
2374 scoped_ptr<content::DownloadTestObserver> waiter(
2375 new content::DownloadTestObserverTerminal(
2376 DownloadManagerForBrowser(browser()), 1,
2377 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL));
2378 chrome::SavePage(browser());
2379 waiter->WaitForFinished();
2380 EXPECT_EQ(1u, waiter->NumDownloadsSeenInState(DownloadItem::COMPLETE));
2381 CheckDownloadStates(1, DownloadItem::COMPLETE);
2383 // Validate that the correct file was downloaded.
2384 GetDownloads(browser(), &download_items);
2385 EXPECT_TRUE(DidShowFileChooser());
2386 ASSERT_EQ(1u, download_items.size());
2387 ASSERT_EQ(jpeg_url, download_items[0]->GetOriginalUrl());
2389 // Try to download it via a context menu.
2390 scoped_ptr<content::DownloadTestObserver> waiter_context_menu(
2391 new content::DownloadTestObserverTerminal(
2392 DownloadManagerForBrowser(browser()), 1,
2393 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL));
2394 content::ContextMenuParams context_menu_params;
2395 context_menu_params.media_type = blink::WebContextMenuData::MediaTypeImage;
2396 context_menu_params.src_url = jpeg_url;
2397 context_menu_params.page_url = jpeg_url;
2398 TestRenderViewContextMenu menu(web_contents->GetMainFrame(),
2399 context_menu_params);
2401 menu.ExecuteCommand(IDC_CONTENT_CONTEXT_SAVEIMAGEAS, 0);
2402 waiter_context_menu->WaitForFinished();
2404 1u, waiter_context_menu->NumDownloadsSeenInState(DownloadItem::COMPLETE));
2405 CheckDownloadStates(2, DownloadItem::COMPLETE);
2407 // Validate that the correct file was downloaded via the context menu.
2408 download_items.clear();
2409 GetDownloads(browser(), &download_items);
2410 EXPECT_TRUE(DidShowFileChooser());
2411 ASSERT_EQ(2u, download_items.size());
2412 ASSERT_EQ(jpeg_url, download_items[0]->GetOriginalUrl());
2413 ASSERT_EQ(jpeg_url, download_items[1]->GetOriginalUrl());
2416 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadErrorsServer) {
2417 DownloadInfo download_info[] = {
2418 { // Normal navigated download.
2421 content::DOWNLOAD_INTERRUPT_REASON_NONE,
2425 { // Normal direct download.
2428 content::DOWNLOAD_INTERRUPT_REASON_NONE,
2432 { // Direct download with 404 error.
2433 "there_IS_no_spoon.zip",
2435 content::DOWNLOAD_INTERRUPT_REASON_SERVER_BAD_CONTENT,
2439 { // Navigated download with 404 error.
2440 "there_IS_no_spoon.zip",
2442 content::DOWNLOAD_INTERRUPT_REASON_SERVER_BAD_CONTENT,
2446 { // Direct download with 400 error.
2447 "zip_file_not_found.zip",
2449 content::DOWNLOAD_INTERRUPT_REASON_SERVER_FAILED,
2453 { // Navigated download with 400 error.
2454 "zip_file_not_found.zip",
2456 content::DOWNLOAD_INTERRUPT_REASON_SERVER_FAILED,
2462 DownloadFilesCheckErrors(ARRAYSIZE_UNSAFE(download_info), download_info);
2465 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadErrorsFile) {
2466 FileErrorInjectInfo error_info[] = {
2467 { // Navigated download with injected "Disk full" error in Initialize().
2470 content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE,
2475 content::TestFileErrorInjector::FILE_OPERATION_INITIALIZE,
2477 content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE,
2480 { // Direct download with injected "Disk full" error in Initialize().
2483 content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE,
2488 content::TestFileErrorInjector::FILE_OPERATION_INITIALIZE,
2490 content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE,
2493 { // Navigated download with injected "Disk full" error in Write().
2496 content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE,
2501 content::TestFileErrorInjector::FILE_OPERATION_WRITE,
2503 content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE,
2506 { // Direct download with injected "Disk full" error in Write().
2509 content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE,
2514 content::TestFileErrorInjector::FILE_OPERATION_WRITE,
2516 content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE,
2519 { // Navigated download with injected "Failed" error in Initialize().
2522 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED,
2527 content::TestFileErrorInjector::FILE_OPERATION_INITIALIZE,
2529 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED,
2532 { // Direct download with injected "Failed" error in Initialize().
2535 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED,
2540 content::TestFileErrorInjector::FILE_OPERATION_INITIALIZE,
2542 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED,
2545 { // Navigated download with injected "Failed" error in Write().
2548 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED,
2553 content::TestFileErrorInjector::FILE_OPERATION_WRITE,
2555 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED,
2558 { // Direct download with injected "Failed" error in Write().
2561 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED,
2566 content::TestFileErrorInjector::FILE_OPERATION_WRITE,
2568 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED,
2571 { // Navigated download with injected "Name too long" error in
2575 content::DOWNLOAD_INTERRUPT_REASON_FILE_NAME_TOO_LONG,
2580 content::TestFileErrorInjector::FILE_OPERATION_INITIALIZE,
2582 content::DOWNLOAD_INTERRUPT_REASON_FILE_NAME_TOO_LONG,
2585 { // Direct download with injected "Name too long" error in Initialize().
2588 content::DOWNLOAD_INTERRUPT_REASON_FILE_NAME_TOO_LONG,
2593 content::TestFileErrorInjector::FILE_OPERATION_INITIALIZE,
2595 content::DOWNLOAD_INTERRUPT_REASON_FILE_NAME_TOO_LONG,
2598 { // Navigated download with injected "Name too long" error in Write().
2601 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED,
2606 content::TestFileErrorInjector::FILE_OPERATION_WRITE,
2608 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED,
2611 { // Direct download with injected "Name too long" error in Write().
2614 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED,
2619 content::TestFileErrorInjector::FILE_OPERATION_WRITE,
2621 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED,
2624 { // Direct download with injected "Disk full" error in 2nd Write().
2625 { "06bESSE21Evolution.ppt",
2627 content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE,
2632 content::TestFileErrorInjector::FILE_OPERATION_WRITE,
2634 content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE,
2639 DownloadInsertFilesErrorCheckErrors(ARRAYSIZE_UNSAFE(error_info), error_info);
2642 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadErrorReadonlyFolder) {
2643 DownloadInfo download_info[] = {
2647 // This passes because we switch to the My Documents folder.
2648 content::DOWNLOAD_INTERRUPT_REASON_NONE,
2655 // This passes because we switch to the My Documents folder.
2656 content::DOWNLOAD_INTERRUPT_REASON_NONE,
2662 DownloadFilesToReadonlyFolder(ARRAYSIZE_UNSAFE(download_info), download_info);
2665 // Test that we show a dangerous downloads warning for a dangerous file
2666 // downloaded through a blob: URL.
2667 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadDangerousBlobData) {
2669 // On Windows, if SafeBrowsing is enabled, certain file types (.exe, .cab,
2670 // .msi) will be handled by the DownloadProtectionService. However, if the URL
2671 // is non-standard (e.g. blob:) then those files won't be handled by the
2672 // DPS. We should be showing the dangerous download warning for any file
2673 // considered dangerous and isn't handled by the DPS.
2674 const char kFilename[] = "foo.exe";
2676 const char kFilename[] = "foo.swf";
2679 std::string path("files/downloads/download-dangerous-blob.html?filename=");
2682 // Need to use http urls because the blob js doesn't work on file urls for
2683 // security reasons.
2684 ASSERT_TRUE(test_server()->Start());
2685 GURL url(test_server()->GetURL(path));
2687 content::DownloadTestObserver* observer(DangerousDownloadWaiter(
2689 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_ACCEPT));
2690 ui_test_utils::NavigateToURL(browser(), url);
2691 observer->WaitForFinished();
2693 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::COMPLETE));
2694 EXPECT_EQ(1u, observer->NumDangerousDownloadsSeen());
2697 IN_PROC_BROWSER_TEST_F(DownloadTest, LoadURLExternallyReferrerPolicy) {
2698 // Do initial setup.
2699 ASSERT_TRUE(test_server()->Start());
2700 EnableFileChooser(true);
2701 std::vector<DownloadItem*> download_items;
2702 GetDownloads(browser(), &download_items);
2703 ASSERT_TRUE(download_items.empty());
2705 // Navigate to a page with a referrer policy and a link on it. The link points
2706 // to testserver's /echoheader.
2707 GURL url = test_server()->GetURL("files/downloads/referrer_policy.html");
2708 ASSERT_TRUE(url.is_valid());
2709 ui_test_utils::NavigateToURL(browser(), url);
2711 scoped_ptr<content::DownloadTestObserver> waiter(
2712 new content::DownloadTestObserverTerminal(
2713 DownloadManagerForBrowser(browser()), 1,
2714 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL));
2716 // Click on the link with the alt key pressed. This will download the link
2718 WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
2719 blink::WebMouseEvent mouse_event;
2720 mouse_event.type = blink::WebInputEvent::MouseDown;
2721 mouse_event.button = blink::WebMouseEvent::ButtonLeft;
2724 mouse_event.clickCount = 1;
2725 mouse_event.modifiers = blink::WebInputEvent::AltKey;
2726 tab->GetRenderViewHost()->ForwardMouseEvent(mouse_event);
2727 mouse_event.type = blink::WebInputEvent::MouseUp;
2728 tab->GetRenderViewHost()->ForwardMouseEvent(mouse_event);
2730 waiter->WaitForFinished();
2731 EXPECT_EQ(1u, waiter->NumDownloadsSeenInState(DownloadItem::COMPLETE));
2732 CheckDownloadStates(1, DownloadItem::COMPLETE);
2734 // Validate that the correct file was downloaded.
2735 GetDownloads(browser(), &download_items);
2736 ASSERT_EQ(1u, download_items.size());
2737 ASSERT_EQ(test_server()->GetURL("echoheader?Referer"),
2738 download_items[0]->GetOriginalUrl());
2740 // Check that the file contains the expected referrer.
2741 base::FilePath file(download_items[0]->GetTargetFilePath());
2742 std::string expected_contents = test_server()->GetURL(std::string()).spec();
2743 ASSERT_TRUE(VerifyFile(file, expected_contents, expected_contents.length()));
2746 IN_PROC_BROWSER_TEST_F(DownloadTest, HiddenDownload) {
2747 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
2748 GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
2750 DownloadManager* download_manager = DownloadManagerForBrowser(browser());
2751 scoped_ptr<content::DownloadTestObserver> observer(
2752 new content::DownloadTestObserverTerminal(
2755 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL));
2757 // Download and set IsHiddenDownload to true.
2758 WebContents* web_contents =
2759 browser()->tab_strip_model()->GetActiveWebContents();
2760 scoped_ptr<DownloadUrlParameters> params(
2761 DownloadUrlParameters::FromWebContents(web_contents, url));
2762 params->set_callback(base::Bind(&SetHiddenDownloadCallback));
2763 download_manager->DownloadUrl(params.Pass());
2764 observer->WaitForFinished();
2766 // Verify that download shelf is not shown.
2767 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
2770 // Verify the multiple downloads infobar.
2771 IN_PROC_BROWSER_TEST_F(DownloadTest, TestMultipleDownloadsInfobar) {
2772 #if defined(OS_WIN) && defined(USE_ASH)
2773 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
2774 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshBrowserTests))
2778 ASSERT_TRUE(test_server()->Start());
2780 // Create a downloads observer.
2781 scoped_ptr<content::DownloadTestObserver> downloads_observer(
2782 CreateWaiter(browser(), 2));
2784 // Create an infobar observer.
2785 content::WindowedNotificationObserver infobar_added_1(
2786 chrome::NOTIFICATION_TAB_CONTENTS_INFOBAR_ADDED,
2787 content::NotificationService::AllSources());
2788 ui_test_utils::NavigateToURL(
2790 test_server()->GetURL("files/downloads/download-a_zip_file.html"));
2791 infobar_added_1.Wait();
2793 InfoBarService* infobar_service = InfoBarService::FromWebContents(
2794 browser()->tab_strip_model()->GetActiveWebContents());
2795 // Verify that there is only one infobar.
2796 ASSERT_EQ(1u, infobar_service->infobar_count());
2798 // Get the infobar at index 0.
2799 infobars::InfoBar* infobar = infobar_service->infobar_at(0);
2800 ConfirmInfoBarDelegate* confirm_infobar =
2801 infobar->delegate()->AsConfirmInfoBarDelegate();
2802 ASSERT_TRUE(confirm_infobar != NULL);
2804 // Verify multi download warning infobar message.
2805 EXPECT_EQ(confirm_infobar->GetMessageText(),
2806 l10n_util::GetStringUTF16(IDS_MULTI_DOWNLOAD_WARNING));
2808 // Click on the "Allow" button to allow multiple downloads.
2809 if (confirm_infobar->Accept())
2810 infobar_service->RemoveInfoBar(infobar);
2811 // Verify that there are no more infobars.
2812 EXPECT_EQ(0u, infobar_service->infobar_count());
2814 // Waits for the download to complete.
2815 downloads_observer->WaitForFinished();
2816 EXPECT_EQ(2u, downloads_observer->NumDownloadsSeenInState(
2817 DownloadItem::COMPLETE));
2820 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadTest_Renaming) {
2821 ASSERT_TRUE(test_server()->Start());
2822 GURL url(test_server()->GetURL("files/downloads/a_zip_file.zip"));
2823 content::DownloadManager* manager = DownloadManagerForBrowser(browser());
2824 base::FilePath origin_file(OriginFile(base::FilePath(FILE_PATH_LITERAL(
2825 "downloads/a_zip_file.zip"))));
2826 ASSERT_TRUE(base::PathExists(origin_file));
2827 std::string origin_contents;
2828 ASSERT_TRUE(base::ReadFileToString(origin_file, &origin_contents));
2830 // Download the same url several times and expect that all downloaded files
2831 // after the zero-th contain a deduplication counter.
2832 for (int index = 0; index < 5; ++index) {
2833 DownloadAndWait(browser(), url);
2834 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
2835 content::DownloadItem* item = manager->GetDownload(
2836 content::DownloadItem::kInvalidId + 1 + index);
2838 ASSERT_EQ(DownloadItem::COMPLETE, item->GetState());
2839 base::FilePath target_path(item->GetTargetFilePath());
2840 EXPECT_EQ(std::string("a_zip_file") +
2841 (index == 0 ? std::string(".zip") :
2842 base::StringPrintf(" (%d).zip", index)),
2843 target_path.BaseName().AsUTF8Unsafe());
2844 ASSERT_TRUE(base::PathExists(target_path));
2845 ASSERT_TRUE(VerifyFile(target_path, origin_contents,
2846 origin_contents.size()));
2850 // Test that the entire download pipeline handles unicode correctly.
2851 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadTest_CrazyFilenames) {
2852 const wchar_t* kCrazyFilenames[] = {
2854 L"\u89c6\u9891\u76f4\u64ad\u56fe\u7247.zip", // chinese chars
2855 L"\u0412\u043e \u0424\u043b\u043e\u0440\u0438\u0434\u0435\u043e\u0431\u044a"
2856 L"\u044f\u0432\u043b\u0435\u043d\u0440\u0435\u0436\u0438\u043c \u0427"
2857 L"\u041f \u0438\u0437-\u0437\u0430 \u0443\u0442\u0435\u0447\u043a\u0438 "
2858 L"\u043d\u0435\u0444\u0442\u0438.zip", // russian
2859 L"Desocupa\xe7\xe3o est\xe1vel.zip",
2861 L"\u0638\u2026\u0638\u02c6\u0637\xa7\u0638\u201a\u0637\xb9 \u0638\u201e"
2862 L"\u0638\u201e\u0637\xb2\u0638\u0679\u0637\xa7\u0637\xb1\u0637\xa9.zip",
2863 L"\u05d4\u05e2\u05d3\u05e4\u05d5\u05ea.zip", // hebrew
2864 L"\u092d\u093e\u0930\u0924.zip", // hindi
2865 L"d\xe9stabilis\xe9.zip", // french
2867 L"\u97d3-\u4e2d \uc815\uc0c1, \ucc9c\uc548\ud568 \uc758\uacac.zip",
2868 L"jiho....tiho...miho.zip",
2869 L"jiho!@#$tiho$%^&-()_+=miho copy.zip", // special chars
2870 L"Wohoo-to hoo+I.zip",
2872 L"This is a very very long english sentence with spaces and , and +.zip",
2875 std::vector<DownloadItem*> download_items;
2876 base::FilePath origin(FILE_PATH_LITERAL("origin"));
2877 ASSERT_TRUE(base::CreateDirectory(DestinationFile(browser(), origin)));
2879 for (size_t index = 0; index < arraysize(kCrazyFilenames); ++index) {
2880 base::string16 crazy16;
2882 const wchar_t* crazy_w = kCrazyFilenames[index];
2883 ASSERT_TRUE(base::WideToUTF8(crazy_w, wcslen(crazy_w), &crazy8));
2884 ASSERT_TRUE(base::WideToUTF16(crazy_w, wcslen(crazy_w), &crazy16));
2885 base::FilePath file_path(DestinationFile(browser(), origin.Append(
2888 #elif defined(OS_POSIX)
2894 EXPECT_EQ(static_cast<int>(crazy8.size()),
2895 base::WriteFile(file_path, crazy8.c_str(), crazy8.size()));
2896 GURL file_url(net::FilePathToFileURL(file_path));
2898 // Download the file and check that the filename is correct.
2899 DownloadAndWait(browser(), file_url);
2900 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
2901 GetDownloads(browser(), &download_items);
2902 ASSERT_EQ(1UL, download_items.size());
2903 base::FilePath downloaded(download_items[0]->GetTargetFilePath());
2904 download_items[0]->Remove();
2905 download_items.clear();
2906 ASSERT_TRUE(CheckDownloadFullPaths(
2913 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadTest_Remove) {
2914 ASSERT_TRUE(test_server()->Start());
2915 GURL url(test_server()->GetURL("files/downloads/a_zip_file.zip"));
2916 std::vector<DownloadItem*> download_items;
2917 GetDownloads(browser(), &download_items);
2918 ASSERT_TRUE(download_items.empty());
2921 DownloadAndWaitWithDisposition(browser(),
2924 ui_test_utils::BROWSER_TEST_NONE);
2925 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
2926 GetDownloads(browser(), &download_items);
2927 ASSERT_EQ(1UL, download_items.size());
2928 base::FilePath downloaded(download_items[0]->GetTargetFilePath());
2930 // Remove the DownloadItem but not the file, then check that the file still
2932 download_items[0]->Remove();
2933 download_items.clear();
2934 GetDownloads(browser(), &download_items);
2935 ASSERT_EQ(0UL, download_items.size());
2936 ASSERT_TRUE(CheckDownloadFullPaths(
2937 browser(), downloaded, OriginFile(base::FilePath(
2938 FILE_PATH_LITERAL("downloads/a_zip_file.zip")))));
2942 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadTest_PauseResumeCancel) {
2943 DownloadItem* download_item = CreateSlowTestDownload();
2944 ASSERT_TRUE(download_item);
2945 ASSERT_FALSE(download_item->GetTargetFilePath().empty());
2946 EXPECT_FALSE(download_item->IsPaused());
2947 EXPECT_NE(DownloadItem::CANCELLED, download_item->GetState());
2948 download_item->Pause();
2949 EXPECT_TRUE(download_item->IsPaused());
2950 download_item->Resume();
2951 EXPECT_FALSE(download_item->IsPaused());
2952 EXPECT_NE(DownloadItem::CANCELLED, download_item->GetState());
2953 download_item->Cancel(true);
2954 EXPECT_EQ(DownloadItem::CANCELLED, download_item->GetState());
2957 // The Mac downloaded files quarantine feature is implemented by the
2958 // Contents/Info.plist file in cocoa apps. browser_tests cannot test
2959 // quarantining files on Mac because it is not a cocoa app.
2960 // TODO(benjhayden) test the equivalents on other platforms.
2962 #if defined(OS_LINUX) && !defined(OS_CHROMEOS) && defined(ARCH_CPU_ARM_FAMILY)
2963 // Timing out on ARM linux: http://crbug.com/238459
2964 #define MAYBE_DownloadTest_PercentComplete DISABLED_DownloadTest_PercentComplete
2965 #elif defined(OS_MACOSX)
2966 // Disable on mac: http://crbug.com/238831
2967 #define MAYBE_DownloadTest_PercentComplete DISABLED_DownloadTest_PercentComplete
2969 #define MAYBE_DownloadTest_PercentComplete DownloadTest_PercentComplete
2971 IN_PROC_BROWSER_TEST_F(DownloadTest, MAYBE_DownloadTest_PercentComplete) {
2972 // Write a huge file.
2973 base::FilePath file_path(DestinationFile(
2974 browser(), base::FilePath(FILE_PATH_LITERAL("DownloadTest_BigZip.zip"))));
2975 base::File file(file_path, base::File::FLAG_CREATE | base::File::FLAG_WRITE);
2976 ASSERT_TRUE(file.IsValid());
2977 int64 size = 1 << 25;
2978 EXPECT_EQ(1, file.Write(size, "a", 1));
2981 #if defined(OS_POSIX)
2982 // Make it readable by chronos on chromeos
2983 base::SetPosixFilePermissions(file_path, 0755);
2986 // Ensure that we have enough disk space.
2987 int64 free_space = base::SysInfo::AmountOfFreeDiskSpace(
2988 GetDownloadDirectory(browser()));
2989 ASSERT_LE(size, free_space) << "Not enough disk space to download. Got "
2991 GURL file_url(net::FilePathToFileURL(file_path));
2992 scoped_ptr<content::DownloadTestObserver> progress_waiter(
2993 CreateInProgressWaiter(browser(), 1));
2995 // Start downloading a file, wait for it to be created.
2996 ui_test_utils::NavigateToURLWithDisposition(
2997 browser(), file_url, CURRENT_TAB, ui_test_utils::BROWSER_TEST_NONE);
2998 progress_waiter->WaitForFinished();
2999 EXPECT_EQ(1u, progress_waiter->NumDownloadsSeenInState(
3000 DownloadItem::IN_PROGRESS));
3001 std::vector<DownloadItem*> download_items;
3002 GetDownloads(browser(), &download_items);
3003 ASSERT_EQ(1UL, download_items.size());
3005 // Wait for the download to complete, checking along the way that the
3006 // PercentComplete() never regresses.
3007 PercentWaiter waiter(download_items[0]);
3008 EXPECT_TRUE(waiter.WaitForFinished());
3009 EXPECT_EQ(DownloadItem::COMPLETE, download_items[0]->GetState());
3010 ASSERT_EQ(100, download_items[0]->PercentComplete());
3011 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
3013 // Check that the file downloaded correctly.
3014 ASSERT_TRUE(base::PathExists(download_items[0]->GetTargetFilePath()));
3015 int64 downloaded_size = 0;
3016 ASSERT_TRUE(base::GetFileSize(
3017 download_items[0]->GetTargetFilePath(), &downloaded_size));
3018 ASSERT_EQ(size + 1, downloaded_size);
3019 ASSERT_TRUE(base::DieFileDie(file_path, false));
3020 ASSERT_TRUE(base::DieFileDie(download_items[0]->GetTargetFilePath(), false));
3023 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadTest_DenyDanger) {
3024 ASSERT_TRUE(test_server()->Start());
3025 GURL url(test_server()->GetURL("files/downloads/dangerous/dangerous.crx"));
3026 scoped_ptr<content::DownloadTestObserver> observer(
3027 DangerousDownloadWaiter(
3029 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_DENY));
3030 ui_test_utils::NavigateToURL(browser(), url);
3031 observer->WaitForFinished();
3032 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::CANCELLED));
3033 EXPECT_EQ(1u, observer->NumDangerousDownloadsSeen());
3034 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
3037 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadPrefs_SaveFilePath) {
3038 DownloadPrefs* on_prefs = DownloadServiceFactory::GetForBrowserContext(
3039 browser()->profile())->GetDownloadManagerDelegate()->download_prefs();
3040 DownloadPrefs* off_prefs = DownloadServiceFactory::GetForBrowserContext(
3041 browser()->profile()->GetOffTheRecordProfile())
3042 ->GetDownloadManagerDelegate()->download_prefs();
3043 base::FilePath dir(on_prefs->SaveFilePath());
3044 EXPECT_EQ(dir.value(), off_prefs->SaveFilePath().value());
3046 on_prefs->SetSaveFilePath(dir.AppendASCII("on"));
3047 EXPECT_EQ(dir.AppendASCII("on").value(), on_prefs->SaveFilePath().value());
3048 EXPECT_EQ(dir.AppendASCII("on").value(), off_prefs->SaveFilePath().value());
3050 on_prefs->SetSaveFilePath(dir);
3051 EXPECT_EQ(dir.value(), on_prefs->SaveFilePath().value());
3052 EXPECT_EQ(dir.value(), off_prefs->SaveFilePath().value());
3054 off_prefs->SetSaveFilePath(dir.AppendASCII("off"));
3055 EXPECT_EQ(dir.value(), on_prefs->SaveFilePath().value());
3056 EXPECT_EQ(dir.AppendASCII("off").value(), off_prefs->SaveFilePath().value());
3058 on_prefs->SetSaveFilePath(dir.AppendASCII("on"));
3059 EXPECT_EQ(dir.AppendASCII("on").value(), on_prefs->SaveFilePath().value());
3060 EXPECT_EQ(dir.AppendASCII("off").value(), off_prefs->SaveFilePath().value());
3063 // A download that is interrupted due to a file error should be able to be
3065 IN_PROC_BROWSER_TEST_F(DownloadTest, Resumption_NoPrompt) {
3066 CommandLine::ForCurrentProcess()->AppendSwitch(
3067 switches::kEnableDownloadResumption);
3068 scoped_refptr<content::TestFileErrorInjector> error_injector(
3069 content::TestFileErrorInjector::Create(
3070 DownloadManagerForBrowser(browser())));
3071 scoped_ptr<content::DownloadTestObserver> completion_observer(
3072 CreateWaiter(browser(), 1));
3073 EnableFileChooser(true);
3075 DownloadItem* download = StartMockDownloadAndInjectError(
3077 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED);
3078 ASSERT_TRUE(download);
3081 completion_observer->WaitForFinished();
3084 1u, completion_observer->NumDownloadsSeenInState(DownloadItem::COMPLETE));
3085 EXPECT_FALSE(DidShowFileChooser());
3088 // A download that's interrupted due to a reason that indicates that the target
3089 // path is invalid or unusable should cause a prompt to be displayed on
3091 IN_PROC_BROWSER_TEST_F(DownloadTest, Resumption_WithPrompt) {
3092 CommandLine::ForCurrentProcess()->AppendSwitch(
3093 switches::kEnableDownloadResumption);
3094 scoped_refptr<content::TestFileErrorInjector> error_injector(
3095 content::TestFileErrorInjector::Create(
3096 DownloadManagerForBrowser(browser())));
3097 scoped_ptr<content::DownloadTestObserver> completion_observer(
3098 CreateWaiter(browser(), 1));
3099 EnableFileChooser(true);
3101 DownloadItem* download = StartMockDownloadAndInjectError(
3103 content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE);
3104 ASSERT_TRUE(download);
3107 completion_observer->WaitForFinished();
3110 1u, completion_observer->NumDownloadsSeenInState(DownloadItem::COMPLETE));
3111 EXPECT_TRUE(DidShowFileChooser());
3114 // The user shouldn't be prompted on a resumed download unless a prompt is
3115 // necessary due to the interrupt reason.
3116 IN_PROC_BROWSER_TEST_F(DownloadTest, Resumption_WithPromptAlways) {
3117 CommandLine::ForCurrentProcess()->AppendSwitch(
3118 switches::kEnableDownloadResumption);
3119 browser()->profile()->GetPrefs()->SetBoolean(
3120 prefs::kPromptForDownload, true);
3121 scoped_refptr<content::TestFileErrorInjector> error_injector(
3122 content::TestFileErrorInjector::Create(
3123 DownloadManagerForBrowser(browser())));
3124 scoped_ptr<content::DownloadTestObserver> completion_observer(
3125 CreateWaiter(browser(), 1));
3126 EnableFileChooser(true);
3128 DownloadItem* download = StartMockDownloadAndInjectError(
3130 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED);
3131 ASSERT_TRUE(download);
3133 // Prompts the user initially because of the kPromptForDownload preference.
3134 EXPECT_TRUE(DidShowFileChooser());
3137 completion_observer->WaitForFinished();
3140 1u, completion_observer->NumDownloadsSeenInState(DownloadItem::COMPLETE));
3141 // Shouldn't prompt for resumption.
3142 EXPECT_FALSE(DidShowFileChooser());
3145 // A download that is interrupted due to a transient error should be resumed
3147 IN_PROC_BROWSER_TEST_F(DownloadTest, Resumption_Automatic) {
3148 CommandLine::ForCurrentProcess()->AppendSwitch(
3149 switches::kEnableDownloadResumption);
3150 scoped_refptr<content::TestFileErrorInjector> error_injector(
3151 content::TestFileErrorInjector::Create(
3152 DownloadManagerForBrowser(browser())));
3154 DownloadItem* download = StartMockDownloadAndInjectError(
3156 content::DOWNLOAD_INTERRUPT_REASON_FILE_TRANSIENT_ERROR);
3157 ASSERT_TRUE(download);
3159 // The number of times this the download is resumed automatically is defined
3160 // in DownloadItemImpl::kMaxAutoResumeAttempts. The number of DownloadFiles
3161 // created should be that number + 1 (for the original download request). We
3162 // only care that it is greater than 1.
3163 EXPECT_GT(1u, error_injector->TotalFileCount());
3166 // An interrupting download should be resumable multiple times.
3167 IN_PROC_BROWSER_TEST_F(DownloadTest, Resumption_MultipleAttempts) {
3168 CommandLine::ForCurrentProcess()->AppendSwitch(
3169 switches::kEnableDownloadResumption);
3170 scoped_refptr<content::TestFileErrorInjector> error_injector(
3171 content::TestFileErrorInjector::Create(
3172 DownloadManagerForBrowser(browser())));
3173 scoped_ptr<DownloadTestObserverNotInProgress> completion_observer(
3174 new DownloadTestObserverNotInProgress(
3175 DownloadManagerForBrowser(browser()), 1));
3176 // Wait for two transitions to a resumable state
3177 scoped_ptr<content::DownloadTestObserver> resumable_observer(
3178 new DownloadTestObserverResumable(
3179 DownloadManagerForBrowser(browser()), 2));
3181 EnableFileChooser(true);
3182 DownloadItem* download = StartMockDownloadAndInjectError(
3184 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED);
3185 ASSERT_TRUE(download);
3187 content::TestFileErrorInjector::FileErrorInfo error_info;
3188 error_info.url = download->GetOriginalUrl().spec();
3189 error_info.code = content::TestFileErrorInjector::FILE_OPERATION_WRITE;
3190 error_info.operation_instance = 0;
3191 error_info.error = content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED;
3192 error_injector->AddError(error_info);
3193 error_injector->InjectErrors();
3195 // Resuming should cause the download to be interrupted again due to the
3196 // errors we are injecting.
3198 resumable_observer->WaitForFinished();
3199 ASSERT_EQ(DownloadItem::INTERRUPTED, download->GetState());
3200 ASSERT_EQ(content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED,
3201 download->GetLastReason());
3203 error_injector->ClearErrors();
3204 error_injector->InjectErrors();
3206 // No errors this time. The download should complete successfully.
3207 EXPECT_FALSE(completion_observer->IsFinished());
3208 completion_observer->StartObserving();
3210 completion_observer->WaitForFinished();
3211 EXPECT_EQ(DownloadItem::COMPLETE, download->GetState());
3213 EXPECT_FALSE(DidShowFileChooser());