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.
5 #include "base/auto_reset.h"
6 #include "base/files/scoped_temp_dir.h"
7 #include "base/json/json_reader.h"
8 #include "base/prefs/pref_service.h"
9 #include "base/values.h"
10 #include "chrome/browser/download/download_item_model.h"
11 #include "chrome/browser/profiles/profile.h"
12 #include "chrome/browser/ui/browser.h"
13 #include "chrome/browser/ui/webui/downloads_dom_handler.h"
14 #include "chrome/common/pref_names.h"
15 #include "chrome/test/base/in_process_browser_test.h"
16 #include "content/public/browser/web_contents.h"
17 #include "content/public/test/mock_download_item.h"
18 #include "content/public/test/mock_download_manager.h"
19 #include "content/public/test/test_utils.h"
23 // Reads |right_json| into a ListValue |left_list|; returns true if all
24 // key-value pairs in in all dictionaries in |right_list| are also in the
25 // corresponding dictionary in |left_list|. Ignores keys in dictionaries in
26 // |left_list| that are not in the corresponding dictionary in |right_list|.
27 bool ListMatches(base::ListValue
* left_list
, const std::string
& right_json
) {
28 scoped_ptr
<base::Value
> right_value(base::JSONReader::Read(right_json
));
29 base::ListValue
* right_list
= NULL
;
30 CHECK(right_value
->GetAsList(&right_list
));
31 for (size_t i
= 0; i
< left_list
->GetSize(); ++i
) {
32 base::DictionaryValue
* left_dict
= NULL
;
33 base::DictionaryValue
* right_dict
= NULL
;
34 CHECK(left_list
->GetDictionary(i
, &left_dict
));
35 CHECK(right_list
->GetDictionary(i
, &right_dict
));
36 for (base::DictionaryValue::Iterator
iter(*right_dict
);
37 !iter
.IsAtEnd(); iter
.Advance()) {
38 base::Value
* left_value
= NULL
;
39 if (left_dict
->HasKey(iter
.key()) &&
40 left_dict
->Get(iter
.key(), &left_value
) &&
41 !iter
.value().Equals(left_value
)) {
42 LOG(WARNING
) << "key \"" << iter
.key() << "\" doesn't match ("
43 << iter
.value() << " vs. " << *left_value
<< ")";
51 // A |DownloadsDOMHandler| that doesn't use a real WebUI object, but is real in
52 // all other respects.
53 class MockDownloadsDOMHandler
: public DownloadsDOMHandler
{
55 explicit MockDownloadsDOMHandler(content::DownloadManager
* dlm
)
56 : DownloadsDOMHandler(dlm
),
58 waiting_updated_(false),
61 ~MockDownloadsDOMHandler() override
{}
63 base::ListValue
* downloads_list() { return downloads_list_
.get(); }
64 base::ListValue
* download_updated() { return download_updated_
.get(); }
66 void WaitForDownloadsList() {
67 if (downloads_list_
.get())
69 base::AutoReset
<bool> reset_waiting(&waiting_list_
, true);
70 content::RunMessageLoop();
73 void WaitForDownloadUpdated() {
74 if (download_updated_
.get())
76 base::AutoReset
<bool> reset_waiting(&waiting_updated_
, true);
77 content::RunMessageLoop();
80 void ForceSendCurrentDownloads() {
81 ScheduleSendCurrentDownloads();
84 void reset_downloads_list() { downloads_list_
.reset(); }
85 void reset_download_updated() { download_updated_
.reset(); }
87 void set_manager(content::DownloadManager
* manager
) { manager_
= manager
; }
89 using DownloadsDOMHandler::FinalizeRemovals
;
92 content::WebContents
* GetWebUIWebContents() override
{ return NULL
; }
94 void CallDownloadsList(const base::ListValue
& downloads
) override
{
95 downloads_list_
.reset(downloads
.DeepCopy());
97 content::BrowserThread::PostTask(content::BrowserThread::UI
,
99 base::MessageLoop::QuitClosure());
103 void CallDownloadUpdated(const base::ListValue
& download
) override
{
104 download_updated_
.reset(download
.DeepCopy());
105 if (waiting_updated_
) {
106 content::BrowserThread::PostTask(content::BrowserThread::UI
,
108 base::MessageLoop::QuitClosure());
112 content::DownloadManager
* GetMainNotifierManager() override
{
113 return manager_
? manager_
: DownloadsDOMHandler::GetMainNotifierManager();
117 scoped_ptr
<base::ListValue
> downloads_list_
;
118 scoped_ptr
<base::ListValue
> download_updated_
;
120 bool waiting_updated_
;
121 content::DownloadManager
* manager_
; // weak.
123 DISALLOW_COPY_AND_ASSIGN(MockDownloadsDOMHandler
);
128 class DownloadsDOMHandlerTest
: public InProcessBrowserTest
{
130 DownloadsDOMHandlerTest() {}
132 ~DownloadsDOMHandlerTest() override
{}
134 void SetUpOnMainThread() override
{
135 mock_handler_
.reset(new MockDownloadsDOMHandler(download_manager()));
136 CHECK(downloads_directory_
.CreateUniqueTempDir());
137 browser()->profile()->GetPrefs()->SetFilePath(
138 prefs::kDownloadDefaultDirectory
,
139 downloads_directory_
.path());
140 CHECK(test_server()->Start());
143 content::DownloadManager
* download_manager() {
144 return content::BrowserContext::GetDownloadManager(browser()->profile());
147 void DownloadAnItem() {
148 GURL url
= test_server()->GetURL("files/downloads/image.jpg");
149 std::vector
<GURL
> url_chain
;
150 url_chain
.push_back(url
);
151 base::Time
current(base::Time::Now());
152 download_manager()->CreateDownloadItem(
154 base::FilePath(FILE_PATH_LITERAL("/path/to/file")),
155 base::FilePath(FILE_PATH_LITERAL("/path/to/file")),
158 "application/octet-stream",
159 "application/octet-stream",
166 content::DownloadItem::COMPLETE
,
167 content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS
,
168 content::DOWNLOAD_INTERRUPT_REASON_NONE
,
171 mock_handler_
->WaitForDownloadsList();
172 ASSERT_EQ(1, static_cast<int>(mock_handler_
->downloads_list()->GetSize()));
173 EXPECT_TRUE(ListMatches(
174 mock_handler_
->downloads_list(),
175 "[{\"file_externally_removed\": false,"
176 " \"file_name\": \"file\","
179 " \"since_string\": \"Today\","
180 " \"state\": \"COMPLETE\","
181 " \"total\": 128}]"));
185 scoped_ptr
<MockDownloadsDOMHandler
> mock_handler_
;
188 base::ScopedTempDir downloads_directory_
;
190 DISALLOW_COPY_AND_ASSIGN(DownloadsDOMHandlerTest
);
193 // Tests removing all items, both when prohibited and when allowed.
194 IN_PROC_BROWSER_TEST_F(DownloadsDOMHandlerTest
, RemoveAll
) {
197 mock_handler_
->reset_downloads_list();
198 browser()->profile()->GetPrefs()->SetBoolean(
199 prefs::kAllowDeletingBrowserHistory
, false);
200 mock_handler_
->HandleClearAll(NULL
);
201 // Attempting to clear all shouldn't do anything when deletion is disabled.
202 mock_handler_
->ForceSendCurrentDownloads();
203 mock_handler_
->WaitForDownloadsList();
204 ASSERT_EQ(1, static_cast<int>(mock_handler_
->downloads_list()->GetSize()));
206 mock_handler_
->reset_downloads_list();
207 browser()->profile()->GetPrefs()->SetBoolean(
208 prefs::kAllowDeletingBrowserHistory
, true);
209 mock_handler_
->HandleClearAll(NULL
);
210 mock_handler_
->WaitForDownloadsList();
211 EXPECT_EQ(0, static_cast<int>(mock_handler_
->downloads_list()->GetSize()));
214 // Tests removing one item, both when prohibited and when allowed.
215 IN_PROC_BROWSER_TEST_F(DownloadsDOMHandlerTest
, RemoveOneItem
) {
217 base::ListValue item
;
218 item
.AppendString("1");
220 mock_handler_
->reset_downloads_list();
221 browser()->profile()->GetPrefs()->SetBoolean(
222 prefs::kAllowDeletingBrowserHistory
, false);
223 mock_handler_
->HandleRemove(&item
);
224 // Removing an item only sends the new download list if anything was actually
225 // removed, so force it.
226 mock_handler_
->ForceSendCurrentDownloads();
227 mock_handler_
->WaitForDownloadsList();
228 ASSERT_EQ(1, static_cast<int>(mock_handler_
->downloads_list()->GetSize()));
230 mock_handler_
->reset_downloads_list();
231 browser()->profile()->GetPrefs()->SetBoolean(
232 prefs::kAllowDeletingBrowserHistory
, true);
233 mock_handler_
->HandleRemove(&item
);
234 mock_handler_
->WaitForDownloadsList();
235 EXPECT_EQ(0, static_cast<int>(mock_handler_
->downloads_list()->GetSize()));
238 IN_PROC_BROWSER_TEST_F(DownloadsDOMHandlerTest
, ClearAllSkipsInProgress
) {
239 content::MockDownloadManager manager
;
240 mock_handler_
->set_manager(&manager
);
242 content::MockDownloadItem item
;
243 EXPECT_CALL(item
, GetState()).WillRepeatedly(
244 testing::Return(content::DownloadItem::IN_PROGRESS
));
245 EXPECT_CALL(item
, UpdateObservers()).Times(0);
247 std::vector
<content::DownloadItem
*> items
;
248 items
.push_back(&item
);
249 EXPECT_CALL(manager
, GetAllDownloads(testing::_
)).WillOnce(
250 testing::SetArgPointee
<0>(items
));
252 mock_handler_
->HandleClearAll(NULL
);
253 EXPECT_TRUE(DownloadItemModel(&item
).ShouldShowInShelf());
256 // Tests that DownloadsDOMHandler detects new downloads and relays them to the
258 // crbug.com/159390: This test fails when daylight savings time ends.
259 IN_PROC_BROWSER_TEST_F(DownloadsDOMHandlerTest
, DownloadsRelayed
) {
262 mock_handler_
->WaitForDownloadUpdated();
263 ASSERT_EQ(1, static_cast<int>(mock_handler_
->download_updated()->GetSize()));
264 EXPECT_TRUE(ListMatches(
265 mock_handler_
->download_updated(),
266 "[{\"file_externally_removed\": true,"
267 " \"id\": \"1\"}]"));
269 mock_handler_
->reset_downloads_list();
270 browser()->profile()->GetPrefs()->SetBoolean(
271 prefs::kAllowDeletingBrowserHistory
, true);
272 mock_handler_
->HandleClearAll(NULL
);
273 mock_handler_
->WaitForDownloadsList();
274 EXPECT_EQ(0, static_cast<int>(mock_handler_
->downloads_list()->GetSize()));
277 // Tests that DownloadsDOMHandler actually calls DownloadItem::Remove() when
278 // it's closed (and removals can no longer be undone).
279 IN_PROC_BROWSER_TEST_F(DownloadsDOMHandlerTest
, RemoveCalledOnPageClose
) {
280 content::MockDownloadManager manager
;
281 mock_handler_
->set_manager(&manager
);
283 content::MockDownloadItem item
;
284 EXPECT_CALL(item
, GetId()).WillRepeatedly(testing::Return(1));
285 EXPECT_CALL(item
, GetState()).WillRepeatedly(
286 testing::Return(content::DownloadItem::COMPLETE
));
288 DownloadItemModel
model(&item
);
289 EXPECT_TRUE(model
.ShouldShowInShelf());
291 EXPECT_CALL(manager
, GetDownload(1)).WillRepeatedly(testing::Return(&item
));
293 base::ListValue remove
;
294 remove
.AppendString("1");
295 EXPECT_CALL(item
, UpdateObservers()).Times(1);
296 mock_handler_
->HandleRemove(&remove
);
297 EXPECT_FALSE(model
.ShouldShowInShelf());
299 EXPECT_CALL(item
, Remove()).Times(1);
300 // Call |mock_handler_->FinalizeRemovals()| instead of |mock_handler_.reset()|
301 // because the vtable is affected during destruction and the fake manager
302 // rigging doesn't work.
303 mock_handler_
->FinalizeRemovals();
306 // TODO(benjhayden): Test the extension downloads filter for both
307 // mock_handler_.downloads_list() and mock_handler_.download_updated().
309 // TODO(benjhayden): Test incognito, both downloads_list() and that on-record
310 // calls can't access off-record items.
312 // TODO(benjhayden): Test that bad download ids incoming from the javascript are
313 // dropped on the floor.
315 // TODO(benjhayden): Test that IsTemporary() downloads are not shown.
317 // TODO(benjhayden): Test that RemoveObserver is called on all download items,
318 // including items that crossed IsTemporary() and back.