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