Update V8 to version 4.6.22.
[chromium-blink-merge.git] / chrome / browser / download / download_browsertest.cc
blob9e78564821e612184908eace40d343e59a8a7f78
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include <sstream>
7 #include "base/bind.h"
8 #include "base/bind_helpers.h"
9 #include "base/command_line.h"
10 #include "base/files/file.h"
11 #include "base/files/file_path.h"
12 #include "base/files/file_util.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_number_conversions.h"
19 #include "base/strings/string_split.h"
20 #include "base/strings/string_util.h"
21 #include "base/strings/stringprintf.h"
22 #include "base/strings/utf_string_conversions.h"
23 #include "base/sys_info.h"
24 #include "base/test/test_file_util.h"
25 #include "chrome/app/chrome_command_ids.h"
26 #include "chrome/browser/browser_process.h"
27 #include "chrome/browser/chrome_notification_types.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_install_prompt_show_params.h"
42 #include "chrome/browser/extensions/extension_service.h"
43 #include "chrome/browser/history/history_service_factory.h"
44 #include "chrome/browser/infobars/infobar_service.h"
45 #include "chrome/browser/net/url_request_mock_util.h"
46 #include "chrome/browser/profiles/profile.h"
47 #include "chrome/browser/renderer_context_menu/render_view_context_menu_browsertest_util.h"
48 #include "chrome/browser/renderer_context_menu/render_view_context_menu_test_util.h"
49 #include "chrome/browser/ui/browser.h"
50 #include "chrome/browser/ui/browser_commands.h"
51 #include "chrome/browser/ui/browser_finder.h"
52 #include "chrome/browser/ui/browser_list.h"
53 #include "chrome/browser/ui/browser_tabstrip.h"
54 #include "chrome/browser/ui/browser_window.h"
55 #include "chrome/browser/ui/chrome_pages.h"
56 #include "chrome/browser/ui/host_desktop.h"
57 #include "chrome/browser/ui/tabs/tab_strip_model.h"
58 #include "chrome/browser/ui/website_settings/permission_bubble_manager.h"
59 #include "chrome/common/chrome_paths.h"
60 #include "chrome/common/chrome_switches.h"
61 #include "chrome/common/pref_names.h"
62 #include "chrome/common/safe_browsing/csd.pb.h"
63 #include "chrome/common/url_constants.h"
64 #include "chrome/grit/generated_resources.h"
65 #include "chrome/test/base/in_process_browser_test.h"
66 #include "chrome/test/base/test_switches.h"
67 #include "chrome/test/base/ui_test_utils.h"
68 #include "components/history/content/browser/download_constants_utils.h"
69 #include "components/history/core/browser/download_constants.h"
70 #include "components/history/core/browser/download_row.h"
71 #include "components/history/core/browser/history_service.h"
72 #include "components/infobars/core/confirm_infobar_delegate.h"
73 #include "components/infobars/core/infobar.h"
74 #include "content/public/browser/download_interrupt_reasons.h"
75 #include "content/public/browser/download_item.h"
76 #include "content/public/browser/download_manager.h"
77 #include "content/public/browser/download_save_info.h"
78 #include "content/public/browser/download_url_parameters.h"
79 #include "content/public/browser/notification_source.h"
80 #include "content/public/browser/render_frame_host.h"
81 #include "content/public/browser/render_view_host.h"
82 #include "content/public/browser/resource_context.h"
83 #include "content/public/browser/web_contents.h"
84 #include "content/public/common/content_switches.h"
85 #include "content/public/common/context_menu_params.h"
86 #include "content/public/test/browser_test_utils.h"
87 #include "content/public/test/download_test_observer.h"
88 #include "content/public/test/test_file_error_injector.h"
89 #include "content/public/test/test_navigation_observer.h"
90 #include "extensions/browser/extension_system.h"
91 #include "extensions/common/feature_switch.h"
92 #include "net/base/filename_util.h"
93 #include "net/test/embedded_test_server/embedded_test_server.h"
94 #include "net/test/embedded_test_server/http_request.h"
95 #include "net/test/embedded_test_server/http_response.h"
96 #include "net/test/url_request/url_request_mock_http_job.h"
97 #include "net/test/url_request/url_request_slow_download_job.h"
98 #include "testing/gtest/include/gtest/gtest.h"
99 #include "ui/base/l10n/l10n_util.h"
100 #include "ui/base/page_transition_types.h"
102 #if defined(FULL_SAFE_BROWSING)
103 #include "chrome/browser/safe_browsing/download_feedback_service.h"
104 #include "chrome/browser/safe_browsing/download_protection_service.h"
105 #include "chrome/browser/safe_browsing/safe_browsing_database.h"
106 #include "chrome/browser/safe_browsing/safe_browsing_service.h"
107 #endif
109 using content::BrowserContext;
110 using content::BrowserThread;
111 using content::DownloadItem;
112 using content::DownloadManager;
113 using content::DownloadUrlParameters;
114 using content::WebContents;
115 using extensions::Extension;
116 using extensions::FeatureSwitch;
117 using net::URLRequestMockHTTPJob;
119 namespace {
121 class CreatedObserver : public content::DownloadManager::Observer {
122 public:
123 explicit CreatedObserver(content::DownloadManager* manager)
124 : manager_(manager),
125 waiting_(false) {
126 manager->AddObserver(this);
128 ~CreatedObserver() override {
129 if (manager_)
130 manager_->RemoveObserver(this);
133 void Wait() {
134 std::vector<DownloadItem*> downloads;
135 manager_->GetAllDownloads(&downloads);
136 if (!downloads.empty())
137 return;
138 waiting_ = true;
139 content::RunMessageLoop();
140 waiting_ = false;
143 private:
144 void OnDownloadCreated(content::DownloadManager* manager,
145 content::DownloadItem* item) override {
146 DCHECK_EQ(manager_, manager);
147 if (waiting_)
148 base::MessageLoopForUI::current()->Quit();
151 content::DownloadManager* manager_;
152 bool waiting_;
154 DISALLOW_COPY_AND_ASSIGN(CreatedObserver);
157 class PercentWaiter : public content::DownloadItem::Observer {
158 public:
159 explicit PercentWaiter(DownloadItem* item)
160 : item_(item),
161 waiting_(false),
162 error_(false),
163 prev_percent_(0) {
164 item_->AddObserver(this);
166 ~PercentWaiter() override {
167 if (item_)
168 item_->RemoveObserver(this);
171 bool WaitForFinished() {
172 if (item_->GetState() == DownloadItem::COMPLETE) {
173 return item_->PercentComplete() == 100;
175 waiting_ = true;
176 content::RunMessageLoop();
177 waiting_ = false;
178 return !error_;
181 private:
182 void OnDownloadUpdated(content::DownloadItem* item) override {
183 DCHECK_EQ(item_, item);
184 if (!error_ &&
185 ((prev_percent_ > item_->PercentComplete()) ||
186 (item_->GetState() == DownloadItem::COMPLETE &&
187 (item_->PercentComplete() != 100)))) {
188 error_ = true;
189 if (waiting_)
190 base::MessageLoopForUI::current()->Quit();
192 if (item_->GetState() == DownloadItem::COMPLETE && waiting_)
193 base::MessageLoopForUI::current()->Quit();
196 void OnDownloadDestroyed(content::DownloadItem* item) override {
197 DCHECK_EQ(item_, item);
198 item_->RemoveObserver(this);
199 item_ = NULL;
202 content::DownloadItem* item_;
203 bool waiting_;
204 bool error_;
205 int prev_percent_;
207 DISALLOW_COPY_AND_ASSIGN(PercentWaiter);
210 // DownloadTestObserver subclass that observes one download until it transitions
211 // from a non-resumable state to a resumable state a specified number of
212 // times. Note that this observer can only observe a single download.
213 class DownloadTestObserverResumable : public content::DownloadTestObserver {
214 public:
215 // Construct a new observer. |transition_count| is the number of times the
216 // download should transition from a non-resumable state to a resumable state.
217 DownloadTestObserverResumable(DownloadManager* download_manager,
218 size_t transition_count)
219 : DownloadTestObserver(download_manager, 1,
220 ON_DANGEROUS_DOWNLOAD_FAIL),
221 was_previously_resumable_(false),
222 transitions_left_(transition_count) {
223 Init();
225 ~DownloadTestObserverResumable() override {}
227 private:
228 bool IsDownloadInFinalState(DownloadItem* download) override {
229 bool is_resumable_now = download->CanResume();
230 if (!was_previously_resumable_ && is_resumable_now)
231 --transitions_left_;
232 was_previously_resumable_ = is_resumable_now;
233 return transitions_left_ == 0;
236 bool was_previously_resumable_;
237 size_t transitions_left_;
239 DISALLOW_COPY_AND_ASSIGN(DownloadTestObserverResumable);
242 // IDs and paths of CRX files used in tests.
243 const char kGoodCrxId[] = "ldnnhddmnhbkjipkidpdiheffobcpfmf";
244 const base::FilePath kGoodCrxPath(FILE_PATH_LITERAL("extensions/good.crx"));
246 const char kLargeThemeCrxId[] = "pjpgmfcmabopnnfonnhmdjglfpjjfkbf";
247 const base::FilePath kLargeThemePath(
248 FILE_PATH_LITERAL("extensions/theme2.crx"));
250 // Get History Information.
251 class DownloadsHistoryDataCollector {
252 public:
253 explicit DownloadsHistoryDataCollector(Profile* profile)
254 : profile_(profile), result_valid_(false) {}
256 bool WaitForDownloadInfo(
257 scoped_ptr<std::vector<history::DownloadRow> >* results) {
258 history::HistoryService* hs = HistoryServiceFactory::GetForProfile(
259 profile_, ServiceAccessType::EXPLICIT_ACCESS);
260 DCHECK(hs);
261 hs->QueryDownloads(
262 base::Bind(&DownloadsHistoryDataCollector::OnQueryDownloadsComplete,
263 base::Unretained(this)));
265 content::RunMessageLoop();
266 if (result_valid_) {
267 *results = results_.Pass();
269 return result_valid_;
272 private:
273 void OnQueryDownloadsComplete(
274 scoped_ptr<std::vector<history::DownloadRow> > entries) {
275 result_valid_ = true;
276 results_ = entries.Pass();
277 base::MessageLoopForUI::current()->Quit();
280 Profile* profile_;
281 scoped_ptr<std::vector<history::DownloadRow> > results_;
282 bool result_valid_;
284 DISALLOW_COPY_AND_ASSIGN(DownloadsHistoryDataCollector);
287 // Mock that simulates a permissions dialog where the user denies
288 // permission to install. TODO(skerner): This could be shared with
289 // extensions tests. Find a common place for this class.
290 class MockAbortExtensionInstallPrompt : public ExtensionInstallPrompt {
291 public:
292 MockAbortExtensionInstallPrompt() :
293 ExtensionInstallPrompt(NULL) {
296 // Simulate a user abort on an extension installation.
297 void ConfirmInstall(Delegate* delegate,
298 const Extension* extension,
299 const ShowDialogCallback& show_dialog_callback) override {
300 delegate->InstallUIAbort(true);
301 base::MessageLoopForUI::current()->Quit();
304 void OnInstallSuccess(const Extension* extension, SkBitmap* icon) override {}
305 void OnInstallFailure(const extensions::CrxInstallError& error) override {}
308 // Mock that simulates a permissions dialog where the user allows
309 // installation.
310 class MockAutoConfirmExtensionInstallPrompt : public ExtensionInstallPrompt {
311 public:
312 explicit MockAutoConfirmExtensionInstallPrompt(
313 content::WebContents* web_contents)
314 : ExtensionInstallPrompt(web_contents) {}
316 // Proceed without confirmation prompt.
317 void ConfirmInstall(Delegate* delegate,
318 const Extension* extension,
319 const ShowDialogCallback& show_dialog_callback) override {
320 delegate->InstallUIProceed();
323 void OnInstallSuccess(const Extension* extension, SkBitmap* icon) override {}
324 void OnInstallFailure(const extensions::CrxInstallError& error) override {}
327 static DownloadManager* DownloadManagerForBrowser(Browser* browser) {
328 return BrowserContext::GetDownloadManager(browser->profile());
331 bool WasAutoOpened(DownloadItem* item) {
332 return item->GetAutoOpened();
335 // Called when a download starts. Marks the download as hidden.
336 void SetHiddenDownloadCallback(DownloadItem* item,
337 content::DownloadInterruptReason reason) {
338 DownloadItemModel(item).SetShouldShowInShelf(false);
341 // Callback for HistoryObserver; used in DownloadHistoryCheck
342 bool HasDataAndName(const history::DownloadRow& row) {
343 return row.received_bytes > 0 && !row.target_path.empty();
346 } // namespace
348 DownloadTestObserverNotInProgress::DownloadTestObserverNotInProgress(
349 DownloadManager* download_manager,
350 size_t count)
351 : DownloadTestObserver(download_manager, count, ON_DANGEROUS_DOWNLOAD_FAIL),
352 started_observing_(false) {
353 Init();
356 DownloadTestObserverNotInProgress::~DownloadTestObserverNotInProgress() {}
358 void DownloadTestObserverNotInProgress::StartObserving() {
359 started_observing_ = true;
362 bool DownloadTestObserverNotInProgress::IsDownloadInFinalState(
363 DownloadItem* download) {
364 return started_observing_ &&
365 download->GetState() != DownloadItem::IN_PROGRESS;
368 class HistoryObserver : public DownloadHistory::Observer {
369 public:
370 typedef base::Callback<bool(const history::DownloadRow&)> FilterCallback;
372 explicit HistoryObserver(Profile* profile)
373 : profile_(profile),
374 waiting_(false),
375 seen_stored_(false) {
376 DownloadServiceFactory::GetForBrowserContext(profile_)->
377 GetDownloadHistory()->AddObserver(this);
380 ~HistoryObserver() override {
381 DownloadService* service = DownloadServiceFactory::GetForBrowserContext(
382 profile_);
383 if (service && service->GetDownloadHistory())
384 service->GetDownloadHistory()->RemoveObserver(this);
387 void SetFilterCallback(const FilterCallback& callback) {
388 callback_ = callback;
391 void OnDownloadStored(content::DownloadItem* item,
392 const history::DownloadRow& info) override {
393 if (!callback_.is_null() && (!callback_.Run(info)))
394 return;
396 seen_stored_ = true;
397 if (waiting_)
398 base::MessageLoopForUI::current()->Quit();
401 void OnDownloadHistoryDestroyed() override {
402 DownloadServiceFactory::GetForBrowserContext(profile_)->
403 GetDownloadHistory()->RemoveObserver(this);
406 void WaitForStored() {
407 if (seen_stored_)
408 return;
409 waiting_ = true;
410 content::RunMessageLoop();
411 waiting_ = false;
414 private:
415 Profile* profile_;
416 bool waiting_;
417 bool seen_stored_;
418 FilterCallback callback_;
420 DISALLOW_COPY_AND_ASSIGN(HistoryObserver);
423 class DownloadTest : public InProcessBrowserTest {
424 public:
425 // Choice of navigation or direct fetch. Used by |DownloadFileCheckErrors()|.
426 enum DownloadMethod {
427 DOWNLOAD_NAVIGATE,
428 DOWNLOAD_DIRECT
431 // Information passed in to |DownloadFileCheckErrors()|.
432 struct DownloadInfo {
433 const char* url_name; // URL for the download.
434 DownloadMethod download_method; // Navigation or Direct.
435 // Download interrupt reason (NONE is OK).
436 content::DownloadInterruptReason reason;
437 bool show_download_item; // True if the download item appears on the shelf.
438 bool should_redirect_to_documents; // True if we save it in "My Documents".
441 struct FileErrorInjectInfo {
442 DownloadInfo download_info;
443 content::TestFileErrorInjector::FileErrorInfo error_info;
446 DownloadTest() {}
448 void SetUpOnMainThread() override {
449 BrowserThread::PostTask(
450 BrowserThread::IO, FROM_HERE,
451 base::Bind(&chrome_browser_net::SetUrlRequestMocksEnabled, true));
452 ASSERT_TRUE(InitialSetup());
455 void TearDownOnMainThread() override {
456 // Needs to be torn down on the main thread. file_activity_observer_ holds a
457 // reference to the ChromeDownloadManagerDelegate which should be destroyed
458 // on the UI thread.
459 file_activity_observer_.reset();
462 void SetUpCommandLine(base::CommandLine* command_line) override {
463 command_line->AppendSwitch(switches::kDisablePluginsDiscovery);
466 // Returning false indicates a failure of the setup, and should be asserted
467 // in the caller.
468 virtual bool InitialSetup() {
469 bool have_test_dir = PathService::Get(chrome::DIR_TEST_DATA, &test_dir_);
470 EXPECT_TRUE(have_test_dir);
471 if (!have_test_dir)
472 return false;
474 // Sanity check default values for window / tab count and shelf visibility.
475 int window_count = chrome::GetTotalBrowserCount();
476 EXPECT_EQ(1, window_count);
477 EXPECT_EQ(1, browser()->tab_strip_model()->count());
478 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
480 // Set up the temporary download folder.
481 bool created_downloads_dir = CreateAndSetDownloadsDirectory(browser());
482 EXPECT_TRUE(created_downloads_dir);
483 if (!created_downloads_dir)
484 return false;
485 browser()->profile()->GetPrefs()->SetBoolean(
486 prefs::kPromptForDownload, false);
488 DownloadManager* manager = DownloadManagerForBrowser(browser());
489 DownloadPrefs::FromDownloadManager(manager)->ResetAutoOpen();
490 manager->RemoveAllDownloads();
492 file_activity_observer_.reset(
493 new DownloadTestFileActivityObserver(browser()->profile()));
495 return true;
498 protected:
499 enum SizeTestType {
500 SIZE_TEST_TYPE_KNOWN,
501 SIZE_TEST_TYPE_UNKNOWN,
504 base::FilePath GetTestDataDirectory() {
505 base::FilePath test_file_directory;
506 PathService::Get(chrome::DIR_TEST_DATA, &test_file_directory);
507 return test_file_directory;
510 base::FilePath GetDownloadsDirectory() {
511 return downloads_directory_.path();
514 // Location of the file source (the place from which it is downloaded).
515 base::FilePath OriginFile(base::FilePath file) {
516 return test_dir_.Append(file);
519 // Location of the file destination (place to which it is downloaded).
520 base::FilePath DestinationFile(Browser* browser, base::FilePath file) {
521 return GetDownloadDirectory(browser).Append(file.BaseName());
524 // Must be called after browser creation. Creates a temporary
525 // directory for downloads that is auto-deleted on destruction.
526 // Returning false indicates a failure of the function, and should be asserted
527 // in the caller.
528 bool CreateAndSetDownloadsDirectory(Browser* browser) {
529 if (!browser)
530 return false;
532 if (!downloads_directory_.CreateUniqueTempDir())
533 return false;
535 browser->profile()->GetPrefs()->SetFilePath(
536 prefs::kDownloadDefaultDirectory,
537 downloads_directory_.path());
538 browser->profile()->GetPrefs()->SetFilePath(
539 prefs::kSaveFileDefaultDirectory,
540 downloads_directory_.path());
542 return true;
545 DownloadPrefs* GetDownloadPrefs(Browser* browser) {
546 return DownloadPrefs::FromDownloadManager(
547 DownloadManagerForBrowser(browser));
550 base::FilePath GetDownloadDirectory(Browser* browser) {
551 return GetDownloadPrefs(browser)->DownloadPath();
554 // Create a DownloadTestObserverTerminal that will wait for the
555 // specified number of downloads to finish.
556 content::DownloadTestObserver* CreateWaiter(
557 Browser* browser, int num_downloads) {
558 DownloadManager* download_manager = DownloadManagerForBrowser(browser);
559 return new content::DownloadTestObserverTerminal(
560 download_manager, num_downloads,
561 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL);
564 // Create a DownloadTestObserverInProgress that will wait for the
565 // specified number of downloads to start.
566 content::DownloadTestObserver* CreateInProgressWaiter(
567 Browser* browser, int num_downloads) {
568 DownloadManager* download_manager = DownloadManagerForBrowser(browser);
569 return new content::DownloadTestObserverInProgress(
570 download_manager, num_downloads);
573 // Create a DownloadTestObserverTerminal that will wait for the
574 // specified number of downloads to finish, or for
575 // a dangerous download warning to be shown.
576 content::DownloadTestObserver* DangerousDownloadWaiter(
577 Browser* browser,
578 int num_downloads,
579 content::DownloadTestObserver::DangerousDownloadAction
580 dangerous_download_action) {
581 DownloadManager* download_manager = DownloadManagerForBrowser(browser);
582 return new content::DownloadTestObserverTerminal(
583 download_manager, num_downloads, dangerous_download_action);
586 void CheckDownloadStatesForBrowser(Browser* browser,
587 size_t num,
588 DownloadItem::DownloadState state) {
589 std::vector<DownloadItem*> download_items;
590 GetDownloads(browser, &download_items);
592 EXPECT_EQ(num, download_items.size());
594 for (size_t i = 0; i < download_items.size(); ++i) {
595 EXPECT_EQ(state, download_items[i]->GetState()) << " Item " << i;
599 void CheckDownloadStates(size_t num, DownloadItem::DownloadState state) {
600 CheckDownloadStatesForBrowser(browser(), num, state);
603 // Download |url|, then wait for the download to finish.
604 // |disposition| indicates where the navigation occurs (current tab, new
605 // foreground tab, etc).
606 // |browser_test_flags| indicate what to wait for, and is an OR of 0 or more
607 // values in the ui_test_utils::BrowserTestWaitFlags enum.
608 void DownloadAndWaitWithDisposition(Browser* browser,
609 const GURL& url,
610 WindowOpenDisposition disposition,
611 int browser_test_flags) {
612 // Setup notification, navigate, and block.
613 scoped_ptr<content::DownloadTestObserver> observer(
614 CreateWaiter(browser, 1));
615 // This call will block until the condition specified by
616 // |browser_test_flags|, but will not wait for the download to finish.
617 ui_test_utils::NavigateToURLWithDisposition(browser,
618 url,
619 disposition,
620 browser_test_flags);
621 // Waits for the download to complete.
622 observer->WaitForFinished();
623 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::COMPLETE));
624 // We don't expect a file chooser to be shown.
625 EXPECT_FALSE(DidShowFileChooser());
628 // Download a file in the current tab, then wait for the download to finish.
629 void DownloadAndWait(Browser* browser,
630 const GURL& url) {
631 DownloadAndWaitWithDisposition(
632 browser,
633 url,
634 CURRENT_TAB,
635 ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
638 // Should only be called when the download is known to have finished
639 // (in error or not).
640 // Returning false indicates a failure of the function, and should be asserted
641 // in the caller.
642 bool CheckDownload(Browser* browser,
643 const base::FilePath& downloaded_filename,
644 const base::FilePath& origin_filename) {
645 // Find the path to which the data will be downloaded.
646 base::FilePath downloaded_file(
647 DestinationFile(browser, downloaded_filename));
649 // Find the origin path (from which the data comes).
650 base::FilePath origin_file(OriginFile(origin_filename));
651 return CheckDownloadFullPaths(browser, downloaded_file, origin_file);
654 // A version of CheckDownload that allows complete path specification.
655 bool CheckDownloadFullPaths(Browser* browser,
656 const base::FilePath& downloaded_file,
657 const base::FilePath& origin_file) {
658 bool origin_file_exists = base::PathExists(origin_file);
659 EXPECT_TRUE(origin_file_exists) << origin_file.value();
660 if (!origin_file_exists)
661 return false;
663 // Confirm the downloaded data file exists.
664 bool downloaded_file_exists = base::PathExists(downloaded_file);
665 EXPECT_TRUE(downloaded_file_exists) << downloaded_file.value();
666 if (!downloaded_file_exists)
667 return false;
669 int64 origin_file_size = 0;
670 EXPECT_TRUE(base::GetFileSize(origin_file, &origin_file_size));
671 std::string original_file_contents;
672 EXPECT_TRUE(base::ReadFileToString(origin_file, &original_file_contents));
673 EXPECT_TRUE(
674 VerifyFile(downloaded_file, original_file_contents, origin_file_size));
676 // Delete the downloaded copy of the file.
677 bool downloaded_file_deleted = base::DieFileDie(downloaded_file, false);
678 EXPECT_TRUE(downloaded_file_deleted);
679 return downloaded_file_deleted;
682 content::DownloadTestObserver* CreateInProgressDownloadObserver(
683 size_t download_count) {
684 DownloadManager* manager = DownloadManagerForBrowser(browser());
685 return new content::DownloadTestObserverInProgress(
686 manager, download_count);
689 DownloadItem* CreateSlowTestDownload() {
690 scoped_ptr<content::DownloadTestObserver> observer(
691 CreateInProgressDownloadObserver(1));
692 GURL slow_download_url(net::URLRequestSlowDownloadJob::kUnknownSizeUrl);
693 DownloadManager* manager = DownloadManagerForBrowser(browser());
695 EXPECT_EQ(0, manager->NonMaliciousInProgressCount());
696 EXPECT_EQ(0, manager->InProgressCount());
697 if (manager->InProgressCount() != 0)
698 return NULL;
700 ui_test_utils::NavigateToURL(browser(), slow_download_url);
702 observer->WaitForFinished();
703 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::IN_PROGRESS));
705 DownloadManager::DownloadVector items;
706 manager->GetAllDownloads(&items);
708 DownloadItem* new_item = NULL;
709 for (DownloadManager::DownloadVector::iterator iter = items.begin();
710 iter != items.end(); ++iter) {
711 if ((*iter)->GetState() == DownloadItem::IN_PROGRESS) {
712 // There should be only one IN_PROGRESS item.
713 EXPECT_EQ(NULL, new_item);
714 new_item = *iter;
717 return new_item;
720 bool RunSizeTest(Browser* browser,
721 SizeTestType type,
722 const std::string& partial_indication,
723 const std::string& total_indication) {
724 EXPECT_TRUE(type == SIZE_TEST_TYPE_UNKNOWN || type == SIZE_TEST_TYPE_KNOWN);
725 if (type != SIZE_TEST_TYPE_KNOWN && type != SIZE_TEST_TYPE_UNKNOWN)
726 return false;
727 GURL url(type == SIZE_TEST_TYPE_KNOWN ?
728 net::URLRequestSlowDownloadJob::kKnownSizeUrl :
729 net::URLRequestSlowDownloadJob::kUnknownSizeUrl);
731 // TODO(ahendrickson) -- |expected_title_in_progress| and
732 // |expected_title_finished| need to be checked.
733 base::FilePath filename;
734 net::FileURLToFilePath(url, &filename);
735 base::string16 expected_title_in_progress(
736 base::ASCIIToUTF16(partial_indication) + filename.LossyDisplayName());
737 base::string16 expected_title_finished(
738 base::ASCIIToUTF16(total_indication) + filename.LossyDisplayName());
740 // Download a partial web page in a background tab and wait.
741 // The mock system will not complete until it gets a special URL.
742 scoped_ptr<content::DownloadTestObserver> observer(
743 CreateWaiter(browser, 1));
744 ui_test_utils::NavigateToURL(browser, url);
746 // TODO(ahendrickson): check download status text before downloading.
747 // Need to:
748 // - Add a member function to the |DownloadShelf| interface class, that
749 // indicates how many members it has.
750 // - Add a member function to |DownloadShelf| to get the status text
751 // of a given member (for example, via the name in |DownloadItemView|'s
752 // GetAccessibleState() member function), by index.
753 // - Iterate over browser->window()->GetDownloadShelf()'s members
754 // to see if any match the status text we want. Start with the last one.
756 // Allow the request to finish. We do this by loading a second URL in a
757 // separate tab.
758 GURL finish_url(net::URLRequestSlowDownloadJob::kFinishDownloadUrl);
759 ui_test_utils::NavigateToURLWithDisposition(
760 browser,
761 finish_url,
762 NEW_FOREGROUND_TAB,
763 ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
764 observer->WaitForFinished();
765 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::COMPLETE));
766 CheckDownloadStatesForBrowser(browser, 1, DownloadItem::COMPLETE);
768 EXPECT_EQ(2, browser->tab_strip_model()->count());
770 // TODO(ahendrickson): check download status text after downloading.
772 base::FilePath basefilename(filename.BaseName());
773 net::FileURLToFilePath(url, &filename);
774 base::FilePath download_path =
775 downloads_directory_.path().Append(basefilename);
776 EXPECT_TRUE(browser->window()->IsDownloadShelfVisible());
778 bool downloaded_path_exists = base::PathExists(download_path);
779 EXPECT_TRUE(downloaded_path_exists);
780 if (!downloaded_path_exists)
781 return false;
783 // Check the file contents.
784 size_t file_size = net::URLRequestSlowDownloadJob::kFirstDownloadSize +
785 net::URLRequestSlowDownloadJob::kSecondDownloadSize;
786 std::string expected_contents(file_size, '*');
787 EXPECT_TRUE(VerifyFile(download_path, expected_contents, file_size));
789 // Delete the file we just downloaded.
790 EXPECT_TRUE(base::DieFileDie(download_path, true));
791 EXPECT_FALSE(base::PathExists(download_path));
793 return true;
796 void GetDownloads(Browser* browser, std::vector<DownloadItem*>* downloads) {
797 DCHECK(downloads);
798 DownloadManager* manager = DownloadManagerForBrowser(browser);
799 manager->GetAllDownloads(downloads);
802 static void ExpectWindowCountAfterDownload(size_t expected) {
803 EXPECT_EQ(expected, chrome::GetTotalBrowserCount());
806 void EnableFileChooser(bool enable) {
807 file_activity_observer_->EnableFileChooser(enable);
810 bool DidShowFileChooser() {
811 return file_activity_observer_->TestAndResetDidShowFileChooser();
814 // Checks that |path| is has |file_size| bytes, and matches the |value|
815 // string.
816 bool VerifyFile(const base::FilePath& path,
817 const std::string& value,
818 const int64 file_size) {
819 std::string file_contents;
821 bool read = base::ReadFileToString(path, &file_contents);
822 EXPECT_TRUE(read) << "Failed reading file: " << path.value() << std::endl;
823 if (!read)
824 return false; // Couldn't read the file.
826 // Note: we don't handle really large files (more than size_t can hold)
827 // so we will fail in that case.
828 size_t expected_size = static_cast<size_t>(file_size);
830 // Check the size.
831 EXPECT_EQ(expected_size, file_contents.size());
832 if (expected_size != file_contents.size())
833 return false;
835 // Check the contents.
836 EXPECT_EQ(value, file_contents);
837 if (memcmp(file_contents.c_str(), value.c_str(), expected_size) != 0)
838 return false;
840 return true;
843 // Attempts to download a file, based on information in |download_info|.
844 // If a Select File dialog opens, will automatically choose the default.
845 void DownloadFilesCheckErrorsSetup() {
846 embedded_test_server()->ServeFilesFromDirectory(GetTestDataDirectory());
847 ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
848 std::vector<DownloadItem*> download_items;
849 GetDownloads(browser(), &download_items);
850 ASSERT_TRUE(download_items.empty());
852 EnableFileChooser(true);
855 void DownloadFilesCheckErrorsLoopBody(const DownloadInfo& download_info,
856 size_t i) {
857 SCOPED_TRACE(
858 ::testing::Message()
859 << " " << __FUNCTION__ << "()"
860 << " index = " << i << " url = '" << download_info.url_name << "'"
861 << " method = " << ((download_info.download_method == DOWNLOAD_DIRECT)
862 ? "DOWNLOAD_DIRECT"
863 : "DOWNLOAD_NAVIGATE")
864 << " show_item = " << download_info.show_download_item << " reason = "
865 << DownloadInterruptReasonToString(download_info.reason));
867 std::vector<DownloadItem*> download_items;
868 GetDownloads(browser(), &download_items);
869 size_t downloads_expected = download_items.size();
871 std::string server_path = "/downloads/";
872 server_path += download_info.url_name;
873 GURL url = embedded_test_server()->GetURL(server_path);
874 ASSERT_TRUE(url.is_valid());
876 DownloadManager* download_manager = DownloadManagerForBrowser(browser());
877 WebContents* web_contents =
878 browser()->tab_strip_model()->GetActiveWebContents();
879 ASSERT_TRUE(web_contents);
881 scoped_ptr<content::DownloadTestObserver> observer(
882 new content::DownloadTestObserverTerminal(
883 download_manager,
885 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL));
887 if (download_info.download_method == DOWNLOAD_DIRECT) {
888 // Go directly to download. Don't wait for navigation.
889 scoped_refptr<content::DownloadTestItemCreationObserver>
890 creation_observer(new content::DownloadTestItemCreationObserver);
892 scoped_ptr<DownloadUrlParameters> params(
893 DownloadUrlParameters::FromWebContents(web_contents, url));
894 params->set_callback(creation_observer->callback());
895 DownloadManagerForBrowser(browser())->DownloadUrl(params.Pass());
897 // Wait until the item is created, or we have determined that it
898 // won't be.
899 creation_observer->WaitForDownloadItemCreation();
901 ASSERT_EQ(download_info.show_download_item,
902 creation_observer->succeeded());
903 if (download_info.show_download_item) {
904 EXPECT_EQ(content::DOWNLOAD_INTERRUPT_REASON_NONE,
905 creation_observer->interrupt_reason());
906 EXPECT_NE(content::DownloadItem::kInvalidId,
907 creation_observer->download_id());
908 } else {
909 EXPECT_NE(content::DOWNLOAD_INTERRUPT_REASON_NONE,
910 creation_observer->interrupt_reason());
911 EXPECT_EQ(content::DownloadItem::kInvalidId,
912 creation_observer->download_id());
914 } else {
915 // Navigate to URL normally, wait until done.
916 ui_test_utils::NavigateToURL(browser(), url);
919 if (download_info.show_download_item) {
920 downloads_expected++;
921 observer->WaitForFinished();
922 DownloadItem::DownloadState final_state =
923 (download_info.reason == content::DOWNLOAD_INTERRUPT_REASON_NONE) ?
924 DownloadItem::COMPLETE :
925 DownloadItem::INTERRUPTED;
926 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(final_state));
929 // Wait till the |DownloadFile|s are destroyed.
930 content::RunAllPendingInMessageLoop(content::BrowserThread::FILE);
931 content::RunAllPendingInMessageLoop(content::BrowserThread::UI);
933 // Validate that the correct files were downloaded.
934 download_items.clear();
935 GetDownloads(browser(), &download_items);
936 ASSERT_EQ(downloads_expected, download_items.size());
938 if (download_info.show_download_item) {
939 // Find the last download item.
940 DownloadItem* item = download_items[0];
941 for (size_t d = 1; d < downloads_expected; ++d) {
942 if (download_items[d]->GetStartTime() > item->GetStartTime())
943 item = download_items[d];
946 ASSERT_EQ(url, item->GetOriginalUrl());
947 ASSERT_EQ(download_info.reason, item->GetLastReason());
949 if (item->GetState() == content::DownloadItem::COMPLETE) {
950 // Clean up the file, in case it ended up in the My Documents folder.
951 base::FilePath destination_folder = GetDownloadDirectory(browser());
952 base::FilePath my_downloaded_file = item->GetTargetFilePath();
953 EXPECT_TRUE(base::PathExists(my_downloaded_file));
954 EXPECT_TRUE(base::DeleteFile(my_downloaded_file, false));
956 EXPECT_EQ(download_info.should_redirect_to_documents ?
957 std::string::npos :
959 my_downloaded_file.value().find(destination_folder.value()));
960 if (download_info.should_redirect_to_documents) {
961 // If it's not where we asked it to be, it should be in the
962 // My Documents folder.
963 base::FilePath my_docs_folder;
964 EXPECT_TRUE(PathService::Get(chrome::DIR_USER_DOCUMENTS,
965 &my_docs_folder));
966 EXPECT_EQ(0u,
967 my_downloaded_file.value().find(my_docs_folder.value()));
973 // Attempts to download a set of files, based on information in the
974 // |download_info| array. |count| is the number of files.
975 // If a Select File dialog appears, it will choose the default and return
976 // immediately.
977 void DownloadFilesCheckErrors(size_t count, DownloadInfo* download_info) {
978 DownloadFilesCheckErrorsSetup();
980 for (size_t i = 0; i < count; ++i) {
981 DownloadFilesCheckErrorsLoopBody(download_info[i], i);
985 void DownloadInsertFilesErrorCheckErrorsLoopBody(
986 scoped_refptr<content::TestFileErrorInjector> injector,
987 const FileErrorInjectInfo& info,
988 size_t i) {
989 std::stringstream s;
990 s << " " << __FUNCTION__ << "()"
991 << " index = " << i
992 << " url = " << info.error_info.url
993 << " operation code = "
994 << content::TestFileErrorInjector::DebugString(info.error_info.code)
995 << " instance = " << info.error_info.operation_instance
996 << " error = "
997 << content::DownloadInterruptReasonToString(info.error_info.error);
999 injector->ClearErrors();
1000 injector->AddError(info.error_info);
1002 injector->InjectErrors();
1004 DownloadFilesCheckErrorsLoopBody(info.download_info, i);
1006 size_t expected_successes = info.download_info.show_download_item ? 1u : 0u;
1007 EXPECT_EQ(expected_successes, injector->TotalFileCount()) << s.str();
1008 EXPECT_EQ(0u, injector->CurrentFileCount()) << s.str();
1010 if (info.download_info.show_download_item)
1011 EXPECT_TRUE(injector->HadFile(GURL(info.error_info.url))) << s.str();
1014 void DownloadInsertFilesErrorCheckErrors(size_t count,
1015 FileErrorInjectInfo* info) {
1016 DownloadFilesCheckErrorsSetup();
1018 // Set up file failures.
1019 scoped_refptr<content::TestFileErrorInjector> injector(
1020 content::TestFileErrorInjector::Create(
1021 DownloadManagerForBrowser(browser())));
1023 for (size_t i = 0; i < count; ++i) {
1024 // Set up the full URL, for download file tracking.
1025 std::string server_path = "/downloads/";
1026 server_path += info[i].download_info.url_name;
1027 GURL url = embedded_test_server()->GetURL(server_path);
1028 info[i].error_info.url = url.spec();
1030 DownloadInsertFilesErrorCheckErrorsLoopBody(injector, info[i], i);
1034 // Attempts to download a file to a read-only folder, based on information
1035 // in |download_info|.
1036 void DownloadFilesToReadonlyFolder(size_t count,
1037 DownloadInfo* download_info) {
1038 DownloadFilesCheckErrorsSetup();
1040 // Make the test folder unwritable.
1041 base::FilePath destination_folder = GetDownloadDirectory(browser());
1042 DVLOG(1) << " " << __FUNCTION__ << "()"
1043 << " folder = '" << destination_folder.value() << "'";
1044 base::FilePermissionRestorer permission_restorer(destination_folder);
1045 EXPECT_TRUE(base::MakeFileUnwritable(destination_folder));
1047 for (size_t i = 0; i < count; ++i) {
1048 DownloadFilesCheckErrorsLoopBody(download_info[i], i);
1052 // A mock install prompt that simulates the user allowing an install request.
1053 void SetAllowMockInstallPrompt() {
1054 download_crx_util::SetMockInstallPromptForTesting(
1055 scoped_ptr<ExtensionInstallPrompt>(
1056 new MockAutoConfirmExtensionInstallPrompt(
1057 browser()->tab_strip_model()->GetActiveWebContents())));
1060 // This method:
1061 // * Starts a mock download by navigating browser() to a URLRequestMockHTTPJob
1062 // mock URL.
1063 // * Injects |error| on the first write using |error_injector|.
1064 // * Waits for the download to be interrupted.
1065 // * Clears the errors on |error_injector|.
1066 // * Returns the resulting interrupted download.
1067 DownloadItem* StartMockDownloadAndInjectError(
1068 content::TestFileErrorInjector* error_injector,
1069 content::DownloadInterruptReason error) {
1070 base::FilePath file_path(FILE_PATH_LITERAL("download-test1.lib"));
1071 GURL url = URLRequestMockHTTPJob::GetMockUrl(file_path);
1073 content::TestFileErrorInjector::FileErrorInfo error_info;
1074 error_info.url = url.spec();
1075 error_info.code = content::TestFileErrorInjector::FILE_OPERATION_WRITE;
1076 error_info.operation_instance = 0;
1077 error_info.error = error;
1078 error_injector->ClearErrors();
1079 error_injector->AddError(error_info);
1080 error_injector->InjectErrors();
1082 scoped_ptr<content::DownloadTestObserver> observer(
1083 new DownloadTestObserverResumable(
1084 DownloadManagerForBrowser(browser()), 1));
1085 ui_test_utils::NavigateToURL(browser(), url);
1086 observer->WaitForFinished();
1088 content::DownloadManager::DownloadVector downloads;
1089 DownloadManagerForBrowser(browser())->GetAllDownloads(&downloads);
1090 EXPECT_EQ(1u, downloads.size());
1092 if (downloads.size() != 1)
1093 return NULL;
1095 error_injector->ClearErrors();
1096 error_injector->InjectErrors();
1097 DownloadItem* download = downloads[0];
1098 EXPECT_EQ(DownloadItem::INTERRUPTED, download->GetState());
1099 EXPECT_EQ(error, download->GetLastReason());
1100 return download;
1103 private:
1104 static void EnsureNoPendingDownloadJobsOnIO(bool* result) {
1105 if (net::URLRequestSlowDownloadJob::NumberOutstandingRequests())
1106 *result = false;
1107 BrowserThread::PostTask(
1108 BrowserThread::UI, FROM_HERE, base::MessageLoop::QuitClosure());
1111 // Location of the test data.
1112 base::FilePath test_dir_;
1114 // Location of the downloads directory for these tests
1115 base::ScopedTempDir downloads_directory_;
1117 scoped_ptr<DownloadTestFileActivityObserver> file_activity_observer_;
1120 // NOTES:
1122 // Files for these tests are found in DIR_TEST_DATA (currently
1123 // "chrome\test\data\", see chrome_paths.cc).
1124 // Mock responses have extension .mock-http-headers appended to the file name.
1126 // Download a file due to the associated MIME type.
1127 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadMimeType) {
1128 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
1129 GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
1131 // Download the file and wait. We do not expect the Select File dialog.
1132 DownloadAndWait(browser(), url);
1134 // Check state.
1135 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1136 CheckDownload(browser(), file, file);
1137 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
1140 #if defined(OS_WIN)
1141 // Download a file and confirm that the zone identifier (on windows)
1142 // is set to internet.
1143 IN_PROC_BROWSER_TEST_F(DownloadTest, CheckInternetZone) {
1144 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
1145 GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
1147 // Download the file and wait. We do not expect the Select File dialog.
1148 DownloadAndWait(browser(), url);
1150 // Check state. Special file state must be checked before CheckDownload,
1151 // as CheckDownload will delete the output file.
1152 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1153 base::FilePath downloaded_file(DestinationFile(browser(), file));
1154 if (base::VolumeSupportsADS(downloaded_file))
1155 EXPECT_TRUE(base::HasInternetZoneIdentifier(downloaded_file));
1156 CheckDownload(browser(), file, file);
1157 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
1159 #endif
1161 // Put up a Select File dialog when the file is downloaded, due to
1162 // downloads preferences settings.
1163 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadMimeTypeSelect) {
1164 // Re-enable prompting.
1165 browser()->profile()->GetPrefs()->SetBoolean(
1166 prefs::kPromptForDownload, true);
1167 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
1168 GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
1170 EnableFileChooser(true);
1172 // Download the file and wait. We expect the Select File dialog to appear
1173 // due to the MIME type, but we still wait until the download completes.
1174 scoped_ptr<content::DownloadTestObserver> observer(
1175 new content::DownloadTestObserverTerminal(
1176 DownloadManagerForBrowser(browser()),
1178 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL));
1179 ui_test_utils::NavigateToURL(browser(), url);
1180 observer->WaitForFinished();
1181 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::COMPLETE));
1182 CheckDownloadStates(1, DownloadItem::COMPLETE);
1183 EXPECT_TRUE(DidShowFileChooser());
1185 // Check state.
1186 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1187 CheckDownload(browser(), file, file);
1188 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
1191 // Access a file with a viewable mime-type, verify that a download
1192 // did not initiate.
1193 IN_PROC_BROWSER_TEST_F(DownloadTest, NoDownload) {
1194 base::FilePath file(FILE_PATH_LITERAL("download-test2.html"));
1195 GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
1196 base::FilePath file_path(DestinationFile(browser(), file));
1198 // Open a web page and wait.
1199 ui_test_utils::NavigateToURL(browser(), url);
1201 // Check that we did not download the web page.
1202 EXPECT_FALSE(base::PathExists(file_path));
1204 // Check state.
1205 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1206 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
1209 // EmbeddedTestServer::HandleRequestCallback function that returns the relative
1210 // URL as the MIME type.
1211 // E.g.:
1212 // C -> S: GET /foo/bar =>
1213 // S -> C: HTTP/1.1 200 OK
1214 // Content-Type: foo/bar
1215 // ...
1216 static scoped_ptr<net::test_server::HttpResponse> RespondWithContentTypeHandler(
1217 const net::test_server::HttpRequest& request) {
1218 scoped_ptr<net::test_server::BasicHttpResponse> response(
1219 new net::test_server::BasicHttpResponse());
1220 response->set_content_type(request.relative_url.substr(1));
1221 response->set_code(net::HTTP_OK);
1222 response->set_content("ooogaboogaboogabooga");
1223 return response.Pass();
1226 IN_PROC_BROWSER_TEST_F(DownloadTest, MimeTypesToShowNotDownload) {
1227 embedded_test_server()->RegisterRequestHandler(
1228 base::Bind(&RespondWithContentTypeHandler));
1229 ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
1231 // These files should all be displayed in the browser.
1232 const char* mime_types[] = {
1233 // It is unclear whether to display text/css or download it.
1234 // Firefox 3: Display
1235 // Internet Explorer 7: Download
1236 // Safari 3.2: Download
1237 // We choose to match Firefox due to the lot of complains
1238 // from the users if css files are downloaded:
1239 // http://code.google.com/p/chromium/issues/detail?id=7192
1240 "text/css",
1241 "text/javascript",
1242 "text/plain",
1243 "application/x-javascript",
1244 "text/html",
1245 "text/xml",
1246 "text/xsl",
1247 "application/xhtml+xml",
1248 "image/png",
1249 "image/gif",
1250 "image/jpeg",
1251 "image/bmp",
1253 for (size_t i = 0; i < arraysize(mime_types); ++i) {
1254 const char* mime_type = mime_types[i];
1255 GURL url(
1256 embedded_test_server()->GetURL(std::string("/").append(mime_type)));
1257 ui_test_utils::NavigateToURL(browser(), url);
1259 // Check state.
1260 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1261 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
1265 // Verify that when the DownloadResourceThrottle cancels a download, the
1266 // download never makes it to the downloads system.
1267 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadResourceThrottleCancels) {
1268 // Navigate to a page with the same domain as the file to download. We can't
1269 // navigate directly to the file we don't want to download because cross-site
1270 // navigations reset the TabDownloadState.
1271 base::FilePath same_site_path(FILE_PATH_LITERAL("download_script.html"));
1272 GURL same_site_url(URLRequestMockHTTPJob::GetMockUrl(same_site_path));
1273 ui_test_utils::NavigateToURL(browser(), same_site_url);
1275 // Make sure the initial navigation didn't trigger a download.
1276 std::vector<content::DownloadItem*> items;
1277 DownloadManagerForBrowser(browser())->GetAllDownloads(&items);
1278 EXPECT_EQ(0u, items.size());
1280 // Disable downloads for the tab.
1281 WebContents* web_contents =
1282 browser()->tab_strip_model()->GetActiveWebContents();
1283 DownloadRequestLimiter::TabDownloadState* tab_download_state =
1284 g_browser_process->download_request_limiter()->GetDownloadState(
1285 web_contents, web_contents, true);
1286 ASSERT_TRUE(tab_download_state);
1287 tab_download_state->set_download_status(
1288 DownloadRequestLimiter::DOWNLOADS_NOT_ALLOWED);
1290 // Try to start the download via Javascript and wait for the corresponding
1291 // load stop event.
1292 content::TestNavigationObserver observer(web_contents);
1293 bool download_assempted;
1294 ASSERT_TRUE(content::ExecuteScriptAndExtractBool(
1295 browser()->tab_strip_model()->GetActiveWebContents(),
1296 "window.domAutomationController.send(startDownload());",
1297 &download_assempted));
1298 ASSERT_TRUE(download_assempted);
1299 observer.Wait();
1301 // Check that we did not download the file.
1302 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
1303 base::FilePath file_path(DestinationFile(browser(), file));
1304 EXPECT_FALSE(base::PathExists(file_path));
1306 // Check state.
1307 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1308 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
1310 // Verify that there's no pending download. The resource throttle
1311 // should have deleted it before it created a download item, so it
1312 // shouldn't be available as a cancelled download either.
1313 DownloadManagerForBrowser(browser())->GetAllDownloads(&items);
1314 EXPECT_EQ(0u, items.size());
1317 // Download a 0-size file with a content-disposition header, verify that the
1318 // download tab opened and the file exists as the filename specified in the
1319 // header. This also ensures we properly handle empty file downloads.
1320 // The download shelf should be visible in the current tab.
1321 IN_PROC_BROWSER_TEST_F(DownloadTest, ContentDisposition) {
1322 base::FilePath file(FILE_PATH_LITERAL("download-test3.gif"));
1323 GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
1324 base::FilePath download_file(
1325 FILE_PATH_LITERAL("download-test3-attachment.gif"));
1327 // Download a file and wait.
1328 DownloadAndWait(browser(), url);
1330 CheckDownload(browser(), download_file, file);
1332 // Check state.
1333 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1334 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
1337 // Test that the download shelf is per-window by starting a download in one
1338 // tab, opening a second tab, closing the shelf, going back to the first tab,
1339 // and checking that the shelf is closed.
1340 IN_PROC_BROWSER_TEST_F(DownloadTest, PerWindowShelf) {
1341 base::FilePath file(FILE_PATH_LITERAL("download-test3.gif"));
1342 GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
1343 base::FilePath download_file(
1344 FILE_PATH_LITERAL("download-test3-attachment.gif"));
1346 // Download a file and wait.
1347 DownloadAndWait(browser(), url);
1349 CheckDownload(browser(), download_file, file);
1351 // Check state.
1352 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1353 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
1355 // Open a second tab and wait.
1356 EXPECT_NE(static_cast<WebContents*>(NULL),
1357 chrome::AddSelectedTabWithURL(browser(),
1358 GURL(url::kAboutBlankURL),
1359 ui::PAGE_TRANSITION_TYPED));
1360 EXPECT_EQ(2, browser()->tab_strip_model()->count());
1361 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
1363 // Hide the download shelf.
1364 browser()->window()->GetDownloadShelf()->Close(DownloadShelf::AUTOMATIC);
1365 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
1367 // Go to the first tab.
1368 browser()->tab_strip_model()->ActivateTabAt(0, true);
1369 EXPECT_EQ(2, browser()->tab_strip_model()->count());
1371 // The download shelf should not be visible.
1372 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
1375 // Check whether the downloads shelf is closed when the downloads tab is
1376 // invoked.
1377 IN_PROC_BROWSER_TEST_F(DownloadTest, CloseShelfOnDownloadsTab) {
1378 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
1379 GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
1381 // Download the file and wait. We do not expect the Select File dialog.
1382 DownloadAndWait(browser(), url);
1384 // Check state.
1385 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1386 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
1388 // Open the downloads tab.
1389 chrome::ShowDownloads(browser());
1390 // The shelf should now be closed.
1391 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
1394 // UnknownSize and KnownSize are tests which depend on
1395 // URLRequestSlowDownloadJob to serve content in a certain way. Data will be
1396 // sent in two chunks where the first chunk is 35K and the second chunk is 10K.
1397 // The test will first attempt to download a file; but the server will "pause"
1398 // in the middle until the server receives a second request for
1399 // "download-finish". At that time, the download will finish.
1400 // These tests don't currently test much due to holes in |RunSizeTest()|. See
1401 // comments in that routine for details.
1402 IN_PROC_BROWSER_TEST_F(DownloadTest, UnknownSize) {
1403 ASSERT_TRUE(RunSizeTest(browser(), SIZE_TEST_TYPE_UNKNOWN,
1404 "32.0 KB - ", "100% - "));
1407 IN_PROC_BROWSER_TEST_F(DownloadTest, KnownSize) {
1408 ASSERT_TRUE(RunSizeTest(browser(), SIZE_TEST_TYPE_KNOWN,
1409 "71% - ", "100% - "));
1412 // Test that when downloading an item in Incognito mode, we don't crash when
1413 // closing the last Incognito window (http://crbug.com/13983).
1414 // Also check that the download shelf is not visible after closing the
1415 // Incognito window.
1416 IN_PROC_BROWSER_TEST_F(DownloadTest, IncognitoDownload) {
1417 Browser* incognito = CreateIncognitoBrowser();
1418 ASSERT_TRUE(incognito);
1419 int window_count = chrome::GetTotalBrowserCount();
1420 EXPECT_EQ(2, window_count);
1422 // Download a file in the Incognito window and wait.
1423 CreateAndSetDownloadsDirectory(incognito);
1424 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
1425 GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
1426 // Since |incognito| is a separate browser, we have to set it up explicitly.
1427 incognito->profile()->GetPrefs()->SetBoolean(prefs::kPromptForDownload,
1428 false);
1429 DownloadAndWait(incognito, url);
1431 // We should still have 2 windows.
1432 ExpectWindowCountAfterDownload(2);
1434 // Verify that the download shelf is showing for the Incognito window.
1435 EXPECT_TRUE(incognito->window()->IsDownloadShelfVisible());
1437 #if !defined(OS_MACOSX)
1438 // On Mac OS X, the UI window close is delayed until the outermost
1439 // message loop runs. So it isn't possible to get a BROWSER_CLOSED
1440 // notification inside of a test.
1441 content::WindowedNotificationObserver signal(
1442 chrome::NOTIFICATION_BROWSER_CLOSED,
1443 content::Source<Browser>(incognito));
1444 #endif
1446 // Close the Incognito window and don't crash.
1447 chrome::CloseWindow(incognito);
1449 #if !defined(OS_MACOSX)
1450 signal.Wait();
1451 ExpectWindowCountAfterDownload(1);
1452 #endif
1454 // Verify that the regular window does not have a download shelf.
1455 // On ChromeOS, the download panel is common to both profiles, so
1456 // it is still visible.
1457 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
1459 CheckDownload(browser(), file, file);
1462 // Download one file on-record, then download the same file off-record, and test
1463 // that the filename is deduplicated. The previous test tests for a specific
1464 // bug; this next test tests that filename deduplication happens independently
1465 // of DownloadManager/CDMD.
1466 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadTest_IncognitoRegular) {
1467 GURL url = net::URLRequestMockHTTPJob::GetMockUrl("downloads/a_zip_file.zip");
1469 // Read the origin file now so that we can compare the downloaded files to it
1470 // later.
1471 base::FilePath origin(OriginFile(base::FilePath(FILE_PATH_LITERAL(
1472 "downloads/a_zip_file.zip"))));
1473 ASSERT_TRUE(base::PathExists(origin));
1474 int64 origin_file_size = 0;
1475 EXPECT_TRUE(base::GetFileSize(origin, &origin_file_size));
1476 std::string original_contents;
1477 EXPECT_TRUE(base::ReadFileToString(origin, &original_contents));
1479 std::vector<DownloadItem*> download_items;
1480 GetDownloads(browser(), &download_items);
1481 ASSERT_TRUE(download_items.empty());
1483 // Download a file in the on-record browser and check that it was downloaded
1484 // correctly.
1485 DownloadAndWaitWithDisposition(browser(),
1486 url,
1487 CURRENT_TAB,
1488 ui_test_utils::BROWSER_TEST_NONE);
1489 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
1490 GetDownloads(browser(), &download_items);
1491 ASSERT_EQ(1UL, download_items.size());
1492 ASSERT_EQ(base::FilePath(FILE_PATH_LITERAL("a_zip_file.zip")),
1493 download_items[0]->GetTargetFilePath().BaseName());
1494 ASSERT_TRUE(base::PathExists(download_items[0]->GetTargetFilePath()));
1495 EXPECT_TRUE(VerifyFile(download_items[0]->GetTargetFilePath(),
1496 original_contents, origin_file_size));
1498 // Setup an incognito window.
1499 Browser* incognito = CreateIncognitoBrowser();
1500 ASSERT_TRUE(incognito);
1501 int window_count = BrowserList::GetInstance(
1502 browser()->host_desktop_type())->size();
1503 EXPECT_EQ(2, window_count);
1504 incognito->profile()->GetPrefs()->SetFilePath(
1505 prefs::kDownloadDefaultDirectory,
1506 GetDownloadsDirectory());
1507 incognito->profile()->GetPrefs()->SetFilePath(
1508 prefs::kSaveFileDefaultDirectory,
1509 GetDownloadsDirectory());
1511 download_items.clear();
1512 GetDownloads(incognito, &download_items);
1513 ASSERT_TRUE(download_items.empty());
1515 // Download a file in the incognito browser and check that it was downloaded
1516 // correctly.
1517 DownloadAndWaitWithDisposition(incognito,
1518 url,
1519 CURRENT_TAB,
1520 ui_test_utils::BROWSER_TEST_NONE);
1521 EXPECT_TRUE(incognito->window()->IsDownloadShelfVisible());
1522 GetDownloads(incognito, &download_items);
1523 ASSERT_EQ(1UL, download_items.size());
1524 ASSERT_EQ(base::FilePath(FILE_PATH_LITERAL("a_zip_file (1).zip")),
1525 download_items[0]->GetTargetFilePath().BaseName());
1526 ASSERT_TRUE(base::PathExists(download_items[0]->GetTargetFilePath()));
1527 EXPECT_TRUE(VerifyFile(download_items[0]->GetTargetFilePath(),
1528 original_contents, origin_file_size));
1531 // Navigate to a new background page, but don't download. Confirm that the
1532 // download shelf is not visible and that we have two tabs.
1533 IN_PROC_BROWSER_TEST_F(DownloadTest, DontCloseNewTab1) {
1534 // Because it's an HTML link, it should open a web page rather than
1535 // downloading.
1536 base::FilePath file1(FILE_PATH_LITERAL("download-test2.html"));
1537 GURL url(URLRequestMockHTTPJob::GetMockUrl(file1));
1539 // Open a web page and wait.
1540 ui_test_utils::NavigateToURLWithDisposition(
1541 browser(),
1542 url,
1543 NEW_BACKGROUND_TAB,
1544 ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
1546 // We should have two tabs now.
1547 EXPECT_EQ(2, browser()->tab_strip_model()->count());
1548 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
1551 // Download a file in a background tab. Verify that the tab is closed
1552 // automatically, and that the download shelf is visible in the current tab.
1553 IN_PROC_BROWSER_TEST_F(DownloadTest, CloseNewTab1) {
1554 // Download a file in a new background tab and wait. The tab is automatically
1555 // closed when the download begins.
1556 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
1557 GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
1558 DownloadAndWaitWithDisposition(
1559 browser(),
1560 url,
1561 NEW_BACKGROUND_TAB,
1564 // When the download finishes, we should still have one tab.
1565 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
1566 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1568 CheckDownload(browser(), file, file);
1571 // Open a web page in the current tab, then download a file in another tab via
1572 // a Javascript call.
1573 // Verify that we have 2 tabs, and the download shelf is visible in the current
1574 // tab.
1576 // The download_page1.html page contains an openNew() function that opens a
1577 // tab and then downloads download-test1.lib.
1578 IN_PROC_BROWSER_TEST_F(DownloadTest, DontCloseNewTab2) {
1579 // Because it's an HTML link, it should open a web page rather than
1580 // downloading.
1581 base::FilePath file1(FILE_PATH_LITERAL("download_page1.html"));
1582 GURL url(URLRequestMockHTTPJob::GetMockUrl(file1));
1584 // Open a web page and wait.
1585 ui_test_utils::NavigateToURL(browser(), url);
1587 // Download a file in a new tab and wait (via Javascript).
1588 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
1589 DownloadAndWaitWithDisposition(browser(),
1590 GURL("javascript:openNew()"),
1591 CURRENT_TAB,
1592 ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
1594 // When the download finishes, we should have two tabs.
1595 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
1596 EXPECT_EQ(2, browser()->tab_strip_model()->count());
1598 CheckDownload(browser(), file, file);
1601 // Open a web page in the current tab, open another tab via a Javascript call,
1602 // then download a file in the new tab.
1603 // Verify that we have 2 tabs, and the download shelf is visible in the current
1604 // tab.
1606 // The download_page2.html page contains an openNew() function that opens a
1607 // tab.
1608 IN_PROC_BROWSER_TEST_F(DownloadTest, DontCloseNewTab3) {
1609 // Because it's an HTML link, it should open a web page rather than
1610 // downloading.
1611 base::FilePath file1(FILE_PATH_LITERAL("download_page2.html"));
1612 GURL url1(URLRequestMockHTTPJob::GetMockUrl(file1));
1614 // Open a web page and wait.
1615 ui_test_utils::NavigateToURL(browser(), url1);
1617 // Open a new tab and wait.
1618 ui_test_utils::NavigateToURLWithDisposition(
1619 browser(),
1620 GURL("javascript:openNew()"),
1621 CURRENT_TAB,
1622 ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
1624 EXPECT_EQ(2, browser()->tab_strip_model()->count());
1626 // Download a file and wait.
1627 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
1628 GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
1629 DownloadAndWaitWithDisposition(browser(),
1630 url,
1631 CURRENT_TAB,
1632 ui_test_utils::BROWSER_TEST_NONE);
1634 // When the download finishes, we should have two tabs.
1635 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
1636 EXPECT_EQ(2, browser()->tab_strip_model()->count());
1638 CheckDownload(browser(), file, file);
1641 // Open a web page in the current tab, then download a file via Javascript,
1642 // which will do so in a temporary tab.
1643 // Verify that we have 1 tab, and the download shelf is visible.
1645 // The download_page3.html page contains an openNew() function that opens a
1646 // tab with download-test1.lib in the URL. When the URL is determined to be
1647 // a download, the tab is closed automatically.
1648 IN_PROC_BROWSER_TEST_F(DownloadTest, CloseNewTab2) {
1649 // Because it's an HTML link, it should open a web page rather than
1650 // downloading.
1651 base::FilePath file1(FILE_PATH_LITERAL("download_page3.html"));
1652 GURL url(URLRequestMockHTTPJob::GetMockUrl(file1));
1654 // Open a web page and wait.
1655 ui_test_utils::NavigateToURL(browser(), url);
1657 // Download a file and wait.
1658 // The file to download is "download-test1.lib".
1659 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
1660 DownloadAndWaitWithDisposition(browser(),
1661 GURL("javascript:openNew()"),
1662 CURRENT_TAB,
1663 ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
1665 // When the download finishes, we should still have one tab.
1666 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
1667 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1669 CheckDownload(browser(), file, file);
1672 // Open a web page in the current tab, then call Javascript via a button to
1673 // download a file in a new tab, which is closed automatically when the
1674 // download begins.
1675 // Verify that we have 1 tab, and the download shelf is visible.
1677 // The download_page4.html page contains a form with download-test1.lib as the
1678 // action.
1679 IN_PROC_BROWSER_TEST_F(DownloadTest, CloseNewTab3) {
1680 // Because it's an HTML link, it should open a web page rather than
1681 // downloading.
1682 base::FilePath file1(FILE_PATH_LITERAL("download_page4.html"));
1683 GURL url(URLRequestMockHTTPJob::GetMockUrl(file1));
1685 // Open a web page and wait.
1686 ui_test_utils::NavigateToURL(browser(), url);
1688 // Download a file in a new tab and wait. The tab will automatically close
1689 // when the download begins.
1690 // The file to download is "download-test1.lib".
1691 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
1692 DownloadAndWaitWithDisposition(
1693 browser(),
1694 GURL("javascript:document.getElementById('form').submit()"),
1695 CURRENT_TAB,
1696 ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
1698 // When the download finishes, we should still have one tab.
1699 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
1700 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1702 CheckDownload(browser(), file, file);
1705 // Download a file in a new window.
1706 // Verify that we have 2 windows, and the download shelf is not visible in the
1707 // first window, but is visible in the second window.
1708 // Close the new window.
1709 // Verify that we have 1 window, and the download shelf is not visible.
1711 // Regression test for http://crbug.com/44454
1712 IN_PROC_BROWSER_TEST_F(DownloadTest, NewWindow) {
1713 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
1714 GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
1715 #if !defined(OS_MACOSX)
1716 // See below.
1717 Browser* first_browser = browser();
1718 #endif
1720 // Download a file in a new window and wait.
1721 DownloadAndWaitWithDisposition(browser(),
1722 url,
1723 NEW_WINDOW,
1724 ui_test_utils::BROWSER_TEST_NONE);
1726 // When the download finishes, the download shelf SHOULD NOT be visible in
1727 // the first window.
1728 ExpectWindowCountAfterDownload(2);
1729 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1730 // Download shelf should close. Download panel stays open on ChromeOS.
1731 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
1733 // The download shelf SHOULD be visible in the second window.
1734 std::set<Browser*> original_browsers;
1735 original_browsers.insert(browser());
1736 Browser* download_browser =
1737 ui_test_utils::GetBrowserNotInSet(original_browsers);
1738 ASSERT_TRUE(download_browser != NULL);
1739 EXPECT_NE(download_browser, browser());
1740 EXPECT_EQ(1, download_browser->tab_strip_model()->count());
1741 EXPECT_TRUE(download_browser->window()->IsDownloadShelfVisible());
1743 #if !defined(OS_MACOSX)
1744 // On Mac OS X, the UI window close is delayed until the outermost
1745 // message loop runs. So it isn't possible to get a BROWSER_CLOSED
1746 // notification inside of a test.
1747 content::WindowedNotificationObserver signal(
1748 chrome::NOTIFICATION_BROWSER_CLOSED,
1749 content::Source<Browser>(download_browser));
1750 #endif
1752 // Close the new window.
1753 chrome::CloseWindow(download_browser);
1755 #if !defined(OS_MACOSX)
1756 signal.Wait();
1757 EXPECT_EQ(first_browser, browser());
1758 ExpectWindowCountAfterDownload(1);
1759 #endif
1761 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1762 // Download shelf should close. Download panel stays open on ChromeOS.
1763 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
1765 CheckDownload(browser(), file, file);
1768 // EmbeddedTestServer::HandleRequestCallback function that responds with a
1769 // redirect to the URL specified via a query string.
1770 // E.g.:
1771 // C -> S: GET /dummy?http://example.com
1772 // S -> C: HTTP/1.1 301 Moved Permanently
1773 // Location: http://example.com
1774 // ...
1775 static scoped_ptr<net::test_server::HttpResponse> ServerRedirectRequestHandler(
1776 const net::test_server::HttpRequest& request) {
1777 scoped_ptr<net::test_server::BasicHttpResponse> response(
1778 new net::test_server::BasicHttpResponse());
1779 size_t query_position = request.relative_url.find('?');
1781 if (query_position == std::string::npos) {
1782 response->set_code(net::HTTP_PERMANENT_REDIRECT);
1783 response->AddCustomHeader("Location",
1784 "https://request-had-no-query-string");
1785 response->set_content_type("text/plain");
1786 response->set_content("Error");
1787 return response.Pass();
1790 response->set_code(net::HTTP_PERMANENT_REDIRECT);
1791 response->AddCustomHeader("Location",
1792 request.relative_url.substr(query_position + 1));
1793 response->set_content_type("text/plain");
1794 response->set_content("It's gone!");
1795 return response.Pass();
1798 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadHistoryCheck) {
1799 GURL download_url(net::URLRequestSlowDownloadJob::kKnownSizeUrl);
1800 base::FilePath file(net::GenerateFileName(download_url,
1801 std::string(),
1802 std::string(),
1803 std::string(),
1804 std::string(),
1805 std::string()));
1807 // We use the server so that we can get a redirect and test url_chain
1808 // persistence.
1809 embedded_test_server()->RegisterRequestHandler(
1810 base::Bind(&ServerRedirectRequestHandler));
1811 ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
1812 GURL redirect_url =
1813 embedded_test_server()->GetURL("/a?" + download_url.spec());
1815 // Download the url and wait until the object has been stored.
1816 base::Time start(base::Time::Now());
1817 HistoryObserver observer(browser()->profile());
1818 observer.SetFilterCallback(base::Bind(&HasDataAndName));
1819 ui_test_utils::NavigateToURL(browser(), redirect_url);
1820 observer.WaitForStored();
1822 // Get the details on what was stored into the history.
1823 scoped_ptr<std::vector<history::DownloadRow> > downloads_in_database;
1824 ASSERT_TRUE(DownloadsHistoryDataCollector(
1825 browser()->profile()).WaitForDownloadInfo(&downloads_in_database));
1826 ASSERT_EQ(1u, downloads_in_database->size());
1828 // Confirm history storage is what you expect for a partially completed
1829 // slow download job.
1830 history::DownloadRow& row(downloads_in_database->at(0));
1831 EXPECT_EQ(DestinationFile(browser(), file), row.target_path);
1832 EXPECT_EQ(DownloadTargetDeterminer::GetCrDownloadPath(
1833 DestinationFile(browser(), file)),
1834 row.current_path);
1835 ASSERT_EQ(2u, row.url_chain.size());
1836 EXPECT_EQ(redirect_url.spec(), row.url_chain[0].spec());
1837 EXPECT_EQ(download_url.spec(), row.url_chain[1].spec());
1838 EXPECT_EQ(history::DownloadDangerType::NOT_DANGEROUS, row.danger_type);
1839 EXPECT_LE(start, row.start_time);
1840 EXPECT_EQ(net::URLRequestSlowDownloadJob::kFirstDownloadSize,
1841 row.received_bytes);
1842 EXPECT_EQ(net::URLRequestSlowDownloadJob::kFirstDownloadSize
1843 + net::URLRequestSlowDownloadJob::kSecondDownloadSize,
1844 row.total_bytes);
1845 EXPECT_EQ(history::DownloadState::IN_PROGRESS, row.state);
1846 EXPECT_FALSE(row.opened);
1848 // Finish the download. We're ok relying on the history to be flushed
1849 // at this point as our queries will be behind the history updates
1850 // invoked by completion.
1851 scoped_ptr<content::DownloadTestObserver> download_observer(
1852 CreateWaiter(browser(), 1));
1853 ui_test_utils::NavigateToURL(browser(),
1854 GURL(net::URLRequestSlowDownloadJob::kErrorDownloadUrl));
1855 download_observer->WaitForFinished();
1856 EXPECT_EQ(1u, download_observer->NumDownloadsSeenInState(
1857 DownloadItem::INTERRUPTED));
1858 base::Time end(base::Time::Now());
1860 // Get what was stored in the history.
1861 ASSERT_TRUE(DownloadsHistoryDataCollector(
1862 browser()->profile()).WaitForDownloadInfo(&downloads_in_database));
1863 ASSERT_EQ(1u, downloads_in_database->size());
1865 // Confirm history storage is what you expect for an interrupted slow download
1866 // job. The download isn't continuable, so there's no intermediate file.
1867 history::DownloadRow& row1(downloads_in_database->at(0));
1868 EXPECT_EQ(DestinationFile(browser(), file), row1.target_path);
1869 EXPECT_TRUE(row1.current_path.empty());
1870 ASSERT_EQ(2u, row1.url_chain.size());
1871 EXPECT_EQ(redirect_url.spec(), row1.url_chain[0].spec());
1872 EXPECT_EQ(download_url.spec(), row1.url_chain[1].spec());
1873 EXPECT_EQ(history::DownloadDangerType::NOT_DANGEROUS, row1.danger_type);
1874 EXPECT_LE(start, row1.start_time);
1875 EXPECT_GE(end, row1.end_time);
1876 EXPECT_EQ(net::URLRequestSlowDownloadJob::kFirstDownloadSize,
1877 row1.received_bytes);
1878 EXPECT_EQ(net::URLRequestSlowDownloadJob::kFirstDownloadSize
1879 + net::URLRequestSlowDownloadJob::kSecondDownloadSize,
1880 row1.total_bytes);
1881 EXPECT_EQ(history::DownloadState::INTERRUPTED, row1.state);
1882 EXPECT_EQ(history::ToHistoryDownloadInterruptReason(
1883 content::DOWNLOAD_INTERRUPT_REASON_NETWORK_FAILED),
1884 row1.interrupt_reason);
1885 EXPECT_FALSE(row1.opened);
1888 // Make sure a dangerous file shows up properly in the history.
1889 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadHistoryDangerCheck) {
1890 #if defined(OS_WIN) && defined(USE_ASH)
1891 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
1892 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1893 switches::kAshBrowserTests))
1894 return;
1895 #endif
1897 // .swf file so that it's dangerous on all platforms (including CrOS).
1898 base::FilePath file(FILE_PATH_LITERAL("downloads/dangerous/dangerous.swf"));
1899 GURL download_url(URLRequestMockHTTPJob::GetMockUrl(file));
1901 // Download the url and wait until the object has been stored.
1902 scoped_ptr<content::DownloadTestObserver> download_observer(
1903 new content::DownloadTestObserverTerminal(
1904 DownloadManagerForBrowser(browser()), 1,
1905 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_IGNORE));
1906 base::Time start(base::Time::Now());
1907 HistoryObserver observer(browser()->profile());
1908 observer.SetFilterCallback(base::Bind(&HasDataAndName));
1909 ui_test_utils::NavigateToURL(browser(), download_url);
1910 observer.WaitForStored();
1912 // Get the details on what was stored into the history.
1913 scoped_ptr<std::vector<history::DownloadRow> > downloads_in_database;
1914 ASSERT_TRUE(DownloadsHistoryDataCollector(
1915 browser()->profile()).WaitForDownloadInfo(&downloads_in_database));
1916 ASSERT_EQ(1u, downloads_in_database->size());
1918 // Confirm history storage is what you expect for an unvalidated
1919 // dangerous file.
1920 history::DownloadRow& row(downloads_in_database->at(0));
1921 EXPECT_EQ(DestinationFile(browser(), file), row.target_path);
1922 EXPECT_NE(DownloadTargetDeterminer::GetCrDownloadPath(
1923 DestinationFile(browser(), file)),
1924 row.current_path);
1925 EXPECT_EQ(history::DownloadDangerType::DANGEROUS_FILE, row.danger_type);
1926 EXPECT_LE(start, row.start_time);
1927 EXPECT_EQ(history::DownloadState::IN_PROGRESS, row.state);
1928 EXPECT_FALSE(row.opened);
1930 // Validate the download and wait for it to finish.
1931 std::vector<DownloadItem*> downloads;
1932 DownloadManagerForBrowser(browser())->GetAllDownloads(&downloads);
1933 ASSERT_EQ(1u, downloads.size());
1934 downloads[0]->ValidateDangerousDownload();
1935 download_observer->WaitForFinished();
1937 // Get history details and confirm it's what you expect.
1938 downloads_in_database->clear();
1939 ASSERT_TRUE(DownloadsHistoryDataCollector(
1940 browser()->profile()).WaitForDownloadInfo(&downloads_in_database));
1941 ASSERT_EQ(1u, downloads_in_database->size());
1942 history::DownloadRow& row1(downloads_in_database->at(0));
1943 EXPECT_EQ(DestinationFile(browser(), file), row1.target_path);
1944 EXPECT_EQ(DestinationFile(browser(), file), row1.current_path);
1945 EXPECT_EQ(history::DownloadDangerType::USER_VALIDATED, row1.danger_type);
1946 EXPECT_LE(start, row1.start_time);
1947 EXPECT_EQ(history::DownloadState::COMPLETE, row1.state);
1948 EXPECT_FALSE(row1.opened);
1949 // Not checking file size--not relevant to the point of the test, and
1950 // the file size is actually different on Windows and other platforms,
1951 // because for source control simplicity it's actually a text file, and
1952 // there are CRLF transformations for those files.
1955 IN_PROC_BROWSER_TEST_F(DownloadTest, PRE_DownloadTest_History) {
1956 // Download a file and wait for it to be stored.
1957 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
1958 GURL download_url(URLRequestMockHTTPJob::GetMockUrl(file));
1959 HistoryObserver observer(browser()->profile());
1960 DownloadAndWait(browser(), download_url);
1961 observer.WaitForStored();
1962 HistoryServiceFactory::GetForProfile(browser()->profile(),
1963 ServiceAccessType::IMPLICIT_ACCESS)
1964 ->FlushForTest(base::Bind(
1965 &base::MessageLoop::Quit,
1966 base::Unretained(base::MessageLoop::current()->current())));
1967 content::RunMessageLoop();
1970 #if defined(OS_CHROMEOS)
1971 // Times out on ChromeOS: http://crbug.com/217810
1972 #define MAYBE_DownloadTest_History DISABLED_DownloadTest_History
1973 #else
1974 #define MAYBE_DownloadTest_History DownloadTest_History
1975 #endif
1976 IN_PROC_BROWSER_TEST_F(DownloadTest, MAYBE_DownloadTest_History) {
1977 // This starts up right after PRE_DownloadTest_History and shares the same
1978 // profile directory.
1979 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
1980 GURL download_url(URLRequestMockHTTPJob::GetMockUrl(file));
1981 std::vector<DownloadItem*> downloads;
1982 content::DownloadManager* manager = DownloadManagerForBrowser(browser());
1984 // Wait for the history to be loaded with a single DownloadItem. Check that
1985 // it's the file that was downloaded in PRE_DownloadTest_History.
1986 CreatedObserver created_observer(manager);
1987 created_observer.Wait();
1988 manager->GetAllDownloads(&downloads);
1989 ASSERT_EQ(1UL, downloads.size());
1990 DownloadItem* item = downloads[0];
1991 EXPECT_EQ(file.value(), item->GetFullPath().BaseName().value());
1992 EXPECT_EQ(file.value(), item->GetTargetFilePath().BaseName().value());
1993 EXPECT_EQ(download_url, item->GetURL());
1994 // The following are set by download-test1.lib.mock-http-headers.
1995 std::string etag = item->GetETag();
1996 base::TrimWhitespaceASCII(etag, base::TRIM_ALL, &etag);
1997 EXPECT_EQ("abracadabra", etag);
1999 std::string last_modified = item->GetLastModifiedTime();
2000 base::TrimWhitespaceASCII(last_modified, base::TRIM_ALL, &last_modified);
2001 EXPECT_EQ("Mon, 13 Nov 2006 20:31:09 GMT", last_modified);
2003 // Downloads that were restored from history shouldn't cause the download
2004 // shelf to be displayed.
2005 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
2008 // Test for crbug.com/14505. This tests that chrome:// urls are still functional
2009 // after download of a file while viewing another chrome://.
2010 IN_PROC_BROWSER_TEST_F(DownloadTest, ChromeURLAfterDownload) {
2011 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
2012 GURL download_url(URLRequestMockHTTPJob::GetMockUrl(file));
2013 GURL flags_url(chrome::kChromeUIFlagsURL);
2014 GURL extensions_url(chrome::kChromeUIExtensionsFrameURL);
2016 ui_test_utils::NavigateToURL(browser(), flags_url);
2017 DownloadAndWait(browser(), download_url);
2018 ui_test_utils::NavigateToURL(browser(), extensions_url);
2019 WebContents* contents =
2020 browser()->tab_strip_model()->GetActiveWebContents();
2021 ASSERT_TRUE(contents);
2022 bool webui_responded = false;
2023 EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
2024 contents,
2025 "window.domAutomationController.send(window.webuiResponded);",
2026 &webui_responded));
2027 EXPECT_TRUE(webui_responded);
2030 // Test for crbug.com/12745. This tests that if a download is initiated from
2031 // a chrome:// page that has registered and onunload handler, the browser
2032 // will be able to close.
2033 IN_PROC_BROWSER_TEST_F(DownloadTest, BrowserCloseAfterDownload) {
2034 GURL downloads_url(chrome::kChromeUIFlagsURL);
2035 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
2036 GURL download_url(URLRequestMockHTTPJob::GetMockUrl(file));
2038 ui_test_utils::NavigateToURL(browser(), downloads_url);
2039 WebContents* contents = browser()->tab_strip_model()->GetActiveWebContents();
2040 ASSERT_TRUE(contents);
2041 bool result = false;
2042 EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
2043 contents,
2044 "window.onunload = function() { var do_nothing = 0; }; "
2045 "window.domAutomationController.send(true);",
2046 &result));
2047 EXPECT_TRUE(result);
2049 DownloadAndWait(browser(), download_url);
2051 content::WindowedNotificationObserver signal(
2052 chrome::NOTIFICATION_BROWSER_CLOSED,
2053 content::Source<Browser>(browser()));
2054 chrome::CloseWindow(browser());
2055 signal.Wait();
2058 // Test to make sure the 'download' attribute in anchor tag is respected.
2059 IN_PROC_BROWSER_TEST_F(DownloadTest, AnchorDownloadTag) {
2060 base::FilePath file(FILE_PATH_LITERAL("download-anchor-attrib.html"));
2061 GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
2063 // Create a download, wait until it's complete, and confirm
2064 // we're in the expected state.
2065 scoped_ptr<content::DownloadTestObserver> observer(
2066 CreateWaiter(browser(), 1));
2067 ui_test_utils::NavigateToURL(browser(), url);
2068 observer->WaitForFinished();
2069 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::COMPLETE));
2070 CheckDownloadStates(1, DownloadItem::COMPLETE);
2072 // Confirm the downloaded data exists.
2073 base::FilePath downloaded_file = GetDownloadDirectory(browser());
2074 downloaded_file = downloaded_file.Append(FILE_PATH_LITERAL("a_red_dot.png"));
2075 EXPECT_TRUE(base::PathExists(downloaded_file));
2078 // Test to make sure auto-open works.
2079 IN_PROC_BROWSER_TEST_F(DownloadTest, AutoOpen) {
2080 base::FilePath file(FILE_PATH_LITERAL("download-autoopen.txt"));
2081 GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
2083 ASSERT_TRUE(
2084 GetDownloadPrefs(browser())->EnableAutoOpenBasedOnExtension(file));
2086 DownloadAndWait(browser(), url);
2088 // Find the download and confirm it was opened.
2089 std::vector<DownloadItem*> downloads;
2090 DownloadManagerForBrowser(browser())->GetAllDownloads(&downloads);
2091 ASSERT_EQ(1u, downloads.size());
2092 EXPECT_EQ(DownloadItem::COMPLETE, downloads[0]->GetState());
2094 // Unfortunately, this will block forever, causing a timeout, if
2095 // the download is never opened.
2096 content::DownloadUpdatedObserver(
2097 downloads[0], base::Bind(&WasAutoOpened)).WaitForEvent();
2098 EXPECT_TRUE(downloads[0]->GetOpened()); // Confirm it anyway.
2100 // As long as we're here, confirmed everything else is good.
2101 EXPECT_EQ(1, browser()->tab_strip_model()->count());
2102 CheckDownload(browser(), file, file);
2103 // Download shelf should close. Download panel stays open on ChromeOS.
2104 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
2107 // Download an extension. Expect a dangerous download warning.
2108 // Deny the download.
2109 IN_PROC_BROWSER_TEST_F(DownloadTest, CrxDenyInstall) {
2110 FeatureSwitch::ScopedOverride enable_easy_off_store_install(
2111 FeatureSwitch::easy_off_store_install(), true);
2113 GURL extension_url(URLRequestMockHTTPJob::GetMockUrl(kGoodCrxPath));
2115 scoped_ptr<content::DownloadTestObserver> observer(
2116 DangerousDownloadWaiter(
2117 browser(), 1,
2118 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_DENY));
2119 ui_test_utils::NavigateToURL(browser(), extension_url);
2121 observer->WaitForFinished();
2122 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::CANCELLED));
2123 EXPECT_EQ(1u, observer->NumDangerousDownloadsSeen());
2125 // Download shelf should close.
2126 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
2128 // Check that the CRX is not installed.
2129 ExtensionService* extension_service = extensions::ExtensionSystem::Get(
2130 browser()->profile())->extension_service();
2131 ASSERT_FALSE(extension_service->GetExtensionById(kGoodCrxId, false));
2134 // Download an extension. Expect a dangerous download warning.
2135 // Allow the download, deny the install.
2136 IN_PROC_BROWSER_TEST_F(DownloadTest, CrxInstallDenysPermissions) {
2137 FeatureSwitch::ScopedOverride enable_easy_off_store_install(
2138 FeatureSwitch::easy_off_store_install(), true);
2140 GURL extension_url(URLRequestMockHTTPJob::GetMockUrl(kGoodCrxPath));
2142 // Install a mock install UI that simulates a user denying permission to
2143 // finish the install.
2144 download_crx_util::SetMockInstallPromptForTesting(
2145 scoped_ptr<ExtensionInstallPrompt>(
2146 new MockAbortExtensionInstallPrompt()));
2148 scoped_ptr<content::DownloadTestObserver> observer(
2149 DangerousDownloadWaiter(
2150 browser(), 1,
2151 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_ACCEPT));
2152 ui_test_utils::NavigateToURL(browser(), extension_url);
2154 observer->WaitForFinished();
2155 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::COMPLETE));
2156 CheckDownloadStates(1, DownloadItem::COMPLETE);
2157 EXPECT_EQ(1u, observer->NumDangerousDownloadsSeen());
2159 // Download shelf should close from auto-open.
2160 content::DownloadManager::DownloadVector downloads;
2161 DownloadManagerForBrowser(browser())->GetAllDownloads(&downloads);
2162 ASSERT_EQ(1u, downloads.size());
2163 content::DownloadUpdatedObserver(
2164 downloads[0], base::Bind(&WasAutoOpened)).WaitForEvent();
2165 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
2167 // Check that the extension was not installed.
2168 ExtensionService* extension_service = extensions::ExtensionSystem::Get(
2169 browser()->profile())->extension_service();
2170 ASSERT_FALSE(extension_service->GetExtensionById(kGoodCrxId, false));
2173 // Download an extension. Expect a dangerous download warning.
2174 // Allow the download, and the install.
2175 IN_PROC_BROWSER_TEST_F(DownloadTest, CrxInstallAcceptPermissions) {
2176 FeatureSwitch::ScopedOverride enable_easy_off_store_install(
2177 FeatureSwitch::easy_off_store_install(), true);
2179 GURL extension_url(URLRequestMockHTTPJob::GetMockUrl(kGoodCrxPath));
2181 // Install a mock install UI that simulates a user allowing permission to
2182 // finish the install.
2183 SetAllowMockInstallPrompt();
2185 scoped_ptr<content::DownloadTestObserver> observer(
2186 DangerousDownloadWaiter(
2187 browser(), 1,
2188 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_ACCEPT));
2189 ui_test_utils::NavigateToURL(browser(), extension_url);
2191 observer->WaitForFinished();
2192 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::COMPLETE));
2193 CheckDownloadStates(1, DownloadItem::COMPLETE);
2194 EXPECT_EQ(1u, observer->NumDangerousDownloadsSeen());
2196 // Download shelf should close from auto-open.
2197 content::DownloadManager::DownloadVector downloads;
2198 DownloadManagerForBrowser(browser())->GetAllDownloads(&downloads);
2199 ASSERT_EQ(1u, downloads.size());
2200 content::DownloadUpdatedObserver(
2201 downloads[0], base::Bind(&WasAutoOpened)).WaitForEvent();
2202 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
2204 // Check that the extension was installed.
2205 ExtensionService* extension_service = extensions::ExtensionSystem::Get(
2206 browser()->profile())->extension_service();
2207 ASSERT_TRUE(extension_service->GetExtensionById(kGoodCrxId, false));
2210 // Test installing a CRX that fails integrity checks.
2211 IN_PROC_BROWSER_TEST_F(DownloadTest, CrxInvalid) {
2212 base::FilePath file(FILE_PATH_LITERAL("extensions/bad_signature.crx"));
2213 GURL extension_url(URLRequestMockHTTPJob::GetMockUrl(file));
2215 // Install a mock install UI that simulates a user allowing permission to
2216 // finish the install, and dismisses any error message. We check that the
2217 // install failed below.
2218 SetAllowMockInstallPrompt();
2220 scoped_ptr<content::DownloadTestObserver> observer(
2221 DangerousDownloadWaiter(
2222 browser(), 1,
2223 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_ACCEPT));
2224 ui_test_utils::NavigateToURL(browser(), extension_url);
2226 observer->WaitForFinished();
2227 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::COMPLETE));
2228 CheckDownloadStates(1, DownloadItem::COMPLETE);
2230 // Check that the extension was not installed.
2231 ExtensionService* extension_service = extensions::ExtensionSystem::Get(
2232 browser()->profile())->extension_service();
2233 ASSERT_FALSE(extension_service->GetExtensionById(kGoodCrxId, false));
2236 // Install a large (100kb) theme.
2237 IN_PROC_BROWSER_TEST_F(DownloadTest, CrxLargeTheme) {
2238 FeatureSwitch::ScopedOverride enable_easy_off_store_install(
2239 FeatureSwitch::easy_off_store_install(), true);
2241 GURL extension_url(URLRequestMockHTTPJob::GetMockUrl(kLargeThemePath));
2243 // Install a mock install UI that simulates a user allowing permission to
2244 // finish the install.
2245 SetAllowMockInstallPrompt();
2247 scoped_ptr<content::DownloadTestObserver> observer(
2248 DangerousDownloadWaiter(
2249 browser(), 1,
2250 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_ACCEPT));
2251 ui_test_utils::NavigateToURL(browser(), extension_url);
2253 observer->WaitForFinished();
2254 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::COMPLETE));
2255 CheckDownloadStates(1, DownloadItem::COMPLETE);
2256 EXPECT_EQ(1u, observer->NumDangerousDownloadsSeen());
2258 // Download shelf should close from auto-open.
2259 content::DownloadManager::DownloadVector downloads;
2260 DownloadManagerForBrowser(browser())->GetAllDownloads(&downloads);
2261 ASSERT_EQ(1u, downloads.size());
2262 content::DownloadUpdatedObserver(
2263 downloads[0], base::Bind(&WasAutoOpened)).WaitForEvent();
2264 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
2266 // Check that the extension was installed.
2267 ExtensionService* extension_service = extensions::ExtensionSystem::Get(
2268 browser()->profile())->extension_service();
2269 ASSERT_TRUE(extension_service->GetExtensionById(kLargeThemeCrxId, false));
2272 // Tests for download initiation functions.
2273 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadUrl) {
2274 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
2275 GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
2277 // DownloadUrl always prompts; return acceptance of whatever it prompts.
2278 EnableFileChooser(true);
2280 WebContents* web_contents =
2281 browser()->tab_strip_model()->GetActiveWebContents();
2282 ASSERT_TRUE(web_contents);
2284 content::DownloadTestObserver* observer(
2285 new content::DownloadTestObserverTerminal(
2286 DownloadManagerForBrowser(browser()), 1,
2287 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL));
2288 scoped_ptr<DownloadUrlParameters> params(
2289 DownloadUrlParameters::FromWebContents(web_contents, url));
2290 params->set_prompt(true);
2291 DownloadManagerForBrowser(browser())->DownloadUrl(params.Pass());
2292 observer->WaitForFinished();
2293 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::COMPLETE));
2294 CheckDownloadStates(1, DownloadItem::COMPLETE);
2295 EXPECT_TRUE(DidShowFileChooser());
2297 // Check state.
2298 EXPECT_EQ(1, browser()->tab_strip_model()->count());
2299 ASSERT_TRUE(CheckDownload(browser(), file, file));
2300 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
2303 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadUrlToPath) {
2304 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
2305 GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
2307 WebContents* web_contents =
2308 browser()->tab_strip_model()->GetActiveWebContents();
2309 ASSERT_TRUE(web_contents);
2311 base::ScopedTempDir other_directory;
2312 ASSERT_TRUE(other_directory.CreateUniqueTempDir());
2313 base::FilePath target_file_full_path
2314 = other_directory.path().Append(file.BaseName());
2315 content::DownloadTestObserver* observer(CreateWaiter(browser(), 1));
2316 scoped_ptr<DownloadUrlParameters> params(
2317 DownloadUrlParameters::FromWebContents(web_contents, url));
2318 params->set_file_path(target_file_full_path);
2319 DownloadManagerForBrowser(browser())->DownloadUrl(params.Pass());
2320 observer->WaitForFinished();
2321 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::COMPLETE));
2323 // Check state.
2324 EXPECT_EQ(1, browser()->tab_strip_model()->count());
2325 ASSERT_TRUE(CheckDownloadFullPaths(browser(),
2326 target_file_full_path,
2327 OriginFile(file)));
2329 // Temporary are treated as auto-opened, and after that open won't be
2330 // visible; wait for auto-open and confirm not visible.
2331 std::vector<DownloadItem*> downloads;
2332 DownloadManagerForBrowser(browser())->GetAllDownloads(&downloads);
2333 ASSERT_EQ(1u, downloads.size());
2334 content::DownloadUpdatedObserver(
2335 downloads[0], base::Bind(&WasAutoOpened)).WaitForEvent();
2336 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
2339 IN_PROC_BROWSER_TEST_F(DownloadTest, SavePageNonHTMLViaGet) {
2340 embedded_test_server()->ServeFilesFromDirectory(GetTestDataDirectory());
2341 ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
2342 EnableFileChooser(true);
2343 std::vector<DownloadItem*> download_items;
2344 GetDownloads(browser(), &download_items);
2345 ASSERT_TRUE(download_items.empty());
2347 // Navigate to a non-HTML resource. The resource also has
2348 // Cache-Control: no-cache set, which normally requires revalidation
2349 // each time.
2350 GURL url = embedded_test_server()->GetURL("/downloads/image.jpg");
2351 ASSERT_TRUE(url.is_valid());
2352 ui_test_utils::NavigateToURL(browser(), url);
2354 // Stop the test server, and then try to save the page. If cache validation
2355 // is not bypassed then this will fail since the server is no longer
2356 // reachable.
2357 ASSERT_TRUE(embedded_test_server()->ShutdownAndWaitUntilComplete());
2359 scoped_ptr<content::DownloadTestObserver> waiter(
2360 new content::DownloadTestObserverTerminal(
2361 DownloadManagerForBrowser(browser()), 1,
2362 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL));
2363 chrome::SavePage(browser());
2364 waiter->WaitForFinished();
2365 EXPECT_EQ(1u, waiter->NumDownloadsSeenInState(DownloadItem::COMPLETE));
2366 CheckDownloadStates(1, DownloadItem::COMPLETE);
2368 // Validate that the correct file was downloaded.
2369 GetDownloads(browser(), &download_items);
2370 EXPECT_TRUE(DidShowFileChooser());
2371 ASSERT_EQ(1u, download_items.size());
2372 ASSERT_EQ(url, download_items[0]->GetOriginalUrl());
2374 // Try to download it via a context menu.
2375 scoped_ptr<content::DownloadTestObserver> waiter_context_menu(
2376 new content::DownloadTestObserverTerminal(
2377 DownloadManagerForBrowser(browser()), 1,
2378 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL));
2379 content::ContextMenuParams context_menu_params;
2380 context_menu_params.media_type = blink::WebContextMenuData::MediaTypeImage;
2381 context_menu_params.src_url = url;
2382 context_menu_params.page_url = url;
2383 TestRenderViewContextMenu menu(
2384 browser()->tab_strip_model()->GetActiveWebContents()->GetMainFrame(),
2385 context_menu_params);
2386 menu.Init();
2387 menu.ExecuteCommand(IDC_CONTENT_CONTEXT_SAVEIMAGEAS, 0);
2388 waiter_context_menu->WaitForFinished();
2389 EXPECT_EQ(
2390 1u, waiter_context_menu->NumDownloadsSeenInState(DownloadItem::COMPLETE));
2391 CheckDownloadStates(2, DownloadItem::COMPLETE);
2393 // Validate that the correct file was downloaded via the context menu.
2394 download_items.clear();
2395 GetDownloads(browser(), &download_items);
2396 EXPECT_TRUE(DidShowFileChooser());
2397 ASSERT_EQ(2u, download_items.size());
2398 ASSERT_EQ(url, download_items[0]->GetOriginalUrl());
2399 ASSERT_EQ(url, download_items[1]->GetOriginalUrl());
2402 // A EmbeddedTestServer::HandleRequestCallback function that checks for requests
2403 // with query string ?allow-post-only, and returns a 404 response if the method
2404 // is not POST.
2405 static scoped_ptr<net::test_server::HttpResponse> FilterPostOnlyURLsHandler(
2406 const net::test_server::HttpRequest& request) {
2407 scoped_ptr<net::test_server::BasicHttpResponse> response;
2408 if (request.relative_url.find("?allow-post-only") != std::string::npos &&
2409 request.method != net::test_server::METHOD_POST) {
2410 response.reset(new net::test_server::BasicHttpResponse());
2411 response->set_code(net::HTTP_NOT_FOUND);
2413 return response.Pass();
2416 IN_PROC_BROWSER_TEST_F(DownloadTest, SavePageNonHTMLViaPost) {
2417 embedded_test_server()->RegisterRequestHandler(
2418 base::Bind(&FilterPostOnlyURLsHandler));
2419 embedded_test_server()->ServeFilesFromDirectory(GetTestDataDirectory());
2420 ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
2421 EnableFileChooser(true);
2422 std::vector<DownloadItem*> download_items;
2423 GetDownloads(browser(), &download_items);
2424 ASSERT_TRUE(download_items.empty());
2426 // Navigate to a form page.
2427 GURL form_url =
2428 embedded_test_server()->GetURL("/downloads/form_page_to_post.html");
2429 ASSERT_TRUE(form_url.is_valid());
2430 ui_test_utils::NavigateToURL(browser(), form_url);
2432 // Submit the form. This will send a POST reqeuest, and the response is a
2433 // JPEG image. The resource also has Cache-Control: no-cache set,
2434 // which normally requires revalidation each time.
2435 GURL jpeg_url =
2436 embedded_test_server()->GetURL("/downloads/image.jpg?allow-post-only");
2437 ASSERT_TRUE(jpeg_url.is_valid());
2438 WebContents* web_contents =
2439 browser()->tab_strip_model()->GetActiveWebContents();
2440 ASSERT_TRUE(web_contents != NULL);
2441 content::WindowedNotificationObserver observer(
2442 content::NOTIFICATION_NAV_ENTRY_COMMITTED,
2443 content::Source<content::NavigationController>(
2444 &web_contents->GetController()));
2445 content::RenderFrameHost* render_frame_host = web_contents->GetMainFrame();
2446 ASSERT_TRUE(render_frame_host != NULL);
2447 render_frame_host->ExecuteJavaScript(base::ASCIIToUTF16("SubmitForm()"));
2448 observer.Wait();
2449 EXPECT_EQ(jpeg_url, web_contents->GetURL());
2451 // Stop the test server, and then try to save the page. If cache validation
2452 // is not bypassed then this will fail since the server is no longer
2453 // reachable. This will also fail if it tries to be retrieved via "GET"
2454 // rather than "POST".
2455 ASSERT_TRUE(embedded_test_server()->ShutdownAndWaitUntilComplete());
2456 scoped_ptr<content::DownloadTestObserver> waiter(
2457 new content::DownloadTestObserverTerminal(
2458 DownloadManagerForBrowser(browser()), 1,
2459 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL));
2460 chrome::SavePage(browser());
2461 waiter->WaitForFinished();
2462 EXPECT_EQ(1u, waiter->NumDownloadsSeenInState(DownloadItem::COMPLETE));
2463 CheckDownloadStates(1, DownloadItem::COMPLETE);
2465 // Validate that the correct file was downloaded.
2466 GetDownloads(browser(), &download_items);
2467 EXPECT_TRUE(DidShowFileChooser());
2468 ASSERT_EQ(1u, download_items.size());
2469 ASSERT_EQ(jpeg_url, download_items[0]->GetOriginalUrl());
2471 // Try to download it via a context menu.
2472 scoped_ptr<content::DownloadTestObserver> waiter_context_menu(
2473 new content::DownloadTestObserverTerminal(
2474 DownloadManagerForBrowser(browser()), 1,
2475 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL));
2476 content::ContextMenuParams context_menu_params;
2477 context_menu_params.media_type = blink::WebContextMenuData::MediaTypeImage;
2478 context_menu_params.src_url = jpeg_url;
2479 context_menu_params.page_url = jpeg_url;
2480 TestRenderViewContextMenu menu(web_contents->GetMainFrame(),
2481 context_menu_params);
2482 menu.Init();
2483 menu.ExecuteCommand(IDC_CONTENT_CONTEXT_SAVEIMAGEAS, 0);
2484 waiter_context_menu->WaitForFinished();
2485 EXPECT_EQ(
2486 1u, waiter_context_menu->NumDownloadsSeenInState(DownloadItem::COMPLETE));
2487 CheckDownloadStates(2, DownloadItem::COMPLETE);
2489 // Validate that the correct file was downloaded via the context menu.
2490 download_items.clear();
2491 GetDownloads(browser(), &download_items);
2492 EXPECT_TRUE(DidShowFileChooser());
2493 ASSERT_EQ(2u, download_items.size());
2494 ASSERT_EQ(jpeg_url, download_items[0]->GetOriginalUrl());
2495 ASSERT_EQ(jpeg_url, download_items[1]->GetOriginalUrl());
2498 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadErrorsServer) {
2499 DownloadInfo download_info[] = {
2500 { // Normal navigated download.
2501 "a_zip_file.zip",
2502 DOWNLOAD_NAVIGATE,
2503 content::DOWNLOAD_INTERRUPT_REASON_NONE,
2504 true,
2505 false
2507 { // Normal direct download.
2508 "a_zip_file.zip",
2509 DOWNLOAD_DIRECT,
2510 content::DOWNLOAD_INTERRUPT_REASON_NONE,
2511 true,
2512 false
2514 { // Direct download with 404 error.
2515 "there_IS_no_spoon.zip",
2516 DOWNLOAD_DIRECT,
2517 content::DOWNLOAD_INTERRUPT_REASON_SERVER_BAD_CONTENT,
2518 true,
2519 false
2521 { // Navigated download with 404 error.
2522 "there_IS_no_spoon.zip",
2523 DOWNLOAD_NAVIGATE,
2524 content::DOWNLOAD_INTERRUPT_REASON_SERVER_BAD_CONTENT,
2525 false,
2526 false
2528 { // Direct download with 400 error.
2529 "zip_file_not_found.zip",
2530 DOWNLOAD_DIRECT,
2531 content::DOWNLOAD_INTERRUPT_REASON_SERVER_FAILED,
2532 true,
2533 false
2535 { // Navigated download with 400 error.
2536 "zip_file_not_found.zip",
2537 DOWNLOAD_NAVIGATE,
2538 content::DOWNLOAD_INTERRUPT_REASON_SERVER_FAILED,
2539 false,
2540 false
2544 DownloadFilesCheckErrors(arraysize(download_info), download_info);
2547 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadErrorsFile) {
2548 FileErrorInjectInfo error_info[] = {
2549 { // Navigated download with injected "Disk full" error in Initialize().
2550 { "a_zip_file.zip",
2551 DOWNLOAD_NAVIGATE,
2552 content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE,
2557 content::TestFileErrorInjector::FILE_OPERATION_INITIALIZE,
2559 content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE,
2562 { // Direct download with injected "Disk full" error in Initialize().
2563 { "a_zip_file.zip",
2564 DOWNLOAD_DIRECT,
2565 content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE,
2570 content::TestFileErrorInjector::FILE_OPERATION_INITIALIZE,
2572 content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE,
2575 { // Navigated download with injected "Disk full" error in Write().
2576 { "a_zip_file.zip",
2577 DOWNLOAD_NAVIGATE,
2578 content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE,
2583 content::TestFileErrorInjector::FILE_OPERATION_WRITE,
2585 content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE,
2588 { // Direct download with injected "Disk full" error in Write().
2589 { "a_zip_file.zip",
2590 DOWNLOAD_DIRECT,
2591 content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE,
2596 content::TestFileErrorInjector::FILE_OPERATION_WRITE,
2598 content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE,
2601 { // Navigated download with injected "Failed" error in Initialize().
2602 { "a_zip_file.zip",
2603 DOWNLOAD_NAVIGATE,
2604 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED,
2609 content::TestFileErrorInjector::FILE_OPERATION_INITIALIZE,
2611 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED,
2614 { // Direct download with injected "Failed" error in Initialize().
2615 { "a_zip_file.zip",
2616 DOWNLOAD_DIRECT,
2617 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED,
2622 content::TestFileErrorInjector::FILE_OPERATION_INITIALIZE,
2624 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED,
2627 { // Navigated download with injected "Failed" error in Write().
2628 { "a_zip_file.zip",
2629 DOWNLOAD_NAVIGATE,
2630 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED,
2635 content::TestFileErrorInjector::FILE_OPERATION_WRITE,
2637 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED,
2640 { // Direct download with injected "Failed" error in Write().
2641 { "a_zip_file.zip",
2642 DOWNLOAD_DIRECT,
2643 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED,
2648 content::TestFileErrorInjector::FILE_OPERATION_WRITE,
2650 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED,
2653 { // Navigated download with injected "Name too long" error in
2654 // Initialize().
2655 { "a_zip_file.zip",
2656 DOWNLOAD_NAVIGATE,
2657 content::DOWNLOAD_INTERRUPT_REASON_FILE_NAME_TOO_LONG,
2662 content::TestFileErrorInjector::FILE_OPERATION_INITIALIZE,
2664 content::DOWNLOAD_INTERRUPT_REASON_FILE_NAME_TOO_LONG,
2667 { // Direct download with injected "Name too long" error in Initialize().
2668 { "a_zip_file.zip",
2669 DOWNLOAD_DIRECT,
2670 content::DOWNLOAD_INTERRUPT_REASON_FILE_NAME_TOO_LONG,
2675 content::TestFileErrorInjector::FILE_OPERATION_INITIALIZE,
2677 content::DOWNLOAD_INTERRUPT_REASON_FILE_NAME_TOO_LONG,
2680 { // Navigated download with injected "Name too long" error in Write().
2681 { "a_zip_file.zip",
2682 DOWNLOAD_NAVIGATE,
2683 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED,
2688 content::TestFileErrorInjector::FILE_OPERATION_WRITE,
2690 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED,
2693 { // Direct download with injected "Name too long" error in Write().
2694 { "a_zip_file.zip",
2695 DOWNLOAD_DIRECT,
2696 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED,
2701 content::TestFileErrorInjector::FILE_OPERATION_WRITE,
2703 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED,
2706 { // Direct download with injected "Disk full" error in 2nd Write().
2707 { "06bESSE21Evolution.ppt",
2708 DOWNLOAD_DIRECT,
2709 content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE,
2714 content::TestFileErrorInjector::FILE_OPERATION_WRITE,
2716 content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE,
2721 DownloadInsertFilesErrorCheckErrors(arraysize(error_info), error_info);
2724 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadErrorReadonlyFolder) {
2725 DownloadInfo download_info[] = {
2727 "a_zip_file.zip",
2728 DOWNLOAD_DIRECT,
2729 // This passes because we switch to the My Documents folder.
2730 content::DOWNLOAD_INTERRUPT_REASON_NONE,
2731 true,
2732 true
2735 "a_zip_file.zip",
2736 DOWNLOAD_NAVIGATE,
2737 // This passes because we switch to the My Documents folder.
2738 content::DOWNLOAD_INTERRUPT_REASON_NONE,
2739 true,
2740 true
2744 DownloadFilesToReadonlyFolder(arraysize(download_info), download_info);
2747 // Test that we show a dangerous downloads warning for a dangerous file
2748 // downloaded through a blob: URL.
2749 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadDangerousBlobData) {
2750 #if defined(OS_WIN)
2751 // On Windows, if SafeBrowsing is enabled, certain file types (.exe, .cab,
2752 // .msi) will be handled by the DownloadProtectionService. However, if the URL
2753 // is non-standard (e.g. blob:) then those files won't be handled by the
2754 // DPS. We should be showing the dangerous download warning for any file
2755 // considered dangerous and isn't handled by the DPS.
2756 const char kFilename[] = "foo.exe";
2757 #else
2758 const char kFilename[] = "foo.swf";
2759 #endif
2761 std::string path("downloads/download-dangerous-blob.html?filename=");
2762 path += kFilename;
2764 // Need to use http urls because the blob js doesn't work on file urls for
2765 // security reasons.
2766 GURL url = net::URLRequestMockHTTPJob::GetMockUrl(path);
2768 content::DownloadTestObserver* observer(DangerousDownloadWaiter(
2769 browser(), 1,
2770 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_ACCEPT));
2771 ui_test_utils::NavigateToURL(browser(), url);
2772 observer->WaitForFinished();
2774 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::COMPLETE));
2775 EXPECT_EQ(1u, observer->NumDangerousDownloadsSeen());
2778 // A EmbeddedTestServer::HandleRequestCallback function that echoes the Referrer
2779 // header as its contents. Only responds to the relative URL /echoreferrer
2780 // E.g.:
2781 // C -> S: GET /foo
2782 // Referer: http://example.com/foo
2783 // S -> C: HTTP/1.1 200 OK
2784 // Content-Type: text/plain
2786 // http://example.com/foo
2787 static scoped_ptr<net::test_server::HttpResponse> EchoReferrerRequestHandler(
2788 const net::test_server::HttpRequest& request) {
2789 const std::string kReferrerHeader = "Referer"; // SIC
2791 if (request.relative_url.find("/echoreferrer") != 0)
2792 return scoped_ptr<net::test_server::HttpResponse>();
2794 scoped_ptr<net::test_server::BasicHttpResponse> response(
2795 new net::test_server::BasicHttpResponse());
2796 response->set_code(net::HTTP_OK);
2797 response->set_content_type("text/plain");
2798 auto referrer_header = request.headers.find(kReferrerHeader);
2799 if (referrer_header != request.headers.end())
2800 response->set_content(referrer_header->second);
2801 return response.Pass();
2804 IN_PROC_BROWSER_TEST_F(DownloadTest, LoadURLExternallyReferrerPolicy) {
2805 embedded_test_server()->RegisterRequestHandler(
2806 base::Bind(&EchoReferrerRequestHandler));
2807 embedded_test_server()->ServeFilesFromDirectory(GetTestDataDirectory());
2808 ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
2809 EnableFileChooser(true);
2810 std::vector<DownloadItem*> download_items;
2811 GetDownloads(browser(), &download_items);
2812 ASSERT_TRUE(download_items.empty());
2814 // Navigate to a page with a referrer policy and a link on it. The link points
2815 // to /echoreferrer.
2816 GURL url = embedded_test_server()->GetURL("/downloads/referrer_policy.html");
2817 ASSERT_TRUE(url.is_valid());
2818 ui_test_utils::NavigateToURL(browser(), url);
2820 scoped_ptr<content::DownloadTestObserver> waiter(
2821 new content::DownloadTestObserverTerminal(
2822 DownloadManagerForBrowser(browser()), 1,
2823 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL));
2825 // Click on the link with the alt key pressed. This will download the link
2826 // target.
2827 WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
2828 blink::WebMouseEvent mouse_event;
2829 mouse_event.type = blink::WebInputEvent::MouseDown;
2830 mouse_event.button = blink::WebMouseEvent::ButtonLeft;
2831 mouse_event.x = 15;
2832 mouse_event.y = 15;
2833 mouse_event.clickCount = 1;
2834 mouse_event.modifiers = blink::WebInputEvent::AltKey;
2835 tab->GetRenderViewHost()->ForwardMouseEvent(mouse_event);
2836 mouse_event.type = blink::WebInputEvent::MouseUp;
2837 tab->GetRenderViewHost()->ForwardMouseEvent(mouse_event);
2839 waiter->WaitForFinished();
2840 EXPECT_EQ(1u, waiter->NumDownloadsSeenInState(DownloadItem::COMPLETE));
2841 CheckDownloadStates(1, DownloadItem::COMPLETE);
2843 // Validate that the correct file was downloaded.
2844 GetDownloads(browser(), &download_items);
2845 ASSERT_EQ(1u, download_items.size());
2846 ASSERT_EQ(embedded_test_server()->GetURL("/echoreferrer"),
2847 download_items[0]->GetOriginalUrl());
2849 // Check that the file contains the expected referrer.
2850 base::FilePath file(download_items[0]->GetTargetFilePath());
2851 std::string expected_contents = embedded_test_server()->GetURL("/").spec();
2852 ASSERT_TRUE(VerifyFile(file, expected_contents, expected_contents.length()));
2855 // This test ensures that the Referer header is properly sanitized when
2856 // Save Link As is chosen from the context menu.
2857 IN_PROC_BROWSER_TEST_F(DownloadTest, SaveLinkAsReferrerPolicyOrigin) {
2858 embedded_test_server()->RegisterRequestHandler(
2859 base::Bind(&EchoReferrerRequestHandler));
2860 ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
2861 EnableFileChooser(true);
2862 std::vector<DownloadItem*> download_items;
2863 GetDownloads(browser(), &download_items);
2864 ASSERT_TRUE(download_items.empty());
2866 // Navigate to the initial page, where Save Link As will be executed.
2867 GURL url = net::URLRequestMockHTTPJob::GetMockHttpsUrl(
2868 std::string("referrer_policy/referrer-policy-start.html?policy=origin") +
2869 "&redirect=" + embedded_test_server()->GetURL("/echoreferrer").spec() +
2870 "&link=true&target=");
2871 ASSERT_TRUE(url.is_valid());
2872 ui_test_utils::NavigateToURL(browser(), url);
2874 scoped_ptr<content::DownloadTestObserver> waiter(
2875 new content::DownloadTestObserverTerminal(
2876 DownloadManagerForBrowser(browser()), 1,
2877 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL));
2879 // Right-click on the link and choose Save Link As. This will download the
2880 // link target.
2881 ContextMenuNotificationObserver context_menu_observer(
2882 IDC_CONTENT_CONTEXT_SAVELINKAS);
2884 WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
2885 blink::WebMouseEvent mouse_event;
2886 mouse_event.type = blink::WebInputEvent::MouseDown;
2887 mouse_event.button = blink::WebMouseEvent::ButtonRight;
2888 mouse_event.x = 15;
2889 mouse_event.y = 15;
2890 mouse_event.clickCount = 1;
2891 tab->GetRenderViewHost()->ForwardMouseEvent(mouse_event);
2892 mouse_event.type = blink::WebInputEvent::MouseUp;
2893 tab->GetRenderViewHost()->ForwardMouseEvent(mouse_event);
2895 waiter->WaitForFinished();
2896 EXPECT_EQ(1u, waiter->NumDownloadsSeenInState(DownloadItem::COMPLETE));
2897 CheckDownloadStates(1, DownloadItem::COMPLETE);
2899 // Validate that the correct file was downloaded.
2900 GetDownloads(browser(), &download_items);
2901 EXPECT_EQ(1u, download_items.size());
2902 EXPECT_EQ(embedded_test_server()->GetURL("/echoreferrer"),
2903 download_items[0]->GetOriginalUrl());
2905 // Check that the file contains the expected referrer.
2906 base::FilePath file(download_items[0]->GetTargetFilePath());
2907 std::string expected_contents =
2908 net::URLRequestMockHTTPJob::GetMockHttpsUrl(std::string()).spec();
2909 EXPECT_TRUE(VerifyFile(file, expected_contents, expected_contents.length()));
2912 // This test ensures that the Referer header is properly sanitized when
2913 // Save Image As is chosen from the context menu.
2914 IN_PROC_BROWSER_TEST_F(DownloadTest, SaveImageAsReferrerPolicyDefault) {
2915 embedded_test_server()->RegisterRequestHandler(
2916 base::Bind(&EchoReferrerRequestHandler));
2917 ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
2918 EnableFileChooser(true);
2919 std::vector<DownloadItem*> download_items;
2920 GetDownloads(browser(), &download_items);
2921 ASSERT_TRUE(download_items.empty());
2923 GURL url = net::URLRequestMockHTTPJob::GetMockHttpsUrl("title1.html");
2924 GURL img_url = embedded_test_server()->GetURL("/echoreferrer");
2925 ASSERT_TRUE(url.is_valid());
2926 ui_test_utils::NavigateToURL(browser(), url);
2928 // Try to download an image via a context menu.
2929 scoped_ptr<content::DownloadTestObserver> waiter_context_menu(
2930 new content::DownloadTestObserverTerminal(
2931 DownloadManagerForBrowser(browser()), 1,
2932 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL));
2933 content::ContextMenuParams context_menu_params;
2934 context_menu_params.media_type = blink::WebContextMenuData::MediaTypeImage;
2935 context_menu_params.page_url = url;
2936 context_menu_params.src_url = img_url;
2937 TestRenderViewContextMenu menu(
2938 browser()->tab_strip_model()->GetActiveWebContents()->GetMainFrame(),
2939 context_menu_params);
2940 menu.Init();
2941 menu.ExecuteCommand(IDC_CONTENT_CONTEXT_SAVEIMAGEAS, 0);
2942 waiter_context_menu->WaitForFinished();
2943 EXPECT_EQ(
2944 1u, waiter_context_menu->NumDownloadsSeenInState(DownloadItem::COMPLETE));
2945 CheckDownloadStates(1, DownloadItem::COMPLETE);
2947 // Validate that the correct file was downloaded via the context menu.
2948 download_items.clear();
2949 GetDownloads(browser(), &download_items);
2950 EXPECT_TRUE(DidShowFileChooser());
2951 ASSERT_EQ(1u, download_items.size());
2952 ASSERT_EQ(img_url, download_items[0]->GetOriginalUrl());
2953 base::FilePath file = download_items[0]->GetTargetFilePath();
2954 // The contents of the file is the value of the Referer header if there was
2955 // one.
2956 EXPECT_TRUE(VerifyFile(file, "", 0));
2959 IN_PROC_BROWSER_TEST_F(DownloadTest, HiddenDownload) {
2960 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
2961 GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
2963 DownloadManager* download_manager = DownloadManagerForBrowser(browser());
2964 scoped_ptr<content::DownloadTestObserver> observer(
2965 new content::DownloadTestObserverTerminal(
2966 download_manager,
2968 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL));
2970 // Download and set IsHiddenDownload to true.
2971 WebContents* web_contents =
2972 browser()->tab_strip_model()->GetActiveWebContents();
2973 scoped_ptr<DownloadUrlParameters> params(
2974 DownloadUrlParameters::FromWebContents(web_contents, url));
2975 params->set_callback(base::Bind(&SetHiddenDownloadCallback));
2976 download_manager->DownloadUrl(params.Pass());
2977 observer->WaitForFinished();
2979 // Verify that download shelf is not shown.
2980 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
2983 // Verify the multiple downloads infobar.
2984 IN_PROC_BROWSER_TEST_F(DownloadTest, TestMultipleDownloadsInfobar) {
2985 #if defined(OS_WIN) && defined(USE_ASH)
2986 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
2987 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
2988 switches::kAshBrowserTests))
2989 return;
2990 #endif
2992 // Ensure that infobars are being used instead of bubbles.
2993 base::CommandLine::ForCurrentProcess()->AppendSwitch(
2994 switches::kDisablePermissionsBubbles);
2996 // Create a downloads observer.
2997 scoped_ptr<content::DownloadTestObserver> downloads_observer(
2998 CreateWaiter(browser(), 2));
3000 // Create an infobar observer.
3001 content::WindowedNotificationObserver infobar_added_1(
3002 chrome::NOTIFICATION_TAB_CONTENTS_INFOBAR_ADDED,
3003 content::NotificationService::AllSources());
3004 ui_test_utils::NavigateToURL(browser(),
3005 net::URLRequestMockHTTPJob::GetMockUrl(
3006 "downloads/download-a_zip_file.html"));
3007 infobar_added_1.Wait();
3009 InfoBarService* infobar_service = InfoBarService::FromWebContents(
3010 browser()->tab_strip_model()->GetActiveWebContents());
3011 // Verify that there is only one infobar.
3012 ASSERT_EQ(1u, infobar_service->infobar_count());
3014 // Get the infobar at index 0.
3015 infobars::InfoBar* infobar = infobar_service->infobar_at(0);
3016 ConfirmInfoBarDelegate* confirm_infobar =
3017 infobar->delegate()->AsConfirmInfoBarDelegate();
3018 ASSERT_TRUE(confirm_infobar != NULL);
3020 // Verify multi download warning infobar message.
3021 EXPECT_EQ(confirm_infobar->GetMessageText(),
3022 l10n_util::GetStringUTF16(IDS_MULTI_DOWNLOAD_WARNING));
3024 // Click on the "Allow" button to allow multiple downloads.
3025 if (confirm_infobar->Accept())
3026 infobar_service->RemoveInfoBar(infobar);
3027 // Verify that there are no more infobars.
3028 EXPECT_EQ(0u, infobar_service->infobar_count());
3030 // Waits for the download to complete.
3031 downloads_observer->WaitForFinished();
3032 EXPECT_EQ(2u, downloads_observer->NumDownloadsSeenInState(
3033 DownloadItem::COMPLETE));
3036 IN_PROC_BROWSER_TEST_F(DownloadTest, TestMultipleDownloadsBubble) {
3037 #if defined(OS_WIN) && defined(USE_ASH)
3038 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
3039 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
3040 switches::kAshBrowserTests))
3041 return;
3042 #endif
3044 #if defined(OS_ANDROID) || defined(OS_IOS)
3045 // Permission bubbles are not supported on mobile.
3046 return;
3047 #endif
3049 // Enable permision bubbles.
3050 base::CommandLine::ForCurrentProcess()->AppendSwitch(
3051 switches::kEnablePermissionsBubbles);
3053 // Create a downloads observer.
3054 scoped_ptr<content::DownloadTestObserver> downloads_observer(
3055 CreateWaiter(browser(), 2));
3057 PermissionBubbleManager* permission_bubble_manager =
3058 PermissionBubbleManager::FromWebContents(
3059 browser()->tab_strip_model()->GetActiveWebContents());
3060 permission_bubble_manager->DisplayPendingRequests(browser());
3061 permission_bubble_manager->set_auto_response_for_test(
3062 PermissionBubbleManager::ACCEPT_ALL);
3064 ui_test_utils::NavigateToURLBlockUntilNavigationsComplete(
3065 browser(), net::URLRequestMockHTTPJob::GetMockUrl(
3066 "downloads/download-a_zip_file.html"),
3069 // Waits for the download to complete.
3070 downloads_observer->WaitForFinished();
3071 EXPECT_EQ(2u, downloads_observer->NumDownloadsSeenInState(
3072 DownloadItem::COMPLETE));
3074 browser()->tab_strip_model()->GetActiveWebContents()->Close();
3077 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadTest_Renaming) {
3078 GURL url = net::URLRequestMockHTTPJob::GetMockUrl("downloads/a_zip_file.zip");
3079 content::DownloadManager* manager = DownloadManagerForBrowser(browser());
3080 base::FilePath origin_file(OriginFile(base::FilePath(FILE_PATH_LITERAL(
3081 "downloads/a_zip_file.zip"))));
3082 ASSERT_TRUE(base::PathExists(origin_file));
3083 std::string origin_contents;
3084 ASSERT_TRUE(base::ReadFileToString(origin_file, &origin_contents));
3086 // Download the same url several times and expect that all downloaded files
3087 // after the zero-th contain a deduplication counter.
3088 for (int index = 0; index < 5; ++index) {
3089 DownloadAndWait(browser(), url);
3090 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
3091 content::DownloadItem* item = manager->GetDownload(
3092 content::DownloadItem::kInvalidId + 1 + index);
3093 ASSERT_TRUE(item);
3094 ASSERT_EQ(DownloadItem::COMPLETE, item->GetState());
3095 base::FilePath target_path(item->GetTargetFilePath());
3096 EXPECT_EQ(std::string("a_zip_file") +
3097 (index == 0 ? std::string(".zip") :
3098 base::StringPrintf(" (%d).zip", index)),
3099 target_path.BaseName().AsUTF8Unsafe());
3100 ASSERT_TRUE(base::PathExists(target_path));
3101 ASSERT_TRUE(VerifyFile(target_path, origin_contents,
3102 origin_contents.size()));
3106 // Test that the entire download pipeline handles unicode correctly.
3107 // Disabled on Windows due to flaky timeouts: crbug.com/446695
3108 #if defined(OS_WIN)
3109 #define MAYBE_DownloadTest_CrazyFilenames DISABLED_DownloadTest_CrazyFilenames
3110 #else
3111 #define MAYBE_DownloadTest_CrazyFilenames DownloadTest_CrazyFilenames
3112 #endif
3113 IN_PROC_BROWSER_TEST_F(DownloadTest, MAYBE_DownloadTest_CrazyFilenames) {
3114 const wchar_t* kCrazyFilenames[] = {
3115 L"a_file_name.zip",
3116 L"\u89c6\u9891\u76f4\u64ad\u56fe\u7247.zip", // chinese chars
3117 L"\u0412\u043e \u0424\u043b\u043e\u0440\u0438\u0434\u0435\u043e\u0431\u044a"
3118 L"\u044f\u0432\u043b\u0435\u043d\u0440\u0435\u0436\u0438\u043c \u0427"
3119 L"\u041f \u0438\u0437-\u0437\u0430 \u0443\u0442\u0435\u0447\u043a\u0438 "
3120 L"\u043d\u0435\u0444\u0442\u0438.zip", // russian
3121 L"Desocupa\xe7\xe3o est\xe1vel.zip",
3122 // arabic:
3123 L"\u0638\u2026\u0638\u02c6\u0637\xa7\u0638\u201a\u0637\xb9 \u0638\u201e"
3124 L"\u0638\u201e\u0637\xb2\u0638\u0679\u0637\xa7\u0637\xb1\u0637\xa9.zip",
3125 L"\u05d4\u05e2\u05d3\u05e4\u05d5\u05ea.zip", // hebrew
3126 L"\u092d\u093e\u0930\u0924.zip", // hindi
3127 L"d\xe9stabilis\xe9.zip", // french
3128 // korean
3129 L"\u97d3-\u4e2d \uc815\uc0c1, \ucc9c\uc548\ud568 \uc758\uacac.zip",
3130 L"jiho....tiho...miho.zip",
3131 L"jiho!@#$tiho$%^&-()_+=miho copy.zip", // special chars
3132 L"Wohoo-to hoo+I.zip",
3133 L"Picture 1.zip",
3134 L"This is a very very long english sentence with spaces and , and +.zip",
3137 std::vector<DownloadItem*> download_items;
3138 base::FilePath origin(FILE_PATH_LITERAL("origin"));
3139 ASSERT_TRUE(base::CreateDirectory(DestinationFile(browser(), origin)));
3141 for (size_t index = 0; index < arraysize(kCrazyFilenames); ++index) {
3142 base::string16 crazy16;
3143 std::string crazy8;
3144 const wchar_t* crazy_w = kCrazyFilenames[index];
3145 ASSERT_TRUE(base::WideToUTF8(crazy_w, wcslen(crazy_w), &crazy8));
3146 ASSERT_TRUE(base::WideToUTF16(crazy_w, wcslen(crazy_w), &crazy16));
3147 base::FilePath file_path(DestinationFile(browser(), origin.Append(
3148 #if defined(OS_WIN)
3149 crazy16
3150 #elif defined(OS_POSIX)
3151 crazy8
3152 #endif
3153 )));
3155 // Create the file.
3156 EXPECT_EQ(static_cast<int>(crazy8.size()),
3157 base::WriteFile(file_path, crazy8.c_str(), crazy8.size()));
3158 GURL file_url(net::FilePathToFileURL(file_path));
3160 // Download the file and check that the filename is correct.
3161 DownloadAndWait(browser(), file_url);
3162 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
3163 GetDownloads(browser(), &download_items);
3164 ASSERT_EQ(1UL, download_items.size());
3165 base::FilePath downloaded(download_items[0]->GetTargetFilePath());
3166 download_items[0]->Remove();
3167 download_items.clear();
3168 ASSERT_TRUE(CheckDownloadFullPaths(
3169 browser(),
3170 downloaded,
3171 file_path));
3175 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadTest_Remove) {
3176 GURL url = net::URLRequestMockHTTPJob::GetMockUrl("downloads/a_zip_file.zip");
3177 std::vector<DownloadItem*> download_items;
3178 GetDownloads(browser(), &download_items);
3179 ASSERT_TRUE(download_items.empty());
3181 // Download a file.
3182 DownloadAndWaitWithDisposition(browser(),
3183 url,
3184 CURRENT_TAB,
3185 ui_test_utils::BROWSER_TEST_NONE);
3186 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
3187 GetDownloads(browser(), &download_items);
3188 ASSERT_EQ(1UL, download_items.size());
3189 base::FilePath downloaded(download_items[0]->GetTargetFilePath());
3191 // Remove the DownloadItem but not the file, then check that the file still
3192 // exists.
3193 download_items[0]->Remove();
3194 download_items.clear();
3195 GetDownloads(browser(), &download_items);
3196 ASSERT_EQ(0UL, download_items.size());
3197 ASSERT_TRUE(CheckDownloadFullPaths(
3198 browser(), downloaded, OriginFile(base::FilePath(
3199 FILE_PATH_LITERAL("downloads/a_zip_file.zip")))));
3202 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadTest_PauseResumeCancel) {
3203 DownloadItem* download_item = CreateSlowTestDownload();
3204 ASSERT_TRUE(download_item);
3205 ASSERT_FALSE(download_item->GetTargetFilePath().empty());
3206 EXPECT_FALSE(download_item->IsPaused());
3207 EXPECT_NE(DownloadItem::CANCELLED, download_item->GetState());
3208 download_item->Pause();
3209 EXPECT_TRUE(download_item->IsPaused());
3210 download_item->Resume();
3211 EXPECT_FALSE(download_item->IsPaused());
3212 EXPECT_NE(DownloadItem::CANCELLED, download_item->GetState());
3213 download_item->Cancel(true);
3214 EXPECT_EQ(DownloadItem::CANCELLED, download_item->GetState());
3217 // The Mac downloaded files quarantine feature is implemented by the
3218 // Contents/Info.plist file in cocoa apps. browser_tests cannot test
3219 // quarantining files on Mac because it is not a cocoa app.
3220 // TODO(benjhayden) test the equivalents on other platforms.
3222 #if defined(OS_LINUX) && !defined(OS_CHROMEOS) && defined(ARCH_CPU_ARM_FAMILY)
3223 // Timing out on ARM linux: http://crbug.com/238459
3224 #define MAYBE_DownloadTest_PercentComplete DISABLED_DownloadTest_PercentComplete
3225 #elif defined(OS_MACOSX)
3226 // Disable on mac: http://crbug.com/238831
3227 #define MAYBE_DownloadTest_PercentComplete DISABLED_DownloadTest_PercentComplete
3228 #else
3229 #define MAYBE_DownloadTest_PercentComplete DownloadTest_PercentComplete
3230 #endif
3231 IN_PROC_BROWSER_TEST_F(DownloadTest, MAYBE_DownloadTest_PercentComplete) {
3232 // Write a huge file.
3233 base::FilePath file_path(DestinationFile(
3234 browser(), base::FilePath(FILE_PATH_LITERAL("DownloadTest_BigZip.zip"))));
3235 base::File file(file_path, base::File::FLAG_CREATE | base::File::FLAG_WRITE);
3236 ASSERT_TRUE(file.IsValid());
3237 int64 size = 1 << 25;
3238 EXPECT_EQ(1, file.Write(size, "a", 1));
3239 file.Close();
3241 #if defined(OS_POSIX)
3242 // Make it readable by chronos on chromeos
3243 base::SetPosixFilePermissions(file_path, 0755);
3244 #endif
3246 // Ensure that we have enough disk space.
3247 int64 free_space = base::SysInfo::AmountOfFreeDiskSpace(
3248 GetDownloadDirectory(browser()));
3249 ASSERT_LE(size, free_space) << "Not enough disk space to download. Got "
3250 << free_space;
3251 GURL file_url(net::FilePathToFileURL(file_path));
3252 scoped_ptr<content::DownloadTestObserver> progress_waiter(
3253 CreateInProgressWaiter(browser(), 1));
3255 // Start downloading a file, wait for it to be created.
3256 ui_test_utils::NavigateToURLWithDisposition(
3257 browser(), file_url, CURRENT_TAB, ui_test_utils::BROWSER_TEST_NONE);
3258 progress_waiter->WaitForFinished();
3259 EXPECT_EQ(1u, progress_waiter->NumDownloadsSeenInState(
3260 DownloadItem::IN_PROGRESS));
3261 std::vector<DownloadItem*> download_items;
3262 GetDownloads(browser(), &download_items);
3263 ASSERT_EQ(1UL, download_items.size());
3265 // Wait for the download to complete, checking along the way that the
3266 // PercentComplete() never regresses.
3267 PercentWaiter waiter(download_items[0]);
3268 EXPECT_TRUE(waiter.WaitForFinished());
3269 EXPECT_EQ(DownloadItem::COMPLETE, download_items[0]->GetState());
3270 ASSERT_EQ(100, download_items[0]->PercentComplete());
3271 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
3273 // Check that the file downloaded correctly.
3274 ASSERT_TRUE(base::PathExists(download_items[0]->GetTargetFilePath()));
3275 int64 downloaded_size = 0;
3276 ASSERT_TRUE(base::GetFileSize(
3277 download_items[0]->GetTargetFilePath(), &downloaded_size));
3278 ASSERT_EQ(size + 1, downloaded_size);
3279 ASSERT_TRUE(base::DieFileDie(file_path, false));
3280 ASSERT_TRUE(base::DieFileDie(download_items[0]->GetTargetFilePath(), false));
3283 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadTest_DenyDanger) {
3284 GURL url = net::URLRequestMockHTTPJob::GetMockUrl(
3285 "downloads/dangerous/dangerous.crx");
3286 scoped_ptr<content::DownloadTestObserver> observer(
3287 DangerousDownloadWaiter(
3288 browser(), 1,
3289 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_DENY));
3290 ui_test_utils::NavigateToURL(browser(), url);
3291 observer->WaitForFinished();
3292 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::CANCELLED));
3293 EXPECT_EQ(1u, observer->NumDangerousDownloadsSeen());
3294 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
3297 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadPrefs_SaveFilePath) {
3298 DownloadPrefs* on_prefs = DownloadServiceFactory::GetForBrowserContext(
3299 browser()->profile())->GetDownloadManagerDelegate()->download_prefs();
3300 DownloadPrefs* off_prefs = DownloadServiceFactory::GetForBrowserContext(
3301 browser()->profile()->GetOffTheRecordProfile())
3302 ->GetDownloadManagerDelegate()->download_prefs();
3303 base::FilePath dir(on_prefs->SaveFilePath());
3304 EXPECT_EQ(dir.value(), off_prefs->SaveFilePath().value());
3306 on_prefs->SetSaveFilePath(dir.AppendASCII("on"));
3307 EXPECT_EQ(dir.AppendASCII("on").value(), on_prefs->SaveFilePath().value());
3308 EXPECT_EQ(dir.AppendASCII("on").value(), off_prefs->SaveFilePath().value());
3310 on_prefs->SetSaveFilePath(dir);
3311 EXPECT_EQ(dir.value(), on_prefs->SaveFilePath().value());
3312 EXPECT_EQ(dir.value(), off_prefs->SaveFilePath().value());
3314 off_prefs->SetSaveFilePath(dir.AppendASCII("off"));
3315 EXPECT_EQ(dir.value(), on_prefs->SaveFilePath().value());
3316 EXPECT_EQ(dir.AppendASCII("off").value(), off_prefs->SaveFilePath().value());
3318 on_prefs->SetSaveFilePath(dir.AppendASCII("on"));
3319 EXPECT_EQ(dir.AppendASCII("on").value(), on_prefs->SaveFilePath().value());
3320 EXPECT_EQ(dir.AppendASCII("off").value(), off_prefs->SaveFilePath().value());
3323 // A download that is interrupted due to a file error should be able to be
3324 // resumed.
3325 IN_PROC_BROWSER_TEST_F(DownloadTest, Resumption_NoPrompt) {
3326 base::CommandLine::ForCurrentProcess()->AppendSwitch(
3327 switches::kEnableDownloadResumption);
3328 scoped_refptr<content::TestFileErrorInjector> error_injector(
3329 content::TestFileErrorInjector::Create(
3330 DownloadManagerForBrowser(browser())));
3331 scoped_ptr<content::DownloadTestObserver> completion_observer(
3332 CreateWaiter(browser(), 1));
3333 EnableFileChooser(true);
3335 DownloadItem* download = StartMockDownloadAndInjectError(
3336 error_injector.get(), content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED);
3337 ASSERT_TRUE(download);
3339 download->Resume();
3340 completion_observer->WaitForFinished();
3342 EXPECT_EQ(
3343 1u, completion_observer->NumDownloadsSeenInState(DownloadItem::COMPLETE));
3344 EXPECT_FALSE(DidShowFileChooser());
3347 // A download that's interrupted due to a reason that indicates that the target
3348 // path is invalid or unusable should cause a prompt to be displayed on
3349 // resumption.
3350 IN_PROC_BROWSER_TEST_F(DownloadTest, Resumption_WithPrompt) {
3351 base::CommandLine::ForCurrentProcess()->AppendSwitch(
3352 switches::kEnableDownloadResumption);
3353 scoped_refptr<content::TestFileErrorInjector> error_injector(
3354 content::TestFileErrorInjector::Create(
3355 DownloadManagerForBrowser(browser())));
3356 scoped_ptr<content::DownloadTestObserver> completion_observer(
3357 CreateWaiter(browser(), 1));
3358 EnableFileChooser(true);
3360 DownloadItem* download = StartMockDownloadAndInjectError(
3361 error_injector.get(), content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE);
3362 ASSERT_TRUE(download);
3364 download->Resume();
3365 completion_observer->WaitForFinished();
3367 EXPECT_EQ(
3368 1u, completion_observer->NumDownloadsSeenInState(DownloadItem::COMPLETE));
3369 EXPECT_TRUE(DidShowFileChooser());
3372 // The user shouldn't be prompted on a resumed download unless a prompt is
3373 // necessary due to the interrupt reason.
3374 IN_PROC_BROWSER_TEST_F(DownloadTest, Resumption_WithPromptAlways) {
3375 base::CommandLine::ForCurrentProcess()->AppendSwitch(
3376 switches::kEnableDownloadResumption);
3377 browser()->profile()->GetPrefs()->SetBoolean(
3378 prefs::kPromptForDownload, true);
3379 scoped_refptr<content::TestFileErrorInjector> error_injector(
3380 content::TestFileErrorInjector::Create(
3381 DownloadManagerForBrowser(browser())));
3382 scoped_ptr<content::DownloadTestObserver> completion_observer(
3383 CreateWaiter(browser(), 1));
3384 EnableFileChooser(true);
3386 DownloadItem* download = StartMockDownloadAndInjectError(
3387 error_injector.get(), content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED);
3388 ASSERT_TRUE(download);
3390 // Prompts the user initially because of the kPromptForDownload preference.
3391 EXPECT_TRUE(DidShowFileChooser());
3393 download->Resume();
3394 completion_observer->WaitForFinished();
3396 EXPECT_EQ(
3397 1u, completion_observer->NumDownloadsSeenInState(DownloadItem::COMPLETE));
3398 // Shouldn't prompt for resumption.
3399 EXPECT_FALSE(DidShowFileChooser());
3402 // A download that is interrupted due to a transient error should be resumed
3403 // automatically.
3404 IN_PROC_BROWSER_TEST_F(DownloadTest, Resumption_Automatic) {
3405 base::CommandLine::ForCurrentProcess()->AppendSwitch(
3406 switches::kEnableDownloadResumption);
3407 scoped_refptr<content::TestFileErrorInjector> error_injector(
3408 content::TestFileErrorInjector::Create(
3409 DownloadManagerForBrowser(browser())));
3411 DownloadItem* download = StartMockDownloadAndInjectError(
3412 error_injector.get(),
3413 content::DOWNLOAD_INTERRUPT_REASON_FILE_TRANSIENT_ERROR);
3414 ASSERT_TRUE(download);
3416 // The number of times this the download is resumed automatically is defined
3417 // in DownloadItemImpl::kMaxAutoResumeAttempts. The number of DownloadFiles
3418 // created should be that number + 1 (for the original download request). We
3419 // only care that it is greater than 1.
3420 EXPECT_GT(1u, error_injector->TotalFileCount());
3423 // An interrupting download should be resumable multiple times.
3424 IN_PROC_BROWSER_TEST_F(DownloadTest, Resumption_MultipleAttempts) {
3425 base::CommandLine::ForCurrentProcess()->AppendSwitch(
3426 switches::kEnableDownloadResumption);
3427 scoped_refptr<content::TestFileErrorInjector> error_injector(
3428 content::TestFileErrorInjector::Create(
3429 DownloadManagerForBrowser(browser())));
3430 scoped_ptr<DownloadTestObserverNotInProgress> completion_observer(
3431 new DownloadTestObserverNotInProgress(
3432 DownloadManagerForBrowser(browser()), 1));
3433 // Wait for two transitions to a resumable state
3434 scoped_ptr<content::DownloadTestObserver> resumable_observer(
3435 new DownloadTestObserverResumable(
3436 DownloadManagerForBrowser(browser()), 2));
3438 EnableFileChooser(true);
3439 DownloadItem* download = StartMockDownloadAndInjectError(
3440 error_injector.get(), content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED);
3441 ASSERT_TRUE(download);
3443 content::TestFileErrorInjector::FileErrorInfo error_info;
3444 error_info.url = download->GetOriginalUrl().spec();
3445 error_info.code = content::TestFileErrorInjector::FILE_OPERATION_WRITE;
3446 error_info.operation_instance = 0;
3447 error_info.error = content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED;
3448 error_injector->AddError(error_info);
3449 error_injector->InjectErrors();
3451 // Resuming should cause the download to be interrupted again due to the
3452 // errors we are injecting.
3453 download->Resume();
3454 resumable_observer->WaitForFinished();
3455 ASSERT_EQ(DownloadItem::INTERRUPTED, download->GetState());
3456 ASSERT_EQ(content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED,
3457 download->GetLastReason());
3459 error_injector->ClearErrors();
3460 error_injector->InjectErrors();
3462 // No errors this time. The download should complete successfully.
3463 EXPECT_FALSE(completion_observer->IsFinished());
3464 completion_observer->StartObserving();
3465 download->Resume();
3466 completion_observer->WaitForFinished();
3467 EXPECT_EQ(DownloadItem::COMPLETE, download->GetState());
3469 EXPECT_FALSE(DidShowFileChooser());
3472 // The file empty.bin is served with a MIME type of application/octet-stream.
3473 // The content body is empty. Make sure this case is handled properly and we
3474 // don't regress on http://crbug.com/320394.
3475 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadTest_GZipWithNoContent) {
3476 GURL url = net::URLRequestMockHTTPJob::GetMockUrl("downloads/empty.bin");
3477 // Downloading the same URL twice causes the second request to be served from
3478 // cached (with a high probability). This test verifies that that doesn't
3479 // happen regardless of whether the request is served via the cache or from
3480 // the network.
3481 DownloadAndWait(browser(), url);
3482 DownloadAndWait(browser(), url);
3485 #if defined(FULL_SAFE_BROWSING)
3487 // The following two tests are only meaningful on OS_WIN since that's the only
3488 // platform where client download checks are currently performed.
3489 // TODO(asanka): Relax this restriction as other platforms are added.
3490 #if defined(OS_WIN)
3491 namespace {
3493 // This is a custom DownloadTestObserver for
3494 // DangerousFileWithSBDisabledBeforeCompletion test that disables the
3495 // SafeBrowsing service when a single download is IN_PROGRESS and has a target
3496 // path assigned. DownloadItemImpl is expected to call MaybeCompleteDownload
3497 // soon afterwards and we want to disable the service before then.
3498 class DisableSafeBrowsingOnInProgressDownload
3499 : public content::DownloadTestObserver {
3500 public:
3501 explicit DisableSafeBrowsingOnInProgressDownload(Browser* browser)
3502 : DownloadTestObserver(DownloadManagerForBrowser(browser),
3504 ON_DANGEROUS_DOWNLOAD_QUIT),
3505 browser_(browser),
3506 final_state_seen_(false) {
3507 Init();
3509 ~DisableSafeBrowsingOnInProgressDownload() override {}
3511 bool IsDownloadInFinalState(DownloadItem* download) override {
3512 if (download->GetState() != DownloadItem::IN_PROGRESS ||
3513 download->GetTargetFilePath().empty())
3514 return false;
3516 if (final_state_seen_)
3517 return true;
3519 final_state_seen_ = true;
3520 browser_->profile()->GetPrefs()->SetBoolean(prefs::kSafeBrowsingEnabled,
3521 false);
3522 EXPECT_EQ(content::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT,
3523 download->GetDangerType());
3524 EXPECT_FALSE(download->IsDangerous());
3525 EXPECT_TRUE(DownloadItemModel(download).IsDangerousFileBasedOnType());
3526 return true;
3529 private:
3530 Browser* browser_;
3531 bool final_state_seen_;
3534 } // namespace
3536 IN_PROC_BROWSER_TEST_F(DownloadTest,
3537 DangerousFileWithSBDisabledBeforeCompletion) {
3538 browser()->profile()->GetPrefs()->SetBoolean(prefs::kSafeBrowsingEnabled,
3539 true);
3540 GURL download_url = net::URLRequestMockHTTPJob::GetMockUrl(
3541 "downloads/dangerous/dangerous.exe");
3542 scoped_ptr<content::DownloadTestObserver> dangerous_observer(
3543 DangerousDownloadWaiter(
3544 browser(),
3546 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_QUIT));
3547 scoped_ptr<content::DownloadTestObserver> in_progress_observer(
3548 new DisableSafeBrowsingOnInProgressDownload(browser()));
3549 ui_test_utils::NavigateToURLWithDisposition(browser(),
3550 download_url,
3551 NEW_BACKGROUND_TAB,
3552 ui_test_utils::BROWSER_TEST_NONE);
3553 in_progress_observer->WaitForFinished();
3555 // SafeBrowsing should have been disabled by our observer.
3556 ASSERT_FALSE(browser()->profile()->GetPrefs()->GetBoolean(
3557 prefs::kSafeBrowsingEnabled));
3559 std::vector<DownloadItem*> downloads;
3560 DownloadManagerForBrowser(browser())->GetAllDownloads(&downloads);
3561 ASSERT_EQ(1u, downloads.size());
3562 DownloadItem* download = downloads[0];
3564 dangerous_observer->WaitForFinished();
3566 EXPECT_TRUE(download->IsDangerous());
3567 EXPECT_EQ(content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE,
3568 download->GetDangerType());
3569 download->Cancel(true);
3572 IN_PROC_BROWSER_TEST_F(DownloadTest, DangerousFileWithSBDisabledBeforeStart) {
3573 // Disable SafeBrowsing
3574 browser()->profile()->GetPrefs()->SetBoolean(prefs::kSafeBrowsingEnabled,
3575 false);
3577 GURL download_url = net::URLRequestMockHTTPJob::GetMockUrl(
3578 "downloads/dangerous/dangerous.exe");
3579 scoped_ptr<content::DownloadTestObserver> dangerous_observer(
3580 DangerousDownloadWaiter(
3581 browser(),
3583 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_QUIT));
3584 ui_test_utils::NavigateToURLWithDisposition(browser(),
3585 download_url,
3586 NEW_BACKGROUND_TAB,
3587 ui_test_utils::BROWSER_TEST_NONE);
3588 dangerous_observer->WaitForFinished();
3590 std::vector<DownloadItem*> downloads;
3591 DownloadManagerForBrowser(browser())->GetAllDownloads(&downloads);
3592 ASSERT_EQ(1u, downloads.size());
3594 DownloadItem* download = downloads[0];
3595 EXPECT_TRUE(download->IsDangerous());
3596 EXPECT_EQ(content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE,
3597 download->GetDangerType());
3599 download->Cancel(true);
3602 IN_PROC_BROWSER_TEST_F(DownloadTest, SafeSupportedFile) {
3603 GURL download_url =
3604 net::URLRequestMockHTTPJob::GetMockUrl("downloads/a_zip_file.zip");
3605 DownloadAndWait(browser(), download_url);
3607 std::vector<DownloadItem*> downloads;
3608 DownloadManagerForBrowser(browser())->GetAllDownloads(&downloads);
3609 ASSERT_EQ(1u, downloads.size());
3611 DownloadItem* download = downloads[0];
3612 EXPECT_FALSE(download->IsDangerous());
3613 EXPECT_EQ(content::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT,
3614 download->GetDangerType());
3616 download->Cancel(true);
3619 #endif // OS_WIN
3621 IN_PROC_BROWSER_TEST_F(DownloadTest, FeedbackService) {
3622 // Make a dangerous file.
3623 base::FilePath file(FILE_PATH_LITERAL("downloads/dangerous/dangerous.swf"));
3624 GURL download_url(net::URLRequestMockHTTPJob::GetMockUrl(file));
3625 scoped_ptr<content::DownloadTestObserverInterrupted> observer(
3626 new content::DownloadTestObserverInterrupted(
3627 DownloadManagerForBrowser(browser()), 1,
3628 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_QUIT));
3629 ui_test_utils::NavigateToURLWithDisposition(
3630 browser(),
3631 GURL(download_url),
3632 NEW_BACKGROUND_TAB,
3633 ui_test_utils::BROWSER_TEST_NONE);
3634 observer->WaitForFinished();
3636 // Get the download from the DownloadManager.
3637 std::vector<DownloadItem*> downloads;
3638 DownloadManagerForBrowser(browser())->GetAllDownloads(&downloads);
3639 ASSERT_EQ(1u, downloads.size());
3640 EXPECT_TRUE(downloads[0]->IsDangerous());
3642 // Save fake pings for the download.
3643 safe_browsing::ClientDownloadReport fake_metadata;
3644 fake_metadata.mutable_download_request()->set_url("http://test");
3645 fake_metadata.mutable_download_request()->set_length(1);
3646 fake_metadata.mutable_download_request()->mutable_digests()->set_sha1("hi");
3647 fake_metadata.mutable_download_response()->set_verdict(
3648 safe_browsing::ClientDownloadResponse::UNCOMMON);
3649 std::string ping_request(
3650 fake_metadata.download_request().SerializeAsString());
3651 std::string ping_response(
3652 fake_metadata.download_response().SerializeAsString());
3653 SafeBrowsingService* sb_service = g_browser_process->safe_browsing_service();
3654 safe_browsing::DownloadProtectionService* download_protection_service =
3655 sb_service->download_protection_service();
3656 download_protection_service->feedback_service()->MaybeStorePingsForDownload(
3657 safe_browsing::DownloadProtectionService::UNCOMMON,
3658 downloads[0],
3659 ping_request,
3660 ping_response);
3661 ASSERT_TRUE(safe_browsing::DownloadFeedbackService::IsEnabledForDownload(
3662 *(downloads[0])));
3664 // Begin feedback and check that the file is "stolen".
3665 download_protection_service->feedback_service()->BeginFeedbackForDownload(
3666 downloads[0]);
3667 std::vector<DownloadItem*> updated_downloads;
3668 GetDownloads(browser(), &updated_downloads);
3669 ASSERT_TRUE(updated_downloads.empty());
3671 #endif