Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(152)

Side by Side Diff: chrome/browser/extensions/api/downloads/downloads_api_unittest.cc

Issue 16924017: A few minor changes to the chrome.downloads extension API (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: @r214130 Created 7 years, 4 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
(Empty)
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 <algorithm>
6
7 #include "base/file_util.h"
8 #include "base/files/scoped_temp_dir.h"
9 #include "base/json/json_reader.h"
10 #include "base/message_loop/message_loop.h"
11 #include "base/prefs/pref_service.h"
12 #include "base/stl_util.h"
13 #include "base/strings/stringprintf.h"
14 #include "chrome/browser/chrome_notification_types.h"
15 #include "chrome/browser/download/download_file_icon_extractor.h"
16 #include "chrome/browser/download/download_service.h"
17 #include "chrome/browser/download/download_service_factory.h"
18 #include "chrome/browser/download/download_test_file_activity_observer.h"
19 #include "chrome/browser/extensions/api/downloads/downloads_api.h"
20 #include "chrome/browser/extensions/event_names.h"
21 #include "chrome/browser/extensions/extension_apitest.h"
22 #include "chrome/browser/extensions/extension_function_test_utils.h"
23 #include "chrome/browser/extensions/extension_service.h"
24 #include "chrome/browser/history/download_row.h"
25 #include "chrome/browser/net/url_request_mock_util.h"
26 #include "chrome/browser/profiles/profile.h"
27 #include "chrome/browser/ui/browser.h"
28 #include "chrome/browser/ui/browser_tabstrip.h"
29 #include "chrome/common/pref_names.h"
30 #include "chrome/test/base/in_process_browser_test.h"
31 #include "chrome/test/base/ui_test_utils.h"
32 #include "content/public/browser/browser_context.h"
33 #include "content/public/browser/browser_thread.h"
34 #include "content/public/browser/download_item.h"
35 #include "content/public/browser/download_manager.h"
36 #include "content/public/browser/notification_service.h"
37 #include "content/public/browser/storage_partition.h"
38 #include "content/public/browser/web_contents.h"
39 #include "content/public/common/content_switches.h"
40 #include "content/public/common/page_transition_types.h"
41 #include "content/public/test/download_test_observer.h"
42 #include "content/test/net/url_request_slow_download_job.h"
43 #include "net/base/data_url.h"
44 #include "net/base/net_util.h"
45 #include "net/url_request/url_request.h"
46 #include "net/url_request/url_request_context.h"
47 #include "net/url_request/url_request_job.h"
48 #include "net/url_request/url_request_job_factory.h"
49 #include "net/url_request/url_request_job_factory_impl.h"
50 #include "webkit/browser/blob/blob_storage_controller.h"
51 #include "webkit/browser/blob/blob_url_request_job.h"
52 #include "webkit/browser/fileapi/file_system_context.h"
53 #include "webkit/browser/fileapi/file_system_operation_runner.h"
54 #include "webkit/browser/fileapi/file_system_url.h"
55 #include "webkit/common/blob/blob_data.h"
56
57 using content::BrowserContext;
58 using content::BrowserThread;
59 using content::DownloadItem;
60 using content::DownloadManager;
61 using content::URLRequestSlowDownloadJob;
62
63 namespace events = extensions::event_names;
64
65 namespace {
66
67 // Comparator that orders download items by their ID. Can be used with
68 // std::sort.
69 struct DownloadIdComparator {
70 bool operator() (DownloadItem* first, DownloadItem* second) {
71 return first->GetId() < second->GetId();
72 }
73 };
74
75 class DownloadsEventsListener : public content::NotificationObserver {
76 public:
77 DownloadsEventsListener()
78 : waiting_(false) {
79 registrar_.Add(this, chrome::NOTIFICATION_EXTENSION_DOWNLOADS_EVENT,
80 content::NotificationService::AllSources());
81 }
82
83 virtual ~DownloadsEventsListener() {
84 registrar_.Remove(this, chrome::NOTIFICATION_EXTENSION_DOWNLOADS_EVENT,
85 content::NotificationService::AllSources());
86 STLDeleteElements(&events_);
87 }
88
89 void ClearEvents() {
90 STLDeleteElements(&events_);
91 events_.clear();
92 }
93
94 class Event {
95 public:
96 Event(Profile* profile,
97 const std::string& event_name,
98 const std::string& json_args,
99 base::Time caught)
100 : profile_(profile),
101 event_name_(event_name),
102 json_args_(json_args),
103 args_(base::JSONReader::Read(json_args)),
104 caught_(caught) {
105 }
106
107 const base::Time& caught() { return caught_; }
108
109 bool Satisfies(const Event& other) const {
110 return other.SatisfiedBy(*this);
111 }
112
113 bool SatisfiedBy(const Event& other) const {
114 if ((profile_ != other.profile_) ||
115 (event_name_ != other.event_name_))
116 return false;
117 if (((event_name_ == events::kOnDownloadDeterminingFilename) ||
118 (event_name_ == events::kOnDownloadCreated) ||
119 (event_name_ == events::kOnDownloadChanged)) &&
120 args_.get() &&
121 other.args_.get()) {
122 base::ListValue* left_list = NULL;
123 base::DictionaryValue* left_dict = NULL;
124 base::ListValue* right_list = NULL;
125 base::DictionaryValue* right_dict = NULL;
126 if (!args_->GetAsList(&left_list) ||
127 !other.args_->GetAsList(&right_list) ||
128 !left_list->GetDictionary(0, &left_dict) ||
129 !right_list->GetDictionary(0, &right_dict))
130 return false;
131 for (base::DictionaryValue::Iterator iter(*left_dict);
132 !iter.IsAtEnd(); iter.Advance()) {
133 base::Value* right_value = NULL;
134 if (!right_dict->HasKey(iter.key()) ||
135 (right_dict->Get(iter.key(), &right_value) &&
136 !iter.value().Equals(right_value))) {
137 return false;
138 }
139 }
140 return true;
141 } else if ((event_name_ == events::kOnDownloadErased) &&
142 args_.get() &&
143 other.args_.get()) {
144 int my_id = -1, other_id = -1;
145 return (args_->GetAsInteger(&my_id) &&
146 other.args_->GetAsInteger(&other_id) &&
147 my_id == other_id);
148 }
149 return json_args_ == other.json_args_;
150 }
151
152 std::string Debug() {
153 return base::StringPrintf("Event(%p, %s, %s, %f)",
154 profile_,
155 event_name_.c_str(),
156 json_args_.c_str(),
157 caught_.ToJsTime());
158 }
159
160 private:
161 Profile* profile_;
162 std::string event_name_;
163 std::string json_args_;
164 scoped_ptr<base::Value> args_;
165 base::Time caught_;
166
167 DISALLOW_COPY_AND_ASSIGN(Event);
168 };
169
170 typedef ExtensionDownloadsEventRouter::DownloadsNotificationSource
171 DownloadsNotificationSource;
172
173 virtual void Observe(int type,
174 const content::NotificationSource& source,
175 const content::NotificationDetails& details) OVERRIDE {
176 switch (type) {
177 case chrome::NOTIFICATION_EXTENSION_DOWNLOADS_EVENT:
178 {
179 DownloadsNotificationSource* dns =
180 content::Source<DownloadsNotificationSource>(source).ptr();
181 Event* new_event = new Event(
182 dns->profile,
183 dns->event_name,
184 *content::Details<std::string>(details).ptr(), base::Time::Now());
185 events_.push_back(new_event);
186 if (waiting_ &&
187 waiting_for_.get() &&
188 new_event->Satisfies(*waiting_for_)) {
189 waiting_ = false;
190 base::MessageLoopForUI::current()->Quit();
191 }
192 break;
193 }
194 default:
195 NOTREACHED();
196 }
197 }
198
199 bool WaitFor(Profile* profile,
200 const std::string& event_name,
201 const std::string& json_args) {
202 waiting_for_.reset(new Event(profile, event_name, json_args, base::Time()));
203 for (std::deque<Event*>::const_iterator iter = events_.begin();
204 iter != events_.end(); ++iter) {
205 if ((*iter)->Satisfies(*waiting_for_.get())) {
206 return true;
207 }
208 }
209 waiting_ = true;
210 content::RunMessageLoop();
211 bool success = !waiting_;
212 if (waiting_) {
213 // Print the events that were caught since the last WaitFor() call to help
214 // find the erroneous event.
215 // TODO(benjhayden) Fuzzy-match and highlight the erroneous event.
216 for (std::deque<Event*>::const_iterator iter = events_.begin();
217 iter != events_.end(); ++iter) {
218 if ((*iter)->caught() > last_wait_) {
219 LOG(INFO) << "Caught " << (*iter)->Debug();
220 }
221 }
222 if (waiting_for_.get()) {
223 LOG(INFO) << "Timed out waiting for " << waiting_for_->Debug();
224 }
225 waiting_ = false;
226 }
227 waiting_for_.reset();
228 last_wait_ = base::Time::Now();
229 return success;
230 }
231
232 private:
233 bool waiting_;
234 base::Time last_wait_;
235 scoped_ptr<Event> waiting_for_;
236 content::NotificationRegistrar registrar_;
237 std::deque<Event*> events_;
238
239 DISALLOW_COPY_AND_ASSIGN(DownloadsEventsListener);
240 };
241
242 class DownloadExtensionTest : public ExtensionApiTest {
243 public:
244 DownloadExtensionTest()
245 : extension_(NULL),
246 incognito_browser_(NULL),
247 current_browser_(NULL) {
248 }
249
250 protected:
251 // Used with CreateHistoryDownloads
252 struct HistoryDownloadInfo {
253 // Filename to use. CreateHistoryDownloads will append this filename to the
254 // temporary downloads directory specified by downloads_directory().
255 const base::FilePath::CharType* filename;
256
257 // State for the download. Note that IN_PROGRESS downloads will be created
258 // as CANCELLED.
259 DownloadItem::DownloadState state;
260
261 // Danger type for the download. Only use DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS
262 // and DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT.
263 content::DownloadDangerType danger_type;
264 };
265
266 void LoadExtension(const char* name) {
267 // Store the created Extension object so that we can attach it to
268 // ExtensionFunctions. Also load the extension in incognito profiles for
269 // testing incognito.
270 extension_ = LoadExtensionIncognito(test_data_dir_.AppendASCII(name));
271 CHECK(extension_);
272 content::WebContents* tab = chrome::AddSelectedTabWithURL(
273 current_browser(),
274 extension_->GetResourceURL("empty.html"),
275 content::PAGE_TRANSITION_LINK);
276 extensions::ExtensionSystem::Get(current_browser()->profile())->
277 event_router()->AddEventListener(
278 extensions::event_names::kOnDownloadCreated,
279 tab->GetRenderProcessHost(),
280 GetExtensionId());
281 extensions::ExtensionSystem::Get(current_browser()->profile())->
282 event_router()->AddEventListener(
283 extensions::event_names::kOnDownloadChanged,
284 tab->GetRenderProcessHost(),
285 GetExtensionId());
286 extensions::ExtensionSystem::Get(current_browser()->profile())->
287 event_router()->AddEventListener(
288 extensions::event_names::kOnDownloadErased,
289 tab->GetRenderProcessHost(),
290 GetExtensionId());
291 }
292
293 content::RenderProcessHost* AddFilenameDeterminer() {
294 content::WebContents* tab = chrome::AddSelectedTabWithURL(
295 current_browser(),
296 extension_->GetResourceURL("empty.html"),
297 content::PAGE_TRANSITION_LINK);
298 extensions::ExtensionSystem::Get(current_browser()->profile())->
299 event_router()->AddEventListener(
300 extensions::event_names::kOnDownloadDeterminingFilename,
301 tab->GetRenderProcessHost(),
302 GetExtensionId());
303 return tab->GetRenderProcessHost();
304 }
305
306 void RemoveFilenameDeterminer(content::RenderProcessHost* host) {
307 extensions::ExtensionSystem::Get(current_browser()->profile())->
308 event_router()->RemoveEventListener(
309 extensions::event_names::kOnDownloadDeterminingFilename,
310 host,
311 GetExtensionId());
312 }
313
314 Browser* current_browser() { return current_browser_; }
315
316 // InProcessBrowserTest
317 virtual void SetUpOnMainThread() OVERRIDE {
318 ExtensionApiTest::SetUpOnMainThread();
319 BrowserThread::PostTask(
320 BrowserThread::IO, FROM_HERE,
321 base::Bind(&chrome_browser_net::SetUrlRequestMocksEnabled, true));
322 InProcessBrowserTest::SetUpOnMainThread();
323 GoOnTheRecord();
324 CreateAndSetDownloadsDirectory();
325 current_browser()->profile()->GetPrefs()->SetBoolean(
326 prefs::kPromptForDownload, false);
327 GetOnRecordManager()->RemoveAllDownloads();
328 events_listener_.reset(new DownloadsEventsListener());
329 // Disable file chooser for current profile.
330 DownloadTestFileActivityObserver observer(current_browser()->profile());
331 observer.EnableFileChooser(false);
332 }
333
334 void GoOnTheRecord() { current_browser_ = browser(); }
335
336 void GoOffTheRecord() {
337 if (!incognito_browser_) {
338 incognito_browser_ = CreateIncognitoBrowser();
339 GetOffRecordManager()->RemoveAllDownloads();
340 // Disable file chooser for incognito profile.
341 DownloadTestFileActivityObserver observer(incognito_browser_->profile());
342 observer.EnableFileChooser(false);
343 }
344 current_browser_ = incognito_browser_;
345 }
346
347 bool WaitFor(const std::string& event_name, const std::string& json_args) {
348 return events_listener_->WaitFor(
349 current_browser()->profile(), event_name, json_args);
350 }
351
352 bool WaitForInterruption(DownloadItem* item, int expected_error,
353 const std::string& on_created_event) {
354 if (!WaitFor(events::kOnDownloadCreated, on_created_event))
355 return false;
356 // Now, onCreated is always fired before interruption.
357 return WaitFor(events::kOnDownloadChanged,
358 base::StringPrintf("[{\"id\": %d,"
359 " \"error\": {\"current\": %d},"
360 " \"state\": {"
361 " \"previous\": \"in_progress\","
362 " \"current\": \"interrupted\"}}]",
363 item->GetId(),
364 expected_error));
365 }
366
367 void ClearEvents() {
368 events_listener_->ClearEvents();
369 }
370
371 std::string GetExtensionURL() {
372 return extension_->url().spec();
373 }
374 std::string GetExtensionId() {
375 return extension_->id();
376 }
377
378 std::string GetFilename(const char* path) {
379 std::string result =
380 downloads_directory_.path().AppendASCII(path).AsUTF8Unsafe();
381 #if defined(OS_WIN)
382 for (std::string::size_type next = result.find("\\");
383 next != std::string::npos;
384 next = result.find("\\", next)) {
385 result.replace(next, 1, "\\\\");
386 next += 2;
387 }
388 #endif
389 return result;
390 }
391
392 DownloadManager* GetOnRecordManager() {
393 return BrowserContext::GetDownloadManager(browser()->profile());
394 }
395 DownloadManager* GetOffRecordManager() {
396 return BrowserContext::GetDownloadManager(
397 browser()->profile()->GetOffTheRecordProfile());
398 }
399 DownloadManager* GetCurrentManager() {
400 return (current_browser_ == incognito_browser_) ?
401 GetOffRecordManager() : GetOnRecordManager();
402 }
403
404 // Creates a set of history downloads based on the provided |history_info|
405 // array. |count| is the number of elements in |history_info|. On success,
406 // |items| will contain |count| DownloadItems in the order that they were
407 // specified in |history_info|. Returns true on success and false otherwise.
408 bool CreateHistoryDownloads(const HistoryDownloadInfo* history_info,
409 size_t count,
410 DownloadManager::DownloadVector* items) {
411 DownloadIdComparator download_id_comparator;
412 base::Time current = base::Time::Now();
413 items->clear();
414 GetOnRecordManager()->GetAllDownloads(items);
415 CHECK_EQ(0, static_cast<int>(items->size()));
416 std::vector<GURL> url_chain;
417 url_chain.push_back(GURL());
418 for (size_t i = 0; i < count; ++i) {
419 DownloadItem* item = GetOnRecordManager()->CreateDownloadItem(
420 content::DownloadItem::kInvalidId + 1 + i,
421 downloads_directory().Append(history_info[i].filename),
422 downloads_directory().Append(history_info[i].filename),
423 url_chain, GURL(), // URL Chain, referrer
424 current, current, // start_time, end_time
425 1, 1, // received_bytes, total_bytes
426 history_info[i].state, // state
427 content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS,
428 content::DOWNLOAD_INTERRUPT_REASON_NONE,
429 false); // opened
430 items->push_back(item);
431 }
432
433 // Order by ID so that they are in the order that we created them.
434 std::sort(items->begin(), items->end(), download_id_comparator);
435 // Set the danger type if necessary.
436 for (size_t i = 0; i < count; ++i) {
437 if (history_info[i].danger_type !=
438 content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS) {
439 EXPECT_EQ(content::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT,
440 history_info[i].danger_type);
441 items->at(i)->OnContentCheckCompleted(history_info[i].danger_type);
442 }
443 }
444 return true;
445 }
446
447 void CreateSlowTestDownloads(
448 size_t count, DownloadManager::DownloadVector* items) {
449 for (size_t i = 0; i < count; ++i) {
450 scoped_ptr<content::DownloadTestObserver> observer(
451 CreateInProgressDownloadObserver(1));
452 GURL slow_download_url(URLRequestSlowDownloadJob::kUnknownSizeUrl);
453 ui_test_utils::NavigateToURLWithDisposition(
454 current_browser(), slow_download_url, CURRENT_TAB,
455 ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
456 observer->WaitForFinished();
457 EXPECT_EQ(
458 1u, observer->NumDownloadsSeenInState(DownloadItem::IN_PROGRESS));
459 }
460 GetCurrentManager()->GetAllDownloads(items);
461 ASSERT_EQ(count, items->size());
462 }
463
464 DownloadItem* CreateSlowTestDownload() {
465 scoped_ptr<content::DownloadTestObserver> observer(
466 CreateInProgressDownloadObserver(1));
467 GURL slow_download_url(URLRequestSlowDownloadJob::kUnknownSizeUrl);
468 DownloadManager* manager = GetCurrentManager();
469
470 EXPECT_EQ(0, manager->InProgressCount());
471 if (manager->InProgressCount() != 0)
472 return NULL;
473
474 ui_test_utils::NavigateToURLWithDisposition(
475 current_browser(), slow_download_url, CURRENT_TAB,
476 ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
477
478 observer->WaitForFinished();
479 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::IN_PROGRESS));
480
481 DownloadManager::DownloadVector items;
482 manager->GetAllDownloads(&items);
483
484 DownloadItem* new_item = NULL;
485 for (DownloadManager::DownloadVector::iterator iter = items.begin();
486 iter != items.end(); ++iter) {
487 if ((*iter)->GetState() == DownloadItem::IN_PROGRESS) {
488 // There should be only one IN_PROGRESS item.
489 EXPECT_EQ(NULL, new_item);
490 new_item = *iter;
491 }
492 }
493 return new_item;
494 }
495
496 void FinishPendingSlowDownloads() {
497 scoped_ptr<content::DownloadTestObserver> observer(
498 CreateDownloadObserver(1));
499 GURL finish_url(URLRequestSlowDownloadJob::kFinishDownloadUrl);
500 ui_test_utils::NavigateToURLWithDisposition(
501 current_browser(), finish_url, NEW_FOREGROUND_TAB,
502 ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
503 observer->WaitForFinished();
504 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::COMPLETE));
505 }
506
507 content::DownloadTestObserver* CreateDownloadObserver(size_t download_count) {
508 return new content::DownloadTestObserverTerminal(
509 GetCurrentManager(), download_count,
510 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL);
511 }
512
513 content::DownloadTestObserver* CreateInProgressDownloadObserver(
514 size_t download_count) {
515 return new content::DownloadTestObserverInProgress(
516 GetCurrentManager(), download_count);
517 }
518
519 bool RunFunction(UIThreadExtensionFunction* function,
520 const std::string& args) {
521 scoped_refptr<UIThreadExtensionFunction> delete_function(function);
522 SetUpExtensionFunction(function);
523 return extension_function_test_utils::RunFunction(
524 function, args, browser(), GetFlags());
525 }
526
527 extension_function_test_utils::RunFunctionFlags GetFlags() {
528 return current_browser()->profile()->IsOffTheRecord() ?
529 extension_function_test_utils::INCLUDE_INCOGNITO :
530 extension_function_test_utils::NONE;
531 }
532
533 // extension_function_test_utils::RunFunction*() only uses browser for its
534 // profile(), so pass it the on-record browser so that it always uses the
535 // on-record profile to match real-life behavior.
536
537 base::Value* RunFunctionAndReturnResult(
538 scoped_refptr<UIThreadExtensionFunction> function,
539 const std::string& args) {
540 SetUpExtensionFunction(function.get());
541 return extension_function_test_utils::RunFunctionAndReturnSingleResult(
542 function.get(), args, browser(), GetFlags());
543 }
544
545 std::string RunFunctionAndReturnError(
546 scoped_refptr<UIThreadExtensionFunction> function,
547 const std::string& args) {
548 SetUpExtensionFunction(function.get());
549 return extension_function_test_utils::RunFunctionAndReturnError(
550 function.get(), args, browser(), GetFlags());
551 }
552
553 bool RunFunctionAndReturnString(
554 scoped_refptr<UIThreadExtensionFunction> function,
555 const std::string& args,
556 std::string* result_string) {
557 SetUpExtensionFunction(function.get());
558 scoped_ptr<base::Value> result(RunFunctionAndReturnResult(function, args));
559 EXPECT_TRUE(result.get());
560 return result.get() && result->GetAsString(result_string);
561 }
562
563 std::string DownloadItemIdAsArgList(const DownloadItem* download_item) {
564 return base::StringPrintf("[%d]", download_item->GetId());
565 }
566
567 const base::FilePath& downloads_directory() {
568 return downloads_directory_.path();
569 }
570
571 DownloadsEventsListener* events_listener() { return events_listener_.get(); }
572
573 private:
574 void SetUpExtensionFunction(UIThreadExtensionFunction* function) {
575 if (extension_) {
576 // Recreate the tab each time for insulation.
577 content::WebContents* tab = chrome::AddSelectedTabWithURL(
578 current_browser(),
579 extension_->GetResourceURL("empty.html"),
580 content::PAGE_TRANSITION_LINK);
581 function->set_extension(extension_);
582 function->SetRenderViewHost(tab->GetRenderViewHost());
583 }
584 }
585
586 void CreateAndSetDownloadsDirectory() {
587 ASSERT_TRUE(downloads_directory_.CreateUniqueTempDir());
588 current_browser()->profile()->GetPrefs()->SetFilePath(
589 prefs::kDownloadDefaultDirectory,
590 downloads_directory_.path());
591 }
592
593 base::ScopedTempDir downloads_directory_;
594 const extensions::Extension* extension_;
595 Browser* incognito_browser_;
596 Browser* current_browser_;
597 scoped_ptr<DownloadsEventsListener> events_listener_;
598
599 DISALLOW_COPY_AND_ASSIGN(DownloadExtensionTest);
600 };
601
602 class MockIconExtractorImpl : public DownloadFileIconExtractor {
603 public:
604 MockIconExtractorImpl(const base::FilePath& path,
605 IconLoader::IconSize icon_size,
606 const std::string& response)
607 : expected_path_(path),
608 expected_icon_size_(icon_size),
609 response_(response) {
610 }
611 virtual ~MockIconExtractorImpl() {}
612
613 virtual bool ExtractIconURLForPath(const base::FilePath& path,
614 IconLoader::IconSize icon_size,
615 IconURLCallback callback) OVERRIDE {
616 EXPECT_STREQ(expected_path_.value().c_str(), path.value().c_str());
617 EXPECT_EQ(expected_icon_size_, icon_size);
618 if (expected_path_ == path &&
619 expected_icon_size_ == icon_size) {
620 callback_ = callback;
621 BrowserThread::PostTask(
622 BrowserThread::UI, FROM_HERE,
623 base::Bind(&MockIconExtractorImpl::RunCallback,
624 base::Unretained(this)));
625 return true;
626 } else {
627 return false;
628 }
629 }
630
631 private:
632 void RunCallback() {
633 callback_.Run(response_);
634 }
635
636 base::FilePath expected_path_;
637 IconLoader::IconSize expected_icon_size_;
638 std::string response_;
639 IconURLCallback callback_;
640 };
641
642 bool ItemNotInProgress(DownloadItem* item) {
643 return item->GetState() != DownloadItem::IN_PROGRESS;
644 }
645
646 // Cancels the underlying DownloadItem when the ScopedCancellingItem goes out of
647 // scope. Like a scoped_ptr, but for DownloadItems.
648 class ScopedCancellingItem {
649 public:
650 explicit ScopedCancellingItem(DownloadItem* item) : item_(item) {}
651 ~ScopedCancellingItem() {
652 item_->Cancel(true);
653 content::DownloadUpdatedObserver observer(
654 item_, base::Bind(&ItemNotInProgress));
655 observer.WaitForEvent();
656 }
657 DownloadItem* get() { return item_; }
658 private:
659 DownloadItem* item_;
660 DISALLOW_COPY_AND_ASSIGN(ScopedCancellingItem);
661 };
662
663 // Cancels all the underlying DownloadItems when the ScopedItemVectorCanceller
664 // goes out of scope. Generalization of ScopedCancellingItem to many
665 // DownloadItems.
666 class ScopedItemVectorCanceller {
667 public:
668 explicit ScopedItemVectorCanceller(DownloadManager::DownloadVector* items)
669 : items_(items) {
670 }
671 ~ScopedItemVectorCanceller() {
672 for (DownloadManager::DownloadVector::const_iterator item = items_->begin();
673 item != items_->end(); ++item) {
674 if ((*item)->GetState() == DownloadItem::IN_PROGRESS)
675 (*item)->Cancel(true);
676 content::DownloadUpdatedObserver observer(
677 (*item), base::Bind(&ItemNotInProgress));
678 observer.WaitForEvent();
679 }
680 }
681
682 private:
683 DownloadManager::DownloadVector* items_;
684 DISALLOW_COPY_AND_ASSIGN(ScopedItemVectorCanceller);
685 };
686
687 class TestProtocolHandler : public net::URLRequestJobFactory::ProtocolHandler {
688 public:
689 explicit TestProtocolHandler(
690 webkit_blob::BlobStorageController* blob_storage_controller,
691 fileapi::FileSystemContext* file_system_context)
692 : blob_storage_controller_(blob_storage_controller),
693 file_system_context_(file_system_context) {}
694
695 virtual ~TestProtocolHandler() {}
696
697 virtual net::URLRequestJob* MaybeCreateJob(
698 net::URLRequest* request,
699 net::NetworkDelegate* network_delegate) const OVERRIDE {
700 return new webkit_blob::BlobURLRequestJob(
701 request,
702 network_delegate,
703 blob_storage_controller_->GetBlobDataFromUrl(request->url()),
704 file_system_context_,
705 base::MessageLoopProxy::current().get());
706 }
707
708 private:
709 webkit_blob::BlobStorageController* const blob_storage_controller_;
710 fileapi::FileSystemContext* const file_system_context_;
711
712 DISALLOW_COPY_AND_ASSIGN(TestProtocolHandler);
713 };
714
715 class TestURLRequestContext : public net::URLRequestContext {
716 public:
717 explicit TestURLRequestContext(
718 fileapi::FileSystemContext* file_system_context)
719 : blob_storage_controller_(new webkit_blob::BlobStorageController) {
720 // Job factory owns the protocol handler.
721 job_factory_.SetProtocolHandler(
722 "blob", new TestProtocolHandler(blob_storage_controller_.get(),
723 file_system_context));
724 set_job_factory(&job_factory_);
725 }
726
727 virtual ~TestURLRequestContext() {}
728
729 webkit_blob::BlobStorageController* blob_storage_controller() const {
730 return blob_storage_controller_.get();
731 }
732
733 private:
734 net::URLRequestJobFactoryImpl job_factory_;
735 scoped_ptr<webkit_blob::BlobStorageController> blob_storage_controller_;
736
737 DISALLOW_COPY_AND_ASSIGN(TestURLRequestContext);
738 };
739
740 // Writes an HTML5 file so that it can be downloaded.
741 class HTML5FileWriter {
742 public:
743 HTML5FileWriter(
744 Profile* profile,
745 const std::string& filename,
746 const std::string& origin,
747 DownloadsEventsListener* events_listener,
748 const std::string& payload)
749 : profile_(profile),
750 filename_(filename),
751 origin_(origin),
752 events_listener_(events_listener),
753 blob_data_(new webkit_blob::BlobData()),
754 payload_(payload),
755 fs_(BrowserContext::GetDefaultStoragePartition(profile_)->
756 GetFileSystemContext()) {
757 CHECK(profile_);
758 CHECK(events_listener_);
759 CHECK(fs_);
760 }
761
762 ~HTML5FileWriter() {
763 CHECK(BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::Bind(
764 &HTML5FileWriter::TearDownURLRequestContext, base::Unretained(this))));
765 events_listener_->WaitFor(
766 profile_, kURLRequestContextToreDown, std::string());
767 }
768
769 bool WriteFile() {
770 DCHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
771 fs_->OpenFileSystem(
772 GURL(origin_),
773 fileapi::kFileSystemTypeTemporary,
774 fileapi::OPEN_FILE_SYSTEM_CREATE_IF_NONEXISTENT,
775 base::Bind(&HTML5FileWriter::OpenFileSystemCallback,
776 base::Unretained(this)));
777 return events_listener_->WaitFor(profile_, kHTML5FileWritten, filename_);
778 }
779
780 private:
781 static const char kHTML5FileWritten[];
782 static const char kURLRequestContextToreDown[];
783 static const bool kExclusive = true;
784
785 GURL blob_url() const { return GURL("blob:" + filename_); }
786
787 void OpenFileSystemCallback(
788 base::PlatformFileError result,
789 const std::string& fs_name,
790 const GURL& root) {
791 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
792 root_ = root.spec();
793 CHECK(BrowserThread::PostTask(BrowserThread::IO, FROM_HERE, base::Bind(
794 &HTML5FileWriter::CreateFile, base::Unretained(this))));
795 }
796
797 fileapi::FileSystemOperationRunner* operation_runner() {
798 return fs_->operation_runner();
799 }
800
801 void CreateFile() {
802 CHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
803 operation_runner()->CreateFile(fs_->CrackURL(GURL(root_ + filename_)),
804 kExclusive, base::Bind(
805 &HTML5FileWriter::CreateFileCallback, base::Unretained(this)));
806 }
807
808 void CreateFileCallback(base::PlatformFileError result) {
809 CHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
810 CHECK_EQ(base::PLATFORM_FILE_OK, result);
811 blob_data_->AppendData(payload_);
812 url_request_context_.reset(new TestURLRequestContext(fs_));
813 url_request_context_->blob_storage_controller()
814 ->AddFinishedBlob(blob_url(), blob_data_.get());
815 operation_runner()->Write(
816 url_request_context_.get(),
817 fs_->CrackURL(GURL(root_ + filename_)),
818 blob_url(),
819 0, // offset
820 base::Bind(&HTML5FileWriter::WriteCallback, base::Unretained(this)));
821 }
822
823 void WriteCallback(
824 base::PlatformFileError result,
825 int64 bytes,
826 bool complete) {
827 CHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
828 CHECK_EQ(base::PLATFORM_FILE_OK, result);
829 CHECK(BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, base::Bind(
830 &HTML5FileWriter::NotifyWritten, base::Unretained(this))));
831 }
832
833 void NotifyWritten() {
834 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
835 DownloadsEventsListener::DownloadsNotificationSource notification_source;
836 notification_source.event_name = kHTML5FileWritten;
837 notification_source.profile = profile_;
838 content::NotificationService::current()->Notify(
839 chrome::NOTIFICATION_EXTENSION_DOWNLOADS_EVENT,
840 content::Source<DownloadsEventsListener::DownloadsNotificationSource>(
841 &notification_source),
842 content::Details<std::string>(&filename_));
843 }
844
845 void TearDownURLRequestContext() {
846 CHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
847 url_request_context_->blob_storage_controller()->RemoveBlob(blob_url());
848 url_request_context_.reset();
849 CHECK(BrowserThread::PostTask(BrowserThread::UI, FROM_HERE, base::Bind(
850 &HTML5FileWriter::NotifyURLRequestContextToreDown,
851 base::Unretained(this))));
852 }
853
854 void NotifyURLRequestContextToreDown() {
855 CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI));
856 DownloadsEventsListener::DownloadsNotificationSource notification_source;
857 notification_source.event_name = kURLRequestContextToreDown;
858 notification_source.profile = profile_;
859 std::string empty_args;
860 content::NotificationService::current()->Notify(
861 chrome::NOTIFICATION_EXTENSION_DOWNLOADS_EVENT,
862 content::Source<DownloadsEventsListener::DownloadsNotificationSource>(
863 &notification_source),
864 content::Details<std::string>(&empty_args));
865 }
866
867 Profile* profile_;
868 std::string filename_;
869 std::string origin_;
870 std::string root_;
871 DownloadsEventsListener* events_listener_;
872 scoped_refptr<webkit_blob::BlobData> blob_data_;
873 std::string payload_;
874 scoped_ptr<TestURLRequestContext> url_request_context_;
875 fileapi::FileSystemContext* fs_;
876
877 DISALLOW_COPY_AND_ASSIGN(HTML5FileWriter);
878 };
879
880 const char HTML5FileWriter::kHTML5FileWritten[] = "html5_file_written";
881 const char HTML5FileWriter::kURLRequestContextToreDown[] =
882 "url_request_context_tore_down";
883
884 // TODO(benjhayden) Merge this with the other TestObservers.
885 class JustInProgressDownloadObserver
886 : public content::DownloadTestObserverInProgress {
887 public:
888 JustInProgressDownloadObserver(
889 DownloadManager* download_manager, size_t wait_count)
890 : content::DownloadTestObserverInProgress(download_manager, wait_count) {
891 }
892
893 virtual ~JustInProgressDownloadObserver() {}
894
895 private:
896 virtual bool IsDownloadInFinalState(DownloadItem* item) OVERRIDE {
897 return item->GetState() == DownloadItem::IN_PROGRESS;
898 }
899
900 DISALLOW_COPY_AND_ASSIGN(JustInProgressDownloadObserver);
901 };
902
903 bool ItemIsInterrupted(DownloadItem* item) {
904 return item->GetState() == DownloadItem::INTERRUPTED;
905 }
906
907 } // namespace
908
909 IN_PROC_BROWSER_TEST_F(DownloadExtensionTest,
910 DownloadExtensionTest_Open) {
911 LoadExtension("downloads_split");
912 EXPECT_STREQ(download_extension_errors::kInvalidOperationError,
913 RunFunctionAndReturnError(
914 new DownloadsOpenFunction(),
915 "[-42]").c_str());
916
917 DownloadItem* download_item = CreateSlowTestDownload();
918 ASSERT_TRUE(download_item);
919 EXPECT_FALSE(download_item->GetOpened());
920 EXPECT_FALSE(download_item->GetOpenWhenComplete());
921 ASSERT_TRUE(WaitFor(events::kOnDownloadCreated,
922 base::StringPrintf("[{\"danger\": \"safe\","
923 " \"incognito\": false,"
924 " \"mime\": \"application/octet-stream\","
925 " \"paused\": false,"
926 " \"url\": \"%s\"}]",
927 download_item->GetURL().spec().c_str())));
928 EXPECT_STREQ(download_extension_errors::kInvalidOperationError,
929 RunFunctionAndReturnError(
930 new DownloadsOpenFunction(),
931 DownloadItemIdAsArgList(download_item)).c_str());
932
933 FinishPendingSlowDownloads();
934 EXPECT_FALSE(download_item->GetOpened());
935 EXPECT_TRUE(RunFunction(new DownloadsOpenFunction(),
936 DownloadItemIdAsArgList(download_item)));
937 EXPECT_TRUE(download_item->GetOpened());
938 }
939
940 IN_PROC_BROWSER_TEST_F(DownloadExtensionTest,
941 DownloadExtensionTest_PauseResumeCancelErase) {
942 DownloadItem* download_item = CreateSlowTestDownload();
943 ASSERT_TRUE(download_item);
944
945 // Call pause(). It should succeed and the download should be paused on
946 // return.
947 EXPECT_TRUE(RunFunction(new DownloadsPauseFunction(),
948 DownloadItemIdAsArgList(download_item)));
949 EXPECT_TRUE(download_item->IsPaused());
950
951 // Calling pause() twice shouldn't be an error.
952 EXPECT_TRUE(RunFunction(new DownloadsPauseFunction(),
953 DownloadItemIdAsArgList(download_item)));
954 EXPECT_TRUE(download_item->IsPaused());
955
956 // Now try resuming this download. It should succeed.
957 EXPECT_TRUE(RunFunction(new DownloadsResumeFunction(),
958 DownloadItemIdAsArgList(download_item)));
959 EXPECT_FALSE(download_item->IsPaused());
960
961 // Resume again. Resuming a download that wasn't paused is not an error.
962 EXPECT_TRUE(RunFunction(new DownloadsResumeFunction(),
963 DownloadItemIdAsArgList(download_item)));
964 EXPECT_FALSE(download_item->IsPaused());
965
966 // Pause again.
967 EXPECT_TRUE(RunFunction(new DownloadsPauseFunction(),
968 DownloadItemIdAsArgList(download_item)));
969 EXPECT_TRUE(download_item->IsPaused());
970
971 // And now cancel.
972 EXPECT_TRUE(RunFunction(new DownloadsCancelFunction(),
973 DownloadItemIdAsArgList(download_item)));
974 EXPECT_EQ(DownloadItem::CANCELLED, download_item->GetState());
975
976 // Cancel again. Shouldn't have any effect.
977 EXPECT_TRUE(RunFunction(new DownloadsCancelFunction(),
978 DownloadItemIdAsArgList(download_item)));
979 EXPECT_EQ(DownloadItem::CANCELLED, download_item->GetState());
980
981 // Calling paused on a non-active download yields kInvalidOperationError.
982 std::string error = RunFunctionAndReturnError(
983 new DownloadsPauseFunction(), DownloadItemIdAsArgList(download_item));
984 EXPECT_STREQ(download_extension_errors::kInvalidOperationError,
985 error.c_str());
986
987 // Calling resume on a non-active download yields kInvalidOperationError
988 error = RunFunctionAndReturnError(
989 new DownloadsResumeFunction(), DownloadItemIdAsArgList(download_item));
990 EXPECT_STREQ(download_extension_errors::kInvalidOperationError,
991 error.c_str());
992
993 // Calling paused on a non-existent download yields kInvalidOperationError.
994 error = RunFunctionAndReturnError(
995 new DownloadsPauseFunction(), "[-42]");
996 EXPECT_STREQ(download_extension_errors::kInvalidOperationError,
997 error.c_str());
998
999 // Calling resume on a non-existent download yields kInvalidOperationError
1000 error = RunFunctionAndReturnError(
1001 new DownloadsResumeFunction(), "[-42]");
1002 EXPECT_STREQ(download_extension_errors::kInvalidOperationError,
1003 error.c_str());
1004
1005 int id = download_item->GetId();
1006 scoped_ptr<base::Value> result(RunFunctionAndReturnResult(
1007 new DownloadsEraseFunction(),
1008 base::StringPrintf("[{\"id\": %d}]", id)));
1009 DownloadManager::DownloadVector items;
1010 GetCurrentManager()->GetAllDownloads(&items);
1011 EXPECT_EQ(0UL, items.size());
1012 ASSERT_TRUE(result);
1013 download_item = NULL;
1014 base::ListValue* result_list = NULL;
1015 ASSERT_TRUE(result->GetAsList(&result_list));
1016 ASSERT_EQ(1UL, result_list->GetSize());
1017 int element = -1;
1018 ASSERT_TRUE(result_list->GetInteger(0, &element));
1019 EXPECT_EQ(id, element);
1020 }
1021
1022 scoped_refptr<UIThreadExtensionFunction> MockedGetFileIconFunction(
1023 const base::FilePath& expected_path,
1024 IconLoader::IconSize icon_size,
1025 const std::string& response) {
1026 scoped_refptr<DownloadsGetFileIconFunction> function(
1027 new DownloadsGetFileIconFunction());
1028 function->SetIconExtractorForTesting(new MockIconExtractorImpl(
1029 expected_path, icon_size, response));
1030 return function;
1031 }
1032
1033 // Test downloads.getFileIcon() on in-progress, finished, cancelled and deleted
1034 // download items.
1035 IN_PROC_BROWSER_TEST_F(DownloadExtensionTest,
1036 DownloadExtensionTest_FileIcon_Active) {
1037 DownloadItem* download_item = CreateSlowTestDownload();
1038 ASSERT_TRUE(download_item);
1039 ASSERT_FALSE(download_item->GetTargetFilePath().empty());
1040 std::string args32(base::StringPrintf("[%d, {\"size\": 32}]",
1041 download_item->GetId()));
1042 std::string result_string;
1043
1044 // Get the icon for the in-progress download. This call should succeed even
1045 // if the file type isn't registered.
1046 // Test whether the correct path is being pased into the icon extractor.
1047 EXPECT_TRUE(RunFunctionAndReturnString(MockedGetFileIconFunction(
1048 download_item->GetTargetFilePath(), IconLoader::NORMAL, "foo"),
1049 base::StringPrintf("[%d, {}]", download_item->GetId()), &result_string));
1050
1051 // Now try a 16x16 icon.
1052 EXPECT_TRUE(RunFunctionAndReturnString(MockedGetFileIconFunction(
1053 download_item->GetTargetFilePath(), IconLoader::SMALL, "foo"),
1054 base::StringPrintf("[%d, {\"size\": 16}]", download_item->GetId()),
1055 &result_string));
1056
1057 // Explicitly asking for 32x32 should give us a 32x32 icon.
1058 EXPECT_TRUE(RunFunctionAndReturnString(MockedGetFileIconFunction(
1059 download_item->GetTargetFilePath(), IconLoader::NORMAL, "foo"),
1060 args32, &result_string));
1061
1062 // Finish the download and try again.
1063 FinishPendingSlowDownloads();
1064 EXPECT_EQ(DownloadItem::COMPLETE, download_item->GetState());
1065 EXPECT_TRUE(RunFunctionAndReturnString(MockedGetFileIconFunction(
1066 download_item->GetTargetFilePath(), IconLoader::NORMAL, "foo"),
1067 args32, &result_string));
1068
1069 // Check the path passed to the icon extractor post-completion.
1070 EXPECT_TRUE(RunFunctionAndReturnString(MockedGetFileIconFunction(
1071 download_item->GetTargetFilePath(), IconLoader::NORMAL, "foo"),
1072 args32, &result_string));
1073
1074 // Now create another download.
1075 download_item = CreateSlowTestDownload();
1076 ASSERT_TRUE(download_item);
1077 ASSERT_FALSE(download_item->GetTargetFilePath().empty());
1078 args32 = base::StringPrintf("[%d, {\"size\": 32}]", download_item->GetId());
1079
1080 // Cancel the download. As long as the download has a target path, we should
1081 // be able to query the file icon.
1082 download_item->Cancel(true);
1083 ASSERT_FALSE(download_item->GetTargetFilePath().empty());
1084 // Let cleanup complete on the FILE thread.
1085 content::RunAllPendingInMessageLoop(BrowserThread::FILE);
1086 // Check the path passed to the icon extractor post-cancellation.
1087 EXPECT_TRUE(RunFunctionAndReturnString(MockedGetFileIconFunction(
1088 download_item->GetTargetFilePath(), IconLoader::NORMAL, "foo"),
1089 args32,
1090 &result_string));
1091
1092 // Simulate an error during icon load by invoking the mock with an empty
1093 // result string.
1094 std::string error = RunFunctionAndReturnError(
1095 MockedGetFileIconFunction(download_item->GetTargetFilePath(),
1096 IconLoader::NORMAL,
1097 std::string()),
1098 args32);
1099 EXPECT_STREQ(download_extension_errors::kIconNotFoundError, error.c_str());
1100
1101 // Once the download item is deleted, we should return kInvalidOperationError.
1102 int id = download_item->GetId();
1103 download_item->Remove();
1104 download_item = NULL;
1105 EXPECT_EQ(static_cast<DownloadItem*>(NULL),
1106 GetCurrentManager()->GetDownload(id));
1107 error = RunFunctionAndReturnError(new DownloadsGetFileIconFunction(), args32);
1108 EXPECT_STREQ(download_extension_errors::kInvalidOperationError,
1109 error.c_str());
1110 }
1111
1112 // Test that we can acquire file icons for history downloads regardless of
1113 // whether they exist or not. If the file doesn't exist we should receive a
1114 // generic icon from the OS/toolkit that may or may not be specific to the file
1115 // type.
1116 IN_PROC_BROWSER_TEST_F(DownloadExtensionTest,
1117 DownloadExtensionTest_FileIcon_History) {
1118 const HistoryDownloadInfo kHistoryInfo[] = {
1119 { FILE_PATH_LITERAL("real.txt"),
1120 DownloadItem::COMPLETE,
1121 content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS },
1122 { FILE_PATH_LITERAL("fake.txt"),
1123 DownloadItem::COMPLETE,
1124 content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS }
1125 };
1126 DownloadManager::DownloadVector all_downloads;
1127 ASSERT_TRUE(CreateHistoryDownloads(kHistoryInfo, arraysize(kHistoryInfo),
1128 &all_downloads));
1129
1130 base::FilePath real_path = all_downloads[0]->GetTargetFilePath();
1131 base::FilePath fake_path = all_downloads[1]->GetTargetFilePath();
1132
1133 EXPECT_EQ(0, file_util::WriteFile(real_path, "", 0));
1134 ASSERT_TRUE(base::PathExists(real_path));
1135 ASSERT_FALSE(base::PathExists(fake_path));
1136
1137 for (DownloadManager::DownloadVector::iterator iter = all_downloads.begin();
1138 iter != all_downloads.end();
1139 ++iter) {
1140 std::string result_string;
1141 // Use a MockIconExtractorImpl to test if the correct path is being passed
1142 // into the DownloadFileIconExtractor.
1143 EXPECT_TRUE(RunFunctionAndReturnString(MockedGetFileIconFunction(
1144 (*iter)->GetTargetFilePath(), IconLoader::NORMAL, "hello"),
1145 base::StringPrintf("[%d, {\"size\": 32}]", (*iter)->GetId()),
1146 &result_string));
1147 EXPECT_STREQ("hello", result_string.c_str());
1148 }
1149
1150 // The temporary files should be cleaned up when the base::ScopedTempDir is re moved.
1151 }
1152
1153 // Test passing the empty query to search().
1154 IN_PROC_BROWSER_TEST_F(DownloadExtensionTest,
1155 DownloadExtensionTest_SearchEmptyQuery) {
1156 ScopedCancellingItem item(CreateSlowTestDownload());
1157 ASSERT_TRUE(item.get());
1158
1159 scoped_ptr<base::Value> result(RunFunctionAndReturnResult(
1160 new DownloadsSearchFunction(), "[{}]"));
1161 ASSERT_TRUE(result.get());
1162 base::ListValue* result_list = NULL;
1163 ASSERT_TRUE(result->GetAsList(&result_list));
1164 ASSERT_EQ(1UL, result_list->GetSize());
1165 }
1166
1167 // Test the |filenameRegex| parameter for search().
1168 IN_PROC_BROWSER_TEST_F(DownloadExtensionTest,
1169 DownloadExtensionTest_SearchFilenameRegex) {
1170 const HistoryDownloadInfo kHistoryInfo[] = {
1171 { FILE_PATH_LITERAL("foobar"),
1172 DownloadItem::COMPLETE,
1173 content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS },
1174 { FILE_PATH_LITERAL("baz"),
1175 DownloadItem::COMPLETE,
1176 content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS }
1177 };
1178 DownloadManager::DownloadVector all_downloads;
1179 ASSERT_TRUE(CreateHistoryDownloads(kHistoryInfo, arraysize(kHistoryInfo),
1180 &all_downloads));
1181
1182 scoped_ptr<base::Value> result(RunFunctionAndReturnResult(
1183 new DownloadsSearchFunction(), "[{\"filenameRegex\": \"foobar\"}]"));
1184 ASSERT_TRUE(result.get());
1185 base::ListValue* result_list = NULL;
1186 ASSERT_TRUE(result->GetAsList(&result_list));
1187 ASSERT_EQ(1UL, result_list->GetSize());
1188 base::DictionaryValue* item_value = NULL;
1189 ASSERT_TRUE(result_list->GetDictionary(0, &item_value));
1190 int item_id = -1;
1191 ASSERT_TRUE(item_value->GetInteger("id", &item_id));
1192 ASSERT_EQ(all_downloads[0]->GetId(), static_cast<uint32>(item_id));
1193 }
1194
1195 // Test the |id| parameter for search().
1196 IN_PROC_BROWSER_TEST_F(DownloadExtensionTest, DownloadExtensionTest_SearchId) {
1197 DownloadManager::DownloadVector items;
1198 CreateSlowTestDownloads(2, &items);
1199 ScopedItemVectorCanceller delete_items(&items);
1200
1201 scoped_ptr<base::Value> result(RunFunctionAndReturnResult(
1202 new DownloadsSearchFunction(), base::StringPrintf(
1203 "[{\"id\": %u}]", items[0]->GetId())));
1204 ASSERT_TRUE(result.get());
1205 base::ListValue* result_list = NULL;
1206 ASSERT_TRUE(result->GetAsList(&result_list));
1207 ASSERT_EQ(1UL, result_list->GetSize());
1208 base::DictionaryValue* item_value = NULL;
1209 ASSERT_TRUE(result_list->GetDictionary(0, &item_value));
1210 int item_id = -1;
1211 ASSERT_TRUE(item_value->GetInteger("id", &item_id));
1212 ASSERT_EQ(items[0]->GetId(), static_cast<uint32>(item_id));
1213 }
1214
1215 // Test specifying both the |id| and |filename| parameters for search().
1216 IN_PROC_BROWSER_TEST_F(DownloadExtensionTest,
1217 DownloadExtensionTest_SearchIdAndFilename) {
1218 DownloadManager::DownloadVector items;
1219 CreateSlowTestDownloads(2, &items);
1220 ScopedItemVectorCanceller delete_items(&items);
1221
1222 scoped_ptr<base::Value> result(RunFunctionAndReturnResult(
1223 new DownloadsSearchFunction(),
1224 "[{\"id\": 0, \"filename\": \"foobar\"}]"));
1225 ASSERT_TRUE(result.get());
1226 base::ListValue* result_list = NULL;
1227 ASSERT_TRUE(result->GetAsList(&result_list));
1228 ASSERT_EQ(0UL, result_list->GetSize());
1229 }
1230
1231 // Test a single |orderBy| parameter for search().
1232 IN_PROC_BROWSER_TEST_F(DownloadExtensionTest,
1233 DownloadExtensionTest_SearchOrderBy) {
1234 const HistoryDownloadInfo kHistoryInfo[] = {
1235 { FILE_PATH_LITERAL("zzz"),
1236 DownloadItem::COMPLETE,
1237 content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS },
1238 { FILE_PATH_LITERAL("baz"),
1239 DownloadItem::COMPLETE,
1240 content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS }
1241 };
1242 DownloadManager::DownloadVector items;
1243 ASSERT_TRUE(CreateHistoryDownloads(kHistoryInfo, arraysize(kHistoryInfo),
1244 &items));
1245
1246 scoped_ptr<base::Value> result(RunFunctionAndReturnResult(
1247 new DownloadsSearchFunction(), "[{\"orderBy\": \"filename\"}]"));
1248 ASSERT_TRUE(result.get());
1249 base::ListValue* result_list = NULL;
1250 ASSERT_TRUE(result->GetAsList(&result_list));
1251 ASSERT_EQ(2UL, result_list->GetSize());
1252 base::DictionaryValue* item0_value = NULL;
1253 base::DictionaryValue* item1_value = NULL;
1254 ASSERT_TRUE(result_list->GetDictionary(0, &item0_value));
1255 ASSERT_TRUE(result_list->GetDictionary(1, &item1_value));
1256 std::string item0_name, item1_name;
1257 ASSERT_TRUE(item0_value->GetString("filename", &item0_name));
1258 ASSERT_TRUE(item1_value->GetString("filename", &item1_name));
1259 ASSERT_GT(items[0]->GetTargetFilePath().value(),
1260 items[1]->GetTargetFilePath().value());
1261 ASSERT_LT(item0_name, item1_name);
1262 }
1263
1264 // Test specifying an empty |orderBy| parameter for search().
1265 IN_PROC_BROWSER_TEST_F(DownloadExtensionTest,
1266 DownloadExtensionTest_SearchOrderByEmpty) {
1267 const HistoryDownloadInfo kHistoryInfo[] = {
1268 { FILE_PATH_LITERAL("zzz"),
1269 DownloadItem::COMPLETE,
1270 content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS },
1271 { FILE_PATH_LITERAL("baz"),
1272 DownloadItem::COMPLETE,
1273 content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS }
1274 };
1275 DownloadManager::DownloadVector items;
1276 ASSERT_TRUE(CreateHistoryDownloads(kHistoryInfo, arraysize(kHistoryInfo),
1277 &items));
1278
1279 scoped_ptr<base::Value> result(RunFunctionAndReturnResult(
1280 new DownloadsSearchFunction(), "[{\"orderBy\": \"\"}]"));
1281 ASSERT_TRUE(result.get());
1282 base::ListValue* result_list = NULL;
1283 ASSERT_TRUE(result->GetAsList(&result_list));
1284 ASSERT_EQ(2UL, result_list->GetSize());
1285 base::DictionaryValue* item0_value = NULL;
1286 base::DictionaryValue* item1_value = NULL;
1287 ASSERT_TRUE(result_list->GetDictionary(0, &item0_value));
1288 ASSERT_TRUE(result_list->GetDictionary(1, &item1_value));
1289 std::string item0_name, item1_name;
1290 ASSERT_TRUE(item0_value->GetString("filename", &item0_name));
1291 ASSERT_TRUE(item1_value->GetString("filename", &item1_name));
1292 ASSERT_GT(items[0]->GetTargetFilePath().value(),
1293 items[1]->GetTargetFilePath().value());
1294 ASSERT_GT(item0_name, item1_name);
1295 }
1296
1297 // Test the |danger| option for search().
1298 IN_PROC_BROWSER_TEST_F(DownloadExtensionTest,
1299 DownloadExtensionTest_SearchDanger) {
1300 const HistoryDownloadInfo kHistoryInfo[] = {
1301 { FILE_PATH_LITERAL("zzz"),
1302 DownloadItem::COMPLETE,
1303 content::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT },
1304 { FILE_PATH_LITERAL("baz"),
1305 DownloadItem::COMPLETE,
1306 content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS }
1307 };
1308 DownloadManager::DownloadVector items;
1309 ASSERT_TRUE(CreateHistoryDownloads(kHistoryInfo, arraysize(kHistoryInfo),
1310 &items));
1311
1312 scoped_ptr<base::Value> result(RunFunctionAndReturnResult(
1313 new DownloadsSearchFunction(), "[{\"danger\": \"content\"}]"));
1314 ASSERT_TRUE(result.get());
1315 base::ListValue* result_list = NULL;
1316 ASSERT_TRUE(result->GetAsList(&result_list));
1317 ASSERT_EQ(1UL, result_list->GetSize());
1318 }
1319
1320 // Test the |state| option for search().
1321 IN_PROC_BROWSER_TEST_F(DownloadExtensionTest,
1322 DownloadExtensionTest_SearchState) {
1323 DownloadManager::DownloadVector items;
1324 CreateSlowTestDownloads(2, &items);
1325 ScopedItemVectorCanceller delete_items(&items);
1326
1327 items[0]->Cancel(true);
1328
1329 scoped_ptr<base::Value> result(RunFunctionAndReturnResult(
1330 new DownloadsSearchFunction(), "[{\"state\": \"in_progress\"}]"));
1331 ASSERT_TRUE(result.get());
1332 base::ListValue* result_list = NULL;
1333 ASSERT_TRUE(result->GetAsList(&result_list));
1334 ASSERT_EQ(1UL, result_list->GetSize());
1335 }
1336
1337 // Test the |limit| option for search().
1338 IN_PROC_BROWSER_TEST_F(DownloadExtensionTest,
1339 DownloadExtensionTest_SearchLimit) {
1340 DownloadManager::DownloadVector items;
1341 CreateSlowTestDownloads(2, &items);
1342 ScopedItemVectorCanceller delete_items(&items);
1343
1344 scoped_ptr<base::Value> result(RunFunctionAndReturnResult(
1345 new DownloadsSearchFunction(), "[{\"limit\": 1}]"));
1346 ASSERT_TRUE(result.get());
1347 base::ListValue* result_list = NULL;
1348 ASSERT_TRUE(result->GetAsList(&result_list));
1349 ASSERT_EQ(1UL, result_list->GetSize());
1350 }
1351
1352 // Test invalid search parameters.
1353 IN_PROC_BROWSER_TEST_F(DownloadExtensionTest,
1354 DownloadExtensionTest_SearchInvalid) {
1355 std::string error = RunFunctionAndReturnError(
1356 new DownloadsSearchFunction(), "[{\"filenameRegex\": \"(\"}]");
1357 EXPECT_STREQ(download_extension_errors::kInvalidFilterError,
1358 error.c_str());
1359 error = RunFunctionAndReturnError(
1360 new DownloadsSearchFunction(), "[{\"orderBy\": \"goat\"}]");
1361 EXPECT_STREQ(download_extension_errors::kInvalidOrderByError,
1362 error.c_str());
1363 error = RunFunctionAndReturnError(
1364 new DownloadsSearchFunction(), "[{\"limit\": -1}]");
1365 EXPECT_STREQ(download_extension_errors::kInvalidQueryLimit,
1366 error.c_str());
1367 }
1368
1369 // Test searching using multiple conditions through multiple downloads.
1370 IN_PROC_BROWSER_TEST_F(DownloadExtensionTest,
1371 DownloadExtensionTest_SearchPlural) {
1372 const HistoryDownloadInfo kHistoryInfo[] = {
1373 { FILE_PATH_LITERAL("aaa"),
1374 DownloadItem::CANCELLED,
1375 content::DOWNLOAD_DANGER_TYPE_NOT_DANGEROUS },
1376 { FILE_PATH_LITERAL("zzz"),
1377 DownloadItem::COMPLETE,
1378 content::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT },
1379 { FILE_PATH_LITERAL("baz"),
1380 DownloadItem::COMPLETE,
1381 content::DOWNLOAD_DANGER_TYPE_DANGEROUS_CONTENT },
1382 };
1383 DownloadManager::DownloadVector items;
1384 ASSERT_TRUE(CreateHistoryDownloads(kHistoryInfo, arraysize(kHistoryInfo),
1385 &items));
1386
1387 scoped_ptr<base::Value> result(RunFunctionAndReturnResult(
1388 new DownloadsSearchFunction(), "[{"
1389 "\"state\": \"complete\", "
1390 "\"danger\": \"content\", "
1391 "\"orderBy\": \"filename\", "
1392 "\"limit\": 1}]"));
1393 ASSERT_TRUE(result.get());
1394 base::ListValue* result_list = NULL;
1395 ASSERT_TRUE(result->GetAsList(&result_list));
1396 ASSERT_EQ(1UL, result_list->GetSize());
1397 base::DictionaryValue* item_value = NULL;
1398 ASSERT_TRUE(result_list->GetDictionary(0, &item_value));
1399 base::FilePath::StringType item_name;
1400 ASSERT_TRUE(item_value->GetString("filename", &item_name));
1401 ASSERT_EQ(items[2]->GetTargetFilePath().value(), item_name);
1402 }
1403
1404 // Test that incognito downloads are only visible in incognito contexts, and
1405 // test that on-record downloads are visible in both incognito and on-record
1406 // contexts, for DownloadsSearchFunction, DownloadsPauseFunction,
1407 // DownloadsResumeFunction, and DownloadsCancelFunction.
1408 IN_PROC_BROWSER_TEST_F(DownloadExtensionTest,
1409 DownloadExtensionTest_SearchPauseResumeCancelGetFileIconIncognito) {
1410 scoped_ptr<base::Value> result_value;
1411 base::ListValue* result_list = NULL;
1412 base::DictionaryValue* result_dict = NULL;
1413 base::FilePath::StringType filename;
1414 bool is_incognito = false;
1415 std::string error;
1416 std::string on_item_arg;
1417 std::string off_item_arg;
1418 std::string result_string;
1419
1420 // Set up one on-record item and one off-record item.
1421 // Set up the off-record item first because otherwise there are mysteriously 3
1422 // items total instead of 2.
1423 // TODO(benjhayden): Figure out where the third item comes from.
1424 GoOffTheRecord();
1425 DownloadItem* off_item = CreateSlowTestDownload();
1426 ASSERT_TRUE(off_item);
1427 off_item_arg = DownloadItemIdAsArgList(off_item);
1428
1429 GoOnTheRecord();
1430 DownloadItem* on_item = CreateSlowTestDownload();
1431 ASSERT_TRUE(on_item);
1432 on_item_arg = DownloadItemIdAsArgList(on_item);
1433 ASSERT_TRUE(on_item->GetTargetFilePath() != off_item->GetTargetFilePath());
1434
1435 // Extensions running in the incognito window should have access to both
1436 // items because the Test extension is in spanning mode.
1437 GoOffTheRecord();
1438 result_value.reset(RunFunctionAndReturnResult(
1439 new DownloadsSearchFunction(), "[{}]"));
1440 ASSERT_TRUE(result_value.get());
1441 ASSERT_TRUE(result_value->GetAsList(&result_list));
1442 ASSERT_EQ(2UL, result_list->GetSize());
1443 ASSERT_TRUE(result_list->GetDictionary(0, &result_dict));
1444 ASSERT_TRUE(result_dict->GetString("filename", &filename));
1445 ASSERT_TRUE(result_dict->GetBoolean("incognito", &is_incognito));
1446 EXPECT_TRUE(on_item->GetTargetFilePath() == base::FilePath(filename));
1447 EXPECT_FALSE(is_incognito);
1448 ASSERT_TRUE(result_list->GetDictionary(1, &result_dict));
1449 ASSERT_TRUE(result_dict->GetString("filename", &filename));
1450 ASSERT_TRUE(result_dict->GetBoolean("incognito", &is_incognito));
1451 EXPECT_TRUE(off_item->GetTargetFilePath() == base::FilePath(filename));
1452 EXPECT_TRUE(is_incognito);
1453
1454 // Extensions running in the on-record window should have access only to the
1455 // on-record item.
1456 GoOnTheRecord();
1457 result_value.reset(RunFunctionAndReturnResult(
1458 new DownloadsSearchFunction(), "[{}]"));
1459 ASSERT_TRUE(result_value.get());
1460 ASSERT_TRUE(result_value->GetAsList(&result_list));
1461 ASSERT_EQ(1UL, result_list->GetSize());
1462 ASSERT_TRUE(result_list->GetDictionary(0, &result_dict));
1463 ASSERT_TRUE(result_dict->GetString("filename", &filename));
1464 EXPECT_TRUE(on_item->GetTargetFilePath() == base::FilePath(filename));
1465 ASSERT_TRUE(result_dict->GetBoolean("incognito", &is_incognito));
1466 EXPECT_FALSE(is_incognito);
1467
1468 // Pausing/Resuming the off-record item while on the record should return an
1469 // error. Cancelling "non-existent" downloads is not an error.
1470 error = RunFunctionAndReturnError(new DownloadsPauseFunction(), off_item_arg);
1471 EXPECT_STREQ(download_extension_errors::kInvalidOperationError,
1472 error.c_str());
1473 error = RunFunctionAndReturnError(new DownloadsResumeFunction(),
1474 off_item_arg);
1475 EXPECT_STREQ(download_extension_errors::kInvalidOperationError,
1476 error.c_str());
1477 error = RunFunctionAndReturnError(
1478 new DownloadsGetFileIconFunction(),
1479 base::StringPrintf("[%d, {}]", off_item->GetId()));
1480 EXPECT_STREQ(download_extension_errors::kInvalidOperationError,
1481 error.c_str());
1482
1483 GoOffTheRecord();
1484
1485 // Do the FileIcon test for both the on- and off-items while off the record.
1486 // NOTE(benjhayden): This does not include the FileIcon test from history,
1487 // just active downloads. This shouldn't be a problem.
1488 EXPECT_TRUE(RunFunctionAndReturnString(MockedGetFileIconFunction(
1489 on_item->GetTargetFilePath(), IconLoader::NORMAL, "foo"),
1490 base::StringPrintf("[%d, {}]", on_item->GetId()), &result_string));
1491 EXPECT_TRUE(RunFunctionAndReturnString(MockedGetFileIconFunction(
1492 off_item->GetTargetFilePath(), IconLoader::NORMAL, "foo"),
1493 base::StringPrintf("[%d, {}]", off_item->GetId()), &result_string));
1494
1495 // Do the pause/resume/cancel test for both the on- and off-items while off
1496 // the record.
1497 EXPECT_TRUE(RunFunction(new DownloadsPauseFunction(), on_item_arg));
1498 EXPECT_TRUE(on_item->IsPaused());
1499 EXPECT_TRUE(RunFunction(new DownloadsPauseFunction(), on_item_arg));
1500 EXPECT_TRUE(on_item->IsPaused());
1501 EXPECT_TRUE(RunFunction(new DownloadsResumeFunction(), on_item_arg));
1502 EXPECT_FALSE(on_item->IsPaused());
1503 EXPECT_TRUE(RunFunction(new DownloadsResumeFunction(), on_item_arg));
1504 EXPECT_FALSE(on_item->IsPaused());
1505 EXPECT_TRUE(RunFunction(new DownloadsPauseFunction(), on_item_arg));
1506 EXPECT_TRUE(on_item->IsPaused());
1507 EXPECT_TRUE(RunFunction(new DownloadsCancelFunction(), on_item_arg));
1508 EXPECT_EQ(DownloadItem::CANCELLED, on_item->GetState());
1509 EXPECT_TRUE(RunFunction(new DownloadsCancelFunction(), on_item_arg));
1510 EXPECT_EQ(DownloadItem::CANCELLED, on_item->GetState());
1511 error = RunFunctionAndReturnError(new DownloadsPauseFunction(), on_item_arg);
1512 EXPECT_STREQ(download_extension_errors::kInvalidOperationError,
1513 error.c_str());
1514 error = RunFunctionAndReturnError(new DownloadsResumeFunction(), on_item_arg);
1515 EXPECT_STREQ(download_extension_errors::kInvalidOperationError,
1516 error.c_str());
1517 EXPECT_TRUE(RunFunction(new DownloadsPauseFunction(), off_item_arg));
1518 EXPECT_TRUE(off_item->IsPaused());
1519 EXPECT_TRUE(RunFunction(new DownloadsPauseFunction(), off_item_arg));
1520 EXPECT_TRUE(off_item->IsPaused());
1521 EXPECT_TRUE(RunFunction(new DownloadsResumeFunction(), off_item_arg));
1522 EXPECT_FALSE(off_item->IsPaused());
1523 EXPECT_TRUE(RunFunction(new DownloadsResumeFunction(), off_item_arg));
1524 EXPECT_FALSE(off_item->IsPaused());
1525 EXPECT_TRUE(RunFunction(new DownloadsPauseFunction(), off_item_arg));
1526 EXPECT_TRUE(off_item->IsPaused());
1527 EXPECT_TRUE(RunFunction(new DownloadsCancelFunction(), off_item_arg));
1528 EXPECT_EQ(DownloadItem::CANCELLED, off_item->GetState());
1529 EXPECT_TRUE(RunFunction(new DownloadsCancelFunction(), off_item_arg));
1530 EXPECT_EQ(DownloadItem::CANCELLED, off_item->GetState());
1531 error = RunFunctionAndReturnError(new DownloadsPauseFunction(),
1532 off_item_arg);
1533 EXPECT_STREQ(download_extension_errors::kInvalidOperationError,
1534 error.c_str());
1535 error = RunFunctionAndReturnError(new DownloadsResumeFunction(),
1536 off_item_arg);
1537 EXPECT_STREQ(download_extension_errors::kInvalidOperationError,
1538 error.c_str());
1539 }
1540
1541 // Test that we can start a download and that the correct sequence of events is
1542 // fired for it.
1543 IN_PROC_BROWSER_TEST_F(DownloadExtensionTest,
1544 DownloadExtensionTest_Download_Basic) {
1545 LoadExtension("downloads_split");
1546 ASSERT_TRUE(StartEmbeddedTestServer());
1547 ASSERT_TRUE(test_server()->Start());
1548 std::string download_url = test_server()->GetURL("slow?0").spec();
1549 GoOnTheRecord();
1550
1551 // Start downloading a file.
1552 scoped_ptr<base::Value> result(RunFunctionAndReturnResult(
1553 new DownloadsDownloadFunction(), base::StringPrintf(
1554 "[{\"url\": \"%s\"}]", download_url.c_str())));
1555 ASSERT_TRUE(result.get());
1556 int result_id = -1;
1557 ASSERT_TRUE(result->GetAsInteger(&result_id));
1558 DownloadItem* item = GetCurrentManager()->GetDownload(result_id);
1559 ASSERT_TRUE(item);
1560 ScopedCancellingItem canceller(item);
1561 ASSERT_EQ(download_url, item->GetOriginalUrl().spec());
1562
1563 ASSERT_TRUE(WaitFor(events::kOnDownloadCreated,
1564 base::StringPrintf("[{\"danger\": \"safe\","
1565 " \"incognito\": false,"
1566 " \"mime\": \"text/plain\","
1567 " \"paused\": false,"
1568 " \"url\": \"%s\"}]",
1569 download_url.c_str())));
1570 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
1571 base::StringPrintf("[{\"id\": %d,"
1572 " \"filename\": {"
1573 " \"previous\": \"\","
1574 " \"current\": \"%s\"}}]",
1575 result_id,
1576 GetFilename("slow.txt").c_str())));
1577 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
1578 base::StringPrintf("[{\"id\": %d,"
1579 " \"state\": {"
1580 " \"previous\": \"in_progress\","
1581 " \"current\": \"complete\"}}]",
1582 result_id)));
1583 }
1584
1585 // Test that we can start a download from an incognito context, and that the
1586 // download knows that it's incognito.
1587 IN_PROC_BROWSER_TEST_F(DownloadExtensionTest,
1588 DownloadExtensionTest_Download_Incognito) {
1589 LoadExtension("downloads_split");
1590 ASSERT_TRUE(StartEmbeddedTestServer());
1591 ASSERT_TRUE(test_server()->Start());
1592 GoOffTheRecord();
1593 std::string download_url = test_server()->GetURL("slow?0").spec();
1594
1595 // Start downloading a file.
1596 scoped_ptr<base::Value> result(RunFunctionAndReturnResult(
1597 new DownloadsDownloadFunction(), base::StringPrintf(
1598 "[{\"url\": \"%s\"}]", download_url.c_str())));
1599 ASSERT_TRUE(result.get());
1600 int result_id = -1;
1601 ASSERT_TRUE(result->GetAsInteger(&result_id));
1602 DownloadItem* item = GetCurrentManager()->GetDownload(result_id);
1603 ASSERT_TRUE(item);
1604 ScopedCancellingItem canceller(item);
1605 ASSERT_EQ(download_url, item->GetOriginalUrl().spec());
1606
1607 ASSERT_TRUE(WaitFor(events::kOnDownloadCreated,
1608 base::StringPrintf("[{\"danger\": \"safe\","
1609 " \"incognito\": true,"
1610 " \"mime\": \"text/plain\","
1611 " \"paused\": false,"
1612 " \"url\": \"%s\"}]",
1613 download_url.c_str())));
1614 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
1615 base::StringPrintf("[{\"id\":%d,"
1616 " \"filename\": {"
1617 " \"previous\": \"\","
1618 " \"current\": \"%s\"}}]",
1619 result_id,
1620 GetFilename("slow.txt").c_str())));
1621 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
1622 base::StringPrintf("[{\"id\":%d,"
1623 " \"state\": {"
1624 " \"current\": \"complete\","
1625 " \"previous\": \"in_progress\"}}]",
1626 result_id)));
1627 }
1628
1629 #if defined(OS_WIN) && defined(USE_AURA)
1630 // This test is very flaky on Win Aura. http://crbug.com/248438
1631 #define MAYBE_DownloadExtensionTest_Download_UnsafeHeaders \
1632 DISABLED_DownloadExtensionTest_Download_UnsafeHeaders
1633 #else
1634 #define MAYBE_DownloadExtensionTest_Download_UnsafeHeaders \
1635 DownloadExtensionTest_Download_UnsafeHeaders
1636 #endif
1637
1638 // Test that we disallow certain headers case-insensitively.
1639 IN_PROC_BROWSER_TEST_F(DownloadExtensionTest,
1640 MAYBE_DownloadExtensionTest_Download_UnsafeHeaders) {
1641 LoadExtension("downloads_split");
1642 ASSERT_TRUE(StartEmbeddedTestServer());
1643 ASSERT_TRUE(test_server()->Start());
1644 GoOnTheRecord();
1645
1646 static const char* kUnsafeHeaders[] = {
1647 "Accept-chArsEt",
1648 "accept-eNcoding",
1649 "coNNection",
1650 "coNteNt-leNgth",
1651 "cooKIE",
1652 "cOOkie2",
1653 "coNteNt-traNsfer-eNcodiNg",
1654 "dAtE",
1655 "ExpEcT",
1656 "hOsT",
1657 "kEEp-aLivE",
1658 "rEfErEr",
1659 "tE",
1660 "trAilER",
1661 "trANsfer-eNcodiNg",
1662 "upGRAde",
1663 "usER-agENt",
1664 "viA",
1665 "pRoxY-",
1666 "sEc-",
1667 "pRoxY-probably-not-evil",
1668 "sEc-probably-not-evil",
1669 "oRiGiN",
1670 "Access-Control-Request-Headers",
1671 "Access-Control-Request-Method",
1672 };
1673
1674 for (size_t index = 0; index < arraysize(kUnsafeHeaders); ++index) {
1675 std::string download_url = test_server()->GetURL("slow?0").spec();
1676 EXPECT_STREQ(download_extension_errors::kGenericError,
1677 RunFunctionAndReturnError(new DownloadsDownloadFunction(),
1678 base::StringPrintf(
1679 "[{\"url\": \"%s\","
1680 " \"filename\": \"unsafe-header-%d.txt\","
1681 " \"headers\": [{"
1682 " \"name\": \"%s\","
1683 " \"value\": \"unsafe\"}]}]",
1684 download_url.c_str(),
1685 static_cast<int>(index),
1686 kUnsafeHeaders[index])).c_str());
1687 }
1688 }
1689
1690 // Test that subdirectories (slashes) are disallowed in filenames.
1691 // TODO(benjhayden) Update this when subdirectories are supported.
1692 IN_PROC_BROWSER_TEST_F(DownloadExtensionTest,
1693 DownloadExtensionTest_Download_Subdirectory) {
1694 LoadExtension("downloads_split");
1695 ASSERT_TRUE(StartEmbeddedTestServer());
1696 ASSERT_TRUE(test_server()->Start());
1697 std::string download_url = test_server()->GetURL("slow?0").spec();
1698 GoOnTheRecord();
1699
1700 EXPECT_STREQ(download_extension_errors::kInvalidFilenameError,
1701 RunFunctionAndReturnError(new DownloadsDownloadFunction(),
1702 base::StringPrintf(
1703 "[{\"url\": \"%s\","
1704 " \"filename\": \"sub/dir/ect/ory.txt\"}]",
1705 download_url.c_str())).c_str());
1706 }
1707
1708 // Test that invalid filenames are disallowed.
1709 IN_PROC_BROWSER_TEST_F(DownloadExtensionTest,
1710 DownloadExtensionTest_Download_InvalidFilename) {
1711 LoadExtension("downloads_split");
1712 ASSERT_TRUE(StartEmbeddedTestServer());
1713 ASSERT_TRUE(test_server()->Start());
1714 std::string download_url = test_server()->GetURL("slow?0").spec();
1715 GoOnTheRecord();
1716
1717 EXPECT_STREQ(download_extension_errors::kInvalidFilenameError,
1718 RunFunctionAndReturnError(new DownloadsDownloadFunction(),
1719 base::StringPrintf(
1720 "[{\"url\": \"%s\","
1721 " \"filename\": \"../../../../../etc/passwd\"}]",
1722 download_url.c_str())).c_str());
1723 }
1724
1725 // Test that downloading invalid URLs immediately returns kInvalidURLError.
1726 IN_PROC_BROWSER_TEST_F(DownloadExtensionTest,
1727 DownloadExtensionTest_Download_InvalidURLs) {
1728 LoadExtension("downloads_split");
1729 GoOnTheRecord();
1730
1731 static const char* kInvalidURLs[] = {
1732 "foo bar",
1733 "../hello",
1734 "/hello",
1735 "google.com/",
1736 "http://",
1737 "#frag",
1738 "foo/bar.html#frag",
1739 };
1740
1741 for (size_t index = 0; index < arraysize(kInvalidURLs); ++index) {
1742 EXPECT_STREQ(download_extension_errors::kInvalidURLError,
1743 RunFunctionAndReturnError(new DownloadsDownloadFunction(),
1744 base::StringPrintf(
1745 "[{\"url\": \"%s\"}]", kInvalidURLs[index])).c_str())
1746 << kInvalidURLs[index];
1747 }
1748
1749 EXPECT_STREQ("net::ERR_ACCESS_DENIED", RunFunctionAndReturnError(
1750 new DownloadsDownloadFunction(),
1751 "[{\"url\": \"javascript:document.write(\\\"hello\\\");\"}]").c_str());
1752 EXPECT_STREQ("net::ERR_ACCESS_DENIED", RunFunctionAndReturnError(
1753 new DownloadsDownloadFunction(),
1754 "[{\"url\": \"javascript:return false;\"}]").c_str());
1755 EXPECT_STREQ("net::ERR_NOT_IMPLEMENTED", RunFunctionAndReturnError(
1756 new DownloadsDownloadFunction(),
1757 "[{\"url\": \"ftp://example.com/example.txt\"}]").c_str());
1758 }
1759
1760 // TODO(benjhayden): Set up a test ftp server, add ftp://localhost* to
1761 // permissions, test downloading from ftp.
1762
1763 // Valid URLs plus fragments are still valid URLs.
1764 IN_PROC_BROWSER_TEST_F(DownloadExtensionTest,
1765 DownloadExtensionTest_Download_URLFragment) {
1766 LoadExtension("downloads_split");
1767 ASSERT_TRUE(StartEmbeddedTestServer());
1768 ASSERT_TRUE(test_server()->Start());
1769 std::string download_url = test_server()->GetURL("slow?0#fragment").spec();
1770 GoOnTheRecord();
1771
1772 scoped_ptr<base::Value> result(RunFunctionAndReturnResult(
1773 new DownloadsDownloadFunction(), base::StringPrintf(
1774 "[{\"url\": \"%s\"}]", download_url.c_str())));
1775 ASSERT_TRUE(result.get());
1776 int result_id = -1;
1777 ASSERT_TRUE(result->GetAsInteger(&result_id));
1778 DownloadItem* item = GetCurrentManager()->GetDownload(result_id);
1779 ASSERT_TRUE(item);
1780 ScopedCancellingItem canceller(item);
1781 ASSERT_EQ(download_url, item->GetOriginalUrl().spec());
1782
1783 ASSERT_TRUE(WaitFor(events::kOnDownloadCreated,
1784 base::StringPrintf("[{\"danger\": \"safe\","
1785 " \"incognito\": false,"
1786 " \"mime\": \"text/plain\","
1787 " \"paused\": false,"
1788 " \"url\": \"%s\"}]",
1789 download_url.c_str())));
1790 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
1791 base::StringPrintf("[{\"id\": %d,"
1792 " \"filename\": {"
1793 " \"previous\": \"\","
1794 " \"current\": \"%s\"}}]",
1795 result_id,
1796 GetFilename("slow.txt").c_str())));
1797 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
1798 base::StringPrintf("[{\"id\": %d,"
1799 " \"state\": {"
1800 " \"previous\": \"in_progress\","
1801 " \"current\": \"complete\"}}]",
1802 result_id)));
1803 }
1804
1805 // Valid data URLs are valid URLs.
1806 IN_PROC_BROWSER_TEST_F(DownloadExtensionTest,
1807 DownloadExtensionTest_Download_DataURL) {
1808 LoadExtension("downloads_split");
1809 std::string download_url = "data:text/plain,hello";
1810 GoOnTheRecord();
1811
1812 scoped_ptr<base::Value> result(RunFunctionAndReturnResult(
1813 new DownloadsDownloadFunction(), base::StringPrintf(
1814 "[{\"url\": \"%s\","
1815 " \"filename\": \"data.txt\"}]", download_url.c_str())));
1816 ASSERT_TRUE(result.get());
1817 int result_id = -1;
1818 ASSERT_TRUE(result->GetAsInteger(&result_id));
1819 DownloadItem* item = GetCurrentManager()->GetDownload(result_id);
1820 ASSERT_TRUE(item);
1821 ScopedCancellingItem canceller(item);
1822 ASSERT_EQ(download_url, item->GetOriginalUrl().spec());
1823
1824 ASSERT_TRUE(WaitFor(events::kOnDownloadCreated,
1825 base::StringPrintf("[{\"danger\": \"safe\","
1826 " \"incognito\": false,"
1827 " \"mime\": \"text/plain\","
1828 " \"paused\": false,"
1829 " \"url\": \"%s\"}]",
1830 download_url.c_str())));
1831 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
1832 base::StringPrintf("[{\"id\": %d,"
1833 " \"filename\": {"
1834 " \"previous\": \"\","
1835 " \"current\": \"%s\"}}]",
1836 result_id,
1837 GetFilename("data.txt").c_str())));
1838 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
1839 base::StringPrintf("[{\"id\": %d,"
1840 " \"state\": {"
1841 " \"previous\": \"in_progress\","
1842 " \"current\": \"complete\"}}]",
1843 result_id)));
1844 }
1845
1846 // Valid file URLs are valid URLs.
1847 #if defined(OS_WIN) && defined(USE_AURA)
1848 // Disabled due to crbug.com/175711
1849 #define MAYBE_DownloadExtensionTest_Download_File \
1850 DISABLED_DownloadExtensionTest_Download_File
1851 #else
1852 #define MAYBE_DownloadExtensionTest_Download_File \
1853 DownloadExtensionTest_Download_File
1854 #endif
1855 IN_PROC_BROWSER_TEST_F(DownloadExtensionTest,
1856 MAYBE_DownloadExtensionTest_Download_File) {
1857 GoOnTheRecord();
1858 LoadExtension("downloads_split");
1859 std::string download_url = "file:///";
1860 #if defined(OS_WIN)
1861 download_url += "C:/";
1862 #endif
1863
1864 scoped_ptr<base::Value> result(RunFunctionAndReturnResult(
1865 new DownloadsDownloadFunction(), base::StringPrintf(
1866 "[{\"url\": \"%s\","
1867 " \"filename\": \"file.txt\"}]", download_url.c_str())));
1868 ASSERT_TRUE(result.get());
1869 int result_id = -1;
1870 ASSERT_TRUE(result->GetAsInteger(&result_id));
1871 DownloadItem* item = GetCurrentManager()->GetDownload(result_id);
1872 ASSERT_TRUE(item);
1873 ScopedCancellingItem canceller(item);
1874 ASSERT_EQ(download_url, item->GetOriginalUrl().spec());
1875
1876 ASSERT_TRUE(WaitFor(events::kOnDownloadCreated,
1877 base::StringPrintf("[{\"danger\": \"safe\","
1878 " \"incognito\": false,"
1879 " \"mime\": \"text/html\","
1880 " \"paused\": false,"
1881 " \"url\": \"%s\"}]",
1882 download_url.c_str())));
1883 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
1884 base::StringPrintf("[{\"id\": %d,"
1885 " \"filename\": {"
1886 " \"previous\": \"\","
1887 " \"current\": \"%s\"}}]",
1888 result_id,
1889 GetFilename("file.txt").c_str())));
1890 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
1891 base::StringPrintf("[{\"id\": %d,"
1892 " \"state\": {"
1893 " \"previous\": \"in_progress\","
1894 " \"current\": \"complete\"}}]",
1895 result_id)));
1896 }
1897
1898 // Test that auth-basic-succeed would fail if the resource requires the
1899 // Authorization header and chrome fails to propagate it back to the server.
1900 // This tests both that testserver.py does not succeed when it should fail as
1901 // well as how the downloads extension API exposes the failure to extensions.
1902 IN_PROC_BROWSER_TEST_F(DownloadExtensionTest,
1903 DownloadExtensionTest_Download_AuthBasic_Fail) {
1904 LoadExtension("downloads_split");
1905 ASSERT_TRUE(StartEmbeddedTestServer());
1906 ASSERT_TRUE(test_server()->Start());
1907 std::string download_url = test_server()->GetURL("auth-basic").spec();
1908 GoOnTheRecord();
1909
1910 scoped_ptr<base::Value> result(RunFunctionAndReturnResult(
1911 new DownloadsDownloadFunction(), base::StringPrintf(
1912 "[{\"url\": \"%s\","
1913 " \"filename\": \"auth-basic-fail.txt\"}]",
1914 download_url.c_str())));
1915 ASSERT_TRUE(result.get());
1916 int result_id = -1;
1917 ASSERT_TRUE(result->GetAsInteger(&result_id));
1918 DownloadItem* item = GetCurrentManager()->GetDownload(result_id);
1919 ASSERT_TRUE(item);
1920 ScopedCancellingItem canceller(item);
1921 ASSERT_EQ(download_url, item->GetOriginalUrl().spec());
1922
1923 ASSERT_TRUE(WaitForInterruption(item, 30, base::StringPrintf(
1924 "[{\"danger\": \"safe\","
1925 " \"incognito\": false,"
1926 " \"mime\": \"text/html\","
1927 " \"paused\": false,"
1928 " \"url\": \"%s\"}]",
1929 download_url.c_str())));
1930 }
1931
1932 // Test that DownloadsDownloadFunction propagates |headers| to the URLRequest.
1933 IN_PROC_BROWSER_TEST_F(DownloadExtensionTest,
1934 DownloadExtensionTest_Download_Headers) {
1935 LoadExtension("downloads_split");
1936 ASSERT_TRUE(StartEmbeddedTestServer());
1937 ASSERT_TRUE(test_server()->Start());
1938 std::string download_url = test_server()->GetURL("files/downloads/"
1939 "a_zip_file.zip?expected_headers=Foo:bar&expected_headers=Qx:yo").spec();
1940 GoOnTheRecord();
1941
1942 scoped_ptr<base::Value> result(RunFunctionAndReturnResult(
1943 new DownloadsDownloadFunction(), base::StringPrintf(
1944 "[{\"url\": \"%s\","
1945 " \"filename\": \"headers-succeed.txt\","
1946 " \"headers\": ["
1947 " {\"name\": \"Foo\", \"value\": \"bar\"},"
1948 " {\"name\": \"Qx\", \"value\":\"yo\"}]}]",
1949 download_url.c_str())));
1950 ASSERT_TRUE(result.get());
1951 int result_id = -1;
1952 ASSERT_TRUE(result->GetAsInteger(&result_id));
1953 DownloadItem* item = GetCurrentManager()->GetDownload(result_id);
1954 ASSERT_TRUE(item);
1955 ScopedCancellingItem canceller(item);
1956 ASSERT_EQ(download_url, item->GetOriginalUrl().spec());
1957
1958 ASSERT_TRUE(WaitFor(events::kOnDownloadCreated,
1959 base::StringPrintf("[{\"danger\": \"safe\","
1960 " \"incognito\": false,"
1961 " \"mime\": \"application/octet-stream\","
1962 " \"paused\": false,"
1963 " \"url\": \"%s\"}]",
1964 download_url.c_str())));
1965 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
1966 base::StringPrintf("[{\"id\": %d,"
1967 " \"filename\": {"
1968 " \"previous\": \"\","
1969 " \"current\": \"%s\"}}]",
1970 result_id,
1971 GetFilename("headers-succeed.txt").c_str())));
1972 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
1973 base::StringPrintf("[{\"id\": %d,"
1974 " \"state\": {"
1975 " \"previous\": \"in_progress\","
1976 " \"current\": \"complete\"}}]",
1977 result_id)));
1978 }
1979
1980 // Test that headers-succeed would fail if the resource requires the headers and
1981 // chrome fails to propagate them back to the server. This tests both that
1982 // testserver.py does not succeed when it should fail as well as how the
1983 // downloads extension api exposes the failure to extensions.
1984 IN_PROC_BROWSER_TEST_F(DownloadExtensionTest,
1985 DownloadExtensionTest_Download_Headers_Fail) {
1986 LoadExtension("downloads_split");
1987 ASSERT_TRUE(StartEmbeddedTestServer());
1988 ASSERT_TRUE(test_server()->Start());
1989 std::string download_url = test_server()->GetURL("files/downloads/"
1990 "a_zip_file.zip?expected_headers=Foo:bar&expected_headers=Qx:yo").spec();
1991 GoOnTheRecord();
1992
1993 scoped_ptr<base::Value> result(RunFunctionAndReturnResult(
1994 new DownloadsDownloadFunction(), base::StringPrintf(
1995 "[{\"url\": \"%s\","
1996 " \"filename\": \"headers-fail.txt\"}]",
1997 download_url.c_str())));
1998 ASSERT_TRUE(result.get());
1999 int result_id = -1;
2000 ASSERT_TRUE(result->GetAsInteger(&result_id));
2001 DownloadItem* item = GetCurrentManager()->GetDownload(result_id);
2002 ASSERT_TRUE(item);
2003 ScopedCancellingItem canceller(item);
2004 ASSERT_EQ(download_url, item->GetOriginalUrl().spec());
2005
2006 ASSERT_TRUE(WaitForInterruption(item, 33, base::StringPrintf(
2007 "[{\"danger\": \"safe\","
2008 " \"incognito\": false,"
2009 " \"bytesReceived\": 0,"
2010 " \"mime\": \"\","
2011 " \"paused\": false,"
2012 " \"url\": \"%s\"}]",
2013 download_url.c_str())));
2014 }
2015
2016 // Test that DownloadsDownloadFunction propagates the Authorization header
2017 // correctly.
2018 IN_PROC_BROWSER_TEST_F(DownloadExtensionTest,
2019 DownloadExtensionTest_Download_AuthBasic) {
2020 LoadExtension("downloads_split");
2021 ASSERT_TRUE(StartEmbeddedTestServer());
2022 ASSERT_TRUE(test_server()->Start());
2023 std::string download_url = test_server()->GetURL("auth-basic").spec();
2024 // This is just base64 of 'username:secret'.
2025 static const char* kAuthorization = "dXNlcm5hbWU6c2VjcmV0";
2026 GoOnTheRecord();
2027
2028 scoped_ptr<base::Value> result(RunFunctionAndReturnResult(
2029 new DownloadsDownloadFunction(), base::StringPrintf(
2030 "[{\"url\": \"%s\","
2031 " \"filename\": \"auth-basic-succeed.txt\","
2032 " \"headers\": [{"
2033 " \"name\": \"Authorization\","
2034 " \"value\": \"Basic %s\"}]}]",
2035 download_url.c_str(), kAuthorization)));
2036 ASSERT_TRUE(result.get());
2037 int result_id = -1;
2038 ASSERT_TRUE(result->GetAsInteger(&result_id));
2039 DownloadItem* item = GetCurrentManager()->GetDownload(result_id);
2040 ASSERT_TRUE(item);
2041 ScopedCancellingItem canceller(item);
2042 ASSERT_EQ(download_url, item->GetOriginalUrl().spec());
2043
2044 ASSERT_TRUE(WaitFor(events::kOnDownloadCreated,
2045 base::StringPrintf("[{\"danger\": \"safe\","
2046 " \"incognito\": false,"
2047 " \"mime\": \"text/html\","
2048 " \"paused\": false,"
2049 " \"url\": \"%s\"}]", download_url.c_str())));
2050 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
2051 base::StringPrintf("[{\"id\": %d,"
2052 " \"state\": {"
2053 " \"previous\": \"in_progress\","
2054 " \"current\": \"complete\"}}]", result_id)));
2055 }
2056
2057 // Test that DownloadsDownloadFunction propagates the |method| and |body|
2058 // parameters to the URLRequest.
2059 IN_PROC_BROWSER_TEST_F(DownloadExtensionTest,
2060 DownloadExtensionTest_Download_Post) {
2061 LoadExtension("downloads_split");
2062 ASSERT_TRUE(StartEmbeddedTestServer());
2063 ASSERT_TRUE(test_server()->Start());
2064 std::string download_url = test_server()->GetURL("files/post/downloads/"
2065 "a_zip_file.zip?expected_body=BODY").spec();
2066 GoOnTheRecord();
2067
2068 scoped_ptr<base::Value> result(RunFunctionAndReturnResult(
2069 new DownloadsDownloadFunction(), base::StringPrintf(
2070 "[{\"url\": \"%s\","
2071 " \"filename\": \"post-succeed.txt\","
2072 " \"method\": \"POST\","
2073 " \"body\": \"BODY\"}]",
2074 download_url.c_str())));
2075 ASSERT_TRUE(result.get());
2076 int result_id = -1;
2077 ASSERT_TRUE(result->GetAsInteger(&result_id));
2078 DownloadItem* item = GetCurrentManager()->GetDownload(result_id);
2079 ASSERT_TRUE(item);
2080 ScopedCancellingItem canceller(item);
2081 ASSERT_EQ(download_url, item->GetOriginalUrl().spec());
2082
2083 ASSERT_TRUE(WaitFor(events::kOnDownloadCreated,
2084 base::StringPrintf("[{\"danger\": \"safe\","
2085 " \"incognito\": false,"
2086 " \"mime\": \"application/octet-stream\","
2087 " \"paused\": false,"
2088 " \"url\": \"%s\"}]", download_url.c_str())));
2089 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
2090 base::StringPrintf("[{\"id\": %d,"
2091 " \"filename\": {"
2092 " \"previous\": \"\","
2093 " \"current\": \"%s\"}}]",
2094 result_id,
2095 GetFilename("post-succeed.txt").c_str())));
2096 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
2097 base::StringPrintf("[{\"id\": %d,"
2098 " \"state\": {"
2099 " \"previous\": \"in_progress\","
2100 " \"current\": \"complete\"}}]",
2101 result_id)));
2102 }
2103
2104 // Test that downloadPostSuccess would fail if the resource requires the POST
2105 // method, and chrome fails to propagate the |method| parameter back to the
2106 // server. This tests both that testserver.py does not succeed when it should
2107 // fail, and this tests how the downloads extension api exposes the failure to
2108 // extensions.
2109 IN_PROC_BROWSER_TEST_F(DownloadExtensionTest,
2110 DownloadExtensionTest_Download_Post_Get) {
2111 LoadExtension("downloads_split");
2112 ASSERT_TRUE(StartEmbeddedTestServer());
2113 ASSERT_TRUE(test_server()->Start());
2114 std::string download_url = test_server()->GetURL("files/post/downloads/"
2115 "a_zip_file.zip?expected_body=BODY").spec();
2116 GoOnTheRecord();
2117
2118 scoped_ptr<base::Value> result(RunFunctionAndReturnResult(
2119 new DownloadsDownloadFunction(), base::StringPrintf(
2120 "[{\"url\": \"%s\","
2121 " \"body\": \"BODY\","
2122 " \"filename\": \"post-get.txt\"}]",
2123 download_url.c_str())));
2124 ASSERT_TRUE(result.get());
2125 int result_id = -1;
2126 ASSERT_TRUE(result->GetAsInteger(&result_id));
2127 DownloadItem* item = GetCurrentManager()->GetDownload(result_id);
2128 ASSERT_TRUE(item);
2129 ScopedCancellingItem canceller(item);
2130 ASSERT_EQ(download_url, item->GetOriginalUrl().spec());
2131
2132 ASSERT_TRUE(WaitForInterruption(item, 33, base::StringPrintf(
2133 "[{\"danger\": \"safe\","
2134 " \"incognito\": false,"
2135 " \"mime\": \"\","
2136 " \"paused\": false,"
2137 " \"id\": %d,"
2138 " \"url\": \"%s\"}]",
2139 result_id,
2140 download_url.c_str())));
2141 }
2142
2143 // Test that downloadPostSuccess would fail if the resource requires the POST
2144 // method, and chrome fails to propagate the |body| parameter back to the
2145 // server. This tests both that testserver.py does not succeed when it should
2146 // fail, and this tests how the downloads extension api exposes the failure to
2147 // extensions.
2148 IN_PROC_BROWSER_TEST_F(DownloadExtensionTest,
2149 DownloadExtensionTest_Download_Post_NoBody) {
2150 LoadExtension("downloads_split");
2151 ASSERT_TRUE(StartEmbeddedTestServer());
2152 ASSERT_TRUE(test_server()->Start());
2153 std::string download_url = test_server()->GetURL("files/post/downloads/"
2154 "a_zip_file.zip?expected_body=BODY").spec();
2155 GoOnTheRecord();
2156
2157 scoped_ptr<base::Value> result(RunFunctionAndReturnResult(
2158 new DownloadsDownloadFunction(), base::StringPrintf(
2159 "[{\"url\": \"%s\","
2160 " \"method\": \"POST\","
2161 " \"filename\": \"post-nobody.txt\"}]",
2162 download_url.c_str())));
2163 ASSERT_TRUE(result.get());
2164 int result_id = -1;
2165 ASSERT_TRUE(result->GetAsInteger(&result_id));
2166 DownloadItem* item = GetCurrentManager()->GetDownload(result_id);
2167 ASSERT_TRUE(item);
2168 ScopedCancellingItem canceller(item);
2169 ASSERT_EQ(download_url, item->GetOriginalUrl().spec());
2170
2171 ASSERT_TRUE(WaitForInterruption(item, 33, base::StringPrintf(
2172 "[{\"danger\": \"safe\","
2173 " \"incognito\": false,"
2174 " \"mime\": \"\","
2175 " \"paused\": false,"
2176 " \"id\": %d,"
2177 " \"url\": \"%s\"}]",
2178 result_id,
2179 download_url.c_str())));
2180 }
2181
2182 // Test that cancel()ing an in-progress download causes its state to transition
2183 // to interrupted, and test that that state transition is detectable by an
2184 // onChanged event listener. TODO(benjhayden): Test other sources of
2185 // interruptions such as server death.
2186 IN_PROC_BROWSER_TEST_F(DownloadExtensionTest,
2187 DownloadExtensionTest_Download_Cancel) {
2188 LoadExtension("downloads_split");
2189 ASSERT_TRUE(StartEmbeddedTestServer());
2190 ASSERT_TRUE(test_server()->Start());
2191 std::string download_url = test_server()->GetURL(
2192 "download-known-size").spec();
2193 GoOnTheRecord();
2194
2195 scoped_ptr<base::Value> result(RunFunctionAndReturnResult(
2196 new DownloadsDownloadFunction(), base::StringPrintf(
2197 "[{\"url\": \"%s\"}]", download_url.c_str())));
2198 ASSERT_TRUE(result.get());
2199 int result_id = -1;
2200 ASSERT_TRUE(result->GetAsInteger(&result_id));
2201 DownloadItem* item = GetCurrentManager()->GetDownload(result_id);
2202 ASSERT_TRUE(item);
2203 ScopedCancellingItem canceller(item);
2204 ASSERT_EQ(download_url, item->GetOriginalUrl().spec());
2205
2206 ASSERT_TRUE(WaitFor(events::kOnDownloadCreated,
2207 base::StringPrintf("[{\"danger\": \"safe\","
2208 " \"incognito\": false,"
2209 " \"mime\": \"application/octet-stream\","
2210 " \"paused\": false,"
2211 " \"id\": %d,"
2212 " \"url\": \"%s\"}]",
2213 result_id,
2214 download_url.c_str())));
2215 item->Cancel(true);
2216 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
2217 base::StringPrintf("[{\"id\": %d,"
2218 " \"error\": {\"current\": 40},"
2219 " \"state\": {"
2220 " \"previous\": \"in_progress\","
2221 " \"current\": \"interrupted\"}}]",
2222 result_id)));
2223 }
2224
2225 // Test downloading filesystem: URLs.
2226 // NOTE: chrome disallows creating HTML5 FileSystem Files in incognito.
2227 IN_PROC_BROWSER_TEST_F(DownloadExtensionTest,
2228 DownloadExtensionTest_Download_FileSystemURL) {
2229 static const char* kPayloadData = "on the record\ndata";
2230 GoOnTheRecord();
2231 LoadExtension("downloads_split");
2232 HTML5FileWriter html5_file_writer(
2233 browser()->profile(),
2234 "on_record.txt",
2235 GetExtensionURL(),
2236 events_listener(),
2237 kPayloadData);
2238 ASSERT_TRUE(html5_file_writer.WriteFile());
2239
2240 std::string download_url = "filesystem:" + GetExtensionURL() +
2241 "temporary/on_record.txt";
2242 scoped_ptr<base::Value> result(RunFunctionAndReturnResult(
2243 new DownloadsDownloadFunction(), base::StringPrintf(
2244 "[{\"url\": \"%s\"}]", download_url.c_str())));
2245 ASSERT_TRUE(result.get());
2246 int result_id = -1;
2247 ASSERT_TRUE(result->GetAsInteger(&result_id));
2248
2249 DownloadItem* item = GetCurrentManager()->GetDownload(result_id);
2250 ASSERT_TRUE(item);
2251 ScopedCancellingItem canceller(item);
2252 ASSERT_EQ(download_url, item->GetOriginalUrl().spec());
2253
2254 ASSERT_TRUE(WaitFor(events::kOnDownloadCreated,
2255 base::StringPrintf("[{\"danger\": \"safe\","
2256 " \"incognito\": false,"
2257 " \"mime\": \"text/plain\","
2258 " \"paused\": false,"
2259 " \"url\": \"%s\"}]",
2260 download_url.c_str())));
2261 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
2262 base::StringPrintf("[{\"id\": %d,"
2263 " \"filename\": {"
2264 " \"previous\": \"\","
2265 " \"current\": \"%s\"}}]",
2266 result_id,
2267 GetFilename("on_record.txt").c_str())));
2268 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
2269 base::StringPrintf("[{\"id\": %d,"
2270 " \"state\": {"
2271 " \"previous\": \"in_progress\","
2272 " \"current\": \"complete\"}}]",
2273 result_id)));
2274 std::string disk_data;
2275 EXPECT_TRUE(file_util::ReadFileToString(item->GetTargetFilePath(),
2276 &disk_data));
2277 EXPECT_STREQ(kPayloadData, disk_data.c_str());
2278 }
2279
2280 IN_PROC_BROWSER_TEST_F(DownloadExtensionTest,
2281 DownloadExtensionTest_OnDeterminingFilename_NoChange) {
2282 GoOnTheRecord();
2283 LoadExtension("downloads_split");
2284 AddFilenameDeterminer();
2285 ASSERT_TRUE(StartEmbeddedTestServer());
2286 ASSERT_TRUE(test_server()->Start());
2287 std::string download_url = test_server()->GetURL("slow?0").spec();
2288
2289 // Start downloading a file.
2290 scoped_ptr<base::Value> result(RunFunctionAndReturnResult(
2291 new DownloadsDownloadFunction(), base::StringPrintf(
2292 "[{\"url\": \"%s\"}]", download_url.c_str())));
2293 ASSERT_TRUE(result.get());
2294 int result_id = -1;
2295 ASSERT_TRUE(result->GetAsInteger(&result_id));
2296 DownloadItem* item = GetCurrentManager()->GetDownload(result_id);
2297 ASSERT_TRUE(item);
2298 ScopedCancellingItem canceller(item);
2299 ASSERT_EQ(download_url, item->GetOriginalUrl().spec());
2300
2301 // Wait for the onCreated and onDeterminingFilename events.
2302 ASSERT_TRUE(WaitFor(events::kOnDownloadCreated,
2303 base::StringPrintf("[{\"danger\": \"safe\","
2304 " \"incognito\": false,"
2305 " \"id\": %d,"
2306 " \"mime\": \"text/plain\","
2307 " \"paused\": false,"
2308 " \"url\": \"%s\"}]",
2309 result_id,
2310 download_url.c_str())));
2311 ASSERT_TRUE(WaitFor(
2312 events::kOnDownloadDeterminingFilename,
2313 base::StringPrintf("[{\"id\": %d,"
2314 " \"filename\":\"slow.txt\"}]",
2315 result_id)));
2316 ASSERT_TRUE(item->GetTargetFilePath().empty());
2317 ASSERT_EQ(DownloadItem::IN_PROGRESS, item->GetState());
2318
2319 // Respond to the onDeterminingFilename.
2320 std::string error;
2321 ASSERT_TRUE(ExtensionDownloadsEventRouter::DetermineFilename(
2322 browser()->profile(),
2323 false,
2324 GetExtensionId(),
2325 result_id,
2326 base::FilePath(),
2327 extensions::api::downloads::FILENAME_CONFLICT_ACTION_UNIQUIFY,
2328 &error));
2329 EXPECT_EQ("", error);
2330
2331 // The download should complete successfully.
2332 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
2333 base::StringPrintf("[{\"id\": %d,"
2334 " \"filename\": {"
2335 " \"previous\": \"\","
2336 " \"current\": \"%s\"}}]",
2337 result_id,
2338 GetFilename("slow.txt").c_str())));
2339 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
2340 base::StringPrintf("[{\"id\": %d,"
2341 " \"state\": {"
2342 " \"previous\": \"in_progress\","
2343 " \"current\": \"complete\"}}]",
2344 result_id)));
2345 }
2346
2347 IN_PROC_BROWSER_TEST_F(
2348 DownloadExtensionTest,
2349 DownloadExtensionTest_OnDeterminingFilename_DangerousOverride) {
2350 GoOnTheRecord();
2351 LoadExtension("downloads_split");
2352 AddFilenameDeterminer();
2353 ASSERT_TRUE(StartEmbeddedTestServer());
2354 ASSERT_TRUE(test_server()->Start());
2355 std::string download_url = test_server()->GetURL("slow?0").spec();
2356
2357 // Start downloading a file.
2358 scoped_ptr<base::Value> result(RunFunctionAndReturnResult(
2359 new DownloadsDownloadFunction(), base::StringPrintf(
2360 "[{\"url\": \"%s\"}]", download_url.c_str())));
2361 ASSERT_TRUE(result.get());
2362 int result_id = -1;
2363 ASSERT_TRUE(result->GetAsInteger(&result_id));
2364 DownloadItem* item = GetCurrentManager()->GetDownload(result_id);
2365 ASSERT_TRUE(item);
2366 ScopedCancellingItem canceller(item);
2367 ASSERT_EQ(download_url, item->GetOriginalUrl().spec());
2368
2369 ASSERT_TRUE(WaitFor(events::kOnDownloadCreated,
2370 base::StringPrintf("[{\"danger\": \"safe\","
2371 " \"incognito\": false,"
2372 " \"id\": %d,"
2373 " \"mime\": \"text/plain\","
2374 " \"paused\": false,"
2375 " \"url\": \"%s\"}]",
2376 result_id,
2377 download_url.c_str())));
2378 ASSERT_TRUE(WaitFor(
2379 events::kOnDownloadDeterminingFilename,
2380 base::StringPrintf("[{\"id\": %d,"
2381 " \"filename\":\"slow.txt\"}]",
2382 result_id)));
2383 ASSERT_TRUE(item->GetTargetFilePath().empty());
2384 ASSERT_EQ(DownloadItem::IN_PROGRESS, item->GetState());
2385
2386 // Respond to the onDeterminingFilename.
2387 std::string error;
2388 ASSERT_TRUE(ExtensionDownloadsEventRouter::DetermineFilename(
2389 browser()->profile(),
2390 false,
2391 GetExtensionId(),
2392 result_id,
2393 base::FilePath(FILE_PATH_LITERAL("overridden.swf")),
2394 extensions::api::downloads::FILENAME_CONFLICT_ACTION_UNIQUIFY,
2395 &error));
2396 EXPECT_EQ("", error);
2397
2398 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
2399 base::StringPrintf("[{\"id\": %d,"
2400 " \"danger\": {"
2401 " \"previous\":\"safe\","
2402 " \"current\":\"file\"},"
2403 " \"dangerAccepted\": {"
2404 " \"current\":false}}]",
2405 result_id)));
2406
2407 item->ValidateDangerousDownload();
2408 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
2409 base::StringPrintf("[{\"id\": %d,"
2410 " \"dangerAccepted\": {"
2411 " \"previous\":false,"
2412 " \"current\":true}}]",
2413 result_id)));
2414 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
2415 base::StringPrintf("[{\"id\": %d,"
2416 " \"state\": {"
2417 " \"previous\": \"in_progress\","
2418 " \"current\": \"complete\"}}]",
2419 result_id)));
2420 EXPECT_EQ(downloads_directory().AppendASCII("overridden.swf"),
2421 item->GetTargetFilePath());
2422 }
2423
2424 IN_PROC_BROWSER_TEST_F(
2425 DownloadExtensionTest,
2426 DownloadExtensionTest_OnDeterminingFilename_ReferencesParentInvalid) {
2427 GoOnTheRecord();
2428 LoadExtension("downloads_split");
2429 AddFilenameDeterminer();
2430 ASSERT_TRUE(StartEmbeddedTestServer());
2431 ASSERT_TRUE(test_server()->Start());
2432 std::string download_url = test_server()->GetURL("slow?0").spec();
2433
2434 // Start downloading a file.
2435 scoped_ptr<base::Value> result(RunFunctionAndReturnResult(
2436 new DownloadsDownloadFunction(), base::StringPrintf(
2437 "[{\"url\": \"%s\"}]", download_url.c_str())));
2438 ASSERT_TRUE(result.get());
2439 int result_id = -1;
2440 ASSERT_TRUE(result->GetAsInteger(&result_id));
2441 DownloadItem* item = GetCurrentManager()->GetDownload(result_id);
2442 ASSERT_TRUE(item);
2443 ScopedCancellingItem canceller(item);
2444 ASSERT_EQ(download_url, item->GetOriginalUrl().spec());
2445
2446 ASSERT_TRUE(WaitFor(events::kOnDownloadCreated,
2447 base::StringPrintf("[{\"danger\": \"safe\","
2448 " \"incognito\": false,"
2449 " \"id\": %d,"
2450 " \"mime\": \"text/plain\","
2451 " \"paused\": false,"
2452 " \"url\": \"%s\"}]",
2453 result_id,
2454 download_url.c_str())));
2455 ASSERT_TRUE(WaitFor(
2456 events::kOnDownloadDeterminingFilename,
2457 base::StringPrintf("[{\"id\": %d,"
2458 " \"filename\":\"slow.txt\"}]",
2459 result_id)));
2460 ASSERT_TRUE(item->GetTargetFilePath().empty());
2461 ASSERT_EQ(DownloadItem::IN_PROGRESS, item->GetState());
2462
2463 // Respond to the onDeterminingFilename.
2464 std::string error;
2465 ASSERT_FALSE(ExtensionDownloadsEventRouter::DetermineFilename(
2466 browser()->profile(),
2467 false,
2468 GetExtensionId(),
2469 result_id,
2470 base::FilePath(FILE_PATH_LITERAL("sneaky/../../sneaky.txt")),
2471 extensions::api::downloads::FILENAME_CONFLICT_ACTION_UNIQUIFY,
2472 &error));
2473 EXPECT_STREQ(download_extension_errors::kInvalidFilenameError, error.c_str());
2474 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
2475 base::StringPrintf("[{\"id\": %d,"
2476 " \"filename\": {"
2477 " \"previous\": \"\","
2478 " \"current\": \"%s\"}}]",
2479 result_id,
2480 GetFilename("slow.txt").c_str())));
2481 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
2482 base::StringPrintf("[{\"id\": %d,"
2483 " \"state\": {"
2484 " \"previous\": \"in_progress\","
2485 " \"current\": \"complete\"}}]",
2486 result_id)));
2487 }
2488
2489 IN_PROC_BROWSER_TEST_F(
2490 DownloadExtensionTest,
2491 DownloadExtensionTest_OnDeterminingFilename_IllegalFilename) {
2492 GoOnTheRecord();
2493 LoadExtension("downloads_split");
2494 AddFilenameDeterminer();
2495 ASSERT_TRUE(StartEmbeddedTestServer());
2496 ASSERT_TRUE(test_server()->Start());
2497 std::string download_url = test_server()->GetURL("slow?0").spec();
2498
2499 // Start downloading a file.
2500 scoped_ptr<base::Value> result(RunFunctionAndReturnResult(
2501 new DownloadsDownloadFunction(), base::StringPrintf(
2502 "[{\"url\": \"%s\"}]", download_url.c_str())));
2503 ASSERT_TRUE(result.get());
2504 int result_id = -1;
2505 ASSERT_TRUE(result->GetAsInteger(&result_id));
2506 DownloadItem* item = GetCurrentManager()->GetDownload(result_id);
2507 ASSERT_TRUE(item);
2508 ScopedCancellingItem canceller(item);
2509 ASSERT_EQ(download_url, item->GetOriginalUrl().spec());
2510
2511 ASSERT_TRUE(WaitFor(events::kOnDownloadCreated,
2512 base::StringPrintf("[{\"danger\": \"safe\","
2513 " \"incognito\": false,"
2514 " \"id\": %d,"
2515 " \"mime\": \"text/plain\","
2516 " \"paused\": false,"
2517 " \"url\": \"%s\"}]",
2518 result_id,
2519 download_url.c_str())));
2520 ASSERT_TRUE(WaitFor(
2521 events::kOnDownloadDeterminingFilename,
2522 base::StringPrintf("[{\"id\": %d,"
2523 " \"filename\":\"slow.txt\"}]",
2524 result_id)));
2525 ASSERT_TRUE(item->GetTargetFilePath().empty());
2526 ASSERT_EQ(DownloadItem::IN_PROGRESS, item->GetState());
2527
2528 // Respond to the onDeterminingFilename.
2529 std::string error;
2530 ASSERT_FALSE(ExtensionDownloadsEventRouter::DetermineFilename(
2531 browser()->profile(),
2532 false,
2533 GetExtensionId(),
2534 result_id,
2535 base::FilePath(FILE_PATH_LITERAL("<")),
2536 extensions::api::downloads::FILENAME_CONFLICT_ACTION_UNIQUIFY,
2537 &error));
2538 EXPECT_STREQ(download_extension_errors::kInvalidFilenameError, error.c_str());
2539 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged, base::StringPrintf(
2540 "[{\"id\": %d,"
2541 " \"filename\": {"
2542 " \"previous\": \"\","
2543 " \"current\": \"%s\"}}]",
2544 result_id,
2545 GetFilename("slow.txt").c_str())));
2546 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged, base::StringPrintf(
2547 "[{\"id\": %d,"
2548 " \"state\": {"
2549 " \"previous\": \"in_progress\","
2550 " \"current\": \"complete\"}}]",
2551 result_id)));
2552 }
2553
2554 IN_PROC_BROWSER_TEST_F(
2555 DownloadExtensionTest,
2556 DownloadExtensionTest_OnDeterminingFilename_IllegalFilenameExtension) {
2557 GoOnTheRecord();
2558 LoadExtension("downloads_split");
2559 AddFilenameDeterminer();
2560 ASSERT_TRUE(StartEmbeddedTestServer());
2561 ASSERT_TRUE(test_server()->Start());
2562 std::string download_url = test_server()->GetURL("slow?0").spec();
2563
2564 // Start downloading a file.
2565 scoped_ptr<base::Value> result(RunFunctionAndReturnResult(
2566 new DownloadsDownloadFunction(), base::StringPrintf(
2567 "[{\"url\": \"%s\"}]", download_url.c_str())));
2568 ASSERT_TRUE(result.get());
2569 int result_id = -1;
2570 ASSERT_TRUE(result->GetAsInteger(&result_id));
2571 DownloadItem* item = GetCurrentManager()->GetDownload(result_id);
2572 ASSERT_TRUE(item);
2573 ScopedCancellingItem canceller(item);
2574 ASSERT_EQ(download_url, item->GetOriginalUrl().spec());
2575
2576 ASSERT_TRUE(WaitFor(events::kOnDownloadCreated,
2577 base::StringPrintf("[{\"danger\": \"safe\","
2578 " \"incognito\": false,"
2579 " \"id\": %d,"
2580 " \"mime\": \"text/plain\","
2581 " \"paused\": false,"
2582 " \"url\": \"%s\"}]",
2583 result_id,
2584 download_url.c_str())));
2585 ASSERT_TRUE(WaitFor(
2586 events::kOnDownloadDeterminingFilename,
2587 base::StringPrintf("[{\"id\": %d,"
2588 " \"filename\":\"slow.txt\"}]",
2589 result_id)));
2590 ASSERT_TRUE(item->GetTargetFilePath().empty());
2591 ASSERT_EQ(DownloadItem::IN_PROGRESS, item->GetState());
2592
2593 // Respond to the onDeterminingFilename.
2594 std::string error;
2595 ASSERT_FALSE(ExtensionDownloadsEventRouter::DetermineFilename(
2596 browser()->profile(),
2597 false,
2598 GetExtensionId(),
2599 result_id,
2600 base::FilePath(FILE_PATH_LITERAL(
2601 "My Computer.{20D04FE0-3AEA-1069-A2D8-08002B30309D}/foo")),
2602 extensions::api::downloads::FILENAME_CONFLICT_ACTION_UNIQUIFY,
2603 &error));
2604 EXPECT_STREQ(download_extension_errors::kInvalidFilenameError, error.c_str());
2605 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged, base::StringPrintf(
2606 "[{\"id\": %d,"
2607 " \"filename\": {"
2608 " \"previous\": \"\","
2609 " \"current\": \"%s\"}}]",
2610 result_id,
2611 GetFilename("slow.txt").c_str())));
2612 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged, base::StringPrintf(
2613 "[{\"id\": %d,"
2614 " \"state\": {"
2615 " \"previous\": \"in_progress\","
2616 " \"current\": \"complete\"}}]",
2617 result_id)));
2618 }
2619
2620 IN_PROC_BROWSER_TEST_F(
2621 DownloadExtensionTest,
2622 DownloadExtensionTest_OnDeterminingFilename_ReservedFilename) {
2623 GoOnTheRecord();
2624 LoadExtension("downloads_split");
2625 AddFilenameDeterminer();
2626 ASSERT_TRUE(StartEmbeddedTestServer());
2627 ASSERT_TRUE(test_server()->Start());
2628 std::string download_url = test_server()->GetURL("slow?0").spec();
2629
2630 // Start downloading a file.
2631 scoped_ptr<base::Value> result(RunFunctionAndReturnResult(
2632 new DownloadsDownloadFunction(), base::StringPrintf(
2633 "[{\"url\": \"%s\"}]", download_url.c_str())));
2634 ASSERT_TRUE(result.get());
2635 int result_id = -1;
2636 ASSERT_TRUE(result->GetAsInteger(&result_id));
2637 DownloadItem* item = GetCurrentManager()->GetDownload(result_id);
2638 ASSERT_TRUE(item);
2639 ScopedCancellingItem canceller(item);
2640 ASSERT_EQ(download_url, item->GetOriginalUrl().spec());
2641
2642 ASSERT_TRUE(WaitFor(events::kOnDownloadCreated,
2643 base::StringPrintf("[{\"danger\": \"safe\","
2644 " \"incognito\": false,"
2645 " \"id\": %d,"
2646 " \"mime\": \"text/plain\","
2647 " \"paused\": false,"
2648 " \"url\": \"%s\"}]",
2649 result_id,
2650 download_url.c_str())));
2651 ASSERT_TRUE(WaitFor(
2652 events::kOnDownloadDeterminingFilename,
2653 base::StringPrintf("[{\"id\": %d,"
2654 " \"filename\":\"slow.txt\"}]",
2655 result_id)));
2656 ASSERT_TRUE(item->GetTargetFilePath().empty());
2657 ASSERT_EQ(DownloadItem::IN_PROGRESS, item->GetState());
2658
2659 // Respond to the onDeterminingFilename.
2660 std::string error;
2661 ASSERT_FALSE(ExtensionDownloadsEventRouter::DetermineFilename(
2662 browser()->profile(),
2663 false,
2664 GetExtensionId(),
2665 result_id,
2666 base::FilePath(FILE_PATH_LITERAL("con.foo")),
2667 extensions::api::downloads::FILENAME_CONFLICT_ACTION_UNIQUIFY,
2668 &error));
2669 EXPECT_STREQ(download_extension_errors::kInvalidFilenameError, error.c_str());
2670 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged, base::StringPrintf(
2671 "[{\"id\": %d,"
2672 " \"filename\": {"
2673 " \"previous\": \"\","
2674 " \"current\": \"%s\"}}]",
2675 result_id,
2676 GetFilename("slow.txt").c_str())));
2677 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged, base::StringPrintf(
2678 "[{\"id\": %d,"
2679 " \"state\": {"
2680 " \"previous\": \"in_progress\","
2681 " \"current\": \"complete\"}}]",
2682 result_id)));
2683 }
2684
2685 IN_PROC_BROWSER_TEST_F(
2686 DownloadExtensionTest,
2687 DownloadExtensionTest_OnDeterminingFilename_CurDirInvalid) {
2688 GoOnTheRecord();
2689 LoadExtension("downloads_split");
2690 AddFilenameDeterminer();
2691 ASSERT_TRUE(StartEmbeddedTestServer());
2692 ASSERT_TRUE(test_server()->Start());
2693 std::string download_url = test_server()->GetURL("slow?0").spec();
2694
2695 // Start downloading a file.
2696 scoped_ptr<base::Value> result(RunFunctionAndReturnResult(
2697 new DownloadsDownloadFunction(), base::StringPrintf(
2698 "[{\"url\": \"%s\"}]", download_url.c_str())));
2699 ASSERT_TRUE(result.get());
2700 int result_id = -1;
2701 ASSERT_TRUE(result->GetAsInteger(&result_id));
2702 DownloadItem* item = GetCurrentManager()->GetDownload(result_id);
2703 ASSERT_TRUE(item);
2704 ScopedCancellingItem canceller(item);
2705 ASSERT_EQ(download_url, item->GetOriginalUrl().spec());
2706
2707 ASSERT_TRUE(WaitFor(events::kOnDownloadCreated,
2708 base::StringPrintf("[{\"danger\": \"safe\","
2709 " \"incognito\": false,"
2710 " \"id\": %d,"
2711 " \"mime\": \"text/plain\","
2712 " \"paused\": false,"
2713 " \"url\": \"%s\"}]",
2714 result_id,
2715 download_url.c_str())));
2716 ASSERT_TRUE(WaitFor(
2717 events::kOnDownloadDeterminingFilename,
2718 base::StringPrintf("[{\"id\": %d,"
2719 " \"filename\":\"slow.txt\"}]",
2720 result_id)));
2721 ASSERT_TRUE(item->GetTargetFilePath().empty());
2722 ASSERT_EQ(DownloadItem::IN_PROGRESS, item->GetState());
2723
2724 // Respond to the onDeterminingFilename.
2725 std::string error;
2726 ASSERT_FALSE(ExtensionDownloadsEventRouter::DetermineFilename(
2727 browser()->profile(),
2728 false,
2729 GetExtensionId(),
2730 result_id,
2731 base::FilePath(FILE_PATH_LITERAL(".")),
2732 extensions::api::downloads::FILENAME_CONFLICT_ACTION_UNIQUIFY,
2733 &error));
2734 EXPECT_STREQ(download_extension_errors::kInvalidFilenameError, error.c_str());
2735 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
2736 base::StringPrintf("[{\"id\": %d,"
2737 " \"filename\": {"
2738 " \"previous\": \"\","
2739 " \"current\": \"%s\"}}]",
2740 result_id,
2741 GetFilename("slow.txt").c_str())));
2742 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
2743 base::StringPrintf("[{\"id\": %d,"
2744 " \"state\": {"
2745 " \"previous\": \"in_progress\","
2746 " \"current\": \"complete\"}}]",
2747 result_id)));
2748 }
2749
2750 IN_PROC_BROWSER_TEST_F(
2751 DownloadExtensionTest,
2752 DownloadExtensionTest_OnDeterminingFilename_ParentDirInvalid) {
2753 ASSERT_TRUE(StartEmbeddedTestServer());
2754 ASSERT_TRUE(test_server()->Start());
2755 GoOnTheRecord();
2756 LoadExtension("downloads_split");
2757 AddFilenameDeterminer();
2758 std::string download_url = test_server()->GetURL("slow?0").spec();
2759
2760 // Start downloading a file.
2761 scoped_ptr<base::Value> result(RunFunctionAndReturnResult(
2762 new DownloadsDownloadFunction(), base::StringPrintf(
2763 "[{\"url\": \"%s\"}]", download_url.c_str())));
2764 ASSERT_TRUE(result.get());
2765 int result_id = -1;
2766 ASSERT_TRUE(result->GetAsInteger(&result_id));
2767 DownloadItem* item = GetCurrentManager()->GetDownload(result_id);
2768 ASSERT_TRUE(item);
2769 ScopedCancellingItem canceller(item);
2770 ASSERT_EQ(download_url, item->GetOriginalUrl().spec());
2771
2772 ASSERT_TRUE(WaitFor(events::kOnDownloadCreated,
2773 base::StringPrintf("[{\"danger\": \"safe\","
2774 " \"incognito\": false,"
2775 " \"id\": %d,"
2776 " \"mime\": \"text/plain\","
2777 " \"paused\": false,"
2778 " \"url\": \"%s\"}]",
2779 result_id,
2780 download_url.c_str())));
2781 ASSERT_TRUE(WaitFor(
2782 events::kOnDownloadDeterminingFilename,
2783 base::StringPrintf("[{\"id\": %d,"
2784 " \"filename\":\"slow.txt\"}]",
2785 result_id)));
2786 ASSERT_TRUE(item->GetTargetFilePath().empty());
2787 ASSERT_EQ(DownloadItem::IN_PROGRESS, item->GetState());
2788
2789 // Respond to the onDeterminingFilename.
2790 std::string error;
2791 ASSERT_FALSE(ExtensionDownloadsEventRouter::DetermineFilename(
2792 browser()->profile(),
2793 false,
2794 GetExtensionId(),
2795 result_id,
2796 base::FilePath(FILE_PATH_LITERAL("..")),
2797 extensions::api::downloads::FILENAME_CONFLICT_ACTION_UNIQUIFY,
2798 &error));
2799 EXPECT_STREQ(download_extension_errors::kInvalidFilenameError, error.c_str());
2800 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
2801 base::StringPrintf("[{\"id\": %d,"
2802 " \"filename\": {"
2803 " \"previous\": \"\","
2804 " \"current\": \"%s\"}}]",
2805 result_id,
2806 GetFilename("slow.txt").c_str())));
2807 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
2808 base::StringPrintf("[{\"id\": %d,"
2809 " \"state\": {"
2810 " \"previous\": \"in_progress\","
2811 " \"current\": \"complete\"}}]",
2812 result_id)));
2813 }
2814
2815 IN_PROC_BROWSER_TEST_F(
2816 DownloadExtensionTest,
2817 DownloadExtensionTest_OnDeterminingFilename_AbsPathInvalid) {
2818 GoOnTheRecord();
2819 LoadExtension("downloads_split");
2820 AddFilenameDeterminer();
2821 ASSERT_TRUE(StartEmbeddedTestServer());
2822 ASSERT_TRUE(test_server()->Start());
2823 std::string download_url = test_server()->GetURL("slow?0").spec();
2824
2825 // Start downloading a file.
2826 scoped_ptr<base::Value> result(RunFunctionAndReturnResult(
2827 new DownloadsDownloadFunction(), base::StringPrintf(
2828 "[{\"url\": \"%s\"}]", download_url.c_str())));
2829 ASSERT_TRUE(result.get());
2830 int result_id = -1;
2831 ASSERT_TRUE(result->GetAsInteger(&result_id));
2832 DownloadItem* item = GetCurrentManager()->GetDownload(result_id);
2833 ASSERT_TRUE(item);
2834 ScopedCancellingItem canceller(item);
2835 ASSERT_EQ(download_url, item->GetOriginalUrl().spec());
2836
2837 ASSERT_TRUE(WaitFor(events::kOnDownloadCreated,
2838 base::StringPrintf("[{\"danger\": \"safe\","
2839 " \"incognito\": false,"
2840 " \"id\": %d,"
2841 " \"mime\": \"text/plain\","
2842 " \"paused\": false,"
2843 " \"url\": \"%s\"}]",
2844 result_id,
2845 download_url.c_str())));
2846 ASSERT_TRUE(WaitFor(
2847 events::kOnDownloadDeterminingFilename,
2848 base::StringPrintf("[{\"id\": %d,"
2849 " \"filename\":\"slow.txt\"}]",
2850 result_id)));
2851 ASSERT_TRUE(item->GetTargetFilePath().empty());
2852 ASSERT_EQ(DownloadItem::IN_PROGRESS, item->GetState());
2853
2854 // Respond to the onDeterminingFilename. Absolute paths should be rejected.
2855 std::string error;
2856 ASSERT_FALSE(ExtensionDownloadsEventRouter::DetermineFilename(
2857 browser()->profile(),
2858 false,
2859 GetExtensionId(),
2860 result_id,
2861 downloads_directory().Append(FILE_PATH_LITERAL("sneaky.txt")),
2862 extensions::api::downloads::FILENAME_CONFLICT_ACTION_UNIQUIFY,
2863 &error));
2864 EXPECT_STREQ(download_extension_errors::kInvalidFilenameError, error.c_str());
2865
2866 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
2867 base::StringPrintf("[{\"id\": %d,"
2868 " \"filename\": {"
2869 " \"previous\": \"\","
2870 " \"current\": \"%s\"}}]",
2871 result_id,
2872 GetFilename("slow.txt").c_str())));
2873 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
2874 base::StringPrintf("[{\"id\": %d,"
2875 " \"state\": {"
2876 " \"previous\": \"in_progress\","
2877 " \"current\": \"complete\"}}]",
2878 result_id)));
2879 }
2880
2881 IN_PROC_BROWSER_TEST_F(
2882 DownloadExtensionTest,
2883 DownloadExtensionTest_OnDeterminingFilename_EmptyBasenameInvalid) {
2884 GoOnTheRecord();
2885 LoadExtension("downloads_split");
2886 AddFilenameDeterminer();
2887 ASSERT_TRUE(StartEmbeddedTestServer());
2888 ASSERT_TRUE(test_server()->Start());
2889 std::string download_url = test_server()->GetURL("slow?0").spec();
2890
2891 // Start downloading a file.
2892 scoped_ptr<base::Value> result(RunFunctionAndReturnResult(
2893 new DownloadsDownloadFunction(), base::StringPrintf(
2894 "[{\"url\": \"%s\"}]", download_url.c_str())));
2895 ASSERT_TRUE(result.get());
2896 int result_id = -1;
2897 ASSERT_TRUE(result->GetAsInteger(&result_id));
2898 DownloadItem* item = GetCurrentManager()->GetDownload(result_id);
2899 ASSERT_TRUE(item);
2900 ScopedCancellingItem canceller(item);
2901 ASSERT_EQ(download_url, item->GetOriginalUrl().spec());
2902
2903 ASSERT_TRUE(WaitFor(events::kOnDownloadCreated,
2904 base::StringPrintf("[{\"danger\": \"safe\","
2905 " \"incognito\": false,"
2906 " \"id\": %d,"
2907 " \"mime\": \"text/plain\","
2908 " \"paused\": false,"
2909 " \"url\": \"%s\"}]",
2910 result_id,
2911 download_url.c_str())));
2912 ASSERT_TRUE(WaitFor(
2913 events::kOnDownloadDeterminingFilename,
2914 base::StringPrintf("[{\"id\": %d,"
2915 " \"filename\":\"slow.txt\"}]",
2916 result_id)));
2917 ASSERT_TRUE(item->GetTargetFilePath().empty());
2918 ASSERT_EQ(DownloadItem::IN_PROGRESS, item->GetState());
2919
2920 // Respond to the onDeterminingFilename. Empty basenames should be rejected.
2921 std::string error;
2922 ASSERT_FALSE(ExtensionDownloadsEventRouter::DetermineFilename(
2923 browser()->profile(),
2924 false,
2925 GetExtensionId(),
2926 result_id,
2927 base::FilePath(FILE_PATH_LITERAL("foo/")),
2928 extensions::api::downloads::FILENAME_CONFLICT_ACTION_UNIQUIFY,
2929 &error));
2930 EXPECT_STREQ(download_extension_errors::kInvalidFilenameError, error.c_str());
2931
2932 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
2933 base::StringPrintf("[{\"id\": %d,"
2934 " \"filename\": {"
2935 " \"previous\": \"\","
2936 " \"current\": \"%s\"}}]",
2937 result_id,
2938 GetFilename("slow.txt").c_str())));
2939 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
2940 base::StringPrintf("[{\"id\": %d,"
2941 " \"state\": {"
2942 " \"previous\": \"in_progress\","
2943 " \"current\": \"complete\"}}]",
2944 result_id)));
2945 }
2946
2947 IN_PROC_BROWSER_TEST_F(
2948 DownloadExtensionTest,
2949 DownloadExtensionTest_OnDeterminingFilename_Override) {
2950 GoOnTheRecord();
2951 LoadExtension("downloads_split");
2952 AddFilenameDeterminer();
2953 ASSERT_TRUE(StartEmbeddedTestServer());
2954 ASSERT_TRUE(test_server()->Start());
2955 std::string download_url = test_server()->GetURL("slow?0").spec();
2956
2957 // Start downloading a file.
2958 scoped_ptr<base::Value> result(RunFunctionAndReturnResult(
2959 new DownloadsDownloadFunction(), base::StringPrintf(
2960 "[{\"url\": \"%s\"}]", download_url.c_str())));
2961 ASSERT_TRUE(result.get());
2962 int result_id = -1;
2963 ASSERT_TRUE(result->GetAsInteger(&result_id));
2964 DownloadItem* item = GetCurrentManager()->GetDownload(result_id);
2965 ASSERT_TRUE(item);
2966 ScopedCancellingItem canceller(item);
2967 ASSERT_EQ(download_url, item->GetOriginalUrl().spec());
2968 ASSERT_TRUE(WaitFor(events::kOnDownloadCreated,
2969 base::StringPrintf("[{\"danger\": \"safe\","
2970 " \"incognito\": false,"
2971 " \"id\": %d,"
2972 " \"mime\": \"text/plain\","
2973 " \"paused\": false,"
2974 " \"url\": \"%s\"}]",
2975 result_id,
2976 download_url.c_str())));
2977 ASSERT_TRUE(WaitFor(
2978 events::kOnDownloadDeterminingFilename,
2979 base::StringPrintf("[{\"id\": %d,"
2980 " \"filename\":\"slow.txt\"}]",
2981 result_id)));
2982 ASSERT_TRUE(item->GetTargetFilePath().empty());
2983 ASSERT_EQ(DownloadItem::IN_PROGRESS, item->GetState());
2984
2985 // Respond to the onDeterminingFilename.
2986 std::string error;
2987 ASSERT_TRUE(ExtensionDownloadsEventRouter::DetermineFilename(
2988 browser()->profile(),
2989 false,
2990 GetExtensionId(),
2991 result_id,
2992 base::FilePath(),
2993 extensions::api::downloads::FILENAME_CONFLICT_ACTION_UNIQUIFY,
2994 &error));
2995 EXPECT_EQ("", error);
2996
2997 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
2998 base::StringPrintf("[{\"id\": %d,"
2999 " \"filename\": {"
3000 " \"previous\": \"\","
3001 " \"current\": \"%s\"}}]",
3002 result_id,
3003 GetFilename("slow.txt").c_str())));
3004 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
3005 base::StringPrintf("[{\"id\": %d,"
3006 " \"state\": {"
3007 " \"previous\": \"in_progress\","
3008 " \"current\": \"complete\"}}]",
3009 result_id)));
3010
3011 // Start downloading a file.
3012 result.reset(RunFunctionAndReturnResult(
3013 new DownloadsDownloadFunction(), base::StringPrintf(
3014 "[{\"url\": \"%s\"}]", download_url.c_str())));
3015 ASSERT_TRUE(result.get());
3016 result_id = -1;
3017 ASSERT_TRUE(result->GetAsInteger(&result_id));
3018 item = GetCurrentManager()->GetDownload(result_id);
3019 ASSERT_TRUE(item);
3020 ScopedCancellingItem canceller2(item);
3021 ASSERT_EQ(download_url, item->GetOriginalUrl().spec());
3022
3023 ASSERT_TRUE(WaitFor(events::kOnDownloadCreated,
3024 base::StringPrintf("[{\"danger\": \"safe\","
3025 " \"incognito\": false,"
3026 " \"id\": %d,"
3027 " \"mime\": \"text/plain\","
3028 " \"paused\": false,"
3029 " \"url\": \"%s\"}]",
3030 result_id,
3031 download_url.c_str())));
3032 ASSERT_TRUE(WaitFor(
3033 events::kOnDownloadDeterminingFilename,
3034 base::StringPrintf("[{\"id\": %d,"
3035 " \"filename\":\"slow.txt\"}]",
3036 result_id)));
3037 ASSERT_TRUE(item->GetTargetFilePath().empty());
3038 ASSERT_EQ(DownloadItem::IN_PROGRESS, item->GetState());
3039
3040 // Respond to the onDeterminingFilename.
3041 // Also test that DetermineFilename allows (chrome) extensions to set
3042 // filenames without (filename) extensions. (Don't ask about v8 extensions or
3043 // python extensions or kernel extensions or firefox extensions...)
3044 error = "";
3045 ASSERT_TRUE(ExtensionDownloadsEventRouter::DetermineFilename(
3046 browser()->profile(),
3047 false,
3048 GetExtensionId(),
3049 result_id,
3050 base::FilePath(FILE_PATH_LITERAL("foo")),
3051 extensions::api::downloads::FILENAME_CONFLICT_ACTION_OVERWRITE,
3052 &error));
3053 EXPECT_EQ("", error);
3054
3055 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
3056 base::StringPrintf("[{\"id\": %d,"
3057 " \"filename\": {"
3058 " \"previous\": \"\","
3059 " \"current\": \"%s\"}}]",
3060 result_id,
3061 GetFilename("foo").c_str())));
3062 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
3063 base::StringPrintf("[{\"id\": %d,"
3064 " \"state\": {"
3065 " \"previous\": \"in_progress\","
3066 " \"current\": \"complete\"}}]",
3067 result_id)));
3068 }
3069
3070 // TODO test precedence rules: install_time
3071
3072 IN_PROC_BROWSER_TEST_F(
3073 DownloadExtensionTest,
3074 DownloadExtensionTest_OnDeterminingFilename_RemoveFilenameDeterminer) {
3075 ASSERT_TRUE(StartEmbeddedTestServer());
3076 ASSERT_TRUE(test_server()->Start());
3077 GoOnTheRecord();
3078 LoadExtension("downloads_split");
3079 content::RenderProcessHost* host = AddFilenameDeterminer();
3080 std::string download_url = test_server()->GetURL("slow?0").spec();
3081
3082 // Start downloading a file.
3083 scoped_ptr<base::Value> result(RunFunctionAndReturnResult(
3084 new DownloadsDownloadFunction(), base::StringPrintf(
3085 "[{\"url\": \"%s\"}]", download_url.c_str())));
3086 ASSERT_TRUE(result.get());
3087 int result_id = -1;
3088 ASSERT_TRUE(result->GetAsInteger(&result_id));
3089 DownloadItem* item = GetCurrentManager()->GetDownload(result_id);
3090 ASSERT_TRUE(item);
3091 ScopedCancellingItem canceller(item);
3092 ASSERT_EQ(download_url, item->GetOriginalUrl().spec());
3093
3094 ASSERT_TRUE(WaitFor(events::kOnDownloadCreated,
3095 base::StringPrintf("[{\"danger\": \"safe\","
3096 " \"incognito\": false,"
3097 " \"id\": %d,"
3098 " \"mime\": \"text/plain\","
3099 " \"paused\": false,"
3100 " \"url\": \"%s\"}]",
3101 result_id,
3102 download_url.c_str())));
3103 ASSERT_TRUE(WaitFor(
3104 events::kOnDownloadDeterminingFilename,
3105 base::StringPrintf("[{\"id\": %d,"
3106 " \"filename\":\"slow.txt\"}]",
3107 result_id)));
3108 ASSERT_TRUE(item->GetTargetFilePath().empty());
3109 ASSERT_EQ(DownloadItem::IN_PROGRESS, item->GetState());
3110
3111 // Remove a determiner while waiting for it.
3112 RemoveFilenameDeterminer(host);
3113
3114 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
3115 base::StringPrintf("[{\"id\": %d,"
3116 " \"state\": {"
3117 " \"previous\": \"in_progress\","
3118 " \"current\": \"complete\"}}]",
3119 result_id)));
3120 }
3121
3122 IN_PROC_BROWSER_TEST_F(
3123 DownloadExtensionTest,
3124 DownloadExtensionTest_OnDeterminingFilename_IncognitoSplit) {
3125 LoadExtension("downloads_split");
3126 ASSERT_TRUE(StartEmbeddedTestServer());
3127 ASSERT_TRUE(test_server()->Start());
3128 std::string download_url = test_server()->GetURL("slow?0").spec();
3129
3130 GoOnTheRecord();
3131 AddFilenameDeterminer();
3132
3133 GoOffTheRecord();
3134 AddFilenameDeterminer();
3135
3136 // Start an on-record download.
3137 GoOnTheRecord();
3138 scoped_ptr<base::Value> result(RunFunctionAndReturnResult(
3139 new DownloadsDownloadFunction(), base::StringPrintf(
3140 "[{\"url\": \"%s\"}]", download_url.c_str())));
3141 ASSERT_TRUE(result.get());
3142 int result_id = -1;
3143 ASSERT_TRUE(result->GetAsInteger(&result_id));
3144 DownloadItem* item = GetCurrentManager()->GetDownload(result_id);
3145 ASSERT_TRUE(item);
3146 ScopedCancellingItem canceller(item);
3147 ASSERT_EQ(download_url, item->GetOriginalUrl().spec());
3148
3149 // Wait for the onCreated and onDeterminingFilename events.
3150 ASSERT_TRUE(WaitFor(events::kOnDownloadCreated,
3151 base::StringPrintf("[{\"danger\": \"safe\","
3152 " \"incognito\": false,"
3153 " \"id\": %d,"
3154 " \"mime\": \"text/plain\","
3155 " \"paused\": false,"
3156 " \"url\": \"%s\"}]",
3157 result_id,
3158 download_url.c_str())));
3159 ASSERT_TRUE(WaitFor(
3160 events::kOnDownloadDeterminingFilename,
3161 base::StringPrintf("[{\"id\": %d,"
3162 " \"incognito\": false,"
3163 " \"filename\":\"slow.txt\"}]",
3164 result_id)));
3165 ASSERT_TRUE(item->GetTargetFilePath().empty());
3166 ASSERT_EQ(DownloadItem::IN_PROGRESS, item->GetState());
3167
3168 // Respond to the onDeterminingFilename events.
3169 std::string error;
3170 ASSERT_TRUE(ExtensionDownloadsEventRouter::DetermineFilename(
3171 current_browser()->profile(),
3172 false,
3173 GetExtensionId(),
3174 result_id,
3175 base::FilePath(FILE_PATH_LITERAL("42.txt")),
3176 extensions::api::downloads::FILENAME_CONFLICT_ACTION_UNIQUIFY,
3177 &error));
3178 EXPECT_EQ("", error);
3179
3180 // The download should complete successfully.
3181 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
3182 base::StringPrintf("[{\"id\": %d,"
3183 " \"filename\": {"
3184 " \"previous\": \"\","
3185 " \"current\": \"%s\"}}]",
3186 result_id,
3187 GetFilename("42.txt").c_str())));
3188 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
3189 base::StringPrintf("[{\"id\": %d,"
3190 " \"state\": {"
3191 " \"previous\": \"in_progress\","
3192 " \"current\": \"complete\"}}]",
3193 result_id)));
3194
3195 // Start an incognito download for comparison.
3196 GoOffTheRecord();
3197 result.reset(RunFunctionAndReturnResult(
3198 new DownloadsDownloadFunction(), base::StringPrintf(
3199 "[{\"url\": \"%s\"}]", download_url.c_str())));
3200 ASSERT_TRUE(result.get());
3201 result_id = -1;
3202 ASSERT_TRUE(result->GetAsInteger(&result_id));
3203 item = GetCurrentManager()->GetDownload(result_id);
3204 ASSERT_TRUE(item);
3205 ScopedCancellingItem canceller2(item);
3206 ASSERT_EQ(download_url, item->GetOriginalUrl().spec());
3207
3208 ASSERT_TRUE(WaitFor(events::kOnDownloadCreated,
3209 base::StringPrintf("[{\"danger\": \"safe\","
3210 " \"incognito\": true,"
3211 " \"id\": %d,"
3212 " \"mime\": \"text/plain\","
3213 " \"paused\": false,"
3214 " \"url\": \"%s\"}]",
3215 result_id,
3216 download_url.c_str())));
3217 // On-Record renderers should not see events for off-record items.
3218 ASSERT_TRUE(WaitFor(
3219 events::kOnDownloadDeterminingFilename,
3220 base::StringPrintf("[{\"id\": %d,"
3221 " \"incognito\": true,"
3222 " \"filename\":\"slow.txt\"}]",
3223 result_id)));
3224 ASSERT_TRUE(item->GetTargetFilePath().empty());
3225 ASSERT_EQ(DownloadItem::IN_PROGRESS, item->GetState());
3226
3227 // Respond to the onDeterminingFilename.
3228 error = "";
3229 ASSERT_TRUE(ExtensionDownloadsEventRouter::DetermineFilename(
3230 current_browser()->profile(),
3231 false,
3232 GetExtensionId(),
3233 result_id,
3234 base::FilePath(FILE_PATH_LITERAL("5.txt")),
3235 extensions::api::downloads::FILENAME_CONFLICT_ACTION_UNIQUIFY,
3236 &error));
3237 EXPECT_EQ("", error);
3238
3239 // The download should complete successfully.
3240 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
3241 base::StringPrintf("[{\"id\": %d,"
3242 " \"filename\": {"
3243 " \"previous\": \"\","
3244 " \"current\": \"%s\"}}]",
3245 result_id,
3246 GetFilename("5.txt").c_str())));
3247 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
3248 base::StringPrintf("[{\"id\": %d,"
3249 " \"state\": {"
3250 " \"previous\": \"in_progress\","
3251 " \"current\": \"complete\"}}]",
3252 result_id)));
3253 }
3254
3255 IN_PROC_BROWSER_TEST_F(
3256 DownloadExtensionTest,
3257 DownloadExtensionTest_OnDeterminingFilename_IncognitoSpanning) {
3258 LoadExtension("downloads_spanning");
3259 ASSERT_TRUE(StartEmbeddedTestServer());
3260 ASSERT_TRUE(test_server()->Start());
3261 std::string download_url = test_server()->GetURL("slow?0").spec();
3262
3263 GoOnTheRecord();
3264 AddFilenameDeterminer();
3265
3266 // There is a single extension renderer that sees both on-record and
3267 // off-record events. The extension functions see the on-record profile with
3268 // include_incognito=true.
3269
3270 // Start an on-record download.
3271 GoOnTheRecord();
3272 scoped_ptr<base::Value> result(RunFunctionAndReturnResult(
3273 new DownloadsDownloadFunction(), base::StringPrintf(
3274 "[{\"url\": \"%s\"}]", download_url.c_str())));
3275 ASSERT_TRUE(result.get());
3276 int result_id = -1;
3277 ASSERT_TRUE(result->GetAsInteger(&result_id));
3278 DownloadItem* item = GetCurrentManager()->GetDownload(result_id);
3279 ASSERT_TRUE(item);
3280 ScopedCancellingItem canceller(item);
3281 ASSERT_EQ(download_url, item->GetOriginalUrl().spec());
3282
3283 // Wait for the onCreated and onDeterminingFilename events.
3284 ASSERT_TRUE(WaitFor(events::kOnDownloadCreated,
3285 base::StringPrintf("[{\"danger\": \"safe\","
3286 " \"incognito\": false,"
3287 " \"id\": %d,"
3288 " \"mime\": \"text/plain\","
3289 " \"paused\": false,"
3290 " \"url\": \"%s\"}]",
3291 result_id,
3292 download_url.c_str())));
3293 ASSERT_TRUE(WaitFor(
3294 events::kOnDownloadDeterminingFilename,
3295 base::StringPrintf("[{\"id\": %d,"
3296 " \"incognito\": false,"
3297 " \"filename\":\"slow.txt\"}]",
3298 result_id)));
3299 ASSERT_TRUE(item->GetTargetFilePath().empty());
3300 ASSERT_EQ(DownloadItem::IN_PROGRESS, item->GetState());
3301
3302 // Respond to the onDeterminingFilename events.
3303 std::string error;
3304 ASSERT_TRUE(ExtensionDownloadsEventRouter::DetermineFilename(
3305 current_browser()->profile(),
3306 true,
3307 GetExtensionId(),
3308 result_id,
3309 base::FilePath(FILE_PATH_LITERAL("42.txt")),
3310 extensions::api::downloads::FILENAME_CONFLICT_ACTION_UNIQUIFY,
3311 &error));
3312 EXPECT_EQ("", error);
3313
3314 // The download should complete successfully.
3315 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
3316 base::StringPrintf("[{\"id\": %d,"
3317 " \"filename\": {"
3318 " \"previous\": \"\","
3319 " \"current\": \"%s\"}}]",
3320 result_id,
3321 GetFilename("42.txt").c_str())));
3322 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
3323 base::StringPrintf("[{\"id\": %d,"
3324 " \"state\": {"
3325 " \"previous\": \"in_progress\","
3326 " \"current\": \"complete\"}}]",
3327 result_id)));
3328
3329 // Start an incognito download for comparison.
3330 GoOffTheRecord();
3331 result.reset(RunFunctionAndReturnResult(
3332 new DownloadsDownloadFunction(), base::StringPrintf(
3333 "[{\"url\": \"%s\"}]", download_url.c_str())));
3334 ASSERT_TRUE(result.get());
3335 result_id = -1;
3336 ASSERT_TRUE(result->GetAsInteger(&result_id));
3337 item = GetCurrentManager()->GetDownload(result_id);
3338 ASSERT_TRUE(item);
3339 ScopedCancellingItem canceller2(item);
3340 ASSERT_EQ(download_url, item->GetOriginalUrl().spec());
3341
3342 ASSERT_TRUE(WaitFor(events::kOnDownloadCreated,
3343 base::StringPrintf("[{\"danger\": \"safe\","
3344 " \"incognito\": true,"
3345 " \"id\": %d,"
3346 " \"mime\": \"text/plain\","
3347 " \"paused\": false,"
3348 " \"url\": \"%s\"}]",
3349 result_id,
3350 download_url.c_str())));
3351 ASSERT_TRUE(WaitFor(
3352 events::kOnDownloadDeterminingFilename,
3353 base::StringPrintf("[{\"id\": %d,"
3354 " \"incognito\": true,"
3355 " \"filename\":\"slow.txt\"}]",
3356 result_id)));
3357 ASSERT_TRUE(item->GetTargetFilePath().empty());
3358 ASSERT_EQ(DownloadItem::IN_PROGRESS, item->GetState());
3359
3360 // Respond to the onDeterminingFilename.
3361 error = "";
3362 ASSERT_TRUE(ExtensionDownloadsEventRouter::DetermineFilename(
3363 current_browser()->profile(),
3364 true,
3365 GetExtensionId(),
3366 result_id,
3367 base::FilePath(FILE_PATH_LITERAL("42.txt")),
3368 extensions::api::downloads::FILENAME_CONFLICT_ACTION_UNIQUIFY,
3369 &error));
3370 EXPECT_EQ("", error);
3371
3372 // The download should complete successfully.
3373 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
3374 base::StringPrintf("[{\"id\": %d,"
3375 " \"filename\": {"
3376 " \"previous\": \"\","
3377 " \"current\": \"%s\"}}]",
3378 result_id,
3379 GetFilename("42 (1).txt").c_str())));
3380 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
3381 base::StringPrintf("[{\"id\": %d,"
3382 " \"state\": {"
3383 " \"previous\": \"in_progress\","
3384 " \"current\": \"complete\"}}]",
3385 result_id)));
3386 }
3387
3388 #if defined(OS_WIN)
3389 // This test is very flaky on Win XP and Aura. http://crbug.com/248438
3390 #define MAYBE_DownloadExtensionTest_OnDeterminingFilename_InterruptedResume \
3391 DISABLED_DownloadExtensionTest_OnDeterminingFilename_InterruptedResume
3392 #else
3393 #define MAYBE_DownloadExtensionTest_OnDeterminingFilename_InterruptedResume \
3394 DownloadExtensionTest_OnDeterminingFilename_InterruptedResume
3395 #endif
3396
3397 // Test download interruption while extensions determining filename. Should not
3398 // re-dispatch onDeterminingFilename.
3399 IN_PROC_BROWSER_TEST_F(
3400 DownloadExtensionTest,
3401 MAYBE_DownloadExtensionTest_OnDeterminingFilename_InterruptedResume) {
3402 CommandLine::ForCurrentProcess()->AppendSwitch(
3403 switches::kEnableDownloadResumption);
3404 LoadExtension("downloads_split");
3405 ASSERT_TRUE(StartEmbeddedTestServer());
3406 ASSERT_TRUE(test_server()->Start());
3407 GoOnTheRecord();
3408 content::RenderProcessHost* host = AddFilenameDeterminer();
3409
3410 // Start a download.
3411 DownloadItem* item = NULL;
3412 {
3413 DownloadManager* manager = GetCurrentManager();
3414 scoped_ptr<content::DownloadTestObserver> observer(
3415 new JustInProgressDownloadObserver(manager, 1));
3416 ASSERT_EQ(0, manager->InProgressCount());
3417 // Tabs created just for a download are automatically closed, invalidating
3418 // the download's WebContents. Downloads without WebContents cannot be
3419 // resumed. http://crbug.com/225901
3420 ui_test_utils::NavigateToURLWithDisposition(
3421 current_browser(),
3422 GURL(URLRequestSlowDownloadJob::kUnknownSizeUrl),
3423 CURRENT_TAB,
3424 ui_test_utils::BROWSER_TEST_NONE);
3425 observer->WaitForFinished();
3426 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::IN_PROGRESS));
3427 DownloadManager::DownloadVector items;
3428 manager->GetAllDownloads(&items);
3429 for (DownloadManager::DownloadVector::iterator iter = items.begin();
3430 iter != items.end(); ++iter) {
3431 if ((*iter)->GetState() == DownloadItem::IN_PROGRESS) {
3432 // There should be only one IN_PROGRESS item.
3433 EXPECT_EQ(NULL, item);
3434 item = *iter;
3435 }
3436 }
3437 ASSERT_TRUE(item);
3438 }
3439 ScopedCancellingItem canceller(item);
3440
3441 // Wait for the onCreated and onDeterminingFilename event.
3442 ASSERT_TRUE(WaitFor(events::kOnDownloadCreated,
3443 base::StringPrintf("[{\"danger\": \"safe\","
3444 " \"incognito\": false,"
3445 " \"id\": %d,"
3446 " \"mime\": \"application/octet-stream\","
3447 " \"paused\": false}]",
3448 item->GetId())));
3449 ASSERT_TRUE(WaitFor(
3450 events::kOnDownloadDeterminingFilename,
3451 base::StringPrintf("[{\"id\": %d,"
3452 " \"incognito\": false,"
3453 " \"filename\":\"download-unknown-size\"}]",
3454 item->GetId())));
3455 ASSERT_TRUE(item->GetTargetFilePath().empty());
3456 ASSERT_EQ(DownloadItem::IN_PROGRESS, item->GetState());
3457
3458 ClearEvents();
3459 ui_test_utils::NavigateToURLWithDisposition(
3460 current_browser(),
3461 GURL(URLRequestSlowDownloadJob::kErrorDownloadUrl),
3462 NEW_BACKGROUND_TAB,
3463 ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
3464
3465 // Errors caught before filename determination are delayed until after
3466 // filename determination.
3467 std::string error;
3468 ASSERT_TRUE(ExtensionDownloadsEventRouter::DetermineFilename(
3469 current_browser()->profile(),
3470 false,
3471 GetExtensionId(),
3472 item->GetId(),
3473 base::FilePath(FILE_PATH_LITERAL("42.txt")),
3474 extensions::api::downloads::FILENAME_CONFLICT_ACTION_UNIQUIFY,
3475 &error)) << error;
3476 EXPECT_EQ("", error);
3477 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
3478 base::StringPrintf("[{\"id\": %d,"
3479 " \"filename\": {"
3480 " \"previous\": \"\","
3481 " \"current\": \"%s\"}}]",
3482 item->GetId(),
3483 GetFilename("42.txt").c_str())));
3484
3485 content::DownloadUpdatedObserver interrupted(item, base::Bind(
3486 ItemIsInterrupted));
3487 ASSERT_TRUE(interrupted.WaitForEvent());
3488 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
3489 base::StringPrintf("[{\"id\": %d,"
3490 " \"error\":{\"current\":20},"
3491 " \"state\":{"
3492 " \"previous\":\"in_progress\","
3493 " \"current\":\"interrupted\"}}]",
3494 item->GetId())));
3495
3496 ClearEvents();
3497 // Downloads that are restarted on resumption trigger another download target
3498 // determination.
3499 RemoveFilenameDeterminer(host);
3500 item->Resume();
3501
3502 // Errors caught before filename determination is complete are delayed until
3503 // after filename determination so that, on resumption, filename determination
3504 // does not need to be re-done. So, there will not be a second
3505 // onDeterminingFilename event.
3506
3507 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
3508 base::StringPrintf("[{\"id\": %d,"
3509 " \"error\":{\"previous\":20},"
3510 " \"state\":{"
3511 " \"previous\":\"interrupted\","
3512 " \"current\":\"in_progress\"}}]",
3513 item->GetId())));
3514
3515 ClearEvents();
3516 FinishPendingSlowDownloads();
3517
3518 // The download should complete successfully.
3519 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
3520 base::StringPrintf("[{\"id\": %d,"
3521 " \"state\": {"
3522 " \"previous\": \"in_progress\","
3523 " \"current\": \"complete\"}}]",
3524 item->GetId())));
3525 }
3526
3527 // TODO(benjhayden) Figure out why DisableExtension() does not fire
3528 // OnListenerRemoved.
3529
3530 // TODO(benjhayden) Test that the shelf is shown for download() both with and
3531 // without a WebContents.
3532
3533 class DownloadsApiTest : public ExtensionApiTest {
3534 public:
3535 DownloadsApiTest() {}
3536 virtual ~DownloadsApiTest() {}
3537 private:
3538 DISALLOW_COPY_AND_ASSIGN(DownloadsApiTest);
3539 };
3540
3541
3542 IN_PROC_BROWSER_TEST_F(DownloadsApiTest, DownloadsApiTest) {
3543 ASSERT_TRUE(RunExtensionTest("downloads")) << message_;
3544 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698