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. 4 5 #include <sstream> 6 7 #include "base/bind.h" 8 #include "base/bind_helpers.h" 9 #include "base/command_line.h" 10 #include "base/file_util.h" 11 #include "base/files/file_path.h" 12 #include "base/files/scoped_temp_dir.h" 13 #include "base/memory/ref_counted.h" 14 #include "base/path_service.h" 15 #include "base/prefs/pref_service.h" 16 #include "base/stl_util.h" 17 #include "base/strings/string_split.h" 18 #include "base/strings/string_util.h" 19 #include "base/strings/stringprintf.h" 20 #include "base/strings/utf_string_conversions.h" 21 #include "base/sys_info.h" 22 #include "base/test/test_file_util.h" 23 #include "chrome/app/chrome_command_ids.h" 24 #include "chrome/browser/browser_process.h" 25 #include "chrome/browser/chrome_notification_types.h" 26 #include "chrome/browser/common/cancelable_request.h" 27 #include "chrome/browser/download/chrome_download_manager_delegate.h" 28 #include "chrome/browser/download/download_crx_util.h" 29 #include "chrome/browser/download/download_history.h" 30 #include "chrome/browser/download/download_item_model.h" 31 #include "chrome/browser/download/download_prefs.h" 32 #include "chrome/browser/download/download_request_limiter.h" 33 #include "chrome/browser/download/download_service.h" 34 #include "chrome/browser/download/download_service_factory.h" 35 #include "chrome/browser/download/download_shelf.h" 36 #include "chrome/browser/download/download_target_determiner.h" 37 #include "chrome/browser/download/download_test_file_activity_observer.h" 38 #include "chrome/browser/extensions/extension_install_prompt.h" 39 #include "chrome/browser/extensions/extension_service.h" 40 #include "chrome/browser/extensions/extension_system.h" 41 #include "chrome/browser/history/download_row.h" 42 #include "chrome/browser/history/history_service.h" 43 #include "chrome/browser/history/history_service_factory.h" 44 #include "chrome/browser/infobars/confirm_infobar_delegate.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/tab_contents/render_view_context_menu.h" 49 #include "chrome/browser/ui/browser.h" 50 #include "chrome/browser/ui/browser_commands.h" 51 #include "chrome/browser/ui/browser_finder.h" 52 #include "chrome/browser/ui/browser_list.h" 53 #include "chrome/browser/ui/browser_tabstrip.h" 54 #include "chrome/browser/ui/browser_window.h" 55 #include "chrome/browser/ui/chrome_pages.h" 56 #include "chrome/browser/ui/host_desktop.h" 57 #include "chrome/browser/ui/tabs/tab_strip_model.h" 58 #include "chrome/common/chrome_paths.h" 59 #include "chrome/common/extensions/feature_switch.h" 60 #include "chrome/common/pref_names.h" 61 #include "chrome/common/url_constants.h" 62 #include "chrome/test/base/in_process_browser_test.h" 63 #include "chrome/test/base/test_switches.h" 64 #include "chrome/test/base/ui_test_utils.h" 65 #include "content/public/browser/download_item.h" 66 #include "content/public/browser/download_manager.h" 67 #include "content/public/browser/download_save_info.h" 68 #include "content/public/browser/download_url_parameters.h" 69 #include "content/public/browser/notification_source.h" 70 #include "content/public/browser/render_view_host.h" 71 #include "content/public/browser/resource_context.h" 72 #include "content/public/browser/web_contents.h" 73 #include "content/public/common/content_switches.h" 74 #include "content/public/common/context_menu_params.h" 75 #include "content/public/common/page_transition_types.h" 76 #include "content/public/test/browser_test_utils.h" 77 #include "content/public/test/download_test_observer.h" 78 #include "content/public/test/test_file_error_injector.h" 79 #include "content/public/test/test_navigation_observer.h" 80 #include "content/test/net/url_request_mock_http_job.h" 81 #include "content/test/net/url_request_slow_download_job.h" 82 #include "grit/generated_resources.h" 83 #include "net/base/net_util.h" 84 #include "net/test/spawned_test_server/spawned_test_server.h" 85 #include "testing/gtest/include/gtest/gtest.h" 86 #include "ui/base/l10n/l10n_util.h" 87 88 using content::BrowserContext; 89 using content::BrowserThread; 90 using content::DownloadItem; 91 using content::DownloadManager; 92 using content::DownloadUrlParameters; 93 using content::URLRequestMockHTTPJob; 94 using content::URLRequestSlowDownloadJob; 95 using content::WebContents; 96 using extensions::Extension; 97 using extensions::FeatureSwitch; 98 99 namespace { 100 101 class CreatedObserver : public content::DownloadManager::Observer { 102 public: 103 explicit CreatedObserver(content::DownloadManager* manager) 104 : manager_(manager), 105 waiting_(false) { 106 manager->AddObserver(this); 107 } 108 virtual ~CreatedObserver() { 109 if (manager_) 110 manager_->RemoveObserver(this); 111 } 112 113 void Wait() { 114 std::vector<DownloadItem*> downloads; 115 manager_->GetAllDownloads(&downloads); 116 if (!downloads.empty()) 117 return; 118 waiting_ = true; 119 content::RunMessageLoop(); 120 waiting_ = false; 121 } 122 123 private: 124 virtual void OnDownloadCreated(content::DownloadManager* manager, 125 content::DownloadItem* item) OVERRIDE { 126 DCHECK_EQ(manager_, manager); 127 if (waiting_) 128 base::MessageLoopForUI::current()->Quit(); 129 } 130 131 content::DownloadManager* manager_; 132 bool waiting_; 133 134 DISALLOW_COPY_AND_ASSIGN(CreatedObserver); 135 }; 136 137 class PercentWaiter : public content::DownloadItem::Observer { 138 public: 139 explicit PercentWaiter(DownloadItem* item) 140 : item_(item), 141 waiting_(false), 142 error_(false), 143 prev_percent_(0) { 144 item_->AddObserver(this); 145 } 146 virtual ~PercentWaiter() { 147 if (item_) 148 item_->RemoveObserver(this); 149 } 150 151 bool WaitForFinished() { 152 if (item_->GetState() == DownloadItem::COMPLETE) { 153 return item_->PercentComplete() == 100; 154 } 155 waiting_ = true; 156 content::RunMessageLoop(); 157 waiting_ = false; 158 return !error_; 159 } 160 161 private: 162 virtual void OnDownloadUpdated(content::DownloadItem* item) OVERRIDE { 163 DCHECK_EQ(item_, item); 164 if (!error_ && 165 ((prev_percent_ > item_->PercentComplete()) || 166 (item_->GetState() == DownloadItem::COMPLETE && 167 (item_->PercentComplete() != 100)))) { 168 error_ = true; 169 if (waiting_) 170 base::MessageLoopForUI::current()->Quit(); 171 } 172 if (item_->GetState() == DownloadItem::COMPLETE && waiting_) 173 base::MessageLoopForUI::current()->Quit(); 174 } 175 176 virtual void OnDownloadDestroyed(content::DownloadItem* item) OVERRIDE { 177 DCHECK_EQ(item_, item); 178 item_->RemoveObserver(this); 179 item_ = NULL; 180 } 181 182 content::DownloadItem* item_; 183 bool waiting_; 184 bool error_; 185 int prev_percent_; 186 187 DISALLOW_COPY_AND_ASSIGN(PercentWaiter); 188 }; 189 190 // DownloadTestObserver subclass that observes one download until it transitions 191 // from a non-resumable state to a resumable state a specified number of 192 // times. Note that this observer can only observe a single download. 193 class DownloadTestObserverResumable : public content::DownloadTestObserver { 194 public: 195 // Construct a new observer. |transition_count| is the number of times the 196 // download should transition from a non-resumable state to a resumable state. 197 DownloadTestObserverResumable(DownloadManager* download_manager, 198 size_t transition_count) 199 : DownloadTestObserver(download_manager, 1, 200 ON_DANGEROUS_DOWNLOAD_FAIL), 201 was_previously_resumable_(false), 202 transitions_left_(transition_count) { 203 Init(); 204 } 205 virtual ~DownloadTestObserverResumable() {} 206 207 private: 208 virtual bool IsDownloadInFinalState(DownloadItem* download) OVERRIDE { 209 bool is_resumable_now = download->CanResume(); 210 if (!was_previously_resumable_ && is_resumable_now) 211 --transitions_left_; 212 was_previously_resumable_ = is_resumable_now; 213 return transitions_left_ == 0; 214 } 215 216 bool was_previously_resumable_; 217 size_t transitions_left_; 218 219 DISALLOW_COPY_AND_ASSIGN(DownloadTestObserverResumable); 220 }; 221 222 // DownloadTestObserver subclass that observes a download until it transitions 223 // from IN_PROGRESS to another state, but only after StartObserving() is called. 224 class DownloadTestObserverNotInProgress : public content::DownloadTestObserver { 225 public: 226 DownloadTestObserverNotInProgress(DownloadManager* download_manager, 227 size_t count) 228 : DownloadTestObserver(download_manager, count, 229 ON_DANGEROUS_DOWNLOAD_FAIL), 230 started_observing_(false) { 231 Init(); 232 } 233 virtual ~DownloadTestObserverNotInProgress() {} 234 235 void StartObserving() { 236 started_observing_ = true; 237 } 238 239 private: 240 virtual bool IsDownloadInFinalState(DownloadItem* download) OVERRIDE { 241 return started_observing_ && 242 download->GetState() != DownloadItem::IN_PROGRESS; 243 } 244 245 bool started_observing_; 246 }; 247 248 // IDs and paths of CRX files used in tests. 249 const char kGoodCrxId[] = "ldnnhddmnhbkjipkidpdiheffobcpfmf"; 250 const base::FilePath kGoodCrxPath(FILE_PATH_LITERAL("extensions/good.crx")); 251 252 const char kLargeThemeCrxId[] = "pjpgmfcmabopnnfonnhmdjglfpjjfkbf"; 253 const base::FilePath kLargeThemePath( 254 FILE_PATH_LITERAL("extensions/theme2.crx")); 255 256 // Get History Information. 257 class DownloadsHistoryDataCollector { 258 public: 259 explicit DownloadsHistoryDataCollector(Profile* profile) 260 : profile_(profile), result_valid_(false) {} 261 262 bool WaitForDownloadInfo( 263 scoped_ptr<std::vector<history::DownloadRow> >* results) { 264 HistoryService* hs = HistoryServiceFactory::GetForProfile( 265 profile_, Profile::EXPLICIT_ACCESS); 266 DCHECK(hs); 267 hs->QueryDownloads( 268 base::Bind(&DownloadsHistoryDataCollector::OnQueryDownloadsComplete, 269 base::Unretained(this))); 270 271 content::RunMessageLoop(); 272 if (result_valid_) { 273 *results = results_.Pass(); 274 } 275 return result_valid_; 276 } 277 278 private: 279 void OnQueryDownloadsComplete( 280 scoped_ptr<std::vector<history::DownloadRow> > entries) { 281 result_valid_ = true; 282 results_ = entries.Pass(); 283 base::MessageLoopForUI::current()->Quit(); 284 } 285 286 Profile* profile_; 287 scoped_ptr<std::vector<history::DownloadRow> > results_; 288 bool result_valid_; 289 CancelableRequestConsumer callback_consumer_; 290 291 DISALLOW_COPY_AND_ASSIGN(DownloadsHistoryDataCollector); 292 }; 293 294 // Mock that simulates a permissions dialog where the user denies 295 // permission to install. TODO(skerner): This could be shared with 296 // extensions tests. Find a common place for this class. 297 class MockAbortExtensionInstallPrompt : public ExtensionInstallPrompt { 298 public: 299 MockAbortExtensionInstallPrompt() : 300 ExtensionInstallPrompt(NULL) { 301 } 302 303 // Simulate a user abort on an extension installation. 304 virtual void ConfirmInstall( 305 Delegate* delegate, 306 const Extension* extension, 307 const ShowDialogCallback& show_dialog_callback) OVERRIDE { 308 delegate->InstallUIAbort(true); 309 base::MessageLoopForUI::current()->Quit(); 310 } 311 312 virtual void OnInstallSuccess(const Extension* extension, 313 SkBitmap* icon) OVERRIDE { 314 } 315 virtual void OnInstallFailure( 316 const extensions::CrxInstallerError& error) OVERRIDE { 317 } 318 }; 319 320 // Mock that simulates a permissions dialog where the user allows 321 // installation. 322 class MockAutoConfirmExtensionInstallPrompt : public ExtensionInstallPrompt { 323 public: 324 explicit MockAutoConfirmExtensionInstallPrompt( 325 content::WebContents* web_contents) 326 : ExtensionInstallPrompt(web_contents) {} 327 328 // Proceed without confirmation prompt. 329 virtual void ConfirmInstall( 330 Delegate* delegate, 331 const Extension* extension, 332 const ShowDialogCallback& show_dialog_callback) OVERRIDE { 333 delegate->InstallUIProceed(); 334 } 335 336 virtual void OnInstallSuccess(const Extension* extension, 337 SkBitmap* icon) OVERRIDE { 338 } 339 virtual void OnInstallFailure( 340 const extensions::CrxInstallerError& error) OVERRIDE { 341 } 342 }; 343 344 static DownloadManager* DownloadManagerForBrowser(Browser* browser) { 345 return BrowserContext::GetDownloadManager(browser->profile()); 346 } 347 348 class TestRenderViewContextMenu : public RenderViewContextMenu { 349 public: 350 TestRenderViewContextMenu(WebContents* web_contents, 351 const content::ContextMenuParams& params) 352 : RenderViewContextMenu(web_contents, params) { 353 } 354 virtual ~TestRenderViewContextMenu() {} 355 356 private: 357 virtual void PlatformInit() OVERRIDE {} 358 virtual void PlatformCancel() OVERRIDE {} 359 virtual bool GetAcceleratorForCommandId(int, ui::Accelerator*) OVERRIDE { 360 return false; 361 } 362 363 DISALLOW_COPY_AND_ASSIGN(TestRenderViewContextMenu); 364 }; 365 366 bool WasAutoOpened(DownloadItem* item) { 367 return item->GetAutoOpened(); 368 } 369 370 // Called when a download starts. Marks the download as hidden. 371 void SetHiddenDownloadCallback(DownloadItem* item, net::Error error) { 372 DownloadItemModel(item).SetShouldShowInShelf(false); 373 } 374 375 // Callback for HistoryObserver; used in DownloadHistoryCheck 376 bool HasDataAndName(const history::DownloadRow& row) { 377 return row.received_bytes > 0 && !row.target_path.empty(); 378 } 379 380 } // namespace 381 382 class HistoryObserver : public DownloadHistory::Observer { 383 public: 384 typedef base::Callback<bool(const history::DownloadRow&)> FilterCallback; 385 386 explicit HistoryObserver(Profile* profile) 387 : profile_(profile), 388 waiting_(false), 389 seen_stored_(false) { 390 DownloadServiceFactory::GetForBrowserContext(profile_)-> 391 GetDownloadHistory()->AddObserver(this); 392 } 393 394 virtual ~HistoryObserver() { 395 DownloadService* service = DownloadServiceFactory::GetForBrowserContext( 396 profile_); 397 if (service && service->GetDownloadHistory()) 398 service->GetDownloadHistory()->RemoveObserver(this); 399 } 400 401 void SetFilterCallback(const FilterCallback& callback) { 402 callback_ = callback; 403 } 404 405 virtual void OnDownloadStored( 406 content::DownloadItem* item, 407 const history::DownloadRow& info) OVERRIDE { 408 if (!callback_.is_null() && (!callback_.Run(info))) 409 return; 410 411 seen_stored_ = true; 412 if (waiting_) 413 base::MessageLoopForUI::current()->Quit(); 414 } 415 416 virtual void OnDownloadHistoryDestroyed() OVERRIDE { 417 DownloadServiceFactory::GetForBrowserContext(profile_)-> 418 GetDownloadHistory()->RemoveObserver(this); 419 } 420 421 void WaitForStored() { 422 if (seen_stored_) 423 return; 424 waiting_ = true; 425 content::RunMessageLoop(); 426 waiting_ = false; 427 } 428 429 private: 430 Profile* profile_; 431 bool waiting_; 432 bool seen_stored_; 433 FilterCallback callback_; 434 435 DISALLOW_COPY_AND_ASSIGN(HistoryObserver); 436 }; 437 438 class DownloadTest : public InProcessBrowserTest { 439 public: 440 // Choice of navigation or direct fetch. Used by |DownloadFileCheckErrors()|. 441 enum DownloadMethod { 442 DOWNLOAD_NAVIGATE, 443 DOWNLOAD_DIRECT 444 }; 445 446 // Information passed in to |DownloadFileCheckErrors()|. 447 struct DownloadInfo { 448 const char* url_name; // URL for the download. 449 DownloadMethod download_method; // Navigation or Direct. 450 // Download interrupt reason (NONE is OK). 451 content::DownloadInterruptReason reason; 452 bool show_download_item; // True if the download item appears on the shelf. 453 bool should_redirect_to_documents; // True if we save it in "My Documents". 454 }; 455 456 struct FileErrorInjectInfo { 457 DownloadInfo download_info; 458 content::TestFileErrorInjector::FileErrorInfo error_info; 459 }; 460 461 DownloadTest() {} 462 463 virtual void SetUpOnMainThread() OVERRIDE { 464 BrowserThread::PostTask( 465 BrowserThread::IO, FROM_HERE, 466 base::Bind(&chrome_browser_net::SetUrlRequestMocksEnabled, true)); 467 ASSERT_TRUE(InitialSetup()); 468 } 469 470 virtual void CleanUpOnMainThread() OVERRIDE { 471 // Needs to be torn down on the main thread. file_activity_observer_ holds a 472 // reference to the ChromeDownloadManagerDelegate which should be destroyed 473 // on the UI thread. 474 file_activity_observer_.reset(); 475 } 476 477 virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE { 478 command_line->AppendSwitch(switches::kDisablePluginsDiscovery); 479 } 480 481 // Returning false indicates a failure of the setup, and should be asserted 482 // in the caller. 483 virtual bool InitialSetup() { 484 bool have_test_dir = PathService::Get(chrome::DIR_TEST_DATA, &test_dir_); 485 EXPECT_TRUE(have_test_dir); 486 if (!have_test_dir) 487 return false; 488 489 // Sanity check default values for window / tab count and shelf visibility. 490 int window_count = chrome::GetTotalBrowserCount(); 491 EXPECT_EQ(1, window_count); 492 EXPECT_EQ(1, browser()->tab_strip_model()->count()); 493 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible()); 494 495 // Set up the temporary download folder. 496 bool created_downloads_dir = CreateAndSetDownloadsDirectory(browser()); 497 EXPECT_TRUE(created_downloads_dir); 498 if (!created_downloads_dir) 499 return false; 500 browser()->profile()->GetPrefs()->SetBoolean( 501 prefs::kPromptForDownload, false); 502 503 DownloadManager* manager = DownloadManagerForBrowser(browser()); 504 DownloadPrefs::FromDownloadManager(manager)->ResetAutoOpen(); 505 manager->RemoveAllDownloads(); 506 507 file_activity_observer_.reset( 508 new DownloadTestFileActivityObserver(browser()->profile())); 509 510 return true; 511 } 512 513 protected: 514 enum SizeTestType { 515 SIZE_TEST_TYPE_KNOWN, 516 SIZE_TEST_TYPE_UNKNOWN, 517 }; 518 519 base::FilePath GetDownloadsDirectory() { 520 return downloads_directory_.path(); 521 } 522 523 // Location of the file source (the place from which it is downloaded). 524 base::FilePath OriginFile(base::FilePath file) { 525 return test_dir_.Append(file); 526 } 527 528 // Location of the file destination (place to which it is downloaded). 529 base::FilePath DestinationFile(Browser* browser, base::FilePath file) { 530 return GetDownloadDirectory(browser).Append(file.BaseName()); 531 } 532 533 // Must be called after browser creation. Creates a temporary 534 // directory for downloads that is auto-deleted on destruction. 535 // Returning false indicates a failure of the function, and should be asserted 536 // in the caller. 537 bool CreateAndSetDownloadsDirectory(Browser* browser) { 538 if (!browser) 539 return false; 540 541 if (!downloads_directory_.CreateUniqueTempDir()) 542 return false; 543 544 browser->profile()->GetPrefs()->SetFilePath( 545 prefs::kDownloadDefaultDirectory, 546 downloads_directory_.path()); 547 browser->profile()->GetPrefs()->SetFilePath( 548 prefs::kSaveFileDefaultDirectory, 549 downloads_directory_.path()); 550 551 return true; 552 } 553 554 DownloadPrefs* GetDownloadPrefs(Browser* browser) { 555 return DownloadPrefs::FromDownloadManager( 556 DownloadManagerForBrowser(browser)); 557 } 558 559 base::FilePath GetDownloadDirectory(Browser* browser) { 560 return GetDownloadPrefs(browser)->DownloadPath(); 561 } 562 563 // Create a DownloadTestObserverTerminal that will wait for the 564 // specified number of downloads to finish. 565 content::DownloadTestObserver* CreateWaiter( 566 Browser* browser, int num_downloads) { 567 DownloadManager* download_manager = DownloadManagerForBrowser(browser); 568 return new content::DownloadTestObserverTerminal( 569 download_manager, num_downloads, 570 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL); 571 } 572 573 // Create a DownloadTestObserverInProgress that will wait for the 574 // specified number of downloads to start. 575 content::DownloadTestObserver* CreateInProgressWaiter( 576 Browser* browser, int num_downloads) { 577 DownloadManager* download_manager = DownloadManagerForBrowser(browser); 578 return new content::DownloadTestObserverInProgress( 579 download_manager, num_downloads); 580 } 581 582 // Create a DownloadTestObserverTerminal that will wait for the 583 // specified number of downloads to finish, or for 584 // a dangerous download warning to be shown. 585 content::DownloadTestObserver* DangerousDownloadWaiter( 586 Browser* browser, 587 int num_downloads, 588 content::DownloadTestObserver::DangerousDownloadAction 589 dangerous_download_action) { 590 DownloadManager* download_manager = DownloadManagerForBrowser(browser); 591 return new content::DownloadTestObserverTerminal( 592 download_manager, num_downloads, 593 dangerous_download_action); 594 } 595 596 void CheckDownloadStatesForBrowser(Browser* browser, 597 size_t num, 598 DownloadItem::DownloadState state) { 599 std::vector<DownloadItem*> download_items; 600 GetDownloads(browser, &download_items); 601 602 EXPECT_EQ(num, download_items.size()); 603 604 for (size_t i = 0; i < download_items.size(); ++i) { 605 EXPECT_EQ(state, download_items[i]->GetState()) << " Item " << i; 606 } 607 } 608 609 void CheckDownloadStates(size_t num, DownloadItem::DownloadState state) { 610 CheckDownloadStatesForBrowser(browser(), num, state); 611 } 612 613 // Download |url|, then wait for the download to finish. 614 // |disposition| indicates where the navigation occurs (current tab, new 615 // foreground tab, etc). 616 // |browser_test_flags| indicate what to wait for, and is an OR of 0 or more 617 // values in the ui_test_utils::BrowserTestWaitFlags enum. 618 void DownloadAndWaitWithDisposition(Browser* browser, 619 const GURL& url, 620 WindowOpenDisposition disposition, 621 int browser_test_flags) { 622 // Setup notification, navigate, and block. 623 scoped_ptr<content::DownloadTestObserver> observer( 624 CreateWaiter(browser, 1)); 625 // This call will block until the condition specified by 626 // |browser_test_flags|, but will not wait for the download to finish. 627 ui_test_utils::NavigateToURLWithDisposition(browser, 628 url, 629 disposition, 630 browser_test_flags); 631 // Waits for the download to complete. 632 observer->WaitForFinished(); 633 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::COMPLETE)); 634 // We don't expect a file chooser to be shown. 635 EXPECT_FALSE(DidShowFileChooser()); 636 } 637 638 // Download a file in the current tab, then wait for the download to finish. 639 void DownloadAndWait(Browser* browser, 640 const GURL& url) { 641 DownloadAndWaitWithDisposition( 642 browser, 643 url, 644 CURRENT_TAB, 645 ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION); 646 } 647 648 // Should only be called when the download is known to have finished 649 // (in error or not). 650 // Returning false indicates a failure of the function, and should be asserted 651 // in the caller. 652 bool CheckDownload(Browser* browser, 653 const base::FilePath& downloaded_filename, 654 const base::FilePath& origin_filename) { 655 // Find the path to which the data will be downloaded. 656 base::FilePath downloaded_file( 657 DestinationFile(browser, downloaded_filename)); 658 659 // Find the origin path (from which the data comes). 660 base::FilePath origin_file(OriginFile(origin_filename)); 661 return CheckDownloadFullPaths(browser, downloaded_file, origin_file); 662 } 663 664 // A version of CheckDownload that allows complete path specification. 665 bool CheckDownloadFullPaths(Browser* browser, 666 const base::FilePath& downloaded_file, 667 const base::FilePath& origin_file) { 668 bool origin_file_exists = base::PathExists(origin_file); 669 EXPECT_TRUE(origin_file_exists) << origin_file.value(); 670 if (!origin_file_exists) 671 return false; 672 673 // Confirm the downloaded data file exists. 674 bool downloaded_file_exists = base::PathExists(downloaded_file); 675 EXPECT_TRUE(downloaded_file_exists) << downloaded_file.value(); 676 if (!downloaded_file_exists) 677 return false; 678 679 int64 origin_file_size = 0; 680 EXPECT_TRUE(file_util::GetFileSize(origin_file, &origin_file_size)); 681 std::string original_file_contents; 682 EXPECT_TRUE( 683 file_util::ReadFileToString(origin_file, &original_file_contents)); 684 EXPECT_TRUE( 685 VerifyFile(downloaded_file, original_file_contents, origin_file_size)); 686 687 // Delete the downloaded copy of the file. 688 bool downloaded_file_deleted = 689 file_util::DieFileDie(downloaded_file, false); 690 EXPECT_TRUE(downloaded_file_deleted); 691 return downloaded_file_deleted; 692 } 693 694 content::DownloadTestObserver* CreateInProgressDownloadObserver( 695 size_t download_count) { 696 DownloadManager* manager = DownloadManagerForBrowser(browser()); 697 return new content::DownloadTestObserverInProgress( 698 manager, download_count); 699 } 700 701 DownloadItem* CreateSlowTestDownload() { 702 scoped_ptr<content::DownloadTestObserver> observer( 703 CreateInProgressDownloadObserver(1)); 704 GURL slow_download_url(URLRequestSlowDownloadJob::kUnknownSizeUrl); 705 DownloadManager* manager = DownloadManagerForBrowser(browser()); 706 707 EXPECT_EQ(0, manager->InProgressCount()); 708 if (manager->InProgressCount() != 0) 709 return NULL; 710 711 ui_test_utils::NavigateToURLWithDisposition( 712 browser(), slow_download_url, CURRENT_TAB, 713 ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION); 714 715 observer->WaitForFinished(); 716 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::IN_PROGRESS)); 717 718 DownloadManager::DownloadVector items; 719 manager->GetAllDownloads(&items); 720 721 DownloadItem* new_item = NULL; 722 for (DownloadManager::DownloadVector::iterator iter = items.begin(); 723 iter != items.end(); ++iter) { 724 if ((*iter)->GetState() == DownloadItem::IN_PROGRESS) { 725 // There should be only one IN_PROGRESS item. 726 EXPECT_EQ(NULL, new_item); 727 new_item = *iter; 728 } 729 } 730 return new_item; 731 } 732 733 bool RunSizeTest(Browser* browser, 734 SizeTestType type, 735 const std::string& partial_indication, 736 const std::string& total_indication) { 737 EXPECT_TRUE(type == SIZE_TEST_TYPE_UNKNOWN || type == SIZE_TEST_TYPE_KNOWN); 738 if (type != SIZE_TEST_TYPE_KNOWN && type != SIZE_TEST_TYPE_UNKNOWN) 739 return false; 740 GURL url(type == SIZE_TEST_TYPE_KNOWN ? 741 URLRequestSlowDownloadJob::kKnownSizeUrl : 742 URLRequestSlowDownloadJob::kUnknownSizeUrl); 743 744 // TODO(ahendrickson) -- |expected_title_in_progress| and 745 // |expected_title_finished| need to be checked. 746 base::FilePath filename; 747 net::FileURLToFilePath(url, &filename); 748 string16 expected_title_in_progress( 749 ASCIIToUTF16(partial_indication) + filename.LossyDisplayName()); 750 string16 expected_title_finished( 751 ASCIIToUTF16(total_indication) + filename.LossyDisplayName()); 752 753 // Download a partial web page in a background tab and wait. 754 // The mock system will not complete until it gets a special URL. 755 scoped_ptr<content::DownloadTestObserver> observer( 756 CreateWaiter(browser, 1)); 757 ui_test_utils::NavigateToURL(browser, url); 758 759 // TODO(ahendrickson): check download status text before downloading. 760 // Need to: 761 // - Add a member function to the |DownloadShelf| interface class, that 762 // indicates how many members it has. 763 // - Add a member function to |DownloadShelf| to get the status text 764 // of a given member (for example, via the name in |DownloadItemView|'s 765 // GetAccessibleState() member function), by index. 766 // - Iterate over browser->window()->GetDownloadShelf()'s members 767 // to see if any match the status text we want. Start with the last one. 768 769 // Allow the request to finish. We do this by loading a second URL in a 770 // separate tab. 771 GURL finish_url(URLRequestSlowDownloadJob::kFinishDownloadUrl); 772 ui_test_utils::NavigateToURLWithDisposition( 773 browser, 774 finish_url, 775 NEW_FOREGROUND_TAB, 776 ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION); 777 observer->WaitForFinished(); 778 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::COMPLETE)); 779 CheckDownloadStatesForBrowser(browser, 1, DownloadItem::COMPLETE); 780 781 EXPECT_EQ(2, browser->tab_strip_model()->count()); 782 783 // TODO(ahendrickson): check download status text after downloading. 784 785 base::FilePath basefilename(filename.BaseName()); 786 net::FileURLToFilePath(url, &filename); 787 base::FilePath download_path = 788 downloads_directory_.path().Append(basefilename); 789 EXPECT_TRUE(browser->window()->IsDownloadShelfVisible()); 790 791 bool downloaded_path_exists = base::PathExists(download_path); 792 EXPECT_TRUE(downloaded_path_exists); 793 if (!downloaded_path_exists) 794 return false; 795 796 // Check the file contents. 797 size_t file_size = URLRequestSlowDownloadJob::kFirstDownloadSize + 798 URLRequestSlowDownloadJob::kSecondDownloadSize; 799 std::string expected_contents(file_size, '*'); 800 EXPECT_TRUE(VerifyFile(download_path, expected_contents, file_size)); 801 802 // Delete the file we just downloaded. 803 EXPECT_TRUE(file_util::DieFileDie(download_path, true)); 804 EXPECT_FALSE(base::PathExists(download_path)); 805 806 return true; 807 } 808 809 void GetDownloads(Browser* browser, std::vector<DownloadItem*>* downloads) { 810 DCHECK(downloads); 811 DownloadManager* manager = DownloadManagerForBrowser(browser); 812 manager->GetAllDownloads(downloads); 813 } 814 815 static void ExpectWindowCountAfterDownload(size_t expected) { 816 EXPECT_EQ(expected, chrome::GetTotalBrowserCount()); 817 } 818 819 void EnableFileChooser(bool enable) { 820 file_activity_observer_->EnableFileChooser(enable); 821 } 822 823 bool DidShowFileChooser() { 824 return file_activity_observer_->TestAndResetDidShowFileChooser(); 825 } 826 827 // Checks that |path| is has |file_size| bytes, and matches the |value| 828 // string. 829 bool VerifyFile(const base::FilePath& path, 830 const std::string& value, 831 const int64 file_size) { 832 std::string file_contents; 833 834 bool read = file_util::ReadFileToString(path, &file_contents); 835 EXPECT_TRUE(read) << "Failed reading file: " << path.value() << std::endl; 836 if (!read) 837 return false; // Couldn't read the file. 838 839 // Note: we don't handle really large files (more than size_t can hold) 840 // so we will fail in that case. 841 size_t expected_size = static_cast<size_t>(file_size); 842 843 // Check the size. 844 EXPECT_EQ(expected_size, file_contents.size()); 845 if (expected_size != file_contents.size()) 846 return false; 847 848 // Check the contents. 849 EXPECT_EQ(value, file_contents); 850 if (memcmp(file_contents.c_str(), value.c_str(), expected_size) != 0) 851 return false; 852 853 return true; 854 } 855 856 // Attempts to download a file, based on information in |download_info|. 857 // If a Select File dialog opens, will automatically choose the default. 858 void DownloadFilesCheckErrorsSetup() { 859 ASSERT_TRUE(test_server()->Start()); 860 std::vector<DownloadItem*> download_items; 861 GetDownloads(browser(), &download_items); 862 ASSERT_TRUE(download_items.empty()); 863 864 EnableFileChooser(true); 865 } 866 867 void DownloadFilesCheckErrorsLoopBody(const DownloadInfo& download_info, 868 size_t i) { 869 std::stringstream s; 870 s << " " << __FUNCTION__ << "()" 871 << " index = " << i 872 << " url = '" << download_info.url_name << "'" 873 << " method = " 874 << ((download_info.download_method == DOWNLOAD_DIRECT) ? 875 "DOWNLOAD_DIRECT" : "DOWNLOAD_NAVIGATE") 876 << " show_item = " << download_info.show_download_item 877 << " reason = " 878 << InterruptReasonDebugString(download_info.reason); 879 880 std::vector<DownloadItem*> download_items; 881 GetDownloads(browser(), &download_items); 882 size_t downloads_expected = download_items.size(); 883 884 std::string server_path = "files/downloads/"; 885 server_path += download_info.url_name; 886 GURL url = test_server()->GetURL(server_path); 887 ASSERT_TRUE(url.is_valid()) << s.str(); 888 889 DownloadManager* download_manager = DownloadManagerForBrowser(browser()); 890 WebContents* web_contents = 891 browser()->tab_strip_model()->GetActiveWebContents(); 892 ASSERT_TRUE(web_contents) << s.str(); 893 894 scoped_ptr<content::DownloadTestObserver> observer( 895 new content::DownloadTestObserverTerminal( 896 download_manager, 897 1, 898 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL)); 899 900 if (download_info.download_method == DOWNLOAD_DIRECT) { 901 // Go directly to download. Don't wait for navigation. 902 scoped_refptr<content::DownloadTestItemCreationObserver> 903 creation_observer(new content::DownloadTestItemCreationObserver); 904 905 scoped_ptr<DownloadUrlParameters> params( 906 DownloadUrlParameters::FromWebContents(web_contents, url)); 907 params->set_callback(creation_observer->callback()); 908 DownloadManagerForBrowser(browser())->DownloadUrl(params.Pass()); 909 910 // Wait until the item is created, or we have determined that it 911 // won't be. 912 creation_observer->WaitForDownloadItemCreation(); 913 914 EXPECT_EQ(download_info.show_download_item, 915 creation_observer->succeeded()); 916 if (download_info.show_download_item) { 917 EXPECT_EQ(net::OK, creation_observer->error()); 918 EXPECT_NE(content::DownloadItem::kInvalidId, 919 creation_observer->download_id()); 920 } else { 921 EXPECT_NE(net::OK, creation_observer->error()); 922 EXPECT_EQ(content::DownloadItem::kInvalidId, 923 creation_observer->download_id()); 924 } 925 } else { 926 // Navigate to URL normally, wait until done. 927 ui_test_utils::NavigateToURLBlockUntilNavigationsComplete(browser(), 928 url, 929 1); 930 } 931 932 if (download_info.show_download_item) { 933 downloads_expected++; 934 observer->WaitForFinished(); 935 DownloadItem::DownloadState final_state = 936 (download_info.reason == content::DOWNLOAD_INTERRUPT_REASON_NONE) ? 937 DownloadItem::COMPLETE : 938 DownloadItem::INTERRUPTED; 939 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(final_state)); 940 } 941 942 // Wait till the |DownloadFile|s are destroyed. 943 content::RunAllPendingInMessageLoop(content::BrowserThread::FILE); 944 content::RunAllPendingInMessageLoop(content::BrowserThread::UI); 945 946 // Validate that the correct files were downloaded. 947 download_items.clear(); 948 GetDownloads(browser(), &download_items); 949 ASSERT_EQ(downloads_expected, download_items.size()) << s.str(); 950 951 if (download_info.show_download_item) { 952 // Find the last download item. 953 DownloadItem* item = download_items[0]; 954 for (size_t d = 1; d < downloads_expected; ++d) { 955 if (download_items[d]->GetStartTime() > item->GetStartTime()) 956 item = download_items[d]; 957 } 958 959 ASSERT_EQ(url, item->GetOriginalUrl()) << s.str(); 960 961 ASSERT_EQ(download_info.reason, item->GetLastReason()) << s.str(); 962 963 if (item->GetState() == content::DownloadItem::COMPLETE) { 964 // Clean up the file, in case it ended up in the My Documents folder. 965 base::FilePath destination_folder = GetDownloadDirectory(browser()); 966 base::FilePath my_downloaded_file = item->GetTargetFilePath(); 967 EXPECT_TRUE(base::PathExists(my_downloaded_file)); 968 EXPECT_TRUE(base::DeleteFile(my_downloaded_file, false)); 969 970 EXPECT_EQ(download_info.should_redirect_to_documents ? 971 std::string::npos : 972 0u, 973 my_downloaded_file.value().find(destination_folder.value())); 974 if (download_info.should_redirect_to_documents) { 975 // If it's not where we asked it to be, it should be in the 976 // My Documents folder. 977 base::FilePath my_docs_folder; 978 EXPECT_TRUE(PathService::Get(chrome::DIR_USER_DOCUMENTS, 979 &my_docs_folder)); 980 EXPECT_EQ(0u, 981 my_downloaded_file.value().find(my_docs_folder.value())); 982 } 983 } 984 } 985 } 986 987 // Attempts to download a set of files, based on information in the 988 // |download_info| array. |count| is the number of files. 989 // If a Select File dialog appears, it will choose the default and return 990 // immediately. 991 void DownloadFilesCheckErrors(size_t count, DownloadInfo* download_info) { 992 DownloadFilesCheckErrorsSetup(); 993 994 for (size_t i = 0; i < count; ++i) { 995 DownloadFilesCheckErrorsLoopBody(download_info[i], i); 996 } 997 } 998 999 void DownloadInsertFilesErrorCheckErrorsLoopBody( 1000 scoped_refptr<content::TestFileErrorInjector> injector, 1001 const FileErrorInjectInfo& info, 1002 size_t i) { 1003 std::stringstream s; 1004 s << " " << __FUNCTION__ << "()" 1005 << " index = " << i 1006 << " url = " << info.error_info.url 1007 << " operation code = " << 1008 content::TestFileErrorInjector::DebugString( 1009 info.error_info.code) 1010 << " instance = " << info.error_info.operation_instance 1011 << " error = " << content::InterruptReasonDebugString( 1012 info.error_info.error); 1013 1014 injector->ClearErrors(); 1015 injector->AddError(info.error_info); 1016 1017 injector->InjectErrors(); 1018 1019 DownloadFilesCheckErrorsLoopBody(info.download_info, i); 1020 1021 size_t expected_successes = info.download_info.show_download_item ? 1u : 0u; 1022 EXPECT_EQ(expected_successes, injector->TotalFileCount()) << s.str(); 1023 EXPECT_EQ(0u, injector->CurrentFileCount()) << s.str(); 1024 1025 if (info.download_info.show_download_item) 1026 EXPECT_TRUE(injector->HadFile(GURL(info.error_info.url))) << s.str(); 1027 } 1028 1029 void DownloadInsertFilesErrorCheckErrors(size_t count, 1030 FileErrorInjectInfo* info) { 1031 DownloadFilesCheckErrorsSetup(); 1032 1033 // Set up file failures. 1034 scoped_refptr<content::TestFileErrorInjector> injector( 1035 content::TestFileErrorInjector::Create( 1036 DownloadManagerForBrowser(browser()))); 1037 1038 for (size_t i = 0; i < count; ++i) { 1039 // Set up the full URL, for download file tracking. 1040 std::string server_path = "files/downloads/"; 1041 server_path += info[i].download_info.url_name; 1042 GURL url = test_server()->GetURL(server_path); 1043 info[i].error_info.url = url.spec(); 1044 1045 DownloadInsertFilesErrorCheckErrorsLoopBody(injector, info[i], i); 1046 } 1047 } 1048 1049 // Attempts to download a file to a read-only folder, based on information 1050 // in |download_info|. 1051 void DownloadFilesToReadonlyFolder(size_t count, 1052 DownloadInfo* download_info) { 1053 DownloadFilesCheckErrorsSetup(); 1054 1055 // Make the test folder unwritable. 1056 base::FilePath destination_folder = GetDownloadDirectory(browser()); 1057 DVLOG(1) << " " << __FUNCTION__ << "()" 1058 << " folder = '" << destination_folder.value() << "'"; 1059 file_util::PermissionRestorer permission_restorer(destination_folder); 1060 EXPECT_TRUE(file_util::MakeFileUnwritable(destination_folder)); 1061 1062 for (size_t i = 0; i < count; ++i) { 1063 DownloadFilesCheckErrorsLoopBody(download_info[i], i); 1064 } 1065 } 1066 1067 // A mock install prompt that simulates the user allowing an install request. 1068 void SetAllowMockInstallPrompt() { 1069 download_crx_util::SetMockInstallPromptForTesting( 1070 scoped_ptr<ExtensionInstallPrompt>( 1071 new MockAutoConfirmExtensionInstallPrompt( 1072 browser()->tab_strip_model()->GetActiveWebContents()))); 1073 } 1074 1075 // This method: 1076 // * Starts a mock download by navigating browser() to a URLRequestMockHTTPJob 1077 // mock URL. 1078 // * Injects |error| on the first write using |error_injector|. 1079 // * Waits for the download to be interrupted. 1080 // * Clears the errors on |error_injector|. 1081 // * Returns the resulting interrupted download. 1082 DownloadItem* StartMockDownloadAndInjectError( 1083 content::TestFileErrorInjector* error_injector, 1084 content::DownloadInterruptReason error) { 1085 base::FilePath file_path(FILE_PATH_LITERAL("download-test1.lib")); 1086 GURL url = URLRequestMockHTTPJob::GetMockUrl(file_path); 1087 1088 content::TestFileErrorInjector::FileErrorInfo error_info; 1089 error_info.url = url.spec(); 1090 error_info.code = content::TestFileErrorInjector::FILE_OPERATION_WRITE; 1091 error_info.operation_instance = 0; 1092 error_info.error = error; 1093 error_injector->ClearErrors(); 1094 error_injector->AddError(error_info); 1095 error_injector->InjectErrors(); 1096 1097 scoped_ptr<content::DownloadTestObserver> observer( 1098 new DownloadTestObserverResumable( 1099 DownloadManagerForBrowser(browser()), 1)); 1100 ui_test_utils::NavigateToURL(browser(), url); 1101 observer->WaitForFinished(); 1102 1103 content::DownloadManager::DownloadVector downloads; 1104 DownloadManagerForBrowser(browser())->GetAllDownloads(&downloads); 1105 EXPECT_EQ(1u, downloads.size()); 1106 1107 if (downloads.size() != 1) 1108 return NULL; 1109 1110 error_injector->ClearErrors(); 1111 error_injector->InjectErrors(); 1112 DownloadItem* download = downloads[0]; 1113 EXPECT_EQ(DownloadItem::INTERRUPTED, download->GetState()); 1114 EXPECT_EQ(error, download->GetLastReason()); 1115 return download; 1116 } 1117 1118 private: 1119 static void EnsureNoPendingDownloadJobsOnIO(bool* result) { 1120 if (URLRequestSlowDownloadJob::NumberOutstandingRequests()) 1121 *result = false; 1122 BrowserThread::PostTask( 1123 BrowserThread::UI, FROM_HERE, base::MessageLoop::QuitClosure()); 1124 } 1125 1126 // Location of the test data. 1127 base::FilePath test_dir_; 1128 1129 // Location of the downloads directory for these tests 1130 base::ScopedTempDir downloads_directory_; 1131 1132 scoped_ptr<DownloadTestFileActivityObserver> file_activity_observer_; 1133 }; 1134 1135 // NOTES: 1136 // 1137 // Files for these tests are found in DIR_TEST_DATA (currently 1138 // "chrome\test\data\", see chrome_paths.cc). 1139 // Mock responses have extension .mock-http-headers appended to the file name. 1140 1141 // Download a file due to the associated MIME type. 1142 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadMimeType) { 1143 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib")); 1144 GURL url(URLRequestMockHTTPJob::GetMockUrl(file)); 1145 1146 // Download the file and wait. We do not expect the Select File dialog. 1147 DownloadAndWait(browser(), url); 1148 1149 // Check state. 1150 EXPECT_EQ(1, browser()->tab_strip_model()->count()); 1151 CheckDownload(browser(), file, file); 1152 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible()); 1153 } 1154 1155 #if defined(OS_WIN) 1156 // Download a file and confirm that the zone identifier (on windows) 1157 // is set to internet. 1158 IN_PROC_BROWSER_TEST_F(DownloadTest, CheckInternetZone) { 1159 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib")); 1160 GURL url(URLRequestMockHTTPJob::GetMockUrl(file)); 1161 1162 // Download the file and wait. We do not expect the Select File dialog. 1163 DownloadAndWait(browser(), url); 1164 1165 // Check state. Special file state must be checked before CheckDownload, 1166 // as CheckDownload will delete the output file. 1167 EXPECT_EQ(1, browser()->tab_strip_model()->count()); 1168 base::FilePath downloaded_file(DestinationFile(browser(), file)); 1169 if (file_util::VolumeSupportsADS(downloaded_file)) 1170 EXPECT_TRUE(file_util::HasInternetZoneIdentifier(downloaded_file)); 1171 CheckDownload(browser(), file, file); 1172 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible()); 1173 } 1174 #endif 1175 1176 // Put up a Select File dialog when the file is downloaded, due to 1177 // downloads preferences settings. 1178 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadMimeTypeSelect) { 1179 // Re-enable prompting. 1180 browser()->profile()->GetPrefs()->SetBoolean( 1181 prefs::kPromptForDownload, true); 1182 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib")); 1183 GURL url(URLRequestMockHTTPJob::GetMockUrl(file)); 1184 1185 EnableFileChooser(true); 1186 1187 // Download the file and wait. We expect the Select File dialog to appear 1188 // due to the MIME type, but we still wait until the download completes. 1189 scoped_ptr<content::DownloadTestObserver> observer( 1190 new content::DownloadTestObserverTerminal( 1191 DownloadManagerForBrowser(browser()), 1192 1, 1193 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL)); 1194 ui_test_utils::NavigateToURLWithDisposition( 1195 browser(), url, CURRENT_TAB, 1196 ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION); 1197 observer->WaitForFinished(); 1198 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::COMPLETE)); 1199 CheckDownloadStates(1, DownloadItem::COMPLETE); 1200 EXPECT_TRUE(DidShowFileChooser()); 1201 1202 // Check state. 1203 EXPECT_EQ(1, browser()->tab_strip_model()->count()); 1204 CheckDownload(browser(), file, file); 1205 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible()); 1206 } 1207 1208 // Access a file with a viewable mime-type, verify that a download 1209 // did not initiate. 1210 IN_PROC_BROWSER_TEST_F(DownloadTest, NoDownload) { 1211 base::FilePath file(FILE_PATH_LITERAL("download-test2.html")); 1212 GURL url(URLRequestMockHTTPJob::GetMockUrl(file)); 1213 base::FilePath file_path(DestinationFile(browser(), file)); 1214 1215 // Open a web page and wait. 1216 ui_test_utils::NavigateToURL(browser(), url); 1217 1218 // Check that we did not download the web page. 1219 EXPECT_FALSE(base::PathExists(file_path)); 1220 1221 // Check state. 1222 EXPECT_EQ(1, browser()->tab_strip_model()->count()); 1223 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible()); 1224 } 1225 1226 IN_PROC_BROWSER_TEST_F(DownloadTest, MimeTypesToShowNotDownload) { 1227 ASSERT_TRUE(test_server()->Start()); 1228 1229 // These files should all be displayed in the browser. 1230 const char* mime_types[] = { 1231 // It is unclear whether to display text/css or download it. 1232 // Firefox 3: Display 1233 // Internet Explorer 7: Download 1234 // Safari 3.2: Download 1235 // We choose to match Firefox due to the lot of complains 1236 // from the users if css files are downloaded: 1237 // http://code.google.com/p/chromium/issues/detail?id=7192 1238 "text/css", 1239 "text/javascript", 1240 "text/plain", 1241 "application/x-javascript", 1242 "text/html", 1243 "text/xml", 1244 "text/xsl", 1245 "application/xhtml+xml", 1246 "image/png", 1247 "image/gif", 1248 "image/jpeg", 1249 "image/bmp", 1250 }; 1251 for (size_t i = 0; i < arraysize(mime_types); ++i) { 1252 const char* mime_type = mime_types[i]; 1253 std::string path("contenttype?"); 1254 GURL url(test_server()->GetURL(path + mime_type)); 1255 ui_test_utils::NavigateToURL(browser(), url); 1256 1257 // Check state. 1258 EXPECT_EQ(1, browser()->tab_strip_model()->count()); 1259 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible()); 1260 } 1261 } 1262 1263 // Verify that when the DownloadResourceThrottle cancels a download, the 1264 // download never makes it to the downloads system. 1265 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadResourceThrottleCancels) { 1266 // Navigate to a page with the same domain as the file to download. We can't 1267 // navigate directly to the file we don't want to download because cross-site 1268 // navigations reset the TabDownloadState. 1269 base::FilePath same_site_path(FILE_PATH_LITERAL("download_script.html")); 1270 GURL same_site_url(URLRequestMockHTTPJob::GetMockUrl(same_site_path)); 1271 ui_test_utils::NavigateToURL(browser(), same_site_url); 1272 1273 // Make sure the initial navigation didn't trigger a download. 1274 std::vector<content::DownloadItem*> items; 1275 DownloadManagerForBrowser(browser())->GetAllDownloads(&items); 1276 EXPECT_EQ(0u, items.size()); 1277 1278 // Disable downloads for the tab. 1279 WebContents* web_contents = 1280 browser()->tab_strip_model()->GetActiveWebContents(); 1281 DownloadRequestLimiter::TabDownloadState* tab_download_state = 1282 g_browser_process->download_request_limiter()->GetDownloadState( 1283 web_contents, web_contents, true); 1284 ASSERT_TRUE(tab_download_state); 1285 tab_download_state->set_download_status( 1286 DownloadRequestLimiter::DOWNLOADS_NOT_ALLOWED); 1287 1288 // Try to start the download via Javascript and wait for the corresponding 1289 // load stop event. 1290 content::TestNavigationObserver observer(web_contents); 1291 bool download_assempted; 1292 ASSERT_TRUE(content::ExecuteScriptAndExtractBool( 1293 browser()->tab_strip_model()->GetActiveWebContents(), 1294 "window.domAutomationController.send(startDownload());", 1295 &download_assempted)); 1296 ASSERT_TRUE(download_assempted); 1297 observer.WaitForObservation( 1298 base::Bind(&content::RunMessageLoop), 1299 base::Bind(&base::MessageLoop::Quit, 1300 base::Unretained(base::MessageLoopForUI::current()))); 1301 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)); 1306 1307 // Check state. 1308 EXPECT_EQ(1, browser()->tab_strip_model()->count()); 1309 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible()); 1310 1311 // Verify that there's no pending download. The resource throttle 1312 // should have deleted it before it created a download item, so it 1313 // shouldn't be available as a cancelled download either. 1314 DownloadManagerForBrowser(browser())->GetAllDownloads(&items); 1315 EXPECT_EQ(0u, items.size()); 1316 } 1317 1318 // Download a 0-size file with a content-disposition header, verify that the 1319 // download tab opened and the file exists as the filename specified in the 1320 // header. This also ensures we properly handle empty file downloads. 1321 // The download shelf should be visible in the current tab. 1322 IN_PROC_BROWSER_TEST_F(DownloadTest, ContentDisposition) { 1323 base::FilePath file(FILE_PATH_LITERAL("download-test3.gif")); 1324 GURL url(URLRequestMockHTTPJob::GetMockUrl(file)); 1325 base::FilePath download_file( 1326 FILE_PATH_LITERAL("download-test3-attachment.gif")); 1327 1328 // Download a file and wait. 1329 DownloadAndWait(browser(), url); 1330 1331 CheckDownload(browser(), download_file, file); 1332 1333 // Check state. 1334 EXPECT_EQ(1, browser()->tab_strip_model()->count()); 1335 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible()); 1336 } 1337 1338 // Test that the download shelf is per-window by starting a download in one 1339 // tab, opening a second tab, closing the shelf, going back to the first tab, 1340 // and checking that the shelf is closed. 1341 IN_PROC_BROWSER_TEST_F(DownloadTest, PerWindowShelf) { 1342 base::FilePath file(FILE_PATH_LITERAL("download-test3.gif")); 1343 GURL url(URLRequestMockHTTPJob::GetMockUrl(file)); 1344 base::FilePath download_file( 1345 FILE_PATH_LITERAL("download-test3-attachment.gif")); 1346 1347 // Download a file and wait. 1348 DownloadAndWait(browser(), url); 1349 1350 CheckDownload(browser(), download_file, file); 1351 1352 // Check state. 1353 EXPECT_EQ(1, browser()->tab_strip_model()->count()); 1354 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible()); 1355 1356 // Open a second tab and wait. 1357 EXPECT_NE(static_cast<WebContents*>(NULL), 1358 chrome::AddSelectedTabWithURL(browser(), GURL(), 1359 content::PAGE_TRANSITION_TYPED)); 1360 EXPECT_EQ(2, browser()->tab_strip_model()->count()); 1361 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible()); 1362 1363 // Hide the download shelf. 1364 browser()->window()->GetDownloadShelf()->Close(DownloadShelf::AUTOMATIC); 1365 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible()); 1366 1367 // Go to the first tab. 1368 browser()->tab_strip_model()->ActivateTabAt(0, true); 1369 EXPECT_EQ(2, browser()->tab_strip_model()->count()); 1370 1371 // The download shelf should not be visible. 1372 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible()); 1373 } 1374 1375 // Check whether the downloads shelf is closed when the downloads tab is 1376 // invoked. 1377 IN_PROC_BROWSER_TEST_F(DownloadTest, CloseShelfOnDownloadsTab) { 1378 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib")); 1379 GURL url(URLRequestMockHTTPJob::GetMockUrl(file)); 1380 1381 // Download the file and wait. We do not expect the Select File dialog. 1382 DownloadAndWait(browser(), url); 1383 1384 // Check state. 1385 EXPECT_EQ(1, browser()->tab_strip_model()->count()); 1386 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible()); 1387 1388 // Open the downloads tab. 1389 chrome::ShowDownloads(browser()); 1390 // The shelf should now be closed. 1391 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible()); 1392 } 1393 1394 // UnknownSize and KnownSize are tests which depend on 1395 // URLRequestSlowDownloadJob to serve content in a certain way. Data will be 1396 // sent in two chunks where the first chunk is 35K and the second chunk is 10K. 1397 // The test will first attempt to download a file; but the server will "pause" 1398 // in the middle until the server receives a second request for 1399 // "download-finish". At that time, the download will finish. 1400 // These tests don't currently test much due to holes in |RunSizeTest()|. See 1401 // comments in that routine for details. 1402 IN_PROC_BROWSER_TEST_F(DownloadTest, UnknownSize) { 1403 ASSERT_TRUE(RunSizeTest(browser(), SIZE_TEST_TYPE_UNKNOWN, 1404 "32.0 KB - ", "100% - ")); 1405 } 1406 1407 IN_PROC_BROWSER_TEST_F(DownloadTest, KnownSize) { 1408 ASSERT_TRUE(RunSizeTest(browser(), SIZE_TEST_TYPE_KNOWN, 1409 "71% - ", "100% - ")); 1410 } 1411 1412 // Test that when downloading an item in Incognito mode, we don't crash when 1413 // closing the last Incognito window (http://crbug.com/13983). 1414 // Also check that the download shelf is not visible after closing the 1415 // Incognito window. 1416 IN_PROC_BROWSER_TEST_F(DownloadTest, IncognitoDownload) { 1417 Browser* incognito = CreateIncognitoBrowser(); 1418 ASSERT_TRUE(incognito); 1419 int window_count = chrome::GetTotalBrowserCount(); 1420 EXPECT_EQ(2, window_count); 1421 1422 // Download a file in the Incognito window and wait. 1423 CreateAndSetDownloadsDirectory(incognito); 1424 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib")); 1425 GURL url(URLRequestMockHTTPJob::GetMockUrl(file)); 1426 // Since |incognito| is a separate browser, we have to set it up explicitly. 1427 incognito->profile()->GetPrefs()->SetBoolean(prefs::kPromptForDownload, 1428 false); 1429 DownloadAndWait(incognito, url); 1430 1431 // We should still have 2 windows. 1432 ExpectWindowCountAfterDownload(2); 1433 1434 // Verify that the download shelf is showing for the Incognito window. 1435 EXPECT_TRUE(incognito->window()->IsDownloadShelfVisible()); 1436 1437 #if !defined(OS_MACOSX) 1438 // On Mac OS X, the UI window close is delayed until the outermost 1439 // message loop runs. So it isn't possible to get a BROWSER_CLOSED 1440 // notification inside of a test. 1441 content::WindowedNotificationObserver signal( 1442 chrome::NOTIFICATION_BROWSER_CLOSED, 1443 content::Source<Browser>(incognito)); 1444 #endif 1445 1446 // Close the Incognito window and don't crash. 1447 chrome::CloseWindow(incognito); 1448 1449 #if !defined(OS_MACOSX) 1450 signal.Wait(); 1451 ExpectWindowCountAfterDownload(1); 1452 #endif 1453 1454 // Verify that the regular window does not have a download shelf. 1455 // On ChromeOS, the download panel is common to both profiles, so 1456 // it is still visible. 1457 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible()); 1458 1459 CheckDownload(browser(), file, file); 1460 } 1461 1462 // Download one file on-record, then download the same file off-record, and test 1463 // that the filename is deduplicated. The previous test tests for a specific 1464 // bug; this next test tests that filename deduplication happens independently 1465 // of DownloadManager/CDMD. 1466 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadTest_IncognitoRegular) { 1467 ASSERT_TRUE(test_server()->Start()); 1468 GURL url(test_server()->GetURL("files/downloads/a_zip_file.zip")); 1469 1470 // Read the origin file now so that we can compare the downloaded files to it 1471 // later. 1472 base::FilePath origin(OriginFile(base::FilePath(FILE_PATH_LITERAL( 1473 "downloads/a_zip_file.zip")))); 1474 ASSERT_TRUE(base::PathExists(origin)); 1475 int64 origin_file_size = 0; 1476 EXPECT_TRUE(file_util::GetFileSize(origin, &origin_file_size)); 1477 std::string original_contents; 1478 EXPECT_TRUE(file_util::ReadFileToString(origin, &original_contents)); 1479 1480 std::vector<DownloadItem*> download_items; 1481 GetDownloads(browser(), &download_items); 1482 ASSERT_TRUE(download_items.empty()); 1483 1484 // Download a file in the on-record browser and check that it was downloaded 1485 // correctly. 1486 DownloadAndWaitWithDisposition(browser(), 1487 url, 1488 CURRENT_TAB, 1489 ui_test_utils::BROWSER_TEST_NONE); 1490 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible()); 1491 GetDownloads(browser(), &download_items); 1492 ASSERT_EQ(1UL, download_items.size()); 1493 ASSERT_EQ(base::FilePath(FILE_PATH_LITERAL("a_zip_file.zip")), 1494 download_items[0]->GetTargetFilePath().BaseName()); 1495 ASSERT_TRUE(base::PathExists(download_items[0]->GetTargetFilePath())); 1496 EXPECT_TRUE(VerifyFile(download_items[0]->GetTargetFilePath(), 1497 original_contents, origin_file_size)); 1498 1499 // Setup an incognito window. 1500 Browser* incognito = CreateIncognitoBrowser(); 1501 ASSERT_TRUE(incognito); 1502 int window_count = BrowserList::GetInstance( 1503 browser()->host_desktop_type())->size(); 1504 EXPECT_EQ(2, window_count); 1505 incognito->profile()->GetPrefs()->SetFilePath( 1506 prefs::kDownloadDefaultDirectory, 1507 GetDownloadsDirectory()); 1508 incognito->profile()->GetPrefs()->SetFilePath( 1509 prefs::kSaveFileDefaultDirectory, 1510 GetDownloadsDirectory()); 1511 1512 download_items.clear(); 1513 GetDownloads(incognito, &download_items); 1514 ASSERT_TRUE(download_items.empty()); 1515 1516 // Download a file in the incognito browser and check that it was downloaded 1517 // correctly. 1518 DownloadAndWaitWithDisposition(incognito, 1519 url, 1520 CURRENT_TAB, 1521 ui_test_utils::BROWSER_TEST_NONE); 1522 EXPECT_TRUE(incognito->window()->IsDownloadShelfVisible()); 1523 GetDownloads(incognito, &download_items); 1524 ASSERT_EQ(1UL, download_items.size()); 1525 ASSERT_EQ(base::FilePath(FILE_PATH_LITERAL("a_zip_file (1).zip")), 1526 download_items[0]->GetTargetFilePath().BaseName()); 1527 ASSERT_TRUE(base::PathExists(download_items[0]->GetTargetFilePath())); 1528 EXPECT_TRUE(VerifyFile(download_items[0]->GetTargetFilePath(), 1529 original_contents, origin_file_size)); 1530 } 1531 1532 // Navigate to a new background page, but don't download. Confirm that the 1533 // download shelf is not visible and that we have two tabs. 1534 IN_PROC_BROWSER_TEST_F(DownloadTest, DontCloseNewTab1) { 1535 // Because it's an HTML link, it should open a web page rather than 1536 // downloading. 1537 base::FilePath file1(FILE_PATH_LITERAL("download-test2.html")); 1538 GURL url(URLRequestMockHTTPJob::GetMockUrl(file1)); 1539 1540 // Open a web page and wait. 1541 ui_test_utils::NavigateToURLWithDisposition( 1542 browser(), 1543 url, 1544 NEW_BACKGROUND_TAB, 1545 ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION); 1546 1547 // We should have two tabs now. 1548 EXPECT_EQ(2, browser()->tab_strip_model()->count()); 1549 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible()); 1550 } 1551 1552 // Download a file in a background tab. Verify that the tab is closed 1553 // automatically, and that the download shelf is visible in the current tab. 1554 IN_PROC_BROWSER_TEST_F(DownloadTest, CloseNewTab1) { 1555 // Download a file in a new background tab and wait. The tab is automatically 1556 // closed when the download begins. 1557 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib")); 1558 GURL url(URLRequestMockHTTPJob::GetMockUrl(file)); 1559 DownloadAndWaitWithDisposition( 1560 browser(), 1561 url, 1562 NEW_BACKGROUND_TAB, 1563 0); 1564 1565 // When the download finishes, we should still have one tab. 1566 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible()); 1567 EXPECT_EQ(1, browser()->tab_strip_model()->count()); 1568 1569 CheckDownload(browser(), file, file); 1570 } 1571 1572 // Open a web page in the current tab, then download a file in another tab via 1573 // a Javascript call. 1574 // Verify that we have 2 tabs, and the download shelf is visible in the current 1575 // tab. 1576 // 1577 // The download_page1.html page contains an openNew() function that opens a 1578 // tab and then downloads download-test1.lib. 1579 IN_PROC_BROWSER_TEST_F(DownloadTest, DontCloseNewTab2) { 1580 // Because it's an HTML link, it should open a web page rather than 1581 // downloading. 1582 base::FilePath file1(FILE_PATH_LITERAL("download_page1.html")); 1583 GURL url(URLRequestMockHTTPJob::GetMockUrl(file1)); 1584 1585 // Open a web page and wait. 1586 ui_test_utils::NavigateToURL(browser(), url); 1587 1588 // Download a file in a new tab and wait (via Javascript). 1589 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib")); 1590 DownloadAndWaitWithDisposition(browser(), 1591 GURL("javascript:openNew()"), 1592 CURRENT_TAB, 1593 ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB); 1594 1595 // When the download finishes, we should have two tabs. 1596 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible()); 1597 EXPECT_EQ(2, browser()->tab_strip_model()->count()); 1598 1599 CheckDownload(browser(), file, file); 1600 } 1601 1602 // Open a web page in the current tab, open another tab via a Javascript call, 1603 // then download a file in the new tab. 1604 // Verify that we have 2 tabs, and the download shelf is visible in the current 1605 // tab. 1606 // 1607 // The download_page2.html page contains an openNew() function that opens a 1608 // tab. 1609 IN_PROC_BROWSER_TEST_F(DownloadTest, DontCloseNewTab3) { 1610 // Because it's an HTML link, it should open a web page rather than 1611 // downloading. 1612 base::FilePath file1(FILE_PATH_LITERAL("download_page2.html")); 1613 GURL url1(URLRequestMockHTTPJob::GetMockUrl(file1)); 1614 1615 // Open a web page and wait. 1616 ui_test_utils::NavigateToURL(browser(), url1); 1617 1618 // Open a new tab and wait. 1619 ui_test_utils::NavigateToURLWithDisposition( 1620 browser(), 1621 GURL("javascript:openNew()"), 1622 CURRENT_TAB, 1623 ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB); 1624 1625 EXPECT_EQ(2, browser()->tab_strip_model()->count()); 1626 1627 // Download a file and wait. 1628 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib")); 1629 GURL url(URLRequestMockHTTPJob::GetMockUrl(file)); 1630 DownloadAndWaitWithDisposition(browser(), 1631 url, 1632 CURRENT_TAB, 1633 ui_test_utils::BROWSER_TEST_NONE); 1634 1635 // When the download finishes, we should have two tabs. 1636 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible()); 1637 EXPECT_EQ(2, browser()->tab_strip_model()->count()); 1638 1639 CheckDownload(browser(), file, file); 1640 } 1641 1642 // Open a web page in the current tab, then download a file via Javascript, 1643 // which will do so in a temporary tab. 1644 // Verify that we have 1 tab, and the download shelf is visible. 1645 // 1646 // The download_page3.html page contains an openNew() function that opens a 1647 // tab with download-test1.lib in the URL. When the URL is determined to be 1648 // a download, the tab is closed automatically. 1649 IN_PROC_BROWSER_TEST_F(DownloadTest, CloseNewTab2) { 1650 // Because it's an HTML link, it should open a web page rather than 1651 // downloading. 1652 base::FilePath file1(FILE_PATH_LITERAL("download_page3.html")); 1653 GURL url(URLRequestMockHTTPJob::GetMockUrl(file1)); 1654 1655 // Open a web page and wait. 1656 ui_test_utils::NavigateToURL(browser(), url); 1657 1658 // Download a file and wait. 1659 // The file to download is "download-test1.lib". 1660 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib")); 1661 DownloadAndWaitWithDisposition(browser(), 1662 GURL("javascript:openNew()"), 1663 CURRENT_TAB, 1664 ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB); 1665 1666 // When the download finishes, we should still have one tab. 1667 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible()); 1668 EXPECT_EQ(1, browser()->tab_strip_model()->count()); 1669 1670 CheckDownload(browser(), file, file); 1671 } 1672 1673 // Open a web page in the current tab, then call Javascript via a button to 1674 // download a file in a new tab, which is closed automatically when the 1675 // download begins. 1676 // Verify that we have 1 tab, and the download shelf is visible. 1677 // 1678 // The download_page4.html page contains a form with download-test1.lib as the 1679 // action. 1680 IN_PROC_BROWSER_TEST_F(DownloadTest, CloseNewTab3) { 1681 // Because it's an HTML link, it should open a web page rather than 1682 // downloading. 1683 base::FilePath file1(FILE_PATH_LITERAL("download_page4.html")); 1684 GURL url(URLRequestMockHTTPJob::GetMockUrl(file1)); 1685 1686 // Open a web page and wait. 1687 ui_test_utils::NavigateToURL(browser(), url); 1688 1689 // Download a file in a new tab and wait. The tab will automatically close 1690 // when the download begins. 1691 // The file to download is "download-test1.lib". 1692 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib")); 1693 DownloadAndWaitWithDisposition( 1694 browser(), 1695 GURL("javascript:document.getElementById('form').submit()"), 1696 CURRENT_TAB, 1697 ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB); 1698 1699 // When the download finishes, we should still have one tab. 1700 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible()); 1701 EXPECT_EQ(1, browser()->tab_strip_model()->count()); 1702 1703 CheckDownload(browser(), file, file); 1704 } 1705 1706 // Download a file in a new window. 1707 // Verify that we have 2 windows, and the download shelf is not visible in the 1708 // first window, but is visible in the second window. 1709 // Close the new window. 1710 // Verify that we have 1 window, and the download shelf is not visible. 1711 // 1712 // Regression test for http://crbug.com/44454 1713 IN_PROC_BROWSER_TEST_F(DownloadTest, NewWindow) { 1714 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib")); 1715 GURL url(URLRequestMockHTTPJob::GetMockUrl(file)); 1716 #if !defined(OS_MACOSX) 1717 // See below. 1718 Browser* first_browser = browser(); 1719 #endif 1720 1721 // Download a file in a new window and wait. 1722 DownloadAndWaitWithDisposition(browser(), 1723 url, 1724 NEW_WINDOW, 1725 ui_test_utils::BROWSER_TEST_NONE); 1726 1727 // When the download finishes, the download shelf SHOULD NOT be visible in 1728 // the first window. 1729 ExpectWindowCountAfterDownload(2); 1730 EXPECT_EQ(1, browser()->tab_strip_model()->count()); 1731 // Download shelf should close. Download panel stays open on ChromeOS. 1732 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible()); 1733 1734 // The download shelf SHOULD be visible in the second window. 1735 std::set<Browser*> original_browsers; 1736 original_browsers.insert(browser()); 1737 Browser* download_browser = 1738 ui_test_utils::GetBrowserNotInSet(original_browsers); 1739 ASSERT_TRUE(download_browser != NULL); 1740 EXPECT_NE(download_browser, browser()); 1741 EXPECT_EQ(1, download_browser->tab_strip_model()->count()); 1742 EXPECT_TRUE(download_browser->window()->IsDownloadShelfVisible()); 1743 1744 #if !defined(OS_MACOSX) 1745 // On Mac OS X, the UI window close is delayed until the outermost 1746 // message loop runs. So it isn't possible to get a BROWSER_CLOSED 1747 // notification inside of a test. 1748 content::WindowedNotificationObserver signal( 1749 chrome::NOTIFICATION_BROWSER_CLOSED, 1750 content::Source<Browser>(download_browser)); 1751 #endif 1752 1753 // Close the new window. 1754 chrome::CloseWindow(download_browser); 1755 1756 #if !defined(OS_MACOSX) 1757 signal.Wait(); 1758 EXPECT_EQ(first_browser, browser()); 1759 ExpectWindowCountAfterDownload(1); 1760 #endif 1761 1762 EXPECT_EQ(1, browser()->tab_strip_model()->count()); 1763 // Download shelf should close. Download panel stays open on ChromeOS. 1764 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible()); 1765 1766 CheckDownload(browser(), file, file); 1767 } 1768 1769 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadHistoryCheck) { 1770 GURL download_url(URLRequestSlowDownloadJob::kKnownSizeUrl); 1771 base::FilePath file(net::GenerateFileName(download_url, 1772 std::string(), 1773 std::string(), 1774 std::string(), 1775 std::string(), 1776 std::string())); 1777 1778 // We use the server so that we can get a redirect and test url_chain 1779 // persistence. 1780 ASSERT_TRUE(test_server()->Start()); 1781 GURL redirect_url = test_server()->GetURL( 1782 "server-redirect?" + download_url.spec()); 1783 1784 // Download the url and wait until the object has been stored. 1785 base::Time start(base::Time::Now()); 1786 HistoryObserver observer(browser()->profile()); 1787 observer.SetFilterCallback(base::Bind(&HasDataAndName)); 1788 ui_test_utils::NavigateToURL(browser(), redirect_url); 1789 observer.WaitForStored(); 1790 1791 // Get the details on what was stored into the history. 1792 scoped_ptr<std::vector<history::DownloadRow> > downloads_in_database; 1793 ASSERT_TRUE(DownloadsHistoryDataCollector( 1794 browser()->profile()).WaitForDownloadInfo(&downloads_in_database)); 1795 ASSERT_EQ(1u, downloads_in_database->size()); 1796 1797 // Confirm history storage is what you expect for a partially completed 1798 // slow download job. 1799 history::DownloadRow& row(downloads_in_database->at(0)); 1800 EXPECT_EQ(DestinationFile(browser(), file), row.target_path); 1801 EXPECT_EQ(DownloadTargetDeterminer::GetCrDownloadPath( 1802 DestinationFile(browser(), file)), 1803 row.current_path); 1804 ASSERT_EQ(2u, row.url_chain.size()); 1805 EXPECT_EQ(redirect_url.spec(), row.url_chain[0].spec()); 1806 EXPECT_EQ(download_url.spec(), row.url_chain[1].spec()); 1807 EXPECT_EQ(content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, row.danger_type); 1808 EXPECT_LE(start, row.start_time); 1809 EXPECT_EQ(URLRequestSlowDownloadJob::kFirstDownloadSize, row.received_bytes); 1810 EXPECT_EQ(URLRequestSlowDownloadJob::kFirstDownloadSize 1811 + URLRequestSlowDownloadJob::kSecondDownloadSize, row.total_bytes); 1812 EXPECT_EQ(content::DownloadItem::IN_PROGRESS, row.state); 1813 EXPECT_FALSE(row.opened); 1814 1815 // Finish the download. We're ok relying on the history to be flushed 1816 // at this point as our queries will be behind the history updates 1817 // invoked by completion. 1818 scoped_ptr<content::DownloadTestObserver> download_observer( 1819 CreateWaiter(browser(), 1)); 1820 ui_test_utils::NavigateToURL(browser(), 1821 GURL(URLRequestSlowDownloadJob::kErrorDownloadUrl)); 1822 download_observer->WaitForFinished(); 1823 EXPECT_EQ(1u, download_observer->NumDownloadsSeenInState( 1824 DownloadItem::INTERRUPTED)); 1825 base::Time end(base::Time::Now()); 1826 1827 // Get what was stored in the history. 1828 ASSERT_TRUE(DownloadsHistoryDataCollector( 1829 browser()->profile()).WaitForDownloadInfo(&downloads_in_database)); 1830 ASSERT_EQ(1u, downloads_in_database->size()); 1831 1832 // Confirm history storage is what you expect for an interrupted slow download 1833 // job. The download isn't continuable, so there's no intermediate file. 1834 history::DownloadRow& row1(downloads_in_database->at(0)); 1835 EXPECT_EQ(DestinationFile(browser(), file), row1.target_path); 1836 EXPECT_TRUE(row1.current_path.empty()); 1837 ASSERT_EQ(2u, row1.url_chain.size()); 1838 EXPECT_EQ(redirect_url.spec(), row1.url_chain[0].spec()); 1839 EXPECT_EQ(download_url.spec(), row1.url_chain[1].spec()); 1840 EXPECT_EQ(content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS, row1.danger_type); 1841 EXPECT_LE(start, row1.start_time); 1842 EXPECT_GE(end, row1.end_time); 1843 EXPECT_EQ(URLRequestSlowDownloadJob::kFirstDownloadSize, 1844 row1.received_bytes); 1845 EXPECT_EQ(URLRequestSlowDownloadJob::kFirstDownloadSize 1846 + URLRequestSlowDownloadJob::kSecondDownloadSize, row1.total_bytes); 1847 EXPECT_EQ(content::DownloadItem::INTERRUPTED, row1.state); 1848 EXPECT_EQ(content::DOWNLOAD_INTERRUPT_REASON_NETWORK_FAILED, 1849 row1.interrupt_reason); 1850 EXPECT_FALSE(row1.opened); 1851 } 1852 1853 // Make sure a dangerous file shows up properly in the history. 1854 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadHistoryDangerCheck) { 1855 #if defined(OS_WIN) && defined(USE_ASH) 1856 // Disable this test in Metro+Ash for now (http://crbug.com/262796). 1857 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshBrowserTests)) 1858 return; 1859 #endif 1860 1861 // .swf file so that it's dangerous on all platforms (including CrOS). 1862 base::FilePath file(FILE_PATH_LITERAL("downloads/dangerous/dangerous.swf")); 1863 GURL download_url(URLRequestMockHTTPJob::GetMockUrl(file)); 1864 1865 // Download the url and wait until the object has been stored. 1866 scoped_ptr<content::DownloadTestObserver> download_observer( 1867 new content::DownloadTestObserverTerminal( 1868 DownloadManagerForBrowser(browser()), 1, 1869 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_IGNORE)); 1870 base::Time start(base::Time::Now()); 1871 HistoryObserver observer(browser()->profile()); 1872 observer.SetFilterCallback(base::Bind(&HasDataAndName)); 1873 ui_test_utils::NavigateToURL(browser(), download_url); 1874 observer.WaitForStored(); 1875 1876 // Get the details on what was stored into the history. 1877 scoped_ptr<std::vector<history::DownloadRow> > downloads_in_database; 1878 ASSERT_TRUE(DownloadsHistoryDataCollector( 1879 browser()->profile()).WaitForDownloadInfo(&downloads_in_database)); 1880 ASSERT_EQ(1u, downloads_in_database->size()); 1881 1882 // Confirm history storage is what you expect for an unvalidated 1883 // dangerous file. 1884 history::DownloadRow& row(downloads_in_database->at(0)); 1885 EXPECT_EQ(DestinationFile(browser(), file), row.target_path); 1886 EXPECT_NE(DownloadTargetDeterminer::GetCrDownloadPath( 1887 DestinationFile(browser(), file)), 1888 row.current_path); 1889 EXPECT_EQ(content::DOWNLOAD_DANGER_TYPE_DANGEROUS_FILE, row.danger_type); 1890 EXPECT_LE(start, row.start_time); 1891 EXPECT_EQ(content::DownloadItem::IN_PROGRESS, row.state); 1892 EXPECT_FALSE(row.opened); 1893 1894 // Validate the download and wait for it to finish. 1895 std::vector<DownloadItem*> downloads; 1896 DownloadManagerForBrowser(browser())->GetAllDownloads(&downloads); 1897 ASSERT_EQ(1u, downloads.size()); 1898 downloads[0]->ValidateDangerousDownload(); 1899 download_observer->WaitForFinished(); 1900 1901 // Get history details and confirm it's what you expect. 1902 downloads_in_database->clear(); 1903 ASSERT_TRUE(DownloadsHistoryDataCollector( 1904 browser()->profile()).WaitForDownloadInfo(&downloads_in_database)); 1905 ASSERT_EQ(1u, downloads_in_database->size()); 1906 history::DownloadRow& row1(downloads_in_database->at(0)); 1907 EXPECT_EQ(DestinationFile(browser(), file), row1.target_path); 1908 EXPECT_EQ(DestinationFile(browser(), file), row1.current_path); 1909 EXPECT_EQ(content::DOWNLOAD_DANGER_TYPE_USER_VALIDATED, row1.danger_type); 1910 EXPECT_LE(start, row1.start_time); 1911 EXPECT_EQ(content::DownloadItem::COMPLETE, row1.state); 1912 EXPECT_FALSE(row1.opened); 1913 // Not checking file size--not relevant to the point of the test, and 1914 // the file size is actually different on Windows and other platforms, 1915 // because for source control simplicity it's actually a text file, and 1916 // there are CRLF transformations for those files. 1917 } 1918 1919 IN_PROC_BROWSER_TEST_F(DownloadTest, PRE_DownloadTest_History) { 1920 // Download a file and wait for it to be stored. 1921 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib")); 1922 GURL download_url(URLRequestMockHTTPJob::GetMockUrl(file)); 1923 HistoryObserver observer(browser()->profile()); 1924 DownloadAndWait(browser(), download_url); 1925 observer.WaitForStored(); 1926 HistoryServiceFactory::GetForProfile( 1927 browser()->profile(), Profile::IMPLICIT_ACCESS)->FlushForTest( 1928 base::Bind(&base::MessageLoop::Quit, 1929 base::Unretained(base::MessageLoop::current()->current()))); 1930 content::RunMessageLoop(); 1931 } 1932 1933 #if defined(OS_CHROMEOS) 1934 #define MAYBE_DownloadTest_History DISABLED_DownloadTest_History 1935 #else 1936 #define MAYBE_DownloadTest_History DownloadTest_History 1937 #endif 1938 IN_PROC_BROWSER_TEST_F(DownloadTest, MAYBE_DownloadTest_History) { 1939 // This starts up right after PRE_DownloadTest_History and shares the same 1940 // profile directory. 1941 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib")); 1942 GURL download_url(URLRequestMockHTTPJob::GetMockUrl(file)); 1943 std::vector<DownloadItem*> downloads; 1944 content::DownloadManager* manager = DownloadManagerForBrowser(browser()); 1945 1946 // Wait for the history to be loaded with a single DownloadItem. Check that 1947 // it's the file that was downloaded in PRE_DownloadTest_History. 1948 CreatedObserver created_observer(manager); 1949 created_observer.Wait(); 1950 manager->GetAllDownloads(&downloads); 1951 ASSERT_EQ(1UL, downloads.size()); 1952 DownloadItem* item = downloads[0]; 1953 EXPECT_EQ(file.value(), item->GetFullPath().BaseName().value()); 1954 EXPECT_EQ(file.value(), item->GetTargetFilePath().BaseName().value()); 1955 EXPECT_EQ(download_url, item->GetURL()); 1956 // The following are set by download-test1.lib.mock-http-headers. 1957 std::string etag = item->GetETag(); 1958 TrimWhitespaceASCII(etag, TRIM_ALL, &etag); 1959 EXPECT_EQ("abracadabra", etag); 1960 1961 std::string last_modified = item->GetLastModifiedTime(); 1962 TrimWhitespaceASCII(last_modified, TRIM_ALL, &last_modified); 1963 EXPECT_EQ("Mon, 13 Nov 2006 20:31:09 GMT", last_modified); 1964 } 1965 1966 // Test for crbug.com/14505. This tests that chrome:// urls are still functional 1967 // after download of a file while viewing another chrome://. 1968 IN_PROC_BROWSER_TEST_F(DownloadTest, ChromeURLAfterDownload) { 1969 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib")); 1970 GURL download_url(URLRequestMockHTTPJob::GetMockUrl(file)); 1971 GURL flags_url(chrome::kChromeUIFlagsURL); 1972 GURL extensions_url(chrome::kChromeUIExtensionsFrameURL); 1973 1974 ui_test_utils::NavigateToURL(browser(), flags_url); 1975 DownloadAndWait(browser(), download_url); 1976 ui_test_utils::NavigateToURL(browser(), extensions_url); 1977 WebContents* contents = 1978 browser()->tab_strip_model()->GetActiveWebContents(); 1979 ASSERT_TRUE(contents); 1980 bool webui_responded = false; 1981 EXPECT_TRUE(content::ExecuteScriptAndExtractBool( 1982 contents, 1983 "window.domAutomationController.send(window.webuiResponded);", 1984 &webui_responded)); 1985 EXPECT_TRUE(webui_responded); 1986 } 1987 1988 // Test for crbug.com/12745. This tests that if a download is initiated from 1989 // a chrome:// page that has registered and onunload handler, the browser 1990 // will be able to close. 1991 IN_PROC_BROWSER_TEST_F(DownloadTest, BrowserCloseAfterDownload) { 1992 GURL downloads_url(chrome::kChromeUIFlagsURL); 1993 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib")); 1994 GURL download_url(URLRequestMockHTTPJob::GetMockUrl(file)); 1995 1996 ui_test_utils::NavigateToURL(browser(), downloads_url); 1997 WebContents* contents = browser()->tab_strip_model()->GetActiveWebContents(); 1998 ASSERT_TRUE(contents); 1999 bool result = false; 2000 EXPECT_TRUE(content::ExecuteScriptAndExtractBool( 2001 contents, 2002 "window.onunload = function() { var do_nothing = 0; }; " 2003 "window.domAutomationController.send(true);", 2004 &result)); 2005 EXPECT_TRUE(result); 2006 2007 DownloadAndWait(browser(), download_url); 2008 2009 content::WindowedNotificationObserver signal( 2010 chrome::NOTIFICATION_BROWSER_CLOSED, 2011 content::Source<Browser>(browser())); 2012 chrome::CloseWindow(browser()); 2013 signal.Wait(); 2014 } 2015 2016 // Test to make sure the 'download' attribute in anchor tag is respected. 2017 IN_PROC_BROWSER_TEST_F(DownloadTest, AnchorDownloadTag) { 2018 base::FilePath file(FILE_PATH_LITERAL("download-anchor-attrib.html")); 2019 GURL url(URLRequestMockHTTPJob::GetMockUrl(file)); 2020 2021 // Create a download, wait until it's complete, and confirm 2022 // we're in the expected state. 2023 scoped_ptr<content::DownloadTestObserver> observer( 2024 CreateWaiter(browser(), 1)); 2025 ui_test_utils::NavigateToURL(browser(), url); 2026 observer->WaitForFinished(); 2027 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::COMPLETE)); 2028 CheckDownloadStates(1, DownloadItem::COMPLETE); 2029 2030 // Confirm the downloaded data exists. 2031 base::FilePath downloaded_file = GetDownloadDirectory(browser()); 2032 downloaded_file = downloaded_file.Append(FILE_PATH_LITERAL("a_red_dot.png")); 2033 EXPECT_TRUE(base::PathExists(downloaded_file)); 2034 } 2035 2036 // Test to make sure auto-open works. 2037 IN_PROC_BROWSER_TEST_F(DownloadTest, AutoOpen) { 2038 base::FilePath file(FILE_PATH_LITERAL("download-autoopen.txt")); 2039 GURL url(URLRequestMockHTTPJob::GetMockUrl(file)); 2040 2041 ASSERT_TRUE( 2042 GetDownloadPrefs(browser())->EnableAutoOpenBasedOnExtension(file)); 2043 2044 DownloadAndWait(browser(), url); 2045 2046 // Find the download and confirm it was opened. 2047 std::vector<DownloadItem*> downloads; 2048 DownloadManagerForBrowser(browser())->GetAllDownloads(&downloads); 2049 ASSERT_EQ(1u, downloads.size()); 2050 EXPECT_EQ(DownloadItem::COMPLETE, downloads[0]->GetState()); 2051 2052 // Unfortunately, this will block forever, causing a timeout, if 2053 // the download is never opened. 2054 content::DownloadUpdatedObserver( 2055 downloads[0], base::Bind(&WasAutoOpened)).WaitForEvent(); 2056 EXPECT_TRUE(downloads[0]->GetOpened()); // Confirm it anyway. 2057 2058 // As long as we're here, confirmed everything else is good. 2059 EXPECT_EQ(1, browser()->tab_strip_model()->count()); 2060 CheckDownload(browser(), file, file); 2061 // Download shelf should close. Download panel stays open on ChromeOS. 2062 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible()); 2063 } 2064 2065 // Download an extension. Expect a dangerous download warning. 2066 // Deny the download. 2067 IN_PROC_BROWSER_TEST_F(DownloadTest, CrxDenyInstall) { 2068 FeatureSwitch::ScopedOverride enable_easy_off_store_install( 2069 FeatureSwitch::easy_off_store_install(), true); 2070 2071 GURL extension_url(URLRequestMockHTTPJob::GetMockUrl(kGoodCrxPath)); 2072 2073 scoped_ptr<content::DownloadTestObserver> observer( 2074 DangerousDownloadWaiter( 2075 browser(), 1, 2076 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_DENY)); 2077 ui_test_utils::NavigateToURL(browser(), extension_url); 2078 2079 observer->WaitForFinished(); 2080 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::CANCELLED)); 2081 EXPECT_EQ(1u, observer->NumDangerousDownloadsSeen()); 2082 2083 // Download shelf should close. 2084 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible()); 2085 2086 // Check that the CRX is not installed. 2087 ExtensionService* extension_service = extensions::ExtensionSystem::Get( 2088 browser()->profile())->extension_service(); 2089 ASSERT_FALSE(extension_service->GetExtensionById(kGoodCrxId, false)); 2090 } 2091 2092 // Download an extension. Expect a dangerous download warning. 2093 // Allow the download, deny the install. 2094 IN_PROC_BROWSER_TEST_F(DownloadTest, CrxInstallDenysPermissions) { 2095 FeatureSwitch::ScopedOverride enable_easy_off_store_install( 2096 FeatureSwitch::easy_off_store_install(), true); 2097 2098 GURL extension_url(URLRequestMockHTTPJob::GetMockUrl(kGoodCrxPath)); 2099 2100 // Install a mock install UI that simulates a user denying permission to 2101 // finish the install. 2102 download_crx_util::SetMockInstallPromptForTesting( 2103 scoped_ptr<ExtensionInstallPrompt>( 2104 new MockAbortExtensionInstallPrompt())); 2105 2106 scoped_ptr<content::DownloadTestObserver> observer( 2107 DangerousDownloadWaiter( 2108 browser(), 1, 2109 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_ACCEPT)); 2110 ui_test_utils::NavigateToURL(browser(), extension_url); 2111 2112 observer->WaitForFinished(); 2113 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::COMPLETE)); 2114 CheckDownloadStates(1, DownloadItem::COMPLETE); 2115 EXPECT_EQ(1u, observer->NumDangerousDownloadsSeen()); 2116 2117 // Download shelf should close from auto-open. 2118 content::DownloadManager::DownloadVector downloads; 2119 DownloadManagerForBrowser(browser())->GetAllDownloads(&downloads); 2120 ASSERT_EQ(1u, downloads.size()); 2121 content::DownloadUpdatedObserver( 2122 downloads[0], base::Bind(&WasAutoOpened)).WaitForEvent(); 2123 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible()); 2124 2125 // Check that the extension was not installed. 2126 ExtensionService* extension_service = extensions::ExtensionSystem::Get( 2127 browser()->profile())->extension_service(); 2128 ASSERT_FALSE(extension_service->GetExtensionById(kGoodCrxId, false)); 2129 } 2130 2131 // Download an extension. Expect a dangerous download warning. 2132 // Allow the download, and the install. 2133 IN_PROC_BROWSER_TEST_F(DownloadTest, CrxInstallAcceptPermissions) { 2134 FeatureSwitch::ScopedOverride enable_easy_off_store_install( 2135 FeatureSwitch::easy_off_store_install(), true); 2136 2137 GURL extension_url(URLRequestMockHTTPJob::GetMockUrl(kGoodCrxPath)); 2138 2139 // Install a mock install UI that simulates a user allowing permission to 2140 // finish the install. 2141 SetAllowMockInstallPrompt(); 2142 2143 scoped_ptr<content::DownloadTestObserver> observer( 2144 DangerousDownloadWaiter( 2145 browser(), 1, 2146 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_ACCEPT)); 2147 ui_test_utils::NavigateToURL(browser(), extension_url); 2148 2149 observer->WaitForFinished(); 2150 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::COMPLETE)); 2151 CheckDownloadStates(1, DownloadItem::COMPLETE); 2152 EXPECT_EQ(1u, observer->NumDangerousDownloadsSeen()); 2153 2154 // Download shelf should close from auto-open. 2155 content::DownloadManager::DownloadVector downloads; 2156 DownloadManagerForBrowser(browser())->GetAllDownloads(&downloads); 2157 ASSERT_EQ(1u, downloads.size()); 2158 content::DownloadUpdatedObserver( 2159 downloads[0], base::Bind(&WasAutoOpened)).WaitForEvent(); 2160 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible()); 2161 2162 // Check that the extension was installed. 2163 ExtensionService* extension_service = extensions::ExtensionSystem::Get( 2164 browser()->profile())->extension_service(); 2165 ASSERT_TRUE(extension_service->GetExtensionById(kGoodCrxId, false)); 2166 } 2167 2168 // Test installing a CRX that fails integrity checks. 2169 IN_PROC_BROWSER_TEST_F(DownloadTest, CrxInvalid) { 2170 base::FilePath file(FILE_PATH_LITERAL("extensions/bad_signature.crx")); 2171 GURL extension_url(URLRequestMockHTTPJob::GetMockUrl(file)); 2172 2173 // Install a mock install UI that simulates a user allowing permission to 2174 // finish the install, and dismisses any error message. We check that the 2175 // install failed below. 2176 SetAllowMockInstallPrompt(); 2177 2178 scoped_ptr<content::DownloadTestObserver> observer( 2179 DangerousDownloadWaiter( 2180 browser(), 1, 2181 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_ACCEPT)); 2182 ui_test_utils::NavigateToURL(browser(), extension_url); 2183 2184 observer->WaitForFinished(); 2185 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::COMPLETE)); 2186 CheckDownloadStates(1, DownloadItem::COMPLETE); 2187 2188 // Check that the extension was not installed. 2189 ExtensionService* extension_service = extensions::ExtensionSystem::Get( 2190 browser()->profile())->extension_service(); 2191 ASSERT_FALSE(extension_service->GetExtensionById(kGoodCrxId, false)); 2192 } 2193 2194 // Install a large (100kb) theme. 2195 IN_PROC_BROWSER_TEST_F(DownloadTest, CrxLargeTheme) { 2196 FeatureSwitch::ScopedOverride enable_easy_off_store_install( 2197 FeatureSwitch::easy_off_store_install(), true); 2198 2199 GURL extension_url(URLRequestMockHTTPJob::GetMockUrl(kLargeThemePath)); 2200 2201 // Install a mock install UI that simulates a user allowing permission to 2202 // finish the install. 2203 SetAllowMockInstallPrompt(); 2204 2205 scoped_ptr<content::DownloadTestObserver> observer( 2206 DangerousDownloadWaiter( 2207 browser(), 1, 2208 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_ACCEPT)); 2209 ui_test_utils::NavigateToURL(browser(), extension_url); 2210 2211 observer->WaitForFinished(); 2212 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::COMPLETE)); 2213 CheckDownloadStates(1, DownloadItem::COMPLETE); 2214 EXPECT_EQ(1u, observer->NumDangerousDownloadsSeen()); 2215 2216 // Download shelf should close from auto-open. 2217 content::DownloadManager::DownloadVector downloads; 2218 DownloadManagerForBrowser(browser())->GetAllDownloads(&downloads); 2219 ASSERT_EQ(1u, downloads.size()); 2220 content::DownloadUpdatedObserver( 2221 downloads[0], base::Bind(&WasAutoOpened)).WaitForEvent(); 2222 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible()); 2223 2224 // Check that the extension was installed. 2225 ExtensionService* extension_service = extensions::ExtensionSystem::Get( 2226 browser()->profile())->extension_service(); 2227 ASSERT_TRUE(extension_service->GetExtensionById(kLargeThemeCrxId, false)); 2228 } 2229 2230 // Tests for download initiation functions. 2231 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadUrl) { 2232 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib")); 2233 GURL url(URLRequestMockHTTPJob::GetMockUrl(file)); 2234 2235 // DownloadUrl always prompts; return acceptance of whatever it prompts. 2236 EnableFileChooser(true); 2237 2238 WebContents* web_contents = 2239 browser()->tab_strip_model()->GetActiveWebContents(); 2240 ASSERT_TRUE(web_contents); 2241 2242 content::DownloadTestObserver* observer( 2243 new content::DownloadTestObserverTerminal( 2244 DownloadManagerForBrowser(browser()), 1, 2245 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL)); 2246 scoped_ptr<DownloadUrlParameters> params( 2247 DownloadUrlParameters::FromWebContents(web_contents, url)); 2248 params->set_prompt(true); 2249 DownloadManagerForBrowser(browser())->DownloadUrl(params.Pass()); 2250 observer->WaitForFinished(); 2251 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::COMPLETE)); 2252 CheckDownloadStates(1, DownloadItem::COMPLETE); 2253 EXPECT_TRUE(DidShowFileChooser()); 2254 2255 // Check state. 2256 EXPECT_EQ(1, browser()->tab_strip_model()->count()); 2257 ASSERT_TRUE(CheckDownload(browser(), file, file)); 2258 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible()); 2259 } 2260 2261 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadUrlToPath) { 2262 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib")); 2263 GURL url(URLRequestMockHTTPJob::GetMockUrl(file)); 2264 2265 WebContents* web_contents = 2266 browser()->tab_strip_model()->GetActiveWebContents(); 2267 ASSERT_TRUE(web_contents); 2268 2269 base::ScopedTempDir other_directory; 2270 ASSERT_TRUE(other_directory.CreateUniqueTempDir()); 2271 base::FilePath target_file_full_path 2272 = other_directory.path().Append(file.BaseName()); 2273 content::DownloadTestObserver* observer(CreateWaiter(browser(), 1)); 2274 scoped_ptr<DownloadUrlParameters> params( 2275 DownloadUrlParameters::FromWebContents(web_contents, url)); 2276 params->set_file_path(target_file_full_path); 2277 DownloadManagerForBrowser(browser())->DownloadUrl(params.Pass()); 2278 observer->WaitForFinished(); 2279 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::COMPLETE)); 2280 2281 // Check state. 2282 EXPECT_EQ(1, browser()->tab_strip_model()->count()); 2283 ASSERT_TRUE(CheckDownloadFullPaths(browser(), 2284 target_file_full_path, 2285 OriginFile(file))); 2286 2287 // Temporary are treated as auto-opened, and after that open won't be 2288 // visible; wait for auto-open and confirm not visible. 2289 std::vector<DownloadItem*> downloads; 2290 DownloadManagerForBrowser(browser())->GetAllDownloads(&downloads); 2291 ASSERT_EQ(1u, downloads.size()); 2292 content::DownloadUpdatedObserver( 2293 downloads[0], base::Bind(&WasAutoOpened)).WaitForEvent(); 2294 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible()); 2295 } 2296 2297 IN_PROC_BROWSER_TEST_F(DownloadTest, SavePageNonHTMLViaGet) { 2298 // Do initial setup. 2299 ASSERT_TRUE(test_server()->Start()); 2300 EnableFileChooser(true); 2301 std::vector<DownloadItem*> download_items; 2302 GetDownloads(browser(), &download_items); 2303 ASSERT_TRUE(download_items.empty()); 2304 2305 // Navigate to a non-HTML resource. The resource also has 2306 // Cache-Control: no-cache set, which normally requires revalidation 2307 // each time. 2308 GURL url = test_server()->GetURL("files/downloads/image.jpg"); 2309 ASSERT_TRUE(url.is_valid()); 2310 ui_test_utils::NavigateToURL(browser(), url); 2311 2312 // Stop the test server, and then try to save the page. If cache validation 2313 // is not bypassed then this will fail since the server is no longer 2314 // reachable. 2315 ASSERT_TRUE(test_server()->Stop()); 2316 scoped_ptr<content::DownloadTestObserver> waiter( 2317 new content::DownloadTestObserverTerminal( 2318 DownloadManagerForBrowser(browser()), 1, 2319 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL)); 2320 chrome::SavePage(browser()); 2321 waiter->WaitForFinished(); 2322 EXPECT_EQ(1u, waiter->NumDownloadsSeenInState(DownloadItem::COMPLETE)); 2323 CheckDownloadStates(1, DownloadItem::COMPLETE); 2324 2325 // Validate that the correct file was downloaded. 2326 GetDownloads(browser(), &download_items); 2327 EXPECT_TRUE(DidShowFileChooser()); 2328 ASSERT_EQ(1u, download_items.size()); 2329 ASSERT_EQ(url, download_items[0]->GetOriginalUrl()); 2330 2331 // Try to download it via a context menu. 2332 scoped_ptr<content::DownloadTestObserver> waiter_context_menu( 2333 new content::DownloadTestObserverTerminal( 2334 DownloadManagerForBrowser(browser()), 1, 2335 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL)); 2336 content::ContextMenuParams context_menu_params; 2337 context_menu_params.media_type = WebKit::WebContextMenuData::MediaTypeImage; 2338 context_menu_params.src_url = url; 2339 context_menu_params.page_url = url; 2340 TestRenderViewContextMenu menu( 2341 browser()->tab_strip_model()->GetActiveWebContents(), 2342 context_menu_params); 2343 menu.Init(); 2344 menu.ExecuteCommand(IDC_CONTENT_CONTEXT_SAVEIMAGEAS, 0); 2345 waiter_context_menu->WaitForFinished(); 2346 EXPECT_EQ( 2347 1u, waiter_context_menu->NumDownloadsSeenInState(DownloadItem::COMPLETE)); 2348 CheckDownloadStates(2, DownloadItem::COMPLETE); 2349 2350 // Validate that the correct file was downloaded via the context menu. 2351 download_items.clear(); 2352 GetDownloads(browser(), &download_items); 2353 EXPECT_TRUE(DidShowFileChooser()); 2354 ASSERT_EQ(2u, download_items.size()); 2355 ASSERT_EQ(url, download_items[0]->GetOriginalUrl()); 2356 ASSERT_EQ(url, download_items[1]->GetOriginalUrl()); 2357 } 2358 2359 IN_PROC_BROWSER_TEST_F(DownloadTest, SavePageNonHTMLViaPost) { 2360 // Do initial setup. 2361 ASSERT_TRUE(test_server()->Start()); 2362 EnableFileChooser(true); 2363 std::vector<DownloadItem*> download_items; 2364 GetDownloads(browser(), &download_items); 2365 ASSERT_TRUE(download_items.empty()); 2366 2367 // Navigate to a form page. 2368 GURL form_url = test_server()->GetURL( 2369 "files/downloads/form_page_to_post.html"); 2370 ASSERT_TRUE(form_url.is_valid()); 2371 ui_test_utils::NavigateToURL(browser(), form_url); 2372 2373 // Submit the form. This will send a POST reqeuest, and the response is a 2374 // JPEG image. The resource also has Cache-Control: no-cache set, 2375 // which normally requires revalidation each time. 2376 GURL jpeg_url = test_server()->GetURL("files/post/downloads/image.jpg"); 2377 ASSERT_TRUE(jpeg_url.is_valid()); 2378 WebContents* web_contents = 2379 browser()->tab_strip_model()->GetActiveWebContents(); 2380 ASSERT_TRUE(web_contents != NULL); 2381 content::WindowedNotificationObserver observer( 2382 content::NOTIFICATION_NAV_ENTRY_COMMITTED, 2383 content::Source<content::NavigationController>( 2384 &web_contents->GetController())); 2385 content::RenderViewHost* render_view_host = web_contents->GetRenderViewHost(); 2386 ASSERT_TRUE(render_view_host != NULL); 2387 render_view_host->ExecuteJavascriptInWebFrame( 2388 string16(), ASCIIToUTF16("SubmitForm()")); 2389 observer.Wait(); 2390 EXPECT_EQ(jpeg_url, web_contents->GetURL()); 2391 2392 // Stop the test server, and then try to save the page. If cache validation 2393 // is not bypassed then this will fail since the server is no longer 2394 // reachable. This will also fail if it tries to be retrieved via "GET" 2395 // rather than "POST". 2396 ASSERT_TRUE(test_server()->Stop()); 2397 scoped_ptr<content::DownloadTestObserver> waiter( 2398 new content::DownloadTestObserverTerminal( 2399 DownloadManagerForBrowser(browser()), 1, 2400 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL)); 2401 chrome::SavePage(browser()); 2402 waiter->WaitForFinished(); 2403 EXPECT_EQ(1u, waiter->NumDownloadsSeenInState(DownloadItem::COMPLETE)); 2404 CheckDownloadStates(1, DownloadItem::COMPLETE); 2405 2406 // Validate that the correct file was downloaded. 2407 GetDownloads(browser(), &download_items); 2408 EXPECT_TRUE(DidShowFileChooser()); 2409 ASSERT_EQ(1u, download_items.size()); 2410 ASSERT_EQ(jpeg_url, download_items[0]->GetOriginalUrl()); 2411 2412 // Try to download it via a context menu. 2413 scoped_ptr<content::DownloadTestObserver> waiter_context_menu( 2414 new content::DownloadTestObserverTerminal( 2415 DownloadManagerForBrowser(browser()), 1, 2416 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL)); 2417 content::ContextMenuParams context_menu_params; 2418 context_menu_params.media_type = WebKit::WebContextMenuData::MediaTypeImage; 2419 context_menu_params.src_url = jpeg_url; 2420 context_menu_params.page_url = jpeg_url; 2421 TestRenderViewContextMenu menu(web_contents, context_menu_params); 2422 menu.Init(); 2423 menu.ExecuteCommand(IDC_CONTENT_CONTEXT_SAVEIMAGEAS, 0); 2424 waiter_context_menu->WaitForFinished(); 2425 EXPECT_EQ( 2426 1u, waiter_context_menu->NumDownloadsSeenInState(DownloadItem::COMPLETE)); 2427 CheckDownloadStates(2, DownloadItem::COMPLETE); 2428 2429 // Validate that the correct file was downloaded via the context menu. 2430 download_items.clear(); 2431 GetDownloads(browser(), &download_items); 2432 EXPECT_TRUE(DidShowFileChooser()); 2433 ASSERT_EQ(2u, download_items.size()); 2434 ASSERT_EQ(jpeg_url, download_items[0]->GetOriginalUrl()); 2435 ASSERT_EQ(jpeg_url, download_items[1]->GetOriginalUrl()); 2436 } 2437 2438 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadErrorsServer) { 2439 DownloadInfo download_info[] = { 2440 { // Normal navigated download. 2441 "a_zip_file.zip", 2442 DOWNLOAD_NAVIGATE, 2443 content::DOWNLOAD_INTERRUPT_REASON_NONE, 2444 true, 2445 false 2446 }, 2447 { // Normal direct download. 2448 "a_zip_file.zip", 2449 DOWNLOAD_DIRECT, 2450 content::DOWNLOAD_INTERRUPT_REASON_NONE, 2451 true, 2452 false 2453 }, 2454 { // Direct download with 404 error. 2455 "there_IS_no_spoon.zip", 2456 DOWNLOAD_DIRECT, 2457 content::DOWNLOAD_INTERRUPT_REASON_SERVER_BAD_CONTENT, 2458 true, 2459 false 2460 }, 2461 { // Navigated download with 404 error. 2462 "there_IS_no_spoon.zip", 2463 DOWNLOAD_NAVIGATE, 2464 content::DOWNLOAD_INTERRUPT_REASON_SERVER_BAD_CONTENT, 2465 false, 2466 false 2467 }, 2468 { // Direct download with 400 error. 2469 "zip_file_not_found.zip", 2470 DOWNLOAD_DIRECT, 2471 content::DOWNLOAD_INTERRUPT_REASON_SERVER_FAILED, 2472 true, 2473 false 2474 }, 2475 { // Navigated download with 400 error. 2476 "zip_file_not_found.zip", 2477 DOWNLOAD_NAVIGATE, 2478 content::DOWNLOAD_INTERRUPT_REASON_SERVER_FAILED, 2479 false, 2480 false 2481 } 2482 }; 2483 2484 DownloadFilesCheckErrors(ARRAYSIZE_UNSAFE(download_info), download_info); 2485 } 2486 2487 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadErrorsFile) { 2488 FileErrorInjectInfo error_info[] = { 2489 { // Navigated download with injected "Disk full" error in Initialize(). 2490 { "a_zip_file.zip", 2491 DOWNLOAD_NAVIGATE, 2492 content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE, 2493 1 2494 }, 2495 { 2496 "", 2497 content::TestFileErrorInjector::FILE_OPERATION_INITIALIZE, 2498 0, 2499 content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE, 2500 } 2501 }, 2502 { // Direct download with injected "Disk full" error in Initialize(). 2503 { "a_zip_file.zip", 2504 DOWNLOAD_DIRECT, 2505 content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE, 2506 1 2507 }, 2508 { 2509 "", 2510 content::TestFileErrorInjector::FILE_OPERATION_INITIALIZE, 2511 0, 2512 content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE, 2513 } 2514 }, 2515 { // Navigated download with injected "Disk full" error in Write(). 2516 { "a_zip_file.zip", 2517 DOWNLOAD_NAVIGATE, 2518 content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE, 2519 1 2520 }, 2521 { 2522 "", 2523 content::TestFileErrorInjector::FILE_OPERATION_WRITE, 2524 0, 2525 content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE, 2526 } 2527 }, 2528 { // Direct download with injected "Disk full" error in Write(). 2529 { "a_zip_file.zip", 2530 DOWNLOAD_DIRECT, 2531 content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE, 2532 1 2533 }, 2534 { 2535 "", 2536 content::TestFileErrorInjector::FILE_OPERATION_WRITE, 2537 0, 2538 content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE, 2539 } 2540 }, 2541 { // Navigated download with injected "Failed" error in Initialize(). 2542 { "a_zip_file.zip", 2543 DOWNLOAD_NAVIGATE, 2544 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED, 2545 1 2546 }, 2547 { 2548 "", 2549 content::TestFileErrorInjector::FILE_OPERATION_INITIALIZE, 2550 0, 2551 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED, 2552 } 2553 }, 2554 { // Direct download with injected "Failed" error in Initialize(). 2555 { "a_zip_file.zip", 2556 DOWNLOAD_DIRECT, 2557 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED, 2558 1 2559 }, 2560 { 2561 "", 2562 content::TestFileErrorInjector::FILE_OPERATION_INITIALIZE, 2563 0, 2564 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED, 2565 } 2566 }, 2567 { // Navigated download with injected "Failed" error in Write(). 2568 { "a_zip_file.zip", 2569 DOWNLOAD_NAVIGATE, 2570 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED, 2571 1 2572 }, 2573 { 2574 "", 2575 content::TestFileErrorInjector::FILE_OPERATION_WRITE, 2576 0, 2577 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED, 2578 } 2579 }, 2580 { // Direct download with injected "Failed" error in Write(). 2581 { "a_zip_file.zip", 2582 DOWNLOAD_DIRECT, 2583 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED, 2584 1 2585 }, 2586 { 2587 "", 2588 content::TestFileErrorInjector::FILE_OPERATION_WRITE, 2589 0, 2590 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED, 2591 } 2592 }, 2593 { // Navigated download with injected "Name too long" error in 2594 // Initialize(). 2595 { "a_zip_file.zip", 2596 DOWNLOAD_NAVIGATE, 2597 content::DOWNLOAD_INTERRUPT_REASON_FILE_NAME_TOO_LONG, 2598 1 2599 }, 2600 { 2601 "", 2602 content::TestFileErrorInjector::FILE_OPERATION_INITIALIZE, 2603 0, 2604 content::DOWNLOAD_INTERRUPT_REASON_FILE_NAME_TOO_LONG, 2605 } 2606 }, 2607 { // Direct download with injected "Name too long" error in Initialize(). 2608 { "a_zip_file.zip", 2609 DOWNLOAD_DIRECT, 2610 content::DOWNLOAD_INTERRUPT_REASON_FILE_NAME_TOO_LONG, 2611 1 2612 }, 2613 { 2614 "", 2615 content::TestFileErrorInjector::FILE_OPERATION_INITIALIZE, 2616 0, 2617 content::DOWNLOAD_INTERRUPT_REASON_FILE_NAME_TOO_LONG, 2618 } 2619 }, 2620 { // Navigated download with injected "Name too long" error in Write(). 2621 { "a_zip_file.zip", 2622 DOWNLOAD_NAVIGATE, 2623 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED, 2624 1 2625 }, 2626 { 2627 "", 2628 content::TestFileErrorInjector::FILE_OPERATION_WRITE, 2629 0, 2630 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED, 2631 } 2632 }, 2633 { // Direct download with injected "Name too long" error in Write(). 2634 { "a_zip_file.zip", 2635 DOWNLOAD_DIRECT, 2636 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED, 2637 1 2638 }, 2639 { 2640 "", 2641 content::TestFileErrorInjector::FILE_OPERATION_WRITE, 2642 0, 2643 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED, 2644 } 2645 }, 2646 { // Direct download with injected "Disk full" error in 2nd Write(). 2647 { "06bESSE21Evolution.ppt", 2648 DOWNLOAD_DIRECT, 2649 content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE, 2650 1 2651 }, 2652 { 2653 "", 2654 content::TestFileErrorInjector::FILE_OPERATION_WRITE, 2655 1, 2656 content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE, 2657 } 2658 } 2659 }; 2660 2661 DownloadInsertFilesErrorCheckErrors(ARRAYSIZE_UNSAFE(error_info), error_info); 2662 } 2663 2664 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadErrorReadonlyFolder) { 2665 DownloadInfo download_info[] = { 2666 { 2667 "a_zip_file.zip", 2668 DOWNLOAD_DIRECT, 2669 // This passes because we switch to the My Documents folder. 2670 content::DOWNLOAD_INTERRUPT_REASON_NONE, 2671 true, 2672 true 2673 }, 2674 { 2675 "a_zip_file.zip", 2676 DOWNLOAD_NAVIGATE, 2677 // This passes because we switch to the My Documents folder. 2678 content::DOWNLOAD_INTERRUPT_REASON_NONE, 2679 true, 2680 true 2681 } 2682 }; 2683 2684 DownloadFilesToReadonlyFolder(ARRAYSIZE_UNSAFE(download_info), download_info); 2685 } 2686 2687 // Test that we show a dangerous downloads warning for a dangerous file 2688 // downloaded through a blob: URL. 2689 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadDangerousBlobData) { 2690 #if defined(OS_WIN) 2691 // On Windows, if SafeBrowsing is enabled, certain file types (.exe, .cab, 2692 // .msi) will be handled by the DownloadProtectionService. However, if the URL 2693 // is non-standard (e.g. blob:) then those files won't be handled by the 2694 // DPS. We should be showing the dangerous download warning for any file 2695 // considered dangerous and isn't handled by the DPS. 2696 const char kFilename[] = "foo.exe"; 2697 #else 2698 const char kFilename[] = "foo.swf"; 2699 #endif 2700 2701 std::string path("files/downloads/download-dangerous-blob.html?filename="); 2702 path += kFilename; 2703 2704 // Need to use http urls because the blob js doesn't work on file urls for 2705 // security reasons. 2706 ASSERT_TRUE(test_server()->Start()); 2707 GURL url(test_server()->GetURL(path)); 2708 2709 content::DownloadTestObserver* observer(DangerousDownloadWaiter( 2710 browser(), 1, 2711 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_ACCEPT)); 2712 ui_test_utils::NavigateToURL(browser(), url); 2713 observer->WaitForFinished(); 2714 2715 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::COMPLETE)); 2716 EXPECT_EQ(1u, observer->NumDangerousDownloadsSeen()); 2717 } 2718 2719 IN_PROC_BROWSER_TEST_F(DownloadTest, LoadURLExternallyReferrerPolicy) { 2720 // Do initial setup. 2721 ASSERT_TRUE(test_server()->Start()); 2722 EnableFileChooser(true); 2723 std::vector<DownloadItem*> download_items; 2724 GetDownloads(browser(), &download_items); 2725 ASSERT_TRUE(download_items.empty()); 2726 2727 // Navigate to a page with a referrer policy and a link on it. The link points 2728 // to testserver's /echoheader. 2729 GURL url = test_server()->GetURL("files/downloads/referrer_policy.html"); 2730 ASSERT_TRUE(url.is_valid()); 2731 ui_test_utils::NavigateToURL(browser(), url); 2732 2733 scoped_ptr<content::DownloadTestObserver> waiter( 2734 new content::DownloadTestObserverTerminal( 2735 DownloadManagerForBrowser(browser()), 1, 2736 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL)); 2737 2738 // Click on the link with the alt key pressed. This will download the link 2739 // target. 2740 WebContents* tab = browser()->tab_strip_model()->GetActiveWebContents(); 2741 WebKit::WebMouseEvent mouse_event; 2742 mouse_event.type = WebKit::WebInputEvent::MouseDown; 2743 mouse_event.button = WebKit::WebMouseEvent::ButtonLeft; 2744 mouse_event.x = 15; 2745 mouse_event.y = 15; 2746 mouse_event.clickCount = 1; 2747 mouse_event.modifiers = WebKit::WebInputEvent::AltKey; 2748 tab->GetRenderViewHost()->ForwardMouseEvent(mouse_event); 2749 mouse_event.type = WebKit::WebInputEvent::MouseUp; 2750 tab->GetRenderViewHost()->ForwardMouseEvent(mouse_event); 2751 2752 waiter->WaitForFinished(); 2753 EXPECT_EQ(1u, waiter->NumDownloadsSeenInState(DownloadItem::COMPLETE)); 2754 CheckDownloadStates(1, DownloadItem::COMPLETE); 2755 2756 // Validate that the correct file was downloaded. 2757 GetDownloads(browser(), &download_items); 2758 ASSERT_EQ(1u, download_items.size()); 2759 ASSERT_EQ(test_server()->GetURL("echoheader?Referer"), 2760 download_items[0]->GetOriginalUrl()); 2761 2762 // Check that the file contains the expected referrer. 2763 base::FilePath file(download_items[0]->GetTargetFilePath()); 2764 std::string expected_contents = test_server()->GetURL(std::string()).spec(); 2765 ASSERT_TRUE(VerifyFile(file, expected_contents, expected_contents.length())); 2766 } 2767 2768 IN_PROC_BROWSER_TEST_F(DownloadTest, HiddenDownload) { 2769 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib")); 2770 GURL url(URLRequestMockHTTPJob::GetMockUrl(file)); 2771 2772 DownloadManager* download_manager = DownloadManagerForBrowser(browser()); 2773 scoped_ptr<content::DownloadTestObserver> observer( 2774 new content::DownloadTestObserverTerminal( 2775 download_manager, 2776 1, 2777 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL)); 2778 2779 // Download and set IsHiddenDownload to true. 2780 WebContents* web_contents = 2781 browser()->tab_strip_model()->GetActiveWebContents(); 2782 scoped_ptr<DownloadUrlParameters> params( 2783 DownloadUrlParameters::FromWebContents(web_contents, url)); 2784 params->set_callback(base::Bind(&SetHiddenDownloadCallback)); 2785 download_manager->DownloadUrl(params.Pass()); 2786 observer->WaitForFinished(); 2787 2788 // Verify that download shelf is not shown. 2789 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible()); 2790 } 2791 2792 // Verify the multiple downloads infobar. 2793 IN_PROC_BROWSER_TEST_F(DownloadTest, TestMultipleDownloadsInfobar) { 2794 #if defined(OS_WIN) && defined(USE_ASH) 2795 // Disable this test in Metro+Ash for now (http://crbug.com/262796). 2796 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshBrowserTests)) 2797 return; 2798 #endif 2799 2800 ASSERT_TRUE(test_server()->Start()); 2801 2802 // Create a downloads observer. 2803 scoped_ptr<content::DownloadTestObserver> downloads_observer( 2804 CreateWaiter(browser(), 2)); 2805 2806 // Create an infobar observer. 2807 content::WindowedNotificationObserver infobar_added_1( 2808 chrome::NOTIFICATION_TAB_CONTENTS_INFOBAR_ADDED, 2809 content::NotificationService::AllSources()); 2810 ui_test_utils::NavigateToURL( 2811 browser(), 2812 test_server()->GetURL("files/downloads/download-a_zip_file.html")); 2813 infobar_added_1.Wait(); 2814 2815 InfoBarService* infobar_service = InfoBarService::FromWebContents( 2816 browser()->tab_strip_model()->GetActiveWebContents()); 2817 // Verify that there is only one infobar. 2818 ASSERT_EQ(1u, infobar_service->infobar_count()); 2819 2820 // Get the infobar at index 0. 2821 InfoBarDelegate* infobar = infobar_service->infobar_at(0); 2822 ConfirmInfoBarDelegate* confirm_infobar = infobar->AsConfirmInfoBarDelegate(); 2823 ASSERT_TRUE(confirm_infobar != NULL); 2824 2825 // Verify multi download warning infobar message. 2826 EXPECT_EQ(confirm_infobar->GetMessageText(), 2827 l10n_util::GetStringUTF16(IDS_MULTI_DOWNLOAD_WARNING)); 2828 2829 // Click on the "Allow" button to allow multiple downloads. 2830 if (confirm_infobar->Accept()) 2831 infobar_service->RemoveInfoBar(infobar); 2832 // Verify that there are no more infobars. 2833 EXPECT_EQ(0u, infobar_service->infobar_count()); 2834 2835 // Waits for the download to complete. 2836 downloads_observer->WaitForFinished(); 2837 EXPECT_EQ(2u, downloads_observer->NumDownloadsSeenInState( 2838 DownloadItem::COMPLETE)); 2839 } 2840 2841 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadTest_Renaming) { 2842 ASSERT_TRUE(test_server()->Start()); 2843 GURL url(test_server()->GetURL("files/downloads/a_zip_file.zip")); 2844 content::DownloadManager* manager = DownloadManagerForBrowser(browser()); 2845 base::FilePath origin_file(OriginFile(base::FilePath(FILE_PATH_LITERAL( 2846 "downloads/a_zip_file.zip")))); 2847 ASSERT_TRUE(base::PathExists(origin_file)); 2848 std::string origin_contents; 2849 ASSERT_TRUE(file_util::ReadFileToString(origin_file, &origin_contents)); 2850 2851 // Download the same url several times and expect that all downloaded files 2852 // after the zero-th contain a deduplication counter. 2853 for (int index = 0; index < 5; ++index) { 2854 DownloadAndWait(browser(), url); 2855 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible()); 2856 content::DownloadItem* item = manager->GetDownload( 2857 content::DownloadItem::kInvalidId + 1 + index); 2858 ASSERT_TRUE(item); 2859 ASSERT_EQ(DownloadItem::COMPLETE, item->GetState()); 2860 base::FilePath target_path(item->GetTargetFilePath()); 2861 EXPECT_EQ(std::string("a_zip_file") + 2862 (index == 0 ? std::string(".zip") : 2863 base::StringPrintf(" (%d).zip", index)), 2864 target_path.BaseName().AsUTF8Unsafe()); 2865 ASSERT_TRUE(base::PathExists(target_path)); 2866 ASSERT_TRUE(VerifyFile(target_path, origin_contents, 2867 origin_contents.size())); 2868 } 2869 } 2870 2871 // Test that the entire download pipeline handles unicode correctly. 2872 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadTest_CrazyFilenames) { 2873 const wchar_t* kCrazyFilenames[] = { 2874 L"a_file_name.zip", 2875 L"\u89c6\u9891\u76f4\u64ad\u56fe\u7247.zip", // chinese chars 2876 L"\u0412\u043e \u0424\u043b\u043e\u0440\u0438\u0434\u0435\u043e\u0431\u044a" 2877 L"\u044f\u0432\u043b\u0435\u043d\u0440\u0435\u0436\u0438\u043c \u0427" 2878 L"\u041f \u0438\u0437-\u0437\u0430 \u0443\u0442\u0435\u0447\u043a\u0438 " 2879 L"\u043d\u0435\u0444\u0442\u0438.zip", // russian 2880 L"Desocupa\xe7\xe3o est\xe1vel.zip", 2881 // arabic: 2882 L"\u0638\u2026\u0638\u02c6\u0637\xa7\u0638\u201a\u0637\xb9 \u0638\u201e" 2883 L"\u0638\u201e\u0637\xb2\u0638\u0679\u0637\xa7\u0637\xb1\u0637\xa9.zip", 2884 L"\u05d4\u05e2\u05d3\u05e4\u05d5\u05ea.zip", // hebrew 2885 L"\u092d\u093e\u0930\u0924.zip", // hindi 2886 L"d\xe9stabilis\xe9.zip", // french 2887 // korean 2888 L"\u97d3-\u4e2d \uc815\uc0c1, \ucc9c\uc548\ud568 \uc758\uacac.zip", 2889 L"jiho....tiho...miho.zip", 2890 L"jiho!@#$tiho$%^&-()_+=miho copy.zip", // special chars 2891 L"Wohoo-to hoo+I.zip", 2892 L"Picture 1.zip", 2893 L"This is a very very long english sentence with spaces and , and +.zip", 2894 }; 2895 2896 std::vector<DownloadItem*> download_items; 2897 static const int kFlags = (base::PLATFORM_FILE_CREATE | 2898 base::PLATFORM_FILE_WRITE); 2899 base::FilePath origin(FILE_PATH_LITERAL("origin")); 2900 ASSERT_TRUE(file_util::CreateDirectory(DestinationFile(browser(), origin))); 2901 2902 for (size_t index = 0; index < arraysize(kCrazyFilenames); ++index) { 2903 string16 crazy16; 2904 std::string crazy8; 2905 const wchar_t* crazy_w = kCrazyFilenames[index]; 2906 ASSERT_TRUE(WideToUTF8(crazy_w, wcslen(crazy_w), &crazy8)); 2907 ASSERT_TRUE(WideToUTF16(crazy_w, wcslen(crazy_w), &crazy16)); 2908 base::FilePath file_path(DestinationFile(browser(), origin.Append( 2909 #if defined(OS_WIN) 2910 crazy16 2911 #elif defined(OS_POSIX) 2912 crazy8 2913 #endif 2914 ))); 2915 2916 // Create the file. 2917 bool created = false; 2918 base::PlatformFileError error = base::PLATFORM_FILE_ERROR_MAX; 2919 base::PlatformFile fd = base::CreatePlatformFile( 2920 file_path, kFlags, &created, &error); 2921 EXPECT_EQ(static_cast<int>(crazy8.size()), 2922 base::WritePlatformFileAtCurrentPos( 2923 fd, crazy8.c_str(), crazy8.size())); 2924 EXPECT_TRUE(base::ClosePlatformFile(fd)); 2925 fd = base::kInvalidPlatformFileValue; 2926 GURL file_url(net::FilePathToFileURL(file_path)); 2927 2928 // Download the file and check that the filename is correct. 2929 DownloadAndWait(browser(), file_url); 2930 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible()); 2931 GetDownloads(browser(), &download_items); 2932 ASSERT_EQ(1UL, download_items.size()); 2933 base::FilePath downloaded(download_items[0]->GetTargetFilePath()); 2934 download_items[0]->Remove(); 2935 download_items.clear(); 2936 ASSERT_TRUE(CheckDownloadFullPaths( 2937 browser(), 2938 downloaded, 2939 file_path)); 2940 } 2941 } 2942 2943 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadTest_Remove) { 2944 ASSERT_TRUE(test_server()->Start()); 2945 GURL url(test_server()->GetURL("files/downloads/a_zip_file.zip")); 2946 std::vector<DownloadItem*> download_items; 2947 GetDownloads(browser(), &download_items); 2948 ASSERT_TRUE(download_items.empty()); 2949 2950 // Download a file. 2951 DownloadAndWaitWithDisposition(browser(), 2952 url, 2953 CURRENT_TAB, 2954 ui_test_utils::BROWSER_TEST_NONE); 2955 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible()); 2956 GetDownloads(browser(), &download_items); 2957 ASSERT_EQ(1UL, download_items.size()); 2958 base::FilePath downloaded(download_items[0]->GetTargetFilePath()); 2959 2960 // Remove the DownloadItem but not the file, then check that the file still 2961 // exists. 2962 download_items[0]->Remove(); 2963 download_items.clear(); 2964 GetDownloads(browser(), &download_items); 2965 ASSERT_EQ(0UL, download_items.size()); 2966 ASSERT_TRUE(CheckDownloadFullPaths( 2967 browser(), downloaded, OriginFile(base::FilePath( 2968 FILE_PATH_LITERAL("downloads/a_zip_file.zip"))))); 2969 2970 } 2971 2972 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadTest_PauseResumeCancel) { 2973 DownloadItem* download_item = CreateSlowTestDownload(); 2974 ASSERT_TRUE(download_item); 2975 ASSERT_FALSE(download_item->GetTargetFilePath().empty()); 2976 EXPECT_FALSE(download_item->IsPaused()); 2977 EXPECT_NE(DownloadItem::CANCELLED, download_item->GetState()); 2978 download_item->Pause(); 2979 EXPECT_TRUE(download_item->IsPaused()); 2980 download_item->Resume(); 2981 EXPECT_FALSE(download_item->IsPaused()); 2982 EXPECT_NE(DownloadItem::CANCELLED, download_item->GetState()); 2983 download_item->Cancel(true); 2984 EXPECT_EQ(DownloadItem::CANCELLED, download_item->GetState()); 2985 } 2986 2987 // The Mac downloaded files quarantine feature is implemented by the 2988 // Contents/Info.plist file in cocoa apps. browser_tests cannot test 2989 // quarantining files on Mac because it is not a cocoa app. 2990 // TODO(benjhayden) test the equivalents on other platforms. 2991 2992 #if defined(OS_LINUX) && !defined(OS_CHROMEOS) && defined(ARCH_CPU_ARM_FAMILY) 2993 // Timing out on ARM linux: http://crbug.com/238459 2994 #define MAYBE_DownloadTest_PercentComplete DISABLED_DownloadTest_PercentComplete 2995 #elif defined(OS_MACOSX) 2996 // Disable on mac: http://crbug.com/238831 2997 #define MAYBE_DownloadTest_PercentComplete DISABLED_DownloadTest_PercentComplete 2998 #else 2999 #define MAYBE_DownloadTest_PercentComplete DownloadTest_PercentComplete 3000 #endif 3001 IN_PROC_BROWSER_TEST_F(DownloadTest, MAYBE_DownloadTest_PercentComplete) { 3002 // Write a huge file. 3003 base::FilePath file_path(DestinationFile( 3004 browser(), base::FilePath(FILE_PATH_LITERAL("DownloadTest_BigZip.zip")))); 3005 int flags = (base::PLATFORM_FILE_CREATE | 3006 base::PLATFORM_FILE_WRITE); 3007 bool created = false; 3008 base::PlatformFileError error = base::PLATFORM_FILE_ERROR_MAX; 3009 base::PlatformFile fd = base::CreatePlatformFile( 3010 file_path, flags, &created, &error); 3011 int64 size = 1 << 29; 3012 EXPECT_EQ(size, base::SeekPlatformFile( 3013 fd, base::PLATFORM_FILE_FROM_BEGIN, size)); 3014 EXPECT_EQ(1, base::WritePlatformFileAtCurrentPos(fd, "a", 1)); 3015 EXPECT_TRUE(base::ClosePlatformFile(fd)); 3016 fd = base::kInvalidPlatformFileValue; 3017 #if defined(OS_POSIX) 3018 // Make it readable by chronos on chromeos 3019 file_util::SetPosixFilePermissions(file_path, 0755); 3020 #endif 3021 3022 // Ensure that we have enough disk space. 3023 int64 free_space = base::SysInfo::AmountOfFreeDiskSpace( 3024 GetDownloadDirectory(browser())); 3025 ASSERT_LE(size, free_space) << "Not enough disk space to download. Got " 3026 << free_space; 3027 GURL file_url(net::FilePathToFileURL(file_path)); 3028 scoped_ptr<content::DownloadTestObserver> progress_waiter( 3029 CreateInProgressWaiter(browser(), 1)); 3030 3031 // Start downloading a file, wait for it to be created. 3032 ui_test_utils::NavigateToURLWithDisposition( 3033 browser(), file_url, CURRENT_TAB, ui_test_utils::BROWSER_TEST_NONE); 3034 progress_waiter->WaitForFinished(); 3035 EXPECT_EQ(1u, progress_waiter->NumDownloadsSeenInState( 3036 DownloadItem::IN_PROGRESS)); 3037 std::vector<DownloadItem*> download_items; 3038 GetDownloads(browser(), &download_items); 3039 ASSERT_EQ(1UL, download_items.size()); 3040 3041 // Wait for the download to complete, checking along the way that the 3042 // PercentComplete() never regresses. 3043 PercentWaiter waiter(download_items[0]); 3044 EXPECT_TRUE(waiter.WaitForFinished()); 3045 EXPECT_EQ(DownloadItem::COMPLETE, download_items[0]->GetState()); 3046 ASSERT_EQ(100, download_items[0]->PercentComplete()); 3047 EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible()); 3048 3049 // Check that the file downloaded correctly. 3050 ASSERT_TRUE(base::PathExists(download_items[0]->GetTargetFilePath())); 3051 int64 downloaded_size = 0; 3052 ASSERT_TRUE(file_util::GetFileSize( 3053 download_items[0]->GetTargetFilePath(), &downloaded_size)); 3054 #if defined(OS_WIN) 3055 ASSERT_EQ(1, downloaded_size); 3056 #else 3057 ASSERT_EQ(size + 1, downloaded_size); 3058 #endif 3059 ASSERT_TRUE(file_util::DieFileDie(file_path, false)); 3060 ASSERT_TRUE(file_util::DieFileDie(download_items[0]->GetTargetFilePath(), 3061 false)); 3062 } 3063 3064 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadTest_DenyDanger) { 3065 ASSERT_TRUE(test_server()->Start()); 3066 GURL url(test_server()->GetURL("files/downloads/dangerous/dangerous.crx")); 3067 scoped_ptr<content::DownloadTestObserver> observer( 3068 DangerousDownloadWaiter( 3069 browser(), 1, 3070 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_DENY)); 3071 ui_test_utils::NavigateToURL(browser(), url); 3072 observer->WaitForFinished(); 3073 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::CANCELLED)); 3074 EXPECT_EQ(1u, observer->NumDangerousDownloadsSeen()); 3075 EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible()); 3076 } 3077 3078 IN_PROC_BROWSER_TEST_F(DownloadTest, DownloadPrefs_SaveFilePath) { 3079 DownloadPrefs* on_prefs = DownloadServiceFactory::GetForBrowserContext( 3080 browser()->profile())->GetDownloadManagerDelegate()->download_prefs(); 3081 DownloadPrefs* off_prefs = DownloadServiceFactory::GetForBrowserContext( 3082 browser()->profile()->GetOffTheRecordProfile()) 3083 ->GetDownloadManagerDelegate()->download_prefs(); 3084 base::FilePath dir(on_prefs->SaveFilePath()); 3085 EXPECT_EQ(dir.value(), off_prefs->SaveFilePath().value()); 3086 3087 on_prefs->SetSaveFilePath(dir.AppendASCII("on")); 3088 EXPECT_EQ(dir.AppendASCII("on").value(), on_prefs->SaveFilePath().value()); 3089 EXPECT_EQ(dir.AppendASCII("on").value(), off_prefs->SaveFilePath().value()); 3090 3091 on_prefs->SetSaveFilePath(dir); 3092 EXPECT_EQ(dir.value(), on_prefs->SaveFilePath().value()); 3093 EXPECT_EQ(dir.value(), off_prefs->SaveFilePath().value()); 3094 3095 off_prefs->SetSaveFilePath(dir.AppendASCII("off")); 3096 EXPECT_EQ(dir.value(), on_prefs->SaveFilePath().value()); 3097 EXPECT_EQ(dir.AppendASCII("off").value(), off_prefs->SaveFilePath().value()); 3098 3099 on_prefs->SetSaveFilePath(dir.AppendASCII("on")); 3100 EXPECT_EQ(dir.AppendASCII("on").value(), on_prefs->SaveFilePath().value()); 3101 EXPECT_EQ(dir.AppendASCII("off").value(), off_prefs->SaveFilePath().value()); 3102 } 3103 3104 // A download that is interrupted due to a file error should be able to be 3105 // resumed. 3106 IN_PROC_BROWSER_TEST_F(DownloadTest, Resumption_NoPrompt) { 3107 CommandLine::ForCurrentProcess()->AppendSwitch( 3108 switches::kEnableDownloadResumption); 3109 scoped_refptr<content::TestFileErrorInjector> error_injector( 3110 content::TestFileErrorInjector::Create( 3111 DownloadManagerForBrowser(browser()))); 3112 scoped_ptr<content::DownloadTestObserver> completion_observer( 3113 CreateWaiter(browser(), 1)); 3114 EnableFileChooser(true); 3115 3116 DownloadItem* download = StartMockDownloadAndInjectError( 3117 error_injector, 3118 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED); 3119 ASSERT_TRUE(download); 3120 3121 download->Resume(); 3122 completion_observer->WaitForFinished(); 3123 3124 EXPECT_EQ( 3125 1u, completion_observer->NumDownloadsSeenInState(DownloadItem::COMPLETE)); 3126 EXPECT_FALSE(DidShowFileChooser()); 3127 } 3128 3129 // A download that's interrupted due to a reason that indicates that the target 3130 // path is invalid or unusable should cause a prompt to be displayed on 3131 // resumption. 3132 IN_PROC_BROWSER_TEST_F(DownloadTest, Resumption_WithPrompt) { 3133 CommandLine::ForCurrentProcess()->AppendSwitch( 3134 switches::kEnableDownloadResumption); 3135 scoped_refptr<content::TestFileErrorInjector> error_injector( 3136 content::TestFileErrorInjector::Create( 3137 DownloadManagerForBrowser(browser()))); 3138 scoped_ptr<content::DownloadTestObserver> completion_observer( 3139 CreateWaiter(browser(), 1)); 3140 EnableFileChooser(true); 3141 3142 DownloadItem* download = StartMockDownloadAndInjectError( 3143 error_injector, 3144 content::DOWNLOAD_INTERRUPT_REASON_FILE_NO_SPACE); 3145 ASSERT_TRUE(download); 3146 3147 download->Resume(); 3148 completion_observer->WaitForFinished(); 3149 3150 EXPECT_EQ( 3151 1u, completion_observer->NumDownloadsSeenInState(DownloadItem::COMPLETE)); 3152 EXPECT_TRUE(DidShowFileChooser()); 3153 } 3154 3155 // The user shouldn't be prompted on a resumed download unless a prompt is 3156 // necessary due to the interrupt reason. 3157 IN_PROC_BROWSER_TEST_F(DownloadTest, Resumption_WithPromptAlways) { 3158 CommandLine::ForCurrentProcess()->AppendSwitch( 3159 switches::kEnableDownloadResumption); 3160 browser()->profile()->GetPrefs()->SetBoolean( 3161 prefs::kPromptForDownload, true); 3162 scoped_refptr<content::TestFileErrorInjector> error_injector( 3163 content::TestFileErrorInjector::Create( 3164 DownloadManagerForBrowser(browser()))); 3165 scoped_ptr<content::DownloadTestObserver> completion_observer( 3166 CreateWaiter(browser(), 1)); 3167 EnableFileChooser(true); 3168 3169 DownloadItem* download = StartMockDownloadAndInjectError( 3170 error_injector, 3171 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED); 3172 ASSERT_TRUE(download); 3173 3174 // Prompts the user initially because of the kPromptForDownload preference. 3175 EXPECT_TRUE(DidShowFileChooser()); 3176 3177 download->Resume(); 3178 completion_observer->WaitForFinished(); 3179 3180 EXPECT_EQ( 3181 1u, completion_observer->NumDownloadsSeenInState(DownloadItem::COMPLETE)); 3182 // Shouldn't prompt for resumption. 3183 EXPECT_FALSE(DidShowFileChooser()); 3184 } 3185 3186 // A download that is interrupted due to a transient error should be resumed 3187 // automatically. 3188 IN_PROC_BROWSER_TEST_F(DownloadTest, Resumption_Automatic) { 3189 CommandLine::ForCurrentProcess()->AppendSwitch( 3190 switches::kEnableDownloadResumption); 3191 scoped_refptr<content::TestFileErrorInjector> error_injector( 3192 content::TestFileErrorInjector::Create( 3193 DownloadManagerForBrowser(browser()))); 3194 3195 DownloadItem* download = StartMockDownloadAndInjectError( 3196 error_injector, 3197 content::DOWNLOAD_INTERRUPT_REASON_FILE_TRANSIENT_ERROR); 3198 ASSERT_TRUE(download); 3199 3200 // The number of times this the download is resumed automatically is defined 3201 // in DownloadItemImpl::kMaxAutoResumeAttempts. The number of DownloadFiles 3202 // created should be that number + 1 (for the original download request). We 3203 // only care that it is greater than 1. 3204 EXPECT_GT(1u, error_injector->TotalFileCount()); 3205 } 3206 3207 // An interrupting download should be resumable multiple times. 3208 IN_PROC_BROWSER_TEST_F(DownloadTest, Resumption_MultipleAttempts) { 3209 CommandLine::ForCurrentProcess()->AppendSwitch( 3210 switches::kEnableDownloadResumption); 3211 scoped_refptr<content::TestFileErrorInjector> error_injector( 3212 content::TestFileErrorInjector::Create( 3213 DownloadManagerForBrowser(browser()))); 3214 scoped_ptr<DownloadTestObserverNotInProgress> completion_observer( 3215 new DownloadTestObserverNotInProgress( 3216 DownloadManagerForBrowser(browser()), 1)); 3217 // Wait for two transitions to a resumable state 3218 scoped_ptr<content::DownloadTestObserver> resumable_observer( 3219 new DownloadTestObserverResumable( 3220 DownloadManagerForBrowser(browser()), 2)); 3221 3222 EnableFileChooser(true); 3223 DownloadItem* download = StartMockDownloadAndInjectError( 3224 error_injector, 3225 content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED); 3226 ASSERT_TRUE(download); 3227 3228 content::TestFileErrorInjector::FileErrorInfo error_info; 3229 error_info.url = download->GetOriginalUrl().spec(); 3230 error_info.code = content::TestFileErrorInjector::FILE_OPERATION_WRITE; 3231 error_info.operation_instance = 0; 3232 error_info.error = content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED; 3233 error_injector->AddError(error_info); 3234 error_injector->InjectErrors(); 3235 3236 // Resuming should cause the download to be interrupted again due to the 3237 // errors we are injecting. 3238 download->Resume(); 3239 resumable_observer->WaitForFinished(); 3240 ASSERT_EQ(DownloadItem::INTERRUPTED, download->GetState()); 3241 ASSERT_EQ(content::DOWNLOAD_INTERRUPT_REASON_FILE_FAILED, 3242 download->GetLastReason()); 3243 3244 error_injector->ClearErrors(); 3245 error_injector->InjectErrors(); 3246 3247 // No errors this time. The download should complete successfully. 3248 EXPECT_FALSE(completion_observer->IsFinished()); 3249 completion_observer->StartObserving(); 3250 download->Resume(); 3251 completion_observer->WaitForFinished(); 3252 EXPECT_EQ(DownloadItem::COMPLETE, download->GetState()); 3253 3254 EXPECT_FALSE(DidShowFileChooser()); 3255 } 3256