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