Revert "Reland c91b178b07b0d - Delete dead signin code (SigninGlobalError)"
[chromium-blink-merge.git] / chrome / browser / download / download_browsertest.cc
blobd73dc34f2a7de2ff5d7913ff3582ab971d8d7801
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/download/notification/download_notification_manager.h"
41 #include "chrome/browser/extensions/extension_install_prompt.h"
42 #include "chrome/browser/extensions/extension_install_prompt_show_params.h"
43 #include "chrome/browser/extensions/extension_service.h"
44 #include "chrome/browser/history/history_service_factory.h"
45 #include "chrome/browser/infobars/infobar_service.h"
46 #include "chrome/browser/net/url_request_mock_util.h"
47 #include "chrome/browser/profiles/profile.h"
48 #include "chrome/browser/renderer_context_menu/render_view_context_menu_browsertest_util.h"
49 #include "chrome/browser/renderer_context_menu/render_view_context_menu_test_util.h"
50 #include "chrome/browser/ui/browser.h"
51 #include "chrome/browser/ui/browser_commands.h"
52 #include "chrome/browser/ui/browser_finder.h"
53 #include "chrome/browser/ui/browser_list.h"
54 #include "chrome/browser/ui/browser_tabstrip.h"
55 #include "chrome/browser/ui/browser_window.h"
56 #include "chrome/browser/ui/chrome_pages.h"
57 #include "chrome/browser/ui/host_desktop.h"
58 #include "chrome/browser/ui/tabs/tab_strip_model.h"
59 #include "chrome/browser/ui/website_settings/permission_bubble_manager.h"
60 #include "chrome/common/chrome_paths.h"
61 #include "chrome/common/chrome_switches.h"
62 #include "chrome/common/pref_names.h"
63 #include "chrome/common/safe_browsing/csd.pb.h"
64 #include "chrome/common/url_constants.h"
65 #include "chrome/grit/generated_resources.h"
66 #include "chrome/test/base/in_process_browser_test.h"
67 #include "chrome/test/base/test_switches.h"
68 #include "chrome/test/base/ui_test_utils.h"
69 #include "components/history/content/browser/download_constants_utils.h"
70 #include "components/history/core/browser/download_constants.h"
71 #include "components/history/core/browser/download_row.h"
72 #include "components/history/core/browser/history_service.h"
73 #include "components/infobars/core/confirm_infobar_delegate.h"
74 #include "components/infobars/core/infobar.h"
75 #include "content/public/browser/download_interrupt_reasons.h"
76 #include "content/public/browser/download_item.h"
77 #include "content/public/browser/download_manager.h"
78 #include "content/public/browser/download_save_info.h"
79 #include "content/public/browser/download_url_parameters.h"
80 #include "content/public/browser/notification_source.h"
81 #include "content/public/browser/render_frame_host.h"
82 #include "content/public/browser/render_view_host.h"
83 #include "content/public/browser/resource_context.h"
84 #include "content/public/browser/web_contents.h"
85 #include "content/public/common/content_switches.h"
86 #include "content/public/common/context_menu_params.h"
87 #include "content/public/test/browser_test_utils.h"
88 #include "content/public/test/download_test_observer.h"
89 #include "content/public/test/test_file_error_injector.h"
90 #include "content/public/test/test_navigation_observer.h"
91 #include "extensions/browser/extension_system.h"
92 #include "extensions/common/feature_switch.h"
93 #include "net/base/filename_util.h"
94 #include "net/test/embedded_test_server/embedded_test_server.h"
95 #include "net/test/embedded_test_server/http_request.h"
96 #include "net/test/embedded_test_server/http_response.h"
97 #include "net/test/url_request/url_request_mock_http_job.h"
98 #include "net/test/url_request/url_request_slow_download_job.h"
99 #include "testing/gtest/include/gtest/gtest.h"
100 #include "ui/base/l10n/l10n_util.h"
101 #include "ui/base/page_transition_types.h"
103 #if defined(FULL_SAFE_BROWSING)
104 #include "chrome/browser/safe_browsing/download_feedback_service.h"
105 #include "chrome/browser/safe_browsing/download_protection_service.h"
106 #include "chrome/browser/safe_browsing/safe_browsing_database.h"
107 #include "chrome/browser/safe_browsing/safe_browsing_service.h"
108 #endif
110 using content::BrowserContext;
111 using content::BrowserThread;
112 using content::DownloadItem;
113 using content::DownloadManager;
114 using content::DownloadUrlParameters;
115 using content::WebContents;
116 using extensions::Extension;
117 using extensions::FeatureSwitch;
118 using net::URLRequestMockHTTPJob;
120 namespace {
122 class CreatedObserver : public content::DownloadManager::Observer {
123 public:
124 explicit CreatedObserver(content::DownloadManager* manager)
125 : manager_(manager),
126 waiting_(false) {
127 manager->AddObserver(this);
129 ~CreatedObserver() override {
130 if (manager_)
131 manager_->RemoveObserver(this);
134 void Wait() {
135 std::vector<DownloadItem*> downloads;
136 manager_->GetAllDownloads(&downloads);
137 if (!downloads.empty())
138 return;
139 waiting_ = true;
140 content::RunMessageLoop();
141 waiting_ = false;
144 private:
145 void OnDownloadCreated(content::DownloadManager* manager,
146 content::DownloadItem* item) override {
147 DCHECK_EQ(manager_, manager);
148 if (waiting_)
149 base::MessageLoopForUI::current()->Quit();
152 content::DownloadManager* manager_;
153 bool waiting_;
155 DISALLOW_COPY_AND_ASSIGN(CreatedObserver);
158 class PercentWaiter : public content::DownloadItem::Observer {
159 public:
160 explicit PercentWaiter(DownloadItem* item)
161 : item_(item),
162 waiting_(false),
163 error_(false),
164 prev_percent_(0) {
165 item_->AddObserver(this);
167 ~PercentWaiter() override {
168 if (item_)
169 item_->RemoveObserver(this);
172 bool WaitForFinished() {
173 if (item_->GetState() == DownloadItem::COMPLETE) {
174 return item_->PercentComplete() == 100;
176 waiting_ = true;
177 content::RunMessageLoop();
178 waiting_ = false;
179 return !error_;
182 private:
183 void OnDownloadUpdated(content::DownloadItem* item) override {
184 DCHECK_EQ(item_, item);
185 if (!error_ &&
186 ((prev_percent_ > item_->PercentComplete()) ||
187 (item_->GetState() == DownloadItem::COMPLETE &&
188 (item_->PercentComplete() != 100)))) {
189 error_ = true;
190 if (waiting_)
191 base::MessageLoopForUI::current()->Quit();
193 if (item_->GetState() == DownloadItem::COMPLETE && waiting_)
194 base::MessageLoopForUI::current()->Quit();
197 void OnDownloadDestroyed(content::DownloadItem* item) override {
198 DCHECK_EQ(item_, item);
199 item_->RemoveObserver(this);
200 item_ = NULL;
203 content::DownloadItem* item_;
204 bool waiting_;
205 bool error_;
206 int prev_percent_;
208 DISALLOW_COPY_AND_ASSIGN(PercentWaiter);
211 // DownloadTestObserver subclass that observes one download until it transitions
212 // from a non-resumable state to a resumable state a specified number of
213 // times. Note that this observer can only observe a single download.
214 class DownloadTestObserverResumable : public content::DownloadTestObserver {
215 public:
216 // Construct a new observer. |transition_count| is the number of times the
217 // download should transition from a non-resumable state to a resumable state.
218 DownloadTestObserverResumable(DownloadManager* download_manager,
219 size_t transition_count)
220 : DownloadTestObserver(download_manager, 1,
221 ON_DANGEROUS_DOWNLOAD_FAIL),
222 was_previously_resumable_(false),
223 transitions_left_(transition_count) {
224 Init();
226 ~DownloadTestObserverResumable() override {}
228 private:
229 bool IsDownloadInFinalState(DownloadItem* download) override {
230 bool is_resumable_now = download->CanResume();
231 if (!was_previously_resumable_ && is_resumable_now)
232 --transitions_left_;
233 was_previously_resumable_ = is_resumable_now;
234 return transitions_left_ == 0;
237 bool was_previously_resumable_;
238 size_t transitions_left_;
240 DISALLOW_COPY_AND_ASSIGN(DownloadTestObserverResumable);
243 // IDs and paths of CRX files used in tests.
244 const char kGoodCrxId[] = "ldnnhddmnhbkjipkidpdiheffobcpfmf";
245 const base::FilePath kGoodCrxPath(FILE_PATH_LITERAL("extensions/good.crx"));
247 const char kLargeThemeCrxId[] = "pjpgmfcmabopnnfonnhmdjglfpjjfkbf";
248 const base::FilePath kLargeThemePath(
249 FILE_PATH_LITERAL("extensions/theme2.crx"));
251 // Get History Information.
252 class DownloadsHistoryDataCollector {
253 public:
254 explicit DownloadsHistoryDataCollector(Profile* profile)
255 : profile_(profile), result_valid_(false) {}
257 bool WaitForDownloadInfo(
258 scoped_ptr<std::vector<history::DownloadRow> >* results) {
259 history::HistoryService* hs = HistoryServiceFactory::GetForProfile(
260 profile_, ServiceAccessType::EXPLICIT_ACCESS);
261 DCHECK(hs);
262 hs->QueryDownloads(
263 base::Bind(&DownloadsHistoryDataCollector::OnQueryDownloadsComplete,
264 base::Unretained(this)));
266 content::RunMessageLoop();
267 if (result_valid_) {
268 *results = results_.Pass();
270 return result_valid_;
273 private:
274 void OnQueryDownloadsComplete(
275 scoped_ptr<std::vector<history::DownloadRow> > entries) {
276 result_valid_ = true;
277 results_ = entries.Pass();
278 base::MessageLoopForUI::current()->Quit();
281 Profile* profile_;
282 scoped_ptr<std::vector<history::DownloadRow> > results_;
283 bool result_valid_;
285 DISALLOW_COPY_AND_ASSIGN(DownloadsHistoryDataCollector);
288 // Mock that simulates a permissions dialog where the user denies
289 // permission to install. TODO(skerner): This could be shared with
290 // extensions tests. Find a common place for this class.
291 class MockAbortExtensionInstallPrompt : public ExtensionInstallPrompt {
292 public:
293 MockAbortExtensionInstallPrompt() :
294 ExtensionInstallPrompt(NULL) {
297 // Simulate a user abort on an extension installation.
298 void ConfirmInstall(Delegate* delegate,
299 const Extension* extension,
300 const ShowDialogCallback& show_dialog_callback) override {
301 delegate->InstallUIAbort(true);
302 base::MessageLoopForUI::current()->Quit();
305 void OnInstallSuccess(const Extension* extension, SkBitmap* icon) override {}
306 void OnInstallFailure(const extensions::CrxInstallError& error) override {}
309 // Mock that simulates a permissions dialog where the user allows
310 // installation.
311 class MockAutoConfirmExtensionInstallPrompt : public ExtensionInstallPrompt {
312 public:
313 explicit MockAutoConfirmExtensionInstallPrompt(
314 content::WebContents* web_contents)
315 : ExtensionInstallPrompt(web_contents) {}
317 // Proceed without confirmation prompt.
318 void ConfirmInstall(Delegate* delegate,
319 const Extension* extension,
320 const ShowDialogCallback& show_dialog_callback) override {
321 delegate->InstallUIProceed();
324 void OnInstallSuccess(const Extension* extension, SkBitmap* icon) override {}
325 void OnInstallFailure(const extensions::CrxInstallError& error) override {}
328 static DownloadManager* DownloadManagerForBrowser(Browser* browser) {
329 return BrowserContext::GetDownloadManager(browser->profile());
332 bool WasAutoOpened(DownloadItem* item) {
333 return item->GetAutoOpened();
336 // Called when a download starts. Marks the download as hidden.
337 void SetHiddenDownloadCallback(DownloadItem* item,
338 content::DownloadInterruptReason reason) {
339 DownloadItemModel(item).SetShouldShowInShelf(false);
342 // Callback for HistoryObserver; used in DownloadHistoryCheck
343 bool HasDataAndName(const history::DownloadRow& row) {
344 return row.received_bytes > 0 && !row.target_path.empty();
347 } // namespace
349 DownloadTestObserverNotInProgress::DownloadTestObserverNotInProgress(
350 DownloadManager* download_manager,
351 size_t count)
352 : DownloadTestObserver(download_manager, count, ON_DANGEROUS_DOWNLOAD_FAIL),
353 started_observing_(false) {
354 Init();
357 DownloadTestObserverNotInProgress::~DownloadTestObserverNotInProgress() {}
359 void DownloadTestObserverNotInProgress::StartObserving() {
360 started_observing_ = true;
363 bool DownloadTestObserverNotInProgress::IsDownloadInFinalState(
364 DownloadItem* download) {
365 return started_observing_ &&
366 download->GetState() != DownloadItem::IN_PROGRESS;
369 class HistoryObserver : public DownloadHistory::Observer {
370 public:
371 typedef base::Callback<bool(const history::DownloadRow&)> FilterCallback;
373 explicit HistoryObserver(Profile* profile)
374 : profile_(profile),
375 waiting_(false),
376 seen_stored_(false) {
377 DownloadServiceFactory::GetForBrowserContext(profile_)->
378 GetDownloadHistory()->AddObserver(this);
381 ~HistoryObserver() override {
382 DownloadService* service = DownloadServiceFactory::GetForBrowserContext(
383 profile_);
384 if (service && service->GetDownloadHistory())
385 service->GetDownloadHistory()->RemoveObserver(this);
388 void SetFilterCallback(const FilterCallback& callback) {
389 callback_ = callback;
392 void OnDownloadStored(content::DownloadItem* item,
393 const history::DownloadRow& info) override {
394 if (!callback_.is_null() && (!callback_.Run(info)))
395 return;
397 seen_stored_ = true;
398 if (waiting_)
399 base::MessageLoopForUI::current()->Quit();
402 void OnDownloadHistoryDestroyed() override {
403 DownloadServiceFactory::GetForBrowserContext(profile_)->
404 GetDownloadHistory()->RemoveObserver(this);
407 void WaitForStored() {
408 if (seen_stored_)
409 return;
410 waiting_ = true;
411 content::RunMessageLoop();
412 waiting_ = false;
415 private:
416 Profile* profile_;
417 bool waiting_;
418 bool seen_stored_;
419 FilterCallback callback_;
421 DISALLOW_COPY_AND_ASSIGN(HistoryObserver);
424 class DownloadTest : public InProcessBrowserTest {
425 public:
426 // Choice of navigation or direct fetch. Used by |DownloadFileCheckErrors()|.
427 enum DownloadMethod {
428 DOWNLOAD_NAVIGATE,
429 DOWNLOAD_DIRECT
432 // Information passed in to |DownloadFileCheckErrors()|.
433 struct DownloadInfo {
434 const char* url_name; // URL for the download.
435 DownloadMethod download_method; // Navigation or Direct.
436 // Download interrupt reason (NONE is OK).
437 content::DownloadInterruptReason reason;
438 bool show_download_item; // True if the download item appears on the shelf.
439 bool should_redirect_to_documents; // True if we save it in "My Documents".
442 struct FileErrorInjectInfo {
443 DownloadInfo download_info;
444 content::TestFileErrorInjector::FileErrorInfo error_info;
447 DownloadTest() {}
449 void SetUpOnMainThread() override {
450 BrowserThread::PostTask(
451 BrowserThread::IO, FROM_HERE,
452 base::Bind(&chrome_browser_net::SetUrlRequestMocksEnabled, true));
453 ASSERT_TRUE(InitialSetup());
456 void TearDownOnMainThread() override {
457 // Needs to be torn down on the main thread. file_activity_observer_ holds a
458 // reference to the ChromeDownloadManagerDelegate which should be destroyed
459 // on the UI thread.
460 file_activity_observer_.reset();
463 void SetUpCommandLine(base::CommandLine* command_line) override {
464 command_line->AppendSwitch(switches::kDisablePluginsDiscovery);
467 // Returning false indicates a failure of the setup, and should be asserted
468 // in the caller.
469 virtual bool InitialSetup() {
470 bool have_test_dir = PathService::Get(chrome::DIR_TEST_DATA, &test_dir_);
471 EXPECT_TRUE(have_test_dir);
472 if (!have_test_dir)
473 return false;
475 // Sanity check default values for window and tab count.
476 int window_count = chrome::GetTotalBrowserCount();
477 EXPECT_EQ(1, window_count);
478 EXPECT_EQ(1, browser()->tab_strip_model()->count());
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 bool VerifyNoDownloads() const {
604 DownloadManager::DownloadVector items;
605 GetDownloads(browser(), &items);
606 return items.empty();
609 // Download |url|, then wait for the download to finish.
610 // |disposition| indicates where the navigation occurs (current tab, new
611 // foreground tab, etc).
612 // |browser_test_flags| indicate what to wait for, and is an OR of 0 or more
613 // values in the ui_test_utils::BrowserTestWaitFlags enum.
614 void DownloadAndWaitWithDisposition(Browser* browser,
615 const GURL& url,
616 WindowOpenDisposition disposition,
617 int browser_test_flags) {
618 // Setup notification, navigate, and block.
619 scoped_ptr<content::DownloadTestObserver> observer(
620 CreateWaiter(browser, 1));
621 // This call will block until the condition specified by
622 // |browser_test_flags|, but will not wait for the download to finish.
623 ui_test_utils::NavigateToURLWithDisposition(browser,
624 url,
625 disposition,
626 browser_test_flags);
627 // Waits for the download to complete.
628 observer->WaitForFinished();
629 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::COMPLETE));
630 // We don't expect a file chooser to be shown.
631 EXPECT_FALSE(DidShowFileChooser());
634 // Download a file in the current tab, then wait for the download to finish.
635 void DownloadAndWait(Browser* browser,
636 const GURL& url) {
637 DownloadAndWaitWithDisposition(
638 browser,
639 url,
640 CURRENT_TAB,
641 ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
644 // Should only be called when the download is known to have finished
645 // (in error or not).
646 // Returning false indicates a failure of the function, and should be asserted
647 // in the caller.
648 bool CheckDownload(Browser* browser,
649 const base::FilePath& downloaded_filename,
650 const base::FilePath& origin_filename) {
651 // Find the path to which the data will be downloaded.
652 base::FilePath downloaded_file(
653 DestinationFile(browser, downloaded_filename));
655 // Find the origin path (from which the data comes).
656 base::FilePath origin_file(OriginFile(origin_filename));
657 return CheckDownloadFullPaths(browser, downloaded_file, origin_file);
660 // A version of CheckDownload that allows complete path specification.
661 bool CheckDownloadFullPaths(Browser* browser,
662 const base::FilePath& downloaded_file,
663 const base::FilePath& origin_file) {
664 bool origin_file_exists = base::PathExists(origin_file);
665 EXPECT_TRUE(origin_file_exists) << origin_file.value();
666 if (!origin_file_exists)
667 return false;
669 // Confirm the downloaded data file exists.
670 bool downloaded_file_exists = base::PathExists(downloaded_file);
671 EXPECT_TRUE(downloaded_file_exists) << downloaded_file.value();
672 if (!downloaded_file_exists)
673 return false;
675 int64 origin_file_size = 0;
676 EXPECT_TRUE(base::GetFileSize(origin_file, &origin_file_size));
677 std::string original_file_contents;
678 EXPECT_TRUE(base::ReadFileToString(origin_file, &original_file_contents));
679 EXPECT_TRUE(
680 VerifyFile(downloaded_file, original_file_contents, origin_file_size));
682 // Delete the downloaded copy of the file.
683 bool downloaded_file_deleted = base::DieFileDie(downloaded_file, false);
684 EXPECT_TRUE(downloaded_file_deleted);
685 return downloaded_file_deleted;
688 content::DownloadTestObserver* CreateInProgressDownloadObserver(
689 size_t download_count) {
690 DownloadManager* manager = DownloadManagerForBrowser(browser());
691 return new content::DownloadTestObserverInProgress(
692 manager, download_count);
695 DownloadItem* CreateSlowTestDownload() {
696 scoped_ptr<content::DownloadTestObserver> observer(
697 CreateInProgressDownloadObserver(1));
698 GURL slow_download_url(net::URLRequestSlowDownloadJob::kUnknownSizeUrl);
699 DownloadManager* manager = DownloadManagerForBrowser(browser());
701 EXPECT_EQ(0, manager->NonMaliciousInProgressCount());
702 EXPECT_EQ(0, manager->InProgressCount());
703 if (manager->InProgressCount() != 0)
704 return NULL;
706 ui_test_utils::NavigateToURL(browser(), slow_download_url);
708 observer->WaitForFinished();
709 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::IN_PROGRESS));
711 DownloadManager::DownloadVector items;
712 manager->GetAllDownloads(&items);
714 DownloadItem* new_item = NULL;
715 for (DownloadManager::DownloadVector::iterator iter = items.begin();
716 iter != items.end(); ++iter) {
717 if ((*iter)->GetState() == DownloadItem::IN_PROGRESS) {
718 // There should be only one IN_PROGRESS item.
719 EXPECT_EQ(NULL, new_item);
720 new_item = *iter;
723 return new_item;
726 bool RunSizeTest(Browser* browser,
727 SizeTestType type,
728 const std::string& partial_indication,
729 const std::string& total_indication) {
730 EXPECT_TRUE(type == SIZE_TEST_TYPE_UNKNOWN || type == SIZE_TEST_TYPE_KNOWN);
731 if (type != SIZE_TEST_TYPE_KNOWN && type != SIZE_TEST_TYPE_UNKNOWN)
732 return false;
733 GURL url(type == SIZE_TEST_TYPE_KNOWN ?
734 net::URLRequestSlowDownloadJob::kKnownSizeUrl :
735 net::URLRequestSlowDownloadJob::kUnknownSizeUrl);
737 // TODO(ahendrickson) -- |expected_title_in_progress| and
738 // |expected_title_finished| need to be checked.
739 base::FilePath filename;
740 net::FileURLToFilePath(url, &filename);
741 base::string16 expected_title_in_progress(
742 base::ASCIIToUTF16(partial_indication) + filename.LossyDisplayName());
743 base::string16 expected_title_finished(
744 base::ASCIIToUTF16(total_indication) + filename.LossyDisplayName());
746 // Download a partial web page in a background tab and wait.
747 // The mock system will not complete until it gets a special URL.
748 scoped_ptr<content::DownloadTestObserver> observer(
749 CreateWaiter(browser, 1));
750 ui_test_utils::NavigateToURL(browser, url);
752 // TODO(ahendrickson): check download status text before downloading.
753 // Need to:
754 // - Add a member function to the |DownloadShelf| interface class, that
755 // indicates how many members it has.
756 // - Add a member function to |DownloadShelf| to get the status text
757 // of a given member (for example, via the name in |DownloadItemView|'s
758 // GetAccessibleState() member function), by index.
759 // - Iterate over browser->window()->GetDownloadShelf()'s members
760 // to see if any match the status text we want. Start with the last one.
762 // Allow the request to finish. We do this by loading a second URL in a
763 // separate tab.
764 GURL finish_url(net::URLRequestSlowDownloadJob::kFinishDownloadUrl);
765 ui_test_utils::NavigateToURLWithDisposition(
766 browser,
767 finish_url,
768 NEW_FOREGROUND_TAB,
769 ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
770 observer->WaitForFinished();
771 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::COMPLETE));
772 CheckDownloadStatesForBrowser(browser, 1, DownloadItem::COMPLETE);
774 EXPECT_EQ(2, browser->tab_strip_model()->count());
776 // TODO(ahendrickson): check download status text after downloading.
778 base::FilePath basefilename(filename.BaseName());
779 net::FileURLToFilePath(url, &filename);
780 base::FilePath download_path =
781 downloads_directory_.path().Append(basefilename);
783 bool downloaded_path_exists = base::PathExists(download_path);
784 EXPECT_TRUE(downloaded_path_exists);
785 if (!downloaded_path_exists)
786 return false;
788 // Check the file contents.
789 size_t file_size = net::URLRequestSlowDownloadJob::kFirstDownloadSize +
790 net::URLRequestSlowDownloadJob::kSecondDownloadSize;
791 std::string expected_contents(file_size, '*');
792 EXPECT_TRUE(VerifyFile(download_path, expected_contents, file_size));
794 // Delete the file we just downloaded.
795 EXPECT_TRUE(base::DieFileDie(download_path, true));
796 EXPECT_FALSE(base::PathExists(download_path));
798 return true;
801 void GetDownloads(Browser* browser,
802 std::vector<DownloadItem*>* downloads) const {
803 DCHECK(downloads);
804 DownloadManager* manager = DownloadManagerForBrowser(browser);
805 manager->GetAllDownloads(downloads);
808 static void ExpectWindowCountAfterDownload(size_t expected) {
809 EXPECT_EQ(expected, chrome::GetTotalBrowserCount());
812 void EnableFileChooser(bool enable) {
813 file_activity_observer_->EnableFileChooser(enable);
816 bool DidShowFileChooser() {
817 return file_activity_observer_->TestAndResetDidShowFileChooser();
820 // Checks that |path| is has |file_size| bytes, and matches the |value|
821 // string.
822 bool VerifyFile(const base::FilePath& path,
823 const std::string& value,
824 const int64 file_size) {
825 std::string file_contents;
827 bool read = base::ReadFileToString(path, &file_contents);
828 EXPECT_TRUE(read) << "Failed reading file: " << path.value() << std::endl;
829 if (!read)
830 return false; // Couldn't read the file.
832 // Note: we don't handle really large files (more than size_t can hold)
833 // so we will fail in that case.
834 size_t expected_size = static_cast<size_t>(file_size);
836 // Check the size.
837 EXPECT_EQ(expected_size, file_contents.size());
838 if (expected_size != file_contents.size())
839 return false;
841 // Check the contents.
842 EXPECT_EQ(value, file_contents);
843 if (memcmp(file_contents.c_str(), value.c_str(), expected_size) != 0)
844 return false;
846 return true;
849 // Attempts to download a file, based on information in |download_info|.
850 // If a Select File dialog opens, will automatically choose the default.
851 void DownloadFilesCheckErrorsSetup() {
852 embedded_test_server()->ServeFilesFromDirectory(GetTestDataDirectory());
853 ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
854 std::vector<DownloadItem*> download_items;
855 GetDownloads(browser(), &download_items);
856 ASSERT_TRUE(download_items.empty());
858 EnableFileChooser(true);
861 void DownloadFilesCheckErrorsLoopBody(const DownloadInfo& download_info,
862 size_t i) {
863 SCOPED_TRACE(
864 ::testing::Message()
865 << " " << __FUNCTION__ << "()"
866 << " index = " << i << " url = '" << download_info.url_name << "'"
867 << " method = " << ((download_info.download_method == DOWNLOAD_DIRECT)
868 ? "DOWNLOAD_DIRECT"
869 : "DOWNLOAD_NAVIGATE")
870 << " show_item = " << download_info.show_download_item << " reason = "
871 << DownloadInterruptReasonToString(download_info.reason));
873 std::vector<DownloadItem*> download_items;
874 GetDownloads(browser(), &download_items);
875 size_t downloads_expected = download_items.size();
877 std::string server_path = "/downloads/";
878 server_path += download_info.url_name;
879 GURL url = embedded_test_server()->GetURL(server_path);
880 ASSERT_TRUE(url.is_valid());
882 DownloadManager* download_manager = DownloadManagerForBrowser(browser());
883 WebContents* web_contents =
884 browser()->tab_strip_model()->GetActiveWebContents();
885 ASSERT_TRUE(web_contents);
887 scoped_ptr<content::DownloadTestObserver> observer(
888 new content::DownloadTestObserverTerminal(
889 download_manager,
891 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL));
893 if (download_info.download_method == DOWNLOAD_DIRECT) {
894 // Go directly to download. Don't wait for navigation.
895 scoped_refptr<content::DownloadTestItemCreationObserver>
896 creation_observer(new content::DownloadTestItemCreationObserver);
898 scoped_ptr<DownloadUrlParameters> params(
899 DownloadUrlParameters::FromWebContents(web_contents, url));
900 params->set_callback(creation_observer->callback());
901 DownloadManagerForBrowser(browser())->DownloadUrl(params.Pass());
903 // Wait until the item is created, or we have determined that it
904 // won't be.
905 creation_observer->WaitForDownloadItemCreation();
907 ASSERT_EQ(download_info.show_download_item,
908 creation_observer->succeeded());
909 if (download_info.show_download_item) {
910 EXPECT_EQ(content::DOWNLOAD_INTERRUPT_REASON_NONE,
911 creation_observer->interrupt_reason());
912 EXPECT_NE(content::DownloadItem::kInvalidId,
913 creation_observer->download_id());
914 } else {
915 EXPECT_NE(content::DOWNLOAD_INTERRUPT_REASON_NONE,
916 creation_observer->interrupt_reason());
917 EXPECT_EQ(content::DownloadItem::kInvalidId,
918 creation_observer->download_id());
920 } else {
921 // Navigate to URL normally, wait until done.
922 ui_test_utils::NavigateToURL(browser(), url);
925 if (download_info.show_download_item) {
926 downloads_expected++;
927 observer->WaitForFinished();
928 DownloadItem::DownloadState final_state =
929 (download_info.reason == content::DOWNLOAD_INTERRUPT_REASON_NONE) ?
930 DownloadItem::COMPLETE :
931 DownloadItem::INTERRUPTED;
932 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(final_state));
935 // Wait till the |DownloadFile|s are destroyed.
936 content::RunAllPendingInMessageLoop(content::BrowserThread::FILE);
937 content::RunAllPendingInMessageLoop(content::BrowserThread::UI);
939 // Validate that the correct files were downloaded.
940 download_items.clear();
941 GetDownloads(browser(), &download_items);
942 ASSERT_EQ(downloads_expected, download_items.size());
944 if (download_info.show_download_item) {
945 // Find the last download item.
946 DownloadItem* item = download_items[0];
947 for (size_t d = 1; d < downloads_expected; ++d) {
948 if (download_items[d]->GetStartTime() > item->GetStartTime())
949 item = download_items[d];
952 ASSERT_EQ(url, item->GetOriginalUrl());
953 ASSERT_EQ(download_info.reason, item->GetLastReason());
955 if (item->GetState() == content::DownloadItem::COMPLETE) {
956 // Clean up the file, in case it ended up in the My Documents folder.
957 base::FilePath destination_folder = GetDownloadDirectory(browser());
958 base::FilePath my_downloaded_file = item->GetTargetFilePath();
959 EXPECT_TRUE(base::PathExists(my_downloaded_file));
960 EXPECT_TRUE(base::DeleteFile(my_downloaded_file, false));
962 EXPECT_EQ(download_info.should_redirect_to_documents ?
963 std::string::npos :
965 my_downloaded_file.value().find(destination_folder.value()));
966 if (download_info.should_redirect_to_documents) {
967 // If it's not where we asked it to be, it should be in the
968 // My Documents folder.
969 base::FilePath my_docs_folder;
970 EXPECT_TRUE(PathService::Get(chrome::DIR_USER_DOCUMENTS,
971 &my_docs_folder));
972 EXPECT_EQ(0u,
973 my_downloaded_file.value().find(my_docs_folder.value()));
979 // Attempts to download a set of files, based on information in the
980 // |download_info| array. |count| is the number of files.
981 // If a Select File dialog appears, it will choose the default and return
982 // immediately.
983 void DownloadFilesCheckErrors(size_t count, DownloadInfo* download_info) {
984 DownloadFilesCheckErrorsSetup();
986 for (size_t i = 0; i < count; ++i) {
987 DownloadFilesCheckErrorsLoopBody(download_info[i], i);
991 void DownloadInsertFilesErrorCheckErrorsLoopBody(
992 scoped_refptr<content::TestFileErrorInjector> injector,
993 const FileErrorInjectInfo& info,
994 size_t i) {
995 std::stringstream s;
996 s << " " << __FUNCTION__ << "()"
997 << " index = " << i
998 << " url = " << info.error_info.url
999 << " operation code = "
1000 << content::TestFileErrorInjector::DebugString(info.error_info.code)
1001 << " instance = " << info.error_info.operation_instance
1002 << " error = "
1003 << content::DownloadInterruptReasonToString(info.error_info.error);
1005 injector->ClearErrors();
1006 injector->AddError(info.error_info);
1008 injector->InjectErrors();
1010 DownloadFilesCheckErrorsLoopBody(info.download_info, i);
1012 size_t expected_successes = info.download_info.show_download_item ? 1u : 0u;
1013 EXPECT_EQ(expected_successes, injector->TotalFileCount()) << s.str();
1014 EXPECT_EQ(0u, injector->CurrentFileCount()) << s.str();
1016 if (info.download_info.show_download_item)
1017 EXPECT_TRUE(injector->HadFile(GURL(info.error_info.url))) << s.str();
1020 void DownloadInsertFilesErrorCheckErrors(size_t count,
1021 FileErrorInjectInfo* info) {
1022 DownloadFilesCheckErrorsSetup();
1024 // Set up file failures.
1025 scoped_refptr<content::TestFileErrorInjector> injector(
1026 content::TestFileErrorInjector::Create(
1027 DownloadManagerForBrowser(browser())));
1029 for (size_t i = 0; i < count; ++i) {
1030 // Set up the full URL, for download file tracking.
1031 std::string server_path = "/downloads/";
1032 server_path += info[i].download_info.url_name;
1033 GURL url = embedded_test_server()->GetURL(server_path);
1034 info[i].error_info.url = url.spec();
1036 DownloadInsertFilesErrorCheckErrorsLoopBody(injector, info[i], i);
1040 // Attempts to download a file to a read-only folder, based on information
1041 // in |download_info|.
1042 void DownloadFilesToReadonlyFolder(size_t count,
1043 DownloadInfo* download_info) {
1044 DownloadFilesCheckErrorsSetup();
1046 // Make the test folder unwritable.
1047 base::FilePath destination_folder = GetDownloadDirectory(browser());
1048 DVLOG(1) << " " << __FUNCTION__ << "()"
1049 << " folder = '" << destination_folder.value() << "'";
1050 base::FilePermissionRestorer permission_restorer(destination_folder);
1051 EXPECT_TRUE(base::MakeFileUnwritable(destination_folder));
1053 for (size_t i = 0; i < count; ++i) {
1054 DownloadFilesCheckErrorsLoopBody(download_info[i], i);
1058 // A mock install prompt that simulates the user allowing an install request.
1059 void SetAllowMockInstallPrompt() {
1060 download_crx_util::SetMockInstallPromptForTesting(
1061 scoped_ptr<ExtensionInstallPrompt>(
1062 new MockAutoConfirmExtensionInstallPrompt(
1063 browser()->tab_strip_model()->GetActiveWebContents())));
1066 // This method:
1067 // * Starts a mock download by navigating browser() to a URLRequestMockHTTPJob
1068 // mock URL.
1069 // * Injects |error| on the first write using |error_injector|.
1070 // * Waits for the download to be interrupted.
1071 // * Clears the errors on |error_injector|.
1072 // * Returns the resulting interrupted download.
1073 DownloadItem* StartMockDownloadAndInjectError(
1074 content::TestFileErrorInjector* error_injector,
1075 content::DownloadInterruptReason error) {
1076 base::FilePath file_path(FILE_PATH_LITERAL("download-test1.lib"));
1077 GURL url = URLRequestMockHTTPJob::GetMockUrl(file_path);
1079 content::TestFileErrorInjector::FileErrorInfo error_info;
1080 error_info.url = url.spec();
1081 error_info.code = content::TestFileErrorInjector::FILE_OPERATION_WRITE;
1082 error_info.operation_instance = 0;
1083 error_info.error = error;
1084 error_injector->ClearErrors();
1085 error_injector->AddError(error_info);
1086 error_injector->InjectErrors();
1088 scoped_ptr<content::DownloadTestObserver> observer(
1089 new DownloadTestObserverResumable(
1090 DownloadManagerForBrowser(browser()), 1));
1091 ui_test_utils::NavigateToURL(browser(), url);
1092 observer->WaitForFinished();
1094 content::DownloadManager::DownloadVector downloads;
1095 DownloadManagerForBrowser(browser())->GetAllDownloads(&downloads);
1096 EXPECT_EQ(1u, downloads.size());
1098 if (downloads.size() != 1)
1099 return NULL;
1101 error_injector->ClearErrors();
1102 error_injector->InjectErrors();
1103 DownloadItem* download = downloads[0];
1104 EXPECT_EQ(DownloadItem::INTERRUPTED, download->GetState());
1105 EXPECT_EQ(error, download->GetLastReason());
1106 return download;
1109 private:
1110 static void EnsureNoPendingDownloadJobsOnIO(bool* result) {
1111 if (net::URLRequestSlowDownloadJob::NumberOutstandingRequests())
1112 *result = false;
1113 BrowserThread::PostTask(
1114 BrowserThread::UI, FROM_HERE, base::MessageLoop::QuitClosure());
1117 // Location of the test data.
1118 base::FilePath test_dir_;
1120 // Location of the downloads directory for these tests
1121 base::ScopedTempDir downloads_directory_;
1123 scoped_ptr<DownloadTestFileActivityObserver> file_activity_observer_;
1126 // NOTES:
1128 // Files for these tests are found in DIR_TEST_DATA (currently
1129 // "chrome\test\data\", see chrome_paths.cc).
1130 // Mock responses have extension .mock-http-headers appended to the file name.
1132 // Download a file due to the associated MIME type.
1133 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadMimeType) {
1134 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
1135 GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
1137 // Download the file and wait. We do not expect the Select File dialog.
1138 DownloadAndWait(browser(), url);
1140 // Check state.
1141 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1142 CheckDownload(browser(), file, file);
1145 #if defined(OS_WIN)
1146 // Download a file and confirm that the zone identifier (on windows)
1147 // is set to internet.
1148 IN_PROC_BROWSER_TEST_F(DownloadTest, CheckInternetZone) {
1149 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
1150 GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
1152 // Download the file and wait. We do not expect the Select File dialog.
1153 DownloadAndWait(browser(), url);
1155 // Check state. Special file state must be checked before CheckDownload,
1156 // as CheckDownload will delete the output file.
1157 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1158 base::FilePath downloaded_file(DestinationFile(browser(), file));
1159 if (base::VolumeSupportsADS(downloaded_file))
1160 EXPECT_TRUE(base::HasInternetZoneIdentifier(downloaded_file));
1161 CheckDownload(browser(), file, file);
1163 #endif
1165 // Put up a Select File dialog when the file is downloaded, due to
1166 // downloads preferences settings.
1167 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadMimeTypeSelect) {
1168 // Re-enable prompting.
1169 browser()->profile()->GetPrefs()->SetBoolean(
1170 prefs::kPromptForDownload, true);
1171 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
1172 GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
1174 EnableFileChooser(true);
1176 // Download the file and wait. We expect the Select File dialog to appear
1177 // due to the MIME type, but we still wait until the download completes.
1178 scoped_ptr<content::DownloadTestObserver> observer(
1179 new content::DownloadTestObserverTerminal(
1180 DownloadManagerForBrowser(browser()),
1182 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL));
1183 ui_test_utils::NavigateToURL(browser(), url);
1184 observer->WaitForFinished();
1185 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::COMPLETE));
1186 CheckDownloadStates(1, DownloadItem::COMPLETE);
1187 EXPECT_TRUE(DidShowFileChooser());
1189 // Check state.
1190 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1191 CheckDownload(browser(), file, file);
1194 // Access a file with a viewable mime-type, verify that a download
1195 // did not initiate.
1196 IN_PROC_BROWSER_TEST_F(DownloadTest, NoDownload) {
1197 base::FilePath file(FILE_PATH_LITERAL("download-test2.html"));
1198 GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
1199 base::FilePath file_path(DestinationFile(browser(), file));
1201 // Open a web page and wait.
1202 ui_test_utils::NavigateToURL(browser(), url);
1204 // Check that we did not download the web page.
1205 EXPECT_FALSE(base::PathExists(file_path));
1207 // Check state.
1208 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1209 EXPECT_TRUE(VerifyNoDownloads());
1212 // EmbeddedTestServer::HandleRequestCallback function that returns the relative
1213 // URL as the MIME type.
1214 // E.g.:
1215 // C -> S: GET /foo/bar =>
1216 // S -> C: HTTP/1.1 200 OK
1217 // Content-Type: foo/bar
1218 // ...
1219 static scoped_ptr<net::test_server::HttpResponse> RespondWithContentTypeHandler(
1220 const net::test_server::HttpRequest& request) {
1221 scoped_ptr<net::test_server::BasicHttpResponse> response(
1222 new net::test_server::BasicHttpResponse());
1223 response->set_content_type(request.relative_url.substr(1));
1224 response->set_code(net::HTTP_OK);
1225 response->set_content("ooogaboogaboogabooga");
1226 return response.Pass();
1229 IN_PROC_BROWSER_TEST_F(DownloadTest, MimeTypesToShowNotDownload) {
1230 embedded_test_server()->RegisterRequestHandler(
1231 base::Bind(&RespondWithContentTypeHandler));
1232 ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
1234 // These files should all be displayed in the browser.
1235 const char* mime_types[] = {
1236 // It is unclear whether to display text/css or download it.
1237 // Firefox 3: Display
1238 // Internet Explorer 7: Download
1239 // Safari 3.2: Download
1240 // We choose to match Firefox due to the lot of complains
1241 // from the users if css files are downloaded:
1242 // http://code.google.com/p/chromium/issues/detail?id=7192
1243 "text/css",
1244 "text/javascript",
1245 "text/plain",
1246 "application/x-javascript",
1247 "text/html",
1248 "text/xml",
1249 "text/xsl",
1250 "application/xhtml+xml",
1251 "image/png",
1252 "image/gif",
1253 "image/jpeg",
1254 "image/bmp",
1256 for (size_t i = 0; i < arraysize(mime_types); ++i) {
1257 const char* mime_type = mime_types[i];
1258 GURL url(
1259 embedded_test_server()->GetURL(std::string("/").append(mime_type)));
1260 ui_test_utils::NavigateToURL(browser(), url);
1262 // Check state.
1263 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1264 EXPECT_TRUE(VerifyNoDownloads());
1268 // Verify that when the DownloadResourceThrottle cancels a download, the
1269 // download never makes it to the downloads system.
1270 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadResourceThrottleCancels) {
1271 // Navigate to a page with the same domain as the file to download. We can't
1272 // navigate directly to the file we don't want to download because cross-site
1273 // navigations reset the TabDownloadState.
1274 base::FilePath same_site_path(FILE_PATH_LITERAL("download_script.html"));
1275 GURL same_site_url(URLRequestMockHTTPJob::GetMockUrl(same_site_path));
1276 ui_test_utils::NavigateToURL(browser(), same_site_url);
1278 // Make sure the initial navigation didn't trigger a download.
1279 EXPECT_TRUE(VerifyNoDownloads());
1281 // Disable downloads for the tab.
1282 WebContents* web_contents =
1283 browser()->tab_strip_model()->GetActiveWebContents();
1284 DownloadRequestLimiter::TabDownloadState* tab_download_state =
1285 g_browser_process->download_request_limiter()->GetDownloadState(
1286 web_contents, web_contents, true);
1287 ASSERT_TRUE(tab_download_state);
1288 tab_download_state->set_download_status(
1289 DownloadRequestLimiter::DOWNLOADS_NOT_ALLOWED);
1291 // Try to start the download via Javascript and wait for the corresponding
1292 // load stop event.
1293 content::TestNavigationObserver observer(web_contents);
1294 bool download_assempted;
1295 ASSERT_TRUE(content::ExecuteScriptAndExtractBool(
1296 browser()->tab_strip_model()->GetActiveWebContents(),
1297 "window.domAutomationController.send(startDownload());",
1298 &download_assempted));
1299 ASSERT_TRUE(download_assempted);
1300 observer.Wait();
1302 // Check that we did not download the file.
1303 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
1304 base::FilePath file_path(DestinationFile(browser(), file));
1305 EXPECT_FALSE(base::PathExists(file_path));
1307 // Check state.
1308 EXPECT_EQ(1, browser()->tab_strip_model()->count());
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 EXPECT_TRUE(VerifyNoDownloads());
1316 // Download a 0-size file with a content-disposition header, verify that the
1317 // download tab opened and the file exists as the filename specified in the
1318 // header. This also ensures we properly handle empty file downloads.
1319 IN_PROC_BROWSER_TEST_F(DownloadTest, ContentDisposition) {
1320 base::FilePath file(FILE_PATH_LITERAL("download-test3.gif"));
1321 GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
1322 base::FilePath download_file(
1323 FILE_PATH_LITERAL("download-test3-attachment.gif"));
1325 // Download a file and wait.
1326 DownloadAndWait(browser(), url);
1328 CheckDownload(browser(), download_file, file);
1330 // Check state.
1331 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1334 // UnknownSize and KnownSize are tests which depend on
1335 // URLRequestSlowDownloadJob to serve content in a certain way. Data will be
1336 // sent in two chunks where the first chunk is 35K and the second chunk is 10K.
1337 // The test will first attempt to download a file; but the server will "pause"
1338 // in the middle until the server receives a second request for
1339 // "download-finish". At that time, the download will finish.
1340 // These tests don't currently test much due to holes in |RunSizeTest()|. See
1341 // comments in that routine for details.
1342 IN_PROC_BROWSER_TEST_F(DownloadTest, UnknownSize) {
1343 ASSERT_TRUE(RunSizeTest(browser(), SIZE_TEST_TYPE_UNKNOWN,
1344 "32.0 KB - ", "100% - "));
1347 IN_PROC_BROWSER_TEST_F(DownloadTest, KnownSize) {
1348 ASSERT_TRUE(RunSizeTest(browser(), SIZE_TEST_TYPE_KNOWN,
1349 "71% - ", "100% - "));
1352 // Test that when downloading an item in Incognito mode, we don't crash when
1353 // closing the last Incognito window (http://crbug.com/13983).
1354 IN_PROC_BROWSER_TEST_F(DownloadTest, IncognitoDownload) {
1355 Browser* incognito = CreateIncognitoBrowser();
1356 ASSERT_TRUE(incognito);
1357 int window_count = chrome::GetTotalBrowserCount();
1358 EXPECT_EQ(2, window_count);
1360 // Download a file in the Incognito window and wait.
1361 CreateAndSetDownloadsDirectory(incognito);
1362 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
1363 GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
1364 // Since |incognito| is a separate browser, we have to set it up explicitly.
1365 incognito->profile()->GetPrefs()->SetBoolean(prefs::kPromptForDownload,
1366 false);
1367 DownloadAndWait(incognito, url);
1369 // We should still have 2 windows.
1370 ExpectWindowCountAfterDownload(2);
1372 #if !defined(OS_MACOSX)
1373 // On Mac OS X, the UI window close is delayed until the outermost
1374 // message loop runs. So it isn't possible to get a BROWSER_CLOSED
1375 // notification inside of a test.
1376 content::WindowedNotificationObserver signal(
1377 chrome::NOTIFICATION_BROWSER_CLOSED,
1378 content::Source<Browser>(incognito));
1379 #endif
1381 // Close the Incognito window and don't crash.
1382 chrome::CloseWindow(incognito);
1384 #if !defined(OS_MACOSX)
1385 signal.Wait();
1386 ExpectWindowCountAfterDownload(1);
1387 #endif
1389 CheckDownload(browser(), file, file);
1392 // Download one file on-record, then download the same file off-record, and test
1393 // that the filename is deduplicated. The previous test tests for a specific
1394 // bug; this next test tests that filename deduplication happens independently
1395 // of DownloadManager/CDMD.
1396 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadTest_IncognitoRegular) {
1397 GURL url = net::URLRequestMockHTTPJob::GetMockUrl("downloads/a_zip_file.zip");
1399 // Read the origin file now so that we can compare the downloaded files to it
1400 // later.
1401 base::FilePath origin(OriginFile(base::FilePath(FILE_PATH_LITERAL(
1402 "downloads/a_zip_file.zip"))));
1403 ASSERT_TRUE(base::PathExists(origin));
1404 int64 origin_file_size = 0;
1405 EXPECT_TRUE(base::GetFileSize(origin, &origin_file_size));
1406 std::string original_contents;
1407 EXPECT_TRUE(base::ReadFileToString(origin, &original_contents));
1409 std::vector<DownloadItem*> download_items;
1410 GetDownloads(browser(), &download_items);
1411 ASSERT_TRUE(download_items.empty());
1413 // Download a file in the on-record browser and check that it was downloaded
1414 // correctly.
1415 DownloadAndWaitWithDisposition(browser(),
1416 url,
1417 CURRENT_TAB,
1418 ui_test_utils::BROWSER_TEST_NONE);
1419 GetDownloads(browser(), &download_items);
1420 ASSERT_EQ(1UL, download_items.size());
1421 ASSERT_EQ(base::FilePath(FILE_PATH_LITERAL("a_zip_file.zip")),
1422 download_items[0]->GetTargetFilePath().BaseName());
1423 ASSERT_TRUE(base::PathExists(download_items[0]->GetTargetFilePath()));
1424 EXPECT_TRUE(VerifyFile(download_items[0]->GetTargetFilePath(),
1425 original_contents, origin_file_size));
1427 // Setup an incognito window.
1428 Browser* incognito = CreateIncognitoBrowser();
1429 ASSERT_TRUE(incognito);
1430 int window_count = BrowserList::GetInstance(
1431 browser()->host_desktop_type())->size();
1432 EXPECT_EQ(2, window_count);
1433 incognito->profile()->GetPrefs()->SetFilePath(
1434 prefs::kDownloadDefaultDirectory,
1435 GetDownloadsDirectory());
1436 incognito->profile()->GetPrefs()->SetFilePath(
1437 prefs::kSaveFileDefaultDirectory,
1438 GetDownloadsDirectory());
1440 download_items.clear();
1441 GetDownloads(incognito, &download_items);
1442 ASSERT_TRUE(download_items.empty());
1444 // Download a file in the incognito browser and check that it was downloaded
1445 // correctly.
1446 DownloadAndWaitWithDisposition(incognito,
1447 url,
1448 CURRENT_TAB,
1449 ui_test_utils::BROWSER_TEST_NONE);
1450 GetDownloads(incognito, &download_items);
1451 ASSERT_EQ(1UL, download_items.size());
1452 ASSERT_EQ(base::FilePath(FILE_PATH_LITERAL("a_zip_file (1).zip")),
1453 download_items[0]->GetTargetFilePath().BaseName());
1454 ASSERT_TRUE(base::PathExists(download_items[0]->GetTargetFilePath()));
1455 EXPECT_TRUE(VerifyFile(download_items[0]->GetTargetFilePath(),
1456 original_contents, origin_file_size));
1459 // Navigate to a new background page, but don't download.
1460 IN_PROC_BROWSER_TEST_F(DownloadTest, DontCloseNewTab1) {
1461 // Because it's an HTML link, it should open a web page rather than
1462 // downloading.
1463 base::FilePath file1(FILE_PATH_LITERAL("download-test2.html"));
1464 GURL url(URLRequestMockHTTPJob::GetMockUrl(file1));
1466 // Open a web page and wait.
1467 ui_test_utils::NavigateToURLWithDisposition(
1468 browser(),
1469 url,
1470 NEW_BACKGROUND_TAB,
1471 ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
1473 // We should have two tabs now.
1474 EXPECT_EQ(2, browser()->tab_strip_model()->count());
1475 EXPECT_TRUE(VerifyNoDownloads());
1478 // Download a file in a background tab. Verify that the tab is closed
1479 // automatically.
1480 IN_PROC_BROWSER_TEST_F(DownloadTest, CloseNewTab1) {
1481 // Download a file in a new background tab and wait. The tab is automatically
1482 // closed when the download begins.
1483 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
1484 GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
1485 DownloadAndWaitWithDisposition(
1486 browser(),
1487 url,
1488 NEW_BACKGROUND_TAB,
1491 // When the download finishes, we should still have one tab.
1492 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1494 CheckDownload(browser(), file, file);
1497 // Open a web page in the current tab, then download a file in another tab via
1498 // a Javascript call.
1499 // Verify that we have 2 tabs.
1501 // The download_page1.html page contains an openNew() function that opens a
1502 // tab and then downloads download-test1.lib.
1503 IN_PROC_BROWSER_TEST_F(DownloadTest, DontCloseNewTab2) {
1504 // Because it's an HTML link, it should open a web page rather than
1505 // downloading.
1506 base::FilePath file1(FILE_PATH_LITERAL("download_page1.html"));
1507 GURL url(URLRequestMockHTTPJob::GetMockUrl(file1));
1509 // Open a web page and wait.
1510 ui_test_utils::NavigateToURL(browser(), url);
1512 // Download a file in a new tab and wait (via Javascript).
1513 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
1514 DownloadAndWaitWithDisposition(browser(),
1515 GURL("javascript:openNew()"),
1516 CURRENT_TAB,
1517 ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
1519 // When the download finishes, we should have two tabs.
1520 EXPECT_EQ(2, browser()->tab_strip_model()->count());
1522 CheckDownload(browser(), file, file);
1525 // Open a web page in the current tab, open another tab via a Javascript call,
1526 // then download a file in the new tab.
1527 // Verify that we have 2 tabs.
1529 // The download_page2.html page contains an openNew() function that opens a
1530 // tab.
1531 IN_PROC_BROWSER_TEST_F(DownloadTest, DontCloseNewTab3) {
1532 // Because it's an HTML link, it should open a web page rather than
1533 // downloading.
1534 base::FilePath file1(FILE_PATH_LITERAL("download_page2.html"));
1535 GURL url1(URLRequestMockHTTPJob::GetMockUrl(file1));
1537 // Open a web page and wait.
1538 ui_test_utils::NavigateToURL(browser(), url1);
1540 // Open a new tab and wait.
1541 ui_test_utils::NavigateToURLWithDisposition(
1542 browser(),
1543 GURL("javascript:openNew()"),
1544 CURRENT_TAB,
1545 ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
1547 EXPECT_EQ(2, browser()->tab_strip_model()->count());
1549 // Download a file and wait.
1550 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
1551 GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
1552 DownloadAndWaitWithDisposition(browser(),
1553 url,
1554 CURRENT_TAB,
1555 ui_test_utils::BROWSER_TEST_NONE);
1557 // When the download finishes, we should have two tabs.
1558 EXPECT_EQ(2, browser()->tab_strip_model()->count());
1560 CheckDownload(browser(), file, file);
1563 // Open a web page in the current tab, then download a file via Javascript,
1564 // which will do so in a temporary tab. Verify that we have 1 tab.
1566 // The download_page3.html page contains an openNew() function that opens a
1567 // tab with download-test1.lib in the URL. When the URL is determined to be
1568 // a download, the tab is closed automatically.
1569 IN_PROC_BROWSER_TEST_F(DownloadTest, CloseNewTab2) {
1570 // Because it's an HTML link, it should open a web page rather than
1571 // downloading.
1572 base::FilePath file1(FILE_PATH_LITERAL("download_page3.html"));
1573 GURL url(URLRequestMockHTTPJob::GetMockUrl(file1));
1575 // Open a web page and wait.
1576 ui_test_utils::NavigateToURL(browser(), url);
1578 // Download a file and wait.
1579 // The file to download is "download-test1.lib".
1580 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
1581 DownloadAndWaitWithDisposition(browser(),
1582 GURL("javascript:openNew()"),
1583 CURRENT_TAB,
1584 ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
1586 // When the download finishes, we should still have one tab.
1587 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1589 CheckDownload(browser(), file, file);
1592 // Open a web page in the current tab, then call Javascript via a button to
1593 // download a file in a new tab, which is closed automatically when the
1594 // download begins.
1595 // Verify that we have 1 tab.
1597 // The download_page4.html page contains a form with download-test1.lib as the
1598 // action.
1599 IN_PROC_BROWSER_TEST_F(DownloadTest, CloseNewTab3) {
1600 // Because it's an HTML link, it should open a web page rather than
1601 // downloading.
1602 base::FilePath file1(FILE_PATH_LITERAL("download_page4.html"));
1603 GURL url(URLRequestMockHTTPJob::GetMockUrl(file1));
1605 // Open a web page and wait.
1606 ui_test_utils::NavigateToURL(browser(), url);
1608 // Download a file in a new tab and wait. The tab will automatically close
1609 // when the download begins.
1610 // The file to download is "download-test1.lib".
1611 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
1612 DownloadAndWaitWithDisposition(
1613 browser(),
1614 GURL("javascript:document.getElementById('form').submit()"),
1615 CURRENT_TAB,
1616 ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
1618 // When the download finishes, we should still have one tab.
1619 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1621 CheckDownload(browser(), file, file);
1624 // EmbeddedTestServer::HandleRequestCallback function that responds with a
1625 // redirect to the URL specified via a query string.
1626 // E.g.:
1627 // C -> S: GET /dummy?http://example.com
1628 // S -> C: HTTP/1.1 301 Moved Permanently
1629 // Location: http://example.com
1630 // ...
1631 static scoped_ptr<net::test_server::HttpResponse> ServerRedirectRequestHandler(
1632 const net::test_server::HttpRequest& request) {
1633 scoped_ptr<net::test_server::BasicHttpResponse> response(
1634 new net::test_server::BasicHttpResponse());
1635 size_t query_position = request.relative_url.find('?');
1637 if (query_position == std::string::npos) {
1638 response->set_code(net::HTTP_PERMANENT_REDIRECT);
1639 response->AddCustomHeader("Location",
1640 "https://request-had-no-query-string");
1641 response->set_content_type("text/plain");
1642 response->set_content("Error");
1643 return response.Pass();
1646 response->set_code(net::HTTP_PERMANENT_REDIRECT);
1647 response->AddCustomHeader("Location",
1648 request.relative_url.substr(query_position + 1));
1649 response->set_content_type("text/plain");
1650 response->set_content("It's gone!");
1651 return response.Pass();
1654 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadHistoryCheck) {
1655 GURL download_url(net::URLRequestSlowDownloadJob::kKnownSizeUrl);
1656 base::FilePath file(net::GenerateFileName(download_url,
1657 std::string(),
1658 std::string(),
1659 std::string(),
1660 std::string(),
1661 std::string()));
1663 // We use the server so that we can get a redirect and test url_chain
1664 // persistence.
1665 embedded_test_server()->RegisterRequestHandler(
1666 base::Bind(&ServerRedirectRequestHandler));
1667 ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
1668 GURL redirect_url =
1669 embedded_test_server()->GetURL("/a?" + download_url.spec());
1671 // Download the url and wait until the object has been stored.
1672 base::Time start(base::Time::Now());
1673 HistoryObserver observer(browser()->profile());
1674 observer.SetFilterCallback(base::Bind(&HasDataAndName));
1675 ui_test_utils::NavigateToURL(browser(), redirect_url);
1676 observer.WaitForStored();
1678 // Get the details on what was stored into the history.
1679 scoped_ptr<std::vector<history::DownloadRow> > downloads_in_database;
1680 ASSERT_TRUE(DownloadsHistoryDataCollector(
1681 browser()->profile()).WaitForDownloadInfo(&downloads_in_database));
1682 ASSERT_EQ(1u, downloads_in_database->size());
1684 // Confirm history storage is what you expect for a partially completed
1685 // slow download job.
1686 history::DownloadRow& row(downloads_in_database->at(0));
1687 EXPECT_EQ(DestinationFile(browser(), file), row.target_path);
1688 EXPECT_EQ(DownloadTargetDeterminer::GetCrDownloadPath(
1689 DestinationFile(browser(), file)),
1690 row.current_path);
1691 ASSERT_EQ(2u, row.url_chain.size());
1692 EXPECT_EQ(redirect_url.spec(), row.url_chain[0].spec());
1693 EXPECT_EQ(download_url.spec(), row.url_chain[1].spec());
1694 EXPECT_EQ(history::DownloadDangerType::NOT_DANGEROUS, row.danger_type);
1695 EXPECT_LE(start, row.start_time);
1696 EXPECT_EQ(net::URLRequestSlowDownloadJob::kFirstDownloadSize,
1697 row.received_bytes);
1698 EXPECT_EQ(net::URLRequestSlowDownloadJob::kFirstDownloadSize
1699 + net::URLRequestSlowDownloadJob::kSecondDownloadSize,
1700 row.total_bytes);
1701 EXPECT_EQ(history::DownloadState::IN_PROGRESS, row.state);
1702 EXPECT_FALSE(row.opened);
1704 // Finish the download. We're ok relying on the history to be flushed
1705 // at this point as our queries will be behind the history updates
1706 // invoked by completion.
1707 scoped_ptr<content::DownloadTestObserver> download_observer(
1708 CreateWaiter(browser(), 1));
1709 ui_test_utils::NavigateToURL(browser(),
1710 GURL(net::URLRequestSlowDownloadJob::kErrorDownloadUrl));
1711 download_observer->WaitForFinished();
1712 EXPECT_EQ(1u, download_observer->NumDownloadsSeenInState(
1713 DownloadItem::INTERRUPTED));
1714 base::Time end(base::Time::Now());
1716 // Get what was stored in the history.
1717 ASSERT_TRUE(DownloadsHistoryDataCollector(
1718 browser()->profile()).WaitForDownloadInfo(&downloads_in_database));
1719 ASSERT_EQ(1u, downloads_in_database->size());
1721 // Confirm history storage is what you expect for an interrupted slow download
1722 // job. The download isn't continuable, so there's no intermediate file.
1723 history::DownloadRow& row1(downloads_in_database->at(0));
1724 EXPECT_EQ(DestinationFile(browser(), file), row1.target_path);
1725 EXPECT_TRUE(row1.current_path.empty());
1726 ASSERT_EQ(2u, row1.url_chain.size());
1727 EXPECT_EQ(redirect_url.spec(), row1.url_chain[0].spec());
1728 EXPECT_EQ(download_url.spec(), row1.url_chain[1].spec());
1729 EXPECT_EQ(history::DownloadDangerType::NOT_DANGEROUS, row1.danger_type);
1730 EXPECT_LE(start, row1.start_time);
1731 EXPECT_GE(end, row1.end_time);
1732 EXPECT_EQ(net::URLRequestSlowDownloadJob::kFirstDownloadSize,
1733 row1.received_bytes);
1734 EXPECT_EQ(net::URLRequestSlowDownloadJob::kFirstDownloadSize
1735 + net::URLRequestSlowDownloadJob::kSecondDownloadSize,
1736 row1.total_bytes);
1737 EXPECT_EQ(history::DownloadState::INTERRUPTED, row1.state);
1738 EXPECT_EQ(history::ToHistoryDownloadInterruptReason(
1739 content::DOWNLOAD_INTERRUPT_REASON_NETWORK_FAILED),
1740 row1.interrupt_reason);
1741 EXPECT_FALSE(row1.opened);
1744 // Make sure a dangerous file shows up properly in the history.
1745 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadHistoryDangerCheck) {
1746 #if defined(OS_WIN) && defined(USE_ASH)
1747 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
1748 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1749 switches::kAshBrowserTests))
1750 return;
1751 #endif
1753 // .swf file so that it's dangerous on all platforms (including CrOS).
1754 base::FilePath file(FILE_PATH_LITERAL("downloads/dangerous/dangerous.swf"));
1755 GURL download_url(URLRequestMockHTTPJob::GetMockUrl(file));
1757 // Download the url and wait until the object has been stored.
1758 scoped_ptr<content::DownloadTestObserver> download_observer(
1759 new content::DownloadTestObserverTerminal(
1760 DownloadManagerForBrowser(browser()), 1,
1761 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_IGNORE));
1762 base::Time start(base::Time::Now());
1763 HistoryObserver observer(browser()->profile());
1764 observer.SetFilterCallback(base::Bind(&HasDataAndName));
1765 ui_test_utils::NavigateToURL(browser(), download_url);
1766 observer.WaitForStored();
1768 // Get the details on what was stored into the history.
1769 scoped_ptr<std::vector<history::DownloadRow> > downloads_in_database;
1770 ASSERT_TRUE(DownloadsHistoryDataCollector(
1771 browser()->profile()).WaitForDownloadInfo(&downloads_in_database));
1772 ASSERT_EQ(1u, downloads_in_database->size());
1774 // Confirm history storage is what you expect for an unvalidated
1775 // dangerous file.
1776 history::DownloadRow& row(downloads_in_database->at(0));
1777 EXPECT_EQ(DestinationFile(browser(), file), row.target_path);
1778 EXPECT_NE(DownloadTargetDeterminer::GetCrDownloadPath(
1779 DestinationFile(browser(), file)),
1780 row.current_path);
1781 EXPECT_EQ(history::DownloadDangerType::DANGEROUS_FILE, row.danger_type);
1782 EXPECT_LE(start, row.start_time);
1783 EXPECT_EQ(history::DownloadState::IN_PROGRESS, row.state);
1784 EXPECT_FALSE(row.opened);
1786 // Validate the download and wait for it to finish.
1787 std::vector<DownloadItem*> downloads;
1788 DownloadManagerForBrowser(browser())->GetAllDownloads(&downloads);
1789 ASSERT_EQ(1u, downloads.size());
1790 downloads[0]->ValidateDangerousDownload();
1791 download_observer->WaitForFinished();
1793 // Get history details and confirm it's what you expect.
1794 downloads_in_database->clear();
1795 ASSERT_TRUE(DownloadsHistoryDataCollector(
1796 browser()->profile()).WaitForDownloadInfo(&downloads_in_database));
1797 ASSERT_EQ(1u, downloads_in_database->size());
1798 history::DownloadRow& row1(downloads_in_database->at(0));
1799 EXPECT_EQ(DestinationFile(browser(), file), row1.target_path);
1800 EXPECT_EQ(DestinationFile(browser(), file), row1.current_path);
1801 EXPECT_EQ(history::DownloadDangerType::USER_VALIDATED, row1.danger_type);
1802 EXPECT_LE(start, row1.start_time);
1803 EXPECT_EQ(history::DownloadState::COMPLETE, row1.state);
1804 EXPECT_FALSE(row1.opened);
1805 // Not checking file size--not relevant to the point of the test, and
1806 // the file size is actually different on Windows and other platforms,
1807 // because for source control simplicity it's actually a text file, and
1808 // there are CRLF transformations for those files.
1811 // Test for crbug.com/14505. This tests that chrome:// urls are still functional
1812 // after download of a file while viewing another chrome://.
1813 IN_PROC_BROWSER_TEST_F(DownloadTest, ChromeURLAfterDownload) {
1814 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
1815 GURL download_url(URLRequestMockHTTPJob::GetMockUrl(file));
1816 GURL flags_url(chrome::kChromeUIFlagsURL);
1817 GURL extensions_url(chrome::kChromeUIExtensionsFrameURL);
1819 ui_test_utils::NavigateToURL(browser(), flags_url);
1820 DownloadAndWait(browser(), download_url);
1821 ui_test_utils::NavigateToURL(browser(), extensions_url);
1822 WebContents* contents =
1823 browser()->tab_strip_model()->GetActiveWebContents();
1824 ASSERT_TRUE(contents);
1825 bool webui_responded = false;
1826 EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
1827 contents,
1828 "window.domAutomationController.send(window.webuiResponded);",
1829 &webui_responded));
1830 EXPECT_TRUE(webui_responded);
1833 // Test for crbug.com/12745. This tests that if a download is initiated from
1834 // a chrome:// page that has registered and onunload handler, the browser
1835 // will be able to close.
1836 IN_PROC_BROWSER_TEST_F(DownloadTest, BrowserCloseAfterDownload) {
1837 GURL downloads_url(chrome::kChromeUIFlagsURL);
1838 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
1839 GURL download_url(URLRequestMockHTTPJob::GetMockUrl(file));
1841 ui_test_utils::NavigateToURL(browser(), downloads_url);
1842 WebContents* contents = browser()->tab_strip_model()->GetActiveWebContents();
1843 ASSERT_TRUE(contents);
1844 bool result = false;
1845 EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
1846 contents,
1847 "window.onunload = function() { var do_nothing = 0; }; "
1848 "window.domAutomationController.send(true);",
1849 &result));
1850 EXPECT_TRUE(result);
1852 DownloadAndWait(browser(), download_url);
1854 content::WindowedNotificationObserver signal(
1855 chrome::NOTIFICATION_BROWSER_CLOSED,
1856 content::Source<Browser>(browser()));
1857 chrome::CloseWindow(browser());
1858 signal.Wait();
1861 // Test to make sure the 'download' attribute in anchor tag is respected.
1862 IN_PROC_BROWSER_TEST_F(DownloadTest, AnchorDownloadTag) {
1863 base::FilePath file(FILE_PATH_LITERAL("download-anchor-attrib.html"));
1864 GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
1866 // Create a download, wait until it's complete, and confirm
1867 // we're in the expected state.
1868 scoped_ptr<content::DownloadTestObserver> observer(
1869 CreateWaiter(browser(), 1));
1870 ui_test_utils::NavigateToURL(browser(), url);
1871 observer->WaitForFinished();
1872 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::COMPLETE));
1873 CheckDownloadStates(1, DownloadItem::COMPLETE);
1875 // Confirm the downloaded data exists.
1876 base::FilePath downloaded_file = GetDownloadDirectory(browser());
1877 downloaded_file = downloaded_file.Append(FILE_PATH_LITERAL("a_red_dot.png"));
1878 EXPECT_TRUE(base::PathExists(downloaded_file));
1881 // Test to make sure auto-open works.
1882 IN_PROC_BROWSER_TEST_F(DownloadTest, AutoOpen) {
1883 base::FilePath file(FILE_PATH_LITERAL("download-autoopen.txt"));
1884 GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
1886 ASSERT_TRUE(
1887 GetDownloadPrefs(browser())->EnableAutoOpenBasedOnExtension(file));
1889 DownloadAndWait(browser(), url);
1891 // Find the download and confirm it was opened.
1892 std::vector<DownloadItem*> downloads;
1893 DownloadManagerForBrowser(browser())->GetAllDownloads(&downloads);
1894 ASSERT_EQ(1u, downloads.size());
1895 EXPECT_EQ(DownloadItem::COMPLETE, downloads[0]->GetState());
1897 // Unfortunately, this will block forever, causing a timeout, if
1898 // the download is never opened.
1899 content::DownloadUpdatedObserver(
1900 downloads[0], base::Bind(&WasAutoOpened)).WaitForEvent();
1901 EXPECT_TRUE(downloads[0]->GetOpened()); // Confirm it anyway.
1903 // As long as we're here, confirmed everything else is good.
1904 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1905 CheckDownload(browser(), file, file);
1908 // Download an extension. Expect a dangerous download warning.
1909 // Deny the download.
1910 IN_PROC_BROWSER_TEST_F(DownloadTest, CrxDenyInstall) {
1911 FeatureSwitch::ScopedOverride enable_easy_off_store_install(
1912 FeatureSwitch::easy_off_store_install(), true);
1914 GURL extension_url(URLRequestMockHTTPJob::GetMockUrl(kGoodCrxPath));
1916 scoped_ptr<content::DownloadTestObserver> observer(
1917 DangerousDownloadWaiter(
1918 browser(), 1,
1919 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_DENY));
1920 ui_test_utils::NavigateToURL(browser(), extension_url);
1922 observer->WaitForFinished();
1923 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::CANCELLED));
1924 EXPECT_EQ(1u, observer->NumDangerousDownloadsSeen());
1925 EXPECT_TRUE(VerifyNoDownloads());
1927 // Check that the CRX is not installed.
1928 ExtensionService* extension_service = extensions::ExtensionSystem::Get(
1929 browser()->profile())->extension_service();
1930 ASSERT_FALSE(extension_service->GetExtensionById(kGoodCrxId, false));
1933 // Download an extension. Expect a dangerous download warning.
1934 // Allow the download, deny the install.
1935 IN_PROC_BROWSER_TEST_F(DownloadTest, CrxInstallDenysPermissions) {
1936 FeatureSwitch::ScopedOverride enable_easy_off_store_install(
1937 FeatureSwitch::easy_off_store_install(), true);
1939 GURL extension_url(URLRequestMockHTTPJob::GetMockUrl(kGoodCrxPath));
1941 // Install a mock install UI that simulates a user denying permission to
1942 // finish the install.
1943 download_crx_util::SetMockInstallPromptForTesting(
1944 scoped_ptr<ExtensionInstallPrompt>(
1945 new MockAbortExtensionInstallPrompt()));
1947 scoped_ptr<content::DownloadTestObserver> observer(
1948 DangerousDownloadWaiter(
1949 browser(), 1,
1950 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_ACCEPT));
1951 ui_test_utils::NavigateToURL(browser(), extension_url);
1953 observer->WaitForFinished();
1954 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::COMPLETE));
1955 CheckDownloadStates(1, DownloadItem::COMPLETE);
1956 EXPECT_EQ(1u, observer->NumDangerousDownloadsSeen());
1958 content::DownloadManager::DownloadVector downloads;
1959 DownloadManagerForBrowser(browser())->GetAllDownloads(&downloads);
1960 ASSERT_EQ(1u, downloads.size());
1961 content::DownloadUpdatedObserver(
1962 downloads[0], base::Bind(&WasAutoOpened)).WaitForEvent();
1964 // Check that the extension was not installed.
1965 ExtensionService* extension_service = extensions::ExtensionSystem::Get(
1966 browser()->profile())->extension_service();
1967 ASSERT_FALSE(extension_service->GetExtensionById(kGoodCrxId, false));
1970 // Download an extension. Expect a dangerous download warning.
1971 // Allow the download, and the install.
1972 IN_PROC_BROWSER_TEST_F(DownloadTest, CrxInstallAcceptPermissions) {
1973 FeatureSwitch::ScopedOverride enable_easy_off_store_install(
1974 FeatureSwitch::easy_off_store_install(), true);
1976 GURL extension_url(URLRequestMockHTTPJob::GetMockUrl(kGoodCrxPath));
1978 // Install a mock install UI that simulates a user allowing permission to
1979 // finish the install.
1980 SetAllowMockInstallPrompt();
1982 scoped_ptr<content::DownloadTestObserver> observer(
1983 DangerousDownloadWaiter(
1984 browser(), 1,
1985 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_ACCEPT));
1986 ui_test_utils::NavigateToURL(browser(), extension_url);
1988 observer->WaitForFinished();
1989 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::COMPLETE));
1990 CheckDownloadStates(1, DownloadItem::COMPLETE);
1991 EXPECT_EQ(1u, observer->NumDangerousDownloadsSeen());
1993 // Download shelf should close from auto-open.
1994 content::DownloadManager::DownloadVector downloads;
1995 DownloadManagerForBrowser(browser())->GetAllDownloads(&downloads);
1996 ASSERT_EQ(1u, downloads.size());
1997 content::DownloadUpdatedObserver(
1998 downloads[0], base::Bind(&WasAutoOpened)).WaitForEvent();
2000 // Check that the extension was installed.
2001 ExtensionService* extension_service = extensions::ExtensionSystem::Get(
2002 browser()->profile())->extension_service();
2003 ASSERT_TRUE(extension_service->GetExtensionById(kGoodCrxId, false));
2006 // Test installing a CRX that fails integrity checks.
2007 IN_PROC_BROWSER_TEST_F(DownloadTest, CrxInvalid) {
2008 base::FilePath file(FILE_PATH_LITERAL("extensions/bad_signature.crx"));
2009 GURL extension_url(URLRequestMockHTTPJob::GetMockUrl(file));
2011 // Install a mock install UI that simulates a user allowing permission to
2012 // finish the install, and dismisses any error message. We check that the
2013 // install failed below.
2014 SetAllowMockInstallPrompt();
2016 scoped_ptr<content::DownloadTestObserver> observer(
2017 DangerousDownloadWaiter(
2018 browser(), 1,
2019 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_ACCEPT));
2020 ui_test_utils::NavigateToURL(browser(), extension_url);
2022 observer->WaitForFinished();
2023 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::COMPLETE));
2024 CheckDownloadStates(1, DownloadItem::COMPLETE);
2026 // Check that the extension was not installed.
2027 ExtensionService* extension_service = extensions::ExtensionSystem::Get(
2028 browser()->profile())->extension_service();
2029 ASSERT_FALSE(extension_service->GetExtensionById(kGoodCrxId, false));
2032 // Install a large (100kb) theme.
2033 IN_PROC_BROWSER_TEST_F(DownloadTest, CrxLargeTheme) {
2034 FeatureSwitch::ScopedOverride enable_easy_off_store_install(
2035 FeatureSwitch::easy_off_store_install(), true);
2037 GURL extension_url(URLRequestMockHTTPJob::GetMockUrl(kLargeThemePath));
2039 // Install a mock install UI that simulates a user allowing permission to
2040 // finish the install.
2041 SetAllowMockInstallPrompt();
2043 scoped_ptr<content::DownloadTestObserver> observer(
2044 DangerousDownloadWaiter(
2045 browser(), 1,
2046 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_ACCEPT));
2047 ui_test_utils::NavigateToURL(browser(), extension_url);
2049 observer->WaitForFinished();
2050 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::COMPLETE));
2051 CheckDownloadStates(1, DownloadItem::COMPLETE);
2052 EXPECT_EQ(1u, observer->NumDangerousDownloadsSeen());
2054 // Download shelf should close from auto-open.
2055 content::DownloadManager::DownloadVector downloads;
2056 DownloadManagerForBrowser(browser())->GetAllDownloads(&downloads);
2057 ASSERT_EQ(1u, downloads.size());
2058 content::DownloadUpdatedObserver(
2059 downloads[0], base::Bind(&WasAutoOpened)).WaitForEvent();
2061 // Check that the extension was installed.
2062 ExtensionService* extension_service = extensions::ExtensionSystem::Get(
2063 browser()->profile())->extension_service();
2064 ASSERT_TRUE(extension_service->GetExtensionById(kLargeThemeCrxId, false));
2067 // Tests for download initiation functions.
2068 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadUrl) {
2069 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
2070 GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
2072 // DownloadUrl always prompts; return acceptance of whatever it prompts.
2073 EnableFileChooser(true);
2075 WebContents* web_contents =
2076 browser()->tab_strip_model()->GetActiveWebContents();
2077 ASSERT_TRUE(web_contents);
2079 content::DownloadTestObserver* observer(
2080 new content::DownloadTestObserverTerminal(
2081 DownloadManagerForBrowser(browser()), 1,
2082 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL));
2083 scoped_ptr<DownloadUrlParameters> params(
2084 DownloadUrlParameters::FromWebContents(web_contents, url));
2085 params->set_prompt(true);
2086 DownloadManagerForBrowser(browser())->DownloadUrl(params.Pass());
2087 observer->WaitForFinished();
2088 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::COMPLETE));
2089 CheckDownloadStates(1, DownloadItem::COMPLETE);
2090 EXPECT_TRUE(DidShowFileChooser());
2092 // Check state.
2093 EXPECT_EQ(1, browser()->tab_strip_model()->count());
2094 ASSERT_TRUE(CheckDownload(browser(), file, file));
2097 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadUrlToPath) {
2098 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
2099 GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
2101 WebContents* web_contents =
2102 browser()->tab_strip_model()->GetActiveWebContents();
2103 ASSERT_TRUE(web_contents);
2105 base::ScopedTempDir other_directory;
2106 ASSERT_TRUE(other_directory.CreateUniqueTempDir());
2107 base::FilePath target_file_full_path
2108 = other_directory.path().Append(file.BaseName());
2109 content::DownloadTestObserver* observer(CreateWaiter(browser(), 1));
2110 scoped_ptr<DownloadUrlParameters> params(
2111 DownloadUrlParameters::FromWebContents(web_contents, url));
2112 params->set_file_path(target_file_full_path);
2113 DownloadManagerForBrowser(browser())->DownloadUrl(params.Pass());
2114 observer->WaitForFinished();
2115 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::COMPLETE));
2117 // Check state.
2118 EXPECT_EQ(1, browser()->tab_strip_model()->count());
2119 ASSERT_TRUE(CheckDownloadFullPaths(browser(),
2120 target_file_full_path,
2121 OriginFile(file)));
2123 // Temporary are treated as auto-opened, and after that open won't be
2124 // visible; wait for auto-open and confirm not visible.
2125 std::vector<DownloadItem*> downloads;
2126 DownloadManagerForBrowser(browser())->GetAllDownloads(&downloads);
2127 ASSERT_EQ(1u, downloads.size());
2128 content::DownloadUpdatedObserver(
2129 downloads[0], base::Bind(&WasAutoOpened)).WaitForEvent();
2132 IN_PROC_BROWSER_TEST_F(DownloadTest, SavePageNonHTMLViaGet) {
2133 embedded_test_server()->ServeFilesFromDirectory(GetTestDataDirectory());
2134 ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
2135 EnableFileChooser(true);
2136 std::vector<DownloadItem*> download_items;
2137 GetDownloads(browser(), &download_items);
2138 ASSERT_TRUE(download_items.empty());
2140 // Navigate to a non-HTML resource. The resource also has
2141 // Cache-Control: no-cache set, which normally requires revalidation
2142 // each time.
2143 GURL url = embedded_test_server()->GetURL("/downloads/image.jpg");
2144 ASSERT_TRUE(url.is_valid());
2145 ui_test_utils::NavigateToURL(browser(), url);
2147 // Stop the test server, and then try to save the page. If cache validation
2148 // is not bypassed then this will fail since the server is no longer
2149 // reachable.
2150 ASSERT_TRUE(embedded_test_server()->ShutdownAndWaitUntilComplete());
2152 scoped_ptr<content::DownloadTestObserver> waiter(
2153 new content::DownloadTestObserverTerminal(
2154 DownloadManagerForBrowser(browser()), 1,
2155 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL));
2156 chrome::SavePage(browser());
2157 waiter->WaitForFinished();
2158 EXPECT_EQ(1u, waiter->NumDownloadsSeenInState(DownloadItem::COMPLETE));
2159 CheckDownloadStates(1, DownloadItem::COMPLETE);
2161 // Validate that the correct file was downloaded.
2162 GetDownloads(browser(), &download_items);
2163 EXPECT_TRUE(DidShowFileChooser());
2164 ASSERT_EQ(1u, download_items.size());
2165 ASSERT_EQ(url, download_items[0]->GetOriginalUrl());
2167 // Try to download it via a context menu.
2168 scoped_ptr<content::DownloadTestObserver> waiter_context_menu(
2169 new content::DownloadTestObserverTerminal(
2170 DownloadManagerForBrowser(browser()), 1,
2171 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL));
2172 content::ContextMenuParams context_menu_params;
2173 context_menu_params.media_type = blink::WebContextMenuData::MediaTypeImage;
2174 context_menu_params.src_url = url;
2175 context_menu_params.page_url = url;
2176 TestRenderViewContextMenu menu(
2177 browser()->tab_strip_model()->GetActiveWebContents()->GetMainFrame(),
2178 context_menu_params);
2179 menu.Init();
2180 menu.ExecuteCommand(IDC_CONTENT_CONTEXT_SAVEIMAGEAS, 0);
2181 waiter_context_menu->WaitForFinished();
2182 EXPECT_EQ(
2183 1u, waiter_context_menu->NumDownloadsSeenInState(DownloadItem::COMPLETE));
2184 CheckDownloadStates(2, DownloadItem::COMPLETE);
2186 // Validate that the correct file was downloaded via the context menu.
2187 download_items.clear();
2188 GetDownloads(browser(), &download_items);
2189 EXPECT_TRUE(DidShowFileChooser());
2190 ASSERT_EQ(2u, download_items.size());
2191 ASSERT_EQ(url, download_items[0]->GetOriginalUrl());
2192 ASSERT_EQ(url, download_items[1]->GetOriginalUrl());
2195 // A EmbeddedTestServer::HandleRequestCallback function that checks for requests
2196 // with query string ?allow-post-only, and returns a 404 response if the method
2197 // is not POST.
2198 static scoped_ptr<net::test_server::HttpResponse> FilterPostOnlyURLsHandler(
2199 const net::test_server::HttpRequest& request) {
2200 scoped_ptr<net::test_server::BasicHttpResponse> response;
2201 if (request.relative_url.find("?allow-post-only") != std::string::npos &&
2202 request.method != net::test_server::METHOD_POST) {
2203 response.reset(new net::test_server::BasicHttpResponse());
2204 response->set_code(net::HTTP_NOT_FOUND);
2206 return response.Pass();
2209 IN_PROC_BROWSER_TEST_F(DownloadTest, SavePageNonHTMLViaPost) {
2210 embedded_test_server()->RegisterRequestHandler(
2211 base::Bind(&FilterPostOnlyURLsHandler));
2212 embedded_test_server()->ServeFilesFromDirectory(GetTestDataDirectory());
2213 ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
2214 EnableFileChooser(true);
2215 std::vector<DownloadItem*> download_items;
2216 GetDownloads(browser(), &download_items);
2217 ASSERT_TRUE(download_items.empty());
2219 // Navigate to a form page.
2220 GURL form_url =
2221 embedded_test_server()->GetURL("/downloads/form_page_to_post.html");
2222 ASSERT_TRUE(form_url.is_valid());
2223 ui_test_utils::NavigateToURL(browser(), form_url);
2225 // Submit the form. This will send a POST reqeuest, and the response is a
2226 // JPEG image. The resource also has Cache-Control: no-cache set,
2227 // which normally requires revalidation each time.
2228 GURL jpeg_url =
2229 embedded_test_server()->GetURL("/downloads/image.jpg?allow-post-only");
2230 ASSERT_TRUE(jpeg_url.is_valid());
2231 WebContents* web_contents =
2232 browser()->tab_strip_model()->GetActiveWebContents();
2233 ASSERT_TRUE(web_contents != NULL);
2234 content::WindowedNotificationObserver observer(
2235 content::NOTIFICATION_NAV_ENTRY_COMMITTED,
2236 content::Source<content::NavigationController>(
2237 &web_contents->GetController()));
2238 content::RenderFrameHost* render_frame_host = web_contents->GetMainFrame();
2239 ASSERT_TRUE(render_frame_host != NULL);
2240 render_frame_host->ExecuteJavaScriptForTests(
2241 base::ASCIIToUTF16("SubmitForm()"));
2242 observer.Wait();
2243 EXPECT_EQ(jpeg_url, web_contents->GetURL());
2245 // Stop the test server, and then try to save the page. If cache validation
2246 // is not bypassed then this will fail since the server is no longer
2247 // reachable. This will also fail if it tries to be retrieved via "GET"
2248 // rather than "POST".
2249 ASSERT_TRUE(embedded_test_server()->ShutdownAndWaitUntilComplete());
2250 scoped_ptr<content::DownloadTestObserver> waiter(
2251 new content::DownloadTestObserverTerminal(
2252 DownloadManagerForBrowser(browser()), 1,
2253 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL));
2254 chrome::SavePage(browser());
2255 waiter->WaitForFinished();
2256 EXPECT_EQ(1u, waiter->NumDownloadsSeenInState(DownloadItem::COMPLETE));
2257 CheckDownloadStates(1, DownloadItem::COMPLETE);
2259 // Validate that the correct file was downloaded.
2260 GetDownloads(browser(), &download_items);
2261 EXPECT_TRUE(DidShowFileChooser());
2262 ASSERT_EQ(1u, download_items.size());
2263 ASSERT_EQ(jpeg_url, download_items[0]->GetOriginalUrl());
2265 // Try to download it via a context menu.
2266 scoped_ptr<content::DownloadTestObserver> waiter_context_menu(
2267 new content::DownloadTestObserverTerminal(
2268 DownloadManagerForBrowser(browser()), 1,
2269 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL));
2270 content::ContextMenuParams context_menu_params;
2271 context_menu_params.media_type = blink::WebContextMenuData::MediaTypeImage;
2272 context_menu_params.src_url = jpeg_url;
2273 context_menu_params.page_url = jpeg_url;
2274 TestRenderViewContextMenu menu(web_contents->GetMainFrame(),
2275 context_menu_params);
2276 menu.Init();
2277 menu.ExecuteCommand(IDC_CONTENT_CONTEXT_SAVEIMAGEAS, 0);
2278 waiter_context_menu->WaitForFinished();
2279 EXPECT_EQ(
2280 1u, waiter_context_menu->NumDownloadsSeenInState(DownloadItem::COMPLETE));
2281 CheckDownloadStates(2, DownloadItem::COMPLETE);
2283 // Validate that the correct file was downloaded via the context menu.
2284 download_items.clear();
2285 GetDownloads(browser(), &download_items);
2286 EXPECT_TRUE(DidShowFileChooser());
2287 ASSERT_EQ(2u, download_items.size());
2288 ASSERT_EQ(jpeg_url, download_items[0]->GetOriginalUrl());
2289 ASSERT_EQ(jpeg_url, download_items[1]->GetOriginalUrl());
2292 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadErrorsServer) {
2293 DownloadInfo download_info[] = {
2294 { // Normal navigated download.
2295 "a_zip_file.zip",
2296 DOWNLOAD_NAVIGATE,
2297 content::DOWNLOAD_INTERRUPT_REASON_NONE,
2298 true,
2299 false
2301 { // Normal direct download.
2302 "a_zip_file.zip",
2303 DOWNLOAD_DIRECT,
2304 content::DOWNLOAD_INTERRUPT_REASON_NONE,
2305 true,
2306 false
2308 { // Direct download with 404 error.
2309 "there_IS_no_spoon.zip",
2310 DOWNLOAD_DIRECT,
2311 content::DOWNLOAD_INTERRUPT_REASON_SERVER_BAD_CONTENT,
2312 true,
2313 false
2315 { // Navigated download with 404 error.
2316 "there_IS_no_spoon.zip",
2317 DOWNLOAD_NAVIGATE,
2318 content::DOWNLOAD_INTERRUPT_REASON_SERVER_BAD_CONTENT,
2319 false,
2320 false
2322 { // Direct download with 400 error.
2323 "zip_file_not_found.zip",
2324 DOWNLOAD_DIRECT,
2325 content::DOWNLOAD_INTERRUPT_REASON_SERVER_FAILED,
2326 true,
2327 false
2329 { // Navigated download with 400 error.
2330 "zip_file_not_found.zip",
2331 DOWNLOAD_NAVIGATE,
2332 content::DOWNLOAD_INTERRUPT_REASON_SERVER_FAILED,
2333 false,
2334 false
2338 DownloadFilesCheckErrors(arraysize(download_info), download_info);
2341 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadErrorsFile) {
2342 FileErrorInjectInfo error_info[] = {
2343 { // Navigated download with injected "Disk full" error in Initialize().
2344 { "a_zip_file.zip",
2345 DOWNLOAD_NAVIGATE,
2346 content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE,
2351 content::TestFileErrorInjector::FILE_OPERATION_INITIALIZE,
2353 content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE,
2356 { // Direct download with injected "Disk full" error in Initialize().
2357 { "a_zip_file.zip",
2358 DOWNLOAD_DIRECT,
2359 content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE,
2364 content::TestFileErrorInjector::FILE_OPERATION_INITIALIZE,
2366 content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE,
2369 { // Navigated download with injected "Disk full" error in Write().
2370 { "a_zip_file.zip",
2371 DOWNLOAD_NAVIGATE,
2372 content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE,
2377 content::TestFileErrorInjector::FILE_OPERATION_WRITE,
2379 content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE,
2382 { // Direct download with injected "Disk full" error in Write().
2383 { "a_zip_file.zip",
2384 DOWNLOAD_DIRECT,
2385 content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE,
2390 content::TestFileErrorInjector::FILE_OPERATION_WRITE,
2392 content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE,
2395 { // Navigated download with injected "Failed" error in Initialize().
2396 { "a_zip_file.zip",
2397 DOWNLOAD_NAVIGATE,
2398 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED,
2403 content::TestFileErrorInjector::FILE_OPERATION_INITIALIZE,
2405 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED,
2408 { // Direct download with injected "Failed" error in Initialize().
2409 { "a_zip_file.zip",
2410 DOWNLOAD_DIRECT,
2411 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED,
2416 content::TestFileErrorInjector::FILE_OPERATION_INITIALIZE,
2418 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED,
2421 { // Navigated download with injected "Failed" error in Write().
2422 { "a_zip_file.zip",
2423 DOWNLOAD_NAVIGATE,
2424 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED,
2429 content::TestFileErrorInjector::FILE_OPERATION_WRITE,
2431 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED,
2434 { // Direct download with injected "Failed" error in Write().
2435 { "a_zip_file.zip",
2436 DOWNLOAD_DIRECT,
2437 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED,
2442 content::TestFileErrorInjector::FILE_OPERATION_WRITE,
2444 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED,
2447 { // Navigated download with injected "Name too long" error in
2448 // Initialize().
2449 { "a_zip_file.zip",
2450 DOWNLOAD_NAVIGATE,
2451 content::DOWNLOAD_INTERRUPT_REASON_FILE_NAME_TOO_LONG,
2456 content::TestFileErrorInjector::FILE_OPERATION_INITIALIZE,
2458 content::DOWNLOAD_INTERRUPT_REASON_FILE_NAME_TOO_LONG,
2461 { // Direct download with injected "Name too long" error in Initialize().
2462 { "a_zip_file.zip",
2463 DOWNLOAD_DIRECT,
2464 content::DOWNLOAD_INTERRUPT_REASON_FILE_NAME_TOO_LONG,
2469 content::TestFileErrorInjector::FILE_OPERATION_INITIALIZE,
2471 content::DOWNLOAD_INTERRUPT_REASON_FILE_NAME_TOO_LONG,
2474 { // Navigated download with injected "Name too long" error in Write().
2475 { "a_zip_file.zip",
2476 DOWNLOAD_NAVIGATE,
2477 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED,
2482 content::TestFileErrorInjector::FILE_OPERATION_WRITE,
2484 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED,
2487 { // Direct download with injected "Name too long" error in Write().
2488 { "a_zip_file.zip",
2489 DOWNLOAD_DIRECT,
2490 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED,
2495 content::TestFileErrorInjector::FILE_OPERATION_WRITE,
2497 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED,
2500 { // Direct download with injected "Disk full" error in 2nd Write().
2501 { "06bESSE21Evolution.ppt",
2502 DOWNLOAD_DIRECT,
2503 content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE,
2508 content::TestFileErrorInjector::FILE_OPERATION_WRITE,
2510 content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE,
2515 DownloadInsertFilesErrorCheckErrors(arraysize(error_info), error_info);
2518 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadErrorReadonlyFolder) {
2519 DownloadInfo download_info[] = {
2521 "a_zip_file.zip",
2522 DOWNLOAD_DIRECT,
2523 // This passes because we switch to the My Documents folder.
2524 content::DOWNLOAD_INTERRUPT_REASON_NONE,
2525 true,
2526 true
2529 "a_zip_file.zip",
2530 DOWNLOAD_NAVIGATE,
2531 // This passes because we switch to the My Documents folder.
2532 content::DOWNLOAD_INTERRUPT_REASON_NONE,
2533 true,
2534 true
2538 DownloadFilesToReadonlyFolder(arraysize(download_info), download_info);
2541 // Test that we show a dangerous downloads warning for a dangerous file
2542 // downloaded through a blob: URL.
2543 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadDangerousBlobData) {
2544 #if defined(OS_WIN)
2545 // On Windows, if SafeBrowsing is enabled, certain file types (.exe, .cab,
2546 // .msi) will be handled by the DownloadProtectionService. However, if the URL
2547 // is non-standard (e.g. blob:) then those files won't be handled by the
2548 // DPS. We should be showing the dangerous download warning for any file
2549 // considered dangerous and isn't handled by the DPS.
2550 const char kFilename[] = "foo.exe";
2551 #else
2552 const char kFilename[] = "foo.swf";
2553 #endif
2555 std::string path("downloads/download-dangerous-blob.html?filename=");
2556 path += kFilename;
2558 // Need to use http urls because the blob js doesn't work on file urls for
2559 // security reasons.
2560 GURL url = net::URLRequestMockHTTPJob::GetMockUrl(path);
2562 content::DownloadTestObserver* observer(DangerousDownloadWaiter(
2563 browser(), 1,
2564 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_ACCEPT));
2565 ui_test_utils::NavigateToURL(browser(), url);
2566 observer->WaitForFinished();
2568 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::COMPLETE));
2569 EXPECT_EQ(1u, observer->NumDangerousDownloadsSeen());
2572 // A EmbeddedTestServer::HandleRequestCallback function that echoes the Referrer
2573 // header as its contents. Only responds to the relative URL /echoreferrer
2574 // E.g.:
2575 // C -> S: GET /foo
2576 // Referer: http://example.com/foo
2577 // S -> C: HTTP/1.1 200 OK
2578 // Content-Type: text/plain
2580 // http://example.com/foo
2581 static scoped_ptr<net::test_server::HttpResponse> EchoReferrerRequestHandler(
2582 const net::test_server::HttpRequest& request) {
2583 const std::string kReferrerHeader = "Referer"; // SIC
2585 if (request.relative_url.find("/echoreferrer") != 0)
2586 return scoped_ptr<net::test_server::HttpResponse>();
2588 scoped_ptr<net::test_server::BasicHttpResponse> response(
2589 new net::test_server::BasicHttpResponse());
2590 response->set_code(net::HTTP_OK);
2591 response->set_content_type("text/plain");
2592 auto referrer_header = request.headers.find(kReferrerHeader);
2593 if (referrer_header != request.headers.end())
2594 response->set_content(referrer_header->second);
2595 return response.Pass();
2598 IN_PROC_BROWSER_TEST_F(DownloadTest, LoadURLExternallyReferrerPolicy) {
2599 embedded_test_server()->RegisterRequestHandler(
2600 base::Bind(&EchoReferrerRequestHandler));
2601 embedded_test_server()->ServeFilesFromDirectory(GetTestDataDirectory());
2602 ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
2603 EnableFileChooser(true);
2604 std::vector<DownloadItem*> download_items;
2605 GetDownloads(browser(), &download_items);
2606 ASSERT_TRUE(download_items.empty());
2608 // Navigate to a page with a referrer policy and a link on it. The link points
2609 // to /echoreferrer.
2610 GURL url = embedded_test_server()->GetURL("/downloads/referrer_policy.html");
2611 ASSERT_TRUE(url.is_valid());
2612 ui_test_utils::NavigateToURL(browser(), url);
2614 scoped_ptr<content::DownloadTestObserver> waiter(
2615 new content::DownloadTestObserverTerminal(
2616 DownloadManagerForBrowser(browser()), 1,
2617 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL));
2619 // Click on the link with the alt key pressed. This will download the link
2620 // target.
2621 WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
2622 blink::WebMouseEvent mouse_event;
2623 mouse_event.type = blink::WebInputEvent::MouseDown;
2624 mouse_event.button = blink::WebMouseEvent::ButtonLeft;
2625 mouse_event.x = 15;
2626 mouse_event.y = 15;
2627 mouse_event.clickCount = 1;
2628 mouse_event.modifiers = blink::WebInputEvent::AltKey;
2629 tab->GetRenderViewHost()->ForwardMouseEvent(mouse_event);
2630 mouse_event.type = blink::WebInputEvent::MouseUp;
2631 tab->GetRenderViewHost()->ForwardMouseEvent(mouse_event);
2633 waiter->WaitForFinished();
2634 EXPECT_EQ(1u, waiter->NumDownloadsSeenInState(DownloadItem::COMPLETE));
2635 CheckDownloadStates(1, DownloadItem::COMPLETE);
2637 // Validate that the correct file was downloaded.
2638 GetDownloads(browser(), &download_items);
2639 ASSERT_EQ(1u, download_items.size());
2640 ASSERT_EQ(embedded_test_server()->GetURL("/echoreferrer"),
2641 download_items[0]->GetOriginalUrl());
2643 // Check that the file contains the expected referrer.
2644 base::FilePath file(download_items[0]->GetTargetFilePath());
2645 std::string expected_contents = embedded_test_server()->GetURL("/").spec();
2646 ASSERT_TRUE(VerifyFile(file, expected_contents, expected_contents.length()));
2649 // This test ensures that the Referer header is properly sanitized when
2650 // Save Link As is chosen from the context menu.
2651 IN_PROC_BROWSER_TEST_F(DownloadTest, SaveLinkAsReferrerPolicyOrigin) {
2652 embedded_test_server()->RegisterRequestHandler(
2653 base::Bind(&EchoReferrerRequestHandler));
2654 ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
2655 EnableFileChooser(true);
2656 std::vector<DownloadItem*> download_items;
2657 GetDownloads(browser(), &download_items);
2658 ASSERT_TRUE(download_items.empty());
2660 // Navigate to the initial page, where Save Link As will be executed.
2661 GURL url = net::URLRequestMockHTTPJob::GetMockHttpsUrl(
2662 std::string("referrer_policy/referrer-policy-start.html?policy=origin") +
2663 "&redirect=" + embedded_test_server()->GetURL("/echoreferrer").spec() +
2664 "&link=true&target=");
2665 ASSERT_TRUE(url.is_valid());
2666 ui_test_utils::NavigateToURL(browser(), url);
2668 scoped_ptr<content::DownloadTestObserver> waiter(
2669 new content::DownloadTestObserverTerminal(
2670 DownloadManagerForBrowser(browser()), 1,
2671 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL));
2673 // Right-click on the link and choose Save Link As. This will download the
2674 // link target.
2675 ContextMenuNotificationObserver context_menu_observer(
2676 IDC_CONTENT_CONTEXT_SAVELINKAS);
2678 WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents();
2679 blink::WebMouseEvent mouse_event;
2680 mouse_event.type = blink::WebInputEvent::MouseDown;
2681 mouse_event.button = blink::WebMouseEvent::ButtonRight;
2682 mouse_event.x = 15;
2683 mouse_event.y = 15;
2684 mouse_event.clickCount = 1;
2685 tab->GetRenderViewHost()->ForwardMouseEvent(mouse_event);
2686 mouse_event.type = blink::WebInputEvent::MouseUp;
2687 tab->GetRenderViewHost()->ForwardMouseEvent(mouse_event);
2689 waiter->WaitForFinished();
2690 EXPECT_EQ(1u, waiter->NumDownloadsSeenInState(DownloadItem::COMPLETE));
2691 CheckDownloadStates(1, DownloadItem::COMPLETE);
2693 // Validate that the correct file was downloaded.
2694 GetDownloads(browser(), &download_items);
2695 EXPECT_EQ(1u, download_items.size());
2696 EXPECT_EQ(embedded_test_server()->GetURL("/echoreferrer"),
2697 download_items[0]->GetOriginalUrl());
2699 // Check that the file contains the expected referrer.
2700 base::FilePath file(download_items[0]->GetTargetFilePath());
2701 std::string expected_contents =
2702 net::URLRequestMockHTTPJob::GetMockHttpsUrl(std::string()).spec();
2703 EXPECT_TRUE(VerifyFile(file, expected_contents, expected_contents.length()));
2706 // This test ensures that the Referer header is properly sanitized when
2707 // Save Image As is chosen from the context menu.
2708 IN_PROC_BROWSER_TEST_F(DownloadTest, SaveImageAsReferrerPolicyDefault) {
2709 embedded_test_server()->RegisterRequestHandler(
2710 base::Bind(&EchoReferrerRequestHandler));
2711 ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
2712 EnableFileChooser(true);
2713 std::vector<DownloadItem*> download_items;
2714 GetDownloads(browser(), &download_items);
2715 ASSERT_TRUE(download_items.empty());
2717 GURL url = net::URLRequestMockHTTPJob::GetMockHttpsUrl("title1.html");
2718 GURL img_url = embedded_test_server()->GetURL("/echoreferrer");
2719 ASSERT_TRUE(url.is_valid());
2720 ui_test_utils::NavigateToURL(browser(), url);
2722 // Try to download an image via a context menu.
2723 scoped_ptr<content::DownloadTestObserver> waiter_context_menu(
2724 new content::DownloadTestObserverTerminal(
2725 DownloadManagerForBrowser(browser()), 1,
2726 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL));
2727 content::ContextMenuParams context_menu_params;
2728 context_menu_params.media_type = blink::WebContextMenuData::MediaTypeImage;
2729 context_menu_params.page_url = url;
2730 context_menu_params.src_url = img_url;
2731 TestRenderViewContextMenu menu(
2732 browser()->tab_strip_model()->GetActiveWebContents()->GetMainFrame(),
2733 context_menu_params);
2734 menu.Init();
2735 menu.ExecuteCommand(IDC_CONTENT_CONTEXT_SAVEIMAGEAS, 0);
2736 waiter_context_menu->WaitForFinished();
2737 EXPECT_EQ(
2738 1u, waiter_context_menu->NumDownloadsSeenInState(DownloadItem::COMPLETE));
2739 CheckDownloadStates(1, DownloadItem::COMPLETE);
2741 // Validate that the correct file was downloaded via the context menu.
2742 download_items.clear();
2743 GetDownloads(browser(), &download_items);
2744 EXPECT_TRUE(DidShowFileChooser());
2745 ASSERT_EQ(1u, download_items.size());
2746 ASSERT_EQ(img_url, download_items[0]->GetOriginalUrl());
2747 base::FilePath file = download_items[0]->GetTargetFilePath();
2748 // The contents of the file is the value of the Referer header if there was
2749 // one.
2750 EXPECT_TRUE(VerifyFile(file, "", 0));
2753 // Verify the multiple downloads infobar.
2754 IN_PROC_BROWSER_TEST_F(DownloadTest, TestMultipleDownloadsInfobar) {
2755 #if defined(OS_WIN) && defined(USE_ASH)
2756 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
2757 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
2758 switches::kAshBrowserTests))
2759 return;
2760 #endif
2762 // Ensure that infobars are being used instead of bubbles.
2763 base::CommandLine::ForCurrentProcess()->AppendSwitch(
2764 switches::kDisablePermissionsBubbles);
2766 // Create a downloads observer.
2767 scoped_ptr<content::DownloadTestObserver> downloads_observer(
2768 CreateWaiter(browser(), 2));
2770 // Create an infobar observer.
2771 content::WindowedNotificationObserver infobar_added_1(
2772 chrome::NOTIFICATION_TAB_CONTENTS_INFOBAR_ADDED,
2773 content::NotificationService::AllSources());
2774 ui_test_utils::NavigateToURL(browser(),
2775 net::URLRequestMockHTTPJob::GetMockUrl(
2776 "downloads/download-a_zip_file.html"));
2777 infobar_added_1.Wait();
2779 InfoBarService* infobar_service = InfoBarService::FromWebContents(
2780 browser()->tab_strip_model()->GetActiveWebContents());
2781 // Verify that there is only one infobar.
2782 ASSERT_EQ(1u, infobar_service->infobar_count());
2784 // Get the infobar at index 0.
2785 infobars::InfoBar* infobar = infobar_service->infobar_at(0);
2786 ConfirmInfoBarDelegate* confirm_infobar =
2787 infobar->delegate()->AsConfirmInfoBarDelegate();
2788 ASSERT_TRUE(confirm_infobar != NULL);
2790 // Verify multi download warning infobar message.
2791 EXPECT_EQ(confirm_infobar->GetMessageText(),
2792 l10n_util::GetStringUTF16(IDS_MULTI_DOWNLOAD_WARNING));
2794 // Click on the "Allow" button to allow multiple downloads.
2795 if (confirm_infobar->Accept())
2796 infobar_service->RemoveInfoBar(infobar);
2797 // Verify that there are no more infobars.
2798 EXPECT_EQ(0u, infobar_service->infobar_count());
2800 // Waits for the download to complete.
2801 downloads_observer->WaitForFinished();
2802 EXPECT_EQ(2u, downloads_observer->NumDownloadsSeenInState(
2803 DownloadItem::COMPLETE));
2806 IN_PROC_BROWSER_TEST_F(DownloadTest, TestMultipleDownloadsBubble) {
2807 #if defined(OS_WIN) && defined(USE_ASH)
2808 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
2809 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
2810 switches::kAshBrowserTests))
2811 return;
2812 #endif
2814 #if defined(OS_ANDROID) || defined(OS_IOS)
2815 // Permission bubbles are not supported on mobile.
2816 return;
2817 #endif
2819 // Enable permision bubbles.
2820 base::CommandLine::ForCurrentProcess()->AppendSwitch(
2821 switches::kEnablePermissionsBubbles);
2823 // Create a downloads observer.
2824 scoped_ptr<content::DownloadTestObserver> downloads_observer(
2825 CreateWaiter(browser(), 2));
2827 PermissionBubbleManager* permission_bubble_manager =
2828 PermissionBubbleManager::FromWebContents(
2829 browser()->tab_strip_model()->GetActiveWebContents());
2830 permission_bubble_manager->DisplayPendingRequests(browser());
2831 permission_bubble_manager->set_auto_response_for_test(
2832 PermissionBubbleManager::ACCEPT_ALL);
2834 ui_test_utils::NavigateToURLBlockUntilNavigationsComplete(
2835 browser(), net::URLRequestMockHTTPJob::GetMockUrl(
2836 "downloads/download-a_zip_file.html"),
2839 // Waits for the download to complete.
2840 downloads_observer->WaitForFinished();
2841 EXPECT_EQ(2u, downloads_observer->NumDownloadsSeenInState(
2842 DownloadItem::COMPLETE));
2844 browser()->tab_strip_model()->GetActiveWebContents()->Close();
2847 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadTest_Renaming) {
2848 GURL url = net::URLRequestMockHTTPJob::GetMockUrl("downloads/a_zip_file.zip");
2849 content::DownloadManager* manager = DownloadManagerForBrowser(browser());
2850 base::FilePath origin_file(OriginFile(base::FilePath(FILE_PATH_LITERAL(
2851 "downloads/a_zip_file.zip"))));
2852 ASSERT_TRUE(base::PathExists(origin_file));
2853 std::string origin_contents;
2854 ASSERT_TRUE(base::ReadFileToString(origin_file, &origin_contents));
2856 // Download the same url several times and expect that all downloaded files
2857 // after the zero-th contain a deduplication counter.
2858 for (int index = 0; index < 5; ++index) {
2859 DownloadAndWait(browser(), url);
2860 content::DownloadItem* item = manager->GetDownload(
2861 content::DownloadItem::kInvalidId + 1 + index);
2862 ASSERT_TRUE(item);
2863 ASSERT_EQ(DownloadItem::COMPLETE, item->GetState());
2864 base::FilePath target_path(item->GetTargetFilePath());
2865 EXPECT_EQ(std::string("a_zip_file") +
2866 (index == 0 ? std::string(".zip") :
2867 base::StringPrintf(" (%d).zip", index)),
2868 target_path.BaseName().AsUTF8Unsafe());
2869 ASSERT_TRUE(base::PathExists(target_path));
2870 ASSERT_TRUE(VerifyFile(target_path, origin_contents,
2871 origin_contents.size()));
2875 // Test that the entire download pipeline handles unicode correctly.
2876 // Disabled on Windows due to flaky timeouts: crbug.com/446695
2877 #if defined(OS_WIN)
2878 #define MAYBE_DownloadTest_CrazyFilenames DISABLED_DownloadTest_CrazyFilenames
2879 #else
2880 #define MAYBE_DownloadTest_CrazyFilenames DownloadTest_CrazyFilenames
2881 #endif
2882 IN_PROC_BROWSER_TEST_F(DownloadTest, MAYBE_DownloadTest_CrazyFilenames) {
2883 const wchar_t* kCrazyFilenames[] = {
2884 L"a_file_name.zip",
2885 L"\u89c6\u9891\u76f4\u64ad\u56fe\u7247.zip", // chinese chars
2886 L"\u0412\u043e \u0424\u043b\u043e\u0440\u0438\u0434\u0435\u043e\u0431\u044a"
2887 L"\u044f\u0432\u043b\u0435\u043d\u0440\u0435\u0436\u0438\u043c \u0427"
2888 L"\u041f \u0438\u0437-\u0437\u0430 \u0443\u0442\u0435\u0447\u043a\u0438 "
2889 L"\u043d\u0435\u0444\u0442\u0438.zip", // russian
2890 L"Desocupa\xe7\xe3o est\xe1vel.zip",
2891 // arabic:
2892 L"\u0638\u2026\u0638\u02c6\u0637\xa7\u0638\u201a\u0637\xb9 \u0638\u201e"
2893 L"\u0638\u201e\u0637\xb2\u0638\u0679\u0637\xa7\u0637\xb1\u0637\xa9.zip",
2894 L"\u05d4\u05e2\u05d3\u05e4\u05d5\u05ea.zip", // hebrew
2895 L"\u092d\u093e\u0930\u0924.zip", // hindi
2896 L"d\xe9stabilis\xe9.zip", // french
2897 // korean
2898 L"\u97d3-\u4e2d \uc815\uc0c1, \ucc9c\uc548\ud568 \uc758\uacac.zip",
2899 L"jiho....tiho...miho.zip",
2900 L"jiho!@#$tiho$%^&-()_+=miho copy.zip", // special chars
2901 L"Wohoo-to hoo+I.zip",
2902 L"Picture 1.zip",
2903 L"This is a very very long english sentence with spaces and , and +.zip",
2906 std::vector<DownloadItem*> download_items;
2907 base::FilePath origin(FILE_PATH_LITERAL("origin"));
2908 ASSERT_TRUE(base::CreateDirectory(DestinationFile(browser(), origin)));
2910 for (size_t index = 0; index < arraysize(kCrazyFilenames); ++index) {
2911 base::string16 crazy16;
2912 std::string crazy8;
2913 const wchar_t* crazy_w = kCrazyFilenames[index];
2914 ASSERT_TRUE(base::WideToUTF8(crazy_w, wcslen(crazy_w), &crazy8));
2915 ASSERT_TRUE(base::WideToUTF16(crazy_w, wcslen(crazy_w), &crazy16));
2916 base::FilePath file_path(DestinationFile(browser(), origin.Append(
2917 #if defined(OS_WIN)
2918 crazy16
2919 #elif defined(OS_POSIX)
2920 crazy8
2921 #endif
2922 )));
2924 // Create the file.
2925 EXPECT_EQ(static_cast<int>(crazy8.size()),
2926 base::WriteFile(file_path, crazy8.c_str(), crazy8.size()));
2927 GURL file_url(net::FilePathToFileURL(file_path));
2929 // Download the file and check that the filename is correct.
2930 DownloadAndWait(browser(), file_url);
2931 GetDownloads(browser(), &download_items);
2932 ASSERT_EQ(1UL, download_items.size());
2933 base::FilePath downloaded(download_items[0]->GetTargetFilePath());
2934 download_items[0]->Remove();
2935 download_items.clear();
2936 ASSERT_TRUE(CheckDownloadFullPaths(
2937 browser(),
2938 downloaded,
2939 file_path));
2943 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadTest_Remove) {
2944 GURL url = net::URLRequestMockHTTPJob::GetMockUrl("downloads/a_zip_file.zip");
2945 std::vector<DownloadItem*> download_items;
2946 GetDownloads(browser(), &download_items);
2947 ASSERT_TRUE(download_items.empty());
2949 // Download a file.
2950 DownloadAndWaitWithDisposition(browser(),
2951 url,
2952 CURRENT_TAB,
2953 ui_test_utils::BROWSER_TEST_NONE);
2954 GetDownloads(browser(), &download_items);
2955 ASSERT_EQ(1UL, download_items.size());
2956 base::FilePath downloaded(download_items[0]->GetTargetFilePath());
2958 // Remove the DownloadItem but not the file, then check that the file still
2959 // exists.
2960 download_items[0]->Remove();
2961 download_items.clear();
2962 GetDownloads(browser(), &download_items);
2963 ASSERT_EQ(0UL, download_items.size());
2964 ASSERT_TRUE(CheckDownloadFullPaths(
2965 browser(), downloaded, OriginFile(base::FilePath(
2966 FILE_PATH_LITERAL("downloads/a_zip_file.zip")))));
2969 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadTest_PauseResumeCancel) {
2970 DownloadItem* download_item = CreateSlowTestDownload();
2971 ASSERT_TRUE(download_item);
2972 ASSERT_FALSE(download_item->GetTargetFilePath().empty());
2973 EXPECT_FALSE(download_item->IsPaused());
2974 EXPECT_NE(DownloadItem::CANCELLED, download_item->GetState());
2975 download_item->Pause();
2976 EXPECT_TRUE(download_item->IsPaused());
2977 download_item->Resume();
2978 EXPECT_FALSE(download_item->IsPaused());
2979 EXPECT_NE(DownloadItem::CANCELLED, download_item->GetState());
2980 download_item->Cancel(true);
2981 EXPECT_EQ(DownloadItem::CANCELLED, download_item->GetState());
2984 // The Mac downloaded files quarantine feature is implemented by the
2985 // Contents/Info.plist file in cocoa apps. browser_tests cannot test
2986 // quarantining files on Mac because it is not a cocoa app.
2987 // TODO(benjhayden) test the equivalents on other platforms.
2989 #if defined(OS_LINUX) && !defined(OS_CHROMEOS) && defined(ARCH_CPU_ARM_FAMILY)
2990 // Timing out on ARM linux: http://crbug.com/238459
2991 #define MAYBE_DownloadTest_PercentComplete DISABLED_DownloadTest_PercentComplete
2992 #elif defined(OS_MACOSX)
2993 // Disable on mac: http://crbug.com/238831
2994 #define MAYBE_DownloadTest_PercentComplete DISABLED_DownloadTest_PercentComplete
2995 #else
2996 #define MAYBE_DownloadTest_PercentComplete DownloadTest_PercentComplete
2997 #endif
2998 IN_PROC_BROWSER_TEST_F(DownloadTest, MAYBE_DownloadTest_PercentComplete) {
2999 // Write a huge file.
3000 base::FilePath file_path(DestinationFile(
3001 browser(), base::FilePath(FILE_PATH_LITERAL("DownloadTest_BigZip.zip"))));
3002 base::File file(file_path, base::File::FLAG_CREATE | base::File::FLAG_WRITE);
3003 ASSERT_TRUE(file.IsValid());
3004 int64 size = 1 << 25;
3005 EXPECT_EQ(1, file.Write(size, "a", 1));
3006 file.Close();
3008 #if defined(OS_POSIX)
3009 // Make it readable by chronos on chromeos
3010 base::SetPosixFilePermissions(file_path, 0755);
3011 #endif
3013 // Ensure that we have enough disk space.
3014 int64 free_space = base::SysInfo::AmountOfFreeDiskSpace(
3015 GetDownloadDirectory(browser()));
3016 ASSERT_LE(size, free_space) << "Not enough disk space to download. Got "
3017 << free_space;
3018 GURL file_url(net::FilePathToFileURL(file_path));
3019 scoped_ptr<content::DownloadTestObserver> progress_waiter(
3020 CreateInProgressWaiter(browser(), 1));
3022 // Start downloading a file, wait for it to be created.
3023 ui_test_utils::NavigateToURLWithDisposition(
3024 browser(), file_url, CURRENT_TAB, ui_test_utils::BROWSER_TEST_NONE);
3025 progress_waiter->WaitForFinished();
3026 EXPECT_EQ(1u, progress_waiter->NumDownloadsSeenInState(
3027 DownloadItem::IN_PROGRESS));
3028 std::vector<DownloadItem*> download_items;
3029 GetDownloads(browser(), &download_items);
3030 ASSERT_EQ(1UL, download_items.size());
3032 // Wait for the download to complete, checking along the way that the
3033 // PercentComplete() never regresses.
3034 PercentWaiter waiter(download_items[0]);
3035 EXPECT_TRUE(waiter.WaitForFinished());
3036 EXPECT_EQ(DownloadItem::COMPLETE, download_items[0]->GetState());
3037 ASSERT_EQ(100, download_items[0]->PercentComplete());
3039 // Check that the file downloaded correctly.
3040 ASSERT_TRUE(base::PathExists(download_items[0]->GetTargetFilePath()));
3041 int64 downloaded_size = 0;
3042 ASSERT_TRUE(base::GetFileSize(
3043 download_items[0]->GetTargetFilePath(), &downloaded_size));
3044 ASSERT_EQ(size + 1, downloaded_size);
3045 ASSERT_TRUE(base::DieFileDie(file_path, false));
3046 ASSERT_TRUE(base::DieFileDie(download_items[0]->GetTargetFilePath(), false));
3049 // A download that is interrupted due to a file error should be able to be
3050 // resumed.
3051 IN_PROC_BROWSER_TEST_F(DownloadTest, Resumption_NoPrompt) {
3052 base::CommandLine::ForCurrentProcess()->AppendSwitch(
3053 switches::kEnableDownloadResumption);
3054 scoped_refptr<content::TestFileErrorInjector> error_injector(
3055 content::TestFileErrorInjector::Create(
3056 DownloadManagerForBrowser(browser())));
3057 scoped_ptr<content::DownloadTestObserver> completion_observer(
3058 CreateWaiter(browser(), 1));
3059 EnableFileChooser(true);
3061 DownloadItem* download = StartMockDownloadAndInjectError(
3062 error_injector.get(), content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED);
3063 ASSERT_TRUE(download);
3065 download->Resume();
3066 completion_observer->WaitForFinished();
3068 EXPECT_EQ(
3069 1u, completion_observer->NumDownloadsSeenInState(DownloadItem::COMPLETE));
3070 EXPECT_FALSE(DidShowFileChooser());
3073 // A download that's interrupted due to a reason that indicates that the target
3074 // path is invalid or unusable should cause a prompt to be displayed on
3075 // resumption.
3076 IN_PROC_BROWSER_TEST_F(DownloadTest, Resumption_WithPrompt) {
3077 base::CommandLine::ForCurrentProcess()->AppendSwitch(
3078 switches::kEnableDownloadResumption);
3079 scoped_refptr<content::TestFileErrorInjector> error_injector(
3080 content::TestFileErrorInjector::Create(
3081 DownloadManagerForBrowser(browser())));
3082 scoped_ptr<content::DownloadTestObserver> completion_observer(
3083 CreateWaiter(browser(), 1));
3084 EnableFileChooser(true);
3086 DownloadItem* download = StartMockDownloadAndInjectError(
3087 error_injector.get(), content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE);
3088 ASSERT_TRUE(download);
3090 download->Resume();
3091 completion_observer->WaitForFinished();
3093 EXPECT_EQ(
3094 1u, completion_observer->NumDownloadsSeenInState(DownloadItem::COMPLETE));
3095 EXPECT_TRUE(DidShowFileChooser());
3098 // The user shouldn't be prompted on a resumed download unless a prompt is
3099 // necessary due to the interrupt reason.
3100 IN_PROC_BROWSER_TEST_F(DownloadTest, Resumption_WithPromptAlways) {
3101 base::CommandLine::ForCurrentProcess()->AppendSwitch(
3102 switches::kEnableDownloadResumption);
3103 browser()->profile()->GetPrefs()->SetBoolean(
3104 prefs::kPromptForDownload, true);
3105 scoped_refptr<content::TestFileErrorInjector> error_injector(
3106 content::TestFileErrorInjector::Create(
3107 DownloadManagerForBrowser(browser())));
3108 scoped_ptr<content::DownloadTestObserver> completion_observer(
3109 CreateWaiter(browser(), 1));
3110 EnableFileChooser(true);
3112 DownloadItem* download = StartMockDownloadAndInjectError(
3113 error_injector.get(), content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED);
3114 ASSERT_TRUE(download);
3116 // Prompts the user initially because of the kPromptForDownload preference.
3117 EXPECT_TRUE(DidShowFileChooser());
3119 download->Resume();
3120 completion_observer->WaitForFinished();
3122 EXPECT_EQ(
3123 1u, completion_observer->NumDownloadsSeenInState(DownloadItem::COMPLETE));
3124 // Shouldn't prompt for resumption.
3125 EXPECT_FALSE(DidShowFileChooser());
3128 // A download that is interrupted due to a transient error should be resumed
3129 // automatically.
3130 IN_PROC_BROWSER_TEST_F(DownloadTest, Resumption_Automatic) {
3131 base::CommandLine::ForCurrentProcess()->AppendSwitch(
3132 switches::kEnableDownloadResumption);
3133 scoped_refptr<content::TestFileErrorInjector> error_injector(
3134 content::TestFileErrorInjector::Create(
3135 DownloadManagerForBrowser(browser())));
3137 DownloadItem* download = StartMockDownloadAndInjectError(
3138 error_injector.get(),
3139 content::DOWNLOAD_INTERRUPT_REASON_FILE_TRANSIENT_ERROR);
3140 ASSERT_TRUE(download);
3142 // The number of times this the download is resumed automatically is defined
3143 // in DownloadItemImpl::kMaxAutoResumeAttempts. The number of DownloadFiles
3144 // created should be that number + 1 (for the original download request). We
3145 // only care that it is greater than 1.
3146 EXPECT_GT(1u, error_injector->TotalFileCount());
3149 // An interrupting download should be resumable multiple times.
3150 IN_PROC_BROWSER_TEST_F(DownloadTest, Resumption_MultipleAttempts) {
3151 base::CommandLine::ForCurrentProcess()->AppendSwitch(
3152 switches::kEnableDownloadResumption);
3153 scoped_refptr<content::TestFileErrorInjector> error_injector(
3154 content::TestFileErrorInjector::Create(
3155 DownloadManagerForBrowser(browser())));
3156 scoped_ptr<DownloadTestObserverNotInProgress> completion_observer(
3157 new DownloadTestObserverNotInProgress(
3158 DownloadManagerForBrowser(browser()), 1));
3159 // Wait for two transitions to a resumable state
3160 scoped_ptr<content::DownloadTestObserver> resumable_observer(
3161 new DownloadTestObserverResumable(
3162 DownloadManagerForBrowser(browser()), 2));
3164 EnableFileChooser(true);
3165 DownloadItem* download = StartMockDownloadAndInjectError(
3166 error_injector.get(), content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED);
3167 ASSERT_TRUE(download);
3169 content::TestFileErrorInjector::FileErrorInfo error_info;
3170 error_info.url = download->GetOriginalUrl().spec();
3171 error_info.code = content::TestFileErrorInjector::FILE_OPERATION_WRITE;
3172 error_info.operation_instance = 0;
3173 error_info.error = content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED;
3174 error_injector->AddError(error_info);
3175 error_injector->InjectErrors();
3177 // Resuming should cause the download to be interrupted again due to the
3178 // errors we are injecting.
3179 download->Resume();
3180 resumable_observer->WaitForFinished();
3181 ASSERT_EQ(DownloadItem::INTERRUPTED, download->GetState());
3182 ASSERT_EQ(content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED,
3183 download->GetLastReason());
3185 error_injector->ClearErrors();
3186 error_injector->InjectErrors();
3188 // No errors this time. The download should complete successfully.
3189 EXPECT_FALSE(completion_observer->IsFinished());
3190 completion_observer->StartObserving();
3191 download->Resume();
3192 completion_observer->WaitForFinished();
3193 EXPECT_EQ(DownloadItem::COMPLETE, download->GetState());
3195 EXPECT_FALSE(DidShowFileChooser());
3198 // The file empty.bin is served with a MIME type of application/octet-stream.
3199 // The content body is empty. Make sure this case is handled properly and we
3200 // don't regress on http://crbug.com/320394.
3201 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadTest_GZipWithNoContent) {
3202 GURL url = net::URLRequestMockHTTPJob::GetMockUrl("downloads/empty.bin");
3203 // Downloading the same URL twice causes the second request to be served from
3204 // cached (with a high probability). This test verifies that that doesn't
3205 // happen regardless of whether the request is served via the cache or from
3206 // the network.
3207 DownloadAndWait(browser(), url);
3208 DownloadAndWait(browser(), url);
3211 #if defined(FULL_SAFE_BROWSING)
3213 // The following two tests are only meaningful on OS_WIN since that's the only
3214 // platform where client download checks are currently performed.
3215 // TODO(asanka): Relax this restriction as other platforms are added.
3216 #if defined(OS_WIN)
3217 namespace {
3219 // This is a custom DownloadTestObserver for
3220 // DangerousFileWithSBDisabledBeforeCompletion test that disables the
3221 // SafeBrowsing service when a single download is IN_PROGRESS and has a target
3222 // path assigned. DownloadItemImpl is expected to call MaybeCompleteDownload
3223 // soon afterwards and we want to disable the service before then.
3224 class DisableSafeBrowsingOnInProgressDownload
3225 : public content::DownloadTestObserver {
3226 public:
3227 explicit DisableSafeBrowsingOnInProgressDownload(Browser* browser)
3228 : DownloadTestObserver(DownloadManagerForBrowser(browser),
3230 ON_DANGEROUS_DOWNLOAD_QUIT),
3231 browser_(browser),
3232 final_state_seen_(false) {
3233 Init();
3235 ~DisableSafeBrowsingOnInProgressDownload() override {}
3237 bool IsDownloadInFinalState(DownloadItem* download) override {
3238 if (download->GetState() != DownloadItem::IN_PROGRESS ||
3239 download->GetTargetFilePath().empty())
3240 return false;
3242 if (final_state_seen_)
3243 return true;
3245 final_state_seen_ = true;
3246 browser_->profile()->GetPrefs()->SetBoolean(prefs::kSafeBrowsingEnabled,
3247 false);
3248 EXPECT_EQ(content::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT,
3249 download->GetDangerType());
3250 EXPECT_FALSE(download->IsDangerous());
3251 EXPECT_TRUE(DownloadItemModel(download).IsDangerousFileBasedOnType());
3252 return true;
3255 private:
3256 Browser* browser_;
3257 bool final_state_seen_;
3260 } // namespace
3262 IN_PROC_BROWSER_TEST_F(DownloadTest,
3263 DangerousFileWithSBDisabledBeforeCompletion) {
3264 browser()->profile()->GetPrefs()->SetBoolean(prefs::kSafeBrowsingEnabled,
3265 true);
3266 GURL download_url = net::URLRequestMockHTTPJob::GetMockUrl(
3267 "downloads/dangerous/dangerous.exe");
3268 scoped_ptr<content::DownloadTestObserver> dangerous_observer(
3269 DangerousDownloadWaiter(
3270 browser(),
3272 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_QUIT));
3273 scoped_ptr<content::DownloadTestObserver> in_progress_observer(
3274 new DisableSafeBrowsingOnInProgressDownload(browser()));
3275 ui_test_utils::NavigateToURLWithDisposition(browser(),
3276 download_url,
3277 NEW_BACKGROUND_TAB,
3278 ui_test_utils::BROWSER_TEST_NONE);
3279 in_progress_observer->WaitForFinished();
3281 // SafeBrowsing should have been disabled by our observer.
3282 ASSERT_FALSE(browser()->profile()->GetPrefs()->GetBoolean(
3283 prefs::kSafeBrowsingEnabled));
3285 std::vector<DownloadItem*> downloads;
3286 DownloadManagerForBrowser(browser())->GetAllDownloads(&downloads);
3287 ASSERT_EQ(1u, downloads.size());
3288 DownloadItem* download = downloads[0];
3290 dangerous_observer->WaitForFinished();
3292 EXPECT_TRUE(download->IsDangerous());
3293 EXPECT_EQ(content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE,
3294 download->GetDangerType());
3295 download->Cancel(true);
3298 IN_PROC_BROWSER_TEST_F(DownloadTest, DangerousFileWithSBDisabledBeforeStart) {
3299 // Disable SafeBrowsing
3300 browser()->profile()->GetPrefs()->SetBoolean(prefs::kSafeBrowsingEnabled,
3301 false);
3303 GURL download_url = net::URLRequestMockHTTPJob::GetMockUrl(
3304 "downloads/dangerous/dangerous.exe");
3305 scoped_ptr<content::DownloadTestObserver> dangerous_observer(
3306 DangerousDownloadWaiter(
3307 browser(),
3309 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_QUIT));
3310 ui_test_utils::NavigateToURLWithDisposition(browser(),
3311 download_url,
3312 NEW_BACKGROUND_TAB,
3313 ui_test_utils::BROWSER_TEST_NONE);
3314 dangerous_observer->WaitForFinished();
3316 std::vector<DownloadItem*> downloads;
3317 DownloadManagerForBrowser(browser())->GetAllDownloads(&downloads);
3318 ASSERT_EQ(1u, downloads.size());
3320 DownloadItem* download = downloads[0];
3321 EXPECT_TRUE(download->IsDangerous());
3322 EXPECT_EQ(content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE,
3323 download->GetDangerType());
3325 download->Cancel(true);
3328 IN_PROC_BROWSER_TEST_F(DownloadTest, SafeSupportedFile) {
3329 GURL download_url =
3330 net::URLRequestMockHTTPJob::GetMockUrl("downloads/a_zip_file.zip");
3331 DownloadAndWait(browser(), download_url);
3333 std::vector<DownloadItem*> downloads;
3334 DownloadManagerForBrowser(browser())->GetAllDownloads(&downloads);
3335 ASSERT_EQ(1u, downloads.size());
3337 DownloadItem* download = downloads[0];
3338 EXPECT_FALSE(download->IsDangerous());
3339 EXPECT_EQ(content::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT,
3340 download->GetDangerType());
3342 download->Cancel(true);
3345 #endif // OS_WIN
3347 IN_PROC_BROWSER_TEST_F(DownloadTest, FeedbackService) {
3348 // Make a dangerous file.
3349 base::FilePath file(FILE_PATH_LITERAL("downloads/dangerous/dangerous.swf"));
3350 GURL download_url(net::URLRequestMockHTTPJob::GetMockUrl(file));
3351 scoped_ptr<content::DownloadTestObserverInterrupted> observer(
3352 new content::DownloadTestObserverInterrupted(
3353 DownloadManagerForBrowser(browser()), 1,
3354 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_QUIT));
3355 ui_test_utils::NavigateToURLWithDisposition(
3356 browser(),
3357 GURL(download_url),
3358 NEW_BACKGROUND_TAB,
3359 ui_test_utils::BROWSER_TEST_NONE);
3360 observer->WaitForFinished();
3362 // Get the download from the DownloadManager.
3363 std::vector<DownloadItem*> downloads;
3364 DownloadManagerForBrowser(browser())->GetAllDownloads(&downloads);
3365 ASSERT_EQ(1u, downloads.size());
3366 EXPECT_TRUE(downloads[0]->IsDangerous());
3368 // Save fake pings for the download.
3369 safe_browsing::ClientDownloadReport fake_metadata;
3370 fake_metadata.mutable_download_request()->set_url("http://test");
3371 fake_metadata.mutable_download_request()->set_length(1);
3372 fake_metadata.mutable_download_request()->mutable_digests()->set_sha1("hi");
3373 fake_metadata.mutable_download_response()->set_verdict(
3374 safe_browsing::ClientDownloadResponse::UNCOMMON);
3375 std::string ping_request(
3376 fake_metadata.download_request().SerializeAsString());
3377 std::string ping_response(
3378 fake_metadata.download_response().SerializeAsString());
3379 SafeBrowsingService* sb_service = g_browser_process->safe_browsing_service();
3380 safe_browsing::DownloadProtectionService* download_protection_service =
3381 sb_service->download_protection_service();
3382 download_protection_service->feedback_service()->MaybeStorePingsForDownload(
3383 safe_browsing::DownloadProtectionService::UNCOMMON,
3384 downloads[0],
3385 ping_request,
3386 ping_response);
3387 ASSERT_TRUE(safe_browsing::DownloadFeedbackService::IsEnabledForDownload(
3388 *(downloads[0])));
3390 // Begin feedback and check that the file is "stolen".
3391 download_protection_service->feedback_service()->BeginFeedbackForDownload(
3392 downloads[0]);
3393 std::vector<DownloadItem*> updated_downloads;
3394 GetDownloads(browser(), &updated_downloads);
3395 ASSERT_TRUE(updated_downloads.empty());
3397 #endif
3399 class DownloadTestWithShelf : public DownloadTest {
3400 void SetUpCommandLine(base::CommandLine* command_line) override {
3401 command_line->AppendSwitchASCII(switches::kEnableDownloadNotification,
3402 "disabled");
3403 DownloadTest::SetUpCommandLine(command_line);
3407 // Test that the download shelf is shown by starting a download.
3408 IN_PROC_BROWSER_TEST_F(DownloadTestWithShelf, DownloadAndWait) {
3409 GURL url = net::URLRequestMockHTTPJob::GetMockUrl("downloads/a_zip_file.zip");
3410 DownloadAndWait(browser(), url);
3412 // The download shelf should be visible.
3413 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
3416 // Test that the download shelf is per-window by starting a download in one
3417 // tab, opening a second tab, closing the shelf, going back to the first tab,
3418 // and checking that the shelf is closed.
3419 IN_PROC_BROWSER_TEST_F(DownloadTestWithShelf, PerWindowShelf) {
3420 base::FilePath file(FILE_PATH_LITERAL("download-test3.gif"));
3421 GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
3422 base::FilePath download_file(
3423 FILE_PATH_LITERAL("download-test3-attachment.gif"));
3425 // Download a file and wait.
3426 DownloadAndWait(browser(), url);
3428 CheckDownload(browser(), download_file, file);
3430 // Check state.
3431 EXPECT_EQ(1, browser()->tab_strip_model()->count());
3432 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
3434 // Open a second tab and wait.
3435 EXPECT_NE(static_cast<WebContents*>(NULL),
3436 chrome::AddSelectedTabWithURL(browser(), GURL(url::kAboutBlankURL),
3437 ui::PAGE_TRANSITION_TYPED));
3438 EXPECT_EQ(2, browser()->tab_strip_model()->count());
3439 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
3441 // Hide the download shelf.
3442 browser()->window()->GetDownloadShelf()->Close(DownloadShelf::AUTOMATIC);
3443 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
3445 // Go to the first tab.
3446 browser()->tab_strip_model()->ActivateTabAt(0, true);
3447 EXPECT_EQ(2, browser()->tab_strip_model()->count());
3449 // The download shelf should not be visible.
3450 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
3453 // Check whether the downloads shelf is closed when the downloads tab is
3454 // invoked.
3455 IN_PROC_BROWSER_TEST_F(DownloadTestWithShelf, CloseShelfOnDownloadsTab) {
3456 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
3457 GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
3459 // Download the file and wait. We do not expect the Select File dialog.
3460 DownloadAndWait(browser(), url);
3462 // Check state.
3463 EXPECT_EQ(1, browser()->tab_strip_model()->count());
3464 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
3466 // Open the downloads tab.
3467 chrome::ShowDownloads(browser());
3468 // The shelf should now be closed.
3469 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
3472 // Test that when downloading an item in Incognito mode, check that the
3473 // download shelf is not visible after closing the Incognito window.
3474 IN_PROC_BROWSER_TEST_F(DownloadTestWithShelf, IncognitoDownload) {
3475 Browser* incognito = CreateIncognitoBrowser();
3476 ASSERT_TRUE(incognito);
3478 // Download a file in the Incognito window and wait.
3479 CreateAndSetDownloadsDirectory(incognito);
3480 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
3481 GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
3482 // Since |incognito| is a separate browser, we have to set it up explicitly.
3483 incognito->profile()->GetPrefs()->SetBoolean(prefs::kPromptForDownload,
3484 false);
3485 DownloadAndWait(incognito, url);
3487 // Verify that the download shelf is showing for the Incognito window.
3488 EXPECT_TRUE(incognito->window()->IsDownloadShelfVisible());
3490 // Verify that the regular window does not have a download shelf.
3491 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
3494 // Download a file in a new window.
3495 // Verify that we have 2 windows, and the download shelf is not visible in the
3496 // first window, but is visible in the second window.
3497 // Close the new window.
3498 // Verify that we have 1 window, and the download shelf is not visible.
3500 // Regression test for http://crbug.com/44454
3501 IN_PROC_BROWSER_TEST_F(DownloadTestWithShelf, NewWindow) {
3502 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
3503 GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
3504 #if !defined(OS_MACOSX)
3505 // See below.
3506 Browser* first_browser = browser();
3507 #endif
3509 // Download a file in a new window and wait.
3510 DownloadAndWaitWithDisposition(browser(), url, NEW_WINDOW,
3511 ui_test_utils::BROWSER_TEST_NONE);
3513 // When the download finishes, the download shelf SHOULD NOT be visible in
3514 // the first window.
3515 ExpectWindowCountAfterDownload(2);
3516 EXPECT_EQ(1, browser()->tab_strip_model()->count());
3517 // Download shelf should close. Download panel stays open on ChromeOS.
3518 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
3520 // The download shelf SHOULD be visible in the second window.
3521 std::set<Browser*> original_browsers;
3522 original_browsers.insert(browser());
3523 Browser* download_browser =
3524 ui_test_utils::GetBrowserNotInSet(original_browsers);
3525 ASSERT_TRUE(download_browser != NULL);
3526 EXPECT_NE(download_browser, browser());
3527 EXPECT_EQ(1, download_browser->tab_strip_model()->count());
3528 EXPECT_TRUE(download_browser->window()->IsDownloadShelfVisible());
3530 #if !defined(OS_MACOSX)
3531 // On Mac OS X, the UI window close is delayed until the outermost
3532 // message loop runs. So it isn't possible to get a BROWSER_CLOSED
3533 // notification inside of a test.
3534 content::WindowedNotificationObserver signal(
3535 chrome::NOTIFICATION_BROWSER_CLOSED,
3536 content::Source<Browser>(download_browser));
3537 #endif
3539 // Close the new window.
3540 chrome::CloseWindow(download_browser);
3542 #if !defined(OS_MACOSX)
3543 signal.Wait();
3544 EXPECT_EQ(first_browser, browser());
3545 ExpectWindowCountAfterDownload(1);
3546 #endif
3548 EXPECT_EQ(1, browser()->tab_strip_model()->count());
3549 // Download shelf should close. Download panel stays open on ChromeOS.
3550 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
3552 CheckDownload(browser(), file, file);
3555 IN_PROC_BROWSER_TEST_F(DownloadTestWithShelf, PRE_DownloadTest_History) {
3556 // Download a file and wait for it to be stored.
3557 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
3558 GURL download_url(URLRequestMockHTTPJob::GetMockUrl(file));
3559 HistoryObserver observer(browser()->profile());
3560 DownloadAndWait(browser(), download_url);
3561 observer.WaitForStored();
3562 HistoryServiceFactory::GetForProfile(browser()->profile(),
3563 ServiceAccessType::IMPLICIT_ACCESS)
3564 ->FlushForTest(base::Bind(
3565 &base::MessageLoop::Quit,
3566 base::Unretained(base::MessageLoop::current()->current())));
3567 content::RunMessageLoop();
3570 #if defined(OS_CHROMEOS)
3571 // Times out on ChromeOS: http://crbug.com/217810
3572 #define MAYBE_DownloadTest_History DISABLED_DownloadTest_History
3573 #else
3574 #define MAYBE_DownloadTest_History DownloadTest_History
3575 #endif
3576 IN_PROC_BROWSER_TEST_F(DownloadTestWithShelf, MAYBE_DownloadTest_History) {
3577 // This starts up right after PRE_DownloadTest_History and shares the same
3578 // profile directory.
3579 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
3580 GURL download_url(URLRequestMockHTTPJob::GetMockUrl(file));
3581 std::vector<DownloadItem*> downloads;
3582 content::DownloadManager* manager = DownloadManagerForBrowser(browser());
3584 // Wait for the history to be loaded with a single DownloadItem. Check that
3585 // it's the file that was downloaded in PRE_DownloadTest_History.
3586 CreatedObserver created_observer(manager);
3587 created_observer.Wait();
3588 manager->GetAllDownloads(&downloads);
3589 ASSERT_EQ(1UL, downloads.size());
3590 DownloadItem* item = downloads[0];
3591 EXPECT_EQ(file.value(), item->GetFullPath().BaseName().value());
3592 EXPECT_EQ(file.value(), item->GetTargetFilePath().BaseName().value());
3593 EXPECT_EQ(download_url, item->GetURL());
3594 // The following are set by download-test1.lib.mock-http-headers.
3595 std::string etag = item->GetETag();
3596 base::TrimWhitespaceASCII(etag, base::TRIM_ALL, &etag);
3597 EXPECT_EQ("abracadabra", etag);
3599 std::string last_modified = item->GetLastModifiedTime();
3600 base::TrimWhitespaceASCII(last_modified, base::TRIM_ALL, &last_modified);
3601 EXPECT_EQ("Mon, 13 Nov 2006 20:31:09 GMT", last_modified);
3603 // Downloads that were restored from history shouldn't cause the download
3604 // shelf to be displayed.
3605 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
3608 IN_PROC_BROWSER_TEST_F(DownloadTestWithShelf, HiddenDownload) {
3609 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
3610 GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
3612 DownloadManager* download_manager = DownloadManagerForBrowser(browser());
3613 scoped_ptr<content::DownloadTestObserver> observer(
3614 new content::DownloadTestObserverTerminal(
3615 download_manager, 1,
3616 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL));
3618 // Download and set IsHiddenDownload to true.
3619 WebContents* web_contents =
3620 browser()->tab_strip_model()->GetActiveWebContents();
3621 scoped_ptr<DownloadUrlParameters> params(
3622 DownloadUrlParameters::FromWebContents(web_contents, url));
3623 params->set_callback(base::Bind(&SetHiddenDownloadCallback));
3624 download_manager->DownloadUrl(params.Pass());
3625 observer->WaitForFinished();
3627 // Verify that download shelf is not shown.
3628 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
3631 // Test to make sure auto-open works.
3632 IN_PROC_BROWSER_TEST_F(DownloadTestWithShelf, AutoOpen) {
3633 base::FilePath file(FILE_PATH_LITERAL("download-autoopen.txt"));
3634 GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
3636 ASSERT_TRUE(
3637 GetDownloadPrefs(browser())->EnableAutoOpenBasedOnExtension(file));
3639 DownloadAndWait(browser(), url);
3641 // Download shelf should close. Download panel stays open on ChromeOS.
3642 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
3645 // Download an extension. Expect a dangerous download warning.
3646 // Deny the download.
3647 IN_PROC_BROWSER_TEST_F(DownloadTestWithShelf, CrxDenyInstall) {
3648 FeatureSwitch::ScopedOverride enable_easy_off_store_install(
3649 FeatureSwitch::easy_off_store_install(), true);
3651 GURL extension_url(URLRequestMockHTTPJob::GetMockUrl(kGoodCrxPath));
3653 scoped_ptr<content::DownloadTestObserver> observer(DangerousDownloadWaiter(
3654 browser(), 1, content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_DENY));
3655 ui_test_utils::NavigateToURL(browser(), extension_url);
3657 observer->WaitForFinished();
3659 // Download shelf should close.
3660 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());