1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
8 #include "base/bind_helpers.h"
9 #include "base/command_line.h"
10 #include "base/files/file.h"
11 #include "base/files/file_path.h"
12 #include "base/files/file_util.h"
13 #include "base/files/scoped_temp_dir.h"
14 #include "base/memory/ref_counted.h"
15 #include "base/path_service.h"
16 #include "base/prefs/pref_service.h"
17 #include "base/stl_util.h"
18 #include "base/strings/string_number_conversions.h"
19 #include "base/strings/string_split.h"
20 #include "base/strings/string_util.h"
21 #include "base/strings/stringprintf.h"
22 #include "base/strings/utf_string_conversions.h"
23 #include "base/sys_info.h"
24 #include "base/test/test_file_util.h"
25 #include "chrome/app/chrome_command_ids.h"
26 #include "chrome/browser/browser_process.h"
27 #include "chrome/browser/chrome_notification_types.h"
28 #include "chrome/browser/download/chrome_download_manager_delegate.h"
29 #include "chrome/browser/download/download_browsertest.h"
30 #include "chrome/browser/download/download_crx_util.h"
31 #include "chrome/browser/download/download_history.h"
32 #include "chrome/browser/download/download_item_model.h"
33 #include "chrome/browser/download/download_prefs.h"
34 #include "chrome/browser/download/download_request_limiter.h"
35 #include "chrome/browser/download/download_service.h"
36 #include "chrome/browser/download/download_service_factory.h"
37 #include "chrome/browser/download/download_shelf.h"
38 #include "chrome/browser/download/download_target_determiner.h"
39 #include "chrome/browser/download/download_test_file_activity_observer.h"
40 #include "chrome/browser/extensions/extension_install_prompt.h"
41 #include "chrome/browser/extensions/extension_install_prompt_show_params.h"
42 #include "chrome/browser/extensions/extension_service.h"
43 #include "chrome/browser/history/history_service_factory.h"
44 #include "chrome/browser/infobars/infobar_service.h"
45 #include "chrome/browser/net/url_request_mock_util.h"
46 #include "chrome/browser/profiles/profile.h"
47 #include "chrome/browser/renderer_context_menu/render_view_context_menu_browsertest_util.h"
48 #include "chrome/browser/renderer_context_menu/render_view_context_menu_test_util.h"
49 #include "chrome/browser/ui/browser.h"
50 #include "chrome/browser/ui/browser_commands.h"
51 #include "chrome/browser/ui/browser_finder.h"
52 #include "chrome/browser/ui/browser_list.h"
53 #include "chrome/browser/ui/browser_tabstrip.h"
54 #include "chrome/browser/ui/browser_window.h"
55 #include "chrome/browser/ui/chrome_pages.h"
56 #include "chrome/browser/ui/host_desktop.h"
57 #include "chrome/browser/ui/tabs/tab_strip_model.h"
58 #include "chrome/browser/ui/website_settings/mock_permission_bubble_view.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/spawned_test_server/spawned_test_server.h"
95 #include "net/test/url_request/url_request_mock_http_job.h"
96 #include "net/test/url_request/url_request_slow_download_job.h"
97 #include "testing/gtest/include/gtest/gtest.h"
98 #include "ui/base/l10n/l10n_util.h"
99 #include "ui/base/page_transition_types.h"
101 #if defined(FULL_SAFE_BROWSING)
102 #include "chrome/browser/safe_browsing/download_feedback_service.h"
103 #include "chrome/browser/safe_browsing/download_protection_service.h"
104 #include "chrome/browser/safe_browsing/safe_browsing_database.h"
105 #include "chrome/browser/safe_browsing/safe_browsing_service.h"
108 using content::BrowserContext
;
109 using content::BrowserThread
;
110 using content::DownloadItem
;
111 using content::DownloadManager
;
112 using content::DownloadUrlParameters
;
113 using content::WebContents
;
114 using extensions::Extension
;
115 using extensions::FeatureSwitch
;
116 using net::URLRequestMockHTTPJob
;
120 class CreatedObserver
: public content::DownloadManager::Observer
{
122 explicit CreatedObserver(content::DownloadManager
* manager
)
125 manager
->AddObserver(this);
127 ~CreatedObserver() override
{
129 manager_
->RemoveObserver(this);
133 std::vector
<DownloadItem
*> downloads
;
134 manager_
->GetAllDownloads(&downloads
);
135 if (!downloads
.empty())
138 content::RunMessageLoop();
143 void OnDownloadCreated(content::DownloadManager
* manager
,
144 content::DownloadItem
* item
) override
{
145 DCHECK_EQ(manager_
, manager
);
147 base::MessageLoopForUI::current()->Quit();
150 content::DownloadManager
* manager_
;
153 DISALLOW_COPY_AND_ASSIGN(CreatedObserver
);
156 class PercentWaiter
: public content::DownloadItem::Observer
{
158 explicit PercentWaiter(DownloadItem
* item
)
163 item_
->AddObserver(this);
165 ~PercentWaiter() override
{
167 item_
->RemoveObserver(this);
170 bool WaitForFinished() {
171 if (item_
->GetState() == DownloadItem::COMPLETE
) {
172 return item_
->PercentComplete() == 100;
175 content::RunMessageLoop();
181 void OnDownloadUpdated(content::DownloadItem
* item
) override
{
182 DCHECK_EQ(item_
, item
);
184 ((prev_percent_
> item_
->PercentComplete()) ||
185 (item_
->GetState() == DownloadItem::COMPLETE
&&
186 (item_
->PercentComplete() != 100)))) {
189 base::MessageLoopForUI::current()->Quit();
191 if (item_
->GetState() == DownloadItem::COMPLETE
&& waiting_
)
192 base::MessageLoopForUI::current()->Quit();
195 void OnDownloadDestroyed(content::DownloadItem
* item
) override
{
196 DCHECK_EQ(item_
, item
);
197 item_
->RemoveObserver(this);
201 content::DownloadItem
* item_
;
206 DISALLOW_COPY_AND_ASSIGN(PercentWaiter
);
209 // DownloadTestObserver subclass that observes one download until it transitions
210 // from a non-resumable state to a resumable state a specified number of
211 // times. Note that this observer can only observe a single download.
212 class DownloadTestObserverResumable
: public content::DownloadTestObserver
{
214 // Construct a new observer. |transition_count| is the number of times the
215 // download should transition from a non-resumable state to a resumable state.
216 DownloadTestObserverResumable(DownloadManager
* download_manager
,
217 size_t transition_count
)
218 : DownloadTestObserver(download_manager
, 1,
219 ON_DANGEROUS_DOWNLOAD_FAIL
),
220 was_previously_resumable_(false),
221 transitions_left_(transition_count
) {
224 ~DownloadTestObserverResumable() override
{}
227 bool IsDownloadInFinalState(DownloadItem
* download
) override
{
228 bool is_resumable_now
= download
->CanResume();
229 if (!was_previously_resumable_
&& is_resumable_now
)
231 was_previously_resumable_
= is_resumable_now
;
232 return transitions_left_
== 0;
235 bool was_previously_resumable_
;
236 size_t transitions_left_
;
238 DISALLOW_COPY_AND_ASSIGN(DownloadTestObserverResumable
);
241 // IDs and paths of CRX files used in tests.
242 const char kGoodCrxId
[] = "ldnnhddmnhbkjipkidpdiheffobcpfmf";
243 const base::FilePath
kGoodCrxPath(FILE_PATH_LITERAL("extensions/good.crx"));
245 const char kLargeThemeCrxId
[] = "pjpgmfcmabopnnfonnhmdjglfpjjfkbf";
246 const base::FilePath
kLargeThemePath(
247 FILE_PATH_LITERAL("extensions/theme2.crx"));
249 // Get History Information.
250 class DownloadsHistoryDataCollector
{
252 explicit DownloadsHistoryDataCollector(Profile
* profile
)
253 : profile_(profile
), result_valid_(false) {}
255 bool WaitForDownloadInfo(
256 scoped_ptr
<std::vector
<history::DownloadRow
> >* results
) {
257 history::HistoryService
* hs
= HistoryServiceFactory::GetForProfile(
258 profile_
, ServiceAccessType::EXPLICIT_ACCESS
);
261 base::Bind(&DownloadsHistoryDataCollector::OnQueryDownloadsComplete
,
262 base::Unretained(this)));
264 content::RunMessageLoop();
266 *results
= results_
.Pass();
268 return result_valid_
;
272 void OnQueryDownloadsComplete(
273 scoped_ptr
<std::vector
<history::DownloadRow
> > entries
) {
274 result_valid_
= true;
275 results_
= entries
.Pass();
276 base::MessageLoopForUI::current()->Quit();
280 scoped_ptr
<std::vector
<history::DownloadRow
> > results_
;
283 DISALLOW_COPY_AND_ASSIGN(DownloadsHistoryDataCollector
);
286 // Mock that simulates a permissions dialog where the user denies
287 // permission to install. TODO(skerner): This could be shared with
288 // extensions tests. Find a common place for this class.
289 class MockAbortExtensionInstallPrompt
: public ExtensionInstallPrompt
{
291 MockAbortExtensionInstallPrompt() :
292 ExtensionInstallPrompt(NULL
) {
295 // Simulate a user abort on an extension installation.
296 void ConfirmInstall(Delegate
* delegate
,
297 const Extension
* extension
,
298 const ShowDialogCallback
& show_dialog_callback
) override
{
299 delegate
->InstallUIAbort(true);
300 base::MessageLoopForUI::current()->Quit();
303 void OnInstallSuccess(const Extension
* extension
, SkBitmap
* icon
) override
{}
304 void OnInstallFailure(const extensions::CrxInstallError
& error
) override
{}
307 // Mock that simulates a permissions dialog where the user allows
309 class MockAutoConfirmExtensionInstallPrompt
: public ExtensionInstallPrompt
{
311 explicit MockAutoConfirmExtensionInstallPrompt(
312 content::WebContents
* web_contents
)
313 : ExtensionInstallPrompt(web_contents
) {}
315 // Proceed without confirmation prompt.
316 void ConfirmInstall(Delegate
* delegate
,
317 const Extension
* extension
,
318 const ShowDialogCallback
& show_dialog_callback
) override
{
319 delegate
->InstallUIProceed();
322 void OnInstallSuccess(const Extension
* extension
, SkBitmap
* icon
) override
{}
323 void OnInstallFailure(const extensions::CrxInstallError
& error
) override
{}
326 static DownloadManager
* DownloadManagerForBrowser(Browser
* browser
) {
327 return BrowserContext::GetDownloadManager(browser
->profile());
330 bool WasAutoOpened(DownloadItem
* item
) {
331 return item
->GetAutoOpened();
334 // Called when a download starts. Marks the download as hidden.
335 void SetHiddenDownloadCallback(DownloadItem
* item
,
336 content::DownloadInterruptReason reason
) {
337 DownloadItemModel(item
).SetShouldShowInShelf(false);
340 // Callback for HistoryObserver; used in DownloadHistoryCheck
341 bool HasDataAndName(const history::DownloadRow
& row
) {
342 return row
.received_bytes
> 0 && !row
.target_path
.empty();
347 DownloadTestObserverNotInProgress::DownloadTestObserverNotInProgress(
348 DownloadManager
* download_manager
,
350 : DownloadTestObserver(download_manager
, count
, ON_DANGEROUS_DOWNLOAD_FAIL
),
351 started_observing_(false) {
355 DownloadTestObserverNotInProgress::~DownloadTestObserverNotInProgress() {}
357 void DownloadTestObserverNotInProgress::StartObserving() {
358 started_observing_
= true;
361 bool DownloadTestObserverNotInProgress::IsDownloadInFinalState(
362 DownloadItem
* download
) {
363 return started_observing_
&&
364 download
->GetState() != DownloadItem::IN_PROGRESS
;
367 class HistoryObserver
: public DownloadHistory::Observer
{
369 typedef base::Callback
<bool(const history::DownloadRow
&)> FilterCallback
;
371 explicit HistoryObserver(Profile
* profile
)
374 seen_stored_(false) {
375 DownloadServiceFactory::GetForBrowserContext(profile_
)->
376 GetDownloadHistory()->AddObserver(this);
379 ~HistoryObserver() override
{
380 DownloadService
* service
= DownloadServiceFactory::GetForBrowserContext(
382 if (service
&& service
->GetDownloadHistory())
383 service
->GetDownloadHistory()->RemoveObserver(this);
386 void SetFilterCallback(const FilterCallback
& callback
) {
387 callback_
= callback
;
390 void OnDownloadStored(content::DownloadItem
* item
,
391 const history::DownloadRow
& info
) override
{
392 if (!callback_
.is_null() && (!callback_
.Run(info
)))
397 base::MessageLoopForUI::current()->Quit();
400 void OnDownloadHistoryDestroyed() override
{
401 DownloadServiceFactory::GetForBrowserContext(profile_
)->
402 GetDownloadHistory()->RemoveObserver(this);
405 void WaitForStored() {
409 content::RunMessageLoop();
417 FilterCallback callback_
;
419 DISALLOW_COPY_AND_ASSIGN(HistoryObserver
);
422 class DownloadTest
: public InProcessBrowserTest
{
424 // Choice of navigation or direct fetch. Used by |DownloadFileCheckErrors()|.
425 enum DownloadMethod
{
430 // Information passed in to |DownloadFileCheckErrors()|.
431 struct DownloadInfo
{
432 const char* url_name
; // URL for the download.
433 DownloadMethod download_method
; // Navigation or Direct.
434 // Download interrupt reason (NONE is OK).
435 content::DownloadInterruptReason reason
;
436 bool show_download_item
; // True if the download item appears on the shelf.
437 bool should_redirect_to_documents
; // True if we save it in "My Documents".
440 struct FileErrorInjectInfo
{
441 DownloadInfo download_info
;
442 content::TestFileErrorInjector::FileErrorInfo error_info
;
447 void SetUpOnMainThread() override
{
448 BrowserThread::PostTask(
449 BrowserThread::IO
, FROM_HERE
,
450 base::Bind(&chrome_browser_net::SetUrlRequestMocksEnabled
, true));
451 ASSERT_TRUE(InitialSetup());
454 void TearDownOnMainThread() override
{
455 // Needs to be torn down on the main thread. file_activity_observer_ holds a
456 // reference to the ChromeDownloadManagerDelegate which should be destroyed
458 file_activity_observer_
.reset();
461 void SetUpCommandLine(base::CommandLine
* command_line
) override
{
462 command_line
->AppendSwitch(switches::kDisablePluginsDiscovery
);
465 // Returning false indicates a failure of the setup, and should be asserted
467 virtual bool InitialSetup() {
468 bool have_test_dir
= PathService::Get(chrome::DIR_TEST_DATA
, &test_dir_
);
469 EXPECT_TRUE(have_test_dir
);
473 // Sanity check default values for window / tab count and shelf visibility.
474 int window_count
= chrome::GetTotalBrowserCount();
475 EXPECT_EQ(1, window_count
);
476 EXPECT_EQ(1, browser()->tab_strip_model()->count());
477 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
479 // Set up the temporary download folder.
480 bool created_downloads_dir
= CreateAndSetDownloadsDirectory(browser());
481 EXPECT_TRUE(created_downloads_dir
);
482 if (!created_downloads_dir
)
484 browser()->profile()->GetPrefs()->SetBoolean(
485 prefs::kPromptForDownload
, false);
487 DownloadManager
* manager
= DownloadManagerForBrowser(browser());
488 DownloadPrefs::FromDownloadManager(manager
)->ResetAutoOpen();
489 manager
->RemoveAllDownloads();
491 file_activity_observer_
.reset(
492 new DownloadTestFileActivityObserver(browser()->profile()));
499 SIZE_TEST_TYPE_KNOWN
,
500 SIZE_TEST_TYPE_UNKNOWN
,
503 base::FilePath
GetDownloadsDirectory() {
504 return downloads_directory_
.path();
507 // Location of the file source (the place from which it is downloaded).
508 base::FilePath
OriginFile(base::FilePath file
) {
509 return test_dir_
.Append(file
);
512 // Location of the file destination (place to which it is downloaded).
513 base::FilePath
DestinationFile(Browser
* browser
, base::FilePath file
) {
514 return GetDownloadDirectory(browser
).Append(file
.BaseName());
517 // Must be called after browser creation. Creates a temporary
518 // directory for downloads that is auto-deleted on destruction.
519 // Returning false indicates a failure of the function, and should be asserted
521 bool CreateAndSetDownloadsDirectory(Browser
* browser
) {
525 if (!downloads_directory_
.CreateUniqueTempDir())
528 browser
->profile()->GetPrefs()->SetFilePath(
529 prefs::kDownloadDefaultDirectory
,
530 downloads_directory_
.path());
531 browser
->profile()->GetPrefs()->SetFilePath(
532 prefs::kSaveFileDefaultDirectory
,
533 downloads_directory_
.path());
538 DownloadPrefs
* GetDownloadPrefs(Browser
* browser
) {
539 return DownloadPrefs::FromDownloadManager(
540 DownloadManagerForBrowser(browser
));
543 base::FilePath
GetDownloadDirectory(Browser
* browser
) {
544 return GetDownloadPrefs(browser
)->DownloadPath();
547 // Create a DownloadTestObserverTerminal that will wait for the
548 // specified number of downloads to finish.
549 content::DownloadTestObserver
* CreateWaiter(
550 Browser
* browser
, int num_downloads
) {
551 DownloadManager
* download_manager
= DownloadManagerForBrowser(browser
);
552 return new content::DownloadTestObserverTerminal(
553 download_manager
, num_downloads
,
554 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL
);
557 // Create a DownloadTestObserverInProgress that will wait for the
558 // specified number of downloads to start.
559 content::DownloadTestObserver
* CreateInProgressWaiter(
560 Browser
* browser
, int num_downloads
) {
561 DownloadManager
* download_manager
= DownloadManagerForBrowser(browser
);
562 return new content::DownloadTestObserverInProgress(
563 download_manager
, num_downloads
);
566 // Create a DownloadTestObserverTerminal that will wait for the
567 // specified number of downloads to finish, or for
568 // a dangerous download warning to be shown.
569 content::DownloadTestObserver
* DangerousDownloadWaiter(
572 content::DownloadTestObserver::DangerousDownloadAction
573 dangerous_download_action
) {
574 DownloadManager
* download_manager
= DownloadManagerForBrowser(browser
);
575 return new content::DownloadTestObserverTerminal(
576 download_manager
, num_downloads
, dangerous_download_action
);
579 void CheckDownloadStatesForBrowser(Browser
* browser
,
581 DownloadItem::DownloadState state
) {
582 std::vector
<DownloadItem
*> download_items
;
583 GetDownloads(browser
, &download_items
);
585 EXPECT_EQ(num
, download_items
.size());
587 for (size_t i
= 0; i
< download_items
.size(); ++i
) {
588 EXPECT_EQ(state
, download_items
[i
]->GetState()) << " Item " << i
;
592 void CheckDownloadStates(size_t num
, DownloadItem::DownloadState state
) {
593 CheckDownloadStatesForBrowser(browser(), num
, state
);
596 // Download |url|, then wait for the download to finish.
597 // |disposition| indicates where the navigation occurs (current tab, new
598 // foreground tab, etc).
599 // |browser_test_flags| indicate what to wait for, and is an OR of 0 or more
600 // values in the ui_test_utils::BrowserTestWaitFlags enum.
601 void DownloadAndWaitWithDisposition(Browser
* browser
,
603 WindowOpenDisposition disposition
,
604 int browser_test_flags
) {
605 // Setup notification, navigate, and block.
606 scoped_ptr
<content::DownloadTestObserver
> observer(
607 CreateWaiter(browser
, 1));
608 // This call will block until the condition specified by
609 // |browser_test_flags|, but will not wait for the download to finish.
610 ui_test_utils::NavigateToURLWithDisposition(browser
,
614 // Waits for the download to complete.
615 observer
->WaitForFinished();
616 EXPECT_EQ(1u, observer
->NumDownloadsSeenInState(DownloadItem::COMPLETE
));
617 // We don't expect a file chooser to be shown.
618 EXPECT_FALSE(DidShowFileChooser());
621 // Download a file in the current tab, then wait for the download to finish.
622 void DownloadAndWait(Browser
* browser
,
624 DownloadAndWaitWithDisposition(
628 ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION
);
631 // Should only be called when the download is known to have finished
632 // (in error or not).
633 // Returning false indicates a failure of the function, and should be asserted
635 bool CheckDownload(Browser
* browser
,
636 const base::FilePath
& downloaded_filename
,
637 const base::FilePath
& origin_filename
) {
638 // Find the path to which the data will be downloaded.
639 base::FilePath
downloaded_file(
640 DestinationFile(browser
, downloaded_filename
));
642 // Find the origin path (from which the data comes).
643 base::FilePath
origin_file(OriginFile(origin_filename
));
644 return CheckDownloadFullPaths(browser
, downloaded_file
, origin_file
);
647 // A version of CheckDownload that allows complete path specification.
648 bool CheckDownloadFullPaths(Browser
* browser
,
649 const base::FilePath
& downloaded_file
,
650 const base::FilePath
& origin_file
) {
651 bool origin_file_exists
= base::PathExists(origin_file
);
652 EXPECT_TRUE(origin_file_exists
) << origin_file
.value();
653 if (!origin_file_exists
)
656 // Confirm the downloaded data file exists.
657 bool downloaded_file_exists
= base::PathExists(downloaded_file
);
658 EXPECT_TRUE(downloaded_file_exists
) << downloaded_file
.value();
659 if (!downloaded_file_exists
)
662 int64 origin_file_size
= 0;
663 EXPECT_TRUE(base::GetFileSize(origin_file
, &origin_file_size
));
664 std::string original_file_contents
;
665 EXPECT_TRUE(base::ReadFileToString(origin_file
, &original_file_contents
));
667 VerifyFile(downloaded_file
, original_file_contents
, origin_file_size
));
669 // Delete the downloaded copy of the file.
670 bool downloaded_file_deleted
= base::DieFileDie(downloaded_file
, false);
671 EXPECT_TRUE(downloaded_file_deleted
);
672 return downloaded_file_deleted
;
675 content::DownloadTestObserver
* CreateInProgressDownloadObserver(
676 size_t download_count
) {
677 DownloadManager
* manager
= DownloadManagerForBrowser(browser());
678 return new content::DownloadTestObserverInProgress(
679 manager
, download_count
);
682 DownloadItem
* CreateSlowTestDownload() {
683 scoped_ptr
<content::DownloadTestObserver
> observer(
684 CreateInProgressDownloadObserver(1));
685 GURL
slow_download_url(net::URLRequestSlowDownloadJob::kUnknownSizeUrl
);
686 DownloadManager
* manager
= DownloadManagerForBrowser(browser());
688 EXPECT_EQ(0, manager
->NonMaliciousInProgressCount());
689 EXPECT_EQ(0, manager
->InProgressCount());
690 if (manager
->InProgressCount() != 0)
693 ui_test_utils::NavigateToURL(browser(), slow_download_url
);
695 observer
->WaitForFinished();
696 EXPECT_EQ(1u, observer
->NumDownloadsSeenInState(DownloadItem::IN_PROGRESS
));
698 DownloadManager::DownloadVector items
;
699 manager
->GetAllDownloads(&items
);
701 DownloadItem
* new_item
= NULL
;
702 for (DownloadManager::DownloadVector::iterator iter
= items
.begin();
703 iter
!= items
.end(); ++iter
) {
704 if ((*iter
)->GetState() == DownloadItem::IN_PROGRESS
) {
705 // There should be only one IN_PROGRESS item.
706 EXPECT_EQ(NULL
, new_item
);
713 bool RunSizeTest(Browser
* browser
,
715 const std::string
& partial_indication
,
716 const std::string
& total_indication
) {
717 EXPECT_TRUE(type
== SIZE_TEST_TYPE_UNKNOWN
|| type
== SIZE_TEST_TYPE_KNOWN
);
718 if (type
!= SIZE_TEST_TYPE_KNOWN
&& type
!= SIZE_TEST_TYPE_UNKNOWN
)
720 GURL
url(type
== SIZE_TEST_TYPE_KNOWN
?
721 net::URLRequestSlowDownloadJob::kKnownSizeUrl
:
722 net::URLRequestSlowDownloadJob::kUnknownSizeUrl
);
724 // TODO(ahendrickson) -- |expected_title_in_progress| and
725 // |expected_title_finished| need to be checked.
726 base::FilePath filename
;
727 net::FileURLToFilePath(url
, &filename
);
728 base::string16
expected_title_in_progress(
729 base::ASCIIToUTF16(partial_indication
) + filename
.LossyDisplayName());
730 base::string16
expected_title_finished(
731 base::ASCIIToUTF16(total_indication
) + filename
.LossyDisplayName());
733 // Download a partial web page in a background tab and wait.
734 // The mock system will not complete until it gets a special URL.
735 scoped_ptr
<content::DownloadTestObserver
> observer(
736 CreateWaiter(browser
, 1));
737 ui_test_utils::NavigateToURL(browser
, url
);
739 // TODO(ahendrickson): check download status text before downloading.
741 // - Add a member function to the |DownloadShelf| interface class, that
742 // indicates how many members it has.
743 // - Add a member function to |DownloadShelf| to get the status text
744 // of a given member (for example, via the name in |DownloadItemView|'s
745 // GetAccessibleState() member function), by index.
746 // - Iterate over browser->window()->GetDownloadShelf()'s members
747 // to see if any match the status text we want. Start with the last one.
749 // Allow the request to finish. We do this by loading a second URL in a
751 GURL
finish_url(net::URLRequestSlowDownloadJob::kFinishDownloadUrl
);
752 ui_test_utils::NavigateToURLWithDisposition(
756 ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION
);
757 observer
->WaitForFinished();
758 EXPECT_EQ(1u, observer
->NumDownloadsSeenInState(DownloadItem::COMPLETE
));
759 CheckDownloadStatesForBrowser(browser
, 1, DownloadItem::COMPLETE
);
761 EXPECT_EQ(2, browser
->tab_strip_model()->count());
763 // TODO(ahendrickson): check download status text after downloading.
765 base::FilePath
basefilename(filename
.BaseName());
766 net::FileURLToFilePath(url
, &filename
);
767 base::FilePath download_path
=
768 downloads_directory_
.path().Append(basefilename
);
769 EXPECT_TRUE(browser
->window()->IsDownloadShelfVisible());
771 bool downloaded_path_exists
= base::PathExists(download_path
);
772 EXPECT_TRUE(downloaded_path_exists
);
773 if (!downloaded_path_exists
)
776 // Check the file contents.
777 size_t file_size
= net::URLRequestSlowDownloadJob::kFirstDownloadSize
+
778 net::URLRequestSlowDownloadJob::kSecondDownloadSize
;
779 std::string
expected_contents(file_size
, '*');
780 EXPECT_TRUE(VerifyFile(download_path
, expected_contents
, file_size
));
782 // Delete the file we just downloaded.
783 EXPECT_TRUE(base::DieFileDie(download_path
, true));
784 EXPECT_FALSE(base::PathExists(download_path
));
789 void GetDownloads(Browser
* browser
, std::vector
<DownloadItem
*>* downloads
) {
791 DownloadManager
* manager
= DownloadManagerForBrowser(browser
);
792 manager
->GetAllDownloads(downloads
);
795 static void ExpectWindowCountAfterDownload(size_t expected
) {
796 EXPECT_EQ(expected
, chrome::GetTotalBrowserCount());
799 void EnableFileChooser(bool enable
) {
800 file_activity_observer_
->EnableFileChooser(enable
);
803 bool DidShowFileChooser() {
804 return file_activity_observer_
->TestAndResetDidShowFileChooser();
807 // Checks that |path| is has |file_size| bytes, and matches the |value|
809 bool VerifyFile(const base::FilePath
& path
,
810 const std::string
& value
,
811 const int64 file_size
) {
812 std::string file_contents
;
814 bool read
= base::ReadFileToString(path
, &file_contents
);
815 EXPECT_TRUE(read
) << "Failed reading file: " << path
.value() << std::endl
;
817 return false; // Couldn't read the file.
819 // Note: we don't handle really large files (more than size_t can hold)
820 // so we will fail in that case.
821 size_t expected_size
= static_cast<size_t>(file_size
);
824 EXPECT_EQ(expected_size
, file_contents
.size());
825 if (expected_size
!= file_contents
.size())
828 // Check the contents.
829 EXPECT_EQ(value
, file_contents
);
830 if (memcmp(file_contents
.c_str(), value
.c_str(), expected_size
) != 0)
836 // Attempts to download a file, based on information in |download_info|.
837 // If a Select File dialog opens, will automatically choose the default.
838 void DownloadFilesCheckErrorsSetup() {
839 ASSERT_TRUE(test_server()->Start());
840 std::vector
<DownloadItem
*> download_items
;
841 GetDownloads(browser(), &download_items
);
842 ASSERT_TRUE(download_items
.empty());
844 EnableFileChooser(true);
847 void DownloadFilesCheckErrorsLoopBody(const DownloadInfo
& download_info
,
850 s
<< " " << __FUNCTION__
<< "()"
852 << " url = '" << download_info
.url_name
<< "'"
854 << ((download_info
.download_method
== DOWNLOAD_DIRECT
) ?
855 "DOWNLOAD_DIRECT" : "DOWNLOAD_NAVIGATE")
856 << " show_item = " << download_info
.show_download_item
857 << " reason = " << DownloadInterruptReasonToString(download_info
.reason
);
859 std::vector
<DownloadItem
*> download_items
;
860 GetDownloads(browser(), &download_items
);
861 size_t downloads_expected
= download_items
.size();
863 std::string server_path
= "files/downloads/";
864 server_path
+= download_info
.url_name
;
865 GURL url
= test_server()->GetURL(server_path
);
866 ASSERT_TRUE(url
.is_valid()) << s
.str();
868 DownloadManager
* download_manager
= DownloadManagerForBrowser(browser());
869 WebContents
* web_contents
=
870 browser()->tab_strip_model()->GetActiveWebContents();
871 ASSERT_TRUE(web_contents
) << s
.str();
873 scoped_ptr
<content::DownloadTestObserver
> observer(
874 new content::DownloadTestObserverTerminal(
877 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL
));
879 if (download_info
.download_method
== DOWNLOAD_DIRECT
) {
880 // Go directly to download. Don't wait for navigation.
881 scoped_refptr
<content::DownloadTestItemCreationObserver
>
882 creation_observer(new content::DownloadTestItemCreationObserver
);
884 scoped_ptr
<DownloadUrlParameters
> params(
885 DownloadUrlParameters::FromWebContents(web_contents
, url
));
886 params
->set_callback(creation_observer
->callback());
887 DownloadManagerForBrowser(browser())->DownloadUrl(params
.Pass());
889 // Wait until the item is created, or we have determined that it
891 creation_observer
->WaitForDownloadItemCreation();
893 EXPECT_EQ(download_info
.show_download_item
,
894 creation_observer
->succeeded());
895 if (download_info
.show_download_item
) {
896 EXPECT_EQ(content::DOWNLOAD_INTERRUPT_REASON_NONE
,
897 creation_observer
->interrupt_reason());
898 EXPECT_NE(content::DownloadItem::kInvalidId
,
899 creation_observer
->download_id());
901 EXPECT_NE(content::DOWNLOAD_INTERRUPT_REASON_NONE
,
902 creation_observer
->interrupt_reason());
903 EXPECT_EQ(content::DownloadItem::kInvalidId
,
904 creation_observer
->download_id());
907 // Navigate to URL normally, wait until done.
908 ui_test_utils::NavigateToURL(browser(), url
);
911 if (download_info
.show_download_item
) {
912 downloads_expected
++;
913 observer
->WaitForFinished();
914 DownloadItem::DownloadState final_state
=
915 (download_info
.reason
== content::DOWNLOAD_INTERRUPT_REASON_NONE
) ?
916 DownloadItem::COMPLETE
:
917 DownloadItem::INTERRUPTED
;
918 EXPECT_EQ(1u, observer
->NumDownloadsSeenInState(final_state
));
921 // Wait till the |DownloadFile|s are destroyed.
922 content::RunAllPendingInMessageLoop(content::BrowserThread::FILE);
923 content::RunAllPendingInMessageLoop(content::BrowserThread::UI
);
925 // Validate that the correct files were downloaded.
926 download_items
.clear();
927 GetDownloads(browser(), &download_items
);
928 ASSERT_EQ(downloads_expected
, download_items
.size()) << s
.str();
930 if (download_info
.show_download_item
) {
931 // Find the last download item.
932 DownloadItem
* item
= download_items
[0];
933 for (size_t d
= 1; d
< downloads_expected
; ++d
) {
934 if (download_items
[d
]->GetStartTime() > item
->GetStartTime())
935 item
= download_items
[d
];
938 ASSERT_EQ(url
, item
->GetOriginalUrl()) << s
.str();
940 ASSERT_EQ(download_info
.reason
, item
->GetLastReason()) << s
.str();
942 if (item
->GetState() == content::DownloadItem::COMPLETE
) {
943 // Clean up the file, in case it ended up in the My Documents folder.
944 base::FilePath destination_folder
= GetDownloadDirectory(browser());
945 base::FilePath my_downloaded_file
= item
->GetTargetFilePath();
946 EXPECT_TRUE(base::PathExists(my_downloaded_file
));
947 EXPECT_TRUE(base::DeleteFile(my_downloaded_file
, false));
949 EXPECT_EQ(download_info
.should_redirect_to_documents
?
952 my_downloaded_file
.value().find(destination_folder
.value()));
953 if (download_info
.should_redirect_to_documents
) {
954 // If it's not where we asked it to be, it should be in the
955 // My Documents folder.
956 base::FilePath my_docs_folder
;
957 EXPECT_TRUE(PathService::Get(chrome::DIR_USER_DOCUMENTS
,
960 my_downloaded_file
.value().find(my_docs_folder
.value()));
966 // Attempts to download a set of files, based on information in the
967 // |download_info| array. |count| is the number of files.
968 // If a Select File dialog appears, it will choose the default and return
970 void DownloadFilesCheckErrors(size_t count
, DownloadInfo
* download_info
) {
971 DownloadFilesCheckErrorsSetup();
973 for (size_t i
= 0; i
< count
; ++i
) {
974 DownloadFilesCheckErrorsLoopBody(download_info
[i
], i
);
978 void DownloadInsertFilesErrorCheckErrorsLoopBody(
979 scoped_refptr
<content::TestFileErrorInjector
> injector
,
980 const FileErrorInjectInfo
& info
,
983 s
<< " " << __FUNCTION__
<< "()"
985 << " url = " << info
.error_info
.url
986 << " operation code = "
987 << content::TestFileErrorInjector::DebugString(info
.error_info
.code
)
988 << " instance = " << info
.error_info
.operation_instance
990 << content::DownloadInterruptReasonToString(info
.error_info
.error
);
992 injector
->ClearErrors();
993 injector
->AddError(info
.error_info
);
995 injector
->InjectErrors();
997 DownloadFilesCheckErrorsLoopBody(info
.download_info
, i
);
999 size_t expected_successes
= info
.download_info
.show_download_item
? 1u : 0u;
1000 EXPECT_EQ(expected_successes
, injector
->TotalFileCount()) << s
.str();
1001 EXPECT_EQ(0u, injector
->CurrentFileCount()) << s
.str();
1003 if (info
.download_info
.show_download_item
)
1004 EXPECT_TRUE(injector
->HadFile(GURL(info
.error_info
.url
))) << s
.str();
1007 void DownloadInsertFilesErrorCheckErrors(size_t count
,
1008 FileErrorInjectInfo
* info
) {
1009 DownloadFilesCheckErrorsSetup();
1011 // Set up file failures.
1012 scoped_refptr
<content::TestFileErrorInjector
> injector(
1013 content::TestFileErrorInjector::Create(
1014 DownloadManagerForBrowser(browser())));
1016 for (size_t i
= 0; i
< count
; ++i
) {
1017 // Set up the full URL, for download file tracking.
1018 std::string server_path
= "files/downloads/";
1019 server_path
+= info
[i
].download_info
.url_name
;
1020 GURL url
= test_server()->GetURL(server_path
);
1021 info
[i
].error_info
.url
= url
.spec();
1023 DownloadInsertFilesErrorCheckErrorsLoopBody(injector
, info
[i
], i
);
1027 // Attempts to download a file to a read-only folder, based on information
1028 // in |download_info|.
1029 void DownloadFilesToReadonlyFolder(size_t count
,
1030 DownloadInfo
* download_info
) {
1031 DownloadFilesCheckErrorsSetup();
1033 // Make the test folder unwritable.
1034 base::FilePath destination_folder
= GetDownloadDirectory(browser());
1035 DVLOG(1) << " " << __FUNCTION__
<< "()"
1036 << " folder = '" << destination_folder
.value() << "'";
1037 base::FilePermissionRestorer
permission_restorer(destination_folder
);
1038 EXPECT_TRUE(base::MakeFileUnwritable(destination_folder
));
1040 for (size_t i
= 0; i
< count
; ++i
) {
1041 DownloadFilesCheckErrorsLoopBody(download_info
[i
], i
);
1045 // A mock install prompt that simulates the user allowing an install request.
1046 void SetAllowMockInstallPrompt() {
1047 download_crx_util::SetMockInstallPromptForTesting(
1048 scoped_ptr
<ExtensionInstallPrompt
>(
1049 new MockAutoConfirmExtensionInstallPrompt(
1050 browser()->tab_strip_model()->GetActiveWebContents())));
1054 // * Starts a mock download by navigating browser() to a URLRequestMockHTTPJob
1056 // * Injects |error| on the first write using |error_injector|.
1057 // * Waits for the download to be interrupted.
1058 // * Clears the errors on |error_injector|.
1059 // * Returns the resulting interrupted download.
1060 DownloadItem
* StartMockDownloadAndInjectError(
1061 content::TestFileErrorInjector
* error_injector
,
1062 content::DownloadInterruptReason error
) {
1063 base::FilePath
file_path(FILE_PATH_LITERAL("download-test1.lib"));
1064 GURL url
= URLRequestMockHTTPJob::GetMockUrl(file_path
);
1066 content::TestFileErrorInjector::FileErrorInfo error_info
;
1067 error_info
.url
= url
.spec();
1068 error_info
.code
= content::TestFileErrorInjector::FILE_OPERATION_WRITE
;
1069 error_info
.operation_instance
= 0;
1070 error_info
.error
= error
;
1071 error_injector
->ClearErrors();
1072 error_injector
->AddError(error_info
);
1073 error_injector
->InjectErrors();
1075 scoped_ptr
<content::DownloadTestObserver
> observer(
1076 new DownloadTestObserverResumable(
1077 DownloadManagerForBrowser(browser()), 1));
1078 ui_test_utils::NavigateToURL(browser(), url
);
1079 observer
->WaitForFinished();
1081 content::DownloadManager::DownloadVector downloads
;
1082 DownloadManagerForBrowser(browser())->GetAllDownloads(&downloads
);
1083 EXPECT_EQ(1u, downloads
.size());
1085 if (downloads
.size() != 1)
1088 error_injector
->ClearErrors();
1089 error_injector
->InjectErrors();
1090 DownloadItem
* download
= downloads
[0];
1091 EXPECT_EQ(DownloadItem::INTERRUPTED
, download
->GetState());
1092 EXPECT_EQ(error
, download
->GetLastReason());
1096 void WaitForBubble(MockPermissionBubbleView
* mock_bubble
) {
1097 if (mock_bubble
->IsVisible())
1099 content::RunMessageLoop();
1103 static void EnsureNoPendingDownloadJobsOnIO(bool* result
) {
1104 if (net::URLRequestSlowDownloadJob::NumberOutstandingRequests())
1106 BrowserThread::PostTask(
1107 BrowserThread::UI
, FROM_HERE
, base::MessageLoop::QuitClosure());
1110 // Location of the test data.
1111 base::FilePath test_dir_
;
1113 // Location of the downloads directory for these tests
1114 base::ScopedTempDir downloads_directory_
;
1116 scoped_ptr
<DownloadTestFileActivityObserver
> file_activity_observer_
;
1121 // Files for these tests are found in DIR_TEST_DATA (currently
1122 // "chrome\test\data\", see chrome_paths.cc).
1123 // Mock responses have extension .mock-http-headers appended to the file name.
1125 // Download a file due to the associated MIME type.
1126 IN_PROC_BROWSER_TEST_F(DownloadTest
, DownloadMimeType
) {
1127 base::FilePath
file(FILE_PATH_LITERAL("download-test1.lib"));
1128 GURL
url(URLRequestMockHTTPJob::GetMockUrl(file
));
1130 // Download the file and wait. We do not expect the Select File dialog.
1131 DownloadAndWait(browser(), url
);
1134 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1135 CheckDownload(browser(), file
, file
);
1136 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
1140 // Download a file and confirm that the zone identifier (on windows)
1141 // is set to internet.
1142 IN_PROC_BROWSER_TEST_F(DownloadTest
, CheckInternetZone
) {
1143 base::FilePath
file(FILE_PATH_LITERAL("download-test1.lib"));
1144 GURL
url(URLRequestMockHTTPJob::GetMockUrl(file
));
1146 // Download the file and wait. We do not expect the Select File dialog.
1147 DownloadAndWait(browser(), url
);
1149 // Check state. Special file state must be checked before CheckDownload,
1150 // as CheckDownload will delete the output file.
1151 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1152 base::FilePath
downloaded_file(DestinationFile(browser(), file
));
1153 if (base::VolumeSupportsADS(downloaded_file
))
1154 EXPECT_TRUE(base::HasInternetZoneIdentifier(downloaded_file
));
1155 CheckDownload(browser(), file
, file
);
1156 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
1160 // Put up a Select File dialog when the file is downloaded, due to
1161 // downloads preferences settings.
1162 IN_PROC_BROWSER_TEST_F(DownloadTest
, DownloadMimeTypeSelect
) {
1163 // Re-enable prompting.
1164 browser()->profile()->GetPrefs()->SetBoolean(
1165 prefs::kPromptForDownload
, true);
1166 base::FilePath
file(FILE_PATH_LITERAL("download-test1.lib"));
1167 GURL
url(URLRequestMockHTTPJob::GetMockUrl(file
));
1169 EnableFileChooser(true);
1171 // Download the file and wait. We expect the Select File dialog to appear
1172 // due to the MIME type, but we still wait until the download completes.
1173 scoped_ptr
<content::DownloadTestObserver
> observer(
1174 new content::DownloadTestObserverTerminal(
1175 DownloadManagerForBrowser(browser()),
1177 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL
));
1178 ui_test_utils::NavigateToURL(browser(), url
);
1179 observer
->WaitForFinished();
1180 EXPECT_EQ(1u, observer
->NumDownloadsSeenInState(DownloadItem::COMPLETE
));
1181 CheckDownloadStates(1, DownloadItem::COMPLETE
);
1182 EXPECT_TRUE(DidShowFileChooser());
1185 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1186 CheckDownload(browser(), file
, file
);
1187 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
1190 // Access a file with a viewable mime-type, verify that a download
1191 // did not initiate.
1192 IN_PROC_BROWSER_TEST_F(DownloadTest
, NoDownload
) {
1193 base::FilePath
file(FILE_PATH_LITERAL("download-test2.html"));
1194 GURL
url(URLRequestMockHTTPJob::GetMockUrl(file
));
1195 base::FilePath
file_path(DestinationFile(browser(), file
));
1197 // Open a web page and wait.
1198 ui_test_utils::NavigateToURL(browser(), url
);
1200 // Check that we did not download the web page.
1201 EXPECT_FALSE(base::PathExists(file_path
));
1204 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1205 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
1208 IN_PROC_BROWSER_TEST_F(DownloadTest
, MimeTypesToShowNotDownload
) {
1209 ASSERT_TRUE(test_server()->Start());
1211 // These files should all be displayed in the browser.
1212 const char* mime_types
[] = {
1213 // It is unclear whether to display text/css or download it.
1214 // Firefox 3: Display
1215 // Internet Explorer 7: Download
1216 // Safari 3.2: Download
1217 // We choose to match Firefox due to the lot of complains
1218 // from the users if css files are downloaded:
1219 // http://code.google.com/p/chromium/issues/detail?id=7192
1223 "application/x-javascript",
1227 "application/xhtml+xml",
1233 for (size_t i
= 0; i
< arraysize(mime_types
); ++i
) {
1234 const char* mime_type
= mime_types
[i
];
1235 std::string
path("contenttype?");
1236 GURL
url(test_server()->GetURL(path
+ mime_type
));
1237 ui_test_utils::NavigateToURL(browser(), url
);
1240 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1241 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
1245 // Verify that when the DownloadResourceThrottle cancels a download, the
1246 // download never makes it to the downloads system.
1247 IN_PROC_BROWSER_TEST_F(DownloadTest
, DownloadResourceThrottleCancels
) {
1248 // Navigate to a page with the same domain as the file to download. We can't
1249 // navigate directly to the file we don't want to download because cross-site
1250 // navigations reset the TabDownloadState.
1251 base::FilePath
same_site_path(FILE_PATH_LITERAL("download_script.html"));
1252 GURL
same_site_url(URLRequestMockHTTPJob::GetMockUrl(same_site_path
));
1253 ui_test_utils::NavigateToURL(browser(), same_site_url
);
1255 // Make sure the initial navigation didn't trigger a download.
1256 std::vector
<content::DownloadItem
*> items
;
1257 DownloadManagerForBrowser(browser())->GetAllDownloads(&items
);
1258 EXPECT_EQ(0u, items
.size());
1260 // Disable downloads for the tab.
1261 WebContents
* web_contents
=
1262 browser()->tab_strip_model()->GetActiveWebContents();
1263 DownloadRequestLimiter::TabDownloadState
* tab_download_state
=
1264 g_browser_process
->download_request_limiter()->GetDownloadState(
1265 web_contents
, web_contents
, true);
1266 ASSERT_TRUE(tab_download_state
);
1267 tab_download_state
->set_download_status(
1268 DownloadRequestLimiter::DOWNLOADS_NOT_ALLOWED
);
1270 // Try to start the download via Javascript and wait for the corresponding
1272 content::TestNavigationObserver
observer(web_contents
);
1273 bool download_assempted
;
1274 ASSERT_TRUE(content::ExecuteScriptAndExtractBool(
1275 browser()->tab_strip_model()->GetActiveWebContents(),
1276 "window.domAutomationController.send(startDownload());",
1277 &download_assempted
));
1278 ASSERT_TRUE(download_assempted
);
1281 // Check that we did not download the file.
1282 base::FilePath
file(FILE_PATH_LITERAL("download-test1.lib"));
1283 base::FilePath
file_path(DestinationFile(browser(), file
));
1284 EXPECT_FALSE(base::PathExists(file_path
));
1287 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1288 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
1290 // Verify that there's no pending download. The resource throttle
1291 // should have deleted it before it created a download item, so it
1292 // shouldn't be available as a cancelled download either.
1293 DownloadManagerForBrowser(browser())->GetAllDownloads(&items
);
1294 EXPECT_EQ(0u, items
.size());
1297 // Download a 0-size file with a content-disposition header, verify that the
1298 // download tab opened and the file exists as the filename specified in the
1299 // header. This also ensures we properly handle empty file downloads.
1300 // The download shelf should be visible in the current tab.
1301 IN_PROC_BROWSER_TEST_F(DownloadTest
, ContentDisposition
) {
1302 base::FilePath
file(FILE_PATH_LITERAL("download-test3.gif"));
1303 GURL
url(URLRequestMockHTTPJob::GetMockUrl(file
));
1304 base::FilePath
download_file(
1305 FILE_PATH_LITERAL("download-test3-attachment.gif"));
1307 // Download a file and wait.
1308 DownloadAndWait(browser(), url
);
1310 CheckDownload(browser(), download_file
, file
);
1313 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1314 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
1317 // Test that the download shelf is per-window by starting a download in one
1318 // tab, opening a second tab, closing the shelf, going back to the first tab,
1319 // and checking that the shelf is closed.
1320 IN_PROC_BROWSER_TEST_F(DownloadTest
, PerWindowShelf
) {
1321 base::FilePath
file(FILE_PATH_LITERAL("download-test3.gif"));
1322 GURL
url(URLRequestMockHTTPJob::GetMockUrl(file
));
1323 base::FilePath
download_file(
1324 FILE_PATH_LITERAL("download-test3-attachment.gif"));
1326 // Download a file and wait.
1327 DownloadAndWait(browser(), url
);
1329 CheckDownload(browser(), download_file
, file
);
1332 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1333 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
1335 // Open a second tab and wait.
1336 EXPECT_NE(static_cast<WebContents
*>(NULL
),
1337 chrome::AddSelectedTabWithURL(browser(),
1338 GURL(url::kAboutBlankURL
),
1339 ui::PAGE_TRANSITION_TYPED
));
1340 EXPECT_EQ(2, browser()->tab_strip_model()->count());
1341 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
1343 // Hide the download shelf.
1344 browser()->window()->GetDownloadShelf()->Close(DownloadShelf::AUTOMATIC
);
1345 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
1347 // Go to the first tab.
1348 browser()->tab_strip_model()->ActivateTabAt(0, true);
1349 EXPECT_EQ(2, browser()->tab_strip_model()->count());
1351 // The download shelf should not be visible.
1352 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
1355 // Check whether the downloads shelf is closed when the downloads tab is
1357 IN_PROC_BROWSER_TEST_F(DownloadTest
, CloseShelfOnDownloadsTab
) {
1358 base::FilePath
file(FILE_PATH_LITERAL("download-test1.lib"));
1359 GURL
url(URLRequestMockHTTPJob::GetMockUrl(file
));
1361 // Download the file and wait. We do not expect the Select File dialog.
1362 DownloadAndWait(browser(), url
);
1365 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1366 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
1368 // Open the downloads tab.
1369 chrome::ShowDownloads(browser());
1370 // The shelf should now be closed.
1371 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
1374 // UnknownSize and KnownSize are tests which depend on
1375 // URLRequestSlowDownloadJob to serve content in a certain way. Data will be
1376 // sent in two chunks where the first chunk is 35K and the second chunk is 10K.
1377 // The test will first attempt to download a file; but the server will "pause"
1378 // in the middle until the server receives a second request for
1379 // "download-finish". At that time, the download will finish.
1380 // These tests don't currently test much due to holes in |RunSizeTest()|. See
1381 // comments in that routine for details.
1382 IN_PROC_BROWSER_TEST_F(DownloadTest
, UnknownSize
) {
1383 ASSERT_TRUE(RunSizeTest(browser(), SIZE_TEST_TYPE_UNKNOWN
,
1384 "32.0 KB - ", "100% - "));
1387 IN_PROC_BROWSER_TEST_F(DownloadTest
, KnownSize
) {
1388 ASSERT_TRUE(RunSizeTest(browser(), SIZE_TEST_TYPE_KNOWN
,
1389 "71% - ", "100% - "));
1392 // Test that when downloading an item in Incognito mode, we don't crash when
1393 // closing the last Incognito window (http://crbug.com/13983).
1394 // Also check that the download shelf is not visible after closing the
1395 // Incognito window.
1396 IN_PROC_BROWSER_TEST_F(DownloadTest
, IncognitoDownload
) {
1397 Browser
* incognito
= CreateIncognitoBrowser();
1398 ASSERT_TRUE(incognito
);
1399 int window_count
= chrome::GetTotalBrowserCount();
1400 EXPECT_EQ(2, window_count
);
1402 // Download a file in the Incognito window and wait.
1403 CreateAndSetDownloadsDirectory(incognito
);
1404 base::FilePath
file(FILE_PATH_LITERAL("download-test1.lib"));
1405 GURL
url(URLRequestMockHTTPJob::GetMockUrl(file
));
1406 // Since |incognito| is a separate browser, we have to set it up explicitly.
1407 incognito
->profile()->GetPrefs()->SetBoolean(prefs::kPromptForDownload
,
1409 DownloadAndWait(incognito
, url
);
1411 // We should still have 2 windows.
1412 ExpectWindowCountAfterDownload(2);
1414 // Verify that the download shelf is showing for the Incognito window.
1415 EXPECT_TRUE(incognito
->window()->IsDownloadShelfVisible());
1417 #if !defined(OS_MACOSX)
1418 // On Mac OS X, the UI window close is delayed until the outermost
1419 // message loop runs. So it isn't possible to get a BROWSER_CLOSED
1420 // notification inside of a test.
1421 content::WindowedNotificationObserver
signal(
1422 chrome::NOTIFICATION_BROWSER_CLOSED
,
1423 content::Source
<Browser
>(incognito
));
1426 // Close the Incognito window and don't crash.
1427 chrome::CloseWindow(incognito
);
1429 #if !defined(OS_MACOSX)
1431 ExpectWindowCountAfterDownload(1);
1434 // Verify that the regular window does not have a download shelf.
1435 // On ChromeOS, the download panel is common to both profiles, so
1436 // it is still visible.
1437 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
1439 CheckDownload(browser(), file
, file
);
1442 // Download one file on-record, then download the same file off-record, and test
1443 // that the filename is deduplicated. The previous test tests for a specific
1444 // bug; this next test tests that filename deduplication happens independently
1445 // of DownloadManager/CDMD.
1446 IN_PROC_BROWSER_TEST_F(DownloadTest
, DownloadTest_IncognitoRegular
) {
1447 ASSERT_TRUE(test_server()->Start());
1448 GURL
url(test_server()->GetURL("files/downloads/a_zip_file.zip"));
1450 // Read the origin file now so that we can compare the downloaded files to it
1452 base::FilePath
origin(OriginFile(base::FilePath(FILE_PATH_LITERAL(
1453 "downloads/a_zip_file.zip"))));
1454 ASSERT_TRUE(base::PathExists(origin
));
1455 int64 origin_file_size
= 0;
1456 EXPECT_TRUE(base::GetFileSize(origin
, &origin_file_size
));
1457 std::string original_contents
;
1458 EXPECT_TRUE(base::ReadFileToString(origin
, &original_contents
));
1460 std::vector
<DownloadItem
*> download_items
;
1461 GetDownloads(browser(), &download_items
);
1462 ASSERT_TRUE(download_items
.empty());
1464 // Download a file in the on-record browser and check that it was downloaded
1466 DownloadAndWaitWithDisposition(browser(),
1469 ui_test_utils::BROWSER_TEST_NONE
);
1470 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
1471 GetDownloads(browser(), &download_items
);
1472 ASSERT_EQ(1UL, download_items
.size());
1473 ASSERT_EQ(base::FilePath(FILE_PATH_LITERAL("a_zip_file.zip")),
1474 download_items
[0]->GetTargetFilePath().BaseName());
1475 ASSERT_TRUE(base::PathExists(download_items
[0]->GetTargetFilePath()));
1476 EXPECT_TRUE(VerifyFile(download_items
[0]->GetTargetFilePath(),
1477 original_contents
, origin_file_size
));
1479 // Setup an incognito window.
1480 Browser
* incognito
= CreateIncognitoBrowser();
1481 ASSERT_TRUE(incognito
);
1482 int window_count
= BrowserList::GetInstance(
1483 browser()->host_desktop_type())->size();
1484 EXPECT_EQ(2, window_count
);
1485 incognito
->profile()->GetPrefs()->SetFilePath(
1486 prefs::kDownloadDefaultDirectory
,
1487 GetDownloadsDirectory());
1488 incognito
->profile()->GetPrefs()->SetFilePath(
1489 prefs::kSaveFileDefaultDirectory
,
1490 GetDownloadsDirectory());
1492 download_items
.clear();
1493 GetDownloads(incognito
, &download_items
);
1494 ASSERT_TRUE(download_items
.empty());
1496 // Download a file in the incognito browser and check that it was downloaded
1498 DownloadAndWaitWithDisposition(incognito
,
1501 ui_test_utils::BROWSER_TEST_NONE
);
1502 EXPECT_TRUE(incognito
->window()->IsDownloadShelfVisible());
1503 GetDownloads(incognito
, &download_items
);
1504 ASSERT_EQ(1UL, download_items
.size());
1505 ASSERT_EQ(base::FilePath(FILE_PATH_LITERAL("a_zip_file (1).zip")),
1506 download_items
[0]->GetTargetFilePath().BaseName());
1507 ASSERT_TRUE(base::PathExists(download_items
[0]->GetTargetFilePath()));
1508 EXPECT_TRUE(VerifyFile(download_items
[0]->GetTargetFilePath(),
1509 original_contents
, origin_file_size
));
1512 // Navigate to a new background page, but don't download. Confirm that the
1513 // download shelf is not visible and that we have two tabs.
1514 IN_PROC_BROWSER_TEST_F(DownloadTest
, DontCloseNewTab1
) {
1515 // Because it's an HTML link, it should open a web page rather than
1517 base::FilePath
file1(FILE_PATH_LITERAL("download-test2.html"));
1518 GURL
url(URLRequestMockHTTPJob::GetMockUrl(file1
));
1520 // Open a web page and wait.
1521 ui_test_utils::NavigateToURLWithDisposition(
1525 ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION
);
1527 // We should have two tabs now.
1528 EXPECT_EQ(2, browser()->tab_strip_model()->count());
1529 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
1532 // Download a file in a background tab. Verify that the tab is closed
1533 // automatically, and that the download shelf is visible in the current tab.
1534 IN_PROC_BROWSER_TEST_F(DownloadTest
, CloseNewTab1
) {
1535 // Download a file in a new background tab and wait. The tab is automatically
1536 // closed when the download begins.
1537 base::FilePath
file(FILE_PATH_LITERAL("download-test1.lib"));
1538 GURL
url(URLRequestMockHTTPJob::GetMockUrl(file
));
1539 DownloadAndWaitWithDisposition(
1545 // When the download finishes, we should still have one tab.
1546 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
1547 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1549 CheckDownload(browser(), file
, file
);
1552 // Open a web page in the current tab, then download a file in another tab via
1553 // a Javascript call.
1554 // Verify that we have 2 tabs, and the download shelf is visible in the current
1557 // The download_page1.html page contains an openNew() function that opens a
1558 // tab and then downloads download-test1.lib.
1559 IN_PROC_BROWSER_TEST_F(DownloadTest
, DontCloseNewTab2
) {
1560 // Because it's an HTML link, it should open a web page rather than
1562 base::FilePath
file1(FILE_PATH_LITERAL("download_page1.html"));
1563 GURL
url(URLRequestMockHTTPJob::GetMockUrl(file1
));
1565 // Open a web page and wait.
1566 ui_test_utils::NavigateToURL(browser(), url
);
1568 // Download a file in a new tab and wait (via Javascript).
1569 base::FilePath
file(FILE_PATH_LITERAL("download-test1.lib"));
1570 DownloadAndWaitWithDisposition(browser(),
1571 GURL("javascript:openNew()"),
1573 ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB
);
1575 // When the download finishes, we should have two tabs.
1576 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
1577 EXPECT_EQ(2, browser()->tab_strip_model()->count());
1579 CheckDownload(browser(), file
, file
);
1582 // Open a web page in the current tab, open another tab via a Javascript call,
1583 // then download a file in the new tab.
1584 // Verify that we have 2 tabs, and the download shelf is visible in the current
1587 // The download_page2.html page contains an openNew() function that opens a
1589 IN_PROC_BROWSER_TEST_F(DownloadTest
, DontCloseNewTab3
) {
1590 // Because it's an HTML link, it should open a web page rather than
1592 base::FilePath
file1(FILE_PATH_LITERAL("download_page2.html"));
1593 GURL
url1(URLRequestMockHTTPJob::GetMockUrl(file1
));
1595 // Open a web page and wait.
1596 ui_test_utils::NavigateToURL(browser(), url1
);
1598 // Open a new tab and wait.
1599 ui_test_utils::NavigateToURLWithDisposition(
1601 GURL("javascript:openNew()"),
1603 ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB
);
1605 EXPECT_EQ(2, browser()->tab_strip_model()->count());
1607 // Download a file and wait.
1608 base::FilePath
file(FILE_PATH_LITERAL("download-test1.lib"));
1609 GURL
url(URLRequestMockHTTPJob::GetMockUrl(file
));
1610 DownloadAndWaitWithDisposition(browser(),
1613 ui_test_utils::BROWSER_TEST_NONE
);
1615 // When the download finishes, we should have two tabs.
1616 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
1617 EXPECT_EQ(2, browser()->tab_strip_model()->count());
1619 CheckDownload(browser(), file
, file
);
1622 // Open a web page in the current tab, then download a file via Javascript,
1623 // which will do so in a temporary tab.
1624 // Verify that we have 1 tab, and the download shelf is visible.
1626 // The download_page3.html page contains an openNew() function that opens a
1627 // tab with download-test1.lib in the URL. When the URL is determined to be
1628 // a download, the tab is closed automatically.
1629 IN_PROC_BROWSER_TEST_F(DownloadTest
, CloseNewTab2
) {
1630 // Because it's an HTML link, it should open a web page rather than
1632 base::FilePath
file1(FILE_PATH_LITERAL("download_page3.html"));
1633 GURL
url(URLRequestMockHTTPJob::GetMockUrl(file1
));
1635 // Open a web page and wait.
1636 ui_test_utils::NavigateToURL(browser(), url
);
1638 // Download a file and wait.
1639 // The file to download is "download-test1.lib".
1640 base::FilePath
file(FILE_PATH_LITERAL("download-test1.lib"));
1641 DownloadAndWaitWithDisposition(browser(),
1642 GURL("javascript:openNew()"),
1644 ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB
);
1646 // When the download finishes, we should still have one tab.
1647 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
1648 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1650 CheckDownload(browser(), file
, file
);
1653 // Open a web page in the current tab, then call Javascript via a button to
1654 // download a file in a new tab, which is closed automatically when the
1656 // Verify that we have 1 tab, and the download shelf is visible.
1658 // The download_page4.html page contains a form with download-test1.lib as the
1660 IN_PROC_BROWSER_TEST_F(DownloadTest
, CloseNewTab3
) {
1661 // Because it's an HTML link, it should open a web page rather than
1663 base::FilePath
file1(FILE_PATH_LITERAL("download_page4.html"));
1664 GURL
url(URLRequestMockHTTPJob::GetMockUrl(file1
));
1666 // Open a web page and wait.
1667 ui_test_utils::NavigateToURL(browser(), url
);
1669 // Download a file in a new tab and wait. The tab will automatically close
1670 // when the download begins.
1671 // The file to download is "download-test1.lib".
1672 base::FilePath
file(FILE_PATH_LITERAL("download-test1.lib"));
1673 DownloadAndWaitWithDisposition(
1675 GURL("javascript:document.getElementById('form').submit()"),
1677 ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB
);
1679 // When the download finishes, we should still have one tab.
1680 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
1681 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1683 CheckDownload(browser(), file
, file
);
1686 // Download a file in a new window.
1687 // Verify that we have 2 windows, and the download shelf is not visible in the
1688 // first window, but is visible in the second window.
1689 // Close the new window.
1690 // Verify that we have 1 window, and the download shelf is not visible.
1692 // Regression test for http://crbug.com/44454
1693 IN_PROC_BROWSER_TEST_F(DownloadTest
, NewWindow
) {
1694 base::FilePath
file(FILE_PATH_LITERAL("download-test1.lib"));
1695 GURL
url(URLRequestMockHTTPJob::GetMockUrl(file
));
1696 #if !defined(OS_MACOSX)
1698 Browser
* first_browser
= browser();
1701 // Download a file in a new window and wait.
1702 DownloadAndWaitWithDisposition(browser(),
1705 ui_test_utils::BROWSER_TEST_NONE
);
1707 // When the download finishes, the download shelf SHOULD NOT be visible in
1708 // the first window.
1709 ExpectWindowCountAfterDownload(2);
1710 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1711 // Download shelf should close. Download panel stays open on ChromeOS.
1712 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
1714 // The download shelf SHOULD be visible in the second window.
1715 std::set
<Browser
*> original_browsers
;
1716 original_browsers
.insert(browser());
1717 Browser
* download_browser
=
1718 ui_test_utils::GetBrowserNotInSet(original_browsers
);
1719 ASSERT_TRUE(download_browser
!= NULL
);
1720 EXPECT_NE(download_browser
, browser());
1721 EXPECT_EQ(1, download_browser
->tab_strip_model()->count());
1722 EXPECT_TRUE(download_browser
->window()->IsDownloadShelfVisible());
1724 #if !defined(OS_MACOSX)
1725 // On Mac OS X, the UI window close is delayed until the outermost
1726 // message loop runs. So it isn't possible to get a BROWSER_CLOSED
1727 // notification inside of a test.
1728 content::WindowedNotificationObserver
signal(
1729 chrome::NOTIFICATION_BROWSER_CLOSED
,
1730 content::Source
<Browser
>(download_browser
));
1733 // Close the new window.
1734 chrome::CloseWindow(download_browser
);
1736 #if !defined(OS_MACOSX)
1738 EXPECT_EQ(first_browser
, browser());
1739 ExpectWindowCountAfterDownload(1);
1742 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1743 // Download shelf should close. Download panel stays open on ChromeOS.
1744 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
1746 CheckDownload(browser(), file
, file
);
1749 IN_PROC_BROWSER_TEST_F(DownloadTest
, DownloadHistoryCheck
) {
1750 GURL
download_url(net::URLRequestSlowDownloadJob::kKnownSizeUrl
);
1751 base::FilePath
file(net::GenerateFileName(download_url
,
1758 // We use the server so that we can get a redirect and test url_chain
1760 ASSERT_TRUE(test_server()->Start());
1761 GURL redirect_url
= test_server()->GetURL(
1762 "server-redirect?" + download_url
.spec());
1764 // Download the url and wait until the object has been stored.
1765 base::Time
start(base::Time::Now());
1766 HistoryObserver
observer(browser()->profile());
1767 observer
.SetFilterCallback(base::Bind(&HasDataAndName
));
1768 ui_test_utils::NavigateToURL(browser(), redirect_url
);
1769 observer
.WaitForStored();
1771 // Get the details on what was stored into the history.
1772 scoped_ptr
<std::vector
<history::DownloadRow
> > downloads_in_database
;
1773 ASSERT_TRUE(DownloadsHistoryDataCollector(
1774 browser()->profile()).WaitForDownloadInfo(&downloads_in_database
));
1775 ASSERT_EQ(1u, downloads_in_database
->size());
1777 // Confirm history storage is what you expect for a partially completed
1778 // slow download job.
1779 history::DownloadRow
& row(downloads_in_database
->at(0));
1780 EXPECT_EQ(DestinationFile(browser(), file
), row
.target_path
);
1781 EXPECT_EQ(DownloadTargetDeterminer::GetCrDownloadPath(
1782 DestinationFile(browser(), file
)),
1784 ASSERT_EQ(2u, row
.url_chain
.size());
1785 EXPECT_EQ(redirect_url
.spec(), row
.url_chain
[0].spec());
1786 EXPECT_EQ(download_url
.spec(), row
.url_chain
[1].spec());
1787 EXPECT_EQ(history::DownloadDangerType::NOT_DANGEROUS
, row
.danger_type
);
1788 EXPECT_LE(start
, row
.start_time
);
1789 EXPECT_EQ(net::URLRequestSlowDownloadJob::kFirstDownloadSize
,
1790 row
.received_bytes
);
1791 EXPECT_EQ(net::URLRequestSlowDownloadJob::kFirstDownloadSize
1792 + net::URLRequestSlowDownloadJob::kSecondDownloadSize
,
1794 EXPECT_EQ(history::DownloadState::IN_PROGRESS
, row
.state
);
1795 EXPECT_FALSE(row
.opened
);
1797 // Finish the download. We're ok relying on the history to be flushed
1798 // at this point as our queries will be behind the history updates
1799 // invoked by completion.
1800 scoped_ptr
<content::DownloadTestObserver
> download_observer(
1801 CreateWaiter(browser(), 1));
1802 ui_test_utils::NavigateToURL(browser(),
1803 GURL(net::URLRequestSlowDownloadJob::kErrorDownloadUrl
));
1804 download_observer
->WaitForFinished();
1805 EXPECT_EQ(1u, download_observer
->NumDownloadsSeenInState(
1806 DownloadItem::INTERRUPTED
));
1807 base::Time
end(base::Time::Now());
1809 // Get what was stored in the history.
1810 ASSERT_TRUE(DownloadsHistoryDataCollector(
1811 browser()->profile()).WaitForDownloadInfo(&downloads_in_database
));
1812 ASSERT_EQ(1u, downloads_in_database
->size());
1814 // Confirm history storage is what you expect for an interrupted slow download
1815 // job. The download isn't continuable, so there's no intermediate file.
1816 history::DownloadRow
& row1(downloads_in_database
->at(0));
1817 EXPECT_EQ(DestinationFile(browser(), file
), row1
.target_path
);
1818 EXPECT_TRUE(row1
.current_path
.empty());
1819 ASSERT_EQ(2u, row1
.url_chain
.size());
1820 EXPECT_EQ(redirect_url
.spec(), row1
.url_chain
[0].spec());
1821 EXPECT_EQ(download_url
.spec(), row1
.url_chain
[1].spec());
1822 EXPECT_EQ(history::DownloadDangerType::NOT_DANGEROUS
, row1
.danger_type
);
1823 EXPECT_LE(start
, row1
.start_time
);
1824 EXPECT_GE(end
, row1
.end_time
);
1825 EXPECT_EQ(net::URLRequestSlowDownloadJob::kFirstDownloadSize
,
1826 row1
.received_bytes
);
1827 EXPECT_EQ(net::URLRequestSlowDownloadJob::kFirstDownloadSize
1828 + net::URLRequestSlowDownloadJob::kSecondDownloadSize
,
1830 EXPECT_EQ(history::DownloadState::INTERRUPTED
, row1
.state
);
1831 EXPECT_EQ(history::ToHistoryDownloadInterruptReason(
1832 content::DOWNLOAD_INTERRUPT_REASON_NETWORK_FAILED
),
1833 row1
.interrupt_reason
);
1834 EXPECT_FALSE(row1
.opened
);
1837 // Make sure a dangerous file shows up properly in the history.
1838 IN_PROC_BROWSER_TEST_F(DownloadTest
, DownloadHistoryDangerCheck
) {
1839 #if defined(OS_WIN) && defined(USE_ASH)
1840 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
1841 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1842 switches::kAshBrowserTests
))
1846 // .swf file so that it's dangerous on all platforms (including CrOS).
1847 base::FilePath
file(FILE_PATH_LITERAL("downloads/dangerous/dangerous.swf"));
1848 GURL
download_url(URLRequestMockHTTPJob::GetMockUrl(file
));
1850 // Download the url and wait until the object has been stored.
1851 scoped_ptr
<content::DownloadTestObserver
> download_observer(
1852 new content::DownloadTestObserverTerminal(
1853 DownloadManagerForBrowser(browser()), 1,
1854 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_IGNORE
));
1855 base::Time
start(base::Time::Now());
1856 HistoryObserver
observer(browser()->profile());
1857 observer
.SetFilterCallback(base::Bind(&HasDataAndName
));
1858 ui_test_utils::NavigateToURL(browser(), download_url
);
1859 observer
.WaitForStored();
1861 // Get the details on what was stored into the history.
1862 scoped_ptr
<std::vector
<history::DownloadRow
> > downloads_in_database
;
1863 ASSERT_TRUE(DownloadsHistoryDataCollector(
1864 browser()->profile()).WaitForDownloadInfo(&downloads_in_database
));
1865 ASSERT_EQ(1u, downloads_in_database
->size());
1867 // Confirm history storage is what you expect for an unvalidated
1869 history::DownloadRow
& row(downloads_in_database
->at(0));
1870 EXPECT_EQ(DestinationFile(browser(), file
), row
.target_path
);
1871 EXPECT_NE(DownloadTargetDeterminer::GetCrDownloadPath(
1872 DestinationFile(browser(), file
)),
1874 EXPECT_EQ(history::DownloadDangerType::DANGEROUS_FILE
, row
.danger_type
);
1875 EXPECT_LE(start
, row
.start_time
);
1876 EXPECT_EQ(history::DownloadState::IN_PROGRESS
, row
.state
);
1877 EXPECT_FALSE(row
.opened
);
1879 // Validate the download and wait for it to finish.
1880 std::vector
<DownloadItem
*> downloads
;
1881 DownloadManagerForBrowser(browser())->GetAllDownloads(&downloads
);
1882 ASSERT_EQ(1u, downloads
.size());
1883 downloads
[0]->ValidateDangerousDownload();
1884 download_observer
->WaitForFinished();
1886 // Get history details and confirm it's what you expect.
1887 downloads_in_database
->clear();
1888 ASSERT_TRUE(DownloadsHistoryDataCollector(
1889 browser()->profile()).WaitForDownloadInfo(&downloads_in_database
));
1890 ASSERT_EQ(1u, downloads_in_database
->size());
1891 history::DownloadRow
& row1(downloads_in_database
->at(0));
1892 EXPECT_EQ(DestinationFile(browser(), file
), row1
.target_path
);
1893 EXPECT_EQ(DestinationFile(browser(), file
), row1
.current_path
);
1894 EXPECT_EQ(history::DownloadDangerType::USER_VALIDATED
, row1
.danger_type
);
1895 EXPECT_LE(start
, row1
.start_time
);
1896 EXPECT_EQ(history::DownloadState::COMPLETE
, row1
.state
);
1897 EXPECT_FALSE(row1
.opened
);
1898 // Not checking file size--not relevant to the point of the test, and
1899 // the file size is actually different on Windows and other platforms,
1900 // because for source control simplicity it's actually a text file, and
1901 // there are CRLF transformations for those files.
1904 IN_PROC_BROWSER_TEST_F(DownloadTest
, PRE_DownloadTest_History
) {
1905 // Download a file and wait for it to be stored.
1906 base::FilePath
file(FILE_PATH_LITERAL("download-test1.lib"));
1907 GURL
download_url(URLRequestMockHTTPJob::GetMockUrl(file
));
1908 HistoryObserver
observer(browser()->profile());
1909 DownloadAndWait(browser(), download_url
);
1910 observer
.WaitForStored();
1911 HistoryServiceFactory::GetForProfile(browser()->profile(),
1912 ServiceAccessType::IMPLICIT_ACCESS
)
1913 ->FlushForTest(base::Bind(
1914 &base::MessageLoop::Quit
,
1915 base::Unretained(base::MessageLoop::current()->current())));
1916 content::RunMessageLoop();
1919 #if defined(OS_CHROMEOS)
1920 // Times out on ChromeOS: http://crbug.com/217810
1921 #define MAYBE_DownloadTest_History DISABLED_DownloadTest_History
1923 #define MAYBE_DownloadTest_History DownloadTest_History
1925 IN_PROC_BROWSER_TEST_F(DownloadTest
, MAYBE_DownloadTest_History
) {
1926 // This starts up right after PRE_DownloadTest_History and shares the same
1927 // profile directory.
1928 base::FilePath
file(FILE_PATH_LITERAL("download-test1.lib"));
1929 GURL
download_url(URLRequestMockHTTPJob::GetMockUrl(file
));
1930 std::vector
<DownloadItem
*> downloads
;
1931 content::DownloadManager
* manager
= DownloadManagerForBrowser(browser());
1933 // Wait for the history to be loaded with a single DownloadItem. Check that
1934 // it's the file that was downloaded in PRE_DownloadTest_History.
1935 CreatedObserver
created_observer(manager
);
1936 created_observer
.Wait();
1937 manager
->GetAllDownloads(&downloads
);
1938 ASSERT_EQ(1UL, downloads
.size());
1939 DownloadItem
* item
= downloads
[0];
1940 EXPECT_EQ(file
.value(), item
->GetFullPath().BaseName().value());
1941 EXPECT_EQ(file
.value(), item
->GetTargetFilePath().BaseName().value());
1942 EXPECT_EQ(download_url
, item
->GetURL());
1943 // The following are set by download-test1.lib.mock-http-headers.
1944 std::string etag
= item
->GetETag();
1945 base::TrimWhitespaceASCII(etag
, base::TRIM_ALL
, &etag
);
1946 EXPECT_EQ("abracadabra", etag
);
1948 std::string last_modified
= item
->GetLastModifiedTime();
1949 base::TrimWhitespaceASCII(last_modified
, base::TRIM_ALL
, &last_modified
);
1950 EXPECT_EQ("Mon, 13 Nov 2006 20:31:09 GMT", last_modified
);
1952 // Downloads that were restored from history shouldn't cause the download
1953 // shelf to be displayed.
1954 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
1957 // Test for crbug.com/14505. This tests that chrome:// urls are still functional
1958 // after download of a file while viewing another chrome://.
1959 IN_PROC_BROWSER_TEST_F(DownloadTest
, ChromeURLAfterDownload
) {
1960 base::FilePath
file(FILE_PATH_LITERAL("download-test1.lib"));
1961 GURL
download_url(URLRequestMockHTTPJob::GetMockUrl(file
));
1962 GURL
flags_url(chrome::kChromeUIFlagsURL
);
1963 GURL
extensions_url(chrome::kChromeUIExtensionsFrameURL
);
1965 ui_test_utils::NavigateToURL(browser(), flags_url
);
1966 DownloadAndWait(browser(), download_url
);
1967 ui_test_utils::NavigateToURL(browser(), extensions_url
);
1968 WebContents
* contents
=
1969 browser()->tab_strip_model()->GetActiveWebContents();
1970 ASSERT_TRUE(contents
);
1971 bool webui_responded
= false;
1972 EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
1974 "window.domAutomationController.send(window.webuiResponded);",
1976 EXPECT_TRUE(webui_responded
);
1979 // Test for crbug.com/12745. This tests that if a download is initiated from
1980 // a chrome:// page that has registered and onunload handler, the browser
1981 // will be able to close.
1982 IN_PROC_BROWSER_TEST_F(DownloadTest
, BrowserCloseAfterDownload
) {
1983 GURL
downloads_url(chrome::kChromeUIFlagsURL
);
1984 base::FilePath
file(FILE_PATH_LITERAL("download-test1.lib"));
1985 GURL
download_url(URLRequestMockHTTPJob::GetMockUrl(file
));
1987 ui_test_utils::NavigateToURL(browser(), downloads_url
);
1988 WebContents
* contents
= browser()->tab_strip_model()->GetActiveWebContents();
1989 ASSERT_TRUE(contents
);
1990 bool result
= false;
1991 EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
1993 "window.onunload = function() { var do_nothing = 0; }; "
1994 "window.domAutomationController.send(true);",
1996 EXPECT_TRUE(result
);
1998 DownloadAndWait(browser(), download_url
);
2000 content::WindowedNotificationObserver
signal(
2001 chrome::NOTIFICATION_BROWSER_CLOSED
,
2002 content::Source
<Browser
>(browser()));
2003 chrome::CloseWindow(browser());
2007 // Test to make sure the 'download' attribute in anchor tag is respected.
2008 IN_PROC_BROWSER_TEST_F(DownloadTest
, AnchorDownloadTag
) {
2009 base::FilePath
file(FILE_PATH_LITERAL("download-anchor-attrib.html"));
2010 GURL
url(URLRequestMockHTTPJob::GetMockUrl(file
));
2012 // Create a download, wait until it's complete, and confirm
2013 // we're in the expected state.
2014 scoped_ptr
<content::DownloadTestObserver
> observer(
2015 CreateWaiter(browser(), 1));
2016 ui_test_utils::NavigateToURL(browser(), url
);
2017 observer
->WaitForFinished();
2018 EXPECT_EQ(1u, observer
->NumDownloadsSeenInState(DownloadItem::COMPLETE
));
2019 CheckDownloadStates(1, DownloadItem::COMPLETE
);
2021 // Confirm the downloaded data exists.
2022 base::FilePath downloaded_file
= GetDownloadDirectory(browser());
2023 downloaded_file
= downloaded_file
.Append(FILE_PATH_LITERAL("a_red_dot.png"));
2024 EXPECT_TRUE(base::PathExists(downloaded_file
));
2027 // Test to make sure auto-open works.
2028 IN_PROC_BROWSER_TEST_F(DownloadTest
, AutoOpen
) {
2029 base::FilePath
file(FILE_PATH_LITERAL("download-autoopen.txt"));
2030 GURL
url(URLRequestMockHTTPJob::GetMockUrl(file
));
2033 GetDownloadPrefs(browser())->EnableAutoOpenBasedOnExtension(file
));
2035 DownloadAndWait(browser(), url
);
2037 // Find the download and confirm it was opened.
2038 std::vector
<DownloadItem
*> downloads
;
2039 DownloadManagerForBrowser(browser())->GetAllDownloads(&downloads
);
2040 ASSERT_EQ(1u, downloads
.size());
2041 EXPECT_EQ(DownloadItem::COMPLETE
, downloads
[0]->GetState());
2043 // Unfortunately, this will block forever, causing a timeout, if
2044 // the download is never opened.
2045 content::DownloadUpdatedObserver(
2046 downloads
[0], base::Bind(&WasAutoOpened
)).WaitForEvent();
2047 EXPECT_TRUE(downloads
[0]->GetOpened()); // Confirm it anyway.
2049 // As long as we're here, confirmed everything else is good.
2050 EXPECT_EQ(1, browser()->tab_strip_model()->count());
2051 CheckDownload(browser(), file
, file
);
2052 // Download shelf should close. Download panel stays open on ChromeOS.
2053 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
2056 // Download an extension. Expect a dangerous download warning.
2057 // Deny the download.
2058 IN_PROC_BROWSER_TEST_F(DownloadTest
, CrxDenyInstall
) {
2059 FeatureSwitch::ScopedOverride
enable_easy_off_store_install(
2060 FeatureSwitch::easy_off_store_install(), true);
2062 GURL
extension_url(URLRequestMockHTTPJob::GetMockUrl(kGoodCrxPath
));
2064 scoped_ptr
<content::DownloadTestObserver
> observer(
2065 DangerousDownloadWaiter(
2067 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_DENY
));
2068 ui_test_utils::NavigateToURL(browser(), extension_url
);
2070 observer
->WaitForFinished();
2071 EXPECT_EQ(1u, observer
->NumDownloadsSeenInState(DownloadItem::CANCELLED
));
2072 EXPECT_EQ(1u, observer
->NumDangerousDownloadsSeen());
2074 // Download shelf should close.
2075 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
2077 // Check that the CRX is not installed.
2078 ExtensionService
* extension_service
= extensions::ExtensionSystem::Get(
2079 browser()->profile())->extension_service();
2080 ASSERT_FALSE(extension_service
->GetExtensionById(kGoodCrxId
, false));
2083 // Download an extension. Expect a dangerous download warning.
2084 // Allow the download, deny the install.
2085 IN_PROC_BROWSER_TEST_F(DownloadTest
, CrxInstallDenysPermissions
) {
2086 FeatureSwitch::ScopedOverride
enable_easy_off_store_install(
2087 FeatureSwitch::easy_off_store_install(), true);
2089 GURL
extension_url(URLRequestMockHTTPJob::GetMockUrl(kGoodCrxPath
));
2091 // Install a mock install UI that simulates a user denying permission to
2092 // finish the install.
2093 download_crx_util::SetMockInstallPromptForTesting(
2094 scoped_ptr
<ExtensionInstallPrompt
>(
2095 new MockAbortExtensionInstallPrompt()));
2097 scoped_ptr
<content::DownloadTestObserver
> observer(
2098 DangerousDownloadWaiter(
2100 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_ACCEPT
));
2101 ui_test_utils::NavigateToURL(browser(), extension_url
);
2103 observer
->WaitForFinished();
2104 EXPECT_EQ(1u, observer
->NumDownloadsSeenInState(DownloadItem::COMPLETE
));
2105 CheckDownloadStates(1, DownloadItem::COMPLETE
);
2106 EXPECT_EQ(1u, observer
->NumDangerousDownloadsSeen());
2108 // Download shelf should close from auto-open.
2109 content::DownloadManager::DownloadVector downloads
;
2110 DownloadManagerForBrowser(browser())->GetAllDownloads(&downloads
);
2111 ASSERT_EQ(1u, downloads
.size());
2112 content::DownloadUpdatedObserver(
2113 downloads
[0], base::Bind(&WasAutoOpened
)).WaitForEvent();
2114 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
2116 // Check that the extension was not installed.
2117 ExtensionService
* extension_service
= extensions::ExtensionSystem::Get(
2118 browser()->profile())->extension_service();
2119 ASSERT_FALSE(extension_service
->GetExtensionById(kGoodCrxId
, false));
2122 // Download an extension. Expect a dangerous download warning.
2123 // Allow the download, and the install.
2124 IN_PROC_BROWSER_TEST_F(DownloadTest
, CrxInstallAcceptPermissions
) {
2125 FeatureSwitch::ScopedOverride
enable_easy_off_store_install(
2126 FeatureSwitch::easy_off_store_install(), true);
2128 GURL
extension_url(URLRequestMockHTTPJob::GetMockUrl(kGoodCrxPath
));
2130 // Install a mock install UI that simulates a user allowing permission to
2131 // finish the install.
2132 SetAllowMockInstallPrompt();
2134 scoped_ptr
<content::DownloadTestObserver
> observer(
2135 DangerousDownloadWaiter(
2137 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_ACCEPT
));
2138 ui_test_utils::NavigateToURL(browser(), extension_url
);
2140 observer
->WaitForFinished();
2141 EXPECT_EQ(1u, observer
->NumDownloadsSeenInState(DownloadItem::COMPLETE
));
2142 CheckDownloadStates(1, DownloadItem::COMPLETE
);
2143 EXPECT_EQ(1u, observer
->NumDangerousDownloadsSeen());
2145 // Download shelf should close from auto-open.
2146 content::DownloadManager::DownloadVector downloads
;
2147 DownloadManagerForBrowser(browser())->GetAllDownloads(&downloads
);
2148 ASSERT_EQ(1u, downloads
.size());
2149 content::DownloadUpdatedObserver(
2150 downloads
[0], base::Bind(&WasAutoOpened
)).WaitForEvent();
2151 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
2153 // Check that the extension was installed.
2154 ExtensionService
* extension_service
= extensions::ExtensionSystem::Get(
2155 browser()->profile())->extension_service();
2156 ASSERT_TRUE(extension_service
->GetExtensionById(kGoodCrxId
, false));
2159 // Test installing a CRX that fails integrity checks.
2160 IN_PROC_BROWSER_TEST_F(DownloadTest
, CrxInvalid
) {
2161 base::FilePath
file(FILE_PATH_LITERAL("extensions/bad_signature.crx"));
2162 GURL
extension_url(URLRequestMockHTTPJob::GetMockUrl(file
));
2164 // Install a mock install UI that simulates a user allowing permission to
2165 // finish the install, and dismisses any error message. We check that the
2166 // install failed below.
2167 SetAllowMockInstallPrompt();
2169 scoped_ptr
<content::DownloadTestObserver
> observer(
2170 DangerousDownloadWaiter(
2172 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_ACCEPT
));
2173 ui_test_utils::NavigateToURL(browser(), extension_url
);
2175 observer
->WaitForFinished();
2176 EXPECT_EQ(1u, observer
->NumDownloadsSeenInState(DownloadItem::COMPLETE
));
2177 CheckDownloadStates(1, DownloadItem::COMPLETE
);
2179 // Check that the extension was not installed.
2180 ExtensionService
* extension_service
= extensions::ExtensionSystem::Get(
2181 browser()->profile())->extension_service();
2182 ASSERT_FALSE(extension_service
->GetExtensionById(kGoodCrxId
, false));
2185 // Install a large (100kb) theme.
2186 IN_PROC_BROWSER_TEST_F(DownloadTest
, CrxLargeTheme
) {
2187 FeatureSwitch::ScopedOverride
enable_easy_off_store_install(
2188 FeatureSwitch::easy_off_store_install(), true);
2190 GURL
extension_url(URLRequestMockHTTPJob::GetMockUrl(kLargeThemePath
));
2192 // Install a mock install UI that simulates a user allowing permission to
2193 // finish the install.
2194 SetAllowMockInstallPrompt();
2196 scoped_ptr
<content::DownloadTestObserver
> observer(
2197 DangerousDownloadWaiter(
2199 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_ACCEPT
));
2200 ui_test_utils::NavigateToURL(browser(), extension_url
);
2202 observer
->WaitForFinished();
2203 EXPECT_EQ(1u, observer
->NumDownloadsSeenInState(DownloadItem::COMPLETE
));
2204 CheckDownloadStates(1, DownloadItem::COMPLETE
);
2205 EXPECT_EQ(1u, observer
->NumDangerousDownloadsSeen());
2207 // Download shelf should close from auto-open.
2208 content::DownloadManager::DownloadVector downloads
;
2209 DownloadManagerForBrowser(browser())->GetAllDownloads(&downloads
);
2210 ASSERT_EQ(1u, downloads
.size());
2211 content::DownloadUpdatedObserver(
2212 downloads
[0], base::Bind(&WasAutoOpened
)).WaitForEvent();
2213 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
2215 // Check that the extension was installed.
2216 ExtensionService
* extension_service
= extensions::ExtensionSystem::Get(
2217 browser()->profile())->extension_service();
2218 ASSERT_TRUE(extension_service
->GetExtensionById(kLargeThemeCrxId
, false));
2221 // Tests for download initiation functions.
2222 IN_PROC_BROWSER_TEST_F(DownloadTest
, DownloadUrl
) {
2223 base::FilePath
file(FILE_PATH_LITERAL("download-test1.lib"));
2224 GURL
url(URLRequestMockHTTPJob::GetMockUrl(file
));
2226 // DownloadUrl always prompts; return acceptance of whatever it prompts.
2227 EnableFileChooser(true);
2229 WebContents
* web_contents
=
2230 browser()->tab_strip_model()->GetActiveWebContents();
2231 ASSERT_TRUE(web_contents
);
2233 content::DownloadTestObserver
* observer(
2234 new content::DownloadTestObserverTerminal(
2235 DownloadManagerForBrowser(browser()), 1,
2236 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL
));
2237 scoped_ptr
<DownloadUrlParameters
> params(
2238 DownloadUrlParameters::FromWebContents(web_contents
, url
));
2239 params
->set_prompt(true);
2240 DownloadManagerForBrowser(browser())->DownloadUrl(params
.Pass());
2241 observer
->WaitForFinished();
2242 EXPECT_EQ(1u, observer
->NumDownloadsSeenInState(DownloadItem::COMPLETE
));
2243 CheckDownloadStates(1, DownloadItem::COMPLETE
);
2244 EXPECT_TRUE(DidShowFileChooser());
2247 EXPECT_EQ(1, browser()->tab_strip_model()->count());
2248 ASSERT_TRUE(CheckDownload(browser(), file
, file
));
2249 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
2252 IN_PROC_BROWSER_TEST_F(DownloadTest
, DownloadUrlToPath
) {
2253 base::FilePath
file(FILE_PATH_LITERAL("download-test1.lib"));
2254 GURL
url(URLRequestMockHTTPJob::GetMockUrl(file
));
2256 WebContents
* web_contents
=
2257 browser()->tab_strip_model()->GetActiveWebContents();
2258 ASSERT_TRUE(web_contents
);
2260 base::ScopedTempDir other_directory
;
2261 ASSERT_TRUE(other_directory
.CreateUniqueTempDir());
2262 base::FilePath target_file_full_path
2263 = other_directory
.path().Append(file
.BaseName());
2264 content::DownloadTestObserver
* observer(CreateWaiter(browser(), 1));
2265 scoped_ptr
<DownloadUrlParameters
> params(
2266 DownloadUrlParameters::FromWebContents(web_contents
, url
));
2267 params
->set_file_path(target_file_full_path
);
2268 DownloadManagerForBrowser(browser())->DownloadUrl(params
.Pass());
2269 observer
->WaitForFinished();
2270 EXPECT_EQ(1u, observer
->NumDownloadsSeenInState(DownloadItem::COMPLETE
));
2273 EXPECT_EQ(1, browser()->tab_strip_model()->count());
2274 ASSERT_TRUE(CheckDownloadFullPaths(browser(),
2275 target_file_full_path
,
2278 // Temporary are treated as auto-opened, and after that open won't be
2279 // visible; wait for auto-open and confirm not visible.
2280 std::vector
<DownloadItem
*> downloads
;
2281 DownloadManagerForBrowser(browser())->GetAllDownloads(&downloads
);
2282 ASSERT_EQ(1u, downloads
.size());
2283 content::DownloadUpdatedObserver(
2284 downloads
[0], base::Bind(&WasAutoOpened
)).WaitForEvent();
2285 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
2288 IN_PROC_BROWSER_TEST_F(DownloadTest
, SavePageNonHTMLViaGet
) {
2289 // Do initial setup.
2290 ASSERT_TRUE(test_server()->Start());
2291 EnableFileChooser(true);
2292 std::vector
<DownloadItem
*> download_items
;
2293 GetDownloads(browser(), &download_items
);
2294 ASSERT_TRUE(download_items
.empty());
2296 // Navigate to a non-HTML resource. The resource also has
2297 // Cache-Control: no-cache set, which normally requires revalidation
2299 GURL url
= test_server()->GetURL("files/downloads/image.jpg");
2300 ASSERT_TRUE(url
.is_valid());
2301 ui_test_utils::NavigateToURL(browser(), url
);
2303 // Stop the test server, and then try to save the page. If cache validation
2304 // is not bypassed then this will fail since the server is no longer
2306 ASSERT_TRUE(test_server()->Stop());
2307 scoped_ptr
<content::DownloadTestObserver
> waiter(
2308 new content::DownloadTestObserverTerminal(
2309 DownloadManagerForBrowser(browser()), 1,
2310 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL
));
2311 chrome::SavePage(browser());
2312 waiter
->WaitForFinished();
2313 EXPECT_EQ(1u, waiter
->NumDownloadsSeenInState(DownloadItem::COMPLETE
));
2314 CheckDownloadStates(1, DownloadItem::COMPLETE
);
2316 // Validate that the correct file was downloaded.
2317 GetDownloads(browser(), &download_items
);
2318 EXPECT_TRUE(DidShowFileChooser());
2319 ASSERT_EQ(1u, download_items
.size());
2320 ASSERT_EQ(url
, download_items
[0]->GetOriginalUrl());
2322 // Try to download it via a context menu.
2323 scoped_ptr
<content::DownloadTestObserver
> waiter_context_menu(
2324 new content::DownloadTestObserverTerminal(
2325 DownloadManagerForBrowser(browser()), 1,
2326 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL
));
2327 content::ContextMenuParams context_menu_params
;
2328 context_menu_params
.media_type
= blink::WebContextMenuData::MediaTypeImage
;
2329 context_menu_params
.src_url
= url
;
2330 context_menu_params
.page_url
= url
;
2331 TestRenderViewContextMenu
menu(
2332 browser()->tab_strip_model()->GetActiveWebContents()->GetMainFrame(),
2333 context_menu_params
);
2335 menu
.ExecuteCommand(IDC_CONTENT_CONTEXT_SAVEIMAGEAS
, 0);
2336 waiter_context_menu
->WaitForFinished();
2338 1u, waiter_context_menu
->NumDownloadsSeenInState(DownloadItem::COMPLETE
));
2339 CheckDownloadStates(2, DownloadItem::COMPLETE
);
2341 // Validate that the correct file was downloaded via the context menu.
2342 download_items
.clear();
2343 GetDownloads(browser(), &download_items
);
2344 EXPECT_TRUE(DidShowFileChooser());
2345 ASSERT_EQ(2u, download_items
.size());
2346 ASSERT_EQ(url
, download_items
[0]->GetOriginalUrl());
2347 ASSERT_EQ(url
, download_items
[1]->GetOriginalUrl());
2350 IN_PROC_BROWSER_TEST_F(DownloadTest
, SavePageNonHTMLViaPost
) {
2351 // Do initial setup.
2352 ASSERT_TRUE(test_server()->Start());
2353 EnableFileChooser(true);
2354 std::vector
<DownloadItem
*> download_items
;
2355 GetDownloads(browser(), &download_items
);
2356 ASSERT_TRUE(download_items
.empty());
2358 // Navigate to a form page.
2359 GURL form_url
= test_server()->GetURL(
2360 "files/downloads/form_page_to_post.html");
2361 ASSERT_TRUE(form_url
.is_valid());
2362 ui_test_utils::NavigateToURL(browser(), form_url
);
2364 // Submit the form. This will send a POST reqeuest, and the response is a
2365 // JPEG image. The resource also has Cache-Control: no-cache set,
2366 // which normally requires revalidation each time.
2367 GURL jpeg_url
= test_server()->GetURL("files/post/downloads/image.jpg");
2368 ASSERT_TRUE(jpeg_url
.is_valid());
2369 WebContents
* web_contents
=
2370 browser()->tab_strip_model()->GetActiveWebContents();
2371 ASSERT_TRUE(web_contents
!= NULL
);
2372 content::WindowedNotificationObserver
observer(
2373 content::NOTIFICATION_NAV_ENTRY_COMMITTED
,
2374 content::Source
<content::NavigationController
>(
2375 &web_contents
->GetController()));
2376 content::RenderFrameHost
* render_frame_host
= web_contents
->GetMainFrame();
2377 ASSERT_TRUE(render_frame_host
!= NULL
);
2378 render_frame_host
->ExecuteJavaScript(base::ASCIIToUTF16("SubmitForm()"));
2380 EXPECT_EQ(jpeg_url
, web_contents
->GetURL());
2382 // Stop the test server, and then try to save the page. If cache validation
2383 // is not bypassed then this will fail since the server is no longer
2384 // reachable. This will also fail if it tries to be retrieved via "GET"
2385 // rather than "POST".
2386 ASSERT_TRUE(test_server()->Stop());
2387 scoped_ptr
<content::DownloadTestObserver
> waiter(
2388 new content::DownloadTestObserverTerminal(
2389 DownloadManagerForBrowser(browser()), 1,
2390 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL
));
2391 chrome::SavePage(browser());
2392 waiter
->WaitForFinished();
2393 EXPECT_EQ(1u, waiter
->NumDownloadsSeenInState(DownloadItem::COMPLETE
));
2394 CheckDownloadStates(1, DownloadItem::COMPLETE
);
2396 // Validate that the correct file was downloaded.
2397 GetDownloads(browser(), &download_items
);
2398 EXPECT_TRUE(DidShowFileChooser());
2399 ASSERT_EQ(1u, download_items
.size());
2400 ASSERT_EQ(jpeg_url
, download_items
[0]->GetOriginalUrl());
2402 // Try to download it via a context menu.
2403 scoped_ptr
<content::DownloadTestObserver
> waiter_context_menu(
2404 new content::DownloadTestObserverTerminal(
2405 DownloadManagerForBrowser(browser()), 1,
2406 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL
));
2407 content::ContextMenuParams context_menu_params
;
2408 context_menu_params
.media_type
= blink::WebContextMenuData::MediaTypeImage
;
2409 context_menu_params
.src_url
= jpeg_url
;
2410 context_menu_params
.page_url
= jpeg_url
;
2411 TestRenderViewContextMenu
menu(web_contents
->GetMainFrame(),
2412 context_menu_params
);
2414 menu
.ExecuteCommand(IDC_CONTENT_CONTEXT_SAVEIMAGEAS
, 0);
2415 waiter_context_menu
->WaitForFinished();
2417 1u, waiter_context_menu
->NumDownloadsSeenInState(DownloadItem::COMPLETE
));
2418 CheckDownloadStates(2, DownloadItem::COMPLETE
);
2420 // Validate that the correct file was downloaded via the context menu.
2421 download_items
.clear();
2422 GetDownloads(browser(), &download_items
);
2423 EXPECT_TRUE(DidShowFileChooser());
2424 ASSERT_EQ(2u, download_items
.size());
2425 ASSERT_EQ(jpeg_url
, download_items
[0]->GetOriginalUrl());
2426 ASSERT_EQ(jpeg_url
, download_items
[1]->GetOriginalUrl());
2429 IN_PROC_BROWSER_TEST_F(DownloadTest
, DownloadErrorsServer
) {
2430 DownloadInfo download_info
[] = {
2431 { // Normal navigated download.
2434 content::DOWNLOAD_INTERRUPT_REASON_NONE
,
2438 { // Normal direct download.
2441 content::DOWNLOAD_INTERRUPT_REASON_NONE
,
2445 { // Direct download with 404 error.
2446 "there_IS_no_spoon.zip",
2448 content::DOWNLOAD_INTERRUPT_REASON_SERVER_BAD_CONTENT
,
2452 { // Navigated download with 404 error.
2453 "there_IS_no_spoon.zip",
2455 content::DOWNLOAD_INTERRUPT_REASON_SERVER_BAD_CONTENT
,
2459 { // Direct download with 400 error.
2460 "zip_file_not_found.zip",
2462 content::DOWNLOAD_INTERRUPT_REASON_SERVER_FAILED
,
2466 { // Navigated download with 400 error.
2467 "zip_file_not_found.zip",
2469 content::DOWNLOAD_INTERRUPT_REASON_SERVER_FAILED
,
2475 DownloadFilesCheckErrors(arraysize(download_info
), download_info
);
2478 IN_PROC_BROWSER_TEST_F(DownloadTest
, DownloadErrorsFile
) {
2479 FileErrorInjectInfo error_info
[] = {
2480 { // Navigated download with injected "Disk full" error in Initialize().
2483 content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE
,
2488 content::TestFileErrorInjector::FILE_OPERATION_INITIALIZE
,
2490 content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE
,
2493 { // Direct download with injected "Disk full" error in Initialize().
2496 content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE
,
2501 content::TestFileErrorInjector::FILE_OPERATION_INITIALIZE
,
2503 content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE
,
2506 { // Navigated download with injected "Disk full" error in Write().
2509 content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE
,
2514 content::TestFileErrorInjector::FILE_OPERATION_WRITE
,
2516 content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE
,
2519 { // Direct download with injected "Disk full" error in Write().
2522 content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE
,
2527 content::TestFileErrorInjector::FILE_OPERATION_WRITE
,
2529 content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE
,
2532 { // Navigated download with injected "Failed" error in Initialize().
2535 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED
,
2540 content::TestFileErrorInjector::FILE_OPERATION_INITIALIZE
,
2542 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED
,
2545 { // Direct download with injected "Failed" error in Initialize().
2548 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED
,
2553 content::TestFileErrorInjector::FILE_OPERATION_INITIALIZE
,
2555 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED
,
2558 { // Navigated download with injected "Failed" error in Write().
2561 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED
,
2566 content::TestFileErrorInjector::FILE_OPERATION_WRITE
,
2568 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED
,
2571 { // Direct download with injected "Failed" error in Write().
2574 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED
,
2579 content::TestFileErrorInjector::FILE_OPERATION_WRITE
,
2581 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED
,
2584 { // Navigated download with injected "Name too long" error in
2588 content::DOWNLOAD_INTERRUPT_REASON_FILE_NAME_TOO_LONG
,
2593 content::TestFileErrorInjector::FILE_OPERATION_INITIALIZE
,
2595 content::DOWNLOAD_INTERRUPT_REASON_FILE_NAME_TOO_LONG
,
2598 { // Direct download with injected "Name too long" error in Initialize().
2601 content::DOWNLOAD_INTERRUPT_REASON_FILE_NAME_TOO_LONG
,
2606 content::TestFileErrorInjector::FILE_OPERATION_INITIALIZE
,
2608 content::DOWNLOAD_INTERRUPT_REASON_FILE_NAME_TOO_LONG
,
2611 { // Navigated download with injected "Name too long" error in Write().
2614 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED
,
2619 content::TestFileErrorInjector::FILE_OPERATION_WRITE
,
2621 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED
,
2624 { // Direct download with injected "Name too long" error in Write().
2627 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED
,
2632 content::TestFileErrorInjector::FILE_OPERATION_WRITE
,
2634 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED
,
2637 { // Direct download with injected "Disk full" error in 2nd Write().
2638 { "06bESSE21Evolution.ppt",
2640 content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE
,
2645 content::TestFileErrorInjector::FILE_OPERATION_WRITE
,
2647 content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE
,
2652 DownloadInsertFilesErrorCheckErrors(arraysize(error_info
), error_info
);
2655 IN_PROC_BROWSER_TEST_F(DownloadTest
, DownloadErrorReadonlyFolder
) {
2656 DownloadInfo download_info
[] = {
2660 // This passes because we switch to the My Documents folder.
2661 content::DOWNLOAD_INTERRUPT_REASON_NONE
,
2668 // This passes because we switch to the My Documents folder.
2669 content::DOWNLOAD_INTERRUPT_REASON_NONE
,
2675 DownloadFilesToReadonlyFolder(arraysize(download_info
), download_info
);
2678 // Test that we show a dangerous downloads warning for a dangerous file
2679 // downloaded through a blob: URL.
2680 IN_PROC_BROWSER_TEST_F(DownloadTest
, DownloadDangerousBlobData
) {
2682 // On Windows, if SafeBrowsing is enabled, certain file types (.exe, .cab,
2683 // .msi) will be handled by the DownloadProtectionService. However, if the URL
2684 // is non-standard (e.g. blob:) then those files won't be handled by the
2685 // DPS. We should be showing the dangerous download warning for any file
2686 // considered dangerous and isn't handled by the DPS.
2687 const char kFilename
[] = "foo.exe";
2689 const char kFilename
[] = "foo.swf";
2692 std::string
path("files/downloads/download-dangerous-blob.html?filename=");
2695 // Need to use http urls because the blob js doesn't work on file urls for
2696 // security reasons.
2697 ASSERT_TRUE(test_server()->Start());
2698 GURL
url(test_server()->GetURL(path
));
2700 content::DownloadTestObserver
* observer(DangerousDownloadWaiter(
2702 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_ACCEPT
));
2703 ui_test_utils::NavigateToURL(browser(), url
);
2704 observer
->WaitForFinished();
2706 EXPECT_EQ(1u, observer
->NumDownloadsSeenInState(DownloadItem::COMPLETE
));
2707 EXPECT_EQ(1u, observer
->NumDangerousDownloadsSeen());
2710 IN_PROC_BROWSER_TEST_F(DownloadTest
, LoadURLExternallyReferrerPolicy
) {
2711 // Do initial setup.
2712 ASSERT_TRUE(test_server()->Start());
2713 EnableFileChooser(true);
2714 std::vector
<DownloadItem
*> download_items
;
2715 GetDownloads(browser(), &download_items
);
2716 ASSERT_TRUE(download_items
.empty());
2718 // Navigate to a page with a referrer policy and a link on it. The link points
2719 // to testserver's /echoheader.
2720 GURL url
= test_server()->GetURL("files/downloads/referrer_policy.html");
2721 ASSERT_TRUE(url
.is_valid());
2722 ui_test_utils::NavigateToURL(browser(), url
);
2724 scoped_ptr
<content::DownloadTestObserver
> waiter(
2725 new content::DownloadTestObserverTerminal(
2726 DownloadManagerForBrowser(browser()), 1,
2727 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL
));
2729 // Click on the link with the alt key pressed. This will download the link
2731 WebContents
* tab
= browser()->tab_strip_model()->GetActiveWebContents();
2732 blink::WebMouseEvent mouse_event
;
2733 mouse_event
.type
= blink::WebInputEvent::MouseDown
;
2734 mouse_event
.button
= blink::WebMouseEvent::ButtonLeft
;
2737 mouse_event
.clickCount
= 1;
2738 mouse_event
.modifiers
= blink::WebInputEvent::AltKey
;
2739 tab
->GetRenderViewHost()->ForwardMouseEvent(mouse_event
);
2740 mouse_event
.type
= blink::WebInputEvent::MouseUp
;
2741 tab
->GetRenderViewHost()->ForwardMouseEvent(mouse_event
);
2743 waiter
->WaitForFinished();
2744 EXPECT_EQ(1u, waiter
->NumDownloadsSeenInState(DownloadItem::COMPLETE
));
2745 CheckDownloadStates(1, DownloadItem::COMPLETE
);
2747 // Validate that the correct file was downloaded.
2748 GetDownloads(browser(), &download_items
);
2749 ASSERT_EQ(1u, download_items
.size());
2750 ASSERT_EQ(test_server()->GetURL("echoheader?Referer"),
2751 download_items
[0]->GetOriginalUrl());
2753 // Check that the file contains the expected referrer.
2754 base::FilePath
file(download_items
[0]->GetTargetFilePath());
2755 std::string expected_contents
= test_server()->GetURL(std::string()).spec();
2756 ASSERT_TRUE(VerifyFile(file
, expected_contents
, expected_contents
.length()));
2759 // This test ensures that the Referer header is properly sanitized when
2760 // Save Link As is chosen from the context menu.
2761 IN_PROC_BROWSER_TEST_F(DownloadTest
, SaveLinkAsReferrerPolicyOrigin
) {
2762 // Do initial setup.
2763 ASSERT_TRUE(test_server()->Start());
2764 net::SpawnedTestServer
ssl_test_server(
2765 net::SpawnedTestServer::TYPE_HTTPS
,
2766 net::SpawnedTestServer::kLocalhost
,
2767 base::FilePath(FILE_PATH_LITERAL("chrome/test/data/referrer_policy")));
2768 ASSERT_TRUE(ssl_test_server
.Start());
2769 EnableFileChooser(true);
2770 std::vector
<DownloadItem
*> download_items
;
2771 GetDownloads(browser(), &download_items
);
2772 ASSERT_TRUE(download_items
.empty());
2774 // Navigate to the initial page, where Save Link As will be executed.
2775 GURL url
= ssl_test_server
.GetURL(
2776 std::string("files/referrer-policy-start.html?policy=origin") +
2777 "&port=" + base::IntToString(test_server()->host_port_pair().port()) +
2779 base::IntToString(ssl_test_server
.host_port_pair().port()) +
2780 "&redirect=echoheader&link=true&target=");
2781 ASSERT_TRUE(url
.is_valid());
2782 ui_test_utils::NavigateToURL(browser(), url
);
2784 scoped_ptr
<content::DownloadTestObserver
> waiter(
2785 new content::DownloadTestObserverTerminal(
2786 DownloadManagerForBrowser(browser()), 1,
2787 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL
));
2789 // Right-click on the link and choose Save Link As. This will download the
2791 ContextMenuNotificationObserver
context_menu_observer(
2792 IDC_CONTENT_CONTEXT_SAVELINKAS
);
2794 WebContents
* tab
= browser()->tab_strip_model()->GetActiveWebContents();
2795 blink::WebMouseEvent mouse_event
;
2796 mouse_event
.type
= blink::WebInputEvent::MouseDown
;
2797 mouse_event
.button
= blink::WebMouseEvent::ButtonRight
;
2800 mouse_event
.clickCount
= 1;
2801 tab
->GetRenderViewHost()->ForwardMouseEvent(mouse_event
);
2802 mouse_event
.type
= blink::WebInputEvent::MouseUp
;
2803 tab
->GetRenderViewHost()->ForwardMouseEvent(mouse_event
);
2805 waiter
->WaitForFinished();
2806 EXPECT_EQ(1u, waiter
->NumDownloadsSeenInState(DownloadItem::COMPLETE
));
2807 CheckDownloadStates(1, DownloadItem::COMPLETE
);
2809 // Validate that the correct file was downloaded.
2810 GetDownloads(browser(), &download_items
);
2811 EXPECT_EQ(1u, download_items
.size());
2812 EXPECT_EQ(test_server()->GetURL("echoheader?Referer"),
2813 download_items
[0]->GetOriginalUrl());
2815 // Check that the file contains the expected referrer.
2816 base::FilePath
file(download_items
[0]->GetTargetFilePath());
2817 std::string expected_contents
= ssl_test_server
.GetURL(std::string()).spec();
2818 EXPECT_TRUE(VerifyFile(file
, expected_contents
, expected_contents
.length()));
2821 // This test ensures that the Referer header is properly sanitized when
2822 // Save Image As is chosen from the context menu. The test succeeds if
2823 // it doesn't crash.
2824 IN_PROC_BROWSER_TEST_F(DownloadTest
, SaveImageAsReferrerPolicyDefault
) {
2825 // Do initial setup.
2826 ASSERT_TRUE(test_server()->Start());
2827 net::SpawnedTestServer
ssl_test_server(
2828 net::SpawnedTestServer::TYPE_HTTPS
,
2829 net::SpawnedTestServer::kLocalhost
,
2830 base::FilePath(FILE_PATH_LITERAL("chrome/test/data/")));
2831 ASSERT_TRUE(ssl_test_server
.Start());
2832 EnableFileChooser(true);
2833 std::vector
<DownloadItem
*> download_items
;
2834 GetDownloads(browser(), &download_items
);
2835 ASSERT_TRUE(download_items
.empty());
2837 GURL url
= ssl_test_server
.GetURL("files/title1.html");
2838 GURL img_url
= test_server()->GetURL("files/downloads/image.jpg");
2839 ASSERT_TRUE(url
.is_valid());
2840 ui_test_utils::NavigateToURL(browser(), url
);
2842 // Try to download an image via a context menu.
2843 scoped_ptr
<content::DownloadTestObserver
> waiter_context_menu(
2844 new content::DownloadTestObserverTerminal(
2845 DownloadManagerForBrowser(browser()), 1,
2846 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL
));
2847 content::ContextMenuParams context_menu_params
;
2848 context_menu_params
.media_type
= blink::WebContextMenuData::MediaTypeImage
;
2849 context_menu_params
.page_url
= url
;
2850 context_menu_params
.src_url
= img_url
;
2851 TestRenderViewContextMenu
menu(
2852 browser()->tab_strip_model()->GetActiveWebContents()->GetMainFrame(),
2853 context_menu_params
);
2855 menu
.ExecuteCommand(IDC_CONTENT_CONTEXT_SAVEIMAGEAS
, 0);
2856 waiter_context_menu
->WaitForFinished();
2858 1u, waiter_context_menu
->NumDownloadsSeenInState(DownloadItem::COMPLETE
));
2859 CheckDownloadStates(1, DownloadItem::COMPLETE
);
2861 // Validate that the correct file was downloaded via the context menu.
2862 download_items
.clear();
2863 GetDownloads(browser(), &download_items
);
2864 EXPECT_TRUE(DidShowFileChooser());
2865 ASSERT_EQ(1u, download_items
.size());
2866 ASSERT_EQ(img_url
, download_items
[0]->GetOriginalUrl());
2869 IN_PROC_BROWSER_TEST_F(DownloadTest
, HiddenDownload
) {
2870 base::FilePath
file(FILE_PATH_LITERAL("download-test1.lib"));
2871 GURL
url(URLRequestMockHTTPJob::GetMockUrl(file
));
2873 DownloadManager
* download_manager
= DownloadManagerForBrowser(browser());
2874 scoped_ptr
<content::DownloadTestObserver
> observer(
2875 new content::DownloadTestObserverTerminal(
2878 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL
));
2880 // Download and set IsHiddenDownload to true.
2881 WebContents
* web_contents
=
2882 browser()->tab_strip_model()->GetActiveWebContents();
2883 scoped_ptr
<DownloadUrlParameters
> params(
2884 DownloadUrlParameters::FromWebContents(web_contents
, url
));
2885 params
->set_callback(base::Bind(&SetHiddenDownloadCallback
));
2886 download_manager
->DownloadUrl(params
.Pass());
2887 observer
->WaitForFinished();
2889 // Verify that download shelf is not shown.
2890 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
2893 // Verify the multiple downloads infobar.
2894 IN_PROC_BROWSER_TEST_F(DownloadTest
, TestMultipleDownloadsInfobar
) {
2895 #if defined(OS_WIN) && defined(USE_ASH)
2896 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
2897 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
2898 switches::kAshBrowserTests
))
2902 ASSERT_TRUE(test_server()->Start());
2904 // Ensure that infobars are being used instead of bubbles.
2905 base::CommandLine::ForCurrentProcess()->AppendSwitch(
2906 switches::kDisablePermissionsBubbles
);
2908 // Create a downloads observer.
2909 scoped_ptr
<content::DownloadTestObserver
> downloads_observer(
2910 CreateWaiter(browser(), 2));
2912 // Create an infobar observer.
2913 content::WindowedNotificationObserver
infobar_added_1(
2914 chrome::NOTIFICATION_TAB_CONTENTS_INFOBAR_ADDED
,
2915 content::NotificationService::AllSources());
2916 ui_test_utils::NavigateToURL(
2918 test_server()->GetURL("files/downloads/download-a_zip_file.html"));
2919 infobar_added_1
.Wait();
2921 InfoBarService
* infobar_service
= InfoBarService::FromWebContents(
2922 browser()->tab_strip_model()->GetActiveWebContents());
2923 // Verify that there is only one infobar.
2924 ASSERT_EQ(1u, infobar_service
->infobar_count());
2926 // Get the infobar at index 0.
2927 infobars::InfoBar
* infobar
= infobar_service
->infobar_at(0);
2928 ConfirmInfoBarDelegate
* confirm_infobar
=
2929 infobar
->delegate()->AsConfirmInfoBarDelegate();
2930 ASSERT_TRUE(confirm_infobar
!= NULL
);
2932 // Verify multi download warning infobar message.
2933 EXPECT_EQ(confirm_infobar
->GetMessageText(),
2934 l10n_util::GetStringUTF16(IDS_MULTI_DOWNLOAD_WARNING
));
2936 // Click on the "Allow" button to allow multiple downloads.
2937 if (confirm_infobar
->Accept())
2938 infobar_service
->RemoveInfoBar(infobar
);
2939 // Verify that there are no more infobars.
2940 EXPECT_EQ(0u, infobar_service
->infobar_count());
2942 // Waits for the download to complete.
2943 downloads_observer
->WaitForFinished();
2944 EXPECT_EQ(2u, downloads_observer
->NumDownloadsSeenInState(
2945 DownloadItem::COMPLETE
));
2948 IN_PROC_BROWSER_TEST_F(DownloadTest
, TestMultipleDownloadsBubble
) {
2949 #if defined(OS_WIN) && defined(USE_ASH)
2950 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
2951 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
2952 switches::kAshBrowserTests
))
2956 #if defined(OS_ANDROID) || defined(OS_IOS)
2957 // Permission bubbles are not supported on mobile.
2961 ASSERT_TRUE(test_server()->Start());
2963 // Enable permision bubbles.
2964 base::CommandLine::ForCurrentProcess()->AppendSwitch(
2965 switches::kEnablePermissionsBubbles
);
2967 // Create a downloads observer.
2968 scoped_ptr
<content::DownloadTestObserver
> downloads_observer(
2969 CreateWaiter(browser(), 2));
2971 MockPermissionBubbleView
* mock_bubble_view
= new MockPermissionBubbleView();
2972 PermissionBubbleManager::FromWebContents(
2973 browser()->tab_strip_model()->GetActiveWebContents())->
2974 SetView(mock_bubble_view
);
2975 mock_bubble_view
->SetBrowserTest(true);
2976 ui_test_utils::NavigateToURLBlockUntilNavigationsComplete(
2978 test_server()->GetURL("files/downloads/download-a_zip_file.html"), 1);
2980 WaitForBubble(mock_bubble_view
);
2982 ASSERT_TRUE(mock_bubble_view
->IsVisible());
2983 mock_bubble_view
->Accept();
2984 ASSERT_FALSE(mock_bubble_view
->IsVisible());
2986 // Waits for the download to complete.
2987 downloads_observer
->WaitForFinished();
2988 EXPECT_EQ(2u, downloads_observer
->NumDownloadsSeenInState(
2989 DownloadItem::COMPLETE
));
2991 browser()->tab_strip_model()->GetActiveWebContents()->Close();
2992 delete mock_bubble_view
;
2995 IN_PROC_BROWSER_TEST_F(DownloadTest
, DownloadTest_Renaming
) {
2996 ASSERT_TRUE(test_server()->Start());
2997 GURL
url(test_server()->GetURL("files/downloads/a_zip_file.zip"));
2998 content::DownloadManager
* manager
= DownloadManagerForBrowser(browser());
2999 base::FilePath
origin_file(OriginFile(base::FilePath(FILE_PATH_LITERAL(
3000 "downloads/a_zip_file.zip"))));
3001 ASSERT_TRUE(base::PathExists(origin_file
));
3002 std::string origin_contents
;
3003 ASSERT_TRUE(base::ReadFileToString(origin_file
, &origin_contents
));
3005 // Download the same url several times and expect that all downloaded files
3006 // after the zero-th contain a deduplication counter.
3007 for (int index
= 0; index
< 5; ++index
) {
3008 DownloadAndWait(browser(), url
);
3009 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
3010 content::DownloadItem
* item
= manager
->GetDownload(
3011 content::DownloadItem::kInvalidId
+ 1 + index
);
3013 ASSERT_EQ(DownloadItem::COMPLETE
, item
->GetState());
3014 base::FilePath
target_path(item
->GetTargetFilePath());
3015 EXPECT_EQ(std::string("a_zip_file") +
3016 (index
== 0 ? std::string(".zip") :
3017 base::StringPrintf(" (%d).zip", index
)),
3018 target_path
.BaseName().AsUTF8Unsafe());
3019 ASSERT_TRUE(base::PathExists(target_path
));
3020 ASSERT_TRUE(VerifyFile(target_path
, origin_contents
,
3021 origin_contents
.size()));
3025 // Test that the entire download pipeline handles unicode correctly.
3026 // Disabled on Windows due to flaky timeouts: crbug.com/446695
3028 #define MAYBE_DownloadTest_CrazyFilenames DISABLED_DownloadTest_CrazyFilenames
3030 #define MAYBE_DownloadTest_CrazyFilenames DownloadTest_CrazyFilenames
3032 IN_PROC_BROWSER_TEST_F(DownloadTest
, MAYBE_DownloadTest_CrazyFilenames
) {
3033 const wchar_t* kCrazyFilenames
[] = {
3035 L
"\u89c6\u9891\u76f4\u64ad\u56fe\u7247.zip", // chinese chars
3036 L
"\u0412\u043e \u0424\u043b\u043e\u0440\u0438\u0434\u0435\u043e\u0431\u044a"
3037 L
"\u044f\u0432\u043b\u0435\u043d\u0440\u0435\u0436\u0438\u043c \u0427"
3038 L
"\u041f \u0438\u0437-\u0437\u0430 \u0443\u0442\u0435\u0447\u043a\u0438 "
3039 L
"\u043d\u0435\u0444\u0442\u0438.zip", // russian
3040 L
"Desocupa\xe7\xe3o est\xe1vel.zip",
3042 L
"\u0638\u2026\u0638\u02c6\u0637\xa7\u0638\u201a\u0637\xb9 \u0638\u201e"
3043 L
"\u0638\u201e\u0637\xb2\u0638\u0679\u0637\xa7\u0637\xb1\u0637\xa9.zip",
3044 L
"\u05d4\u05e2\u05d3\u05e4\u05d5\u05ea.zip", // hebrew
3045 L
"\u092d\u093e\u0930\u0924.zip", // hindi
3046 L
"d\xe9stabilis\xe9.zip", // french
3048 L
"\u97d3-\u4e2d \uc815\uc0c1, \ucc9c\uc548\ud568 \uc758\uacac.zip",
3049 L
"jiho....tiho...miho.zip",
3050 L
"jiho!@#$tiho$%^&-()_+=miho copy.zip", // special chars
3051 L
"Wohoo-to hoo+I.zip",
3053 L
"This is a very very long english sentence with spaces and , and +.zip",
3056 std::vector
<DownloadItem
*> download_items
;
3057 base::FilePath
origin(FILE_PATH_LITERAL("origin"));
3058 ASSERT_TRUE(base::CreateDirectory(DestinationFile(browser(), origin
)));
3060 for (size_t index
= 0; index
< arraysize(kCrazyFilenames
); ++index
) {
3061 base::string16 crazy16
;
3063 const wchar_t* crazy_w
= kCrazyFilenames
[index
];
3064 ASSERT_TRUE(base::WideToUTF8(crazy_w
, wcslen(crazy_w
), &crazy8
));
3065 ASSERT_TRUE(base::WideToUTF16(crazy_w
, wcslen(crazy_w
), &crazy16
));
3066 base::FilePath
file_path(DestinationFile(browser(), origin
.Append(
3069 #elif defined(OS_POSIX)
3075 EXPECT_EQ(static_cast<int>(crazy8
.size()),
3076 base::WriteFile(file_path
, crazy8
.c_str(), crazy8
.size()));
3077 GURL
file_url(net::FilePathToFileURL(file_path
));
3079 // Download the file and check that the filename is correct.
3080 DownloadAndWait(browser(), file_url
);
3081 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
3082 GetDownloads(browser(), &download_items
);
3083 ASSERT_EQ(1UL, download_items
.size());
3084 base::FilePath
downloaded(download_items
[0]->GetTargetFilePath());
3085 download_items
[0]->Remove();
3086 download_items
.clear();
3087 ASSERT_TRUE(CheckDownloadFullPaths(
3094 IN_PROC_BROWSER_TEST_F(DownloadTest
, DownloadTest_Remove
) {
3095 ASSERT_TRUE(test_server()->Start());
3096 GURL
url(test_server()->GetURL("files/downloads/a_zip_file.zip"));
3097 std::vector
<DownloadItem
*> download_items
;
3098 GetDownloads(browser(), &download_items
);
3099 ASSERT_TRUE(download_items
.empty());
3102 DownloadAndWaitWithDisposition(browser(),
3105 ui_test_utils::BROWSER_TEST_NONE
);
3106 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
3107 GetDownloads(browser(), &download_items
);
3108 ASSERT_EQ(1UL, download_items
.size());
3109 base::FilePath
downloaded(download_items
[0]->GetTargetFilePath());
3111 // Remove the DownloadItem but not the file, then check that the file still
3113 download_items
[0]->Remove();
3114 download_items
.clear();
3115 GetDownloads(browser(), &download_items
);
3116 ASSERT_EQ(0UL, download_items
.size());
3117 ASSERT_TRUE(CheckDownloadFullPaths(
3118 browser(), downloaded
, OriginFile(base::FilePath(
3119 FILE_PATH_LITERAL("downloads/a_zip_file.zip")))));
3122 IN_PROC_BROWSER_TEST_F(DownloadTest
, DownloadTest_PauseResumeCancel
) {
3123 DownloadItem
* download_item
= CreateSlowTestDownload();
3124 ASSERT_TRUE(download_item
);
3125 ASSERT_FALSE(download_item
->GetTargetFilePath().empty());
3126 EXPECT_FALSE(download_item
->IsPaused());
3127 EXPECT_NE(DownloadItem::CANCELLED
, download_item
->GetState());
3128 download_item
->Pause();
3129 EXPECT_TRUE(download_item
->IsPaused());
3130 download_item
->Resume();
3131 EXPECT_FALSE(download_item
->IsPaused());
3132 EXPECT_NE(DownloadItem::CANCELLED
, download_item
->GetState());
3133 download_item
->Cancel(true);
3134 EXPECT_EQ(DownloadItem::CANCELLED
, download_item
->GetState());
3137 // The Mac downloaded files quarantine feature is implemented by the
3138 // Contents/Info.plist file in cocoa apps. browser_tests cannot test
3139 // quarantining files on Mac because it is not a cocoa app.
3140 // TODO(benjhayden) test the equivalents on other platforms.
3142 #if defined(OS_LINUX) && !defined(OS_CHROMEOS) && defined(ARCH_CPU_ARM_FAMILY)
3143 // Timing out on ARM linux: http://crbug.com/238459
3144 #define MAYBE_DownloadTest_PercentComplete DISABLED_DownloadTest_PercentComplete
3145 #elif defined(OS_MACOSX)
3146 // Disable on mac: http://crbug.com/238831
3147 #define MAYBE_DownloadTest_PercentComplete DISABLED_DownloadTest_PercentComplete
3149 #define MAYBE_DownloadTest_PercentComplete DownloadTest_PercentComplete
3151 IN_PROC_BROWSER_TEST_F(DownloadTest
, MAYBE_DownloadTest_PercentComplete
) {
3152 // Write a huge file.
3153 base::FilePath
file_path(DestinationFile(
3154 browser(), base::FilePath(FILE_PATH_LITERAL("DownloadTest_BigZip.zip"))));
3155 base::File
file(file_path
, base::File::FLAG_CREATE
| base::File::FLAG_WRITE
);
3156 ASSERT_TRUE(file
.IsValid());
3157 int64 size
= 1 << 25;
3158 EXPECT_EQ(1, file
.Write(size
, "a", 1));
3161 #if defined(OS_POSIX)
3162 // Make it readable by chronos on chromeos
3163 base::SetPosixFilePermissions(file_path
, 0755);
3166 // Ensure that we have enough disk space.
3167 int64 free_space
= base::SysInfo::AmountOfFreeDiskSpace(
3168 GetDownloadDirectory(browser()));
3169 ASSERT_LE(size
, free_space
) << "Not enough disk space to download. Got "
3171 GURL
file_url(net::FilePathToFileURL(file_path
));
3172 scoped_ptr
<content::DownloadTestObserver
> progress_waiter(
3173 CreateInProgressWaiter(browser(), 1));
3175 // Start downloading a file, wait for it to be created.
3176 ui_test_utils::NavigateToURLWithDisposition(
3177 browser(), file_url
, CURRENT_TAB
, ui_test_utils::BROWSER_TEST_NONE
);
3178 progress_waiter
->WaitForFinished();
3179 EXPECT_EQ(1u, progress_waiter
->NumDownloadsSeenInState(
3180 DownloadItem::IN_PROGRESS
));
3181 std::vector
<DownloadItem
*> download_items
;
3182 GetDownloads(browser(), &download_items
);
3183 ASSERT_EQ(1UL, download_items
.size());
3185 // Wait for the download to complete, checking along the way that the
3186 // PercentComplete() never regresses.
3187 PercentWaiter
waiter(download_items
[0]);
3188 EXPECT_TRUE(waiter
.WaitForFinished());
3189 EXPECT_EQ(DownloadItem::COMPLETE
, download_items
[0]->GetState());
3190 ASSERT_EQ(100, download_items
[0]->PercentComplete());
3191 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
3193 // Check that the file downloaded correctly.
3194 ASSERT_TRUE(base::PathExists(download_items
[0]->GetTargetFilePath()));
3195 int64 downloaded_size
= 0;
3196 ASSERT_TRUE(base::GetFileSize(
3197 download_items
[0]->GetTargetFilePath(), &downloaded_size
));
3198 ASSERT_EQ(size
+ 1, downloaded_size
);
3199 ASSERT_TRUE(base::DieFileDie(file_path
, false));
3200 ASSERT_TRUE(base::DieFileDie(download_items
[0]->GetTargetFilePath(), false));
3203 IN_PROC_BROWSER_TEST_F(DownloadTest
, DownloadTest_DenyDanger
) {
3204 ASSERT_TRUE(test_server()->Start());
3205 GURL
url(test_server()->GetURL("files/downloads/dangerous/dangerous.crx"));
3206 scoped_ptr
<content::DownloadTestObserver
> observer(
3207 DangerousDownloadWaiter(
3209 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_DENY
));
3210 ui_test_utils::NavigateToURL(browser(), url
);
3211 observer
->WaitForFinished();
3212 EXPECT_EQ(1u, observer
->NumDownloadsSeenInState(DownloadItem::CANCELLED
));
3213 EXPECT_EQ(1u, observer
->NumDangerousDownloadsSeen());
3214 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
3217 IN_PROC_BROWSER_TEST_F(DownloadTest
, DownloadPrefs_SaveFilePath
) {
3218 DownloadPrefs
* on_prefs
= DownloadServiceFactory::GetForBrowserContext(
3219 browser()->profile())->GetDownloadManagerDelegate()->download_prefs();
3220 DownloadPrefs
* off_prefs
= DownloadServiceFactory::GetForBrowserContext(
3221 browser()->profile()->GetOffTheRecordProfile())
3222 ->GetDownloadManagerDelegate()->download_prefs();
3223 base::FilePath
dir(on_prefs
->SaveFilePath());
3224 EXPECT_EQ(dir
.value(), off_prefs
->SaveFilePath().value());
3226 on_prefs
->SetSaveFilePath(dir
.AppendASCII("on"));
3227 EXPECT_EQ(dir
.AppendASCII("on").value(), on_prefs
->SaveFilePath().value());
3228 EXPECT_EQ(dir
.AppendASCII("on").value(), off_prefs
->SaveFilePath().value());
3230 on_prefs
->SetSaveFilePath(dir
);
3231 EXPECT_EQ(dir
.value(), on_prefs
->SaveFilePath().value());
3232 EXPECT_EQ(dir
.value(), off_prefs
->SaveFilePath().value());
3234 off_prefs
->SetSaveFilePath(dir
.AppendASCII("off"));
3235 EXPECT_EQ(dir
.value(), on_prefs
->SaveFilePath().value());
3236 EXPECT_EQ(dir
.AppendASCII("off").value(), off_prefs
->SaveFilePath().value());
3238 on_prefs
->SetSaveFilePath(dir
.AppendASCII("on"));
3239 EXPECT_EQ(dir
.AppendASCII("on").value(), on_prefs
->SaveFilePath().value());
3240 EXPECT_EQ(dir
.AppendASCII("off").value(), off_prefs
->SaveFilePath().value());
3243 // A download that is interrupted due to a file error should be able to be
3245 IN_PROC_BROWSER_TEST_F(DownloadTest
, Resumption_NoPrompt
) {
3246 base::CommandLine::ForCurrentProcess()->AppendSwitch(
3247 switches::kEnableDownloadResumption
);
3248 scoped_refptr
<content::TestFileErrorInjector
> error_injector(
3249 content::TestFileErrorInjector::Create(
3250 DownloadManagerForBrowser(browser())));
3251 scoped_ptr
<content::DownloadTestObserver
> completion_observer(
3252 CreateWaiter(browser(), 1));
3253 EnableFileChooser(true);
3255 DownloadItem
* download
= StartMockDownloadAndInjectError(
3256 error_injector
.get(), content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED
);
3257 ASSERT_TRUE(download
);
3260 completion_observer
->WaitForFinished();
3263 1u, completion_observer
->NumDownloadsSeenInState(DownloadItem::COMPLETE
));
3264 EXPECT_FALSE(DidShowFileChooser());
3267 // A download that's interrupted due to a reason that indicates that the target
3268 // path is invalid or unusable should cause a prompt to be displayed on
3270 IN_PROC_BROWSER_TEST_F(DownloadTest
, Resumption_WithPrompt
) {
3271 base::CommandLine::ForCurrentProcess()->AppendSwitch(
3272 switches::kEnableDownloadResumption
);
3273 scoped_refptr
<content::TestFileErrorInjector
> error_injector(
3274 content::TestFileErrorInjector::Create(
3275 DownloadManagerForBrowser(browser())));
3276 scoped_ptr
<content::DownloadTestObserver
> completion_observer(
3277 CreateWaiter(browser(), 1));
3278 EnableFileChooser(true);
3280 DownloadItem
* download
= StartMockDownloadAndInjectError(
3281 error_injector
.get(), content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE
);
3282 ASSERT_TRUE(download
);
3285 completion_observer
->WaitForFinished();
3288 1u, completion_observer
->NumDownloadsSeenInState(DownloadItem::COMPLETE
));
3289 EXPECT_TRUE(DidShowFileChooser());
3292 // The user shouldn't be prompted on a resumed download unless a prompt is
3293 // necessary due to the interrupt reason.
3294 IN_PROC_BROWSER_TEST_F(DownloadTest
, Resumption_WithPromptAlways
) {
3295 base::CommandLine::ForCurrentProcess()->AppendSwitch(
3296 switches::kEnableDownloadResumption
);
3297 browser()->profile()->GetPrefs()->SetBoolean(
3298 prefs::kPromptForDownload
, true);
3299 scoped_refptr
<content::TestFileErrorInjector
> error_injector(
3300 content::TestFileErrorInjector::Create(
3301 DownloadManagerForBrowser(browser())));
3302 scoped_ptr
<content::DownloadTestObserver
> completion_observer(
3303 CreateWaiter(browser(), 1));
3304 EnableFileChooser(true);
3306 DownloadItem
* download
= StartMockDownloadAndInjectError(
3307 error_injector
.get(), content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED
);
3308 ASSERT_TRUE(download
);
3310 // Prompts the user initially because of the kPromptForDownload preference.
3311 EXPECT_TRUE(DidShowFileChooser());
3314 completion_observer
->WaitForFinished();
3317 1u, completion_observer
->NumDownloadsSeenInState(DownloadItem::COMPLETE
));
3318 // Shouldn't prompt for resumption.
3319 EXPECT_FALSE(DidShowFileChooser());
3322 // A download that is interrupted due to a transient error should be resumed
3324 IN_PROC_BROWSER_TEST_F(DownloadTest
, Resumption_Automatic
) {
3325 base::CommandLine::ForCurrentProcess()->AppendSwitch(
3326 switches::kEnableDownloadResumption
);
3327 scoped_refptr
<content::TestFileErrorInjector
> error_injector(
3328 content::TestFileErrorInjector::Create(
3329 DownloadManagerForBrowser(browser())));
3331 DownloadItem
* download
= StartMockDownloadAndInjectError(
3332 error_injector
.get(),
3333 content::DOWNLOAD_INTERRUPT_REASON_FILE_TRANSIENT_ERROR
);
3334 ASSERT_TRUE(download
);
3336 // The number of times this the download is resumed automatically is defined
3337 // in DownloadItemImpl::kMaxAutoResumeAttempts. The number of DownloadFiles
3338 // created should be that number + 1 (for the original download request). We
3339 // only care that it is greater than 1.
3340 EXPECT_GT(1u, error_injector
->TotalFileCount());
3343 // An interrupting download should be resumable multiple times.
3344 IN_PROC_BROWSER_TEST_F(DownloadTest
, Resumption_MultipleAttempts
) {
3345 base::CommandLine::ForCurrentProcess()->AppendSwitch(
3346 switches::kEnableDownloadResumption
);
3347 scoped_refptr
<content::TestFileErrorInjector
> error_injector(
3348 content::TestFileErrorInjector::Create(
3349 DownloadManagerForBrowser(browser())));
3350 scoped_ptr
<DownloadTestObserverNotInProgress
> completion_observer(
3351 new DownloadTestObserverNotInProgress(
3352 DownloadManagerForBrowser(browser()), 1));
3353 // Wait for two transitions to a resumable state
3354 scoped_ptr
<content::DownloadTestObserver
> resumable_observer(
3355 new DownloadTestObserverResumable(
3356 DownloadManagerForBrowser(browser()), 2));
3358 EnableFileChooser(true);
3359 DownloadItem
* download
= StartMockDownloadAndInjectError(
3360 error_injector
.get(), content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED
);
3361 ASSERT_TRUE(download
);
3363 content::TestFileErrorInjector::FileErrorInfo error_info
;
3364 error_info
.url
= download
->GetOriginalUrl().spec();
3365 error_info
.code
= content::TestFileErrorInjector::FILE_OPERATION_WRITE
;
3366 error_info
.operation_instance
= 0;
3367 error_info
.error
= content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED
;
3368 error_injector
->AddError(error_info
);
3369 error_injector
->InjectErrors();
3371 // Resuming should cause the download to be interrupted again due to the
3372 // errors we are injecting.
3374 resumable_observer
->WaitForFinished();
3375 ASSERT_EQ(DownloadItem::INTERRUPTED
, download
->GetState());
3376 ASSERT_EQ(content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED
,
3377 download
->GetLastReason());
3379 error_injector
->ClearErrors();
3380 error_injector
->InjectErrors();
3382 // No errors this time. The download should complete successfully.
3383 EXPECT_FALSE(completion_observer
->IsFinished());
3384 completion_observer
->StartObserving();
3386 completion_observer
->WaitForFinished();
3387 EXPECT_EQ(DownloadItem::COMPLETE
, download
->GetState());
3389 EXPECT_FALSE(DidShowFileChooser());
3392 // The file empty.bin is served with a MIME type of application/octet-stream.
3393 // The content body is empty. Make sure this case is handled properly and we
3394 // don't regress on http://crbug.com/320394.
3395 IN_PROC_BROWSER_TEST_F(DownloadTest
, DownloadTest_GZipWithNoContent
) {
3396 ASSERT_TRUE(test_server()->Start());
3397 GURL
url(test_server()->GetURL("files/downloads/empty.bin"));
3398 // Downloading the same URL twice causes the second request to be served from
3399 // cached (with a high probability). This test verifies that that doesn't
3400 // happen regardless of whether the request is served via the cache or from
3402 DownloadAndWait(browser(), url
);
3403 DownloadAndWait(browser(), url
);
3406 #if defined(FULL_SAFE_BROWSING)
3408 // The following two tests are only meaningful on OS_WIN since that's the only
3409 // platform where client download checks are currently performed.
3410 // TODO(asanka): Relax this restriction as other platforms are added.
3414 // This is a custom DownloadTestObserver for
3415 // DangerousFileWithSBDisabledBeforeCompletion test that disables the
3416 // SafeBrowsing service when a single download is IN_PROGRESS and has a target
3417 // path assigned. DownloadItemImpl is expected to call MaybeCompleteDownload
3418 // soon afterwards and we want to disable the service before then.
3419 class DisableSafeBrowsingOnInProgressDownload
3420 : public content::DownloadTestObserver
{
3422 explicit DisableSafeBrowsingOnInProgressDownload(Browser
* browser
)
3423 : DownloadTestObserver(DownloadManagerForBrowser(browser
),
3425 ON_DANGEROUS_DOWNLOAD_QUIT
),
3427 final_state_seen_(false) {
3430 virtual ~DisableSafeBrowsingOnInProgressDownload() {}
3432 virtual bool IsDownloadInFinalState(DownloadItem
* download
) override
{
3433 if (download
->GetState() != DownloadItem::IN_PROGRESS
||
3434 download
->GetTargetFilePath().empty())
3437 if (final_state_seen_
)
3440 final_state_seen_
= true;
3441 browser_
->profile()->GetPrefs()->SetBoolean(prefs::kSafeBrowsingEnabled
,
3443 EXPECT_EQ(content::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT
,
3444 download
->GetDangerType());
3445 EXPECT_FALSE(download
->IsDangerous());
3446 EXPECT_TRUE(DownloadItemModel(download
).IsDangerousFileBasedOnType());
3452 bool final_state_seen_
;
3457 IN_PROC_BROWSER_TEST_F(DownloadTest
,
3458 DangerousFileWithSBDisabledBeforeCompletion
) {
3459 browser()->profile()->GetPrefs()->SetBoolean(prefs::kSafeBrowsingEnabled
,
3461 ASSERT_TRUE(test_server()->Start());
3463 test_server()->GetURL("files/downloads/dangerous/dangerous.exe"));
3464 scoped_ptr
<content::DownloadTestObserver
> dangerous_observer(
3465 DangerousDownloadWaiter(
3468 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_QUIT
));
3469 scoped_ptr
<content::DownloadTestObserver
> in_progress_observer(
3470 new DisableSafeBrowsingOnInProgressDownload(browser()));
3471 ui_test_utils::NavigateToURLWithDisposition(browser(),
3474 ui_test_utils::BROWSER_TEST_NONE
);
3475 in_progress_observer
->WaitForFinished();
3477 // SafeBrowsing should have been disabled by our observer.
3478 ASSERT_FALSE(browser()->profile()->GetPrefs()->GetBoolean(
3479 prefs::kSafeBrowsingEnabled
));
3481 std::vector
<DownloadItem
*> downloads
;
3482 DownloadManagerForBrowser(browser())->GetAllDownloads(&downloads
);
3483 ASSERT_EQ(1u, downloads
.size());
3484 DownloadItem
* download
= downloads
[0];
3486 dangerous_observer
->WaitForFinished();
3488 EXPECT_TRUE(download
->IsDangerous());
3489 EXPECT_EQ(content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE
,
3490 download
->GetDangerType());
3491 download
->Cancel(true);
3494 IN_PROC_BROWSER_TEST_F(DownloadTest
, DangerousFileWithSBDisabledBeforeStart
) {
3495 // Disable SafeBrowsing
3496 browser()->profile()->GetPrefs()->SetBoolean(prefs::kSafeBrowsingEnabled
,
3499 ASSERT_TRUE(test_server()->Start());
3501 test_server()->GetURL("files/downloads/dangerous/dangerous.exe"));
3502 scoped_ptr
<content::DownloadTestObserver
> dangerous_observer(
3503 DangerousDownloadWaiter(
3506 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_QUIT
));
3507 ui_test_utils::NavigateToURLWithDisposition(browser(),
3510 ui_test_utils::BROWSER_TEST_NONE
);
3511 dangerous_observer
->WaitForFinished();
3513 std::vector
<DownloadItem
*> downloads
;
3514 DownloadManagerForBrowser(browser())->GetAllDownloads(&downloads
);
3515 ASSERT_EQ(1u, downloads
.size());
3517 DownloadItem
* download
= downloads
[0];
3518 EXPECT_TRUE(download
->IsDangerous());
3519 EXPECT_EQ(content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE
,
3520 download
->GetDangerType());
3522 download
->Cancel(true);
3525 IN_PROC_BROWSER_TEST_F(DownloadTest
, SafeSupportedFile
) {
3526 ASSERT_TRUE(test_server()->Start());
3527 GURL
download_url(test_server()->GetURL("files/downloads/a_zip_file.zip"));
3528 DownloadAndWait(browser(), download_url
);
3530 std::vector
<DownloadItem
*> downloads
;
3531 DownloadManagerForBrowser(browser())->GetAllDownloads(&downloads
);
3532 ASSERT_EQ(1u, downloads
.size());
3534 DownloadItem
* download
= downloads
[0];
3535 EXPECT_FALSE(download
->IsDangerous());
3536 EXPECT_EQ(content::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT
,
3537 download
->GetDangerType());
3539 download
->Cancel(true);
3544 IN_PROC_BROWSER_TEST_F(DownloadTest
, FeedbackService
) {
3545 // Make a dangerous file.
3546 base::FilePath
file(FILE_PATH_LITERAL("downloads/dangerous/dangerous.swf"));
3547 GURL
download_url(net::URLRequestMockHTTPJob::GetMockUrl(file
));
3548 scoped_ptr
<content::DownloadTestObserverInterrupted
> observer(
3549 new content::DownloadTestObserverInterrupted(
3550 DownloadManagerForBrowser(browser()), 1,
3551 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_QUIT
));
3552 ui_test_utils::NavigateToURLWithDisposition(
3556 ui_test_utils::BROWSER_TEST_NONE
);
3557 observer
->WaitForFinished();
3559 // Get the download from the DownloadManager.
3560 std::vector
<DownloadItem
*> downloads
;
3561 DownloadManagerForBrowser(browser())->GetAllDownloads(&downloads
);
3562 ASSERT_EQ(1u, downloads
.size());
3563 EXPECT_TRUE(downloads
[0]->IsDangerous());
3565 // Save fake pings for the download.
3566 safe_browsing::ClientDownloadReport fake_metadata
;
3567 fake_metadata
.mutable_download_request()->set_url("http://test");
3568 fake_metadata
.mutable_download_request()->set_length(1);
3569 fake_metadata
.mutable_download_request()->mutable_digests()->set_sha1("hi");
3570 fake_metadata
.mutable_download_response()->set_verdict(
3571 safe_browsing::ClientDownloadResponse::UNCOMMON
);
3572 std::string
ping_request(
3573 fake_metadata
.download_request().SerializeAsString());
3574 std::string
ping_response(
3575 fake_metadata
.download_response().SerializeAsString());
3576 SafeBrowsingService
* sb_service
= g_browser_process
->safe_browsing_service();
3577 safe_browsing::DownloadProtectionService
* download_protection_service
=
3578 sb_service
->download_protection_service();
3579 download_protection_service
->feedback_service()->MaybeStorePingsForDownload(
3580 safe_browsing::DownloadProtectionService::UNCOMMON
,
3584 ASSERT_TRUE(safe_browsing::DownloadFeedbackService::IsEnabledForDownload(
3587 // Begin feedback and check that the file is "stolen".
3588 download_protection_service
->feedback_service()->BeginFeedbackForDownload(
3590 std::vector
<DownloadItem
*> updated_downloads
;
3591 GetDownloads(browser(), &updated_downloads
);
3592 ASSERT_TRUE(updated_downloads
.empty());