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/download/notification/download_notification_manager.h"
41 #include "chrome/browser/extensions/extension_install_prompt.h"
42 #include "chrome/browser/extensions/extension_install_prompt_show_params.h"
43 #include "chrome/browser/extensions/extension_service.h"
44 #include "chrome/browser/history/history_service_factory.h"
45 #include "chrome/browser/infobars/infobar_service.h"
46 #include "chrome/browser/net/url_request_mock_util.h"
47 #include "chrome/browser/profiles/profile.h"
48 #include "chrome/browser/renderer_context_menu/render_view_context_menu_browsertest_util.h"
49 #include "chrome/browser/renderer_context_menu/render_view_context_menu_test_util.h"
50 #include "chrome/browser/ui/browser.h"
51 #include "chrome/browser/ui/browser_commands.h"
52 #include "chrome/browser/ui/browser_finder.h"
53 #include "chrome/browser/ui/browser_list.h"
54 #include "chrome/browser/ui/browser_tabstrip.h"
55 #include "chrome/browser/ui/browser_window.h"
56 #include "chrome/browser/ui/chrome_pages.h"
57 #include "chrome/browser/ui/host_desktop.h"
58 #include "chrome/browser/ui/tabs/tab_strip_model.h"
59 #include "chrome/browser/ui/website_settings/permission_bubble_manager.h"
60 #include "chrome/common/chrome_paths.h"
61 #include "chrome/common/chrome_switches.h"
62 #include "chrome/common/pref_names.h"
63 #include "chrome/common/safe_browsing/csd.pb.h"
64 #include "chrome/common/url_constants.h"
65 #include "chrome/grit/generated_resources.h"
66 #include "chrome/test/base/in_process_browser_test.h"
67 #include "chrome/test/base/test_switches.h"
68 #include "chrome/test/base/ui_test_utils.h"
69 #include "components/history/content/browser/download_constants_utils.h"
70 #include "components/history/core/browser/download_constants.h"
71 #include "components/history/core/browser/download_row.h"
72 #include "components/history/core/browser/history_service.h"
73 #include "components/infobars/core/confirm_infobar_delegate.h"
74 #include "components/infobars/core/infobar.h"
75 #include "content/public/browser/download_interrupt_reasons.h"
76 #include "content/public/browser/download_item.h"
77 #include "content/public/browser/download_manager.h"
78 #include "content/public/browser/download_save_info.h"
79 #include "content/public/browser/download_url_parameters.h"
80 #include "content/public/browser/notification_source.h"
81 #include "content/public/browser/render_frame_host.h"
82 #include "content/public/browser/render_view_host.h"
83 #include "content/public/browser/resource_context.h"
84 #include "content/public/browser/web_contents.h"
85 #include "content/public/common/content_switches.h"
86 #include "content/public/common/context_menu_params.h"
87 #include "content/public/test/browser_test_utils.h"
88 #include "content/public/test/download_test_observer.h"
89 #include "content/public/test/test_file_error_injector.h"
90 #include "content/public/test/test_navigation_observer.h"
91 #include "extensions/browser/extension_system.h"
92 #include "extensions/common/feature_switch.h"
93 #include "net/base/filename_util.h"
94 #include "net/test/embedded_test_server/embedded_test_server.h"
95 #include "net/test/embedded_test_server/http_request.h"
96 #include "net/test/embedded_test_server/http_response.h"
97 #include "net/test/url_request/url_request_mock_http_job.h"
98 #include "net/test/url_request/url_request_slow_download_job.h"
99 #include "testing/gtest/include/gtest/gtest.h"
100 #include "ui/base/l10n/l10n_util.h"
101 #include "ui/base/page_transition_types.h"
103 #if defined(FULL_SAFE_BROWSING)
104 #include "chrome/browser/safe_browsing/download_feedback_service.h"
105 #include "chrome/browser/safe_browsing/download_protection_service.h"
106 #include "chrome/browser/safe_browsing/safe_browsing_database.h"
107 #include "chrome/browser/safe_browsing/safe_browsing_service.h"
110 using content::BrowserContext
;
111 using content::BrowserThread
;
112 using content::DownloadItem
;
113 using content::DownloadManager
;
114 using content::DownloadUrlParameters
;
115 using content::WebContents
;
116 using extensions::Extension
;
117 using extensions::FeatureSwitch
;
118 using net::URLRequestMockHTTPJob
;
122 class CreatedObserver
: public content::DownloadManager::Observer
{
124 explicit CreatedObserver(content::DownloadManager
* manager
)
127 manager
->AddObserver(this);
129 ~CreatedObserver() override
{
131 manager_
->RemoveObserver(this);
135 std::vector
<DownloadItem
*> downloads
;
136 manager_
->GetAllDownloads(&downloads
);
137 if (!downloads
.empty())
140 content::RunMessageLoop();
145 void OnDownloadCreated(content::DownloadManager
* manager
,
146 content::DownloadItem
* item
) override
{
147 DCHECK_EQ(manager_
, manager
);
149 base::MessageLoopForUI::current()->Quit();
152 content::DownloadManager
* manager_
;
155 DISALLOW_COPY_AND_ASSIGN(CreatedObserver
);
158 class PercentWaiter
: public content::DownloadItem::Observer
{
160 explicit PercentWaiter(DownloadItem
* item
)
165 item_
->AddObserver(this);
167 ~PercentWaiter() override
{
169 item_
->RemoveObserver(this);
172 bool WaitForFinished() {
173 if (item_
->GetState() == DownloadItem::COMPLETE
) {
174 return item_
->PercentComplete() == 100;
177 content::RunMessageLoop();
183 void OnDownloadUpdated(content::DownloadItem
* item
) override
{
184 DCHECK_EQ(item_
, item
);
186 ((prev_percent_
> item_
->PercentComplete()) ||
187 (item_
->GetState() == DownloadItem::COMPLETE
&&
188 (item_
->PercentComplete() != 100)))) {
191 base::MessageLoopForUI::current()->Quit();
193 if (item_
->GetState() == DownloadItem::COMPLETE
&& waiting_
)
194 base::MessageLoopForUI::current()->Quit();
197 void OnDownloadDestroyed(content::DownloadItem
* item
) override
{
198 DCHECK_EQ(item_
, item
);
199 item_
->RemoveObserver(this);
203 content::DownloadItem
* item_
;
208 DISALLOW_COPY_AND_ASSIGN(PercentWaiter
);
211 // DownloadTestObserver subclass that observes one download until it transitions
212 // from a non-resumable state to a resumable state a specified number of
213 // times. Note that this observer can only observe a single download.
214 class DownloadTestObserverResumable
: public content::DownloadTestObserver
{
216 // Construct a new observer. |transition_count| is the number of times the
217 // download should transition from a non-resumable state to a resumable state.
218 DownloadTestObserverResumable(DownloadManager
* download_manager
,
219 size_t transition_count
)
220 : DownloadTestObserver(download_manager
, 1,
221 ON_DANGEROUS_DOWNLOAD_FAIL
),
222 was_previously_resumable_(false),
223 transitions_left_(transition_count
) {
226 ~DownloadTestObserverResumable() override
{}
229 bool IsDownloadInFinalState(DownloadItem
* download
) override
{
230 bool is_resumable_now
= download
->CanResume();
231 if (!was_previously_resumable_
&& is_resumable_now
)
233 was_previously_resumable_
= is_resumable_now
;
234 return transitions_left_
== 0;
237 bool was_previously_resumable_
;
238 size_t transitions_left_
;
240 DISALLOW_COPY_AND_ASSIGN(DownloadTestObserverResumable
);
243 // IDs and paths of CRX files used in tests.
244 const char kGoodCrxId
[] = "ldnnhddmnhbkjipkidpdiheffobcpfmf";
245 const base::FilePath
kGoodCrxPath(FILE_PATH_LITERAL("extensions/good.crx"));
247 const char kLargeThemeCrxId
[] = "pjpgmfcmabopnnfonnhmdjglfpjjfkbf";
248 const base::FilePath
kLargeThemePath(
249 FILE_PATH_LITERAL("extensions/theme2.crx"));
251 // Get History Information.
252 class DownloadsHistoryDataCollector
{
254 explicit DownloadsHistoryDataCollector(Profile
* profile
)
255 : profile_(profile
), result_valid_(false) {}
257 bool WaitForDownloadInfo(
258 scoped_ptr
<std::vector
<history::DownloadRow
> >* results
) {
259 history::HistoryService
* hs
= HistoryServiceFactory::GetForProfile(
260 profile_
, ServiceAccessType::EXPLICIT_ACCESS
);
263 base::Bind(&DownloadsHistoryDataCollector::OnQueryDownloadsComplete
,
264 base::Unretained(this)));
266 content::RunMessageLoop();
268 *results
= results_
.Pass();
270 return result_valid_
;
274 void OnQueryDownloadsComplete(
275 scoped_ptr
<std::vector
<history::DownloadRow
> > entries
) {
276 result_valid_
= true;
277 results_
= entries
.Pass();
278 base::MessageLoopForUI::current()->Quit();
282 scoped_ptr
<std::vector
<history::DownloadRow
> > results_
;
285 DISALLOW_COPY_AND_ASSIGN(DownloadsHistoryDataCollector
);
288 // Mock that simulates a permissions dialog where the user denies
289 // permission to install. TODO(skerner): This could be shared with
290 // extensions tests. Find a common place for this class.
291 class MockAbortExtensionInstallPrompt
: public ExtensionInstallPrompt
{
293 MockAbortExtensionInstallPrompt() :
294 ExtensionInstallPrompt(NULL
) {
297 // Simulate a user abort on an extension installation.
298 void ConfirmInstall(Delegate
* delegate
,
299 const Extension
* extension
,
300 const ShowDialogCallback
& show_dialog_callback
) override
{
301 delegate
->InstallUIAbort(true);
302 base::MessageLoopForUI::current()->Quit();
305 void OnInstallSuccess(const Extension
* extension
, SkBitmap
* icon
) override
{}
306 void OnInstallFailure(const extensions::CrxInstallError
& error
) override
{}
309 // Mock that simulates a permissions dialog where the user allows
311 class MockAutoConfirmExtensionInstallPrompt
: public ExtensionInstallPrompt
{
313 explicit MockAutoConfirmExtensionInstallPrompt(
314 content::WebContents
* web_contents
)
315 : ExtensionInstallPrompt(web_contents
) {}
317 // Proceed without confirmation prompt.
318 void ConfirmInstall(Delegate
* delegate
,
319 const Extension
* extension
,
320 const ShowDialogCallback
& show_dialog_callback
) override
{
321 delegate
->InstallUIProceed();
324 void OnInstallSuccess(const Extension
* extension
, SkBitmap
* icon
) override
{}
325 void OnInstallFailure(const extensions::CrxInstallError
& error
) override
{}
328 static DownloadManager
* DownloadManagerForBrowser(Browser
* browser
) {
329 return BrowserContext::GetDownloadManager(browser
->profile());
332 bool WasAutoOpened(DownloadItem
* item
) {
333 return item
->GetAutoOpened();
336 // Called when a download starts. Marks the download as hidden.
337 void SetHiddenDownloadCallback(DownloadItem
* item
,
338 content::DownloadInterruptReason reason
) {
339 DownloadItemModel(item
).SetShouldShowInShelf(false);
342 // Callback for HistoryObserver; used in DownloadHistoryCheck
343 bool HasDataAndName(const history::DownloadRow
& row
) {
344 return row
.received_bytes
> 0 && !row
.target_path
.empty();
349 DownloadTestObserverNotInProgress::DownloadTestObserverNotInProgress(
350 DownloadManager
* download_manager
,
352 : DownloadTestObserver(download_manager
, count
, ON_DANGEROUS_DOWNLOAD_FAIL
),
353 started_observing_(false) {
357 DownloadTestObserverNotInProgress::~DownloadTestObserverNotInProgress() {}
359 void DownloadTestObserverNotInProgress::StartObserving() {
360 started_observing_
= true;
363 bool DownloadTestObserverNotInProgress::IsDownloadInFinalState(
364 DownloadItem
* download
) {
365 return started_observing_
&&
366 download
->GetState() != DownloadItem::IN_PROGRESS
;
369 class HistoryObserver
: public DownloadHistory::Observer
{
371 typedef base::Callback
<bool(const history::DownloadRow
&)> FilterCallback
;
373 explicit HistoryObserver(Profile
* profile
)
376 seen_stored_(false) {
377 DownloadServiceFactory::GetForBrowserContext(profile_
)->
378 GetDownloadHistory()->AddObserver(this);
381 ~HistoryObserver() override
{
382 DownloadService
* service
= DownloadServiceFactory::GetForBrowserContext(
384 if (service
&& service
->GetDownloadHistory())
385 service
->GetDownloadHistory()->RemoveObserver(this);
388 void SetFilterCallback(const FilterCallback
& callback
) {
389 callback_
= callback
;
392 void OnDownloadStored(content::DownloadItem
* item
,
393 const history::DownloadRow
& info
) override
{
394 if (!callback_
.is_null() && (!callback_
.Run(info
)))
399 base::MessageLoopForUI::current()->Quit();
402 void OnDownloadHistoryDestroyed() override
{
403 DownloadServiceFactory::GetForBrowserContext(profile_
)->
404 GetDownloadHistory()->RemoveObserver(this);
407 void WaitForStored() {
411 content::RunMessageLoop();
419 FilterCallback callback_
;
421 DISALLOW_COPY_AND_ASSIGN(HistoryObserver
);
424 class DownloadTest
: public InProcessBrowserTest
{
426 // Choice of navigation or direct fetch. Used by |DownloadFileCheckErrors()|.
427 enum DownloadMethod
{
432 // Information passed in to |DownloadFileCheckErrors()|.
433 struct DownloadInfo
{
434 const char* url_name
; // URL for the download.
435 DownloadMethod download_method
; // Navigation or Direct.
436 // Download interrupt reason (NONE is OK).
437 content::DownloadInterruptReason reason
;
438 bool show_download_item
; // True if the download item appears on the shelf.
439 bool should_redirect_to_documents
; // True if we save it in "My Documents".
442 struct FileErrorInjectInfo
{
443 DownloadInfo download_info
;
444 content::TestFileErrorInjector::FileErrorInfo error_info
;
449 void SetUpOnMainThread() override
{
450 BrowserThread::PostTask(
451 BrowserThread::IO
, FROM_HERE
,
452 base::Bind(&chrome_browser_net::SetUrlRequestMocksEnabled
, true));
453 ASSERT_TRUE(InitialSetup());
456 void TearDownOnMainThread() override
{
457 // Needs to be torn down on the main thread. file_activity_observer_ holds a
458 // reference to the ChromeDownloadManagerDelegate which should be destroyed
460 file_activity_observer_
.reset();
463 void SetUpCommandLine(base::CommandLine
* command_line
) override
{
464 command_line
->AppendSwitch(switches::kDisablePluginsDiscovery
);
467 // Returning false indicates a failure of the setup, and should be asserted
469 virtual bool InitialSetup() {
470 bool have_test_dir
= PathService::Get(chrome::DIR_TEST_DATA
, &test_dir_
);
471 EXPECT_TRUE(have_test_dir
);
475 // Sanity check default values for window and tab count.
476 int window_count
= chrome::GetTotalBrowserCount();
477 EXPECT_EQ(1, window_count
);
478 EXPECT_EQ(1, browser()->tab_strip_model()->count());
480 // Set up the temporary download folder.
481 bool created_downloads_dir
= CreateAndSetDownloadsDirectory(browser());
482 EXPECT_TRUE(created_downloads_dir
);
483 if (!created_downloads_dir
)
485 browser()->profile()->GetPrefs()->SetBoolean(
486 prefs::kPromptForDownload
, false);
488 DownloadManager
* manager
= DownloadManagerForBrowser(browser());
489 DownloadPrefs::FromDownloadManager(manager
)->ResetAutoOpen();
490 manager
->RemoveAllDownloads();
492 file_activity_observer_
.reset(
493 new DownloadTestFileActivityObserver(browser()->profile()));
500 SIZE_TEST_TYPE_KNOWN
,
501 SIZE_TEST_TYPE_UNKNOWN
,
504 base::FilePath
GetTestDataDirectory() {
505 base::FilePath test_file_directory
;
506 PathService::Get(chrome::DIR_TEST_DATA
, &test_file_directory
);
507 return test_file_directory
;
510 base::FilePath
GetDownloadsDirectory() {
511 return downloads_directory_
.path();
514 // Location of the file source (the place from which it is downloaded).
515 base::FilePath
OriginFile(base::FilePath file
) {
516 return test_dir_
.Append(file
);
519 // Location of the file destination (place to which it is downloaded).
520 base::FilePath
DestinationFile(Browser
* browser
, base::FilePath file
) {
521 return GetDownloadDirectory(browser
).Append(file
.BaseName());
524 // Must be called after browser creation. Creates a temporary
525 // directory for downloads that is auto-deleted on destruction.
526 // Returning false indicates a failure of the function, and should be asserted
528 bool CreateAndSetDownloadsDirectory(Browser
* browser
) {
532 if (!downloads_directory_
.CreateUniqueTempDir())
535 browser
->profile()->GetPrefs()->SetFilePath(
536 prefs::kDownloadDefaultDirectory
,
537 downloads_directory_
.path());
538 browser
->profile()->GetPrefs()->SetFilePath(
539 prefs::kSaveFileDefaultDirectory
,
540 downloads_directory_
.path());
545 DownloadPrefs
* GetDownloadPrefs(Browser
* browser
) {
546 return DownloadPrefs::FromDownloadManager(
547 DownloadManagerForBrowser(browser
));
550 base::FilePath
GetDownloadDirectory(Browser
* browser
) {
551 return GetDownloadPrefs(browser
)->DownloadPath();
554 // Create a DownloadTestObserverTerminal that will wait for the
555 // specified number of downloads to finish.
556 content::DownloadTestObserver
* CreateWaiter(
557 Browser
* browser
, int num_downloads
) {
558 DownloadManager
* download_manager
= DownloadManagerForBrowser(browser
);
559 return new content::DownloadTestObserverTerminal(
560 download_manager
, num_downloads
,
561 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL
);
564 // Create a DownloadTestObserverInProgress that will wait for the
565 // specified number of downloads to start.
566 content::DownloadTestObserver
* CreateInProgressWaiter(
567 Browser
* browser
, int num_downloads
) {
568 DownloadManager
* download_manager
= DownloadManagerForBrowser(browser
);
569 return new content::DownloadTestObserverInProgress(
570 download_manager
, num_downloads
);
573 // Create a DownloadTestObserverTerminal that will wait for the
574 // specified number of downloads to finish, or for
575 // a dangerous download warning to be shown.
576 content::DownloadTestObserver
* DangerousDownloadWaiter(
579 content::DownloadTestObserver::DangerousDownloadAction
580 dangerous_download_action
) {
581 DownloadManager
* download_manager
= DownloadManagerForBrowser(browser
);
582 return new content::DownloadTestObserverTerminal(
583 download_manager
, num_downloads
, dangerous_download_action
);
586 void CheckDownloadStatesForBrowser(Browser
* browser
,
588 DownloadItem::DownloadState state
) {
589 std::vector
<DownloadItem
*> download_items
;
590 GetDownloads(browser
, &download_items
);
592 EXPECT_EQ(num
, download_items
.size());
594 for (size_t i
= 0; i
< download_items
.size(); ++i
) {
595 EXPECT_EQ(state
, download_items
[i
]->GetState()) << " Item " << i
;
599 void CheckDownloadStates(size_t num
, DownloadItem::DownloadState state
) {
600 CheckDownloadStatesForBrowser(browser(), num
, state
);
603 bool VerifyNoDownloads() const {
604 DownloadManager::DownloadVector items
;
605 GetDownloads(browser(), &items
);
606 return items
.empty();
609 // Download |url|, then wait for the download to finish.
610 // |disposition| indicates where the navigation occurs (current tab, new
611 // foreground tab, etc).
612 // |browser_test_flags| indicate what to wait for, and is an OR of 0 or more
613 // values in the ui_test_utils::BrowserTestWaitFlags enum.
614 void DownloadAndWaitWithDisposition(Browser
* browser
,
616 WindowOpenDisposition disposition
,
617 int browser_test_flags
) {
618 // Setup notification, navigate, and block.
619 scoped_ptr
<content::DownloadTestObserver
> observer(
620 CreateWaiter(browser
, 1));
621 // This call will block until the condition specified by
622 // |browser_test_flags|, but will not wait for the download to finish.
623 ui_test_utils::NavigateToURLWithDisposition(browser
,
627 // Waits for the download to complete.
628 observer
->WaitForFinished();
629 EXPECT_EQ(1u, observer
->NumDownloadsSeenInState(DownloadItem::COMPLETE
));
630 // We don't expect a file chooser to be shown.
631 EXPECT_FALSE(DidShowFileChooser());
634 // Download a file in the current tab, then wait for the download to finish.
635 void DownloadAndWait(Browser
* browser
,
637 DownloadAndWaitWithDisposition(
641 ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION
);
644 // Should only be called when the download is known to have finished
645 // (in error or not).
646 // Returning false indicates a failure of the function, and should be asserted
648 bool CheckDownload(Browser
* browser
,
649 const base::FilePath
& downloaded_filename
,
650 const base::FilePath
& origin_filename
) {
651 // Find the path to which the data will be downloaded.
652 base::FilePath
downloaded_file(
653 DestinationFile(browser
, downloaded_filename
));
655 // Find the origin path (from which the data comes).
656 base::FilePath
origin_file(OriginFile(origin_filename
));
657 return CheckDownloadFullPaths(browser
, downloaded_file
, origin_file
);
660 // A version of CheckDownload that allows complete path specification.
661 bool CheckDownloadFullPaths(Browser
* browser
,
662 const base::FilePath
& downloaded_file
,
663 const base::FilePath
& origin_file
) {
664 bool origin_file_exists
= base::PathExists(origin_file
);
665 EXPECT_TRUE(origin_file_exists
) << origin_file
.value();
666 if (!origin_file_exists
)
669 // Confirm the downloaded data file exists.
670 bool downloaded_file_exists
= base::PathExists(downloaded_file
);
671 EXPECT_TRUE(downloaded_file_exists
) << downloaded_file
.value();
672 if (!downloaded_file_exists
)
675 int64 origin_file_size
= 0;
676 EXPECT_TRUE(base::GetFileSize(origin_file
, &origin_file_size
));
677 std::string original_file_contents
;
678 EXPECT_TRUE(base::ReadFileToString(origin_file
, &original_file_contents
));
680 VerifyFile(downloaded_file
, original_file_contents
, origin_file_size
));
682 // Delete the downloaded copy of the file.
683 bool downloaded_file_deleted
= base::DieFileDie(downloaded_file
, false);
684 EXPECT_TRUE(downloaded_file_deleted
);
685 return downloaded_file_deleted
;
688 content::DownloadTestObserver
* CreateInProgressDownloadObserver(
689 size_t download_count
) {
690 DownloadManager
* manager
= DownloadManagerForBrowser(browser());
691 return new content::DownloadTestObserverInProgress(
692 manager
, download_count
);
695 DownloadItem
* CreateSlowTestDownload() {
696 scoped_ptr
<content::DownloadTestObserver
> observer(
697 CreateInProgressDownloadObserver(1));
698 GURL
slow_download_url(net::URLRequestSlowDownloadJob::kUnknownSizeUrl
);
699 DownloadManager
* manager
= DownloadManagerForBrowser(browser());
701 EXPECT_EQ(0, manager
->NonMaliciousInProgressCount());
702 EXPECT_EQ(0, manager
->InProgressCount());
703 if (manager
->InProgressCount() != 0)
706 ui_test_utils::NavigateToURL(browser(), slow_download_url
);
708 observer
->WaitForFinished();
709 EXPECT_EQ(1u, observer
->NumDownloadsSeenInState(DownloadItem::IN_PROGRESS
));
711 DownloadManager::DownloadVector items
;
712 manager
->GetAllDownloads(&items
);
714 DownloadItem
* new_item
= NULL
;
715 for (DownloadManager::DownloadVector::iterator iter
= items
.begin();
716 iter
!= items
.end(); ++iter
) {
717 if ((*iter
)->GetState() == DownloadItem::IN_PROGRESS
) {
718 // There should be only one IN_PROGRESS item.
719 EXPECT_EQ(NULL
, new_item
);
726 bool RunSizeTest(Browser
* browser
,
728 const std::string
& partial_indication
,
729 const std::string
& total_indication
) {
730 EXPECT_TRUE(type
== SIZE_TEST_TYPE_UNKNOWN
|| type
== SIZE_TEST_TYPE_KNOWN
);
731 if (type
!= SIZE_TEST_TYPE_KNOWN
&& type
!= SIZE_TEST_TYPE_UNKNOWN
)
733 GURL
url(type
== SIZE_TEST_TYPE_KNOWN
?
734 net::URLRequestSlowDownloadJob::kKnownSizeUrl
:
735 net::URLRequestSlowDownloadJob::kUnknownSizeUrl
);
737 // TODO(ahendrickson) -- |expected_title_in_progress| and
738 // |expected_title_finished| need to be checked.
739 base::FilePath filename
;
740 net::FileURLToFilePath(url
, &filename
);
741 base::string16
expected_title_in_progress(
742 base::ASCIIToUTF16(partial_indication
) + filename
.LossyDisplayName());
743 base::string16
expected_title_finished(
744 base::ASCIIToUTF16(total_indication
) + filename
.LossyDisplayName());
746 // Download a partial web page in a background tab and wait.
747 // The mock system will not complete until it gets a special URL.
748 scoped_ptr
<content::DownloadTestObserver
> observer(
749 CreateWaiter(browser
, 1));
750 ui_test_utils::NavigateToURL(browser
, url
);
752 // TODO(ahendrickson): check download status text before downloading.
754 // - Add a member function to the |DownloadShelf| interface class, that
755 // indicates how many members it has.
756 // - Add a member function to |DownloadShelf| to get the status text
757 // of a given member (for example, via the name in |DownloadItemView|'s
758 // GetAccessibleState() member function), by index.
759 // - Iterate over browser->window()->GetDownloadShelf()'s members
760 // to see if any match the status text we want. Start with the last one.
762 // Allow the request to finish. We do this by loading a second URL in a
764 GURL
finish_url(net::URLRequestSlowDownloadJob::kFinishDownloadUrl
);
765 ui_test_utils::NavigateToURLWithDisposition(
769 ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION
);
770 observer
->WaitForFinished();
771 EXPECT_EQ(1u, observer
->NumDownloadsSeenInState(DownloadItem::COMPLETE
));
772 CheckDownloadStatesForBrowser(browser
, 1, DownloadItem::COMPLETE
);
774 EXPECT_EQ(2, browser
->tab_strip_model()->count());
776 // TODO(ahendrickson): check download status text after downloading.
778 base::FilePath
basefilename(filename
.BaseName());
779 net::FileURLToFilePath(url
, &filename
);
780 base::FilePath download_path
=
781 downloads_directory_
.path().Append(basefilename
);
783 bool downloaded_path_exists
= base::PathExists(download_path
);
784 EXPECT_TRUE(downloaded_path_exists
);
785 if (!downloaded_path_exists
)
788 // Check the file contents.
789 size_t file_size
= net::URLRequestSlowDownloadJob::kFirstDownloadSize
+
790 net::URLRequestSlowDownloadJob::kSecondDownloadSize
;
791 std::string
expected_contents(file_size
, '*');
792 EXPECT_TRUE(VerifyFile(download_path
, expected_contents
, file_size
));
794 // Delete the file we just downloaded.
795 EXPECT_TRUE(base::DieFileDie(download_path
, true));
796 EXPECT_FALSE(base::PathExists(download_path
));
801 void GetDownloads(Browser
* browser
,
802 std::vector
<DownloadItem
*>* downloads
) const {
804 DownloadManager
* manager
= DownloadManagerForBrowser(browser
);
805 manager
->GetAllDownloads(downloads
);
808 static void ExpectWindowCountAfterDownload(size_t expected
) {
809 EXPECT_EQ(expected
, chrome::GetTotalBrowserCount());
812 void EnableFileChooser(bool enable
) {
813 file_activity_observer_
->EnableFileChooser(enable
);
816 bool DidShowFileChooser() {
817 return file_activity_observer_
->TestAndResetDidShowFileChooser();
820 // Checks that |path| is has |file_size| bytes, and matches the |value|
822 bool VerifyFile(const base::FilePath
& path
,
823 const std::string
& value
,
824 const int64 file_size
) {
825 std::string file_contents
;
827 bool read
= base::ReadFileToString(path
, &file_contents
);
828 EXPECT_TRUE(read
) << "Failed reading file: " << path
.value() << std::endl
;
830 return false; // Couldn't read the file.
832 // Note: we don't handle really large files (more than size_t can hold)
833 // so we will fail in that case.
834 size_t expected_size
= static_cast<size_t>(file_size
);
837 EXPECT_EQ(expected_size
, file_contents
.size());
838 if (expected_size
!= file_contents
.size())
841 // Check the contents.
842 EXPECT_EQ(value
, file_contents
);
843 if (memcmp(file_contents
.c_str(), value
.c_str(), expected_size
) != 0)
849 // Attempts to download a file, based on information in |download_info|.
850 // If a Select File dialog opens, will automatically choose the default.
851 void DownloadFilesCheckErrorsSetup() {
852 embedded_test_server()->ServeFilesFromDirectory(GetTestDataDirectory());
853 ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
854 std::vector
<DownloadItem
*> download_items
;
855 GetDownloads(browser(), &download_items
);
856 ASSERT_TRUE(download_items
.empty());
858 EnableFileChooser(true);
861 void DownloadFilesCheckErrorsLoopBody(const DownloadInfo
& download_info
,
865 << " " << __FUNCTION__
<< "()"
866 << " index = " << i
<< " url = '" << download_info
.url_name
<< "'"
867 << " method = " << ((download_info
.download_method
== DOWNLOAD_DIRECT
)
869 : "DOWNLOAD_NAVIGATE")
870 << " show_item = " << download_info
.show_download_item
<< " reason = "
871 << DownloadInterruptReasonToString(download_info
.reason
));
873 std::vector
<DownloadItem
*> download_items
;
874 GetDownloads(browser(), &download_items
);
875 size_t downloads_expected
= download_items
.size();
877 std::string server_path
= "/downloads/";
878 server_path
+= download_info
.url_name
;
879 GURL url
= embedded_test_server()->GetURL(server_path
);
880 ASSERT_TRUE(url
.is_valid());
882 DownloadManager
* download_manager
= DownloadManagerForBrowser(browser());
883 WebContents
* web_contents
=
884 browser()->tab_strip_model()->GetActiveWebContents();
885 ASSERT_TRUE(web_contents
);
887 scoped_ptr
<content::DownloadTestObserver
> observer(
888 new content::DownloadTestObserverTerminal(
891 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL
));
893 if (download_info
.download_method
== DOWNLOAD_DIRECT
) {
894 // Go directly to download. Don't wait for navigation.
895 scoped_refptr
<content::DownloadTestItemCreationObserver
>
896 creation_observer(new content::DownloadTestItemCreationObserver
);
898 scoped_ptr
<DownloadUrlParameters
> params(
899 DownloadUrlParameters::FromWebContents(web_contents
, url
));
900 params
->set_callback(creation_observer
->callback());
901 DownloadManagerForBrowser(browser())->DownloadUrl(params
.Pass());
903 // Wait until the item is created, or we have determined that it
905 creation_observer
->WaitForDownloadItemCreation();
907 ASSERT_EQ(download_info
.show_download_item
,
908 creation_observer
->succeeded());
909 if (download_info
.show_download_item
) {
910 EXPECT_EQ(content::DOWNLOAD_INTERRUPT_REASON_NONE
,
911 creation_observer
->interrupt_reason());
912 EXPECT_NE(content::DownloadItem::kInvalidId
,
913 creation_observer
->download_id());
915 EXPECT_NE(content::DOWNLOAD_INTERRUPT_REASON_NONE
,
916 creation_observer
->interrupt_reason());
917 EXPECT_EQ(content::DownloadItem::kInvalidId
,
918 creation_observer
->download_id());
921 // Navigate to URL normally, wait until done.
922 ui_test_utils::NavigateToURL(browser(), url
);
925 if (download_info
.show_download_item
) {
926 downloads_expected
++;
927 observer
->WaitForFinished();
928 DownloadItem::DownloadState final_state
=
929 (download_info
.reason
== content::DOWNLOAD_INTERRUPT_REASON_NONE
) ?
930 DownloadItem::COMPLETE
:
931 DownloadItem::INTERRUPTED
;
932 EXPECT_EQ(1u, observer
->NumDownloadsSeenInState(final_state
));
935 // Wait till the |DownloadFile|s are destroyed.
936 content::RunAllPendingInMessageLoop(content::BrowserThread::FILE);
937 content::RunAllPendingInMessageLoop(content::BrowserThread::UI
);
939 // Validate that the correct files were downloaded.
940 download_items
.clear();
941 GetDownloads(browser(), &download_items
);
942 ASSERT_EQ(downloads_expected
, download_items
.size());
944 if (download_info
.show_download_item
) {
945 // Find the last download item.
946 DownloadItem
* item
= download_items
[0];
947 for (size_t d
= 1; d
< downloads_expected
; ++d
) {
948 if (download_items
[d
]->GetStartTime() > item
->GetStartTime())
949 item
= download_items
[d
];
952 ASSERT_EQ(url
, item
->GetOriginalUrl());
953 ASSERT_EQ(download_info
.reason
, item
->GetLastReason());
955 if (item
->GetState() == content::DownloadItem::COMPLETE
) {
956 // Clean up the file, in case it ended up in the My Documents folder.
957 base::FilePath destination_folder
= GetDownloadDirectory(browser());
958 base::FilePath my_downloaded_file
= item
->GetTargetFilePath();
959 EXPECT_TRUE(base::PathExists(my_downloaded_file
));
960 EXPECT_TRUE(base::DeleteFile(my_downloaded_file
, false));
962 EXPECT_EQ(download_info
.should_redirect_to_documents
?
965 my_downloaded_file
.value().find(destination_folder
.value()));
966 if (download_info
.should_redirect_to_documents
) {
967 // If it's not where we asked it to be, it should be in the
968 // My Documents folder.
969 base::FilePath my_docs_folder
;
970 EXPECT_TRUE(PathService::Get(chrome::DIR_USER_DOCUMENTS
,
973 my_downloaded_file
.value().find(my_docs_folder
.value()));
979 // Attempts to download a set of files, based on information in the
980 // |download_info| array. |count| is the number of files.
981 // If a Select File dialog appears, it will choose the default and return
983 void DownloadFilesCheckErrors(size_t count
, DownloadInfo
* download_info
) {
984 DownloadFilesCheckErrorsSetup();
986 for (size_t i
= 0; i
< count
; ++i
) {
987 DownloadFilesCheckErrorsLoopBody(download_info
[i
], i
);
991 void DownloadInsertFilesErrorCheckErrorsLoopBody(
992 scoped_refptr
<content::TestFileErrorInjector
> injector
,
993 const FileErrorInjectInfo
& info
,
996 s
<< " " << __FUNCTION__
<< "()"
998 << " url = " << info
.error_info
.url
999 << " operation code = "
1000 << content::TestFileErrorInjector::DebugString(info
.error_info
.code
)
1001 << " instance = " << info
.error_info
.operation_instance
1003 << content::DownloadInterruptReasonToString(info
.error_info
.error
);
1005 injector
->ClearErrors();
1006 injector
->AddError(info
.error_info
);
1008 injector
->InjectErrors();
1010 DownloadFilesCheckErrorsLoopBody(info
.download_info
, i
);
1012 size_t expected_successes
= info
.download_info
.show_download_item
? 1u : 0u;
1013 EXPECT_EQ(expected_successes
, injector
->TotalFileCount()) << s
.str();
1014 EXPECT_EQ(0u, injector
->CurrentFileCount()) << s
.str();
1016 if (info
.download_info
.show_download_item
)
1017 EXPECT_TRUE(injector
->HadFile(GURL(info
.error_info
.url
))) << s
.str();
1020 void DownloadInsertFilesErrorCheckErrors(size_t count
,
1021 FileErrorInjectInfo
* info
) {
1022 DownloadFilesCheckErrorsSetup();
1024 // Set up file failures.
1025 scoped_refptr
<content::TestFileErrorInjector
> injector(
1026 content::TestFileErrorInjector::Create(
1027 DownloadManagerForBrowser(browser())));
1029 for (size_t i
= 0; i
< count
; ++i
) {
1030 // Set up the full URL, for download file tracking.
1031 std::string server_path
= "/downloads/";
1032 server_path
+= info
[i
].download_info
.url_name
;
1033 GURL url
= embedded_test_server()->GetURL(server_path
);
1034 info
[i
].error_info
.url
= url
.spec();
1036 DownloadInsertFilesErrorCheckErrorsLoopBody(injector
, info
[i
], i
);
1040 // Attempts to download a file to a read-only folder, based on information
1041 // in |download_info|.
1042 void DownloadFilesToReadonlyFolder(size_t count
,
1043 DownloadInfo
* download_info
) {
1044 DownloadFilesCheckErrorsSetup();
1046 // Make the test folder unwritable.
1047 base::FilePath destination_folder
= GetDownloadDirectory(browser());
1048 DVLOG(1) << " " << __FUNCTION__
<< "()"
1049 << " folder = '" << destination_folder
.value() << "'";
1050 base::FilePermissionRestorer
permission_restorer(destination_folder
);
1051 EXPECT_TRUE(base::MakeFileUnwritable(destination_folder
));
1053 for (size_t i
= 0; i
< count
; ++i
) {
1054 DownloadFilesCheckErrorsLoopBody(download_info
[i
], i
);
1058 // A mock install prompt that simulates the user allowing an install request.
1059 void SetAllowMockInstallPrompt() {
1060 download_crx_util::SetMockInstallPromptForTesting(
1061 scoped_ptr
<ExtensionInstallPrompt
>(
1062 new MockAutoConfirmExtensionInstallPrompt(
1063 browser()->tab_strip_model()->GetActiveWebContents())));
1067 // * Starts a mock download by navigating browser() to a URLRequestMockHTTPJob
1069 // * Injects |error| on the first write using |error_injector|.
1070 // * Waits for the download to be interrupted.
1071 // * Clears the errors on |error_injector|.
1072 // * Returns the resulting interrupted download.
1073 DownloadItem
* StartMockDownloadAndInjectError(
1074 content::TestFileErrorInjector
* error_injector
,
1075 content::DownloadInterruptReason error
) {
1076 base::FilePath
file_path(FILE_PATH_LITERAL("download-test1.lib"));
1077 GURL url
= URLRequestMockHTTPJob::GetMockUrl(file_path
);
1079 content::TestFileErrorInjector::FileErrorInfo error_info
;
1080 error_info
.url
= url
.spec();
1081 error_info
.code
= content::TestFileErrorInjector::FILE_OPERATION_WRITE
;
1082 error_info
.operation_instance
= 0;
1083 error_info
.error
= error
;
1084 error_injector
->ClearErrors();
1085 error_injector
->AddError(error_info
);
1086 error_injector
->InjectErrors();
1088 scoped_ptr
<content::DownloadTestObserver
> observer(
1089 new DownloadTestObserverResumable(
1090 DownloadManagerForBrowser(browser()), 1));
1091 ui_test_utils::NavigateToURL(browser(), url
);
1092 observer
->WaitForFinished();
1094 content::DownloadManager::DownloadVector downloads
;
1095 DownloadManagerForBrowser(browser())->GetAllDownloads(&downloads
);
1096 EXPECT_EQ(1u, downloads
.size());
1098 if (downloads
.size() != 1)
1101 error_injector
->ClearErrors();
1102 error_injector
->InjectErrors();
1103 DownloadItem
* download
= downloads
[0];
1104 EXPECT_EQ(DownloadItem::INTERRUPTED
, download
->GetState());
1105 EXPECT_EQ(error
, download
->GetLastReason());
1110 static void EnsureNoPendingDownloadJobsOnIO(bool* result
) {
1111 if (net::URLRequestSlowDownloadJob::NumberOutstandingRequests())
1113 BrowserThread::PostTask(
1114 BrowserThread::UI
, FROM_HERE
, base::MessageLoop::QuitClosure());
1117 // Location of the test data.
1118 base::FilePath test_dir_
;
1120 // Location of the downloads directory for these tests
1121 base::ScopedTempDir downloads_directory_
;
1123 scoped_ptr
<DownloadTestFileActivityObserver
> file_activity_observer_
;
1128 // Files for these tests are found in DIR_TEST_DATA (currently
1129 // "chrome\test\data\", see chrome_paths.cc).
1130 // Mock responses have extension .mock-http-headers appended to the file name.
1132 // Download a file due to the associated MIME type.
1133 IN_PROC_BROWSER_TEST_F(DownloadTest
, DownloadMimeType
) {
1134 base::FilePath
file(FILE_PATH_LITERAL("download-test1.lib"));
1135 GURL
url(URLRequestMockHTTPJob::GetMockUrl(file
));
1137 // Download the file and wait. We do not expect the Select File dialog.
1138 DownloadAndWait(browser(), url
);
1141 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1142 CheckDownload(browser(), file
, file
);
1146 // Download a file and confirm that the zone identifier (on windows)
1147 // is set to internet.
1148 IN_PROC_BROWSER_TEST_F(DownloadTest
, CheckInternetZone
) {
1149 base::FilePath
file(FILE_PATH_LITERAL("download-test1.lib"));
1150 GURL
url(URLRequestMockHTTPJob::GetMockUrl(file
));
1152 // Download the file and wait. We do not expect the Select File dialog.
1153 DownloadAndWait(browser(), url
);
1155 // Check state. Special file state must be checked before CheckDownload,
1156 // as CheckDownload will delete the output file.
1157 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1158 base::FilePath
downloaded_file(DestinationFile(browser(), file
));
1159 if (base::VolumeSupportsADS(downloaded_file
))
1160 EXPECT_TRUE(base::HasInternetZoneIdentifier(downloaded_file
));
1161 CheckDownload(browser(), file
, file
);
1165 // Put up a Select File dialog when the file is downloaded, due to
1166 // downloads preferences settings.
1167 IN_PROC_BROWSER_TEST_F(DownloadTest
, DownloadMimeTypeSelect
) {
1168 // Re-enable prompting.
1169 browser()->profile()->GetPrefs()->SetBoolean(
1170 prefs::kPromptForDownload
, true);
1171 base::FilePath
file(FILE_PATH_LITERAL("download-test1.lib"));
1172 GURL
url(URLRequestMockHTTPJob::GetMockUrl(file
));
1174 EnableFileChooser(true);
1176 // Download the file and wait. We expect the Select File dialog to appear
1177 // due to the MIME type, but we still wait until the download completes.
1178 scoped_ptr
<content::DownloadTestObserver
> observer(
1179 new content::DownloadTestObserverTerminal(
1180 DownloadManagerForBrowser(browser()),
1182 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL
));
1183 ui_test_utils::NavigateToURL(browser(), url
);
1184 observer
->WaitForFinished();
1185 EXPECT_EQ(1u, observer
->NumDownloadsSeenInState(DownloadItem::COMPLETE
));
1186 CheckDownloadStates(1, DownloadItem::COMPLETE
);
1187 EXPECT_TRUE(DidShowFileChooser());
1190 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1191 CheckDownload(browser(), file
, file
);
1194 // Access a file with a viewable mime-type, verify that a download
1195 // did not initiate.
1196 IN_PROC_BROWSER_TEST_F(DownloadTest
, NoDownload
) {
1197 base::FilePath
file(FILE_PATH_LITERAL("download-test2.html"));
1198 GURL
url(URLRequestMockHTTPJob::GetMockUrl(file
));
1199 base::FilePath
file_path(DestinationFile(browser(), file
));
1201 // Open a web page and wait.
1202 ui_test_utils::NavigateToURL(browser(), url
);
1204 // Check that we did not download the web page.
1205 EXPECT_FALSE(base::PathExists(file_path
));
1208 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1209 EXPECT_TRUE(VerifyNoDownloads());
1212 // EmbeddedTestServer::HandleRequestCallback function that returns the relative
1213 // URL as the MIME type.
1215 // C -> S: GET /foo/bar =>
1216 // S -> C: HTTP/1.1 200 OK
1217 // Content-Type: foo/bar
1219 static scoped_ptr
<net::test_server::HttpResponse
> RespondWithContentTypeHandler(
1220 const net::test_server::HttpRequest
& request
) {
1221 scoped_ptr
<net::test_server::BasicHttpResponse
> response(
1222 new net::test_server::BasicHttpResponse());
1223 response
->set_content_type(request
.relative_url
.substr(1));
1224 response
->set_code(net::HTTP_OK
);
1225 response
->set_content("ooogaboogaboogabooga");
1226 return response
.Pass();
1229 IN_PROC_BROWSER_TEST_F(DownloadTest
, MimeTypesToShowNotDownload
) {
1230 embedded_test_server()->RegisterRequestHandler(
1231 base::Bind(&RespondWithContentTypeHandler
));
1232 ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
1234 // These files should all be displayed in the browser.
1235 const char* mime_types
[] = {
1236 // It is unclear whether to display text/css or download it.
1237 // Firefox 3: Display
1238 // Internet Explorer 7: Download
1239 // Safari 3.2: Download
1240 // We choose to match Firefox due to the lot of complains
1241 // from the users if css files are downloaded:
1242 // http://code.google.com/p/chromium/issues/detail?id=7192
1246 "application/x-javascript",
1250 "application/xhtml+xml",
1256 for (size_t i
= 0; i
< arraysize(mime_types
); ++i
) {
1257 const char* mime_type
= mime_types
[i
];
1259 embedded_test_server()->GetURL(std::string("/").append(mime_type
)));
1260 ui_test_utils::NavigateToURL(browser(), url
);
1263 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1264 EXPECT_TRUE(VerifyNoDownloads());
1268 // Verify that when the DownloadResourceThrottle cancels a download, the
1269 // download never makes it to the downloads system.
1270 IN_PROC_BROWSER_TEST_F(DownloadTest
, DownloadResourceThrottleCancels
) {
1271 // Navigate to a page with the same domain as the file to download. We can't
1272 // navigate directly to the file we don't want to download because cross-site
1273 // navigations reset the TabDownloadState.
1274 base::FilePath
same_site_path(FILE_PATH_LITERAL("download_script.html"));
1275 GURL
same_site_url(URLRequestMockHTTPJob::GetMockUrl(same_site_path
));
1276 ui_test_utils::NavigateToURL(browser(), same_site_url
);
1278 // Make sure the initial navigation didn't trigger a download.
1279 EXPECT_TRUE(VerifyNoDownloads());
1281 // Disable downloads for the tab.
1282 WebContents
* web_contents
=
1283 browser()->tab_strip_model()->GetActiveWebContents();
1284 DownloadRequestLimiter::TabDownloadState
* tab_download_state
=
1285 g_browser_process
->download_request_limiter()->GetDownloadState(
1286 web_contents
, web_contents
, true);
1287 ASSERT_TRUE(tab_download_state
);
1288 tab_download_state
->set_download_status(
1289 DownloadRequestLimiter::DOWNLOADS_NOT_ALLOWED
);
1291 // Try to start the download via Javascript and wait for the corresponding
1293 content::TestNavigationObserver
observer(web_contents
);
1294 bool download_assempted
;
1295 ASSERT_TRUE(content::ExecuteScriptAndExtractBool(
1296 browser()->tab_strip_model()->GetActiveWebContents(),
1297 "window.domAutomationController.send(startDownload());",
1298 &download_assempted
));
1299 ASSERT_TRUE(download_assempted
);
1302 // Check that we did not download the file.
1303 base::FilePath
file(FILE_PATH_LITERAL("download-test1.lib"));
1304 base::FilePath
file_path(DestinationFile(browser(), file
));
1305 EXPECT_FALSE(base::PathExists(file_path
));
1308 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1310 // Verify that there's no pending download. The resource throttle
1311 // should have deleted it before it created a download item, so it
1312 // shouldn't be available as a cancelled download either.
1313 EXPECT_TRUE(VerifyNoDownloads());
1316 // Download a 0-size file with a content-disposition header, verify that the
1317 // download tab opened and the file exists as the filename specified in the
1318 // header. This also ensures we properly handle empty file downloads.
1319 IN_PROC_BROWSER_TEST_F(DownloadTest
, ContentDisposition
) {
1320 base::FilePath
file(FILE_PATH_LITERAL("download-test3.gif"));
1321 GURL
url(URLRequestMockHTTPJob::GetMockUrl(file
));
1322 base::FilePath
download_file(
1323 FILE_PATH_LITERAL("download-test3-attachment.gif"));
1325 // Download a file and wait.
1326 DownloadAndWait(browser(), url
);
1328 CheckDownload(browser(), download_file
, file
);
1331 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1334 // UnknownSize and KnownSize are tests which depend on
1335 // URLRequestSlowDownloadJob to serve content in a certain way. Data will be
1336 // sent in two chunks where the first chunk is 35K and the second chunk is 10K.
1337 // The test will first attempt to download a file; but the server will "pause"
1338 // in the middle until the server receives a second request for
1339 // "download-finish". At that time, the download will finish.
1340 // These tests don't currently test much due to holes in |RunSizeTest()|. See
1341 // comments in that routine for details.
1342 IN_PROC_BROWSER_TEST_F(DownloadTest
, UnknownSize
) {
1343 ASSERT_TRUE(RunSizeTest(browser(), SIZE_TEST_TYPE_UNKNOWN
,
1344 "32.0 KB - ", "100% - "));
1347 IN_PROC_BROWSER_TEST_F(DownloadTest
, KnownSize
) {
1348 ASSERT_TRUE(RunSizeTest(browser(), SIZE_TEST_TYPE_KNOWN
,
1349 "71% - ", "100% - "));
1352 // Test that when downloading an item in Incognito mode, we don't crash when
1353 // closing the last Incognito window (http://crbug.com/13983).
1354 IN_PROC_BROWSER_TEST_F(DownloadTest
, IncognitoDownload
) {
1355 Browser
* incognito
= CreateIncognitoBrowser();
1356 ASSERT_TRUE(incognito
);
1357 int window_count
= chrome::GetTotalBrowserCount();
1358 EXPECT_EQ(2, window_count
);
1360 // Download a file in the Incognito window and wait.
1361 CreateAndSetDownloadsDirectory(incognito
);
1362 base::FilePath
file(FILE_PATH_LITERAL("download-test1.lib"));
1363 GURL
url(URLRequestMockHTTPJob::GetMockUrl(file
));
1364 // Since |incognito| is a separate browser, we have to set it up explicitly.
1365 incognito
->profile()->GetPrefs()->SetBoolean(prefs::kPromptForDownload
,
1367 DownloadAndWait(incognito
, url
);
1369 // We should still have 2 windows.
1370 ExpectWindowCountAfterDownload(2);
1372 #if !defined(OS_MACOSX)
1373 // On Mac OS X, the UI window close is delayed until the outermost
1374 // message loop runs. So it isn't possible to get a BROWSER_CLOSED
1375 // notification inside of a test.
1376 content::WindowedNotificationObserver
signal(
1377 chrome::NOTIFICATION_BROWSER_CLOSED
,
1378 content::Source
<Browser
>(incognito
));
1381 // Close the Incognito window and don't crash.
1382 chrome::CloseWindow(incognito
);
1384 #if !defined(OS_MACOSX)
1386 ExpectWindowCountAfterDownload(1);
1389 CheckDownload(browser(), file
, file
);
1392 // Download one file on-record, then download the same file off-record, and test
1393 // that the filename is deduplicated. The previous test tests for a specific
1394 // bug; this next test tests that filename deduplication happens independently
1395 // of DownloadManager/CDMD.
1396 IN_PROC_BROWSER_TEST_F(DownloadTest
, DownloadTest_IncognitoRegular
) {
1397 GURL url
= net::URLRequestMockHTTPJob::GetMockUrl("downloads/a_zip_file.zip");
1399 // Read the origin file now so that we can compare the downloaded files to it
1401 base::FilePath
origin(OriginFile(base::FilePath(FILE_PATH_LITERAL(
1402 "downloads/a_zip_file.zip"))));
1403 ASSERT_TRUE(base::PathExists(origin
));
1404 int64 origin_file_size
= 0;
1405 EXPECT_TRUE(base::GetFileSize(origin
, &origin_file_size
));
1406 std::string original_contents
;
1407 EXPECT_TRUE(base::ReadFileToString(origin
, &original_contents
));
1409 std::vector
<DownloadItem
*> download_items
;
1410 GetDownloads(browser(), &download_items
);
1411 ASSERT_TRUE(download_items
.empty());
1413 // Download a file in the on-record browser and check that it was downloaded
1415 DownloadAndWaitWithDisposition(browser(),
1418 ui_test_utils::BROWSER_TEST_NONE
);
1419 GetDownloads(browser(), &download_items
);
1420 ASSERT_EQ(1UL, download_items
.size());
1421 ASSERT_EQ(base::FilePath(FILE_PATH_LITERAL("a_zip_file.zip")),
1422 download_items
[0]->GetTargetFilePath().BaseName());
1423 ASSERT_TRUE(base::PathExists(download_items
[0]->GetTargetFilePath()));
1424 EXPECT_TRUE(VerifyFile(download_items
[0]->GetTargetFilePath(),
1425 original_contents
, origin_file_size
));
1427 // Setup an incognito window.
1428 Browser
* incognito
= CreateIncognitoBrowser();
1429 ASSERT_TRUE(incognito
);
1430 int window_count
= BrowserList::GetInstance(
1431 browser()->host_desktop_type())->size();
1432 EXPECT_EQ(2, window_count
);
1433 incognito
->profile()->GetPrefs()->SetFilePath(
1434 prefs::kDownloadDefaultDirectory
,
1435 GetDownloadsDirectory());
1436 incognito
->profile()->GetPrefs()->SetFilePath(
1437 prefs::kSaveFileDefaultDirectory
,
1438 GetDownloadsDirectory());
1440 download_items
.clear();
1441 GetDownloads(incognito
, &download_items
);
1442 ASSERT_TRUE(download_items
.empty());
1444 // Download a file in the incognito browser and check that it was downloaded
1446 DownloadAndWaitWithDisposition(incognito
,
1449 ui_test_utils::BROWSER_TEST_NONE
);
1450 GetDownloads(incognito
, &download_items
);
1451 ASSERT_EQ(1UL, download_items
.size());
1452 ASSERT_EQ(base::FilePath(FILE_PATH_LITERAL("a_zip_file (1).zip")),
1453 download_items
[0]->GetTargetFilePath().BaseName());
1454 ASSERT_TRUE(base::PathExists(download_items
[0]->GetTargetFilePath()));
1455 EXPECT_TRUE(VerifyFile(download_items
[0]->GetTargetFilePath(),
1456 original_contents
, origin_file_size
));
1459 // Navigate to a new background page, but don't download.
1460 IN_PROC_BROWSER_TEST_F(DownloadTest
, DontCloseNewTab1
) {
1461 // Because it's an HTML link, it should open a web page rather than
1463 base::FilePath
file1(FILE_PATH_LITERAL("download-test2.html"));
1464 GURL
url(URLRequestMockHTTPJob::GetMockUrl(file1
));
1466 // Open a web page and wait.
1467 ui_test_utils::NavigateToURLWithDisposition(
1471 ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION
);
1473 // We should have two tabs now.
1474 EXPECT_EQ(2, browser()->tab_strip_model()->count());
1475 EXPECT_TRUE(VerifyNoDownloads());
1478 // Download a file in a background tab. Verify that the tab is closed
1480 IN_PROC_BROWSER_TEST_F(DownloadTest
, CloseNewTab1
) {
1481 // Download a file in a new background tab and wait. The tab is automatically
1482 // closed when the download begins.
1483 base::FilePath
file(FILE_PATH_LITERAL("download-test1.lib"));
1484 GURL
url(URLRequestMockHTTPJob::GetMockUrl(file
));
1485 DownloadAndWaitWithDisposition(
1491 // When the download finishes, we should still have one tab.
1492 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1494 CheckDownload(browser(), file
, file
);
1497 // Open a web page in the current tab, then download a file in another tab via
1498 // a Javascript call.
1499 // Verify that we have 2 tabs.
1501 // The download_page1.html page contains an openNew() function that opens a
1502 // tab and then downloads download-test1.lib.
1503 IN_PROC_BROWSER_TEST_F(DownloadTest
, DontCloseNewTab2
) {
1504 // Because it's an HTML link, it should open a web page rather than
1506 base::FilePath
file1(FILE_PATH_LITERAL("download_page1.html"));
1507 GURL
url(URLRequestMockHTTPJob::GetMockUrl(file1
));
1509 // Open a web page and wait.
1510 ui_test_utils::NavigateToURL(browser(), url
);
1512 // Download a file in a new tab and wait (via Javascript).
1513 base::FilePath
file(FILE_PATH_LITERAL("download-test1.lib"));
1514 DownloadAndWaitWithDisposition(browser(),
1515 GURL("javascript:openNew()"),
1517 ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB
);
1519 // When the download finishes, we should have two tabs.
1520 EXPECT_EQ(2, browser()->tab_strip_model()->count());
1522 CheckDownload(browser(), file
, file
);
1525 // Open a web page in the current tab, open another tab via a Javascript call,
1526 // then download a file in the new tab.
1527 // Verify that we have 2 tabs.
1529 // The download_page2.html page contains an openNew() function that opens a
1531 IN_PROC_BROWSER_TEST_F(DownloadTest
, DontCloseNewTab3
) {
1532 // Because it's an HTML link, it should open a web page rather than
1534 base::FilePath
file1(FILE_PATH_LITERAL("download_page2.html"));
1535 GURL
url1(URLRequestMockHTTPJob::GetMockUrl(file1
));
1537 // Open a web page and wait.
1538 ui_test_utils::NavigateToURL(browser(), url1
);
1540 // Open a new tab and wait.
1541 ui_test_utils::NavigateToURLWithDisposition(
1543 GURL("javascript:openNew()"),
1545 ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB
);
1547 EXPECT_EQ(2, browser()->tab_strip_model()->count());
1549 // Download a file and wait.
1550 base::FilePath
file(FILE_PATH_LITERAL("download-test1.lib"));
1551 GURL
url(URLRequestMockHTTPJob::GetMockUrl(file
));
1552 DownloadAndWaitWithDisposition(browser(),
1555 ui_test_utils::BROWSER_TEST_NONE
);
1557 // When the download finishes, we should have two tabs.
1558 EXPECT_EQ(2, browser()->tab_strip_model()->count());
1560 CheckDownload(browser(), file
, file
);
1563 // Open a web page in the current tab, then download a file via Javascript,
1564 // which will do so in a temporary tab. Verify that we have 1 tab.
1566 // The download_page3.html page contains an openNew() function that opens a
1567 // tab with download-test1.lib in the URL. When the URL is determined to be
1568 // a download, the tab is closed automatically.
1569 IN_PROC_BROWSER_TEST_F(DownloadTest
, CloseNewTab2
) {
1570 // Because it's an HTML link, it should open a web page rather than
1572 base::FilePath
file1(FILE_PATH_LITERAL("download_page3.html"));
1573 GURL
url(URLRequestMockHTTPJob::GetMockUrl(file1
));
1575 // Open a web page and wait.
1576 ui_test_utils::NavigateToURL(browser(), url
);
1578 // Download a file and wait.
1579 // The file to download is "download-test1.lib".
1580 base::FilePath
file(FILE_PATH_LITERAL("download-test1.lib"));
1581 DownloadAndWaitWithDisposition(browser(),
1582 GURL("javascript:openNew()"),
1584 ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB
);
1586 // When the download finishes, we should still have one tab.
1587 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1589 CheckDownload(browser(), file
, file
);
1592 // Open a web page in the current tab, then call Javascript via a button to
1593 // download a file in a new tab, which is closed automatically when the
1595 // Verify that we have 1 tab.
1597 // The download_page4.html page contains a form with download-test1.lib as the
1599 IN_PROC_BROWSER_TEST_F(DownloadTest
, CloseNewTab3
) {
1600 // Because it's an HTML link, it should open a web page rather than
1602 base::FilePath
file1(FILE_PATH_LITERAL("download_page4.html"));
1603 GURL
url(URLRequestMockHTTPJob::GetMockUrl(file1
));
1605 // Open a web page and wait.
1606 ui_test_utils::NavigateToURL(browser(), url
);
1608 // Download a file in a new tab and wait. The tab will automatically close
1609 // when the download begins.
1610 // The file to download is "download-test1.lib".
1611 base::FilePath
file(FILE_PATH_LITERAL("download-test1.lib"));
1612 DownloadAndWaitWithDisposition(
1614 GURL("javascript:document.getElementById('form').submit()"),
1616 ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB
);
1618 // When the download finishes, we should still have one tab.
1619 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1621 CheckDownload(browser(), file
, file
);
1624 // EmbeddedTestServer::HandleRequestCallback function that responds with a
1625 // redirect to the URL specified via a query string.
1627 // C -> S: GET /dummy?http://example.com
1628 // S -> C: HTTP/1.1 301 Moved Permanently
1629 // Location: http://example.com
1631 static scoped_ptr
<net::test_server::HttpResponse
> ServerRedirectRequestHandler(
1632 const net::test_server::HttpRequest
& request
) {
1633 scoped_ptr
<net::test_server::BasicHttpResponse
> response(
1634 new net::test_server::BasicHttpResponse());
1635 size_t query_position
= request
.relative_url
.find('?');
1637 if (query_position
== std::string::npos
) {
1638 response
->set_code(net::HTTP_PERMANENT_REDIRECT
);
1639 response
->AddCustomHeader("Location",
1640 "https://request-had-no-query-string");
1641 response
->set_content_type("text/plain");
1642 response
->set_content("Error");
1643 return response
.Pass();
1646 response
->set_code(net::HTTP_PERMANENT_REDIRECT
);
1647 response
->AddCustomHeader("Location",
1648 request
.relative_url
.substr(query_position
+ 1));
1649 response
->set_content_type("text/plain");
1650 response
->set_content("It's gone!");
1651 return response
.Pass();
1654 IN_PROC_BROWSER_TEST_F(DownloadTest
, DownloadHistoryCheck
) {
1655 GURL
download_url(net::URLRequestSlowDownloadJob::kKnownSizeUrl
);
1656 base::FilePath
file(net::GenerateFileName(download_url
,
1663 // We use the server so that we can get a redirect and test url_chain
1665 embedded_test_server()->RegisterRequestHandler(
1666 base::Bind(&ServerRedirectRequestHandler
));
1667 ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
1669 embedded_test_server()->GetURL("/a?" + download_url
.spec());
1671 // Download the url and wait until the object has been stored.
1672 base::Time
start(base::Time::Now());
1673 HistoryObserver
observer(browser()->profile());
1674 observer
.SetFilterCallback(base::Bind(&HasDataAndName
));
1675 ui_test_utils::NavigateToURL(browser(), redirect_url
);
1676 observer
.WaitForStored();
1678 // Get the details on what was stored into the history.
1679 scoped_ptr
<std::vector
<history::DownloadRow
> > downloads_in_database
;
1680 ASSERT_TRUE(DownloadsHistoryDataCollector(
1681 browser()->profile()).WaitForDownloadInfo(&downloads_in_database
));
1682 ASSERT_EQ(1u, downloads_in_database
->size());
1684 // Confirm history storage is what you expect for a partially completed
1685 // slow download job.
1686 history::DownloadRow
& row(downloads_in_database
->at(0));
1687 EXPECT_EQ(DestinationFile(browser(), file
), row
.target_path
);
1688 EXPECT_EQ(DownloadTargetDeterminer::GetCrDownloadPath(
1689 DestinationFile(browser(), file
)),
1691 ASSERT_EQ(2u, row
.url_chain
.size());
1692 EXPECT_EQ(redirect_url
.spec(), row
.url_chain
[0].spec());
1693 EXPECT_EQ(download_url
.spec(), row
.url_chain
[1].spec());
1694 EXPECT_EQ(history::DownloadDangerType::NOT_DANGEROUS
, row
.danger_type
);
1695 EXPECT_LE(start
, row
.start_time
);
1696 EXPECT_EQ(net::URLRequestSlowDownloadJob::kFirstDownloadSize
,
1697 row
.received_bytes
);
1698 EXPECT_EQ(net::URLRequestSlowDownloadJob::kFirstDownloadSize
1699 + net::URLRequestSlowDownloadJob::kSecondDownloadSize
,
1701 EXPECT_EQ(history::DownloadState::IN_PROGRESS
, row
.state
);
1702 EXPECT_FALSE(row
.opened
);
1704 // Finish the download. We're ok relying on the history to be flushed
1705 // at this point as our queries will be behind the history updates
1706 // invoked by completion.
1707 scoped_ptr
<content::DownloadTestObserver
> download_observer(
1708 CreateWaiter(browser(), 1));
1709 ui_test_utils::NavigateToURL(browser(),
1710 GURL(net::URLRequestSlowDownloadJob::kErrorDownloadUrl
));
1711 download_observer
->WaitForFinished();
1712 EXPECT_EQ(1u, download_observer
->NumDownloadsSeenInState(
1713 DownloadItem::INTERRUPTED
));
1714 base::Time
end(base::Time::Now());
1716 // Get what was stored in the history.
1717 ASSERT_TRUE(DownloadsHistoryDataCollector(
1718 browser()->profile()).WaitForDownloadInfo(&downloads_in_database
));
1719 ASSERT_EQ(1u, downloads_in_database
->size());
1721 // Confirm history storage is what you expect for an interrupted slow download
1722 // job. The download isn't continuable, so there's no intermediate file.
1723 history::DownloadRow
& row1(downloads_in_database
->at(0));
1724 EXPECT_EQ(DestinationFile(browser(), file
), row1
.target_path
);
1725 EXPECT_TRUE(row1
.current_path
.empty());
1726 ASSERT_EQ(2u, row1
.url_chain
.size());
1727 EXPECT_EQ(redirect_url
.spec(), row1
.url_chain
[0].spec());
1728 EXPECT_EQ(download_url
.spec(), row1
.url_chain
[1].spec());
1729 EXPECT_EQ(history::DownloadDangerType::NOT_DANGEROUS
, row1
.danger_type
);
1730 EXPECT_LE(start
, row1
.start_time
);
1731 EXPECT_GE(end
, row1
.end_time
);
1732 EXPECT_EQ(net::URLRequestSlowDownloadJob::kFirstDownloadSize
,
1733 row1
.received_bytes
);
1734 EXPECT_EQ(net::URLRequestSlowDownloadJob::kFirstDownloadSize
1735 + net::URLRequestSlowDownloadJob::kSecondDownloadSize
,
1737 EXPECT_EQ(history::DownloadState::INTERRUPTED
, row1
.state
);
1738 EXPECT_EQ(history::ToHistoryDownloadInterruptReason(
1739 content::DOWNLOAD_INTERRUPT_REASON_NETWORK_FAILED
),
1740 row1
.interrupt_reason
);
1741 EXPECT_FALSE(row1
.opened
);
1744 // Make sure a dangerous file shows up properly in the history.
1745 IN_PROC_BROWSER_TEST_F(DownloadTest
, DownloadHistoryDangerCheck
) {
1746 #if defined(OS_WIN) && defined(USE_ASH)
1747 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
1748 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
1749 switches::kAshBrowserTests
))
1752 // Disable SafeBrowsing so that danger will be determined by downloads system.
1753 browser()->profile()->GetPrefs()->SetBoolean(prefs::kSafeBrowsingEnabled
,
1756 // .swf file so that it's dangerous on all platforms (including CrOS).
1757 base::FilePath
file(FILE_PATH_LITERAL("downloads/dangerous/dangerous.swf"));
1758 GURL
download_url(URLRequestMockHTTPJob::GetMockUrl(file
));
1760 // Download the url and wait until the object has been stored.
1761 scoped_ptr
<content::DownloadTestObserver
> download_observer(
1762 new content::DownloadTestObserverTerminal(
1763 DownloadManagerForBrowser(browser()), 1,
1764 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_IGNORE
));
1765 base::Time
start(base::Time::Now());
1766 HistoryObserver
observer(browser()->profile());
1767 observer
.SetFilterCallback(base::Bind(&HasDataAndName
));
1768 ui_test_utils::NavigateToURL(browser(), download_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 an unvalidated
1779 history::DownloadRow
& row(downloads_in_database
->at(0));
1780 EXPECT_EQ(DestinationFile(browser(), file
), row
.target_path
);
1781 EXPECT_NE(DownloadTargetDeterminer::GetCrDownloadPath(
1782 DestinationFile(browser(), file
)),
1784 EXPECT_EQ(history::DownloadDangerType::DANGEROUS_FILE
, row
.danger_type
);
1785 EXPECT_LE(start
, row
.start_time
);
1786 EXPECT_EQ(history::DownloadState::IN_PROGRESS
, row
.state
);
1787 EXPECT_FALSE(row
.opened
);
1789 // Validate the download and wait for it to finish.
1790 std::vector
<DownloadItem
*> downloads
;
1791 DownloadManagerForBrowser(browser())->GetAllDownloads(&downloads
);
1792 ASSERT_EQ(1u, downloads
.size());
1793 downloads
[0]->ValidateDangerousDownload();
1794 download_observer
->WaitForFinished();
1796 // Get history details and confirm it's what you expect.
1797 downloads_in_database
->clear();
1798 ASSERT_TRUE(DownloadsHistoryDataCollector(
1799 browser()->profile()).WaitForDownloadInfo(&downloads_in_database
));
1800 ASSERT_EQ(1u, downloads_in_database
->size());
1801 history::DownloadRow
& row1(downloads_in_database
->at(0));
1802 EXPECT_EQ(DestinationFile(browser(), file
), row1
.target_path
);
1803 EXPECT_EQ(DestinationFile(browser(), file
), row1
.current_path
);
1804 EXPECT_EQ(history::DownloadDangerType::USER_VALIDATED
, row1
.danger_type
);
1805 EXPECT_LE(start
, row1
.start_time
);
1806 EXPECT_EQ(history::DownloadState::COMPLETE
, row1
.state
);
1807 EXPECT_FALSE(row1
.opened
);
1808 // Not checking file size--not relevant to the point of the test, and
1809 // the file size is actually different on Windows and other platforms,
1810 // because for source control simplicity it's actually a text file, and
1811 // there are CRLF transformations for those files.
1814 // Test for crbug.com/14505. This tests that chrome:// urls are still functional
1815 // after download of a file while viewing another chrome://.
1816 IN_PROC_BROWSER_TEST_F(DownloadTest
, ChromeURLAfterDownload
) {
1817 base::FilePath
file(FILE_PATH_LITERAL("download-test1.lib"));
1818 GURL
download_url(URLRequestMockHTTPJob::GetMockUrl(file
));
1819 GURL
flags_url(chrome::kChromeUIFlagsURL
);
1820 GURL
extensions_url(chrome::kChromeUIExtensionsFrameURL
);
1822 ui_test_utils::NavigateToURL(browser(), flags_url
);
1823 DownloadAndWait(browser(), download_url
);
1824 ui_test_utils::NavigateToURL(browser(), extensions_url
);
1825 WebContents
* contents
=
1826 browser()->tab_strip_model()->GetActiveWebContents();
1827 ASSERT_TRUE(contents
);
1828 bool webui_responded
= false;
1829 EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
1831 "window.domAutomationController.send(window.webuiResponded);",
1833 EXPECT_TRUE(webui_responded
);
1836 // Test for crbug.com/12745. This tests that if a download is initiated from
1837 // a chrome:// page that has registered and onunload handler, the browser
1838 // will be able to close.
1839 IN_PROC_BROWSER_TEST_F(DownloadTest
, BrowserCloseAfterDownload
) {
1840 GURL
downloads_url(chrome::kChromeUIFlagsURL
);
1841 base::FilePath
file(FILE_PATH_LITERAL("download-test1.lib"));
1842 GURL
download_url(URLRequestMockHTTPJob::GetMockUrl(file
));
1844 ui_test_utils::NavigateToURL(browser(), downloads_url
);
1845 WebContents
* contents
= browser()->tab_strip_model()->GetActiveWebContents();
1846 ASSERT_TRUE(contents
);
1847 bool result
= false;
1848 EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
1850 "window.onunload = function() { var do_nothing = 0; }; "
1851 "window.domAutomationController.send(true);",
1853 EXPECT_TRUE(result
);
1855 DownloadAndWait(browser(), download_url
);
1857 content::WindowedNotificationObserver
signal(
1858 chrome::NOTIFICATION_BROWSER_CLOSED
,
1859 content::Source
<Browser
>(browser()));
1860 chrome::CloseWindow(browser());
1864 // Test to make sure the 'download' attribute in anchor tag is respected.
1865 IN_PROC_BROWSER_TEST_F(DownloadTest
, AnchorDownloadTag
) {
1866 base::FilePath
file(FILE_PATH_LITERAL("download-anchor-attrib.html"));
1867 GURL
url(URLRequestMockHTTPJob::GetMockUrl(file
));
1869 // Create a download, wait until it's complete, and confirm
1870 // we're in the expected state.
1871 scoped_ptr
<content::DownloadTestObserver
> observer(
1872 CreateWaiter(browser(), 1));
1873 ui_test_utils::NavigateToURL(browser(), url
);
1874 observer
->WaitForFinished();
1875 EXPECT_EQ(1u, observer
->NumDownloadsSeenInState(DownloadItem::COMPLETE
));
1876 CheckDownloadStates(1, DownloadItem::COMPLETE
);
1878 // Confirm the downloaded data exists.
1879 base::FilePath downloaded_file
= GetDownloadDirectory(browser());
1880 downloaded_file
= downloaded_file
.Append(FILE_PATH_LITERAL("a_red_dot.png"));
1881 EXPECT_TRUE(base::PathExists(downloaded_file
));
1884 // Test to make sure auto-open works.
1885 IN_PROC_BROWSER_TEST_F(DownloadTest
, AutoOpen
) {
1886 base::FilePath
file(FILE_PATH_LITERAL("download-autoopen.txt"));
1887 GURL
url(URLRequestMockHTTPJob::GetMockUrl(file
));
1890 GetDownloadPrefs(browser())->EnableAutoOpenBasedOnExtension(file
));
1892 DownloadAndWait(browser(), url
);
1894 // Find the download and confirm it was opened.
1895 std::vector
<DownloadItem
*> downloads
;
1896 DownloadManagerForBrowser(browser())->GetAllDownloads(&downloads
);
1897 ASSERT_EQ(1u, downloads
.size());
1898 EXPECT_EQ(DownloadItem::COMPLETE
, downloads
[0]->GetState());
1900 // Unfortunately, this will block forever, causing a timeout, if
1901 // the download is never opened.
1902 content::DownloadUpdatedObserver(
1903 downloads
[0], base::Bind(&WasAutoOpened
)).WaitForEvent();
1904 EXPECT_TRUE(downloads
[0]->GetOpened()); // Confirm it anyway.
1906 // As long as we're here, confirmed everything else is good.
1907 EXPECT_EQ(1, browser()->tab_strip_model()->count());
1908 CheckDownload(browser(), file
, file
);
1911 // Download an extension. Expect a dangerous download warning.
1912 // Deny the download.
1913 IN_PROC_BROWSER_TEST_F(DownloadTest
, CrxDenyInstall
) {
1914 FeatureSwitch::ScopedOverride
enable_easy_off_store_install(
1915 FeatureSwitch::easy_off_store_install(), true);
1917 GURL
extension_url(URLRequestMockHTTPJob::GetMockUrl(kGoodCrxPath
));
1919 scoped_ptr
<content::DownloadTestObserver
> observer(
1920 DangerousDownloadWaiter(
1922 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_DENY
));
1923 ui_test_utils::NavigateToURL(browser(), extension_url
);
1925 observer
->WaitForFinished();
1926 EXPECT_EQ(1u, observer
->NumDownloadsSeenInState(DownloadItem::CANCELLED
));
1927 EXPECT_EQ(1u, observer
->NumDangerousDownloadsSeen());
1928 EXPECT_TRUE(VerifyNoDownloads());
1930 // Check that the CRX is not installed.
1931 ExtensionService
* extension_service
= extensions::ExtensionSystem::Get(
1932 browser()->profile())->extension_service();
1933 ASSERT_FALSE(extension_service
->GetExtensionById(kGoodCrxId
, false));
1936 // Download an extension. Expect a dangerous download warning.
1937 // Allow the download, deny the install.
1938 IN_PROC_BROWSER_TEST_F(DownloadTest
, CrxInstallDenysPermissions
) {
1939 FeatureSwitch::ScopedOverride
enable_easy_off_store_install(
1940 FeatureSwitch::easy_off_store_install(), true);
1942 GURL
extension_url(URLRequestMockHTTPJob::GetMockUrl(kGoodCrxPath
));
1944 // Install a mock install UI that simulates a user denying permission to
1945 // finish the install.
1946 download_crx_util::SetMockInstallPromptForTesting(
1947 scoped_ptr
<ExtensionInstallPrompt
>(
1948 new MockAbortExtensionInstallPrompt()));
1950 scoped_ptr
<content::DownloadTestObserver
> observer(
1951 DangerousDownloadWaiter(
1953 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_ACCEPT
));
1954 ui_test_utils::NavigateToURL(browser(), extension_url
);
1956 observer
->WaitForFinished();
1957 EXPECT_EQ(1u, observer
->NumDownloadsSeenInState(DownloadItem::COMPLETE
));
1958 CheckDownloadStates(1, DownloadItem::COMPLETE
);
1959 EXPECT_EQ(1u, observer
->NumDangerousDownloadsSeen());
1961 content::DownloadManager::DownloadVector downloads
;
1962 DownloadManagerForBrowser(browser())->GetAllDownloads(&downloads
);
1963 ASSERT_EQ(1u, downloads
.size());
1964 content::DownloadUpdatedObserver(
1965 downloads
[0], base::Bind(&WasAutoOpened
)).WaitForEvent();
1967 // Check that the extension was not installed.
1968 ExtensionService
* extension_service
= extensions::ExtensionSystem::Get(
1969 browser()->profile())->extension_service();
1970 ASSERT_FALSE(extension_service
->GetExtensionById(kGoodCrxId
, false));
1973 // Download an extension. Expect a dangerous download warning.
1974 // Allow the download, and the install.
1975 IN_PROC_BROWSER_TEST_F(DownloadTest
, CrxInstallAcceptPermissions
) {
1976 FeatureSwitch::ScopedOverride
enable_easy_off_store_install(
1977 FeatureSwitch::easy_off_store_install(), true);
1979 GURL
extension_url(URLRequestMockHTTPJob::GetMockUrl(kGoodCrxPath
));
1981 // Install a mock install UI that simulates a user allowing permission to
1982 // finish the install.
1983 SetAllowMockInstallPrompt();
1985 scoped_ptr
<content::DownloadTestObserver
> observer(
1986 DangerousDownloadWaiter(
1988 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_ACCEPT
));
1989 ui_test_utils::NavigateToURL(browser(), extension_url
);
1991 observer
->WaitForFinished();
1992 EXPECT_EQ(1u, observer
->NumDownloadsSeenInState(DownloadItem::COMPLETE
));
1993 CheckDownloadStates(1, DownloadItem::COMPLETE
);
1994 EXPECT_EQ(1u, observer
->NumDangerousDownloadsSeen());
1996 // Download shelf should close from auto-open.
1997 content::DownloadManager::DownloadVector downloads
;
1998 DownloadManagerForBrowser(browser())->GetAllDownloads(&downloads
);
1999 ASSERT_EQ(1u, downloads
.size());
2000 content::DownloadUpdatedObserver(
2001 downloads
[0], base::Bind(&WasAutoOpened
)).WaitForEvent();
2003 // Check that the extension was installed.
2004 ExtensionService
* extension_service
= extensions::ExtensionSystem::Get(
2005 browser()->profile())->extension_service();
2006 ASSERT_TRUE(extension_service
->GetExtensionById(kGoodCrxId
, false));
2009 // Test installing a CRX that fails integrity checks.
2010 IN_PROC_BROWSER_TEST_F(DownloadTest
, CrxInvalid
) {
2011 base::FilePath
file(FILE_PATH_LITERAL("extensions/bad_signature.crx"));
2012 GURL
extension_url(URLRequestMockHTTPJob::GetMockUrl(file
));
2014 // Install a mock install UI that simulates a user allowing permission to
2015 // finish the install, and dismisses any error message. We check that the
2016 // install failed below.
2017 SetAllowMockInstallPrompt();
2019 scoped_ptr
<content::DownloadTestObserver
> observer(
2020 DangerousDownloadWaiter(
2022 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_ACCEPT
));
2023 ui_test_utils::NavigateToURL(browser(), extension_url
);
2025 observer
->WaitForFinished();
2026 EXPECT_EQ(1u, observer
->NumDownloadsSeenInState(DownloadItem::COMPLETE
));
2027 CheckDownloadStates(1, DownloadItem::COMPLETE
);
2029 // Check that the extension was not installed.
2030 ExtensionService
* extension_service
= extensions::ExtensionSystem::Get(
2031 browser()->profile())->extension_service();
2032 ASSERT_FALSE(extension_service
->GetExtensionById(kGoodCrxId
, false));
2035 // Install a large (100kb) theme.
2036 IN_PROC_BROWSER_TEST_F(DownloadTest
, CrxLargeTheme
) {
2037 FeatureSwitch::ScopedOverride
enable_easy_off_store_install(
2038 FeatureSwitch::easy_off_store_install(), true);
2040 GURL
extension_url(URLRequestMockHTTPJob::GetMockUrl(kLargeThemePath
));
2042 // Install a mock install UI that simulates a user allowing permission to
2043 // finish the install.
2044 SetAllowMockInstallPrompt();
2046 scoped_ptr
<content::DownloadTestObserver
> observer(
2047 DangerousDownloadWaiter(
2049 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_ACCEPT
));
2050 ui_test_utils::NavigateToURL(browser(), extension_url
);
2052 observer
->WaitForFinished();
2053 EXPECT_EQ(1u, observer
->NumDownloadsSeenInState(DownloadItem::COMPLETE
));
2054 CheckDownloadStates(1, DownloadItem::COMPLETE
);
2055 EXPECT_EQ(1u, observer
->NumDangerousDownloadsSeen());
2057 // Download shelf should close from auto-open.
2058 content::DownloadManager::DownloadVector downloads
;
2059 DownloadManagerForBrowser(browser())->GetAllDownloads(&downloads
);
2060 ASSERT_EQ(1u, downloads
.size());
2061 content::DownloadUpdatedObserver(
2062 downloads
[0], base::Bind(&WasAutoOpened
)).WaitForEvent();
2064 // Check that the extension was installed.
2065 ExtensionService
* extension_service
= extensions::ExtensionSystem::Get(
2066 browser()->profile())->extension_service();
2067 ASSERT_TRUE(extension_service
->GetExtensionById(kLargeThemeCrxId
, false));
2070 // Tests for download initiation functions.
2071 IN_PROC_BROWSER_TEST_F(DownloadTest
, DownloadUrl
) {
2072 base::FilePath
file(FILE_PATH_LITERAL("download-test1.lib"));
2073 GURL
url(URLRequestMockHTTPJob::GetMockUrl(file
));
2075 // DownloadUrl always prompts; return acceptance of whatever it prompts.
2076 EnableFileChooser(true);
2078 WebContents
* web_contents
=
2079 browser()->tab_strip_model()->GetActiveWebContents();
2080 ASSERT_TRUE(web_contents
);
2082 content::DownloadTestObserver
* observer(
2083 new content::DownloadTestObserverTerminal(
2084 DownloadManagerForBrowser(browser()), 1,
2085 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL
));
2086 scoped_ptr
<DownloadUrlParameters
> params(
2087 DownloadUrlParameters::FromWebContents(web_contents
, url
));
2088 params
->set_prompt(true);
2089 DownloadManagerForBrowser(browser())->DownloadUrl(params
.Pass());
2090 observer
->WaitForFinished();
2091 EXPECT_EQ(1u, observer
->NumDownloadsSeenInState(DownloadItem::COMPLETE
));
2092 CheckDownloadStates(1, DownloadItem::COMPLETE
);
2093 EXPECT_TRUE(DidShowFileChooser());
2096 EXPECT_EQ(1, browser()->tab_strip_model()->count());
2097 ASSERT_TRUE(CheckDownload(browser(), file
, file
));
2100 IN_PROC_BROWSER_TEST_F(DownloadTest
, DownloadUrlToPath
) {
2101 base::FilePath
file(FILE_PATH_LITERAL("download-test1.lib"));
2102 GURL
url(URLRequestMockHTTPJob::GetMockUrl(file
));
2104 WebContents
* web_contents
=
2105 browser()->tab_strip_model()->GetActiveWebContents();
2106 ASSERT_TRUE(web_contents
);
2108 base::ScopedTempDir other_directory
;
2109 ASSERT_TRUE(other_directory
.CreateUniqueTempDir());
2110 base::FilePath target_file_full_path
2111 = other_directory
.path().Append(file
.BaseName());
2112 content::DownloadTestObserver
* observer(CreateWaiter(browser(), 1));
2113 scoped_ptr
<DownloadUrlParameters
> params(
2114 DownloadUrlParameters::FromWebContents(web_contents
, url
));
2115 params
->set_file_path(target_file_full_path
);
2116 DownloadManagerForBrowser(browser())->DownloadUrl(params
.Pass());
2117 observer
->WaitForFinished();
2118 EXPECT_EQ(1u, observer
->NumDownloadsSeenInState(DownloadItem::COMPLETE
));
2121 EXPECT_EQ(1, browser()->tab_strip_model()->count());
2122 ASSERT_TRUE(CheckDownloadFullPaths(browser(),
2123 target_file_full_path
,
2126 // Temporary are treated as auto-opened, and after that open won't be
2127 // visible; wait for auto-open and confirm not visible.
2128 std::vector
<DownloadItem
*> downloads
;
2129 DownloadManagerForBrowser(browser())->GetAllDownloads(&downloads
);
2130 ASSERT_EQ(1u, downloads
.size());
2131 content::DownloadUpdatedObserver(
2132 downloads
[0], base::Bind(&WasAutoOpened
)).WaitForEvent();
2135 IN_PROC_BROWSER_TEST_F(DownloadTest
, SavePageNonHTMLViaGet
) {
2136 embedded_test_server()->ServeFilesFromDirectory(GetTestDataDirectory());
2137 ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
2138 EnableFileChooser(true);
2139 std::vector
<DownloadItem
*> download_items
;
2140 GetDownloads(browser(), &download_items
);
2141 ASSERT_TRUE(download_items
.empty());
2143 // Navigate to a non-HTML resource. The resource also has
2144 // Cache-Control: no-cache set, which normally requires revalidation
2146 GURL url
= embedded_test_server()->GetURL("/downloads/image.jpg");
2147 ASSERT_TRUE(url
.is_valid());
2148 ui_test_utils::NavigateToURL(browser(), url
);
2150 // Stop the test server, and then try to save the page. If cache validation
2151 // is not bypassed then this will fail since the server is no longer
2153 ASSERT_TRUE(embedded_test_server()->ShutdownAndWaitUntilComplete());
2155 scoped_ptr
<content::DownloadTestObserver
> waiter(
2156 new content::DownloadTestObserverTerminal(
2157 DownloadManagerForBrowser(browser()), 1,
2158 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL
));
2159 chrome::SavePage(browser());
2160 waiter
->WaitForFinished();
2161 EXPECT_EQ(1u, waiter
->NumDownloadsSeenInState(DownloadItem::COMPLETE
));
2162 CheckDownloadStates(1, DownloadItem::COMPLETE
);
2164 // Validate that the correct file was downloaded.
2165 GetDownloads(browser(), &download_items
);
2166 EXPECT_TRUE(DidShowFileChooser());
2167 ASSERT_EQ(1u, download_items
.size());
2168 ASSERT_EQ(url
, download_items
[0]->GetOriginalUrl());
2170 // Try to download it via a context menu.
2171 scoped_ptr
<content::DownloadTestObserver
> waiter_context_menu(
2172 new content::DownloadTestObserverTerminal(
2173 DownloadManagerForBrowser(browser()), 1,
2174 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL
));
2175 content::ContextMenuParams context_menu_params
;
2176 context_menu_params
.media_type
= blink::WebContextMenuData::MediaTypeImage
;
2177 context_menu_params
.src_url
= url
;
2178 context_menu_params
.page_url
= url
;
2179 TestRenderViewContextMenu
menu(
2180 browser()->tab_strip_model()->GetActiveWebContents()->GetMainFrame(),
2181 context_menu_params
);
2183 menu
.ExecuteCommand(IDC_CONTENT_CONTEXT_SAVEIMAGEAS
, 0);
2184 waiter_context_menu
->WaitForFinished();
2186 1u, waiter_context_menu
->NumDownloadsSeenInState(DownloadItem::COMPLETE
));
2187 CheckDownloadStates(2, DownloadItem::COMPLETE
);
2189 // Validate that the correct file was downloaded via the context menu.
2190 download_items
.clear();
2191 GetDownloads(browser(), &download_items
);
2192 EXPECT_TRUE(DidShowFileChooser());
2193 ASSERT_EQ(2u, download_items
.size());
2194 ASSERT_EQ(url
, download_items
[0]->GetOriginalUrl());
2195 ASSERT_EQ(url
, download_items
[1]->GetOriginalUrl());
2198 // A EmbeddedTestServer::HandleRequestCallback function that checks for requests
2199 // with query string ?allow-post-only, and returns a 404 response if the method
2201 static scoped_ptr
<net::test_server::HttpResponse
> FilterPostOnlyURLsHandler(
2202 const net::test_server::HttpRequest
& request
) {
2203 scoped_ptr
<net::test_server::BasicHttpResponse
> response
;
2204 if (request
.relative_url
.find("?allow-post-only") != std::string::npos
&&
2205 request
.method
!= net::test_server::METHOD_POST
) {
2206 response
.reset(new net::test_server::BasicHttpResponse());
2207 response
->set_code(net::HTTP_NOT_FOUND
);
2209 return response
.Pass();
2212 IN_PROC_BROWSER_TEST_F(DownloadTest
, SavePageNonHTMLViaPost
) {
2213 embedded_test_server()->RegisterRequestHandler(
2214 base::Bind(&FilterPostOnlyURLsHandler
));
2215 embedded_test_server()->ServeFilesFromDirectory(GetTestDataDirectory());
2216 ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
2217 EnableFileChooser(true);
2218 std::vector
<DownloadItem
*> download_items
;
2219 GetDownloads(browser(), &download_items
);
2220 ASSERT_TRUE(download_items
.empty());
2222 // Navigate to a form page.
2224 embedded_test_server()->GetURL("/downloads/form_page_to_post.html");
2225 ASSERT_TRUE(form_url
.is_valid());
2226 ui_test_utils::NavigateToURL(browser(), form_url
);
2228 // Submit the form. This will send a POST reqeuest, and the response is a
2229 // JPEG image. The resource also has Cache-Control: no-cache set,
2230 // which normally requires revalidation each time.
2232 embedded_test_server()->GetURL("/downloads/image.jpg?allow-post-only");
2233 ASSERT_TRUE(jpeg_url
.is_valid());
2234 WebContents
* web_contents
=
2235 browser()->tab_strip_model()->GetActiveWebContents();
2236 ASSERT_TRUE(web_contents
!= NULL
);
2237 content::WindowedNotificationObserver
observer(
2238 content::NOTIFICATION_NAV_ENTRY_COMMITTED
,
2239 content::Source
<content::NavigationController
>(
2240 &web_contents
->GetController()));
2241 content::RenderFrameHost
* render_frame_host
= web_contents
->GetMainFrame();
2242 ASSERT_TRUE(render_frame_host
!= NULL
);
2243 render_frame_host
->ExecuteJavaScriptForTests(
2244 base::ASCIIToUTF16("SubmitForm()"));
2246 EXPECT_EQ(jpeg_url
, web_contents
->GetURL());
2248 // Stop the test server, and then try to save the page. If cache validation
2249 // is not bypassed then this will fail since the server is no longer
2250 // reachable. This will also fail if it tries to be retrieved via "GET"
2251 // rather than "POST".
2252 ASSERT_TRUE(embedded_test_server()->ShutdownAndWaitUntilComplete());
2253 scoped_ptr
<content::DownloadTestObserver
> waiter(
2254 new content::DownloadTestObserverTerminal(
2255 DownloadManagerForBrowser(browser()), 1,
2256 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL
));
2257 chrome::SavePage(browser());
2258 waiter
->WaitForFinished();
2259 EXPECT_EQ(1u, waiter
->NumDownloadsSeenInState(DownloadItem::COMPLETE
));
2260 CheckDownloadStates(1, DownloadItem::COMPLETE
);
2262 // Validate that the correct file was downloaded.
2263 GetDownloads(browser(), &download_items
);
2264 EXPECT_TRUE(DidShowFileChooser());
2265 ASSERT_EQ(1u, download_items
.size());
2266 ASSERT_EQ(jpeg_url
, download_items
[0]->GetOriginalUrl());
2268 // Try to download it via a context menu.
2269 scoped_ptr
<content::DownloadTestObserver
> waiter_context_menu(
2270 new content::DownloadTestObserverTerminal(
2271 DownloadManagerForBrowser(browser()), 1,
2272 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL
));
2273 content::ContextMenuParams context_menu_params
;
2274 context_menu_params
.media_type
= blink::WebContextMenuData::MediaTypeImage
;
2275 context_menu_params
.src_url
= jpeg_url
;
2276 context_menu_params
.page_url
= jpeg_url
;
2277 TestRenderViewContextMenu
menu(web_contents
->GetMainFrame(),
2278 context_menu_params
);
2280 menu
.ExecuteCommand(IDC_CONTENT_CONTEXT_SAVEIMAGEAS
, 0);
2281 waiter_context_menu
->WaitForFinished();
2283 1u, waiter_context_menu
->NumDownloadsSeenInState(DownloadItem::COMPLETE
));
2284 CheckDownloadStates(2, DownloadItem::COMPLETE
);
2286 // Validate that the correct file was downloaded via the context menu.
2287 download_items
.clear();
2288 GetDownloads(browser(), &download_items
);
2289 EXPECT_TRUE(DidShowFileChooser());
2290 ASSERT_EQ(2u, download_items
.size());
2291 ASSERT_EQ(jpeg_url
, download_items
[0]->GetOriginalUrl());
2292 ASSERT_EQ(jpeg_url
, download_items
[1]->GetOriginalUrl());
2295 IN_PROC_BROWSER_TEST_F(DownloadTest
, DownloadErrorsServer
) {
2296 DownloadInfo download_info
[] = {
2297 { // Normal navigated download.
2300 content::DOWNLOAD_INTERRUPT_REASON_NONE
,
2304 { // Normal direct download.
2307 content::DOWNLOAD_INTERRUPT_REASON_NONE
,
2311 { // Direct download with 404 error.
2312 "there_IS_no_spoon.zip",
2314 content::DOWNLOAD_INTERRUPT_REASON_SERVER_BAD_CONTENT
,
2318 { // Navigated download with 404 error.
2319 "there_IS_no_spoon.zip",
2321 content::DOWNLOAD_INTERRUPT_REASON_SERVER_BAD_CONTENT
,
2325 { // Direct download with 400 error.
2326 "zip_file_not_found.zip",
2328 content::DOWNLOAD_INTERRUPT_REASON_SERVER_FAILED
,
2332 { // Navigated download with 400 error.
2333 "zip_file_not_found.zip",
2335 content::DOWNLOAD_INTERRUPT_REASON_SERVER_FAILED
,
2341 DownloadFilesCheckErrors(arraysize(download_info
), download_info
);
2344 IN_PROC_BROWSER_TEST_F(DownloadTest
, DownloadErrorsFile
) {
2345 FileErrorInjectInfo error_info
[] = {
2346 { // Navigated download with injected "Disk full" error in Initialize().
2349 content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE
,
2354 content::TestFileErrorInjector::FILE_OPERATION_INITIALIZE
,
2356 content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE
,
2359 { // Direct download with injected "Disk full" error in Initialize().
2362 content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE
,
2367 content::TestFileErrorInjector::FILE_OPERATION_INITIALIZE
,
2369 content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE
,
2372 { // Navigated download with injected "Disk full" error in Write().
2375 content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE
,
2380 content::TestFileErrorInjector::FILE_OPERATION_WRITE
,
2382 content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE
,
2385 { // Direct download with injected "Disk full" error in Write().
2388 content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE
,
2393 content::TestFileErrorInjector::FILE_OPERATION_WRITE
,
2395 content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE
,
2398 { // Navigated download with injected "Failed" error in Initialize().
2401 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED
,
2406 content::TestFileErrorInjector::FILE_OPERATION_INITIALIZE
,
2408 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED
,
2411 { // Direct download with injected "Failed" error in Initialize().
2414 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED
,
2419 content::TestFileErrorInjector::FILE_OPERATION_INITIALIZE
,
2421 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED
,
2424 { // Navigated download with injected "Failed" error in Write().
2427 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED
,
2432 content::TestFileErrorInjector::FILE_OPERATION_WRITE
,
2434 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED
,
2437 { // Direct download with injected "Failed" error in Write().
2440 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED
,
2445 content::TestFileErrorInjector::FILE_OPERATION_WRITE
,
2447 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED
,
2450 { // Navigated download with injected "Name too long" error in
2454 content::DOWNLOAD_INTERRUPT_REASON_FILE_NAME_TOO_LONG
,
2459 content::TestFileErrorInjector::FILE_OPERATION_INITIALIZE
,
2461 content::DOWNLOAD_INTERRUPT_REASON_FILE_NAME_TOO_LONG
,
2464 { // Direct download with injected "Name too long" error in Initialize().
2467 content::DOWNLOAD_INTERRUPT_REASON_FILE_NAME_TOO_LONG
,
2472 content::TestFileErrorInjector::FILE_OPERATION_INITIALIZE
,
2474 content::DOWNLOAD_INTERRUPT_REASON_FILE_NAME_TOO_LONG
,
2477 { // Navigated download with injected "Name too long" error in Write().
2480 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED
,
2485 content::TestFileErrorInjector::FILE_OPERATION_WRITE
,
2487 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED
,
2490 { // Direct download with injected "Name too long" error in Write().
2493 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED
,
2498 content::TestFileErrorInjector::FILE_OPERATION_WRITE
,
2500 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED
,
2503 { // Direct download with injected "Disk full" error in 2nd Write().
2504 { "06bESSE21Evolution.ppt",
2506 content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE
,
2511 content::TestFileErrorInjector::FILE_OPERATION_WRITE
,
2513 content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE
,
2518 DownloadInsertFilesErrorCheckErrors(arraysize(error_info
), error_info
);
2521 IN_PROC_BROWSER_TEST_F(DownloadTest
, DownloadErrorReadonlyFolder
) {
2522 DownloadInfo download_info
[] = {
2526 // This passes because we switch to the My Documents folder.
2527 content::DOWNLOAD_INTERRUPT_REASON_NONE
,
2534 // This passes because we switch to the My Documents folder.
2535 content::DOWNLOAD_INTERRUPT_REASON_NONE
,
2541 DownloadFilesToReadonlyFolder(arraysize(download_info
), download_info
);
2544 // Test that we show a dangerous downloads warning for a dangerous file
2545 // downloaded through a blob: URL.
2546 IN_PROC_BROWSER_TEST_F(DownloadTest
, DownloadDangerousBlobData
) {
2548 // On Windows, if SafeBrowsing is enabled, certain file types (.exe, .cab,
2549 // .msi) will be handled by the DownloadProtectionService. However, if the URL
2550 // is non-standard (e.g. blob:) then those files won't be handled by the
2551 // DPS. We should be showing the dangerous download warning for any file
2552 // considered dangerous and isn't handled by the DPS.
2553 const char kFilename
[] = "foo.exe";
2555 const char kFilename
[] = "foo.swf";
2558 std::string
path("downloads/download-dangerous-blob.html?filename=");
2561 // Need to use http urls because the blob js doesn't work on file urls for
2562 // security reasons.
2563 GURL url
= net::URLRequestMockHTTPJob::GetMockUrl(path
);
2565 content::DownloadTestObserver
* observer(DangerousDownloadWaiter(
2567 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_ACCEPT
));
2568 ui_test_utils::NavigateToURL(browser(), url
);
2569 observer
->WaitForFinished();
2571 EXPECT_EQ(1u, observer
->NumDownloadsSeenInState(DownloadItem::COMPLETE
));
2572 EXPECT_EQ(1u, observer
->NumDangerousDownloadsSeen());
2575 // A EmbeddedTestServer::HandleRequestCallback function that echoes the Referrer
2576 // header as its contents. Only responds to the relative URL /echoreferrer
2579 // Referer: http://example.com/foo
2580 // S -> C: HTTP/1.1 200 OK
2581 // Content-Type: text/plain
2583 // http://example.com/foo
2584 static scoped_ptr
<net::test_server::HttpResponse
> EchoReferrerRequestHandler(
2585 const net::test_server::HttpRequest
& request
) {
2586 const std::string kReferrerHeader
= "Referer"; // SIC
2588 if (request
.relative_url
.find("/echoreferrer") != 0)
2589 return scoped_ptr
<net::test_server::HttpResponse
>();
2591 scoped_ptr
<net::test_server::BasicHttpResponse
> response(
2592 new net::test_server::BasicHttpResponse());
2593 response
->set_code(net::HTTP_OK
);
2594 response
->set_content_type("text/plain");
2595 auto referrer_header
= request
.headers
.find(kReferrerHeader
);
2596 if (referrer_header
!= request
.headers
.end())
2597 response
->set_content(referrer_header
->second
);
2598 return response
.Pass();
2601 IN_PROC_BROWSER_TEST_F(DownloadTest
, LoadURLExternallyReferrerPolicy
) {
2602 embedded_test_server()->RegisterRequestHandler(
2603 base::Bind(&EchoReferrerRequestHandler
));
2604 embedded_test_server()->ServeFilesFromDirectory(GetTestDataDirectory());
2605 ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
2606 EnableFileChooser(true);
2607 std::vector
<DownloadItem
*> download_items
;
2608 GetDownloads(browser(), &download_items
);
2609 ASSERT_TRUE(download_items
.empty());
2611 // Navigate to a page with a referrer policy and a link on it. The link points
2612 // to /echoreferrer.
2613 GURL url
= embedded_test_server()->GetURL("/downloads/referrer_policy.html");
2614 ASSERT_TRUE(url
.is_valid());
2615 ui_test_utils::NavigateToURL(browser(), url
);
2617 scoped_ptr
<content::DownloadTestObserver
> waiter(
2618 new content::DownloadTestObserverTerminal(
2619 DownloadManagerForBrowser(browser()), 1,
2620 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL
));
2622 // Click on the link with the alt key pressed. This will download the link
2624 WebContents
* tab
= browser()->tab_strip_model()->GetActiveWebContents();
2625 blink::WebMouseEvent mouse_event
;
2626 mouse_event
.type
= blink::WebInputEvent::MouseDown
;
2627 mouse_event
.button
= blink::WebMouseEvent::ButtonLeft
;
2630 mouse_event
.clickCount
= 1;
2631 mouse_event
.modifiers
= blink::WebInputEvent::AltKey
;
2632 tab
->GetRenderViewHost()->ForwardMouseEvent(mouse_event
);
2633 mouse_event
.type
= blink::WebInputEvent::MouseUp
;
2634 tab
->GetRenderViewHost()->ForwardMouseEvent(mouse_event
);
2636 waiter
->WaitForFinished();
2637 EXPECT_EQ(1u, waiter
->NumDownloadsSeenInState(DownloadItem::COMPLETE
));
2638 CheckDownloadStates(1, DownloadItem::COMPLETE
);
2640 // Validate that the correct file was downloaded.
2641 GetDownloads(browser(), &download_items
);
2642 ASSERT_EQ(1u, download_items
.size());
2643 ASSERT_EQ(embedded_test_server()->GetURL("/echoreferrer"),
2644 download_items
[0]->GetOriginalUrl());
2646 // Check that the file contains the expected referrer.
2647 base::FilePath
file(download_items
[0]->GetTargetFilePath());
2648 std::string expected_contents
= embedded_test_server()->GetURL("/").spec();
2649 ASSERT_TRUE(VerifyFile(file
, expected_contents
, expected_contents
.length()));
2652 // This test ensures that the Referer header is properly sanitized when
2653 // Save Link As is chosen from the context menu.
2654 IN_PROC_BROWSER_TEST_F(DownloadTest
, SaveLinkAsReferrerPolicyOrigin
) {
2655 embedded_test_server()->RegisterRequestHandler(
2656 base::Bind(&EchoReferrerRequestHandler
));
2657 ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
2658 EnableFileChooser(true);
2659 std::vector
<DownloadItem
*> download_items
;
2660 GetDownloads(browser(), &download_items
);
2661 ASSERT_TRUE(download_items
.empty());
2663 // Navigate to the initial page, where Save Link As will be executed.
2664 GURL url
= net::URLRequestMockHTTPJob::GetMockHttpsUrl(
2665 std::string("referrer_policy/referrer-policy-start.html?policy=origin") +
2666 "&redirect=" + embedded_test_server()->GetURL("/echoreferrer").spec() +
2667 "&link=true&target=");
2668 ASSERT_TRUE(url
.is_valid());
2669 ui_test_utils::NavigateToURL(browser(), url
);
2671 scoped_ptr
<content::DownloadTestObserver
> waiter(
2672 new content::DownloadTestObserverTerminal(
2673 DownloadManagerForBrowser(browser()), 1,
2674 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL
));
2676 // Right-click on the link and choose Save Link As. This will download the
2678 ContextMenuNotificationObserver
context_menu_observer(
2679 IDC_CONTENT_CONTEXT_SAVELINKAS
);
2681 WebContents
* tab
= browser()->tab_strip_model()->GetActiveWebContents();
2682 blink::WebMouseEvent mouse_event
;
2683 mouse_event
.type
= blink::WebInputEvent::MouseDown
;
2684 mouse_event
.button
= blink::WebMouseEvent::ButtonRight
;
2687 mouse_event
.clickCount
= 1;
2688 tab
->GetRenderViewHost()->ForwardMouseEvent(mouse_event
);
2689 mouse_event
.type
= blink::WebInputEvent::MouseUp
;
2690 tab
->GetRenderViewHost()->ForwardMouseEvent(mouse_event
);
2692 waiter
->WaitForFinished();
2693 EXPECT_EQ(1u, waiter
->NumDownloadsSeenInState(DownloadItem::COMPLETE
));
2694 CheckDownloadStates(1, DownloadItem::COMPLETE
);
2696 // Validate that the correct file was downloaded.
2697 GetDownloads(browser(), &download_items
);
2698 EXPECT_EQ(1u, download_items
.size());
2699 EXPECT_EQ(embedded_test_server()->GetURL("/echoreferrer"),
2700 download_items
[0]->GetOriginalUrl());
2702 // Check that the file contains the expected referrer.
2703 base::FilePath
file(download_items
[0]->GetTargetFilePath());
2704 std::string expected_contents
=
2705 net::URLRequestMockHTTPJob::GetMockHttpsUrl(std::string()).spec();
2706 EXPECT_TRUE(VerifyFile(file
, expected_contents
, expected_contents
.length()));
2709 // This test ensures that the Referer header is properly sanitized when
2710 // Save Image As is chosen from the context menu.
2711 IN_PROC_BROWSER_TEST_F(DownloadTest
, SaveImageAsReferrerPolicyDefault
) {
2712 embedded_test_server()->RegisterRequestHandler(
2713 base::Bind(&EchoReferrerRequestHandler
));
2714 ASSERT_TRUE(embedded_test_server()->InitializeAndWaitUntilReady());
2715 EnableFileChooser(true);
2716 std::vector
<DownloadItem
*> download_items
;
2717 GetDownloads(browser(), &download_items
);
2718 ASSERT_TRUE(download_items
.empty());
2720 GURL url
= net::URLRequestMockHTTPJob::GetMockHttpsUrl("title1.html");
2721 GURL img_url
= embedded_test_server()->GetURL("/echoreferrer");
2722 ASSERT_TRUE(url
.is_valid());
2723 ui_test_utils::NavigateToURL(browser(), url
);
2725 // Try to download an image via a context menu.
2726 scoped_ptr
<content::DownloadTestObserver
> waiter_context_menu(
2727 new content::DownloadTestObserverTerminal(
2728 DownloadManagerForBrowser(browser()), 1,
2729 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL
));
2730 content::ContextMenuParams context_menu_params
;
2731 context_menu_params
.media_type
= blink::WebContextMenuData::MediaTypeImage
;
2732 context_menu_params
.page_url
= url
;
2733 context_menu_params
.src_url
= img_url
;
2734 TestRenderViewContextMenu
menu(
2735 browser()->tab_strip_model()->GetActiveWebContents()->GetMainFrame(),
2736 context_menu_params
);
2738 menu
.ExecuteCommand(IDC_CONTENT_CONTEXT_SAVEIMAGEAS
, 0);
2739 waiter_context_menu
->WaitForFinished();
2741 1u, waiter_context_menu
->NumDownloadsSeenInState(DownloadItem::COMPLETE
));
2742 CheckDownloadStates(1, DownloadItem::COMPLETE
);
2744 // Validate that the correct file was downloaded via the context menu.
2745 download_items
.clear();
2746 GetDownloads(browser(), &download_items
);
2747 EXPECT_TRUE(DidShowFileChooser());
2748 ASSERT_EQ(1u, download_items
.size());
2749 ASSERT_EQ(img_url
, download_items
[0]->GetOriginalUrl());
2750 base::FilePath file
= download_items
[0]->GetTargetFilePath();
2751 // The contents of the file is the value of the Referer header if there was
2753 EXPECT_TRUE(VerifyFile(file
, "", 0));
2756 // On mobile, the multiple downloads UI is an infobar. On desktop, it's a
2757 // bubble. Test each as appropriate.
2758 #if defined(OS_ANDROID) || defined(OS_IOS)
2759 IN_PROC_BROWSER_TEST_F(DownloadTest
, TestMultipleDownloadsInfobar
) {
2760 // Ensure that infobars are being used instead of bubbles.
2761 base::CommandLine::ForCurrentProcess()->AppendSwitch(
2762 switches::kDisablePermissionsBubbles
);
2764 // Create a downloads observer.
2765 scoped_ptr
<content::DownloadTestObserver
> downloads_observer(
2766 CreateWaiter(browser(), 2));
2768 // Create an infobar observer.
2769 content::WindowedNotificationObserver
infobar_added_1(
2770 chrome::NOTIFICATION_TAB_CONTENTS_INFOBAR_ADDED
,
2771 content::NotificationService::AllSources());
2772 ui_test_utils::NavigateToURL(browser(),
2773 net::URLRequestMockHTTPJob::GetMockUrl(
2774 "downloads/download-a_zip_file.html"));
2775 infobar_added_1
.Wait();
2777 InfoBarService
* infobar_service
= InfoBarService::FromWebContents(
2778 browser()->tab_strip_model()->GetActiveWebContents());
2779 // Verify that there is only one infobar.
2780 ASSERT_EQ(1u, infobar_service
->infobar_count());
2782 // Get the infobar at index 0.
2783 infobars::InfoBar
* infobar
= infobar_service
->infobar_at(0);
2784 ConfirmInfoBarDelegate
* confirm_infobar
=
2785 infobar
->delegate()->AsConfirmInfoBarDelegate();
2786 ASSERT_TRUE(confirm_infobar
!= NULL
);
2788 // Verify multi download warning infobar message.
2789 EXPECT_EQ(confirm_infobar
->GetMessageText(),
2790 l10n_util::GetStringUTF16(IDS_MULTI_DOWNLOAD_WARNING
));
2792 // Click on the "Allow" button to allow multiple downloads.
2793 if (confirm_infobar
->Accept())
2794 infobar_service
->RemoveInfoBar(infobar
);
2795 // Verify that there are no more infobars.
2796 EXPECT_EQ(0u, infobar_service
->infobar_count());
2798 // Waits for the download to complete.
2799 downloads_observer
->WaitForFinished();
2800 EXPECT_EQ(2u, downloads_observer
->NumDownloadsSeenInState(
2801 DownloadItem::COMPLETE
));
2804 IN_PROC_BROWSER_TEST_F(DownloadTest
, TestMultipleDownloadsBubble
) {
2805 #if defined(OS_WIN) && defined(USE_ASH)
2806 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
2807 if (base::CommandLine::ForCurrentProcess()->HasSwitch(
2808 switches::kAshBrowserTests
))
2812 // Enable permision bubbles.
2813 base::CommandLine::ForCurrentProcess()->AppendSwitch(
2814 switches::kEnablePermissionsBubbles
);
2816 // Create a downloads observer.
2817 scoped_ptr
<content::DownloadTestObserver
> downloads_observer(
2818 CreateWaiter(browser(), 2));
2820 PermissionBubbleManager
* permission_bubble_manager
=
2821 PermissionBubbleManager::FromWebContents(
2822 browser()->tab_strip_model()->GetActiveWebContents());
2823 permission_bubble_manager
->DisplayPendingRequests();
2824 permission_bubble_manager
->set_auto_response_for_test(
2825 PermissionBubbleManager::ACCEPT_ALL
);
2827 ui_test_utils::NavigateToURLBlockUntilNavigationsComplete(
2828 browser(), net::URLRequestMockHTTPJob::GetMockUrl(
2829 "downloads/download-a_zip_file.html"),
2832 // Waits for the download to complete.
2833 downloads_observer
->WaitForFinished();
2834 EXPECT_EQ(2u, downloads_observer
->NumDownloadsSeenInState(
2835 DownloadItem::COMPLETE
));
2837 browser()->tab_strip_model()->GetActiveWebContents()->Close();
2841 IN_PROC_BROWSER_TEST_F(DownloadTest
, DownloadTest_Renaming
) {
2842 GURL url
= net::URLRequestMockHTTPJob::GetMockUrl("downloads/a_zip_file.zip");
2843 content::DownloadManager
* manager
= DownloadManagerForBrowser(browser());
2844 base::FilePath
origin_file(OriginFile(base::FilePath(FILE_PATH_LITERAL(
2845 "downloads/a_zip_file.zip"))));
2846 ASSERT_TRUE(base::PathExists(origin_file
));
2847 std::string origin_contents
;
2848 ASSERT_TRUE(base::ReadFileToString(origin_file
, &origin_contents
));
2850 // Download the same url several times and expect that all downloaded files
2851 // after the zero-th contain a deduplication counter.
2852 for (int index
= 0; index
< 5; ++index
) {
2853 DownloadAndWait(browser(), url
);
2854 content::DownloadItem
* item
= manager
->GetDownload(
2855 content::DownloadItem::kInvalidId
+ 1 + index
);
2857 ASSERT_EQ(DownloadItem::COMPLETE
, item
->GetState());
2858 base::FilePath
target_path(item
->GetTargetFilePath());
2859 EXPECT_EQ(std::string("a_zip_file") +
2860 (index
== 0 ? std::string(".zip") :
2861 base::StringPrintf(" (%d).zip", index
)),
2862 target_path
.BaseName().AsUTF8Unsafe());
2863 ASSERT_TRUE(base::PathExists(target_path
));
2864 ASSERT_TRUE(VerifyFile(target_path
, origin_contents
,
2865 origin_contents
.size()));
2869 // Test that the entire download pipeline handles unicode correctly.
2870 // Disabled on Windows due to flaky timeouts: crbug.com/446695
2872 #define MAYBE_DownloadTest_CrazyFilenames DISABLED_DownloadTest_CrazyFilenames
2874 #define MAYBE_DownloadTest_CrazyFilenames DownloadTest_CrazyFilenames
2876 IN_PROC_BROWSER_TEST_F(DownloadTest
, MAYBE_DownloadTest_CrazyFilenames
) {
2877 const wchar_t* kCrazyFilenames
[] = {
2879 L
"\u89c6\u9891\u76f4\u64ad\u56fe\u7247.zip", // chinese chars
2880 L
"\u0412\u043e \u0424\u043b\u043e\u0440\u0438\u0434\u0435\u043e\u0431\u044a"
2881 L
"\u044f\u0432\u043b\u0435\u043d\u0440\u0435\u0436\u0438\u043c \u0427"
2882 L
"\u041f \u0438\u0437-\u0437\u0430 \u0443\u0442\u0435\u0447\u043a\u0438 "
2883 L
"\u043d\u0435\u0444\u0442\u0438.zip", // russian
2884 L
"Desocupa\xe7\xe3o est\xe1vel.zip",
2886 L
"\u0638\u2026\u0638\u02c6\u0637\xa7\u0638\u201a\u0637\xb9 \u0638\u201e"
2887 L
"\u0638\u201e\u0637\xb2\u0638\u0679\u0637\xa7\u0637\xb1\u0637\xa9.zip",
2888 L
"\u05d4\u05e2\u05d3\u05e4\u05d5\u05ea.zip", // hebrew
2889 L
"\u092d\u093e\u0930\u0924.zip", // hindi
2890 L
"d\xe9stabilis\xe9.zip", // french
2892 L
"\u97d3-\u4e2d \uc815\uc0c1, \ucc9c\uc548\ud568 \uc758\uacac.zip",
2893 L
"jiho....tiho...miho.zip",
2894 L
"jiho!@#$tiho$%^&-()_+=miho copy.zip", // special chars
2895 L
"Wohoo-to hoo+I.zip",
2897 L
"This is a very very long english sentence with spaces and , and +.zip",
2900 std::vector
<DownloadItem
*> download_items
;
2901 base::FilePath
origin(FILE_PATH_LITERAL("origin"));
2902 ASSERT_TRUE(base::CreateDirectory(DestinationFile(browser(), origin
)));
2904 for (size_t index
= 0; index
< arraysize(kCrazyFilenames
); ++index
) {
2905 base::string16 crazy16
;
2907 const wchar_t* crazy_w
= kCrazyFilenames
[index
];
2908 ASSERT_TRUE(base::WideToUTF8(crazy_w
, wcslen(crazy_w
), &crazy8
));
2909 ASSERT_TRUE(base::WideToUTF16(crazy_w
, wcslen(crazy_w
), &crazy16
));
2910 base::FilePath
file_path(DestinationFile(browser(), origin
.Append(
2913 #elif defined(OS_POSIX)
2919 EXPECT_EQ(static_cast<int>(crazy8
.size()),
2920 base::WriteFile(file_path
, crazy8
.c_str(), crazy8
.size()));
2921 GURL
file_url(net::FilePathToFileURL(file_path
));
2923 // Download the file and check that the filename is correct.
2924 DownloadAndWait(browser(), file_url
);
2925 GetDownloads(browser(), &download_items
);
2926 ASSERT_EQ(1UL, download_items
.size());
2927 base::FilePath
downloaded(download_items
[0]->GetTargetFilePath());
2928 download_items
[0]->Remove();
2929 download_items
.clear();
2930 ASSERT_TRUE(CheckDownloadFullPaths(
2937 IN_PROC_BROWSER_TEST_F(DownloadTest
, DownloadTest_Remove
) {
2938 GURL url
= net::URLRequestMockHTTPJob::GetMockUrl("downloads/a_zip_file.zip");
2939 std::vector
<DownloadItem
*> download_items
;
2940 GetDownloads(browser(), &download_items
);
2941 ASSERT_TRUE(download_items
.empty());
2944 DownloadAndWaitWithDisposition(browser(),
2947 ui_test_utils::BROWSER_TEST_NONE
);
2948 GetDownloads(browser(), &download_items
);
2949 ASSERT_EQ(1UL, download_items
.size());
2950 base::FilePath
downloaded(download_items
[0]->GetTargetFilePath());
2952 // Remove the DownloadItem but not the file, then check that the file still
2954 download_items
[0]->Remove();
2955 download_items
.clear();
2956 GetDownloads(browser(), &download_items
);
2957 ASSERT_EQ(0UL, download_items
.size());
2958 ASSERT_TRUE(CheckDownloadFullPaths(
2959 browser(), downloaded
, OriginFile(base::FilePath(
2960 FILE_PATH_LITERAL("downloads/a_zip_file.zip")))));
2963 IN_PROC_BROWSER_TEST_F(DownloadTest
, DownloadTest_PauseResumeCancel
) {
2964 DownloadItem
* download_item
= CreateSlowTestDownload();
2965 ASSERT_TRUE(download_item
);
2966 ASSERT_FALSE(download_item
->GetTargetFilePath().empty());
2967 EXPECT_FALSE(download_item
->IsPaused());
2968 EXPECT_NE(DownloadItem::CANCELLED
, download_item
->GetState());
2969 download_item
->Pause();
2970 EXPECT_TRUE(download_item
->IsPaused());
2971 download_item
->Resume();
2972 EXPECT_FALSE(download_item
->IsPaused());
2973 EXPECT_NE(DownloadItem::CANCELLED
, download_item
->GetState());
2974 download_item
->Cancel(true);
2975 EXPECT_EQ(DownloadItem::CANCELLED
, download_item
->GetState());
2978 // The Mac downloaded files quarantine feature is implemented by the
2979 // Contents/Info.plist file in cocoa apps. browser_tests cannot test
2980 // quarantining files on Mac because it is not a cocoa app.
2981 // TODO(benjhayden) test the equivalents on other platforms.
2983 #if defined(OS_LINUX) && !defined(OS_CHROMEOS) && defined(ARCH_CPU_ARM_FAMILY)
2984 // Timing out on ARM linux: http://crbug.com/238459
2985 #define MAYBE_DownloadTest_PercentComplete DISABLED_DownloadTest_PercentComplete
2986 #elif defined(OS_MACOSX)
2987 // Disable on mac: http://crbug.com/238831
2988 #define MAYBE_DownloadTest_PercentComplete DISABLED_DownloadTest_PercentComplete
2990 #define MAYBE_DownloadTest_PercentComplete DownloadTest_PercentComplete
2992 IN_PROC_BROWSER_TEST_F(DownloadTest
, MAYBE_DownloadTest_PercentComplete
) {
2993 // Write a huge file.
2994 base::FilePath
file_path(DestinationFile(
2995 browser(), base::FilePath(FILE_PATH_LITERAL("DownloadTest_BigZip.zip"))));
2996 base::File
file(file_path
, base::File::FLAG_CREATE
| base::File::FLAG_WRITE
);
2997 ASSERT_TRUE(file
.IsValid());
2998 int64 size
= 1 << 25;
2999 EXPECT_EQ(1, file
.Write(size
, "a", 1));
3002 #if defined(OS_POSIX)
3003 // Make it readable by chronos on chromeos
3004 base::SetPosixFilePermissions(file_path
, 0755);
3007 // Ensure that we have enough disk space.
3008 int64 free_space
= base::SysInfo::AmountOfFreeDiskSpace(
3009 GetDownloadDirectory(browser()));
3010 ASSERT_LE(size
, free_space
) << "Not enough disk space to download. Got "
3012 GURL
file_url(net::FilePathToFileURL(file_path
));
3013 scoped_ptr
<content::DownloadTestObserver
> progress_waiter(
3014 CreateInProgressWaiter(browser(), 1));
3016 // Start downloading a file, wait for it to be created.
3017 ui_test_utils::NavigateToURLWithDisposition(
3018 browser(), file_url
, CURRENT_TAB
, ui_test_utils::BROWSER_TEST_NONE
);
3019 progress_waiter
->WaitForFinished();
3020 EXPECT_EQ(1u, progress_waiter
->NumDownloadsSeenInState(
3021 DownloadItem::IN_PROGRESS
));
3022 std::vector
<DownloadItem
*> download_items
;
3023 GetDownloads(browser(), &download_items
);
3024 ASSERT_EQ(1UL, download_items
.size());
3026 // Wait for the download to complete, checking along the way that the
3027 // PercentComplete() never regresses.
3028 PercentWaiter
waiter(download_items
[0]);
3029 EXPECT_TRUE(waiter
.WaitForFinished());
3030 EXPECT_EQ(DownloadItem::COMPLETE
, download_items
[0]->GetState());
3031 ASSERT_EQ(100, download_items
[0]->PercentComplete());
3033 // Check that the file downloaded correctly.
3034 ASSERT_TRUE(base::PathExists(download_items
[0]->GetTargetFilePath()));
3035 int64 downloaded_size
= 0;
3036 ASSERT_TRUE(base::GetFileSize(
3037 download_items
[0]->GetTargetFilePath(), &downloaded_size
));
3038 ASSERT_EQ(size
+ 1, downloaded_size
);
3039 ASSERT_TRUE(base::DieFileDie(file_path
, false));
3040 ASSERT_TRUE(base::DieFileDie(download_items
[0]->GetTargetFilePath(), false));
3043 // A download that is interrupted due to a file error should be able to be
3045 IN_PROC_BROWSER_TEST_F(DownloadTest
, Resumption_NoPrompt
) {
3046 base::CommandLine::ForCurrentProcess()->AppendSwitch(
3047 switches::kEnableDownloadResumption
);
3048 scoped_refptr
<content::TestFileErrorInjector
> error_injector(
3049 content::TestFileErrorInjector::Create(
3050 DownloadManagerForBrowser(browser())));
3051 scoped_ptr
<content::DownloadTestObserver
> completion_observer(
3052 CreateWaiter(browser(), 1));
3053 EnableFileChooser(true);
3055 DownloadItem
* download
= StartMockDownloadAndInjectError(
3056 error_injector
.get(), content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED
);
3057 ASSERT_TRUE(download
);
3060 completion_observer
->WaitForFinished();
3063 1u, completion_observer
->NumDownloadsSeenInState(DownloadItem::COMPLETE
));
3064 EXPECT_FALSE(DidShowFileChooser());
3067 // A download that's interrupted due to a reason that indicates that the target
3068 // path is invalid or unusable should cause a prompt to be displayed on
3070 IN_PROC_BROWSER_TEST_F(DownloadTest
, Resumption_WithPrompt
) {
3071 base::CommandLine::ForCurrentProcess()->AppendSwitch(
3072 switches::kEnableDownloadResumption
);
3073 scoped_refptr
<content::TestFileErrorInjector
> error_injector(
3074 content::TestFileErrorInjector::Create(
3075 DownloadManagerForBrowser(browser())));
3076 scoped_ptr
<content::DownloadTestObserver
> completion_observer(
3077 CreateWaiter(browser(), 1));
3078 EnableFileChooser(true);
3080 DownloadItem
* download
= StartMockDownloadAndInjectError(
3081 error_injector
.get(), content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE
);
3082 ASSERT_TRUE(download
);
3085 completion_observer
->WaitForFinished();
3088 1u, completion_observer
->NumDownloadsSeenInState(DownloadItem::COMPLETE
));
3089 EXPECT_TRUE(DidShowFileChooser());
3092 // The user shouldn't be prompted on a resumed download unless a prompt is
3093 // necessary due to the interrupt reason.
3094 IN_PROC_BROWSER_TEST_F(DownloadTest
, Resumption_WithPromptAlways
) {
3095 base::CommandLine::ForCurrentProcess()->AppendSwitch(
3096 switches::kEnableDownloadResumption
);
3097 browser()->profile()->GetPrefs()->SetBoolean(
3098 prefs::kPromptForDownload
, true);
3099 scoped_refptr
<content::TestFileErrorInjector
> error_injector(
3100 content::TestFileErrorInjector::Create(
3101 DownloadManagerForBrowser(browser())));
3102 scoped_ptr
<content::DownloadTestObserver
> completion_observer(
3103 CreateWaiter(browser(), 1));
3104 EnableFileChooser(true);
3106 DownloadItem
* download
= StartMockDownloadAndInjectError(
3107 error_injector
.get(), content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED
);
3108 ASSERT_TRUE(download
);
3110 // Prompts the user initially because of the kPromptForDownload preference.
3111 EXPECT_TRUE(DidShowFileChooser());
3114 completion_observer
->WaitForFinished();
3117 1u, completion_observer
->NumDownloadsSeenInState(DownloadItem::COMPLETE
));
3118 // Shouldn't prompt for resumption.
3119 EXPECT_FALSE(DidShowFileChooser());
3122 // A download that is interrupted due to a transient error should be resumed
3124 IN_PROC_BROWSER_TEST_F(DownloadTest
, Resumption_Automatic
) {
3125 base::CommandLine::ForCurrentProcess()->AppendSwitch(
3126 switches::kEnableDownloadResumption
);
3127 scoped_refptr
<content::TestFileErrorInjector
> error_injector(
3128 content::TestFileErrorInjector::Create(
3129 DownloadManagerForBrowser(browser())));
3131 DownloadItem
* download
= StartMockDownloadAndInjectError(
3132 error_injector
.get(),
3133 content::DOWNLOAD_INTERRUPT_REASON_FILE_TRANSIENT_ERROR
);
3134 ASSERT_TRUE(download
);
3136 // The number of times this the download is resumed automatically is defined
3137 // in DownloadItemImpl::kMaxAutoResumeAttempts. The number of DownloadFiles
3138 // created should be that number + 1 (for the original download request). We
3139 // only care that it is greater than 1.
3140 EXPECT_GT(1u, error_injector
->TotalFileCount());
3143 // An interrupting download should be resumable multiple times.
3144 IN_PROC_BROWSER_TEST_F(DownloadTest
, Resumption_MultipleAttempts
) {
3145 base::CommandLine::ForCurrentProcess()->AppendSwitch(
3146 switches::kEnableDownloadResumption
);
3147 scoped_refptr
<content::TestFileErrorInjector
> error_injector(
3148 content::TestFileErrorInjector::Create(
3149 DownloadManagerForBrowser(browser())));
3150 scoped_ptr
<DownloadTestObserverNotInProgress
> completion_observer(
3151 new DownloadTestObserverNotInProgress(
3152 DownloadManagerForBrowser(browser()), 1));
3153 // Wait for two transitions to a resumable state
3154 scoped_ptr
<content::DownloadTestObserver
> resumable_observer(
3155 new DownloadTestObserverResumable(
3156 DownloadManagerForBrowser(browser()), 2));
3158 EnableFileChooser(true);
3159 DownloadItem
* download
= StartMockDownloadAndInjectError(
3160 error_injector
.get(), content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED
);
3161 ASSERT_TRUE(download
);
3163 content::TestFileErrorInjector::FileErrorInfo error_info
;
3164 error_info
.url
= download
->GetOriginalUrl().spec();
3165 error_info
.code
= content::TestFileErrorInjector::FILE_OPERATION_WRITE
;
3166 error_info
.operation_instance
= 0;
3167 error_info
.error
= content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED
;
3168 error_injector
->AddError(error_info
);
3169 error_injector
->InjectErrors();
3171 // Resuming should cause the download to be interrupted again due to the
3172 // errors we are injecting.
3174 resumable_observer
->WaitForFinished();
3175 ASSERT_EQ(DownloadItem::INTERRUPTED
, download
->GetState());
3176 ASSERT_EQ(content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED
,
3177 download
->GetLastReason());
3179 error_injector
->ClearErrors();
3180 error_injector
->InjectErrors();
3182 // No errors this time. The download should complete successfully.
3183 EXPECT_FALSE(completion_observer
->IsFinished());
3184 completion_observer
->StartObserving();
3186 completion_observer
->WaitForFinished();
3187 EXPECT_EQ(DownloadItem::COMPLETE
, download
->GetState());
3189 EXPECT_FALSE(DidShowFileChooser());
3192 // The file empty.bin is served with a MIME type of application/octet-stream.
3193 // The content body is empty. Make sure this case is handled properly and we
3194 // don't regress on http://crbug.com/320394.
3195 IN_PROC_BROWSER_TEST_F(DownloadTest
, DownloadTest_GZipWithNoContent
) {
3196 GURL url
= net::URLRequestMockHTTPJob::GetMockUrl("downloads/empty.bin");
3197 // Downloading the same URL twice causes the second request to be served from
3198 // cached (with a high probability). This test verifies that that doesn't
3199 // happen regardless of whether the request is served via the cache or from
3201 DownloadAndWait(browser(), url
);
3202 DownloadAndWait(browser(), url
);
3205 #if defined(FULL_SAFE_BROWSING)
3207 // The following two tests are only meaningful on OS_WIN since that's the only
3208 // platform where client download checks are currently performed.
3209 // TODO(asanka): Relax this restriction as other platforms are added.
3213 // This is a custom DownloadTestObserver for
3214 // DangerousFileWithSBDisabledBeforeCompletion test that disables the
3215 // SafeBrowsing service when a single download is IN_PROGRESS and has a target
3216 // path assigned. DownloadItemImpl is expected to call MaybeCompleteDownload
3217 // soon afterwards and we want to disable the service before then.
3218 class DisableSafeBrowsingOnInProgressDownload
3219 : public content::DownloadTestObserver
{
3221 explicit DisableSafeBrowsingOnInProgressDownload(Browser
* browser
)
3222 : DownloadTestObserver(DownloadManagerForBrowser(browser
),
3224 ON_DANGEROUS_DOWNLOAD_QUIT
),
3226 final_state_seen_(false) {
3229 ~DisableSafeBrowsingOnInProgressDownload() override
{}
3231 bool IsDownloadInFinalState(DownloadItem
* download
) override
{
3232 if (download
->GetState() != DownloadItem::IN_PROGRESS
||
3233 download
->GetTargetFilePath().empty())
3236 if (final_state_seen_
)
3239 final_state_seen_
= true;
3240 browser_
->profile()->GetPrefs()->SetBoolean(prefs::kSafeBrowsingEnabled
,
3242 EXPECT_EQ(content::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT
,
3243 download
->GetDangerType());
3244 EXPECT_FALSE(download
->IsDangerous());
3245 EXPECT_TRUE(DownloadItemModel(download
).IsDangerousFileBasedOnType());
3251 bool final_state_seen_
;
3256 IN_PROC_BROWSER_TEST_F(DownloadTest
,
3257 DangerousFileWithSBDisabledBeforeCompletion
) {
3258 browser()->profile()->GetPrefs()->SetBoolean(prefs::kSafeBrowsingEnabled
,
3260 GURL download_url
= net::URLRequestMockHTTPJob::GetMockUrl(
3261 "downloads/dangerous/dangerous.exe");
3262 scoped_ptr
<content::DownloadTestObserver
> dangerous_observer(
3263 DangerousDownloadWaiter(
3266 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_QUIT
));
3267 scoped_ptr
<content::DownloadTestObserver
> in_progress_observer(
3268 new DisableSafeBrowsingOnInProgressDownload(browser()));
3269 ui_test_utils::NavigateToURLWithDisposition(browser(),
3272 ui_test_utils::BROWSER_TEST_NONE
);
3273 in_progress_observer
->WaitForFinished();
3275 // SafeBrowsing should have been disabled by our observer.
3276 ASSERT_FALSE(browser()->profile()->GetPrefs()->GetBoolean(
3277 prefs::kSafeBrowsingEnabled
));
3279 std::vector
<DownloadItem
*> downloads
;
3280 DownloadManagerForBrowser(browser())->GetAllDownloads(&downloads
);
3281 ASSERT_EQ(1u, downloads
.size());
3282 DownloadItem
* download
= downloads
[0];
3284 dangerous_observer
->WaitForFinished();
3286 EXPECT_TRUE(download
->IsDangerous());
3287 EXPECT_EQ(content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE
,
3288 download
->GetDangerType());
3289 download
->Cancel(true);
3292 IN_PROC_BROWSER_TEST_F(DownloadTest
, DangerousFileWithSBDisabledBeforeStart
) {
3293 // Disable SafeBrowsing
3294 browser()->profile()->GetPrefs()->SetBoolean(prefs::kSafeBrowsingEnabled
,
3297 GURL download_url
= net::URLRequestMockHTTPJob::GetMockUrl(
3298 "downloads/dangerous/dangerous.exe");
3299 scoped_ptr
<content::DownloadTestObserver
> dangerous_observer(
3300 DangerousDownloadWaiter(
3303 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_QUIT
));
3304 ui_test_utils::NavigateToURLWithDisposition(browser(),
3307 ui_test_utils::BROWSER_TEST_NONE
);
3308 dangerous_observer
->WaitForFinished();
3310 std::vector
<DownloadItem
*> downloads
;
3311 DownloadManagerForBrowser(browser())->GetAllDownloads(&downloads
);
3312 ASSERT_EQ(1u, downloads
.size());
3314 DownloadItem
* download
= downloads
[0];
3315 EXPECT_TRUE(download
->IsDangerous());
3316 EXPECT_EQ(content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE
,
3317 download
->GetDangerType());
3319 download
->Cancel(true);
3322 IN_PROC_BROWSER_TEST_F(DownloadTest
, SafeSupportedFile
) {
3324 net::URLRequestMockHTTPJob::GetMockUrl("downloads/a_zip_file.zip");
3325 DownloadAndWait(browser(), download_url
);
3327 std::vector
<DownloadItem
*> downloads
;
3328 DownloadManagerForBrowser(browser())->GetAllDownloads(&downloads
);
3329 ASSERT_EQ(1u, downloads
.size());
3331 DownloadItem
* download
= downloads
[0];
3332 EXPECT_FALSE(download
->IsDangerous());
3333 EXPECT_EQ(content::DOWNLOAD_DANGER_TYPE_MAYBE_DANGEROUS_CONTENT
,
3334 download
->GetDangerType());
3336 download
->Cancel(true);
3341 IN_PROC_BROWSER_TEST_F(DownloadTest
, FeedbackService
) {
3342 // Make a dangerous file.
3343 base::FilePath
file(FILE_PATH_LITERAL("downloads/dangerous/dangerous.swf"));
3344 GURL
download_url(net::URLRequestMockHTTPJob::GetMockUrl(file
));
3345 scoped_ptr
<content::DownloadTestObserverInterrupted
> observer(
3346 new content::DownloadTestObserverInterrupted(
3347 DownloadManagerForBrowser(browser()), 1,
3348 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_QUIT
));
3349 ui_test_utils::NavigateToURLWithDisposition(
3353 ui_test_utils::BROWSER_TEST_NONE
);
3354 observer
->WaitForFinished();
3356 // Get the download from the DownloadManager.
3357 std::vector
<DownloadItem
*> downloads
;
3358 DownloadManagerForBrowser(browser())->GetAllDownloads(&downloads
);
3359 ASSERT_EQ(1u, downloads
.size());
3360 EXPECT_TRUE(downloads
[0]->IsDangerous());
3362 // Save fake pings for the download.
3363 safe_browsing::ClientDownloadReport fake_metadata
;
3364 fake_metadata
.mutable_download_request()->set_url("http://test");
3365 fake_metadata
.mutable_download_request()->set_length(1);
3366 fake_metadata
.mutable_download_request()->mutable_digests()->set_sha1("hi");
3367 fake_metadata
.mutable_download_response()->set_verdict(
3368 safe_browsing::ClientDownloadResponse::UNCOMMON
);
3369 std::string
ping_request(
3370 fake_metadata
.download_request().SerializeAsString());
3371 std::string
ping_response(
3372 fake_metadata
.download_response().SerializeAsString());
3373 SafeBrowsingService
* sb_service
= g_browser_process
->safe_browsing_service();
3374 safe_browsing::DownloadProtectionService
* download_protection_service
=
3375 sb_service
->download_protection_service();
3376 download_protection_service
->feedback_service()->MaybeStorePingsForDownload(
3377 safe_browsing::DownloadProtectionService::UNCOMMON
,
3381 ASSERT_TRUE(safe_browsing::DownloadFeedbackService::IsEnabledForDownload(
3384 // Begin feedback and check that the file is "stolen".
3385 download_protection_service
->feedback_service()->BeginFeedbackForDownload(
3387 std::vector
<DownloadItem
*> updated_downloads
;
3388 GetDownloads(browser(), &updated_downloads
);
3389 ASSERT_TRUE(updated_downloads
.empty());
3393 class DownloadTestWithShelf
: public DownloadTest
{
3394 void SetUpCommandLine(base::CommandLine
* command_line
) override
{
3395 command_line
->AppendSwitchASCII(switches::kEnableDownloadNotification
,
3397 DownloadTest::SetUpCommandLine(command_line
);
3401 // Test that the download shelf is shown by starting a download.
3402 IN_PROC_BROWSER_TEST_F(DownloadTestWithShelf
, DownloadAndWait
) {
3403 GURL url
= net::URLRequestMockHTTPJob::GetMockUrl("downloads/a_zip_file.zip");
3404 DownloadAndWait(browser(), url
);
3406 // The download shelf should be visible.
3407 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
3410 // Test that the download shelf is per-window by starting a download in one
3411 // tab, opening a second tab, closing the shelf, going back to the first tab,
3412 // and checking that the shelf is closed.
3413 IN_PROC_BROWSER_TEST_F(DownloadTestWithShelf
, PerWindowShelf
) {
3414 base::FilePath
file(FILE_PATH_LITERAL("download-test3.gif"));
3415 GURL
url(URLRequestMockHTTPJob::GetMockUrl(file
));
3416 base::FilePath
download_file(
3417 FILE_PATH_LITERAL("download-test3-attachment.gif"));
3419 // Download a file and wait.
3420 DownloadAndWait(browser(), url
);
3422 CheckDownload(browser(), download_file
, file
);
3425 EXPECT_EQ(1, browser()->tab_strip_model()->count());
3426 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
3428 // Open a second tab and wait.
3429 EXPECT_NE(static_cast<WebContents
*>(NULL
),
3430 chrome::AddSelectedTabWithURL(browser(), GURL(url::kAboutBlankURL
),
3431 ui::PAGE_TRANSITION_TYPED
));
3432 EXPECT_EQ(2, browser()->tab_strip_model()->count());
3433 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
3435 // Hide the download shelf.
3436 browser()->window()->GetDownloadShelf()->Close(DownloadShelf::AUTOMATIC
);
3437 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
3439 // Go to the first tab.
3440 browser()->tab_strip_model()->ActivateTabAt(0, true);
3441 EXPECT_EQ(2, browser()->tab_strip_model()->count());
3443 // The download shelf should not be visible.
3444 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
3447 // Check whether the downloads shelf is closed when the downloads tab is
3449 IN_PROC_BROWSER_TEST_F(DownloadTestWithShelf
, CloseShelfOnDownloadsTab
) {
3450 base::FilePath
file(FILE_PATH_LITERAL("download-test1.lib"));
3451 GURL
url(URLRequestMockHTTPJob::GetMockUrl(file
));
3453 // Download the file and wait. We do not expect the Select File dialog.
3454 DownloadAndWait(browser(), url
);
3457 EXPECT_EQ(1, browser()->tab_strip_model()->count());
3458 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
3460 // Open the downloads tab.
3461 chrome::ShowDownloads(browser());
3462 // The shelf should now be closed.
3463 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
3466 // Test that when downloading an item in Incognito mode, check that the
3467 // download shelf is not visible after closing the Incognito window.
3468 IN_PROC_BROWSER_TEST_F(DownloadTestWithShelf
, IncognitoDownload
) {
3469 Browser
* incognito
= CreateIncognitoBrowser();
3470 ASSERT_TRUE(incognito
);
3472 // Download a file in the Incognito window and wait.
3473 CreateAndSetDownloadsDirectory(incognito
);
3474 base::FilePath
file(FILE_PATH_LITERAL("download-test1.lib"));
3475 GURL
url(URLRequestMockHTTPJob::GetMockUrl(file
));
3476 // Since |incognito| is a separate browser, we have to set it up explicitly.
3477 incognito
->profile()->GetPrefs()->SetBoolean(prefs::kPromptForDownload
,
3479 DownloadAndWait(incognito
, url
);
3481 // Verify that the download shelf is showing for the Incognito window.
3482 EXPECT_TRUE(incognito
->window()->IsDownloadShelfVisible());
3484 // Verify that the regular window does not have a download shelf.
3485 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
3488 // Download a file in a new window.
3489 // Verify that we have 2 windows, and the download shelf is not visible in the
3490 // first window, but is visible in the second window.
3491 // Close the new window.
3492 // Verify that we have 1 window, and the download shelf is not visible.
3494 // Regression test for http://crbug.com/44454
3495 IN_PROC_BROWSER_TEST_F(DownloadTestWithShelf
, NewWindow
) {
3496 base::FilePath
file(FILE_PATH_LITERAL("download-test1.lib"));
3497 GURL
url(URLRequestMockHTTPJob::GetMockUrl(file
));
3498 #if !defined(OS_MACOSX)
3500 Browser
* first_browser
= browser();
3503 // Download a file in a new window and wait.
3504 DownloadAndWaitWithDisposition(browser(), url
, NEW_WINDOW
,
3505 ui_test_utils::BROWSER_TEST_NONE
);
3507 // When the download finishes, the download shelf SHOULD NOT be visible in
3508 // the first window.
3509 ExpectWindowCountAfterDownload(2);
3510 EXPECT_EQ(1, browser()->tab_strip_model()->count());
3511 // Download shelf should close. Download panel stays open on ChromeOS.
3512 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
3514 // The download shelf SHOULD be visible in the second window.
3515 std::set
<Browser
*> original_browsers
;
3516 original_browsers
.insert(browser());
3517 Browser
* download_browser
=
3518 ui_test_utils::GetBrowserNotInSet(original_browsers
);
3519 ASSERT_TRUE(download_browser
!= NULL
);
3520 EXPECT_NE(download_browser
, browser());
3521 EXPECT_EQ(1, download_browser
->tab_strip_model()->count());
3522 EXPECT_TRUE(download_browser
->window()->IsDownloadShelfVisible());
3524 #if !defined(OS_MACOSX)
3525 // On Mac OS X, the UI window close is delayed until the outermost
3526 // message loop runs. So it isn't possible to get a BROWSER_CLOSED
3527 // notification inside of a test.
3528 content::WindowedNotificationObserver
signal(
3529 chrome::NOTIFICATION_BROWSER_CLOSED
,
3530 content::Source
<Browser
>(download_browser
));
3533 // Close the new window.
3534 chrome::CloseWindow(download_browser
);
3536 #if !defined(OS_MACOSX)
3538 EXPECT_EQ(first_browser
, browser());
3539 ExpectWindowCountAfterDownload(1);
3542 EXPECT_EQ(1, browser()->tab_strip_model()->count());
3543 // Download shelf should close. Download panel stays open on ChromeOS.
3544 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
3546 CheckDownload(browser(), file
, file
);
3549 IN_PROC_BROWSER_TEST_F(DownloadTestWithShelf
, PRE_DownloadTest_History
) {
3550 // Download a file and wait for it to be stored.
3551 base::FilePath
file(FILE_PATH_LITERAL("download-test1.lib"));
3552 GURL
download_url(URLRequestMockHTTPJob::GetMockUrl(file
));
3553 HistoryObserver
observer(browser()->profile());
3554 DownloadAndWait(browser(), download_url
);
3555 observer
.WaitForStored();
3556 HistoryServiceFactory::GetForProfile(browser()->profile(),
3557 ServiceAccessType::IMPLICIT_ACCESS
)
3558 ->FlushForTest(base::Bind(
3559 &base::MessageLoop::Quit
,
3560 base::Unretained(base::MessageLoop::current()->current())));
3561 content::RunMessageLoop();
3564 #if defined(OS_CHROMEOS)
3565 // Times out on ChromeOS: http://crbug.com/217810
3566 #define MAYBE_DownloadTest_History DISABLED_DownloadTest_History
3568 #define MAYBE_DownloadTest_History DownloadTest_History
3570 IN_PROC_BROWSER_TEST_F(DownloadTestWithShelf
, MAYBE_DownloadTest_History
) {
3571 // This starts up right after PRE_DownloadTest_History and shares the same
3572 // profile directory.
3573 base::FilePath
file(FILE_PATH_LITERAL("download-test1.lib"));
3574 GURL
download_url(URLRequestMockHTTPJob::GetMockUrl(file
));
3575 std::vector
<DownloadItem
*> downloads
;
3576 content::DownloadManager
* manager
= DownloadManagerForBrowser(browser());
3578 // Wait for the history to be loaded with a single DownloadItem. Check that
3579 // it's the file that was downloaded in PRE_DownloadTest_History.
3580 CreatedObserver
created_observer(manager
);
3581 created_observer
.Wait();
3582 manager
->GetAllDownloads(&downloads
);
3583 ASSERT_EQ(1UL, downloads
.size());
3584 DownloadItem
* item
= downloads
[0];
3585 EXPECT_EQ(file
.value(), item
->GetFullPath().BaseName().value());
3586 EXPECT_EQ(file
.value(), item
->GetTargetFilePath().BaseName().value());
3587 EXPECT_EQ(download_url
, item
->GetURL());
3588 // The following are set by download-test1.lib.mock-http-headers.
3589 std::string etag
= item
->GetETag();
3590 base::TrimWhitespaceASCII(etag
, base::TRIM_ALL
, &etag
);
3591 EXPECT_EQ("abracadabra", etag
);
3593 std::string last_modified
= item
->GetLastModifiedTime();
3594 base::TrimWhitespaceASCII(last_modified
, base::TRIM_ALL
, &last_modified
);
3595 EXPECT_EQ("Mon, 13 Nov 2006 20:31:09 GMT", last_modified
);
3597 // Downloads that were restored from history shouldn't cause the download
3598 // shelf to be displayed.
3599 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
3602 IN_PROC_BROWSER_TEST_F(DownloadTestWithShelf
, HiddenDownload
) {
3603 base::FilePath
file(FILE_PATH_LITERAL("download-test1.lib"));
3604 GURL
url(URLRequestMockHTTPJob::GetMockUrl(file
));
3606 DownloadManager
* download_manager
= DownloadManagerForBrowser(browser());
3607 scoped_ptr
<content::DownloadTestObserver
> observer(
3608 new content::DownloadTestObserverTerminal(
3609 download_manager
, 1,
3610 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL
));
3612 // Download and set IsHiddenDownload to true.
3613 WebContents
* web_contents
=
3614 browser()->tab_strip_model()->GetActiveWebContents();
3615 scoped_ptr
<DownloadUrlParameters
> params(
3616 DownloadUrlParameters::FromWebContents(web_contents
, url
));
3617 params
->set_callback(base::Bind(&SetHiddenDownloadCallback
));
3618 download_manager
->DownloadUrl(params
.Pass());
3619 observer
->WaitForFinished();
3621 // Verify that download shelf is not shown.
3622 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
3625 // Test to make sure auto-open works.
3626 IN_PROC_BROWSER_TEST_F(DownloadTestWithShelf
, AutoOpen
) {
3627 base::FilePath
file(FILE_PATH_LITERAL("download-autoopen.txt"));
3628 GURL
url(URLRequestMockHTTPJob::GetMockUrl(file
));
3631 GetDownloadPrefs(browser())->EnableAutoOpenBasedOnExtension(file
));
3633 DownloadAndWait(browser(), url
);
3635 // Download shelf should close. Download panel stays open on ChromeOS.
3636 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
3639 // Download an extension. Expect a dangerous download warning.
3640 // Deny the download.
3641 IN_PROC_BROWSER_TEST_F(DownloadTestWithShelf
, CrxDenyInstall
) {
3642 FeatureSwitch::ScopedOverride
enable_easy_off_store_install(
3643 FeatureSwitch::easy_off_store_install(), true);
3645 GURL
extension_url(URLRequestMockHTTPJob::GetMockUrl(kGoodCrxPath
));
3647 scoped_ptr
<content::DownloadTestObserver
> observer(DangerousDownloadWaiter(
3648 browser(), 1, content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_DENY
));
3649 ui_test_utils::NavigateToURL(browser(), extension_url
);
3651 observer
->WaitForFinished();
3653 // Download shelf should close.
3654 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());