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

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: @r212092 Created 7 years, 5 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.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 "javascript:document.write(\\\"hello\\\");",
1740 "javascript:return false;",
1741 "ftp://example.com/example.txt",
1742 };
1743
1744 for (size_t index = 0; index < arraysize(kInvalidURLs); ++index) {
1745 EXPECT_STREQ(download_extension_errors::kInvalidURLError,
1746 RunFunctionAndReturnError(new DownloadsDownloadFunction(),
1747 base::StringPrintf(
1748 "[{\"url\": \"%s\"}]", kInvalidURLs[index])).c_str());
1749 }
1750 }
1751
1752 // TODO(benjhayden): Set up a test ftp server, add ftp://localhost* to
1753 // permissions, test downloading from ftp.
1754
1755 // Valid URLs plus fragments are still valid URLs.
1756 IN_PROC_BROWSER_TEST_F(DownloadExtensionTest,
1757 DownloadExtensionTest_Download_URLFragment) {
1758 LoadExtension("downloads_split");
1759 ASSERT_TRUE(StartEmbeddedTestServer());
1760 ASSERT_TRUE(test_server()->Start());
1761 std::string download_url = test_server()->GetURL("slow?0#fragment").spec();
1762 GoOnTheRecord();
1763
1764 scoped_ptr<base::Value> result(RunFunctionAndReturnResult(
1765 new DownloadsDownloadFunction(), base::StringPrintf(
1766 "[{\"url\": \"%s\"}]", download_url.c_str())));
1767 ASSERT_TRUE(result.get());
1768 int result_id = -1;
1769 ASSERT_TRUE(result->GetAsInteger(&result_id));
1770 DownloadItem* item = GetCurrentManager()->GetDownload(result_id);
1771 ASSERT_TRUE(item);
1772 ScopedCancellingItem canceller(item);
1773 ASSERT_EQ(download_url, item->GetOriginalUrl().spec());
1774
1775 ASSERT_TRUE(WaitFor(events::kOnDownloadCreated,
1776 base::StringPrintf("[{\"danger\": \"safe\","
1777 " \"incognito\": false,"
1778 " \"mime\": \"text/plain\","
1779 " \"paused\": false,"
1780 " \"url\": \"%s\"}]",
1781 download_url.c_str())));
1782 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
1783 base::StringPrintf("[{\"id\": %d,"
1784 " \"filename\": {"
1785 " \"previous\": \"\","
1786 " \"current\": \"%s\"}}]",
1787 result_id,
1788 GetFilename("slow.txt").c_str())));
1789 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
1790 base::StringPrintf("[{\"id\": %d,"
1791 " \"state\": {"
1792 " \"previous\": \"in_progress\","
1793 " \"current\": \"complete\"}}]",
1794 result_id)));
1795 }
1796
1797 // Valid data URLs are valid URLs.
1798 IN_PROC_BROWSER_TEST_F(DownloadExtensionTest,
1799 DownloadExtensionTest_Download_DataURL) {
1800 LoadExtension("downloads_split");
1801 std::string download_url = "data:text/plain,hello";
1802 GoOnTheRecord();
1803
1804 scoped_ptr<base::Value> result(RunFunctionAndReturnResult(
1805 new DownloadsDownloadFunction(), base::StringPrintf(
1806 "[{\"url\": \"%s\","
1807 " \"filename\": \"data.txt\"}]", download_url.c_str())));
1808 ASSERT_TRUE(result.get());
1809 int result_id = -1;
1810 ASSERT_TRUE(result->GetAsInteger(&result_id));
1811 DownloadItem* item = GetCurrentManager()->GetDownload(result_id);
1812 ASSERT_TRUE(item);
1813 ScopedCancellingItem canceller(item);
1814 ASSERT_EQ(download_url, item->GetOriginalUrl().spec());
1815
1816 ASSERT_TRUE(WaitFor(events::kOnDownloadCreated,
1817 base::StringPrintf("[{\"danger\": \"safe\","
1818 " \"incognito\": false,"
1819 " \"mime\": \"text/plain\","
1820 " \"paused\": false,"
1821 " \"url\": \"%s\"}]",
1822 download_url.c_str())));
1823 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
1824 base::StringPrintf("[{\"id\": %d,"
1825 " \"filename\": {"
1826 " \"previous\": \"\","
1827 " \"current\": \"%s\"}}]",
1828 result_id,
1829 GetFilename("data.txt").c_str())));
1830 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
1831 base::StringPrintf("[{\"id\": %d,"
1832 " \"state\": {"
1833 " \"previous\": \"in_progress\","
1834 " \"current\": \"complete\"}}]",
1835 result_id)));
1836 }
1837
1838 // Valid file URLs are valid URLs.
1839 #if defined(OS_WIN) && defined(USE_AURA)
1840 // Disabled due to crbug.com/175711
1841 #define MAYBE_DownloadExtensionTest_Download_File \
1842 DISABLED_DownloadExtensionTest_Download_File
1843 #else
1844 #define MAYBE_DownloadExtensionTest_Download_File \
1845 DownloadExtensionTest_Download_File
1846 #endif
1847 IN_PROC_BROWSER_TEST_F(DownloadExtensionTest,
1848 MAYBE_DownloadExtensionTest_Download_File) {
1849 GoOnTheRecord();
1850 LoadExtension("downloads_split");
1851 std::string download_url = "file:///";
1852 #if defined(OS_WIN)
1853 download_url += "C:/";
1854 #endif
1855
1856 scoped_ptr<base::Value> result(RunFunctionAndReturnResult(
1857 new DownloadsDownloadFunction(), base::StringPrintf(
1858 "[{\"url\": \"%s\","
1859 " \"filename\": \"file.txt\"}]", download_url.c_str())));
1860 ASSERT_TRUE(result.get());
1861 int result_id = -1;
1862 ASSERT_TRUE(result->GetAsInteger(&result_id));
1863 DownloadItem* item = GetCurrentManager()->GetDownload(result_id);
1864 ASSERT_TRUE(item);
1865 ScopedCancellingItem canceller(item);
1866 ASSERT_EQ(download_url, item->GetOriginalUrl().spec());
1867
1868 ASSERT_TRUE(WaitFor(events::kOnDownloadCreated,
1869 base::StringPrintf("[{\"danger\": \"safe\","
1870 " \"incognito\": false,"
1871 " \"mime\": \"text/html\","
1872 " \"paused\": false,"
1873 " \"url\": \"%s\"}]",
1874 download_url.c_str())));
1875 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
1876 base::StringPrintf("[{\"id\": %d,"
1877 " \"filename\": {"
1878 " \"previous\": \"\","
1879 " \"current\": \"%s\"}}]",
1880 result_id,
1881 GetFilename("file.txt").c_str())));
1882 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
1883 base::StringPrintf("[{\"id\": %d,"
1884 " \"state\": {"
1885 " \"previous\": \"in_progress\","
1886 " \"current\": \"complete\"}}]",
1887 result_id)));
1888 }
1889
1890 // Test that auth-basic-succeed would fail if the resource requires the
1891 // Authorization header and chrome fails to propagate it back to the server.
1892 // This tests both that testserver.py does not succeed when it should fail as
1893 // well as how the downloads extension API exposes the failure to extensions.
1894 IN_PROC_BROWSER_TEST_F(DownloadExtensionTest,
1895 DownloadExtensionTest_Download_AuthBasic_Fail) {
1896 LoadExtension("downloads_split");
1897 ASSERT_TRUE(StartEmbeddedTestServer());
1898 ASSERT_TRUE(test_server()->Start());
1899 std::string download_url = test_server()->GetURL("auth-basic").spec();
1900 GoOnTheRecord();
1901
1902 scoped_ptr<base::Value> result(RunFunctionAndReturnResult(
1903 new DownloadsDownloadFunction(), base::StringPrintf(
1904 "[{\"url\": \"%s\","
1905 " \"filename\": \"auth-basic-fail.txt\"}]",
1906 download_url.c_str())));
1907 ASSERT_TRUE(result.get());
1908 int result_id = -1;
1909 ASSERT_TRUE(result->GetAsInteger(&result_id));
1910 DownloadItem* item = GetCurrentManager()->GetDownload(result_id);
1911 ASSERT_TRUE(item);
1912 ScopedCancellingItem canceller(item);
1913 ASSERT_EQ(download_url, item->GetOriginalUrl().spec());
1914
1915 ASSERT_TRUE(WaitForInterruption(item, 30, base::StringPrintf(
1916 "[{\"danger\": \"safe\","
1917 " \"incognito\": false,"
1918 " \"mime\": \"text/html\","
1919 " \"paused\": false,"
1920 " \"url\": \"%s\"}]",
1921 download_url.c_str())));
1922 }
1923
1924 // Test that DownloadsDownloadFunction propagates |headers| to the URLRequest.
1925 IN_PROC_BROWSER_TEST_F(DownloadExtensionTest,
1926 DownloadExtensionTest_Download_Headers) {
1927 LoadExtension("downloads_split");
1928 ASSERT_TRUE(StartEmbeddedTestServer());
1929 ASSERT_TRUE(test_server()->Start());
1930 std::string download_url = test_server()->GetURL("files/downloads/"
1931 "a_zip_file.zip?expected_headers=Foo:bar&expected_headers=Qx:yo").spec();
1932 GoOnTheRecord();
1933
1934 scoped_ptr<base::Value> result(RunFunctionAndReturnResult(
1935 new DownloadsDownloadFunction(), base::StringPrintf(
1936 "[{\"url\": \"%s\","
1937 " \"filename\": \"headers-succeed.txt\","
1938 " \"headers\": ["
1939 " {\"name\": \"Foo\", \"value\": \"bar\"},"
1940 " {\"name\": \"Qx\", \"value\":\"yo\"}]}]",
1941 download_url.c_str())));
1942 ASSERT_TRUE(result.get());
1943 int result_id = -1;
1944 ASSERT_TRUE(result->GetAsInteger(&result_id));
1945 DownloadItem* item = GetCurrentManager()->GetDownload(result_id);
1946 ASSERT_TRUE(item);
1947 ScopedCancellingItem canceller(item);
1948 ASSERT_EQ(download_url, item->GetOriginalUrl().spec());
1949
1950 ASSERT_TRUE(WaitFor(events::kOnDownloadCreated,
1951 base::StringPrintf("[{\"danger\": \"safe\","
1952 " \"incognito\": false,"
1953 " \"mime\": \"application/octet-stream\","
1954 " \"paused\": false,"
1955 " \"url\": \"%s\"}]",
1956 download_url.c_str())));
1957 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
1958 base::StringPrintf("[{\"id\": %d,"
1959 " \"filename\": {"
1960 " \"previous\": \"\","
1961 " \"current\": \"%s\"}}]",
1962 result_id,
1963 GetFilename("headers-succeed.txt").c_str())));
1964 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
1965 base::StringPrintf("[{\"id\": %d,"
1966 " \"state\": {"
1967 " \"previous\": \"in_progress\","
1968 " \"current\": \"complete\"}}]",
1969 result_id)));
1970 }
1971
1972 // Test that headers-succeed would fail if the resource requires the headers and
1973 // chrome fails to propagate them back to the server. This tests both that
1974 // testserver.py does not succeed when it should fail as well as how the
1975 // downloads extension api exposes the failure to extensions.
1976 IN_PROC_BROWSER_TEST_F(DownloadExtensionTest,
1977 DownloadExtensionTest_Download_Headers_Fail) {
1978 LoadExtension("downloads_split");
1979 ASSERT_TRUE(StartEmbeddedTestServer());
1980 ASSERT_TRUE(test_server()->Start());
1981 std::string download_url = test_server()->GetURL("files/downloads/"
1982 "a_zip_file.zip?expected_headers=Foo:bar&expected_headers=Qx:yo").spec();
1983 GoOnTheRecord();
1984
1985 scoped_ptr<base::Value> result(RunFunctionAndReturnResult(
1986 new DownloadsDownloadFunction(), base::StringPrintf(
1987 "[{\"url\": \"%s\","
1988 " \"filename\": \"headers-fail.txt\"}]",
1989 download_url.c_str())));
1990 ASSERT_TRUE(result.get());
1991 int result_id = -1;
1992 ASSERT_TRUE(result->GetAsInteger(&result_id));
1993 DownloadItem* item = GetCurrentManager()->GetDownload(result_id);
1994 ASSERT_TRUE(item);
1995 ScopedCancellingItem canceller(item);
1996 ASSERT_EQ(download_url, item->GetOriginalUrl().spec());
1997
1998 ASSERT_TRUE(WaitForInterruption(item, 33, base::StringPrintf(
1999 "[{\"danger\": \"safe\","
2000 " \"incognito\": false,"
2001 " \"bytesReceived\": 0,"
2002 " \"mime\": \"\","
2003 " \"paused\": false,"
2004 " \"url\": \"%s\"}]",
2005 download_url.c_str())));
2006 }
2007
2008 // Test that DownloadsDownloadFunction propagates the Authorization header
2009 // correctly.
2010 IN_PROC_BROWSER_TEST_F(DownloadExtensionTest,
2011 DownloadExtensionTest_Download_AuthBasic) {
2012 LoadExtension("downloads_split");
2013 ASSERT_TRUE(StartEmbeddedTestServer());
2014 ASSERT_TRUE(test_server()->Start());
2015 std::string download_url = test_server()->GetURL("auth-basic").spec();
2016 // This is just base64 of 'username:secret'.
2017 static const char* kAuthorization = "dXNlcm5hbWU6c2VjcmV0";
2018 GoOnTheRecord();
2019
2020 scoped_ptr<base::Value> result(RunFunctionAndReturnResult(
2021 new DownloadsDownloadFunction(), base::StringPrintf(
2022 "[{\"url\": \"%s\","
2023 " \"filename\": \"auth-basic-succeed.txt\","
2024 " \"headers\": [{"
2025 " \"name\": \"Authorization\","
2026 " \"value\": \"Basic %s\"}]}]",
2027 download_url.c_str(), kAuthorization)));
2028 ASSERT_TRUE(result.get());
2029 int result_id = -1;
2030 ASSERT_TRUE(result->GetAsInteger(&result_id));
2031 DownloadItem* item = GetCurrentManager()->GetDownload(result_id);
2032 ASSERT_TRUE(item);
2033 ScopedCancellingItem canceller(item);
2034 ASSERT_EQ(download_url, item->GetOriginalUrl().spec());
2035
2036 ASSERT_TRUE(WaitFor(events::kOnDownloadCreated,
2037 base::StringPrintf("[{\"danger\": \"safe\","
2038 " \"incognito\": false,"
2039 " \"mime\": \"text/html\","
2040 " \"paused\": false,"
2041 " \"url\": \"%s\"}]", download_url.c_str())));
2042 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
2043 base::StringPrintf("[{\"id\": %d,"
2044 " \"state\": {"
2045 " \"previous\": \"in_progress\","
2046 " \"current\": \"complete\"}}]", result_id)));
2047 }
2048
2049 // Test that DownloadsDownloadFunction propagates the |method| and |body|
2050 // parameters to the URLRequest.
2051 IN_PROC_BROWSER_TEST_F(DownloadExtensionTest,
2052 DownloadExtensionTest_Download_Post) {
2053 LoadExtension("downloads_split");
2054 ASSERT_TRUE(StartEmbeddedTestServer());
2055 ASSERT_TRUE(test_server()->Start());
2056 std::string download_url = test_server()->GetURL("files/post/downloads/"
2057 "a_zip_file.zip?expected_body=BODY").spec();
2058 GoOnTheRecord();
2059
2060 scoped_ptr<base::Value> result(RunFunctionAndReturnResult(
2061 new DownloadsDownloadFunction(), base::StringPrintf(
2062 "[{\"url\": \"%s\","
2063 " \"filename\": \"post-succeed.txt\","
2064 " \"method\": \"POST\","
2065 " \"body\": \"BODY\"}]",
2066 download_url.c_str())));
2067 ASSERT_TRUE(result.get());
2068 int result_id = -1;
2069 ASSERT_TRUE(result->GetAsInteger(&result_id));
2070 DownloadItem* item = GetCurrentManager()->GetDownload(result_id);
2071 ASSERT_TRUE(item);
2072 ScopedCancellingItem canceller(item);
2073 ASSERT_EQ(download_url, item->GetOriginalUrl().spec());
2074
2075 ASSERT_TRUE(WaitFor(events::kOnDownloadCreated,
2076 base::StringPrintf("[{\"danger\": \"safe\","
2077 " \"incognito\": false,"
2078 " \"mime\": \"application/octet-stream\","
2079 " \"paused\": false,"
2080 " \"url\": \"%s\"}]", download_url.c_str())));
2081 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
2082 base::StringPrintf("[{\"id\": %d,"
2083 " \"filename\": {"
2084 " \"previous\": \"\","
2085 " \"current\": \"%s\"}}]",
2086 result_id,
2087 GetFilename("post-succeed.txt").c_str())));
2088 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
2089 base::StringPrintf("[{\"id\": %d,"
2090 " \"state\": {"
2091 " \"previous\": \"in_progress\","
2092 " \"current\": \"complete\"}}]",
2093 result_id)));
2094 }
2095
2096 // Test that downloadPostSuccess would fail if the resource requires the POST
2097 // method, and chrome fails to propagate the |method| parameter back to the
2098 // server. This tests both that testserver.py does not succeed when it should
2099 // fail, and this tests how the downloads extension api exposes the failure to
2100 // extensions.
2101 IN_PROC_BROWSER_TEST_F(DownloadExtensionTest,
2102 DownloadExtensionTest_Download_Post_Get) {
2103 LoadExtension("downloads_split");
2104 ASSERT_TRUE(StartEmbeddedTestServer());
2105 ASSERT_TRUE(test_server()->Start());
2106 std::string download_url = test_server()->GetURL("files/post/downloads/"
2107 "a_zip_file.zip?expected_body=BODY").spec();
2108 GoOnTheRecord();
2109
2110 scoped_ptr<base::Value> result(RunFunctionAndReturnResult(
2111 new DownloadsDownloadFunction(), base::StringPrintf(
2112 "[{\"url\": \"%s\","
2113 " \"body\": \"BODY\","
2114 " \"filename\": \"post-get.txt\"}]",
2115 download_url.c_str())));
2116 ASSERT_TRUE(result.get());
2117 int result_id = -1;
2118 ASSERT_TRUE(result->GetAsInteger(&result_id));
2119 DownloadItem* item = GetCurrentManager()->GetDownload(result_id);
2120 ASSERT_TRUE(item);
2121 ScopedCancellingItem canceller(item);
2122 ASSERT_EQ(download_url, item->GetOriginalUrl().spec());
2123
2124 ASSERT_TRUE(WaitForInterruption(item, 33, base::StringPrintf(
2125 "[{\"danger\": \"safe\","
2126 " \"incognito\": false,"
2127 " \"mime\": \"\","
2128 " \"paused\": false,"
2129 " \"id\": %d,"
2130 " \"url\": \"%s\"}]",
2131 result_id,
2132 download_url.c_str())));
2133 }
2134
2135 // Test that downloadPostSuccess would fail if the resource requires the POST
2136 // method, and chrome fails to propagate the |body| parameter back to the
2137 // server. This tests both that testserver.py does not succeed when it should
2138 // fail, and this tests how the downloads extension api exposes the failure to
2139 // extensions.
2140 IN_PROC_BROWSER_TEST_F(DownloadExtensionTest,
2141 DownloadExtensionTest_Download_Post_NoBody) {
2142 LoadExtension("downloads_split");
2143 ASSERT_TRUE(StartEmbeddedTestServer());
2144 ASSERT_TRUE(test_server()->Start());
2145 std::string download_url = test_server()->GetURL("files/post/downloads/"
2146 "a_zip_file.zip?expected_body=BODY").spec();
2147 GoOnTheRecord();
2148
2149 scoped_ptr<base::Value> result(RunFunctionAndReturnResult(
2150 new DownloadsDownloadFunction(), base::StringPrintf(
2151 "[{\"url\": \"%s\","
2152 " \"method\": \"POST\","
2153 " \"filename\": \"post-nobody.txt\"}]",
2154 download_url.c_str())));
2155 ASSERT_TRUE(result.get());
2156 int result_id = -1;
2157 ASSERT_TRUE(result->GetAsInteger(&result_id));
2158 DownloadItem* item = GetCurrentManager()->GetDownload(result_id);
2159 ASSERT_TRUE(item);
2160 ScopedCancellingItem canceller(item);
2161 ASSERT_EQ(download_url, item->GetOriginalUrl().spec());
2162
2163 ASSERT_TRUE(WaitForInterruption(item, 33, base::StringPrintf(
2164 "[{\"danger\": \"safe\","
2165 " \"incognito\": false,"
2166 " \"mime\": \"\","
2167 " \"paused\": false,"
2168 " \"id\": %d,"
2169 " \"url\": \"%s\"}]",
2170 result_id,
2171 download_url.c_str())));
2172 }
2173
2174 // Test that cancel()ing an in-progress download causes its state to transition
2175 // to interrupted, and test that that state transition is detectable by an
2176 // onChanged event listener. TODO(benjhayden): Test other sources of
2177 // interruptions such as server death.
2178 IN_PROC_BROWSER_TEST_F(DownloadExtensionTest,
2179 DownloadExtensionTest_Download_Cancel) {
2180 LoadExtension("downloads_split");
2181 ASSERT_TRUE(StartEmbeddedTestServer());
2182 ASSERT_TRUE(test_server()->Start());
2183 std::string download_url = test_server()->GetURL(
2184 "download-known-size").spec();
2185 GoOnTheRecord();
2186
2187 scoped_ptr<base::Value> result(RunFunctionAndReturnResult(
2188 new DownloadsDownloadFunction(), base::StringPrintf(
2189 "[{\"url\": \"%s\"}]", download_url.c_str())));
2190 ASSERT_TRUE(result.get());
2191 int result_id = -1;
2192 ASSERT_TRUE(result->GetAsInteger(&result_id));
2193 DownloadItem* item = GetCurrentManager()->GetDownload(result_id);
2194 ASSERT_TRUE(item);
2195 ScopedCancellingItem canceller(item);
2196 ASSERT_EQ(download_url, item->GetOriginalUrl().spec());
2197
2198 ASSERT_TRUE(WaitFor(events::kOnDownloadCreated,
2199 base::StringPrintf("[{\"danger\": \"safe\","
2200 " \"incognito\": false,"
2201 " \"mime\": \"application/octet-stream\","
2202 " \"paused\": false,"
2203 " \"id\": %d,"
2204 " \"url\": \"%s\"}]",
2205 result_id,
2206 download_url.c_str())));
2207 item->Cancel(true);
2208 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
2209 base::StringPrintf("[{\"id\": %d,"
2210 " \"error\": {\"current\": 40},"
2211 " \"state\": {"
2212 " \"previous\": \"in_progress\","
2213 " \"current\": \"interrupted\"}}]",
2214 result_id)));
2215 }
2216
2217 // Test downloading filesystem: URLs.
2218 // NOTE: chrome disallows creating HTML5 FileSystem Files in incognito.
2219 IN_PROC_BROWSER_TEST_F(DownloadExtensionTest,
2220 DownloadExtensionTest_Download_FileSystemURL) {
2221 static const char* kPayloadData = "on the record\ndata";
2222 GoOnTheRecord();
2223 LoadExtension("downloads_split");
2224 HTML5FileWriter html5_file_writer(
2225 browser()->profile(),
2226 "on_record.txt",
2227 GetExtensionURL(),
2228 events_listener(),
2229 kPayloadData);
2230 ASSERT_TRUE(html5_file_writer.WriteFile());
2231
2232 std::string download_url = "filesystem:" + GetExtensionURL() +
2233 "temporary/on_record.txt";
2234 scoped_ptr<base::Value> result(RunFunctionAndReturnResult(
2235 new DownloadsDownloadFunction(), base::StringPrintf(
2236 "[{\"url\": \"%s\"}]", download_url.c_str())));
2237 ASSERT_TRUE(result.get());
2238 int result_id = -1;
2239 ASSERT_TRUE(result->GetAsInteger(&result_id));
2240
2241 DownloadItem* item = GetCurrentManager()->GetDownload(result_id);
2242 ASSERT_TRUE(item);
2243 ScopedCancellingItem canceller(item);
2244 ASSERT_EQ(download_url, item->GetOriginalUrl().spec());
2245
2246 ASSERT_TRUE(WaitFor(events::kOnDownloadCreated,
2247 base::StringPrintf("[{\"danger\": \"safe\","
2248 " \"incognito\": false,"
2249 " \"mime\": \"text/plain\","
2250 " \"paused\": false,"
2251 " \"url\": \"%s\"}]",
2252 download_url.c_str())));
2253 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
2254 base::StringPrintf("[{\"id\": %d,"
2255 " \"filename\": {"
2256 " \"previous\": \"\","
2257 " \"current\": \"%s\"}}]",
2258 result_id,
2259 GetFilename("on_record.txt").c_str())));
2260 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
2261 base::StringPrintf("[{\"id\": %d,"
2262 " \"state\": {"
2263 " \"previous\": \"in_progress\","
2264 " \"current\": \"complete\"}}]",
2265 result_id)));
2266 std::string disk_data;
2267 EXPECT_TRUE(file_util::ReadFileToString(item->GetTargetFilePath(),
2268 &disk_data));
2269 EXPECT_STREQ(kPayloadData, disk_data.c_str());
2270 }
2271
2272 IN_PROC_BROWSER_TEST_F(DownloadExtensionTest,
2273 DownloadExtensionTest_OnDeterminingFilename_NoChange) {
2274 GoOnTheRecord();
2275 LoadExtension("downloads_split");
2276 AddFilenameDeterminer();
2277 ASSERT_TRUE(StartEmbeddedTestServer());
2278 ASSERT_TRUE(test_server()->Start());
2279 std::string download_url = test_server()->GetURL("slow?0").spec();
2280
2281 // Start downloading a file.
2282 scoped_ptr<base::Value> result(RunFunctionAndReturnResult(
2283 new DownloadsDownloadFunction(), base::StringPrintf(
2284 "[{\"url\": \"%s\"}]", download_url.c_str())));
2285 ASSERT_TRUE(result.get());
2286 int result_id = -1;
2287 ASSERT_TRUE(result->GetAsInteger(&result_id));
2288 DownloadItem* item = GetCurrentManager()->GetDownload(result_id);
2289 ASSERT_TRUE(item);
2290 ScopedCancellingItem canceller(item);
2291 ASSERT_EQ(download_url, item->GetOriginalUrl().spec());
2292
2293 // Wait for the onCreated and onDeterminingFilename events.
2294 ASSERT_TRUE(WaitFor(events::kOnDownloadCreated,
2295 base::StringPrintf("[{\"danger\": \"safe\","
2296 " \"incognito\": false,"
2297 " \"id\": %d,"
2298 " \"mime\": \"text/plain\","
2299 " \"paused\": false,"
2300 " \"url\": \"%s\"}]",
2301 result_id,
2302 download_url.c_str())));
2303 ASSERT_TRUE(WaitFor(
2304 events::kOnDownloadDeterminingFilename,
2305 base::StringPrintf("[{\"id\": %d,"
2306 " \"filename\":\"slow.txt\"}]",
2307 result_id)));
2308 ASSERT_TRUE(item->GetTargetFilePath().empty());
2309 ASSERT_EQ(DownloadItem::IN_PROGRESS, item->GetState());
2310
2311 // Respond to the onDeterminingFilename.
2312 std::string error;
2313 ASSERT_TRUE(ExtensionDownloadsEventRouter::DetermineFilename(
2314 browser()->profile(),
2315 false,
2316 GetExtensionId(),
2317 result_id,
2318 base::FilePath(),
2319 extensions::api::downloads::FILENAME_CONFLICT_ACTION_UNIQUIFY,
2320 &error));
2321 EXPECT_EQ("", error);
2322
2323 // The download should complete successfully.
2324 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
2325 base::StringPrintf("[{\"id\": %d,"
2326 " \"filename\": {"
2327 " \"previous\": \"\","
2328 " \"current\": \"%s\"}}]",
2329 result_id,
2330 GetFilename("slow.txt").c_str())));
2331 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
2332 base::StringPrintf("[{\"id\": %d,"
2333 " \"state\": {"
2334 " \"previous\": \"in_progress\","
2335 " \"current\": \"complete\"}}]",
2336 result_id)));
2337 }
2338
2339 IN_PROC_BROWSER_TEST_F(
2340 DownloadExtensionTest,
2341 DownloadExtensionTest_OnDeterminingFilename_DangerousOverride) {
2342 GoOnTheRecord();
2343 LoadExtension("downloads_split");
2344 AddFilenameDeterminer();
2345 ASSERT_TRUE(StartEmbeddedTestServer());
2346 ASSERT_TRUE(test_server()->Start());
2347 std::string download_url = test_server()->GetURL("slow?0").spec();
2348
2349 // Start downloading a file.
2350 scoped_ptr<base::Value> result(RunFunctionAndReturnResult(
2351 new DownloadsDownloadFunction(), base::StringPrintf(
2352 "[{\"url\": \"%s\"}]", download_url.c_str())));
2353 ASSERT_TRUE(result.get());
2354 int result_id = -1;
2355 ASSERT_TRUE(result->GetAsInteger(&result_id));
2356 DownloadItem* item = GetCurrentManager()->GetDownload(result_id);
2357 ASSERT_TRUE(item);
2358 ScopedCancellingItem canceller(item);
2359 ASSERT_EQ(download_url, item->GetOriginalUrl().spec());
2360
2361 ASSERT_TRUE(WaitFor(events::kOnDownloadCreated,
2362 base::StringPrintf("[{\"danger\": \"safe\","
2363 " \"incognito\": false,"
2364 " \"id\": %d,"
2365 " \"mime\": \"text/plain\","
2366 " \"paused\": false,"
2367 " \"url\": \"%s\"}]",
2368 result_id,
2369 download_url.c_str())));
2370 ASSERT_TRUE(WaitFor(
2371 events::kOnDownloadDeterminingFilename,
2372 base::StringPrintf("[{\"id\": %d,"
2373 " \"filename\":\"slow.txt\"}]",
2374 result_id)));
2375 ASSERT_TRUE(item->GetTargetFilePath().empty());
2376 ASSERT_EQ(DownloadItem::IN_PROGRESS, item->GetState());
2377
2378 // Respond to the onDeterminingFilename.
2379 std::string error;
2380 ASSERT_TRUE(ExtensionDownloadsEventRouter::DetermineFilename(
2381 browser()->profile(),
2382 false,
2383 GetExtensionId(),
2384 result_id,
2385 base::FilePath(FILE_PATH_LITERAL("overridden.swf")),
2386 extensions::api::downloads::FILENAME_CONFLICT_ACTION_UNIQUIFY,
2387 &error));
2388 EXPECT_EQ("", error);
2389
2390 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
2391 base::StringPrintf("[{\"id\": %d,"
2392 " \"danger\": {"
2393 " \"previous\":\"safe\","
2394 " \"current\":\"file\"},"
2395 " \"dangerAccepted\": {"
2396 " \"current\":false}}]",
2397 result_id)));
2398
2399 item->ValidateDangerousDownload();
2400 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
2401 base::StringPrintf("[{\"id\": %d,"
2402 " \"dangerAccepted\": {"
2403 " \"previous\":false,"
2404 " \"current\":true}}]",
2405 result_id)));
2406 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
2407 base::StringPrintf("[{\"id\": %d,"
2408 " \"state\": {"
2409 " \"previous\": \"in_progress\","
2410 " \"current\": \"complete\"}}]",
2411 result_id)));
2412 EXPECT_EQ(downloads_directory().AppendASCII("overridden.swf"),
2413 item->GetTargetFilePath());
2414 }
2415
2416 IN_PROC_BROWSER_TEST_F(
2417 DownloadExtensionTest,
2418 DownloadExtensionTest_OnDeterminingFilename_ReferencesParentInvalid) {
2419 GoOnTheRecord();
2420 LoadExtension("downloads_split");
2421 AddFilenameDeterminer();
2422 ASSERT_TRUE(StartEmbeddedTestServer());
2423 ASSERT_TRUE(test_server()->Start());
2424 std::string download_url = test_server()->GetURL("slow?0").spec();
2425
2426 // Start downloading a file.
2427 scoped_ptr<base::Value> result(RunFunctionAndReturnResult(
2428 new DownloadsDownloadFunction(), base::StringPrintf(
2429 "[{\"url\": \"%s\"}]", download_url.c_str())));
2430 ASSERT_TRUE(result.get());
2431 int result_id = -1;
2432 ASSERT_TRUE(result->GetAsInteger(&result_id));
2433 DownloadItem* item = GetCurrentManager()->GetDownload(result_id);
2434 ASSERT_TRUE(item);
2435 ScopedCancellingItem canceller(item);
2436 ASSERT_EQ(download_url, item->GetOriginalUrl().spec());
2437
2438 ASSERT_TRUE(WaitFor(events::kOnDownloadCreated,
2439 base::StringPrintf("[{\"danger\": \"safe\","
2440 " \"incognito\": false,"
2441 " \"id\": %d,"
2442 " \"mime\": \"text/plain\","
2443 " \"paused\": false,"
2444 " \"url\": \"%s\"}]",
2445 result_id,
2446 download_url.c_str())));
2447 ASSERT_TRUE(WaitFor(
2448 events::kOnDownloadDeterminingFilename,
2449 base::StringPrintf("[{\"id\": %d,"
2450 " \"filename\":\"slow.txt\"}]",
2451 result_id)));
2452 ASSERT_TRUE(item->GetTargetFilePath().empty());
2453 ASSERT_EQ(DownloadItem::IN_PROGRESS, item->GetState());
2454
2455 // Respond to the onDeterminingFilename.
2456 std::string error;
2457 ASSERT_FALSE(ExtensionDownloadsEventRouter::DetermineFilename(
2458 browser()->profile(),
2459 false,
2460 GetExtensionId(),
2461 result_id,
2462 base::FilePath(FILE_PATH_LITERAL("sneaky/../../sneaky.txt")),
2463 extensions::api::downloads::FILENAME_CONFLICT_ACTION_UNIQUIFY,
2464 &error));
2465 EXPECT_STREQ(download_extension_errors::kInvalidFilenameError, error.c_str());
2466 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
2467 base::StringPrintf("[{\"id\": %d,"
2468 " \"filename\": {"
2469 " \"previous\": \"\","
2470 " \"current\": \"%s\"}}]",
2471 result_id,
2472 GetFilename("slow.txt").c_str())));
2473 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
2474 base::StringPrintf("[{\"id\": %d,"
2475 " \"state\": {"
2476 " \"previous\": \"in_progress\","
2477 " \"current\": \"complete\"}}]",
2478 result_id)));
2479 }
2480
2481 IN_PROC_BROWSER_TEST_F(
2482 DownloadExtensionTest,
2483 DownloadExtensionTest_OnDeterminingFilename_IllegalFilename) {
2484 GoOnTheRecord();
2485 LoadExtension("downloads_split");
2486 AddFilenameDeterminer();
2487 ASSERT_TRUE(StartEmbeddedTestServer());
2488 ASSERT_TRUE(test_server()->Start());
2489 std::string download_url = test_server()->GetURL("slow?0").spec();
2490
2491 // Start downloading a file.
2492 scoped_ptr<base::Value> result(RunFunctionAndReturnResult(
2493 new DownloadsDownloadFunction(), base::StringPrintf(
2494 "[{\"url\": \"%s\"}]", download_url.c_str())));
2495 ASSERT_TRUE(result.get());
2496 int result_id = -1;
2497 ASSERT_TRUE(result->GetAsInteger(&result_id));
2498 DownloadItem* item = GetCurrentManager()->GetDownload(result_id);
2499 ASSERT_TRUE(item);
2500 ScopedCancellingItem canceller(item);
2501 ASSERT_EQ(download_url, item->GetOriginalUrl().spec());
2502
2503 ASSERT_TRUE(WaitFor(events::kOnDownloadCreated,
2504 base::StringPrintf("[{\"danger\": \"safe\","
2505 " \"incognito\": false,"
2506 " \"id\": %d,"
2507 " \"mime\": \"text/plain\","
2508 " \"paused\": false,"
2509 " \"url\": \"%s\"}]",
2510 result_id,
2511 download_url.c_str())));
2512 ASSERT_TRUE(WaitFor(
2513 events::kOnDownloadDeterminingFilename,
2514 base::StringPrintf("[{\"id\": %d,"
2515 " \"filename\":\"slow.txt\"}]",
2516 result_id)));
2517 ASSERT_TRUE(item->GetTargetFilePath().empty());
2518 ASSERT_EQ(DownloadItem::IN_PROGRESS, item->GetState());
2519
2520 // Respond to the onDeterminingFilename.
2521 std::string error;
2522 ASSERT_FALSE(ExtensionDownloadsEventRouter::DetermineFilename(
2523 browser()->profile(),
2524 false,
2525 GetExtensionId(),
2526 result_id,
2527 base::FilePath(FILE_PATH_LITERAL("<")),
2528 extensions::api::downloads::FILENAME_CONFLICT_ACTION_UNIQUIFY,
2529 &error));
2530 EXPECT_STREQ(download_extension_errors::kInvalidFilenameError, error.c_str());
2531 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged, base::StringPrintf(
2532 "[{\"id\": %d,"
2533 " \"filename\": {"
2534 " \"previous\": \"\","
2535 " \"current\": \"%s\"}}]",
2536 result_id,
2537 GetFilename("slow.txt").c_str())));
2538 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged, base::StringPrintf(
2539 "[{\"id\": %d,"
2540 " \"state\": {"
2541 " \"previous\": \"in_progress\","
2542 " \"current\": \"complete\"}}]",
2543 result_id)));
2544 }
2545
2546 IN_PROC_BROWSER_TEST_F(
2547 DownloadExtensionTest,
2548 DownloadExtensionTest_OnDeterminingFilename_IllegalFilenameExtension) {
2549 GoOnTheRecord();
2550 LoadExtension("downloads_split");
2551 AddFilenameDeterminer();
2552 ASSERT_TRUE(StartEmbeddedTestServer());
2553 ASSERT_TRUE(test_server()->Start());
2554 std::string download_url = test_server()->GetURL("slow?0").spec();
2555
2556 // Start downloading a file.
2557 scoped_ptr<base::Value> result(RunFunctionAndReturnResult(
2558 new DownloadsDownloadFunction(), base::StringPrintf(
2559 "[{\"url\": \"%s\"}]", download_url.c_str())));
2560 ASSERT_TRUE(result.get());
2561 int result_id = -1;
2562 ASSERT_TRUE(result->GetAsInteger(&result_id));
2563 DownloadItem* item = GetCurrentManager()->GetDownload(result_id);
2564 ASSERT_TRUE(item);
2565 ScopedCancellingItem canceller(item);
2566 ASSERT_EQ(download_url, item->GetOriginalUrl().spec());
2567
2568 ASSERT_TRUE(WaitFor(events::kOnDownloadCreated,
2569 base::StringPrintf("[{\"danger\": \"safe\","
2570 " \"incognito\": false,"
2571 " \"id\": %d,"
2572 " \"mime\": \"text/plain\","
2573 " \"paused\": false,"
2574 " \"url\": \"%s\"}]",
2575 result_id,
2576 download_url.c_str())));
2577 ASSERT_TRUE(WaitFor(
2578 events::kOnDownloadDeterminingFilename,
2579 base::StringPrintf("[{\"id\": %d,"
2580 " \"filename\":\"slow.txt\"}]",
2581 result_id)));
2582 ASSERT_TRUE(item->GetTargetFilePath().empty());
2583 ASSERT_EQ(DownloadItem::IN_PROGRESS, item->GetState());
2584
2585 // Respond to the onDeterminingFilename.
2586 std::string error;
2587 ASSERT_FALSE(ExtensionDownloadsEventRouter::DetermineFilename(
2588 browser()->profile(),
2589 false,
2590 GetExtensionId(),
2591 result_id,
2592 base::FilePath(FILE_PATH_LITERAL(
2593 "My Computer.{20D04FE0-3AEA-1069-A2D8-08002B30309D}/foo")),
2594 extensions::api::downloads::FILENAME_CONFLICT_ACTION_UNIQUIFY,
2595 &error));
2596 EXPECT_STREQ(download_extension_errors::kInvalidFilenameError, error.c_str());
2597 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged, base::StringPrintf(
2598 "[{\"id\": %d,"
2599 " \"filename\": {"
2600 " \"previous\": \"\","
2601 " \"current\": \"%s\"}}]",
2602 result_id,
2603 GetFilename("slow.txt").c_str())));
2604 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged, base::StringPrintf(
2605 "[{\"id\": %d,"
2606 " \"state\": {"
2607 " \"previous\": \"in_progress\","
2608 " \"current\": \"complete\"}}]",
2609 result_id)));
2610 }
2611
2612 IN_PROC_BROWSER_TEST_F(
2613 DownloadExtensionTest,
2614 DownloadExtensionTest_OnDeterminingFilename_ReservedFilename) {
2615 GoOnTheRecord();
2616 LoadExtension("downloads_split");
2617 AddFilenameDeterminer();
2618 ASSERT_TRUE(StartEmbeddedTestServer());
2619 ASSERT_TRUE(test_server()->Start());
2620 std::string download_url = test_server()->GetURL("slow?0").spec();
2621
2622 // Start downloading a file.
2623 scoped_ptr<base::Value> result(RunFunctionAndReturnResult(
2624 new DownloadsDownloadFunction(), base::StringPrintf(
2625 "[{\"url\": \"%s\"}]", download_url.c_str())));
2626 ASSERT_TRUE(result.get());
2627 int result_id = -1;
2628 ASSERT_TRUE(result->GetAsInteger(&result_id));
2629 DownloadItem* item = GetCurrentManager()->GetDownload(result_id);
2630 ASSERT_TRUE(item);
2631 ScopedCancellingItem canceller(item);
2632 ASSERT_EQ(download_url, item->GetOriginalUrl().spec());
2633
2634 ASSERT_TRUE(WaitFor(events::kOnDownloadCreated,
2635 base::StringPrintf("[{\"danger\": \"safe\","
2636 " \"incognito\": false,"
2637 " \"id\": %d,"
2638 " \"mime\": \"text/plain\","
2639 " \"paused\": false,"
2640 " \"url\": \"%s\"}]",
2641 result_id,
2642 download_url.c_str())));
2643 ASSERT_TRUE(WaitFor(
2644 events::kOnDownloadDeterminingFilename,
2645 base::StringPrintf("[{\"id\": %d,"
2646 " \"filename\":\"slow.txt\"}]",
2647 result_id)));
2648 ASSERT_TRUE(item->GetTargetFilePath().empty());
2649 ASSERT_EQ(DownloadItem::IN_PROGRESS, item->GetState());
2650
2651 // Respond to the onDeterminingFilename.
2652 std::string error;
2653 ASSERT_FALSE(ExtensionDownloadsEventRouter::DetermineFilename(
2654 browser()->profile(),
2655 false,
2656 GetExtensionId(),
2657 result_id,
2658 base::FilePath(FILE_PATH_LITERAL("con.foo")),
2659 extensions::api::downloads::FILENAME_CONFLICT_ACTION_UNIQUIFY,
2660 &error));
2661 EXPECT_STREQ(download_extension_errors::kInvalidFilenameError, error.c_str());
2662 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged, base::StringPrintf(
2663 "[{\"id\": %d,"
2664 " \"filename\": {"
2665 " \"previous\": \"\","
2666 " \"current\": \"%s\"}}]",
2667 result_id,
2668 GetFilename("slow.txt").c_str())));
2669 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged, base::StringPrintf(
2670 "[{\"id\": %d,"
2671 " \"state\": {"
2672 " \"previous\": \"in_progress\","
2673 " \"current\": \"complete\"}}]",
2674 result_id)));
2675 }
2676
2677 IN_PROC_BROWSER_TEST_F(
2678 DownloadExtensionTest,
2679 DownloadExtensionTest_OnDeterminingFilename_CurDirInvalid) {
2680 GoOnTheRecord();
2681 LoadExtension("downloads_split");
2682 AddFilenameDeterminer();
2683 ASSERT_TRUE(StartEmbeddedTestServer());
2684 ASSERT_TRUE(test_server()->Start());
2685 std::string download_url = test_server()->GetURL("slow?0").spec();
2686
2687 // Start downloading a file.
2688 scoped_ptr<base::Value> result(RunFunctionAndReturnResult(
2689 new DownloadsDownloadFunction(), base::StringPrintf(
2690 "[{\"url\": \"%s\"}]", download_url.c_str())));
2691 ASSERT_TRUE(result.get());
2692 int result_id = -1;
2693 ASSERT_TRUE(result->GetAsInteger(&result_id));
2694 DownloadItem* item = GetCurrentManager()->GetDownload(result_id);
2695 ASSERT_TRUE(item);
2696 ScopedCancellingItem canceller(item);
2697 ASSERT_EQ(download_url, item->GetOriginalUrl().spec());
2698
2699 ASSERT_TRUE(WaitFor(events::kOnDownloadCreated,
2700 base::StringPrintf("[{\"danger\": \"safe\","
2701 " \"incognito\": false,"
2702 " \"id\": %d,"
2703 " \"mime\": \"text/plain\","
2704 " \"paused\": false,"
2705 " \"url\": \"%s\"}]",
2706 result_id,
2707 download_url.c_str())));
2708 ASSERT_TRUE(WaitFor(
2709 events::kOnDownloadDeterminingFilename,
2710 base::StringPrintf("[{\"id\": %d,"
2711 " \"filename\":\"slow.txt\"}]",
2712 result_id)));
2713 ASSERT_TRUE(item->GetTargetFilePath().empty());
2714 ASSERT_EQ(DownloadItem::IN_PROGRESS, item->GetState());
2715
2716 // Respond to the onDeterminingFilename.
2717 std::string error;
2718 ASSERT_FALSE(ExtensionDownloadsEventRouter::DetermineFilename(
2719 browser()->profile(),
2720 false,
2721 GetExtensionId(),
2722 result_id,
2723 base::FilePath(FILE_PATH_LITERAL(".")),
2724 extensions::api::downloads::FILENAME_CONFLICT_ACTION_UNIQUIFY,
2725 &error));
2726 EXPECT_STREQ(download_extension_errors::kInvalidFilenameError, error.c_str());
2727 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
2728 base::StringPrintf("[{\"id\": %d,"
2729 " \"filename\": {"
2730 " \"previous\": \"\","
2731 " \"current\": \"%s\"}}]",
2732 result_id,
2733 GetFilename("slow.txt").c_str())));
2734 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
2735 base::StringPrintf("[{\"id\": %d,"
2736 " \"state\": {"
2737 " \"previous\": \"in_progress\","
2738 " \"current\": \"complete\"}}]",
2739 result_id)));
2740 }
2741
2742 IN_PROC_BROWSER_TEST_F(
2743 DownloadExtensionTest,
2744 DownloadExtensionTest_OnDeterminingFilename_ParentDirInvalid) {
2745 ASSERT_TRUE(StartEmbeddedTestServer());
2746 ASSERT_TRUE(test_server()->Start());
2747 GoOnTheRecord();
2748 LoadExtension("downloads_split");
2749 AddFilenameDeterminer();
2750 std::string download_url = test_server()->GetURL("slow?0").spec();
2751
2752 // Start downloading a file.
2753 scoped_ptr<base::Value> result(RunFunctionAndReturnResult(
2754 new DownloadsDownloadFunction(), base::StringPrintf(
2755 "[{\"url\": \"%s\"}]", download_url.c_str())));
2756 ASSERT_TRUE(result.get());
2757 int result_id = -1;
2758 ASSERT_TRUE(result->GetAsInteger(&result_id));
2759 DownloadItem* item = GetCurrentManager()->GetDownload(result_id);
2760 ASSERT_TRUE(item);
2761 ScopedCancellingItem canceller(item);
2762 ASSERT_EQ(download_url, item->GetOriginalUrl().spec());
2763
2764 ASSERT_TRUE(WaitFor(events::kOnDownloadCreated,
2765 base::StringPrintf("[{\"danger\": \"safe\","
2766 " \"incognito\": false,"
2767 " \"id\": %d,"
2768 " \"mime\": \"text/plain\","
2769 " \"paused\": false,"
2770 " \"url\": \"%s\"}]",
2771 result_id,
2772 download_url.c_str())));
2773 ASSERT_TRUE(WaitFor(
2774 events::kOnDownloadDeterminingFilename,
2775 base::StringPrintf("[{\"id\": %d,"
2776 " \"filename\":\"slow.txt\"}]",
2777 result_id)));
2778 ASSERT_TRUE(item->GetTargetFilePath().empty());
2779 ASSERT_EQ(DownloadItem::IN_PROGRESS, item->GetState());
2780
2781 // Respond to the onDeterminingFilename.
2782 std::string error;
2783 ASSERT_FALSE(ExtensionDownloadsEventRouter::DetermineFilename(
2784 browser()->profile(),
2785 false,
2786 GetExtensionId(),
2787 result_id,
2788 base::FilePath(FILE_PATH_LITERAL("..")),
2789 extensions::api::downloads::FILENAME_CONFLICT_ACTION_UNIQUIFY,
2790 &error));
2791 EXPECT_STREQ(download_extension_errors::kInvalidFilenameError, error.c_str());
2792 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
2793 base::StringPrintf("[{\"id\": %d,"
2794 " \"filename\": {"
2795 " \"previous\": \"\","
2796 " \"current\": \"%s\"}}]",
2797 result_id,
2798 GetFilename("slow.txt").c_str())));
2799 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
2800 base::StringPrintf("[{\"id\": %d,"
2801 " \"state\": {"
2802 " \"previous\": \"in_progress\","
2803 " \"current\": \"complete\"}}]",
2804 result_id)));
2805 }
2806
2807 IN_PROC_BROWSER_TEST_F(
2808 DownloadExtensionTest,
2809 DownloadExtensionTest_OnDeterminingFilename_AbsPathInvalid) {
2810 GoOnTheRecord();
2811 LoadExtension("downloads_split");
2812 AddFilenameDeterminer();
2813 ASSERT_TRUE(StartEmbeddedTestServer());
2814 ASSERT_TRUE(test_server()->Start());
2815 std::string download_url = test_server()->GetURL("slow?0").spec();
2816
2817 // Start downloading a file.
2818 scoped_ptr<base::Value> result(RunFunctionAndReturnResult(
2819 new DownloadsDownloadFunction(), base::StringPrintf(
2820 "[{\"url\": \"%s\"}]", download_url.c_str())));
2821 ASSERT_TRUE(result.get());
2822 int result_id = -1;
2823 ASSERT_TRUE(result->GetAsInteger(&result_id));
2824 DownloadItem* item = GetCurrentManager()->GetDownload(result_id);
2825 ASSERT_TRUE(item);
2826 ScopedCancellingItem canceller(item);
2827 ASSERT_EQ(download_url, item->GetOriginalUrl().spec());
2828
2829 ASSERT_TRUE(WaitFor(events::kOnDownloadCreated,
2830 base::StringPrintf("[{\"danger\": \"safe\","
2831 " \"incognito\": false,"
2832 " \"id\": %d,"
2833 " \"mime\": \"text/plain\","
2834 " \"paused\": false,"
2835 " \"url\": \"%s\"}]",
2836 result_id,
2837 download_url.c_str())));
2838 ASSERT_TRUE(WaitFor(
2839 events::kOnDownloadDeterminingFilename,
2840 base::StringPrintf("[{\"id\": %d,"
2841 " \"filename\":\"slow.txt\"}]",
2842 result_id)));
2843 ASSERT_TRUE(item->GetTargetFilePath().empty());
2844 ASSERT_EQ(DownloadItem::IN_PROGRESS, item->GetState());
2845
2846 // Respond to the onDeterminingFilename. Absolute paths should be rejected.
2847 std::string error;
2848 ASSERT_FALSE(ExtensionDownloadsEventRouter::DetermineFilename(
2849 browser()->profile(),
2850 false,
2851 GetExtensionId(),
2852 result_id,
2853 downloads_directory().Append(FILE_PATH_LITERAL("sneaky.txt")),
2854 extensions::api::downloads::FILENAME_CONFLICT_ACTION_UNIQUIFY,
2855 &error));
2856 EXPECT_STREQ(download_extension_errors::kInvalidFilenameError, error.c_str());
2857
2858 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
2859 base::StringPrintf("[{\"id\": %d,"
2860 " \"filename\": {"
2861 " \"previous\": \"\","
2862 " \"current\": \"%s\"}}]",
2863 result_id,
2864 GetFilename("slow.txt").c_str())));
2865 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
2866 base::StringPrintf("[{\"id\": %d,"
2867 " \"state\": {"
2868 " \"previous\": \"in_progress\","
2869 " \"current\": \"complete\"}}]",
2870 result_id)));
2871 }
2872
2873 IN_PROC_BROWSER_TEST_F(
2874 DownloadExtensionTest,
2875 DownloadExtensionTest_OnDeterminingFilename_EmptyBasenameInvalid) {
2876 GoOnTheRecord();
2877 LoadExtension("downloads_split");
2878 AddFilenameDeterminer();
2879 ASSERT_TRUE(StartEmbeddedTestServer());
2880 ASSERT_TRUE(test_server()->Start());
2881 std::string download_url = test_server()->GetURL("slow?0").spec();
2882
2883 // Start downloading a file.
2884 scoped_ptr<base::Value> result(RunFunctionAndReturnResult(
2885 new DownloadsDownloadFunction(), base::StringPrintf(
2886 "[{\"url\": \"%s\"}]", download_url.c_str())));
2887 ASSERT_TRUE(result.get());
2888 int result_id = -1;
2889 ASSERT_TRUE(result->GetAsInteger(&result_id));
2890 DownloadItem* item = GetCurrentManager()->GetDownload(result_id);
2891 ASSERT_TRUE(item);
2892 ScopedCancellingItem canceller(item);
2893 ASSERT_EQ(download_url, item->GetOriginalUrl().spec());
2894
2895 ASSERT_TRUE(WaitFor(events::kOnDownloadCreated,
2896 base::StringPrintf("[{\"danger\": \"safe\","
2897 " \"incognito\": false,"
2898 " \"id\": %d,"
2899 " \"mime\": \"text/plain\","
2900 " \"paused\": false,"
2901 " \"url\": \"%s\"}]",
2902 result_id,
2903 download_url.c_str())));
2904 ASSERT_TRUE(WaitFor(
2905 events::kOnDownloadDeterminingFilename,
2906 base::StringPrintf("[{\"id\": %d,"
2907 " \"filename\":\"slow.txt\"}]",
2908 result_id)));
2909 ASSERT_TRUE(item->GetTargetFilePath().empty());
2910 ASSERT_EQ(DownloadItem::IN_PROGRESS, item->GetState());
2911
2912 // Respond to the onDeterminingFilename. Empty basenames should be rejected.
2913 std::string error;
2914 ASSERT_FALSE(ExtensionDownloadsEventRouter::DetermineFilename(
2915 browser()->profile(),
2916 false,
2917 GetExtensionId(),
2918 result_id,
2919 base::FilePath(FILE_PATH_LITERAL("foo/")),
2920 extensions::api::downloads::FILENAME_CONFLICT_ACTION_UNIQUIFY,
2921 &error));
2922 EXPECT_STREQ(download_extension_errors::kInvalidFilenameError, error.c_str());
2923
2924 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
2925 base::StringPrintf("[{\"id\": %d,"
2926 " \"filename\": {"
2927 " \"previous\": \"\","
2928 " \"current\": \"%s\"}}]",
2929 result_id,
2930 GetFilename("slow.txt").c_str())));
2931 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
2932 base::StringPrintf("[{\"id\": %d,"
2933 " \"state\": {"
2934 " \"previous\": \"in_progress\","
2935 " \"current\": \"complete\"}}]",
2936 result_id)));
2937 }
2938
2939 IN_PROC_BROWSER_TEST_F(
2940 DownloadExtensionTest,
2941 DownloadExtensionTest_OnDeterminingFilename_Override) {
2942 GoOnTheRecord();
2943 LoadExtension("downloads_split");
2944 AddFilenameDeterminer();
2945 ASSERT_TRUE(StartEmbeddedTestServer());
2946 ASSERT_TRUE(test_server()->Start());
2947 std::string download_url = test_server()->GetURL("slow?0").spec();
2948
2949 // Start downloading a file.
2950 scoped_ptr<base::Value> result(RunFunctionAndReturnResult(
2951 new DownloadsDownloadFunction(), base::StringPrintf(
2952 "[{\"url\": \"%s\"}]", download_url.c_str())));
2953 ASSERT_TRUE(result.get());
2954 int result_id = -1;
2955 ASSERT_TRUE(result->GetAsInteger(&result_id));
2956 DownloadItem* item = GetCurrentManager()->GetDownload(result_id);
2957 ASSERT_TRUE(item);
2958 ScopedCancellingItem canceller(item);
2959 ASSERT_EQ(download_url, item->GetOriginalUrl().spec());
2960 ASSERT_TRUE(WaitFor(events::kOnDownloadCreated,
2961 base::StringPrintf("[{\"danger\": \"safe\","
2962 " \"incognito\": false,"
2963 " \"id\": %d,"
2964 " \"mime\": \"text/plain\","
2965 " \"paused\": false,"
2966 " \"url\": \"%s\"}]",
2967 result_id,
2968 download_url.c_str())));
2969 ASSERT_TRUE(WaitFor(
2970 events::kOnDownloadDeterminingFilename,
2971 base::StringPrintf("[{\"id\": %d,"
2972 " \"filename\":\"slow.txt\"}]",
2973 result_id)));
2974 ASSERT_TRUE(item->GetTargetFilePath().empty());
2975 ASSERT_EQ(DownloadItem::IN_PROGRESS, item->GetState());
2976
2977 // Respond to the onDeterminingFilename.
2978 std::string error;
2979 ASSERT_TRUE(ExtensionDownloadsEventRouter::DetermineFilename(
2980 browser()->profile(),
2981 false,
2982 GetExtensionId(),
2983 result_id,
2984 base::FilePath(),
2985 extensions::api::downloads::FILENAME_CONFLICT_ACTION_UNIQUIFY,
2986 &error));
2987 EXPECT_EQ("", error);
2988
2989 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
2990 base::StringPrintf("[{\"id\": %d,"
2991 " \"filename\": {"
2992 " \"previous\": \"\","
2993 " \"current\": \"%s\"}}]",
2994 result_id,
2995 GetFilename("slow.txt").c_str())));
2996 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
2997 base::StringPrintf("[{\"id\": %d,"
2998 " \"state\": {"
2999 " \"previous\": \"in_progress\","
3000 " \"current\": \"complete\"}}]",
3001 result_id)));
3002
3003 // Start downloading a file.
3004 result.reset(RunFunctionAndReturnResult(
3005 new DownloadsDownloadFunction(), base::StringPrintf(
3006 "[{\"url\": \"%s\"}]", download_url.c_str())));
3007 ASSERT_TRUE(result.get());
3008 result_id = -1;
3009 ASSERT_TRUE(result->GetAsInteger(&result_id));
3010 item = GetCurrentManager()->GetDownload(result_id);
3011 ASSERT_TRUE(item);
3012 ScopedCancellingItem canceller2(item);
3013 ASSERT_EQ(download_url, item->GetOriginalUrl().spec());
3014
3015 ASSERT_TRUE(WaitFor(events::kOnDownloadCreated,
3016 base::StringPrintf("[{\"danger\": \"safe\","
3017 " \"incognito\": false,"
3018 " \"id\": %d,"
3019 " \"mime\": \"text/plain\","
3020 " \"paused\": false,"
3021 " \"url\": \"%s\"}]",
3022 result_id,
3023 download_url.c_str())));
3024 ASSERT_TRUE(WaitFor(
3025 events::kOnDownloadDeterminingFilename,
3026 base::StringPrintf("[{\"id\": %d,"
3027 " \"filename\":\"slow.txt\"}]",
3028 result_id)));
3029 ASSERT_TRUE(item->GetTargetFilePath().empty());
3030 ASSERT_EQ(DownloadItem::IN_PROGRESS, item->GetState());
3031
3032 // Respond to the onDeterminingFilename.
3033 // Also test that DetermineFilename allows (chrome) extensions to set
3034 // filenames without (filename) extensions. (Don't ask about v8 extensions or
3035 // python extensions or kernel extensions or firefox extensions...)
3036 error = "";
3037 ASSERT_TRUE(ExtensionDownloadsEventRouter::DetermineFilename(
3038 browser()->profile(),
3039 false,
3040 GetExtensionId(),
3041 result_id,
3042 base::FilePath(FILE_PATH_LITERAL("foo")),
3043 extensions::api::downloads::FILENAME_CONFLICT_ACTION_OVERWRITE,
3044 &error));
3045 EXPECT_EQ("", error);
3046
3047 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
3048 base::StringPrintf("[{\"id\": %d,"
3049 " \"filename\": {"
3050 " \"previous\": \"\","
3051 " \"current\": \"%s\"}}]",
3052 result_id,
3053 GetFilename("foo").c_str())));
3054 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
3055 base::StringPrintf("[{\"id\": %d,"
3056 " \"state\": {"
3057 " \"previous\": \"in_progress\","
3058 " \"current\": \"complete\"}}]",
3059 result_id)));
3060 }
3061
3062 // TODO test precedence rules: install_time
3063
3064 IN_PROC_BROWSER_TEST_F(
3065 DownloadExtensionTest,
3066 DownloadExtensionTest_OnDeterminingFilename_RemoveFilenameDeterminer) {
3067 ASSERT_TRUE(StartEmbeddedTestServer());
3068 ASSERT_TRUE(test_server()->Start());
3069 GoOnTheRecord();
3070 LoadExtension("downloads_split");
3071 content::RenderProcessHost* host = AddFilenameDeterminer();
3072 std::string download_url = test_server()->GetURL("slow?0").spec();
3073
3074 // Start downloading a file.
3075 scoped_ptr<base::Value> result(RunFunctionAndReturnResult(
3076 new DownloadsDownloadFunction(), base::StringPrintf(
3077 "[{\"url\": \"%s\"}]", download_url.c_str())));
3078 ASSERT_TRUE(result.get());
3079 int result_id = -1;
3080 ASSERT_TRUE(result->GetAsInteger(&result_id));
3081 DownloadItem* item = GetCurrentManager()->GetDownload(result_id);
3082 ASSERT_TRUE(item);
3083 ScopedCancellingItem canceller(item);
3084 ASSERT_EQ(download_url, item->GetOriginalUrl().spec());
3085
3086 ASSERT_TRUE(WaitFor(events::kOnDownloadCreated,
3087 base::StringPrintf("[{\"danger\": \"safe\","
3088 " \"incognito\": false,"
3089 " \"id\": %d,"
3090 " \"mime\": \"text/plain\","
3091 " \"paused\": false,"
3092 " \"url\": \"%s\"}]",
3093 result_id,
3094 download_url.c_str())));
3095 ASSERT_TRUE(WaitFor(
3096 events::kOnDownloadDeterminingFilename,
3097 base::StringPrintf("[{\"id\": %d,"
3098 " \"filename\":\"slow.txt\"}]",
3099 result_id)));
3100 ASSERT_TRUE(item->GetTargetFilePath().empty());
3101 ASSERT_EQ(DownloadItem::IN_PROGRESS, item->GetState());
3102
3103 // Remove a determiner while waiting for it.
3104 RemoveFilenameDeterminer(host);
3105
3106 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
3107 base::StringPrintf("[{\"id\": %d,"
3108 " \"state\": {"
3109 " \"previous\": \"in_progress\","
3110 " \"current\": \"complete\"}}]",
3111 result_id)));
3112 }
3113
3114 IN_PROC_BROWSER_TEST_F(
3115 DownloadExtensionTest,
3116 DownloadExtensionTest_OnDeterminingFilename_IncognitoSplit) {
3117 LoadExtension("downloads_split");
3118 ASSERT_TRUE(StartEmbeddedTestServer());
3119 ASSERT_TRUE(test_server()->Start());
3120 std::string download_url = test_server()->GetURL("slow?0").spec();
3121
3122 GoOnTheRecord();
3123 AddFilenameDeterminer();
3124
3125 GoOffTheRecord();
3126 AddFilenameDeterminer();
3127
3128 // Start an on-record download.
3129 GoOnTheRecord();
3130 scoped_ptr<base::Value> result(RunFunctionAndReturnResult(
3131 new DownloadsDownloadFunction(), base::StringPrintf(
3132 "[{\"url\": \"%s\"}]", download_url.c_str())));
3133 ASSERT_TRUE(result.get());
3134 int result_id = -1;
3135 ASSERT_TRUE(result->GetAsInteger(&result_id));
3136 DownloadItem* item = GetCurrentManager()->GetDownload(result_id);
3137 ASSERT_TRUE(item);
3138 ScopedCancellingItem canceller(item);
3139 ASSERT_EQ(download_url, item->GetOriginalUrl().spec());
3140
3141 // Wait for the onCreated and onDeterminingFilename events.
3142 ASSERT_TRUE(WaitFor(events::kOnDownloadCreated,
3143 base::StringPrintf("[{\"danger\": \"safe\","
3144 " \"incognito\": false,"
3145 " \"id\": %d,"
3146 " \"mime\": \"text/plain\","
3147 " \"paused\": false,"
3148 " \"url\": \"%s\"}]",
3149 result_id,
3150 download_url.c_str())));
3151 ASSERT_TRUE(WaitFor(
3152 events::kOnDownloadDeterminingFilename,
3153 base::StringPrintf("[{\"id\": %d,"
3154 " \"incognito\": false,"
3155 " \"filename\":\"slow.txt\"}]",
3156 result_id)));
3157 ASSERT_TRUE(item->GetTargetFilePath().empty());
3158 ASSERT_EQ(DownloadItem::IN_PROGRESS, item->GetState());
3159
3160 // Respond to the onDeterminingFilename events.
3161 std::string error;
3162 ASSERT_TRUE(ExtensionDownloadsEventRouter::DetermineFilename(
3163 current_browser()->profile(),
3164 false,
3165 GetExtensionId(),
3166 result_id,
3167 base::FilePath(FILE_PATH_LITERAL("42.txt")),
3168 extensions::api::downloads::FILENAME_CONFLICT_ACTION_UNIQUIFY,
3169 &error));
3170 EXPECT_EQ("", error);
3171
3172 // The download should complete successfully.
3173 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
3174 base::StringPrintf("[{\"id\": %d,"
3175 " \"filename\": {"
3176 " \"previous\": \"\","
3177 " \"current\": \"%s\"}}]",
3178 result_id,
3179 GetFilename("42.txt").c_str())));
3180 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
3181 base::StringPrintf("[{\"id\": %d,"
3182 " \"state\": {"
3183 " \"previous\": \"in_progress\","
3184 " \"current\": \"complete\"}}]",
3185 result_id)));
3186
3187 // Start an incognito download for comparison.
3188 GoOffTheRecord();
3189 result.reset(RunFunctionAndReturnResult(
3190 new DownloadsDownloadFunction(), base::StringPrintf(
3191 "[{\"url\": \"%s\"}]", download_url.c_str())));
3192 ASSERT_TRUE(result.get());
3193 result_id = -1;
3194 ASSERT_TRUE(result->GetAsInteger(&result_id));
3195 item = GetCurrentManager()->GetDownload(result_id);
3196 ASSERT_TRUE(item);
3197 ScopedCancellingItem canceller2(item);
3198 ASSERT_EQ(download_url, item->GetOriginalUrl().spec());
3199
3200 ASSERT_TRUE(WaitFor(events::kOnDownloadCreated,
3201 base::StringPrintf("[{\"danger\": \"safe\","
3202 " \"incognito\": true,"
3203 " \"id\": %d,"
3204 " \"mime\": \"text/plain\","
3205 " \"paused\": false,"
3206 " \"url\": \"%s\"}]",
3207 result_id,
3208 download_url.c_str())));
3209 // On-Record renderers should not see events for off-record items.
3210 ASSERT_TRUE(WaitFor(
3211 events::kOnDownloadDeterminingFilename,
3212 base::StringPrintf("[{\"id\": %d,"
3213 " \"incognito\": true,"
3214 " \"filename\":\"slow.txt\"}]",
3215 result_id)));
3216 ASSERT_TRUE(item->GetTargetFilePath().empty());
3217 ASSERT_EQ(DownloadItem::IN_PROGRESS, item->GetState());
3218
3219 // Respond to the onDeterminingFilename.
3220 error = "";
3221 ASSERT_TRUE(ExtensionDownloadsEventRouter::DetermineFilename(
3222 current_browser()->profile(),
3223 false,
3224 GetExtensionId(),
3225 result_id,
3226 base::FilePath(FILE_PATH_LITERAL("5.txt")),
3227 extensions::api::downloads::FILENAME_CONFLICT_ACTION_UNIQUIFY,
3228 &error));
3229 EXPECT_EQ("", error);
3230
3231 // The download should complete successfully.
3232 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
3233 base::StringPrintf("[{\"id\": %d,"
3234 " \"filename\": {"
3235 " \"previous\": \"\","
3236 " \"current\": \"%s\"}}]",
3237 result_id,
3238 GetFilename("5.txt").c_str())));
3239 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
3240 base::StringPrintf("[{\"id\": %d,"
3241 " \"state\": {"
3242 " \"previous\": \"in_progress\","
3243 " \"current\": \"complete\"}}]",
3244 result_id)));
3245 }
3246
3247 IN_PROC_BROWSER_TEST_F(
3248 DownloadExtensionTest,
3249 DownloadExtensionTest_OnDeterminingFilename_IncognitoSpanning) {
3250 LoadExtension("downloads_spanning");
3251 ASSERT_TRUE(StartEmbeddedTestServer());
3252 ASSERT_TRUE(test_server()->Start());
3253 std::string download_url = test_server()->GetURL("slow?0").spec();
3254
3255 GoOnTheRecord();
3256 AddFilenameDeterminer();
3257
3258 // There is a single extension renderer that sees both on-record and
3259 // off-record events. The extension functions see the on-record profile with
3260 // include_incognito=true.
3261
3262 // Start an on-record download.
3263 GoOnTheRecord();
3264 scoped_ptr<base::Value> result(RunFunctionAndReturnResult(
3265 new DownloadsDownloadFunction(), base::StringPrintf(
3266 "[{\"url\": \"%s\"}]", download_url.c_str())));
3267 ASSERT_TRUE(result.get());
3268 int result_id = -1;
3269 ASSERT_TRUE(result->GetAsInteger(&result_id));
3270 DownloadItem* item = GetCurrentManager()->GetDownload(result_id);
3271 ASSERT_TRUE(item);
3272 ScopedCancellingItem canceller(item);
3273 ASSERT_EQ(download_url, item->GetOriginalUrl().spec());
3274
3275 // Wait for the onCreated and onDeterminingFilename events.
3276 ASSERT_TRUE(WaitFor(events::kOnDownloadCreated,
3277 base::StringPrintf("[{\"danger\": \"safe\","
3278 " \"incognito\": false,"
3279 " \"id\": %d,"
3280 " \"mime\": \"text/plain\","
3281 " \"paused\": false,"
3282 " \"url\": \"%s\"}]",
3283 result_id,
3284 download_url.c_str())));
3285 ASSERT_TRUE(WaitFor(
3286 events::kOnDownloadDeterminingFilename,
3287 base::StringPrintf("[{\"id\": %d,"
3288 " \"incognito\": false,"
3289 " \"filename\":\"slow.txt\"}]",
3290 result_id)));
3291 ASSERT_TRUE(item->GetTargetFilePath().empty());
3292 ASSERT_EQ(DownloadItem::IN_PROGRESS, item->GetState());
3293
3294 // Respond to the onDeterminingFilename events.
3295 std::string error;
3296 ASSERT_TRUE(ExtensionDownloadsEventRouter::DetermineFilename(
3297 current_browser()->profile(),
3298 true,
3299 GetExtensionId(),
3300 result_id,
3301 base::FilePath(FILE_PATH_LITERAL("42.txt")),
3302 extensions::api::downloads::FILENAME_CONFLICT_ACTION_UNIQUIFY,
3303 &error));
3304 EXPECT_EQ("", error);
3305
3306 // The download should complete successfully.
3307 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
3308 base::StringPrintf("[{\"id\": %d,"
3309 " \"filename\": {"
3310 " \"previous\": \"\","
3311 " \"current\": \"%s\"}}]",
3312 result_id,
3313 GetFilename("42.txt").c_str())));
3314 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
3315 base::StringPrintf("[{\"id\": %d,"
3316 " \"state\": {"
3317 " \"previous\": \"in_progress\","
3318 " \"current\": \"complete\"}}]",
3319 result_id)));
3320
3321 // Start an incognito download for comparison.
3322 GoOffTheRecord();
3323 result.reset(RunFunctionAndReturnResult(
3324 new DownloadsDownloadFunction(), base::StringPrintf(
3325 "[{\"url\": \"%s\"}]", download_url.c_str())));
3326 ASSERT_TRUE(result.get());
3327 result_id = -1;
3328 ASSERT_TRUE(result->GetAsInteger(&result_id));
3329 item = GetCurrentManager()->GetDownload(result_id);
3330 ASSERT_TRUE(item);
3331 ScopedCancellingItem canceller2(item);
3332 ASSERT_EQ(download_url, item->GetOriginalUrl().spec());
3333
3334 ASSERT_TRUE(WaitFor(events::kOnDownloadCreated,
3335 base::StringPrintf("[{\"danger\": \"safe\","
3336 " \"incognito\": true,"
3337 " \"id\": %d,"
3338 " \"mime\": \"text/plain\","
3339 " \"paused\": false,"
3340 " \"url\": \"%s\"}]",
3341 result_id,
3342 download_url.c_str())));
3343 ASSERT_TRUE(WaitFor(
3344 events::kOnDownloadDeterminingFilename,
3345 base::StringPrintf("[{\"id\": %d,"
3346 " \"incognito\": true,"
3347 " \"filename\":\"slow.txt\"}]",
3348 result_id)));
3349 ASSERT_TRUE(item->GetTargetFilePath().empty());
3350 ASSERT_EQ(DownloadItem::IN_PROGRESS, item->GetState());
3351
3352 // Respond to the onDeterminingFilename.
3353 error = "";
3354 ASSERT_TRUE(ExtensionDownloadsEventRouter::DetermineFilename(
3355 current_browser()->profile(),
3356 true,
3357 GetExtensionId(),
3358 result_id,
3359 base::FilePath(FILE_PATH_LITERAL("42.txt")),
3360 extensions::api::downloads::FILENAME_CONFLICT_ACTION_UNIQUIFY,
3361 &error));
3362 EXPECT_EQ("", error);
3363
3364 // The download should complete successfully.
3365 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
3366 base::StringPrintf("[{\"id\": %d,"
3367 " \"filename\": {"
3368 " \"previous\": \"\","
3369 " \"current\": \"%s\"}}]",
3370 result_id,
3371 GetFilename("42 (1).txt").c_str())));
3372 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
3373 base::StringPrintf("[{\"id\": %d,"
3374 " \"state\": {"
3375 " \"previous\": \"in_progress\","
3376 " \"current\": \"complete\"}}]",
3377 result_id)));
3378 }
3379
3380 #if defined(OS_WIN)
3381 // This test is very flaky on Win XP and Aura. http://crbug.com/248438
3382 #define MAYBE_DownloadExtensionTest_OnDeterminingFilename_InterruptedResume \
3383 DISABLED_DownloadExtensionTest_OnDeterminingFilename_InterruptedResume
3384 #else
3385 #define MAYBE_DownloadExtensionTest_OnDeterminingFilename_InterruptedResume \
3386 DownloadExtensionTest_OnDeterminingFilename_InterruptedResume
3387 #endif
3388
3389 // Test download interruption while extensions determining filename. Should not
3390 // re-dispatch onDeterminingFilename.
3391 IN_PROC_BROWSER_TEST_F(
3392 DownloadExtensionTest,
3393 MAYBE_DownloadExtensionTest_OnDeterminingFilename_InterruptedResume) {
3394 CommandLine::ForCurrentProcess()->AppendSwitch(
3395 switches::kEnableDownloadResumption);
3396 LoadExtension("downloads_split");
3397 ASSERT_TRUE(StartEmbeddedTestServer());
3398 ASSERT_TRUE(test_server()->Start());
3399 GoOnTheRecord();
3400 content::RenderProcessHost* host = AddFilenameDeterminer();
3401
3402 // Start a download.
3403 DownloadItem* item = NULL;
3404 {
3405 DownloadManager* manager = GetCurrentManager();
3406 scoped_ptr<content::DownloadTestObserver> observer(
3407 new JustInProgressDownloadObserver(manager, 1));
3408 ASSERT_EQ(0, manager->InProgressCount());
3409 // Tabs created just for a download are automatically closed, invalidating
3410 // the download's WebContents. Downloads without WebContents cannot be
3411 // resumed. http://crbug.com/225901
3412 ui_test_utils::NavigateToURLWithDisposition(
3413 current_browser(),
3414 GURL(URLRequestSlowDownloadJob::kUnknownSizeUrl),
3415 CURRENT_TAB,
3416 ui_test_utils::BROWSER_TEST_NONE);
3417 observer->WaitForFinished();
3418 EXPECT_EQ(1u, observer->NumDownloadsSeenInState(DownloadItem::IN_PROGRESS));
3419 DownloadManager::DownloadVector items;
3420 manager->GetAllDownloads(&items);
3421 for (DownloadManager::DownloadVector::iterator iter = items.begin();
3422 iter != items.end(); ++iter) {
3423 if ((*iter)->GetState() == DownloadItem::IN_PROGRESS) {
3424 // There should be only one IN_PROGRESS item.
3425 EXPECT_EQ(NULL, item);
3426 item = *iter;
3427 }
3428 }
3429 ASSERT_TRUE(item);
3430 }
3431 ScopedCancellingItem canceller(item);
3432
3433 // Wait for the onCreated and onDeterminingFilename event.
3434 ASSERT_TRUE(WaitFor(events::kOnDownloadCreated,
3435 base::StringPrintf("[{\"danger\": \"safe\","
3436 " \"incognito\": false,"
3437 " \"id\": %d,"
3438 " \"mime\": \"application/octet-stream\","
3439 " \"paused\": false}]",
3440 item->GetId())));
3441 ASSERT_TRUE(WaitFor(
3442 events::kOnDownloadDeterminingFilename,
3443 base::StringPrintf("[{\"id\": %d,"
3444 " \"incognito\": false,"
3445 " \"filename\":\"download-unknown-size\"}]",
3446 item->GetId())));
3447 ASSERT_TRUE(item->GetTargetFilePath().empty());
3448 ASSERT_EQ(DownloadItem::IN_PROGRESS, item->GetState());
3449
3450 ClearEvents();
3451 ui_test_utils::NavigateToURLWithDisposition(
3452 current_browser(),
3453 GURL(URLRequestSlowDownloadJob::kErrorDownloadUrl),
3454 NEW_BACKGROUND_TAB,
3455 ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
3456
3457 // Errors caught before filename determination are delayed until after
3458 // filename determination.
3459 std::string error;
3460 ASSERT_TRUE(ExtensionDownloadsEventRouter::DetermineFilename(
3461 current_browser()->profile(),
3462 false,
3463 GetExtensionId(),
3464 item->GetId(),
3465 base::FilePath(FILE_PATH_LITERAL("42.txt")),
3466 extensions::api::downloads::FILENAME_CONFLICT_ACTION_UNIQUIFY,
3467 &error)) << error;
3468 EXPECT_EQ("", error);
3469 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
3470 base::StringPrintf("[{\"id\": %d,"
3471 " \"filename\": {"
3472 " \"previous\": \"\","
3473 " \"current\": \"%s\"}}]",
3474 item->GetId(),
3475 GetFilename("42.txt").c_str())));
3476
3477 content::DownloadUpdatedObserver interrupted(item, base::Bind(
3478 ItemIsInterrupted));
3479 ASSERT_TRUE(interrupted.WaitForEvent());
3480 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
3481 base::StringPrintf("[{\"id\": %d,"
3482 " \"error\":{\"current\":20},"
3483 " \"state\":{"
3484 " \"previous\":\"in_progress\","
3485 " \"current\":\"interrupted\"}}]",
3486 item->GetId())));
3487
3488 ClearEvents();
3489 // Downloads that are restarted on resumption trigger another download target
3490 // determination.
3491 RemoveFilenameDeterminer(host);
3492 item->Resume();
3493
3494 // Errors caught before filename determination is complete are delayed until
3495 // after filename determination so that, on resumption, filename determination
3496 // does not need to be re-done. So, there will not be a second
3497 // onDeterminingFilename event.
3498
3499 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
3500 base::StringPrintf("[{\"id\": %d,"
3501 " \"error\":{\"previous\":20},"
3502 " \"state\":{"
3503 " \"previous\":\"interrupted\","
3504 " \"current\":\"in_progress\"}}]",
3505 item->GetId())));
3506
3507 ClearEvents();
3508 FinishPendingSlowDownloads();
3509
3510 // The download should complete successfully.
3511 ASSERT_TRUE(WaitFor(events::kOnDownloadChanged,
3512 base::StringPrintf("[{\"id\": %d,"
3513 " \"state\": {"
3514 " \"previous\": \"in_progress\","
3515 " \"current\": \"complete\"}}]",
3516 item->GetId())));
3517 }
3518
3519 // TODO(benjhayden) Figure out why DisableExtension() does not fire
3520 // OnListenerRemoved.
3521
3522 // TODO(benjhayden) Test that the shelf is shown for download() both with and
3523 // without a WebContents.
3524
3525 class DownloadsApiTest : public ExtensionApiTest {
3526 public:
3527 DownloadsApiTest() {}
3528 virtual ~DownloadsApiTest() {}
3529 private:
3530 DISALLOW_COPY_AND_ASSIGN(DownloadsApiTest);
3531 };
3532
3533
3534 IN_PROC_BROWSER_TEST_F(DownloadsApiTest, DownloadsApiTest) {
3535 ASSERT_TRUE(RunExtensionTest("downloads")) << message_;
3536 }
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698