summaryrefslogtreecommitdiffstats
path: root/chrome/browser/download/download_manager_unittest.cc
blob: d2a48042e4dbe69640e4cbe340b3d23029eb4d74 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <string>
#include <set>

#include "base/scoped_ptr.h"
#include "base/string_util.h"
#include "build/build_config.h"
#include "chrome/browser/download/download_file.h"
#include "chrome/browser/download/download_file_manager.h"
#include "chrome/browser/download/download_item.h"
#include "chrome/browser/download/download_manager.h"
#include "chrome/browser/download/download_prefs.h"
#include "chrome/browser/download/download_status_updater.h"
#include "chrome/browser/download/download_util.h"
#include "chrome/browser/download/mock_download_manager.h"
#include "chrome/browser/history/download_create_info.h"
#include "chrome/browser/prefs/pref_service.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/testing_profile.h"
#include "content/browser/browser_thread.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gmock_mutant.h"
#include "testing/gtest/include/gtest/gtest.h"

class DownloadManagerTest : public testing::Test {
 public:
  DownloadManagerTest()
      : profile_(new TestingProfile()),
        download_manager_(new MockDownloadManager(&download_status_updater_)),
        ui_thread_(BrowserThread::UI, &message_loop_),
        file_thread_(BrowserThread::FILE, &message_loop_) {
    download_manager_->Init(profile_.get());
  }

  ~DownloadManagerTest() {
    download_manager_->Shutdown();
    // profile_ must outlive download_manager_, so we explicitly delete
    // download_manager_ first.
    download_manager_ = NULL;
    profile_.reset(NULL);
    message_loop_.RunAllPending();
  }

  void AddDownloadToFileManager(int id, DownloadFile* download) {
    file_manager()->downloads_[id] = download;
  }

 protected:
  DownloadStatusUpdater download_status_updater_;
  scoped_ptr<TestingProfile> profile_;
  scoped_refptr<DownloadManager> download_manager_;
  scoped_refptr<DownloadFileManager> file_manager_;
  MessageLoopForUI message_loop_;
  BrowserThread ui_thread_;
  BrowserThread file_thread_;

  DownloadFileManager* file_manager() {
    if (!file_manager_) {
      file_manager_ = new DownloadFileManager(NULL);
      download_manager_->file_manager_ = file_manager_;
    }
    return file_manager_;
  }

  // Make sure download item |id| was set with correct safety state for
  // given |is_dangerous_file| and |is_dangerous_url|.
  bool VerifySafetyState(bool is_dangerous_file,
                         bool is_dangerous_url,
                         int id) {
    DownloadItem::SafetyState safety_state =
        download_manager_->GetDownloadItem(id)->safety_state();
    return (is_dangerous_file || is_dangerous_url) ?
        safety_state != DownloadItem::SAFE : safety_state == DownloadItem::SAFE;
  }

  DISALLOW_COPY_AND_ASSIGN(DownloadManagerTest);
};

namespace {

const struct {
  const char* url;
  const char* mime_type;
  bool save_as;
  bool prompt_for_download;
  bool expected_save_as;
} kStartDownloadCases[] = {
  { "http://www.foo.com/dont-open.html",
    "text/html",
    false,
    false,
    false, },
  { "http://www.foo.com/save-as.html",
    "text/html",
    true,
    false,
    true, },
  { "http://www.foo.com/always-prompt.html",
    "text/html",
    false,
    true,
    true, },
  { "http://www.foo.com/user-script-text-html-mimetype.user.js",
    "text/html",
    false,
    false,
    false, },
  { "http://www.foo.com/extensionless-extension",
    "application/x-chrome-extension",
    true,
    false,
    true, },
  { "http://www.foo.com/save-as.pdf",
    "application/pdf",
    true,
    false,
    true, },
  { "http://www.foo.com/sometimes_prompt.pdf",
    "application/pdf",
    false,
    true,
    false, },
  { "http://www.foo.com/always_prompt.jar",
    "application/jar",
    false,
    true,
    true, },
};

const struct {
  FilePath::StringType suggested_path;
  bool is_dangerous_file;
  bool is_dangerous_url;
  bool finish_before_rename;
  int expected_rename_count;
} kDownloadRenameCases[] = {
  // Safe download, download finishes BEFORE file name determined.
  // Renamed twice (linear path through UI).  Crdownload file does not need
  // to be deleted.
  { FILE_PATH_LITERAL("foo.zip"),
    false, false, true, 2, },
  // Dangerous download (file is dangerous or download URL is not safe or both),
  // download finishes BEFORE file name determined. Needs to be renamed only
  // once.
  { FILE_PATH_LITERAL("Unconfirmed xxx.crdownload"),
    true, false, true, 1, },
  { FILE_PATH_LITERAL("Unconfirmed xxx.crdownload"),
    false, true, true, 1, },
  { FILE_PATH_LITERAL("Unconfirmed xxx.crdownload"),
    true, true, true, 1, },
  // Safe download, download finishes AFTER file name determined.
  // Needs to be renamed twice.
  { FILE_PATH_LITERAL("foo.zip"),
    false, false, false, 2, },
  // Dangerous download, download finishes AFTER file name determined.
  // Needs to be renamed only once.
  { FILE_PATH_LITERAL("Unconfirmed xxx.crdownload"),
    true, false, false, 1, },
  { FILE_PATH_LITERAL("Unconfirmed xxx.crdownload"),
    false, true, false, 1, },
  { FILE_PATH_LITERAL("Unconfirmed xxx.crdownload"),
    true, true, false, 1, },
};

class MockDownloadFile : public DownloadFile {
 public:
  MockDownloadFile(DownloadCreateInfo* info, DownloadManager* manager)
      : DownloadFile(info, manager), renamed_count_(0) { }
  virtual ~MockDownloadFile() { Destructed(); }
  MOCK_METHOD1(Rename, bool(const FilePath&));
  MOCK_METHOD0(Destructed, void());

  bool TestMultipleRename(
      int expected_count, const FilePath& expected,
      const FilePath& path) {
    ++renamed_count_;
    EXPECT_EQ(expected_count, renamed_count_);
    EXPECT_EQ(expected.value(), path.value());
    return true;
  }

 private:
  int renamed_count_;
};

// This is an observer that records what download IDs have opened a select
// file dialog.
class SelectFileObserver : public DownloadManager::Observer {
 public:
  explicit SelectFileObserver(DownloadManager* download_manager)
      : download_manager_(download_manager) {
    DCHECK(download_manager_);
    download_manager_->AddObserver(this);
  }

  ~SelectFileObserver() {
    download_manager_->RemoveObserver(this);
  }

  // Downloadmanager::Observer functions.
  virtual void ModelChanged() {}
  virtual void ManagerGoingDown() {}
  virtual void SelectFileDialogDisplayed(int32 id) {
    file_dialog_ids_.insert(id);
  }

  bool ShowedFileDialogForId(int32 id) {
    return file_dialog_ids_.find(id) != file_dialog_ids_.end();
  }

 private:
  std::set<int32> file_dialog_ids_;
  DownloadManager* download_manager_;
};

}  // namespace

#if !defined(OS_CHROMEOS)

TEST_F(DownloadManagerTest, StartDownload) {
  BrowserThread io_thread(BrowserThread::IO, &message_loop_);
  PrefService* prefs = profile_->GetPrefs();
  prefs->SetFilePath(prefs::kDownloadDefaultDirectory, FilePath());
  download_manager_->download_prefs()->EnableAutoOpenBasedOnExtension(
      FilePath(FILE_PATH_LITERAL("example.pdf")));

  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kStartDownloadCases); ++i) {
    prefs->SetBoolean(prefs::kPromptForDownload,
                      kStartDownloadCases[i].prompt_for_download);

    SelectFileObserver observer(download_manager_);
    DownloadCreateInfo* info = new DownloadCreateInfo;
    info->download_id = static_cast<int>(i);
    info->prompt_user_for_save_location = kStartDownloadCases[i].save_as;
    info->url = GURL(kStartDownloadCases[i].url);
    info->mime_type = kStartDownloadCases[i].mime_type;
    download_manager_->CreateDownloadItem(info);

    DownloadFile* download(new DownloadFile(info, download_manager_));
    AddDownloadToFileManager(info->download_id, download);
    download->Initialize(false);
    download_manager_->StartDownload(info);
    message_loop_.RunAllPending();

    // NOTE: At this point, |AttachDownloadItem| will have been run if we don't
    // need to prompt the user, so |info| could have been destructed.
    // This means that we can't check any of its values.
    // However, SelectFileObserver will have recorded any attempt to open the
    // select file dialog.
    EXPECT_EQ(kStartDownloadCases[i].expected_save_as,
              observer.ShowedFileDialogForId(i));

    // If the Save As dialog pops up, it never reached
    // DownloadManager::AttachDownloadItem(), and never deleted info or
    // completed.  This cleans up info.
    // Note that DownloadManager::FileSelectionCanceled() is never called.
    if (observer.ShowedFileDialogForId(i)) {
      delete info;
    }
  }
}

#endif // !defined(OS_CHROMEOS)

TEST_F(DownloadManagerTest, DownloadRenameTest) {
  using ::testing::_;
  using ::testing::CreateFunctor;
  using ::testing::Invoke;
  using ::testing::Return;

  for (size_t i = 0; i < ARRAYSIZE_UNSAFE(kDownloadRenameCases); ++i) {
    // |info| will be destroyed in download_manager_.
    DownloadCreateInfo* info(new DownloadCreateInfo);
    info->download_id = static_cast<int>(i);
    info->prompt_user_for_save_location = false;
    info->is_dangerous_file = kDownloadRenameCases[i].is_dangerous_file;
    info->is_dangerous_url = kDownloadRenameCases[i].is_dangerous_url;
    FilePath new_path(kDownloadRenameCases[i].suggested_path);

    MockDownloadFile* download(new MockDownloadFile(info, download_manager_));
    AddDownloadToFileManager(info->download_id, download);

    // |download| is owned by DownloadFileManager.
    ::testing::Mock::AllowLeak(download);
    EXPECT_CALL(*download, Destructed()).Times(1);

    if (kDownloadRenameCases[i].expected_rename_count == 1) {
      EXPECT_CALL(*download, Rename(new_path)).WillOnce(Return(true));
    } else {
      ASSERT_EQ(2, kDownloadRenameCases[i].expected_rename_count);
      FilePath crdownload(download_util::GetCrDownloadPath(new_path));
      EXPECT_CALL(*download, Rename(_))
          .WillOnce(testing::WithArgs<0>(Invoke(CreateFunctor(
              download, &MockDownloadFile::TestMultipleRename,
              1, crdownload))))
          .WillOnce(testing::WithArgs<0>(Invoke(CreateFunctor(
              download, &MockDownloadFile::TestMultipleRename,
              2, new_path))));
    }
    download_manager_->CreateDownloadItem(info);

    if (kDownloadRenameCases[i].finish_before_rename) {
      download_manager_->OnAllDataSaved(i, 1024, std::string("fake_hash"));
      message_loop_.RunAllPending();
      download_manager_->FileSelected(new_path, i, info);
    } else {
      download_manager_->FileSelected(new_path, i, info);
      message_loop_.RunAllPending();
      download_manager_->OnAllDataSaved(i, 1024, std::string("fake_hash"));
    }

    message_loop_.RunAllPending();
    EXPECT_TRUE(VerifySafetyState(kDownloadRenameCases[i].is_dangerous_file,
                                  kDownloadRenameCases[i].is_dangerous_url,
                                  i));
  }
}