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

Side by Side Diff: chrome/browser/chromeos/extensions/file_browser_resource_throttle_browsertest.cc

Issue 12381035: Move Mime type handling to streamsPrivate API, so that it works on Desktop Chrome. (Closed) Base URL: http://git.chromium.org/chromium/src.git@master
Patch Set: Initialize test variable Created 7 years, 9 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
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 "base/message_loop.h"
6 #include "base/prefs/pref_service.h"
7 #include "chrome/browser/chromeos/extensions/file_browser_handler.h"
8 #include "chrome/browser/chromeos/extensions/file_browser_resource_throttle.h"
9 #include "chrome/browser/download/download_prefs.h"
10 #include "chrome/browser/extensions/event_router.h"
11 #include "chrome/browser/extensions/extension_apitest.h"
12 #include "chrome/browser/extensions/extension_info_map.h"
13 #include "chrome/browser/extensions/extension_system.h"
14 #include "chrome/browser/google_apis/test_server/http_request.h"
15 #include "chrome/browser/google_apis/test_server/http_response.h"
16 #include "chrome/browser/google_apis/test_server/http_server.h"
17 #include "chrome/browser/profiles/profile.h"
18 #include "chrome/browser/ui/browser.h"
19 #include "chrome/browser/ui/tabs/tab_strip_model.h"
20 #include "chrome/common/pref_names.cc"
21 #include "chrome/test/base/ui_test_utils.h"
22 #include "content/public/browser/download_item.h"
23 #include "content/public/browser/download_manager.h"
24 #include "content/public/browser/render_process_host.h"
25 #include "content/public/browser/resource_controller.h"
26 #include "content/public/browser/web_contents.h"
27 #include "content/public/test/download_test_observer.h"
28 #include "testing/gmock/include/gmock/gmock.h"
29
30 using content::BrowserContext;
31 using content::BrowserThread;
32 using content::DownloadItem;
33 using content::DownloadManager;
34 using content::DownloadUrlParameters;
35 using content::ResourceController;
36 using content::WebContents;
37 using extensions::Event;
38 using extensions::ExtensionSystem;
39 using google_apis::test_server::HttpRequest;
40 using google_apis::test_server::HttpResponse;
41 using google_apis::test_server::HttpServer;
42 using testing::_;
43
44 namespace {
45
46 // Used in FileBrowserResourceThrottleExtensionApiTest.Basic test to mock the
47 // resource controller bound to the test resource throttle.
48 class MockResourceController : public ResourceController {
49 public:
50 virtual ~MockResourceController() {}
51 MOCK_METHOD0(Cancel, void());
52 MOCK_METHOD0(CancelAndIgnore, void());
53 MOCK_METHOD1(CancelWithError, void(int error_code));
54 MOCK_METHOD0(Resume, void());
55 };
56
57 // Creates and triggers a test FileBrowserResourceThrottle for the listed
58 // request parameters (child and routing id from which the request came,
59 // request's MIME type and URL), with extension info map |info_map| and resource
60 // controller |controller|.
61 // The created resource throttle is started by calling |WillProcessResponse|.
62 // Used in FileBrowserResourceThrottleExtensionApiTest.Basic test.
63 //
64 // Must be called on the IO thread.
65 void CreateAndTriggerThrottle(int child_id,
66 int routing_id,
67 const std::string& mime_type,
68 const GURL& url,
69 bool is_incognito,
70 scoped_refptr<ExtensionInfoMap> info_map,
71 ResourceController* controller) {
72 typedef FileBrowserResourceThrottle::FileBrowserHandlerEventRouter
73 HandlerEventRouter;
74 scoped_ptr<FileBrowserResourceThrottle> throttle(
75 FileBrowserResourceThrottle::CreateForTest(child_id, routing_id,
76 mime_type, url, is_incognito, info_map,
77 scoped_ptr<HandlerEventRouter>()));
78
79 throttle->set_controller_for_testing(controller);
80
81 bool defer;
82 throttle->WillProcessResponse(&defer);
83 EXPECT_FALSE(defer);
84 }
85
86 // Test server's request handler.
87 // Returns response that should be sent by the test server.
88 scoped_ptr<HttpResponse> HandleRequest(const HttpRequest& request) {
89 scoped_ptr<HttpResponse> response(new HttpResponse());
90
91 // For relative path "/doc_path.doc", return success response with MIME type
92 // "application/msword".
93 if (request.relative_url == "/doc_path.doc") {
94 response->set_code(google_apis::test_server::SUCCESS);
95 response->set_content_type("application/msword");
96 return response.Pass();
97 }
98
99 // For relative path "/test_path_attch.txt", return success response with
100 // MIME type "plain/text" and content "txt content". Also, set content
101 // disposition to be attachment.
102 if (request.relative_url == "/text_path_attch.txt") {
103 response->set_code(google_apis::test_server::SUCCESS);
104 response->set_content("txt content");
105 response->set_content_type("plain/text");
106 response->AddCustomHeader("Content-Disposition",
107 "attachment; filename=test_path.txt");
108 return response.Pass();
109 }
110 // For relative path "/test_path_attch.txt", return success response with
111 // MIME type "plain/text" and content "txt content".
112 if (request.relative_url == "/text_path.txt") {
113 response->set_code(google_apis::test_server::SUCCESS);
114 response->set_content("txt content");
115 response->set_content_type("plain/text");
116 return response.Pass();
117 }
118
119 // No other requests should be handled in the tests.
120 EXPECT_TRUE(false) << "NOTREACHED!";
121 response->set_code(google_apis::test_server::NOT_FOUND);
122 return response.Pass();
123 }
124
125 // Tests to verify that resources are correctly intercepted by
126 // FileBrowserResourceThrottle.
127 // The test extension expects the resources that should be handed to the
128 // extension to have MIME type 'application/msword' and the resources that
129 // should be downloaded by the browser to have MIME type 'plain/text'.
130 class FileBrowserResourceThrottleExtensionApiTest : public ExtensionApiTest {
131 public:
132 FileBrowserResourceThrottleExtensionApiTest() {}
133
134 virtual ~FileBrowserResourceThrottleExtensionApiTest() {
135 // Clear the test extension from the white-list.
136 FileBrowserHandler::set_extension_whitelisted_for_test(NULL);
137 }
138
139 virtual void SetUpOnMainThread() OVERRIDE {
140 // Init test server.
141 test_server_.reset(new HttpServer());
142 test_server_->InitializeAndWaitUntilReady();
143 test_server_->RegisterRequestHandler(base::Bind(&HandleRequest));
144
145 ExtensionApiTest::SetUpOnMainThread();
146 }
147
148 virtual void CleanUpOnMainThread() OVERRIDE {
149 // Tear down the test server.
150 test_server_->ShutdownAndWaitUntilComplete();
151 test_server_.reset();
152 ExtensionApiTest::CleanUpOnMainThread();
153 }
154
155 void InitializeDownloadSettings() {
156 ASSERT_TRUE(browser());
157 ASSERT_TRUE(downloads_dir_.CreateUniqueTempDir());
158
159 // Setup default downloads directory to the scoped tmp directory created for
160 // the test.
161 browser()->profile()->GetPrefs()->SetFilePath(
162 prefs::kDownloadDefaultDirectory, downloads_dir_.path());
163 // Ensure there are no prompts for download during the test.
164 browser()->profile()->GetPrefs()->SetBoolean(
165 prefs::kPromptForDownload, false);
166
167 DownloadManager* manager = GetDownloadManager();
168 DownloadPrefs::FromDownloadManager(manager)->ResetAutoOpen();
169 manager->RemoveAllDownloads();
170 }
171
172 // Sends onExecuteContentHandler event with the MIME type "test/done" to the
173 // test extension.
174 // The test extension calls 'chrome.test.notifySuccess' when it receives the
175 // event with the "test/done" MIME type (unless the 'chrome.test.notifyFail'
176 // has already been called).
177 void SendDoneEvent() {
178 scoped_ptr<ListValue> event_args(new ListValue());
179 event_args->Append(new base::StringValue("test/done"));
180 event_args->Append(new base::StringValue("http://foo"));
181
182 scoped_ptr<Event> event(new Event(
183 "fileBrowserHandler.onExecuteContentHandler", event_args.Pass()));
184
185 ExtensionSystem::Get(browser()->profile())->event_router()->
186 DispatchEventToExtension(test_extension_id_, event.Pass());
187 }
188
189 // Loads the test extension and set's up its file_browser_handler to handle
190 // 'application/msword' and 'plain/text' MIME types.
191 // The extension will notify success when it detects an event with the MIME
192 // type 'application/msword' and notify fail when it detects an event with the
193 // MIME type 'plain/text'.
194 const extensions::Extension* LoadTestExtension() {
195 const extensions::Extension* extension = LoadExtension(
196 test_data_dir_.AppendASCII("file_browser/handle_mime_type"));
197 if (!extension)
198 return NULL;
199
200 FileBrowserHandler::List* handlers =
201 FileBrowserHandler::GetHandlers(extension);
202 if (!handlers || handlers->size() == 0u) {
203 message_ = "No file browser handlers defined.";
204 return NULL;
205 }
206
207 test_extension_id_ = extension->id();
208
209 FileBrowserHandler::set_extension_whitelisted_for_test(&test_extension_id_);
210
211 // The MIME type filters cannot be defined directly in the extension's
212 // manifest because the extension installation would fail for the extension
213 // that is not white-listed to handle MIME types with its file browser
214 // handlers.
215 FileBrowserHandler* file_browser_handler = const_cast<FileBrowserHandler*>(
216 handlers->at(0).get());
217 file_browser_handler->AddMIMEType("application/msword");
218 file_browser_handler->AddMIMEType("plain/text");
219
220 return extension;
221 }
222
223 // Returns the download manager for the current browser.
224 DownloadManager* GetDownloadManager() const {
225 DownloadManager* download_manager =
226 BrowserContext::GetDownloadManager(browser()->profile());
227 EXPECT_TRUE(download_manager);
228 return download_manager;
229 }
230
231 // Deletes the download and waits until it's flushed.
232 // The |manager| should have |download| in its list of downloads.
233 void DeleteDownloadAndWaitForFlush(DownloadItem* download,
234 DownloadManager* manager) {
235 scoped_refptr<content::DownloadTestFlushObserver> flush_observer(
236 new content::DownloadTestFlushObserver(manager));
237 download->Delete(DownloadItem::DELETE_DUE_TO_USER_DISCARD);
238 flush_observer->WaitForFlush();
239 }
240
241 protected:
242 std::string test_extension_id_;
243 // The HTTP server used in the tests.
244 scoped_ptr<HttpServer> test_server_;
245 base::ScopedTempDir downloads_dir_;
246 };
247
248 // http://crbug.com/176082: This test flaky on Chrome OS ASAN bots.
249 #if defined(OS_CHROMEOS)
250 #define MAYBE_Basic DISABLED_Basic
251 #else
252 #define MAYBE_Basic Basic
253 #endif
254 // Tests that invoking FileBrowserResourceThrottle with handleable MIME type
255 // actually invokes the fileBrowserHandler.onExecuteContnentHandler event.
256 IN_PROC_BROWSER_TEST_F(FileBrowserResourceThrottleExtensionApiTest,
257 MAYBE_Basic) {
258 ASSERT_TRUE(LoadTestExtension()) << message_;
259
260 ResultCatcher catcher;
261
262 MockResourceController mock_resource_controller;
263 EXPECT_CALL(mock_resource_controller, Cancel()).Times(0);
264 EXPECT_CALL(mock_resource_controller, CancelAndIgnore()).Times(1);
265 EXPECT_CALL(mock_resource_controller, CancelWithError(_)).Times(0);
266 EXPECT_CALL(mock_resource_controller, Resume()).Times(0);
267
268 // Get child and routing id from the current web contents (the real values
269 // should be used so the FileBrowserHandlerEventRouter can correctly extract
270 // profile from them).
271 WebContents* web_contents =
272 browser()->tab_strip_model()->GetActiveWebContents();
273 ASSERT_TRUE(web_contents);
274 int child_id = web_contents->GetRenderProcessHost()->GetID();
275 int routing_id = web_contents->GetRoutingID();
276
277 scoped_refptr<ExtensionInfoMap> info_map =
278 extensions::ExtensionSystem::Get(browser()->profile())->info_map();
279
280 // The resource throttle must be created and invoked on IO thread.
281 BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
282 base::Bind(&CreateAndTriggerThrottle, child_id, routing_id,
283 "application/msword", GURL("http://foo"), false, info_map,
284 &mock_resource_controller));
285
286 // Wait for the test extension to received the onExecuteContentHandler event.
287 EXPECT_TRUE(catcher.GetNextResult());
288 }
289
290 // Tests that navigating to a resource with a MIME type handleable by an
291 // installed, white-listed extension invokes the extension's
292 // onExecuteContentHandler event (and does not start a download).
293 IN_PROC_BROWSER_TEST_F(FileBrowserResourceThrottleExtensionApiTest, Navigate) {
294 ASSERT_TRUE(LoadTestExtension()) << message_;
295
296 ResultCatcher catcher;
297
298 ui_test_utils::NavigateToURL(browser(),
299 test_server_->GetURL("/doc_path.doc"));
300
301 // Wait for the response from the test server.
302 MessageLoop::current()->RunUntilIdle();
303
304 // There should be no downloads started by the navigation.
305 DownloadManager* download_manager = GetDownloadManager();
306 std::vector<DownloadItem*> downloads;
307 download_manager->GetAllDownloads(&downloads);
308 ASSERT_EQ(0u, downloads.size());
309
310 // The test extension should receive onExecuteContentHandler event with MIME
311 // type 'application/msword' (and call chrome.test.notifySuccess).
312 EXPECT_TRUE(catcher.GetNextResult());
313 }
314
315 // Tests that navigation to an attachment starts a download, even if there is an
316 // extension with a file browser handler that can handle the attachment's MIME
317 // type.
318 IN_PROC_BROWSER_TEST_F(FileBrowserResourceThrottleExtensionApiTest,
319 NavigateToAnAttachment) {
320 InitializeDownloadSettings();
321
322 ASSERT_TRUE(LoadTestExtension()) << message_;
323
324 ResultCatcher catcher;
325
326 // The test should start a downloadm.
327 DownloadManager* download_manager = GetDownloadManager();
328 scoped_ptr<content::DownloadTestObserver> download_observer(
329 new content::DownloadTestObserverInProgress(download_manager, 1));
330
331 ui_test_utils::NavigateToURL(browser(),
332 test_server_->GetURL("/text_path_attch.txt"));
333
334 // Wait for the download to start.
335 download_observer->WaitForFinished();
336
337 // There should be one download started by the navigation.
338 DownloadManager::DownloadVector downloads;
339 download_manager->GetAllDownloads(&downloads);
340 ASSERT_EQ(1u, downloads.size());
341
342 // Cancel and delete the download started in the test.
343 DeleteDownloadAndWaitForFlush(downloads[0], download_manager);
344
345 // The test extension should not receive any events by now. Send it an event
346 // with MIME type "test/done", so it stops waiting for the events. (If there
347 // was an event with MIME type 'plain/text', |catcher.GetNextResult()| will
348 // fail regardless of the sent event; chrome.test.notifySuccess will not be
349 // called by the extension).
350 SendDoneEvent();
351 EXPECT_TRUE(catcher.GetNextResult());
352 }
353
354 // Tests that direct download requests don't get intercepted by
355 // FileBrowserResourceThrottle, even if there is an extension with a file
356 // browser handler that can handle the download's MIME type.
357 IN_PROC_BROWSER_TEST_F(FileBrowserResourceThrottleExtensionApiTest,
358 DirectDownload) {
359 InitializeDownloadSettings();
360
361 ASSERT_TRUE(LoadTestExtension()) << message_;
362
363 ResultCatcher catcher;
364
365 DownloadManager* download_manager = GetDownloadManager();
366 scoped_ptr<content::DownloadTestObserver> download_observer(
367 new content::DownloadTestObserverInProgress(download_manager, 1));
368
369 // The resource's URL on the test server.
370 GURL url = test_server_->GetURL("/text_path.txt");
371
372 // The download's target file path.
373 base::FilePath target_path =
374 downloads_dir_.path().Append(FILE_PATH_LITERAL("download_target.txt"));
375
376 // Set the downloads parameters.
377 content::WebContents* web_contents =
378 browser()->tab_strip_model()->GetActiveWebContents();
379 ASSERT_TRUE(web_contents);
380 scoped_ptr<DownloadUrlParameters> params(
381 DownloadUrlParameters::FromWebContents(web_contents, url));
382 params->set_file_path(target_path);
383
384 // Start download of the URL with a path "/text_path.txt" on the test server.
385 download_manager->DownloadUrl(params.Pass());
386
387 // Wait for the download to start.
388 download_observer->WaitForFinished();
389
390 // There should have been one download.
391 std::vector<DownloadItem*> downloads;
392 download_manager->GetAllDownloads(&downloads);
393 ASSERT_EQ(1u, downloads.size());
394
395 // Cancel and delete the download statred in the test.
396 DeleteDownloadAndWaitForFlush(downloads[0], download_manager);
397
398 // The test extension should not receive any events by now. Send it an event
399 // with MIME type "test/done", so it stops waiting for the events. (If there
400 // was an event with MIME type 'plain/text', |catcher.GetNextResult()| will
401 // fail regardless of the sent event; chrome.test.notifySuccess will not be
402 // called by the extension).
403 SendDoneEvent();
404 EXPECT_TRUE(catcher.GetNextResult());
405 }
406
407 } // namespace
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698