download_browsertest.cc revision 72a454cd3513ac24fbdd0e0cb9ad70b86a99b801
1// Copyright (c) 2010 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 "base/file_path.h"
6#include "base/file_util.h"
7#include "base/path_service.h"
8#include "base/scoped_temp_dir.h"
9#include "base/test/test_file_util.h"
10#include "base/utf_string_conversions.h"
11#include "chrome/browser/browser_window.h"
12#include "chrome/browser/download/download_item.h"
13#include "chrome/browser/download/download_manager.h"
14#include "chrome/browser/download/download_prefs.h"
15#include "chrome/browser/download/download_shelf.h"
16#include "chrome/browser/net/url_request_mock_http_job.h"
17#include "chrome/browser/net/url_request_slow_download_job.h"
18#include "chrome/browser/prefs/pref_service.h"
19#include "chrome/browser/profiles/profile.h"
20#include "chrome/browser/ui/browser.h"
21#include "chrome/browser/ui/browser_list.h"
22#include "chrome/common/pref_names.h"
23#include "chrome/common/chrome_paths.h"
24#include "chrome/common/page_transition_types.h"
25#include "chrome/common/url_constants.h"
26#include "chrome/test/in_process_browser_test.h"
27#include "chrome/test/ui_test_utils.h"
28#include "net/base/net_util.h"
29#include "testing/gtest/include/gtest/gtest.h"
30
31namespace {
32
33// Variation of DownloadsCompleteObserver from ui_test_utils.cc; the
34// specifically targeted download tests need finer granularity on waiting.
35// Construction of this class defines a system state, based on some number
36// of downloads being seen in a particular state + other events that
37// may occur in the download system.  That state will be recorded if it
38// occurs at any point after construction.  When that state occurs, the class
39// is considered finished.  Callers may either probe for the finished state, or
40// wait on it.
41class DownloadsObserver : public DownloadManager::Observer,
42                          public DownloadItem::Observer {
43 public:
44  // The action which should be considered the completion of the download.
45  enum DownloadFinishedSignal { COMPLETE, FILE_RENAME };
46
47  // Create an object that will be considered completed when |wait_count|
48  // download items have entered state |download_finished_signal|.
49  // If |finish_on_select_file| is true, the object will also be
50  // considered finished if the DownloadManager raises a
51  // SelectFileDialogDisplayed() notification.
52
53  // TODO(rdsmith): Add option of "dangerous accept/reject dialog" as
54  // a unblocking event; if that shows up when you aren't expecting it,
55  // it'll result in a hang/timeout as we'll never get to final rename.
56  // This probably means rewriting the interface to take a list of events
57  // to treat as completion events.
58  DownloadsObserver(DownloadManager* download_manager,
59                    size_t wait_count,
60                    DownloadFinishedSignal download_finished_signal,
61                    bool finish_on_select_file)
62      : download_manager_(download_manager),
63        wait_count_(wait_count),
64        finished_downloads_at_construction_(0),
65        waiting_(false),
66        download_finished_signal_(download_finished_signal),
67        finish_on_select_file_(finish_on_select_file),
68        select_file_dialog_seen_(false) {
69    download_manager_->AddObserver(this);  // Will call initial ModelChanged().
70    finished_downloads_at_construction_ = finished_downloads_.size();
71  }
72
73  ~DownloadsObserver() {
74    std::set<DownloadItem*>::iterator it = downloads_observed_.begin();
75    for (; it != downloads_observed_.end(); ++it) {
76      (*it)->RemoveObserver(this);
77    }
78    download_manager_->RemoveObserver(this);
79  }
80
81  // State accessors.
82  bool select_file_dialog_seen() { return select_file_dialog_seen_; }
83
84  // Wait for whatever state was specified in the constructor.
85  void WaitForFinished() {
86    if (!IsFinished()) {
87      waiting_ = true;
88      ui_test_utils::RunMessageLoop();
89      waiting_ = false;
90    }
91  }
92
93  // Return true if everything's happened that we're configured for.
94  bool IsFinished() {
95    if (finished_downloads_.size() - finished_downloads_at_construction_
96        >= wait_count_)
97      return true;
98    return (finish_on_select_file_ && select_file_dialog_seen_);
99  }
100
101  // DownloadItem::Observer
102  virtual void OnDownloadUpdated(DownloadItem* download) {
103    if (download_finished_signal_ == COMPLETE &&
104        download->state() == DownloadItem::COMPLETE)
105      DownloadInFinalState(download);
106  }
107
108  virtual void OnDownloadFileCompleted(DownloadItem* download) {
109    if (download_finished_signal_ == FILE_RENAME)
110      DownloadInFinalState(download);
111  }
112
113  virtual void OnDownloadOpened(DownloadItem* download) {}
114
115  // DownloadManager::Observer
116  virtual void ModelChanged() {
117    // Regenerate DownloadItem observers.  If there are any download items
118    // in the COMPLETE state and that's our final state, note them in
119    // finished_downloads_ (done by OnDownloadUpdated).
120    std::vector<DownloadItem*> downloads;
121    download_manager_->SearchDownloads(string16(), &downloads);
122
123    std::vector<DownloadItem*>::iterator it = downloads.begin();
124    for (; it != downloads.end(); ++it) {
125      OnDownloadUpdated(*it);  // Safe to call multiple times; checks state.
126
127      std::set<DownloadItem*>::const_iterator
128          finished_it(finished_downloads_.find(*it));
129      std::set<DownloadItem*>::iterator
130          observed_it(downloads_observed_.find(*it));
131
132      // If it isn't finished and we're aren't observing it, start.
133      if (finished_it == finished_downloads_.end() &&
134          observed_it == downloads_observed_.end()) {
135        (*it)->AddObserver(this);
136        downloads_observed_.insert(*it);
137        continue;
138      }
139
140      // If it is finished and we are observing it, stop.
141      if (finished_it != finished_downloads_.end() &&
142          observed_it != downloads_observed_.end()) {
143        (*it)->RemoveObserver(this);
144        downloads_observed_.erase(observed_it);
145        continue;
146      }
147    }
148  }
149
150  virtual void SelectFileDialogDisplayed() {
151    select_file_dialog_seen_ = true;
152    SignalIfFinished();
153  }
154
155 private:
156  // Called when we know that a download item is in a final state.
157  // Note that this is not the same as it first transitioning in to the
158  // final state; in the case of DownloadItem::COMPLETE, multiple
159  // notifications may occur once the item is in that state.  So we
160  // keep our own track of transitions into final.
161  void DownloadInFinalState(DownloadItem* download) {
162    if (finished_downloads_.find(download) != finished_downloads_.end()) {
163      // We've already seen terminal state on this download.
164      return;
165    }
166
167    // Record the transition.
168    finished_downloads_.insert(download);
169
170    SignalIfFinished();
171  }
172
173  void SignalIfFinished() {
174    if (waiting_ && IsFinished())
175      MessageLoopForUI::current()->Quit();
176  }
177
178  // The observed download manager.
179  DownloadManager* download_manager_;
180
181  // The set of DownloadItem's that have transitioned to their finished state
182  // since construction of this object.  When the size of this array
183  // reaches wait_count_, we're done.
184  std::set<DownloadItem*> finished_downloads_;
185
186  // The set of DownloadItem's we are currently observing.  Generally there
187  // won't be any overlap with the above; once we see the final state
188  // on a DownloadItem, we'll stop observing it.
189  std::set<DownloadItem*> downloads_observed_;
190
191  // The number of downloads to wait on completing.
192  size_t wait_count_;
193
194  // The number of downloads entered in final state in initial
195  // ModelChanged().  We use |finished_downloads_| to track the incoming
196  // transitions to final state we should ignore, and to track the
197  // number of final state transitions that occurred between
198  // construction and return from wait.  But if the final state is the
199  // COMPLETE state, some downloads may be in it (and thus be entered
200  // into finished_downloads_) when we construct this class.  We don't
201  // want to count those;
202  int finished_downloads_at_construction_;
203
204  // Whether an internal message loop has been started and must be quit upon
205  // all downloads completing.
206  bool waiting_;
207
208  // The action on which to consider the DownloadItem finished.
209  DownloadFinishedSignal download_finished_signal_;
210
211  // True if we should transition the DownloadsObserver to finished if
212  // the select file dialog comes up.
213  bool finish_on_select_file_;
214
215  // True if we've seen the select file dialog.
216  bool select_file_dialog_seen_;
217
218  DISALLOW_COPY_AND_ASSIGN(DownloadsObserver);
219};
220
221class DownloadTest : public InProcessBrowserTest {
222 public:
223  enum SelectExpectation {
224    EXPECT_NO_SELECT_DIALOG = -1,
225    EXPECT_NOTHING,
226    EXPECT_SELECT_DIALOG
227  };
228
229  // Returning false indicates a failure of the setup, and should be asserted
230  // in the caller.
231  virtual bool InitialSetup(bool prompt_for_download) {
232    bool have_test_dir = PathService::Get(chrome::DIR_TEST_DATA, &test_dir_);
233    EXPECT_TRUE(have_test_dir);
234    if (!have_test_dir)
235      return false;
236
237    // Sanity check default values for window / tab count and shelf visibility.
238    int window_count = BrowserList::size();
239    EXPECT_EQ(1, window_count);
240    EXPECT_EQ(1, browser()->tab_count());
241    bool is_shelf_visible = browser()->window()->IsDownloadShelfVisible();
242    EXPECT_FALSE(is_shelf_visible);
243
244    // Set up the temporary download folder.
245    bool created_downloads_dir = CreateAndSetDownloadsDirectory(browser());
246    EXPECT_TRUE(created_downloads_dir);
247    if (!created_downloads_dir)
248      return false;
249    browser()->profile()->GetPrefs()->SetBoolean(prefs::kPromptForDownload,
250                                                 prompt_for_download);
251
252    return true;
253  }
254
255 protected:
256
257  // Must be called after browser creation.  Creates a temporary
258  // directory for downloads that is auto-deleted on destruction.
259  // Returning false indicates a failure of the function, and should be asserted
260  // in the caller.
261  bool CreateAndSetDownloadsDirectory(Browser* browser) {
262    if (!browser)
263      return false;
264
265    if (!downloads_directory_.CreateUniqueTempDir())
266      return false;
267
268    browser->profile()->GetPrefs()->SetFilePath(
269        prefs::kDownloadDefaultDirectory,
270        downloads_directory_.path());
271
272    return true;
273  }
274
275  FilePath GetDownloadDirectory(Browser* browser) {
276    DownloadManager* download_mananger =
277        browser->profile()->GetDownloadManager();
278    return download_mananger->download_prefs()->download_path();
279  }
280
281  DownloadsObserver* CreateWaiter(Browser* browser, int num_downloads) {
282    DownloadManager* download_manager =
283        browser->profile()->GetDownloadManager();
284    return new DownloadsObserver(
285        download_manager, num_downloads,
286        DownloadsObserver::FILE_RENAME,  // Really done
287        true);                           // Bail on select file
288  }
289
290  // Download |url|, then wait for the download to finish.
291  // |disposition| indicates where the navigation occurs (current tab, new
292  // foreground tab, etc).
293  // |expectation| indicates whether or not a Select File dialog should be
294  // open when the download is finished, or if we don't care.
295  // If the dialog appears, the test completes.  The only effect |expectation|
296  // has is whether or not the test succeeds.
297  // |browser_test_flags| indicate what to wait for, and is an OR of 0 or more
298  // values in the ui_test_utils::BrowserTestWaitFlags enum.
299  void DownloadAndWaitWithDisposition(Browser* browser,
300                                      const GURL& url,
301                                      WindowOpenDisposition disposition,
302                                      SelectExpectation expectation,
303                                      int browser_test_flags) {
304    // Setup notification, navigate, and block.
305    scoped_ptr<DownloadsObserver> observer(CreateWaiter(browser, 1));
306    // This call will block until the condition specified by
307    // |browser_test_flags|, but will not wait for the download to finish.
308    ui_test_utils::NavigateToURLWithDisposition(browser,
309                                                url,
310                                                disposition,
311                                                browser_test_flags);
312    // Waits for the download to complete.
313    observer->WaitForFinished();
314
315    // If specified, check the state of the select file dialog.
316    if (expectation != EXPECT_NOTHING) {
317      EXPECT_EQ(expectation == EXPECT_SELECT_DIALOG,
318                observer->select_file_dialog_seen());
319    }
320  }
321
322  // Download a file in the current tab, then wait for the download to finish.
323  void DownloadAndWait(Browser* browser,
324                       const GURL& url,
325                       SelectExpectation expectation) {
326    DownloadAndWaitWithDisposition(
327        browser,
328        url,
329        CURRENT_TAB,
330        expectation,
331        ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
332  }
333
334  // Should only be called when the download is known to have finished
335  // (in error or not).
336  // Returning false indicates a failure of the function, and should be asserted
337  // in the caller.
338  bool CheckDownload(Browser* browser,
339                     const FilePath& downloaded_filename,
340                     const FilePath& origin_filename) {
341    // Find the path to which the data will be downloaded.
342    FilePath downloaded_file =
343        GetDownloadDirectory(browser).Append(downloaded_filename);
344
345    // Find the origin path (from which the data comes).
346    FilePath origin_file(test_dir_.Append(origin_filename));
347    bool origin_file_exists = file_util::PathExists(origin_file);
348    EXPECT_TRUE(origin_file_exists);
349    if (!origin_file_exists)
350      return false;
351
352    // Confirm the downloaded data file exists.
353    bool downloaded_file_exists = file_util::PathExists(downloaded_file);
354    EXPECT_TRUE(downloaded_file_exists);
355    if (!downloaded_file_exists)
356      return false;
357
358    int64 origin_file_size = 0;
359    int64 downloaded_file_size = 0;
360    EXPECT_TRUE(file_util::GetFileSize(origin_file, &origin_file_size));
361    EXPECT_TRUE(file_util::GetFileSize(downloaded_file, &downloaded_file_size));
362    EXPECT_EQ(origin_file_size, downloaded_file_size);
363    EXPECT_TRUE(file_util::ContentsEqual(downloaded_file, origin_file));
364
365    // Delete the downloaded copy of the file.
366    bool downloaded_file_deleted =
367        file_util::DieFileDie(downloaded_file, false);
368    EXPECT_TRUE(downloaded_file_deleted);
369    return downloaded_file_deleted;
370  }
371
372  // TODO(ahendrickson) -- |expected_title_in_progress| and
373  // |expected_title_finished| need to be checked.
374  bool RunSizeTest(Browser* browser,
375                   const GURL& url,
376                   const string16& expected_title_in_progress,
377                   const string16& expected_title_finished) {
378    if (!InitialSetup(false))
379      return false;
380
381    // Download a partial web page in a background tab and wait.
382    // The mock system will not complete until it gets a special URL.
383    scoped_ptr<DownloadsObserver> observer(CreateWaiter(browser, 1));
384    ui_test_utils::NavigateToURL(browser, url);
385
386    // TODO(ahendrickson): check download status text before downloading.
387    // Need to:
388    //  - Add a member function to the |DownloadShelf| interface class, that
389    //    indicates how many members it has.
390    //  - Add a member function to |DownloadShelf| to get the status text
391    //    of a given member (for example, via |DownloadItemView|'s
392    //    GetAccessibleName() member function), by index.
393    //  - Iterate over browser->window()->GetDownloadShelf()'s members
394    //    to see if any match the status text we want.  Start with the last one.
395
396    // Complete sending the request.  We do this by loading a second URL in a
397    // separate tab.
398    GURL finish_url(URLRequestSlowDownloadJob::kFinishDownloadUrl);
399    ui_test_utils::NavigateToURLWithDisposition(
400        browser,
401        finish_url,
402        NEW_FOREGROUND_TAB,
403        ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
404    observer->WaitForFinished();
405
406    EXPECT_EQ(2, browser->tab_count());
407
408    // TODO(ahendrickson): check download status text after downloading.
409
410    // Make sure the download shelf is showing.
411    EXPECT_TRUE(browser->window()->IsDownloadShelfVisible());
412
413    FilePath filename;
414    net::FileURLToFilePath(url, &filename);
415    filename = filename.BaseName();
416    FilePath download_path = downloads_directory_.path().Append(filename);
417
418    bool downloaded_path_exists = file_util::PathExists(download_path);
419    EXPECT_TRUE(downloaded_path_exists);
420    if (!downloaded_path_exists)
421      return false;
422
423    // Delete the file we just downloaded.
424    EXPECT_TRUE(file_util::DieFileDie(download_path, true));
425    EXPECT_FALSE(file_util::PathExists(download_path));
426
427    return true;
428  }
429
430 private:
431  // Location of the test data.
432  FilePath test_dir_;
433
434  // Location of the downloads directory for these tests
435  ScopedTempDir downloads_directory_;
436};
437
438// NOTES:
439//
440// Files for these tests are found in DIR_TEST_DATA (currently
441// "chrome\test\data\", see chrome_paths.cc).
442// Mock responses have extension .mock-http-headers appended to the file name.
443
444// Download a file due to the associated MIME type.
445//
446// Test is believed good (non-flaky) in itself, but it
447// sometimes trips over underlying flakiness in the downloads
448// subsystem in in http://crbug.com/63237.  Until that bug is
449// fixed, this test should be considered flaky.  It's entered as
450// DISABLED since if 63237 does cause a failure, it'll be a timeout.
451IN_PROC_BROWSER_TEST_F(DownloadTest, DISABLED_DownloadMimeType) {
452  ASSERT_TRUE(InitialSetup(false));
453  FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
454  GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
455
456  // Download the file and wait.  We do not expect the Select File dialog.
457  DownloadAndWait(browser(), url, EXPECT_NO_SELECT_DIALOG);
458
459  // Check state.
460  EXPECT_EQ(1, browser()->tab_count());
461  CheckDownload(browser(), file, file);
462  EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
463}
464
465#if defined(OS_WIN)
466// Download a file and confirm that the zone identifier (on windows)
467// is set to internet.
468// This is flaky due to http://crbug.com/20809.  It's marked as
469// DISABLED because when the test fails it fails via a timeout.
470IN_PROC_BROWSER_TEST_F(DownloadTest, DISABLED_CheckInternetZone) {
471  ASSERT_TRUE(InitialSetup(false));
472  FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
473  GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
474
475  // Download the file and wait.  We do not expect the Select File dialog.
476  DownloadAndWait(browser(), url, EXPECT_NO_SELECT_DIALOG);
477
478  // Check state.
479  EXPECT_EQ(1, browser()->tab_count());
480  CheckDownload(browser(), file, file);
481  EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
482
483  FilePath downloaded_file = GetDownloadDirectory(browser()).Append(file);
484  if (file_util::VolumeSupportsADS(downloaded_file))
485    EXPECT_TRUE(file_util::HasInternetZoneIdentifier(downloaded_file));
486}
487#endif
488
489// Put up a Select File dialog when the file is downloaded, due to its MIME
490// type.
491//
492// This test runs correctly, but leaves behind turds in the test user's
493// download directory because of http://crbug.com/62099.  No big loss; it
494// was primarily confirming DownloadsObserver wait on select file dialog
495// functionality anyway.
496IN_PROC_BROWSER_TEST_F(DownloadTest, DISABLED_DownloadMimeTypeSelect) {
497  ASSERT_TRUE(InitialSetup(true));
498  FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
499  GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
500
501  // Download the file and wait.  We expect the Select File dialog to appear
502  // due to the MIME type.
503  DownloadAndWait(browser(), url, EXPECT_SELECT_DIALOG);
504
505  // Check state.
506  EXPECT_EQ(1, browser()->tab_count());
507  // Since we exited while the Select File dialog was visible, there should not
508  // be anything in the download shelf and so it should not be visible.
509  EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
510}
511
512// Access a file with a viewable mime-type, verify that a download
513// did not initiate.
514IN_PROC_BROWSER_TEST_F(DownloadTest, NoDownload) {
515  ASSERT_TRUE(InitialSetup(false));
516  FilePath file(FILE_PATH_LITERAL("download-test2.html"));
517  GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
518  FilePath file_path = GetDownloadDirectory(browser()).Append(file);
519
520  // Open a web page and wait.
521  ui_test_utils::NavigateToURL(browser(), url);
522
523  // Check that we did not download the web page.
524  EXPECT_FALSE(file_util::PathExists(file_path));
525
526  // Check state.
527  EXPECT_EQ(1, browser()->tab_count());
528  EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
529}
530
531// Download a 0-size file with a content-disposition header, verify that the
532// download tab opened and the file exists as the filename specified in the
533// header.  This also ensures we properly handle empty file downloads.
534// The download shelf should be visible in the current tab.
535//
536// Test is believed mostly good (non-flaky) in itself, but it
537// sometimes trips over underlying flakiness in the downloads
538// subsystem in in http://crbug.com/63237.  Until that bug is
539// fixed, this test should be considered flaky.  It's entered as
540// DISABLED since if 63237 does cause a failure, it'll be a timeout.
541IN_PROC_BROWSER_TEST_F(DownloadTest, DISABLED_ContentDisposition) {
542  ASSERT_TRUE(InitialSetup(false));
543  FilePath file(FILE_PATH_LITERAL("download-test3.gif"));
544  GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
545  FilePath download_file(FILE_PATH_LITERAL("download-test3-attachment.gif"));
546
547  // Download a file and wait.
548  DownloadAndWait(browser(), url, EXPECT_NO_SELECT_DIALOG);
549
550  CheckDownload(browser(), download_file, file);
551
552  // Check state.
553  EXPECT_EQ(1, browser()->tab_count());
554  EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
555}
556
557// Test that the download shelf is per-window by starting a download in one
558// tab, opening a second tab, closing the shelf, going back to the first tab,
559// and checking that the shelf is closed.
560//
561// The test sometimes trips over underlying flakiness in the downloads
562// subsystem in in http://crbug.com/63237.  It's entered as
563// DISABLED since if 63237 does cause a failure, it'll be a timeout.
564IN_PROC_BROWSER_TEST_F(DownloadTest, DISABLED_PerWindowShelf) {
565  ASSERT_TRUE(InitialSetup(false));
566  FilePath file(FILE_PATH_LITERAL("download-test3.gif"));
567  GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
568  FilePath download_file(FILE_PATH_LITERAL("download-test3-attachment.gif"));
569
570  // Download a file and wait.
571  DownloadAndWait(browser(), url, EXPECT_NO_SELECT_DIALOG);
572
573  CheckDownload(browser(), download_file, file);
574
575  // Check state.
576  EXPECT_EQ(1, browser()->tab_count());
577  EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
578
579  // Open a second tab and wait.
580  EXPECT_NE(static_cast<TabContentsWrapper*>(NULL),
581            browser()->AddSelectedTabWithURL(GURL(), PageTransition::TYPED));
582  EXPECT_EQ(2, browser()->tab_count());
583  EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
584
585  // Hide the download shelf.
586  browser()->window()->GetDownloadShelf()->Close();
587  EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
588
589  // Go to the first tab.
590  browser()->SelectTabContentsAt(0, true);
591  EXPECT_EQ(2, browser()->tab_count());
592
593  // The download shelf should not be visible.
594  EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
595}
596
597// UnknownSize and KnownSize are tests which depend on
598// URLRequestSlowDownloadJob to serve content in a certain way. Data will be
599// sent in two chunks where the first chunk is 35K and the second chunk is 10K.
600// The test will first attempt to download a file; but the server will "pause"
601// in the middle until the server receives a second request for
602// "download-finish".  At that time, the download will finish.
603// These tests don't currently test much due to holes in |RunSizeTest()|.  See
604// comments in that routine for details.
605
606// Test is believed mostly good (non-flaky) in itself, but it
607// very occasionally trips over underlying flakiness in the downloads
608// subsystem in in http://crbug.com/63237.  Until that bug is
609// fixed, this test should be considered flaky.  It's entered as
610// DISABLED since if 63237 does cause a failure, it'll be a timeout.
611IN_PROC_BROWSER_TEST_F(DownloadTest, DISABLED_UnknownSize) {
612  GURL url(URLRequestSlowDownloadJob::kUnknownSizeUrl);
613  FilePath filename;
614  net::FileURLToFilePath(url, &filename);
615  filename = filename.BaseName();
616  ASSERT_TRUE(RunSizeTest(
617                  browser(),
618                  url,
619                  ASCIIToUTF16("32.0 KB - ") + filename.LossyDisplayName(),
620                  ASCIIToUTF16("100% - ") + filename.LossyDisplayName()));
621}
622
623// Test is believed mostly good (non-flaky) in itself, but it
624// very occasionally trips over underlying flakiness in the downloads
625// subsystem in in http://crbug.com/63237.  Until that bug is
626// fixed, this test should be considered flaky.  It's entered as
627// DISABLED since if 63237 does cause a failure, it'll be a timeout.
628IN_PROC_BROWSER_TEST_F(DownloadTest, DISABLED_KnownSize) {
629  GURL url(URLRequestSlowDownloadJob::kKnownSizeUrl);
630  FilePath filename;
631  net::FileURLToFilePath(url, &filename);
632  filename = filename.BaseName();
633  ASSERT_TRUE(RunSizeTest(
634                  browser(),
635                  url,
636                  ASCIIToUTF16("71% - ") + filename.LossyDisplayName(),
637                  ASCIIToUTF16("100% - ") + filename.LossyDisplayName()));
638}
639
640// Test that when downloading an item in Incognito mode, we don't crash when
641// closing the last Incognito window (http://crbug.com/13983).
642// Also check that the download shelf is not visible after closing the
643// Incognito window.
644//
645// Test is believed mostly good (non-flaky) in itself, but it
646// sometimes trips over underlying flakiness in the downloads
647// subsystem in in http://crbug.com/63237.  Until that bug is
648// fixed, this test should be considered flaky.  It's entered as
649// DISABLED since if 63237 does cause a failure, it'll be a timeout.
650IN_PROC_BROWSER_TEST_F(DownloadTest, DISABLED_IncognitoDownload) {
651  ASSERT_TRUE(InitialSetup(false));
652
653  // Open an Incognito window.
654  Browser* incognito = CreateIncognitoBrowser();  // Waits.
655  ASSERT_TRUE(incognito);
656  int window_count = BrowserList::size();
657  EXPECT_EQ(2, window_count);
658
659  // Download a file in the Incognito window and wait.
660  CreateAndSetDownloadsDirectory(incognito);
661  FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
662  GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
663  // Since |incognito| is a separate browser, we have to set it up explicitly.
664  incognito->profile()->GetPrefs()->SetBoolean(prefs::kPromptForDownload,
665                                               false);
666  DownloadAndWait(incognito, url, EXPECT_NO_SELECT_DIALOG);
667
668  // We should still have 2 windows.
669  window_count = BrowserList::size();
670  EXPECT_EQ(2, window_count);
671
672  // Verify that the download shelf is showing for the Incognito window.
673  bool is_shelf_visible = incognito->window()->IsDownloadShelfVisible();
674  EXPECT_TRUE(is_shelf_visible);
675
676  // Close the Incognito window and don't crash.
677  incognito->CloseWindow();
678#if !defined(OS_MACOSX)
679  // On Mac OS X, the UI window close is delayed until the outermost
680  // message loop runs.  So it isn't possible to get a BROWSER_CLOSED
681  // notification inside of a test.
682  ui_test_utils::WaitForNotificationFrom(NotificationType::BROWSER_CLOSED,
683                                         Source<Browser>(incognito));
684
685  window_count = BrowserList::size();
686  EXPECT_EQ(1, window_count);
687#endif
688
689  // Verify that the regular window does not have a download shelf.
690  is_shelf_visible = browser()->window()->IsDownloadShelfVisible();
691  EXPECT_FALSE(is_shelf_visible);
692
693  CheckDownload(browser(), file, file);
694}
695
696// Navigate to a new background page, but don't download.  Confirm that the
697// download shelf is not visible and that we have two tabs.
698IN_PROC_BROWSER_TEST_F(DownloadTest, DontCloseNewTab1) {
699  ASSERT_TRUE(InitialSetup(false));
700  // Because it's an HTML link, it should open a web page rather than
701  // downloading.
702  FilePath file1(FILE_PATH_LITERAL("download-test2.html"));
703  GURL url(URLRequestMockHTTPJob::GetMockUrl(file1));
704
705  // Open a web page and wait.
706  ui_test_utils::NavigateToURLWithDisposition(
707      browser(),
708      url,
709      NEW_BACKGROUND_TAB,
710      ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
711
712  // We should have two tabs now.
713  EXPECT_EQ(2, browser()->tab_count());
714  EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
715}
716
717// Download a file in a background tab. Verify that the tab is closed
718// automatically, and that the download shelf is visible in the current tab.
719//
720// The test sometimes trips over underlying flakiness in the downloads
721// subsystem in http://crbug.com/63237.  It's entered as
722// DISABLED since if 63237 does cause a failure, it'll be a timeout.
723IN_PROC_BROWSER_TEST_F(DownloadTest, DISABLED_CloseNewTab1) {
724  ASSERT_TRUE(InitialSetup(false));
725
726  // Download a file in a new background tab and wait.  The tab is automatically
727  // closed when the download begins.
728  FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
729  GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
730  DownloadAndWaitWithDisposition(
731      browser(),
732      url,
733      NEW_BACKGROUND_TAB,
734      EXPECT_NO_SELECT_DIALOG,
735      ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
736
737  // When the download finishes, we should still have one tab.
738  EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
739  EXPECT_EQ(1, browser()->tab_count());
740
741  CheckDownload(browser(), file, file);
742}
743
744// Open a web page in the current tab, then download a file in another tab via
745// a Javascript call.
746// Verify that we have 2 tabs, and the download shelf is visible in the current
747// tab.
748//
749// The download_page1.html page contains an openNew() function that opens a
750// tab and then downloads download-test1.lib.
751//
752// The test sometimes trips over underlying flakiness in the downloads
753// subsystem in in http://crbug.com/63237.  It's entered as
754// DISABLED since if 63237 does cause a failure, it'll be a timeout.
755IN_PROC_BROWSER_TEST_F(DownloadTest, DISABLED_DontCloseNewTab2) {
756  ASSERT_TRUE(InitialSetup(false));
757  // Because it's an HTML link, it should open a web page rather than
758  // downloading.
759  FilePath file1(FILE_PATH_LITERAL("download_page1.html"));
760  GURL url(URLRequestMockHTTPJob::GetMockUrl(file1));
761
762  // Open a web page and wait.
763  ui_test_utils::NavigateToURL(browser(), url);
764
765  // Download a file in a new tab and wait (via Javascript).
766  FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
767  DownloadAndWaitWithDisposition(browser(),
768                                 GURL("javascript:openNew()"),
769                                 CURRENT_TAB,
770                                 EXPECT_NO_SELECT_DIALOG,
771                                 ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
772
773  // When the download finishes, we should have two tabs.
774  EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
775  EXPECT_EQ(2, browser()->tab_count());
776
777  CheckDownload(browser(), file, file);
778}
779
780// Open a web page in the current tab, open another tab via a Javascript call,
781// then download a file in the new tab.
782// Verify that we have 2 tabs, and the download shelf is visible in the current
783// tab.
784//
785// The download_page2.html page contains an openNew() function that opens a
786// tab.
787//
788// The test sometimes trips over underlying flakiness in the downloads
789// subsystem in in http://crbug.com/63237.  It's entered as
790// DISABLED since if 63237 does cause a failure, it'll be a timeout.
791IN_PROC_BROWSER_TEST_F(DownloadTest, DISABLED_DontCloseNewTab3) {
792  ASSERT_TRUE(InitialSetup(false));
793  // Because it's an HTML link, it should open a web page rather than
794  // downloading.
795  FilePath file1(FILE_PATH_LITERAL("download_page2.html"));
796  GURL url1(URLRequestMockHTTPJob::GetMockUrl(file1));
797
798  // Open a web page and wait.
799  ui_test_utils::NavigateToURL(browser(), url1);
800
801  // Open a new tab and wait.
802  ui_test_utils::NavigateToURLWithDisposition(
803      browser(),
804      GURL("javascript:openNew()"),
805      CURRENT_TAB,
806      ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
807
808  EXPECT_EQ(2, browser()->tab_count());
809
810  // Download a file and wait.
811  FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
812  GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
813  DownloadAndWaitWithDisposition(browser(),
814                                 url,
815                                 CURRENT_TAB,
816                                 EXPECT_NO_SELECT_DIALOG,
817                                 ui_test_utils::BROWSER_TEST_NONE);
818
819  // When the download finishes, we should have two tabs.
820  EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
821  EXPECT_EQ(2, browser()->tab_count());
822
823  CheckDownload(browser(), file, file);
824}
825
826// Open a web page in the current tab, then download a file via Javascript,
827// which will do so in a temporary tab.
828// Verify that we have 1 tab, and the download shelf is visible.
829//
830// The download_page3.html page contains an openNew() function that opens a
831// tab with download-test1.lib in the URL.  When the URL is determined to be
832// a download, the tab is closed automatically.
833//
834// The test sometimes trips over underlying flakiness in the downloads
835// subsystem in in http://crbug.com/63237.  It's entered as
836// DISABLED since if 63237 does cause a failure, it'll be a timeout.
837IN_PROC_BROWSER_TEST_F(DownloadTest, DISABLED_CloseNewTab2) {
838  ASSERT_TRUE(InitialSetup(false));
839  // Because it's an HTML link, it should open a web page rather than
840  // downloading.
841  FilePath file1(FILE_PATH_LITERAL("download_page3.html"));
842  GURL url(URLRequestMockHTTPJob::GetMockUrl(file1));
843
844  // Open a web page and wait.
845  ui_test_utils::NavigateToURL(browser(), url);
846
847  // Download a file and wait.
848  // The file to download is "download-test1.lib".
849  FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
850  DownloadAndWaitWithDisposition(browser(),
851                                 GURL("javascript:openNew()"),
852                                 CURRENT_TAB,
853                                 EXPECT_NO_SELECT_DIALOG,
854                                 ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
855
856  // When the download finishes, we should still have one tab.
857  EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
858  EXPECT_EQ(1, browser()->tab_count());
859
860  CheckDownload(browser(), file, file);
861}
862
863// Open a web page in the current tab, then call Javascript via a button to
864// download a file in a new tab, which is closed automatically when the
865// download begins.
866// Verify that we have 1 tab, and the download shelf is visible.
867//
868// The download_page4.html page contains a form with download-test1.lib as the
869// action.
870//
871// The test sometimes trips over underlying flakiness in the downloads
872// subsystem in in http://crbug.com/63237.  It's entered as
873// DISABLED since if 63237 does cause a failure, it'll be a timeout.
874IN_PROC_BROWSER_TEST_F(DownloadTest, DISABLED_CloseNewTab3) {
875  ASSERT_TRUE(InitialSetup(false));
876  // Because it's an HTML link, it should open a web page rather than
877  // downloading.
878  FilePath file1(FILE_PATH_LITERAL("download_page4.html"));
879  GURL url(URLRequestMockHTTPJob::GetMockUrl(file1));
880
881  // Open a web page and wait.
882  ui_test_utils::NavigateToURL(browser(), url);
883
884  // Download a file in a new tab and wait.  The tab will automatically close
885  // when the download begins.
886  // The file to download is "download-test1.lib".
887  FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
888  DownloadAndWaitWithDisposition(
889      browser(),
890      GURL("javascript:document.getElementById('form').submit()"),
891      CURRENT_TAB,
892      EXPECT_NO_SELECT_DIALOG,
893      ui_test_utils::BROWSER_TEST_WAIT_FOR_TAB);
894
895  // When the download finishes, we should still have one tab.
896  EXPECT_TRUE(browser()->window()->IsDownloadShelfVisible());
897  EXPECT_EQ(1, browser()->tab_count());
898
899  CheckDownload(browser(), file, file);
900}
901
902// Download a file in a new window.
903// Verify that we have 2 windows, and the download shelf is not visible in the
904// first window, but is visible in the second window.
905// Close the new window.
906// Verify that we have 1 window, and the download shelf is not visible.
907//
908// Regression test for http://crbug.com/44454
909//
910// Test is believed mostly good (non-flaky) in itself, but it
911// sometimes trips over underlying flakiness in the downloads
912// subsystem in in http://crbug.com/63237.  Until that bug is
913// fixed, this test should be considered flaky.  It's entered as
914// DISABLED since if 63237 does cause a failure, it'll be a timeout.
915IN_PROC_BROWSER_TEST_F(DownloadTest, DISABLED_NewWindow) {
916  ASSERT_TRUE(InitialSetup(false));
917  FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
918  GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
919#if !defined(OS_MACOSX)
920  // See below.
921  Browser* first_browser = browser();
922#endif
923
924  // Download a file in a new window and wait.
925  DownloadAndWaitWithDisposition(browser(),
926                                 url,
927                                 NEW_WINDOW,
928                                 EXPECT_NO_SELECT_DIALOG,
929                                 ui_test_utils::BROWSER_TEST_NONE);
930
931  // When the download finishes, the download shelf SHOULD NOT be visible in
932  // the first window.
933  int window_count = BrowserList::size();
934  EXPECT_EQ(2, window_count);
935  EXPECT_EQ(1, browser()->tab_count());
936  EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
937
938  // The download shelf SHOULD be visible in the second window.
939  std::set<Browser*> original_browsers;
940  original_browsers.insert(browser());
941  Browser* download_browser =
942      ui_test_utils::GetBrowserNotInSet(original_browsers);
943  ASSERT_TRUE(download_browser != NULL);
944  EXPECT_NE(download_browser, browser());
945  EXPECT_EQ(1, download_browser->tab_count());
946  EXPECT_TRUE(download_browser->window()->IsDownloadShelfVisible());
947
948  // Close the new window.
949  download_browser->CloseWindow();
950#if !defined(OS_MACOSX)
951  // On Mac OS X, the UI window close is delayed until the outermost
952  // message loop runs.  So it isn't possible to get a BROWSER_CLOSED
953  // notification inside of a test.
954  ui_test_utils::WaitForNotificationFrom(NotificationType::BROWSER_CLOSED,
955                                         Source<Browser>(download_browser));
956  EXPECT_EQ(first_browser, browser());
957  window_count = BrowserList::size();
958  EXPECT_EQ(1, window_count);
959#endif
960
961  EXPECT_EQ(1, browser()->tab_count());
962  // The download shelf should not be visible in the remaining window.
963  EXPECT_FALSE(browser()->window()->IsDownloadShelfVisible());
964
965  CheckDownload(browser(), file, file);
966}
967
968}  // namespace
969