Upstream version 9.38.198.0
[platform/framework/web/crosswalk.git] / src / chrome / browser / apps / web_view_browsertest.cc
1 // Copyright 2013 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 "apps/ui/native_app_window.h"
6 #include "base/path_service.h"
7 #include "base/strings/stringprintf.h"
8 #include "base/strings/utf_string_conversions.h"
9 #include "chrome/browser/apps/app_browsertest_util.h"
10 #include "chrome/browser/chrome_content_browser_client.h"
11 #include "chrome/browser/extensions/extension_test_message_listener.h"
12 #include "chrome/browser/prerender/prerender_link_manager.h"
13 #include "chrome/browser/prerender/prerender_link_manager_factory.h"
14 #include "chrome/browser/profiles/profile.h"
15 #include "chrome/browser/renderer_context_menu/render_view_context_menu.h"
16 #include "chrome/browser/renderer_context_menu/render_view_context_menu_test_util.h"
17 #include "chrome/browser/task_manager/task_manager_browsertest_util.h"
18 #include "chrome/browser/ui/browser.h"
19 #include "chrome/browser/ui/browser_dialogs.h"
20 #include "chrome/browser/ui/tabs/tab_strip_model.h"
21 #include "chrome/test/base/ui_test_utils.h"
22 #include "content/public/browser/gpu_data_manager.h"
23 #include "content/public/browser/interstitial_page.h"
24 #include "content/public/browser/interstitial_page_delegate.h"
25 #include "content/public/browser/notification_service.h"
26 #include "content/public/browser/render_process_host.h"
27 #include "content/public/browser/web_contents_delegate.h"
28 #include "content/public/common/content_switches.h"
29 #include "content/public/test/browser_test_utils.h"
30 #include "content/public/test/fake_speech_recognition_manager.h"
31 #include "content/public/test/test_renderer_host.h"
32 #include "extensions/browser/guest_view/guest_view_manager.h"
33 #include "extensions/browser/guest_view/guest_view_manager_factory.h"
34 #include "extensions/common/extension.h"
35 #include "extensions/common/extensions_client.h"
36 #include "media/base/media_switches.h"
37 #include "net/test/embedded_test_server/embedded_test_server.h"
38 #include "net/test/embedded_test_server/http_request.h"
39 #include "net/test/embedded_test_server/http_response.h"
40 #include "ui/gl/gl_switches.h"
41
42 #if defined(OS_CHROMEOS)
43 #include "chrome/browser/chromeos/accessibility/accessibility_manager.h"
44 #include "chrome/browser/chromeos/accessibility/speech_monitor.h"
45 #endif
46
47 // For fine-grained suppression on flaky tests.
48 #if defined(OS_WIN)
49 #include "base/win/windows_version.h"
50 #endif
51
52 using extensions::ContextMenuMatcher;
53 using extensions::MenuItem;
54 using prerender::PrerenderLinkManager;
55 using prerender::PrerenderLinkManagerFactory;
56 using task_manager::browsertest_util::MatchAboutBlankTab;
57 using task_manager::browsertest_util::MatchAnyApp;
58 using task_manager::browsertest_util::MatchAnyBackground;
59 using task_manager::browsertest_util::MatchAnyTab;
60 using task_manager::browsertest_util::MatchAnyWebView;
61 using task_manager::browsertest_util::MatchApp;
62 using task_manager::browsertest_util::MatchBackground;
63 using task_manager::browsertest_util::MatchWebView;
64 using task_manager::browsertest_util::WaitForTaskManagerRows;
65 using ui::MenuModel;
66
67 namespace {
68 const char kEmptyResponsePath[] = "/close-socket";
69 const char kRedirectResponsePath[] = "/server-redirect";
70 const char kRedirectResponseFullPath[] =
71     "/extensions/platform_apps/web_view/shim/guest_redirect.html";
72
73 // Platform-specific filename relative to the chrome executable.
74 #if defined(OS_WIN)
75 const wchar_t library_name[] = L"ppapi_tests.dll";
76 #elif defined(OS_MACOSX)
77 const char library_name[] = "ppapi_tests.plugin";
78 #elif defined(OS_POSIX)
79 const char library_name[] = "libppapi_tests.so";
80 #endif
81
82 class EmptyHttpResponse : public net::test_server::HttpResponse {
83  public:
84   virtual std::string ToResponseString() const OVERRIDE {
85     return std::string();
86   }
87 };
88
89 class TestInterstitialPageDelegate : public content::InterstitialPageDelegate {
90  public:
91   TestInterstitialPageDelegate() {
92   }
93   virtual ~TestInterstitialPageDelegate() {}
94   virtual std::string GetHTMLContents() OVERRIDE { return std::string(); }
95 };
96
97 class TestGuestViewManager : public extensions::GuestViewManager {
98  public:
99   explicit TestGuestViewManager(content::BrowserContext* context) :
100       GuestViewManager(context),
101       web_contents_(NULL) {}
102
103   content::WebContents* WaitForGuestCreated() {
104     if (web_contents_)
105       return web_contents_;
106
107     message_loop_runner_ = new content::MessageLoopRunner;
108     message_loop_runner_->Run();
109     return web_contents_;
110   }
111
112  private:
113   // GuestViewManager override:
114   virtual void AddGuest(int guest_instance_id,
115                         content::WebContents* guest_web_contents) OVERRIDE{
116     extensions::GuestViewManager::AddGuest(
117         guest_instance_id, guest_web_contents);
118     web_contents_ = guest_web_contents;
119
120     if (message_loop_runner_)
121       message_loop_runner_->Quit();
122   }
123
124   content::WebContents* web_contents_;
125   scoped_refptr<content::MessageLoopRunner> message_loop_runner_;
126 };
127
128 // Test factory for creating test instances of GuestViewManager.
129 class TestGuestViewManagerFactory :
130   public extensions::GuestViewManagerFactory {
131  public:
132   TestGuestViewManagerFactory() :
133       test_guest_view_manager_(NULL) {}
134
135   virtual ~TestGuestViewManagerFactory() {}
136
137   virtual extensions::GuestViewManager* CreateGuestViewManager(
138       content::BrowserContext* context) OVERRIDE {
139     return GetManager(context);
140   }
141
142   TestGuestViewManager* GetManager(content::BrowserContext* context) {
143     if (!test_guest_view_manager_) {
144       test_guest_view_manager_ = new TestGuestViewManager(context);
145     }
146     return test_guest_view_manager_;
147   }
148
149  private:
150   TestGuestViewManager* test_guest_view_manager_;
151
152   DISALLOW_COPY_AND_ASSIGN(TestGuestViewManagerFactory);
153 };
154
155 class WebContentsHiddenObserver : public content::WebContentsObserver {
156  public:
157   WebContentsHiddenObserver(content::WebContents* web_contents,
158                             const base::Closure& hidden_callback)
159       : WebContentsObserver(web_contents),
160         hidden_callback_(hidden_callback),
161         hidden_observed_(false) {
162   }
163
164   // WebContentsObserver.
165   virtual void WasHidden() OVERRIDE {
166     hidden_observed_ = true;
167     hidden_callback_.Run();
168   }
169
170   bool hidden_observed() { return hidden_observed_; }
171
172  private:
173   base::Closure hidden_callback_;
174   bool hidden_observed_;
175
176   DISALLOW_COPY_AND_ASSIGN(WebContentsHiddenObserver);
177 };
178
179 class InterstitialObserver : public content::WebContentsObserver {
180  public:
181   InterstitialObserver(content::WebContents* web_contents,
182                        const base::Closure& attach_callback,
183                        const base::Closure& detach_callback)
184       : WebContentsObserver(web_contents),
185         attach_callback_(attach_callback),
186         detach_callback_(detach_callback) {
187   }
188
189   virtual void DidAttachInterstitialPage() OVERRIDE {
190     attach_callback_.Run();
191   }
192
193   virtual void DidDetachInterstitialPage() OVERRIDE {
194     detach_callback_.Run();
195   }
196
197  private:
198   base::Closure attach_callback_;
199   base::Closure detach_callback_;
200
201   DISALLOW_COPY_AND_ASSIGN(InterstitialObserver);
202 };
203
204 void ExecuteScriptWaitForTitle(content::WebContents* web_contents,
205                                const char* script,
206                                const char* title) {
207   base::string16 expected_title(base::ASCIIToUTF16(title));
208   base::string16 error_title(base::ASCIIToUTF16("error"));
209
210   content::TitleWatcher title_watcher(web_contents, expected_title);
211   title_watcher.AlsoWaitForTitle(error_title);
212   EXPECT_TRUE(content::ExecuteScript(web_contents, script));
213   EXPECT_EQ(expected_title, title_watcher.WaitAndGetTitle());
214 }
215
216 }  // namespace
217
218 // This class intercepts media access request from the embedder. The request
219 // should be triggered only if the embedder API (from tests) allows the request
220 // in Javascript.
221 // We do not issue the actual media request; the fact that the request reached
222 // embedder's WebContents is good enough for our tests. This is also to make
223 // the test run successfully on trybots.
224 class MockWebContentsDelegate : public content::WebContentsDelegate {
225  public:
226   MockWebContentsDelegate() : requested_(false) {}
227   virtual ~MockWebContentsDelegate() {}
228
229   virtual void RequestMediaAccessPermission(
230       content::WebContents* web_contents,
231       const content::MediaStreamRequest& request,
232       const content::MediaResponseCallback& callback) OVERRIDE {
233     requested_ = true;
234     if (message_loop_runner_.get())
235       message_loop_runner_->Quit();
236   }
237
238   void WaitForSetMediaPermission() {
239     if (requested_)
240       return;
241     message_loop_runner_ = new content::MessageLoopRunner;
242     message_loop_runner_->Run();
243   }
244
245  private:
246   bool requested_;
247   scoped_refptr<content::MessageLoopRunner> message_loop_runner_;
248
249   DISALLOW_COPY_AND_ASSIGN(MockWebContentsDelegate);
250 };
251
252 // This class intercepts download request from the guest.
253 class MockDownloadWebContentsDelegate : public content::WebContentsDelegate {
254  public:
255   explicit MockDownloadWebContentsDelegate(
256       content::WebContentsDelegate* orig_delegate)
257       : orig_delegate_(orig_delegate),
258         waiting_for_decision_(false),
259         expect_allow_(false),
260         decision_made_(false),
261         last_download_allowed_(false) {}
262   virtual ~MockDownloadWebContentsDelegate() {}
263
264   virtual void CanDownload(
265       content::RenderViewHost* render_view_host,
266       const GURL& url,
267       const std::string& request_method,
268       const base::Callback<void(bool)>& callback) OVERRIDE {
269     orig_delegate_->CanDownload(
270         render_view_host, url, request_method,
271         base::Bind(&MockDownloadWebContentsDelegate::DownloadDecided,
272                    base::Unretained(this)));
273   }
274
275   void WaitForCanDownload(bool expect_allow) {
276     EXPECT_FALSE(waiting_for_decision_);
277     waiting_for_decision_ = true;
278
279     if (decision_made_) {
280       EXPECT_EQ(expect_allow, last_download_allowed_);
281       return;
282     }
283
284     expect_allow_ = expect_allow;
285     message_loop_runner_ = new content::MessageLoopRunner;
286     message_loop_runner_->Run();
287   }
288
289   void DownloadDecided(bool allow) {
290     EXPECT_FALSE(decision_made_);
291     decision_made_ = true;
292
293     if (waiting_for_decision_) {
294       EXPECT_EQ(expect_allow_, allow);
295       if (message_loop_runner_.get())
296         message_loop_runner_->Quit();
297       return;
298     }
299     last_download_allowed_ = allow;
300   }
301
302   void Reset() {
303     waiting_for_decision_ = false;
304     decision_made_ = false;
305   }
306
307  private:
308   content::WebContentsDelegate* orig_delegate_;
309   bool waiting_for_decision_;
310   bool expect_allow_;
311   bool decision_made_;
312   bool last_download_allowed_;
313   scoped_refptr<content::MessageLoopRunner> message_loop_runner_;
314
315   DISALLOW_COPY_AND_ASSIGN(MockDownloadWebContentsDelegate);
316 };
317
318 class WebViewTest : public extensions::PlatformAppBrowserTest {
319  protected:
320   virtual void SetUp() OVERRIDE {
321     if (UsesFakeSpeech()) {
322       // SpeechRecognition test specific SetUp.
323       fake_speech_recognition_manager_.reset(
324           new content::FakeSpeechRecognitionManager());
325       fake_speech_recognition_manager_->set_should_send_fake_response(true);
326       // Inject the fake manager factory so that the test result is returned to
327       // the web page.
328       content::SpeechRecognitionManager::SetManagerForTesting(
329           fake_speech_recognition_manager_.get());
330     }
331     extensions::PlatformAppBrowserTest::SetUp();
332   }
333
334   virtual void TearDown() OVERRIDE {
335     if (UsesFakeSpeech()) {
336       // SpeechRecognition test specific TearDown.
337       content::SpeechRecognitionManager::SetManagerForTesting(NULL);
338     }
339
340     extensions::PlatformAppBrowserTest::TearDown();
341   }
342
343   virtual void SetUpOnMainThread() OVERRIDE {
344     extensions::PlatformAppBrowserTest::SetUpOnMainThread();
345     const testing::TestInfo* const test_info =
346         testing::UnitTest::GetInstance()->current_test_info();
347     // Mock out geolocation for geolocation specific tests.
348     if (!strncmp(test_info->name(), "GeolocationAPI",
349             strlen("GeolocationAPI"))) {
350       ui_test_utils::OverrideGeolocation(10, 20);
351     }
352   }
353
354   virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
355     command_line->AppendSwitch(switches::kUseFakeDeviceForMediaStream);
356     command_line->AppendSwitchASCII(switches::kJavaScriptFlags, "--expose-gc");
357
358     extensions::PlatformAppBrowserTest::SetUpCommandLine(command_line);
359   }
360
361   // This method is responsible for initializing a packaged app, which contains
362   // multiple webview tags. The tags have different partition identifiers and
363   // their WebContent objects are returned as output. The method also verifies
364   // the expected process allocation and storage partition assignment.
365   // The |navigate_to_url| parameter is used to navigate the main browser
366   // window.
367   //
368   // TODO(ajwong): This function is getting to be too large. Either refactor it
369   // so the test can specify a configuration of WebView tags that we will
370   // dynamically inject JS to generate, or move this test wholesale into
371   // something that RunPlatformAppTest() can execute purely in Javascript. This
372   // won't let us do a white-box examination of the StoragePartition equivalence
373   // directly, but we will be able to view the black box effects which is good
374   // enough.  http://crbug.com/160361
375   void NavigateAndOpenAppForIsolation(
376       GURL navigate_to_url,
377       content::WebContents** default_tag_contents1,
378       content::WebContents** default_tag_contents2,
379       content::WebContents** named_partition_contents1,
380       content::WebContents** named_partition_contents2,
381       content::WebContents** persistent_partition_contents1,
382       content::WebContents** persistent_partition_contents2,
383       content::WebContents** persistent_partition_contents3) {
384     GURL::Replacements replace_host;
385     std::string host_str("localhost");  // Must stay in scope with replace_host.
386     replace_host.SetHostStr(host_str);
387
388     navigate_to_url = navigate_to_url.ReplaceComponents(replace_host);
389
390     GURL tag_url1 = embedded_test_server()->GetURL(
391         "/extensions/platform_apps/web_view/isolation/cookie.html");
392     tag_url1 = tag_url1.ReplaceComponents(replace_host);
393     GURL tag_url2 = embedded_test_server()->GetURL(
394         "/extensions/platform_apps/web_view/isolation/cookie2.html");
395     tag_url2 = tag_url2.ReplaceComponents(replace_host);
396     GURL tag_url3 = embedded_test_server()->GetURL(
397         "/extensions/platform_apps/web_view/isolation/storage1.html");
398     tag_url3 = tag_url3.ReplaceComponents(replace_host);
399     GURL tag_url4 = embedded_test_server()->GetURL(
400         "/extensions/platform_apps/web_view/isolation/storage2.html");
401     tag_url4 = tag_url4.ReplaceComponents(replace_host);
402     GURL tag_url5 = embedded_test_server()->GetURL(
403         "/extensions/platform_apps/web_view/isolation/storage1.html#p1");
404     tag_url5 = tag_url5.ReplaceComponents(replace_host);
405     GURL tag_url6 = embedded_test_server()->GetURL(
406         "/extensions/platform_apps/web_view/isolation/storage1.html#p2");
407     tag_url6 = tag_url6.ReplaceComponents(replace_host);
408     GURL tag_url7 = embedded_test_server()->GetURL(
409         "/extensions/platform_apps/web_view/isolation/storage1.html#p3");
410     tag_url7 = tag_url7.ReplaceComponents(replace_host);
411
412     ui_test_utils::NavigateToURLWithDisposition(
413         browser(), navigate_to_url, CURRENT_TAB,
414         ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
415
416     ui_test_utils::UrlLoadObserver observer1(
417         tag_url1, content::NotificationService::AllSources());
418     ui_test_utils::UrlLoadObserver observer2(
419         tag_url2, content::NotificationService::AllSources());
420     ui_test_utils::UrlLoadObserver observer3(
421         tag_url3, content::NotificationService::AllSources());
422     ui_test_utils::UrlLoadObserver observer4(
423         tag_url4, content::NotificationService::AllSources());
424     ui_test_utils::UrlLoadObserver observer5(
425         tag_url5, content::NotificationService::AllSources());
426     ui_test_utils::UrlLoadObserver observer6(
427         tag_url6, content::NotificationService::AllSources());
428     ui_test_utils::UrlLoadObserver observer7(
429         tag_url7, content::NotificationService::AllSources());
430     LoadAndLaunchPlatformApp("web_view/isolation", "Launched");
431     observer1.Wait();
432     observer2.Wait();
433     observer3.Wait();
434     observer4.Wait();
435     observer5.Wait();
436     observer6.Wait();
437     observer7.Wait();
438
439     content::Source<content::NavigationController> source1 = observer1.source();
440     EXPECT_TRUE(source1->GetWebContents()->GetRenderProcessHost()->
441         IsIsolatedGuest());
442     content::Source<content::NavigationController> source2 = observer2.source();
443     EXPECT_TRUE(source2->GetWebContents()->GetRenderProcessHost()->
444         IsIsolatedGuest());
445     content::Source<content::NavigationController> source3 = observer3.source();
446     EXPECT_TRUE(source3->GetWebContents()->GetRenderProcessHost()->
447         IsIsolatedGuest());
448     content::Source<content::NavigationController> source4 = observer4.source();
449     EXPECT_TRUE(source4->GetWebContents()->GetRenderProcessHost()->
450         IsIsolatedGuest());
451     content::Source<content::NavigationController> source5 = observer5.source();
452     EXPECT_TRUE(source5->GetWebContents()->GetRenderProcessHost()->
453         IsIsolatedGuest());
454     content::Source<content::NavigationController> source6 = observer6.source();
455     EXPECT_TRUE(source6->GetWebContents()->GetRenderProcessHost()->
456         IsIsolatedGuest());
457     content::Source<content::NavigationController> source7 = observer7.source();
458     EXPECT_TRUE(source7->GetWebContents()->GetRenderProcessHost()->
459         IsIsolatedGuest());
460
461     // Check that the first two tags use the same process and it is different
462     // than the process used by the other two.
463     EXPECT_EQ(source1->GetWebContents()->GetRenderProcessHost()->GetID(),
464               source2->GetWebContents()->GetRenderProcessHost()->GetID());
465     EXPECT_EQ(source3->GetWebContents()->GetRenderProcessHost()->GetID(),
466               source4->GetWebContents()->GetRenderProcessHost()->GetID());
467     EXPECT_NE(source1->GetWebContents()->GetRenderProcessHost()->GetID(),
468               source3->GetWebContents()->GetRenderProcessHost()->GetID());
469
470     // The two sets of tags should also be isolated from the main browser.
471     EXPECT_NE(source1->GetWebContents()->GetRenderProcessHost()->GetID(),
472               browser()->tab_strip_model()->GetWebContentsAt(0)->
473                   GetRenderProcessHost()->GetID());
474     EXPECT_NE(source3->GetWebContents()->GetRenderProcessHost()->GetID(),
475               browser()->tab_strip_model()->GetWebContentsAt(0)->
476                   GetRenderProcessHost()->GetID());
477
478     // Check that the storage partitions of the first two tags match and are
479     // different than the other two.
480     EXPECT_EQ(
481         source1->GetWebContents()->GetRenderProcessHost()->
482             GetStoragePartition(),
483         source2->GetWebContents()->GetRenderProcessHost()->
484             GetStoragePartition());
485     EXPECT_EQ(
486         source3->GetWebContents()->GetRenderProcessHost()->
487             GetStoragePartition(),
488         source4->GetWebContents()->GetRenderProcessHost()->
489             GetStoragePartition());
490     EXPECT_NE(
491         source1->GetWebContents()->GetRenderProcessHost()->
492             GetStoragePartition(),
493         source3->GetWebContents()->GetRenderProcessHost()->
494             GetStoragePartition());
495
496     // Ensure the persistent storage partitions are different.
497     EXPECT_EQ(
498         source5->GetWebContents()->GetRenderProcessHost()->
499             GetStoragePartition(),
500         source6->GetWebContents()->GetRenderProcessHost()->
501             GetStoragePartition());
502     EXPECT_NE(
503         source5->GetWebContents()->GetRenderProcessHost()->
504             GetStoragePartition(),
505         source7->GetWebContents()->GetRenderProcessHost()->
506             GetStoragePartition());
507     EXPECT_NE(
508         source1->GetWebContents()->GetRenderProcessHost()->
509             GetStoragePartition(),
510         source5->GetWebContents()->GetRenderProcessHost()->
511             GetStoragePartition());
512     EXPECT_NE(
513         source1->GetWebContents()->GetRenderProcessHost()->
514             GetStoragePartition(),
515         source7->GetWebContents()->GetRenderProcessHost()->
516             GetStoragePartition());
517
518     *default_tag_contents1 = source1->GetWebContents();
519     *default_tag_contents2 = source2->GetWebContents();
520     *named_partition_contents1 = source3->GetWebContents();
521     *named_partition_contents2 = source4->GetWebContents();
522     if (persistent_partition_contents1) {
523       *persistent_partition_contents1 = source5->GetWebContents();
524     }
525     if (persistent_partition_contents2) {
526       *persistent_partition_contents2 = source6->GetWebContents();
527     }
528     if (persistent_partition_contents3) {
529       *persistent_partition_contents3 = source7->GetWebContents();
530     }
531   }
532
533   // Handles |request| by serving a redirect response.
534   static scoped_ptr<net::test_server::HttpResponse> RedirectResponseHandler(
535       const std::string& path,
536       const GURL& redirect_target,
537       const net::test_server::HttpRequest& request) {
538     if (!StartsWithASCII(path, request.relative_url, true))
539       return scoped_ptr<net::test_server::HttpResponse>();
540
541     scoped_ptr<net::test_server::BasicHttpResponse> http_response(
542         new net::test_server::BasicHttpResponse);
543     http_response->set_code(net::HTTP_MOVED_PERMANENTLY);
544     http_response->AddCustomHeader("Location", redirect_target.spec());
545     return http_response.PassAs<net::test_server::HttpResponse>();
546   }
547
548   // Handles |request| by serving an empty response.
549   static scoped_ptr<net::test_server::HttpResponse> EmptyResponseHandler(
550       const std::string& path,
551       const net::test_server::HttpRequest& request) {
552     if (StartsWithASCII(path, request.relative_url, true)) {
553       return scoped_ptr<net::test_server::HttpResponse>(
554           new EmptyHttpResponse);
555     }
556
557     return scoped_ptr<net::test_server::HttpResponse>();
558   }
559
560   // Shortcut to return the current MenuManager.
561   extensions::MenuManager* menu_manager() {
562     return extensions::MenuManager::Get(browser()->profile());
563   }
564
565   // This gets all the items that any extension has registered for possible
566   // inclusion in context menus.
567   MenuItem::List GetItems() {
568     MenuItem::List result;
569     std::set<MenuItem::ExtensionKey> extension_ids =
570         menu_manager()->ExtensionIds();
571     std::set<MenuItem::ExtensionKey>::iterator i;
572     for (i = extension_ids.begin(); i != extension_ids.end(); ++i) {
573       const MenuItem::List* list = menu_manager()->MenuItems(*i);
574       result.insert(result.end(), list->begin(), list->end());
575     }
576     return result;
577   }
578
579   enum TestServer {
580     NEEDS_TEST_SERVER,
581     NO_TEST_SERVER
582   };
583
584   void TestHelper(const std::string& test_name,
585                   const std::string& app_location,
586                   TestServer test_server) {
587     // For serving guest pages.
588     if (test_server == NEEDS_TEST_SERVER) {
589       if (!StartEmbeddedTestServer()) {
590         LOG(ERROR) << "FAILED TO START TEST SERVER.";
591         return;
592       }
593       embedded_test_server()->RegisterRequestHandler(
594           base::Bind(&WebViewTest::RedirectResponseHandler,
595                     kRedirectResponsePath,
596                     embedded_test_server()->GetURL(kRedirectResponseFullPath)));
597
598       embedded_test_server()->RegisterRequestHandler(
599           base::Bind(&WebViewTest::EmptyResponseHandler, kEmptyResponsePath));
600     }
601
602     LoadAndLaunchPlatformApp(app_location.c_str(), "Launched");
603
604     // Flush any pending events to make sure we start with a clean slate.
605     content::RunAllPendingInMessageLoop();
606
607     content::WebContents* embedder_web_contents =
608         GetFirstAppWindowWebContents();
609     if (!embedder_web_contents) {
610       LOG(ERROR) << "UNABLE TO FIND EMBEDDER WEB CONTENTS.";
611       return;
612     }
613
614     ExtensionTestMessageListener done_listener("TEST_PASSED", false);
615     done_listener.set_failure_message("TEST_FAILED");
616     if (!content::ExecuteScript(
617             embedder_web_contents,
618             base::StringPrintf("runTest('%s')", test_name.c_str()))) {
619       LOG(ERROR) << "UNABLE TO START TEST.";
620       return;
621     }
622     ASSERT_TRUE(done_listener.WaitUntilSatisfied());
623   }
624
625   content::WebContents* LoadGuest(const std::string& guest_path,
626                                   const std::string& app_path) {
627     GURL::Replacements replace_host;
628     std::string host_str("localhost");  // Must stay in scope with replace_host.
629     replace_host.SetHostStr(host_str);
630
631     GURL guest_url = embedded_test_server()->GetURL(guest_path);
632     guest_url = guest_url.ReplaceComponents(replace_host);
633
634     ui_test_utils::UrlLoadObserver guest_observer(
635         guest_url, content::NotificationService::AllSources());
636
637     LoadAndLaunchPlatformApp(app_path.c_str(), "guest-loaded");
638
639     guest_observer.Wait();
640     content::Source<content::NavigationController> source =
641         guest_observer.source();
642     EXPECT_TRUE(source->GetWebContents()->GetRenderProcessHost()->
643         IsIsolatedGuest());
644
645     content::WebContents* guest_web_contents = source->GetWebContents();
646     return guest_web_contents;
647   }
648
649   // Runs media_access/allow tests.
650   void MediaAccessAPIAllowTestHelper(const std::string& test_name);
651
652   // Runs media_access/deny tests, each of them are run separately otherwise
653   // they timeout (mostly on Windows).
654   void MediaAccessAPIDenyTestHelper(const std::string& test_name) {
655     ASSERT_TRUE(StartEmbeddedTestServer());  // For serving guest pages.
656     LoadAndLaunchPlatformApp("web_view/media_access/deny", "loaded");
657
658     content::WebContents* embedder_web_contents =
659         GetFirstAppWindowWebContents();
660     ASSERT_TRUE(embedder_web_contents);
661
662     ExtensionTestMessageListener test_run_listener("PASSED", false);
663     test_run_listener.set_failure_message("FAILED");
664     EXPECT_TRUE(
665         content::ExecuteScript(
666             embedder_web_contents,
667             base::StringPrintf("startDenyTest('%s')", test_name.c_str())));
668     ASSERT_TRUE(test_run_listener.WaitUntilSatisfied());
669   }
670
671   void WaitForInterstitial(content::WebContents* web_contents) {
672     scoped_refptr<content::MessageLoopRunner> loop_runner(
673         new content::MessageLoopRunner);
674     InterstitialObserver observer(web_contents,
675                                   loop_runner->QuitClosure(),
676                                   base::Closure());
677     if (!content::InterstitialPage::GetInterstitialPage(web_contents))
678       loop_runner->Run();
679   }
680
681   void LoadAppWithGuest(const std::string& app_path) {
682
683     ExtensionTestMessageListener launched_listener("WebViewTest.LAUNCHED",
684                                                    false);
685     launched_listener.set_failure_message("WebViewTest.FAILURE");
686     LoadAndLaunchPlatformApp(app_path.c_str(), &launched_listener);
687
688     guest_web_contents_ = GetGuestViewManager()->WaitForGuestCreated();
689   }
690
691   void SendMessageToEmbedder(const std::string& message) {
692     EXPECT_TRUE(
693         content::ExecuteScript(
694             GetEmbedderWebContents(),
695             base::StringPrintf("onAppCommand('%s');", message.c_str())));
696   }
697
698   void SendMessageToGuestAndWait(const std::string& message,
699                                  const std::string& wait_message) {
700     scoped_ptr<ExtensionTestMessageListener> listener;
701     if (!wait_message.empty()) {
702       listener.reset(new ExtensionTestMessageListener(wait_message, false));
703     }
704
705     EXPECT_TRUE(
706         content::ExecuteScript(
707             GetGuestWebContents(),
708             base::StringPrintf("onAppCommand('%s');", message.c_str())));
709
710     if (listener) {
711       ASSERT_TRUE(listener->WaitUntilSatisfied());
712     }
713   }
714
715   content::WebContents* GetGuestWebContents() {
716     return guest_web_contents_;
717   }
718
719   content::WebContents* GetEmbedderWebContents() {
720     if (!embedder_web_contents_) {
721       embedder_web_contents_ = GetFirstAppWindowWebContents();
722     }
723     return embedder_web_contents_;
724   }
725
726   TestGuestViewManager* GetGuestViewManager() {
727     return factory_.GetManager(browser()->profile());
728   }
729
730   WebViewTest() : guest_web_contents_(NULL),
731                   embedder_web_contents_(NULL) {
732     extensions::GuestViewManager::set_factory_for_testing(&factory_);
733   }
734
735  private:
736   bool UsesFakeSpeech() {
737     const testing::TestInfo* const test_info =
738         testing::UnitTest::GetInstance()->current_test_info();
739
740     // SpeechRecognition test specific SetUp.
741     return !strcmp(test_info->name(),
742                    "SpeechRecognitionAPI_HasPermissionAllow");
743   }
744
745   scoped_ptr<content::FakeSpeechRecognitionManager>
746       fake_speech_recognition_manager_;
747
748   TestGuestViewManagerFactory factory_;
749   // Note that these are only set if you launch app using LoadAppWithGuest().
750   content::WebContents* guest_web_contents_;
751   content::WebContents* embedder_web_contents_;
752 };
753
754 // This test verifies that hiding the guest triggers WebContents::WasHidden().
755 IN_PROC_BROWSER_TEST_F(WebViewTest, GuestVisibilityChanged) {
756   LoadAppWithGuest("web_view/visibility_changed");
757
758   scoped_refptr<content::MessageLoopRunner> loop_runner(
759       new content::MessageLoopRunner);
760   WebContentsHiddenObserver observer(GetGuestWebContents(),
761                                      loop_runner->QuitClosure());
762
763   // Handled in platform_apps/web_view/visibility_changed/main.js
764   SendMessageToEmbedder("hide-guest");
765   if (!observer.hidden_observed())
766     loop_runner->Run();
767 }
768
769 // This test verifies that hiding the embedder also hides the guest.
770 IN_PROC_BROWSER_TEST_F(WebViewTest, EmbedderVisibilityChanged) {
771   LoadAppWithGuest("web_view/visibility_changed");
772
773   scoped_refptr<content::MessageLoopRunner> loop_runner(
774       new content::MessageLoopRunner);
775   WebContentsHiddenObserver observer(GetGuestWebContents(),
776                                      loop_runner->QuitClosure());
777
778   // Handled in platform_apps/web_view/visibility_changed/main.js
779   SendMessageToEmbedder("hide-embedder");
780   if (!observer.hidden_observed())
781     loop_runner->Run();
782 }
783
784 // This test verifies that reloading the embedder reloads the guest (and doest
785 // not crash).
786 IN_PROC_BROWSER_TEST_F(WebViewTest, ReloadEmbedder) {
787   // Just load a guest from other test, we do not want to add a separate
788   // platform_app for this test.
789   LoadAppWithGuest("web_view/visibility_changed");
790
791   ExtensionTestMessageListener launched_again_listener("WebViewTest.LAUNCHED",
792                                                        false);
793   GetEmbedderWebContents()->GetController().Reload(false);
794   ASSERT_TRUE(launched_again_listener.WaitUntilSatisfied());
795 }
796
797 IN_PROC_BROWSER_TEST_F(WebViewTest, AcceptTouchEvents) {
798   LoadAppWithGuest("web_view/accept_touch_events");
799
800   content::RenderViewHost* embedder_rvh =
801       GetEmbedderWebContents()->GetRenderViewHost();
802
803   bool embedder_has_touch_handler =
804       content::RenderViewHostTester::HasTouchEventHandler(embedder_rvh);
805   EXPECT_FALSE(embedder_has_touch_handler);
806
807   SendMessageToGuestAndWait("install-touch-handler", "installed-touch-handler");
808
809   // Note that we need to wait for the installed/registered touch handler to
810   // appear in browser process before querying |embedder_rvh|.
811   // In practice, since we do a roundrtip from browser process to guest and
812   // back, this is sufficient.
813   embedder_has_touch_handler =
814       content::RenderViewHostTester::HasTouchEventHandler(embedder_rvh);
815   EXPECT_TRUE(embedder_has_touch_handler);
816
817   SendMessageToGuestAndWait("uninstall-touch-handler",
818                             "uninstalled-touch-handler");
819   // Same as the note above about waiting.
820   embedder_has_touch_handler =
821       content::RenderViewHostTester::HasTouchEventHandler(embedder_rvh);
822   EXPECT_FALSE(embedder_has_touch_handler);
823 }
824
825 // This test ensures JavaScript errors ("Cannot redefine property") do not
826 // happen when a <webview> is removed from DOM and added back.
827 IN_PROC_BROWSER_TEST_F(WebViewTest,
828                        AddRemoveWebView_AddRemoveWebView) {
829   ASSERT_TRUE(StartEmbeddedTestServer());  // For serving guest pages.
830   ASSERT_TRUE(RunPlatformAppTest("platform_apps/web_view/addremove"))
831       << message_;
832 }
833
834 IN_PROC_BROWSER_TEST_F(WebViewTest, AutoSize) {
835 #if defined(OS_WIN)
836   // Flaky on XP bot http://crbug.com/299507
837   if (base::win::GetVersion() <= base::win::VERSION_XP)
838     return;
839 #endif
840
841   ASSERT_TRUE(RunPlatformAppTest("platform_apps/web_view/autosize"))
842       << message_;
843 }
844
845 // http://crbug.com/326332
846 IN_PROC_BROWSER_TEST_F(WebViewTest, DISABLED_Shim_TestAutosizeAfterNavigation) {
847   TestHelper("testAutosizeAfterNavigation", "web_view/shim", NO_TEST_SERVER);
848 }
849
850 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestAutosizeBeforeNavigation) {
851   TestHelper("testAutosizeBeforeNavigation", "web_view/shim", NO_TEST_SERVER);
852 }
853 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestAutosizeRemoveAttributes) {
854   TestHelper("testAutosizeRemoveAttributes", "web_view/shim", NO_TEST_SERVER);
855 }
856
857 // This test is disabled due to being flaky. http://crbug.com/282116
858 #if defined(OS_WIN) || defined(OS_MACOSX)
859 #define MAYBE_Shim_TestAutosizeWithPartialAttributes \
860     DISABLED_Shim_TestAutosizeWithPartialAttributes
861 #else
862 #define MAYBE_Shim_TestAutosizeWithPartialAttributes \
863     Shim_TestAutosizeWithPartialAttributes
864 #endif
865 IN_PROC_BROWSER_TEST_F(WebViewTest,
866                        MAYBE_Shim_TestAutosizeWithPartialAttributes) {
867   TestHelper("testAutosizeWithPartialAttributes",
868              "web_view/shim",
869              NO_TEST_SERVER);
870 }
871
872 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestAPIMethodExistence) {
873   TestHelper("testAPIMethodExistence", "web_view/shim", NO_TEST_SERVER);
874 }
875
876 // Tests the existence of WebRequest API event objects on the request
877 // object, on the webview element, and hanging directly off webview.
878 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestWebRequestAPIExistence) {
879   TestHelper("testWebRequestAPIExistence", "web_view/shim", NO_TEST_SERVER);
880 }
881
882 // http://crbug.com/315920
883 #if defined(GOOGLE_CHROME_BUILD) && (defined(OS_WIN) || defined(OS_LINUX))
884 #define MAYBE_Shim_TestChromeExtensionURL DISABLED_Shim_TestChromeExtensionURL
885 #else
886 #define MAYBE_Shim_TestChromeExtensionURL Shim_TestChromeExtensionURL
887 #endif
888 IN_PROC_BROWSER_TEST_F(WebViewTest, MAYBE_Shim_TestChromeExtensionURL) {
889   TestHelper("testChromeExtensionURL", "web_view/shim", NO_TEST_SERVER);
890 }
891
892 // http://crbug.com/315920
893 #if defined(GOOGLE_CHROME_BUILD) && (defined(OS_WIN) || defined(OS_LINUX))
894 #define MAYBE_Shim_TestChromeExtensionRelativePath \
895     DISABLED_Shim_TestChromeExtensionRelativePath
896 #else
897 #define MAYBE_Shim_TestChromeExtensionRelativePath \
898     Shim_TestChromeExtensionRelativePath
899 #endif
900 IN_PROC_BROWSER_TEST_F(WebViewTest,
901                        MAYBE_Shim_TestChromeExtensionRelativePath) {
902   TestHelper("testChromeExtensionRelativePath",
903              "web_view/shim",
904              NO_TEST_SERVER);
905 }
906
907 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestDisplayNoneWebviewLoad) {
908   TestHelper("testDisplayNoneWebviewLoad", "web_view/shim", NO_TEST_SERVER);
909 }
910
911 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestDisplayNoneWebviewRemoveChild) {
912   TestHelper("testDisplayNoneWebviewRemoveChild",
913              "web_view/shim", NO_TEST_SERVER);
914 }
915
916 IN_PROC_BROWSER_TEST_F(WebViewTest,
917                        Shim_TestInlineScriptFromAccessibleResources) {
918   TestHelper("testInlineScriptFromAccessibleResources",
919              "web_view/shim",
920              NO_TEST_SERVER);
921 }
922
923 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestInvalidChromeExtensionURL) {
924   TestHelper("testInvalidChromeExtensionURL", "web_view/shim", NO_TEST_SERVER);
925 }
926
927 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestEventName) {
928   TestHelper("testEventName", "web_view/shim", NO_TEST_SERVER);
929 }
930
931 // WebViewTest.Shim_TestOnEventProperty is flaky, so disable it.
932 // http://crbug.com/359832.
933 IN_PROC_BROWSER_TEST_F(WebViewTest, DISABLED_Shim_TestOnEventProperty) {
934   TestHelper("testOnEventProperties", "web_view/shim", NO_TEST_SERVER);
935 }
936
937 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestLoadProgressEvent) {
938   TestHelper("testLoadProgressEvent", "web_view/shim", NO_TEST_SERVER);
939 }
940
941 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestDestroyOnEventListener) {
942   TestHelper("testDestroyOnEventListener", "web_view/shim", NO_TEST_SERVER);
943 }
944
945 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestCannotMutateEventName) {
946   TestHelper("testCannotMutateEventName", "web_view/shim", NO_TEST_SERVER);
947 }
948
949 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestPartitionRaisesException) {
950   TestHelper("testPartitionRaisesException", "web_view/shim", NO_TEST_SERVER);
951 }
952
953 IN_PROC_BROWSER_TEST_F(WebViewTest,
954                        Shim_TestPartitionRemovalAfterNavigationFails) {
955   TestHelper("testPartitionRemovalAfterNavigationFails",
956              "web_view/shim",
957              NO_TEST_SERVER);
958 }
959
960 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestExecuteScriptFail) {
961 #if defined(OS_WIN)
962   // Flaky on XP bot http://crbug.com/266185
963   if (base::win::GetVersion() <= base::win::VERSION_XP)
964     return;
965 #endif
966
967   TestHelper("testExecuteScriptFail", "web_view/shim", NEEDS_TEST_SERVER);
968 }
969
970 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestExecuteScript) {
971   TestHelper("testExecuteScript", "web_view/shim", NO_TEST_SERVER);
972 }
973
974 IN_PROC_BROWSER_TEST_F(
975     WebViewTest,
976     Shim_TestExecuteScriptIsAbortedWhenWebViewSourceIsChanged) {
977   TestHelper("testExecuteScriptIsAbortedWhenWebViewSourceIsChanged",
978              "web_view/shim",
979              NO_TEST_SERVER);
980 }
981
982 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestTerminateAfterExit) {
983   TestHelper("testTerminateAfterExit", "web_view/shim", NO_TEST_SERVER);
984 }
985
986 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestAssignSrcAfterCrash) {
987   TestHelper("testAssignSrcAfterCrash", "web_view/shim", NO_TEST_SERVER);
988 }
989
990 IN_PROC_BROWSER_TEST_F(WebViewTest,
991                        Shim_TestNavOnConsecutiveSrcAttributeChanges) {
992   TestHelper("testNavOnConsecutiveSrcAttributeChanges",
993              "web_view/shim",
994              NO_TEST_SERVER);
995 }
996
997 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestNavOnSrcAttributeChange) {
998   TestHelper("testNavOnSrcAttributeChange", "web_view/shim", NO_TEST_SERVER);
999 }
1000
1001 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestNavigateAfterResize) {
1002   TestHelper("testNavigateAfterResize", "web_view/shim", NO_TEST_SERVER);
1003 }
1004
1005 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestRemoveSrcAttribute) {
1006   TestHelper("testRemoveSrcAttribute", "web_view/shim", NO_TEST_SERVER);
1007 }
1008
1009 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestReassignSrcAttribute) {
1010   TestHelper("testReassignSrcAttribute", "web_view/shim", NO_TEST_SERVER);
1011 }
1012
1013 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestNewWindow) {
1014   TestHelper("testNewWindow", "web_view/shim", NEEDS_TEST_SERVER);
1015 }
1016
1017 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestNewWindowTwoListeners) {
1018   TestHelper("testNewWindowTwoListeners", "web_view/shim", NEEDS_TEST_SERVER);
1019 }
1020
1021 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestNewWindowNoPreventDefault) {
1022   TestHelper("testNewWindowNoPreventDefault",
1023              "web_view/shim",
1024              NEEDS_TEST_SERVER);
1025 }
1026
1027 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestNewWindowNoReferrerLink) {
1028   TestHelper("testNewWindowNoReferrerLink", "web_view/shim", NEEDS_TEST_SERVER);
1029 }
1030
1031 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestContentLoadEvent) {
1032   TestHelper("testContentLoadEvent", "web_view/shim", NO_TEST_SERVER);
1033 }
1034
1035 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestDeclarativeWebRequestAPI) {
1036   TestHelper("testDeclarativeWebRequestAPI",
1037              "web_view/shim",
1038              NEEDS_TEST_SERVER);
1039 }
1040
1041 IN_PROC_BROWSER_TEST_F(WebViewTest,
1042                        Shim_TestDeclarativeWebRequestAPISendMessage) {
1043   TestHelper("testDeclarativeWebRequestAPISendMessage",
1044              "web_view/shim",
1045              NEEDS_TEST_SERVER);
1046 }
1047
1048 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestWebRequestAPI) {
1049   TestHelper("testWebRequestAPI", "web_view/shim", NEEDS_TEST_SERVER);
1050 }
1051
1052 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestWebRequestAPIGoogleProperty) {
1053   TestHelper("testWebRequestAPIGoogleProperty",
1054              "web_view/shim",
1055              NO_TEST_SERVER);
1056 }
1057
1058 // This test is disabled due to being flaky. http://crbug.com/309451
1059 #if defined(OS_WIN)
1060 #define MAYBE_Shim_TestWebRequestListenerSurvivesReparenting \
1061     DISABLED_Shim_TestWebRequestListenerSurvivesReparenting
1062 #else
1063 #define MAYBE_Shim_TestWebRequestListenerSurvivesReparenting \
1064     Shim_TestWebRequestListenerSurvivesReparenting
1065 #endif
1066 IN_PROC_BROWSER_TEST_F(
1067     WebViewTest,
1068     MAYBE_Shim_TestWebRequestListenerSurvivesReparenting) {
1069   TestHelper("testWebRequestListenerSurvivesReparenting",
1070              "web_view/shim",
1071              NEEDS_TEST_SERVER);
1072 }
1073
1074 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestLoadStartLoadRedirect) {
1075   TestHelper("testLoadStartLoadRedirect", "web_view/shim", NEEDS_TEST_SERVER);
1076 }
1077
1078 IN_PROC_BROWSER_TEST_F(WebViewTest,
1079                        Shim_TestLoadAbortChromeExtensionURLWrongPartition) {
1080   TestHelper("testLoadAbortChromeExtensionURLWrongPartition",
1081              "web_view/shim",
1082              NO_TEST_SERVER);
1083 }
1084
1085 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestLoadAbortEmptyResponse) {
1086   TestHelper("testLoadAbortEmptyResponse", "web_view/shim", NEEDS_TEST_SERVER);
1087 }
1088
1089 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestLoadAbortIllegalChromeURL) {
1090   TestHelper("testLoadAbortIllegalChromeURL",
1091              "web_view/shim",
1092              NO_TEST_SERVER);
1093 }
1094
1095 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestLoadAbortIllegalFileURL) {
1096   TestHelper("testLoadAbortIllegalFileURL", "web_view/shim", NO_TEST_SERVER);
1097 }
1098
1099 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestLoadAbortIllegalJavaScriptURL) {
1100   TestHelper("testLoadAbortIllegalJavaScriptURL",
1101              "web_view/shim",
1102              NO_TEST_SERVER);
1103 }
1104
1105 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestLoadAbortInvalidNavigation) {
1106   TestHelper("testLoadAbortInvalidNavigation", "web_view/shim", NO_TEST_SERVER);
1107 }
1108
1109 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestLoadAbortNonWebSafeScheme) {
1110   TestHelper("testLoadAbortNonWebSafeScheme", "web_view/shim", NO_TEST_SERVER);
1111 }
1112
1113 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestReload) {
1114   TestHelper("testReload", "web_view/shim", NEEDS_TEST_SERVER);
1115 }
1116
1117 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestGetProcessId) {
1118   TestHelper("testGetProcessId", "web_view/shim", NEEDS_TEST_SERVER);
1119 }
1120
1121 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestHiddenBeforeNavigation) {
1122   TestHelper("testHiddenBeforeNavigation", "web_view/shim", NO_TEST_SERVER);
1123 }
1124
1125 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestRemoveWebviewOnExit) {
1126   ASSERT_TRUE(StartEmbeddedTestServer());  // For serving guest pages.
1127
1128   // Launch the app and wait until it's ready to load a test.
1129   LoadAndLaunchPlatformApp("web_view/shim", "Launched");
1130
1131   content::WebContents* embedder_web_contents = GetFirstAppWindowWebContents();
1132   ASSERT_TRUE(embedder_web_contents);
1133
1134   GURL::Replacements replace_host;
1135   std::string host_str("localhost");  // Must stay in scope with replace_host.
1136   replace_host.SetHostStr(host_str);
1137
1138   std::string guest_path(
1139       "/extensions/platform_apps/web_view/shim/empty_guest.html");
1140   GURL guest_url = embedded_test_server()->GetURL(guest_path);
1141   guest_url = guest_url.ReplaceComponents(replace_host);
1142
1143   ui_test_utils::UrlLoadObserver guest_observer(
1144       guest_url, content::NotificationService::AllSources());
1145
1146   // Run the test and wait until the guest WebContents is available and has
1147   // finished loading.
1148   ExtensionTestMessageListener guest_loaded_listener("guest-loaded", false);
1149   EXPECT_TRUE(content::ExecuteScript(
1150                   embedder_web_contents,
1151                   "runTest('testRemoveWebviewOnExit')"));
1152   guest_observer.Wait();
1153
1154   content::Source<content::NavigationController> source =
1155       guest_observer.source();
1156   EXPECT_TRUE(source->GetWebContents()->GetRenderProcessHost()->
1157       IsIsolatedGuest());
1158
1159   ASSERT_TRUE(guest_loaded_listener.WaitUntilSatisfied());
1160
1161   content::WebContentsDestroyedWatcher destroyed_watcher(
1162       source->GetWebContents());
1163
1164   // Tell the embedder to kill the guest.
1165   EXPECT_TRUE(content::ExecuteScript(
1166                   embedder_web_contents,
1167                   "removeWebviewOnExitDoCrash();"));
1168
1169   // Wait until the guest WebContents is destroyed.
1170   destroyed_watcher.Wait();
1171 }
1172
1173 // Remove <webview> immediately after navigating it.
1174 // This is a regression test for http://crbug.com/276023.
1175 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestRemoveWebviewAfterNavigation) {
1176   TestHelper("testRemoveWebviewAfterNavigation",
1177              "web_view/shim",
1178              NO_TEST_SERVER);
1179 }
1180
1181 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestNavigationToExternalProtocol) {
1182   TestHelper("testNavigationToExternalProtocol",
1183              "web_view/shim",
1184              NO_TEST_SERVER);
1185 }
1186
1187 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestResizeWebviewResizesContent) {
1188   TestHelper("testResizeWebviewResizesContent",
1189              "web_view/shim",
1190              NO_TEST_SERVER);
1191 }
1192
1193 // This test makes sure we do not crash if app is closed while interstitial
1194 // page is being shown in guest.
1195 // Disabled under LeakSanitizer due to memory leaks. http://crbug.com/321662
1196 #if defined(LEAK_SANITIZER)
1197 #define MAYBE_InterstitialTeardown DISABLED_InterstitialTeardown
1198 #else
1199 #define MAYBE_InterstitialTeardown InterstitialTeardown
1200 #endif
1201 IN_PROC_BROWSER_TEST_F(WebViewTest, MAYBE_InterstitialTeardown) {
1202 #if defined(OS_WIN)
1203   // Flaky on XP bot http://crbug.com/297014
1204   if (base::win::GetVersion() <= base::win::VERSION_XP)
1205     return;
1206 #endif
1207
1208   // Start a HTTPS server so we can load an interstitial page inside guest.
1209   net::SpawnedTestServer::SSLOptions ssl_options;
1210   ssl_options.server_certificate =
1211       net::SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME;
1212   net::SpawnedTestServer https_server(
1213       net::SpawnedTestServer::TYPE_HTTPS, ssl_options,
1214       base::FilePath(FILE_PATH_LITERAL("chrome/test/data")));
1215   ASSERT_TRUE(https_server.Start());
1216
1217   net::HostPortPair host_and_port = https_server.host_port_pair();
1218
1219   LoadAndLaunchPlatformApp("web_view/interstitial_teardown", "EmbedderLoaded");
1220
1221   // Now load the guest.
1222   content::WebContents* embedder_web_contents = GetFirstAppWindowWebContents();
1223   ExtensionTestMessageListener second("GuestAddedToDom", false);
1224   EXPECT_TRUE(content::ExecuteScript(
1225       embedder_web_contents,
1226       base::StringPrintf("loadGuest(%d);\n", host_and_port.port())));
1227   ASSERT_TRUE(second.WaitUntilSatisfied());
1228
1229   // Wait for interstitial page to be shown in guest.
1230   content::WebContents* guest_web_contents =
1231       GetGuestViewManager()->WaitForGuestCreated();
1232   ASSERT_TRUE(guest_web_contents->GetRenderProcessHost()->IsIsolatedGuest());
1233   WaitForInterstitial(guest_web_contents);
1234
1235   // Now close the app while interstitial page being shown in guest.
1236   apps::AppWindow* window = GetFirstAppWindow();
1237   window->GetBaseWindow()->Close();
1238 }
1239
1240 IN_PROC_BROWSER_TEST_F(WebViewTest, ShimSrcAttribute) {
1241   ASSERT_TRUE(RunPlatformAppTest("platform_apps/web_view/src_attribute"))
1242       << message_;
1243 }
1244
1245 // This test verifies that prerendering has been disabled inside <webview>.
1246 // This test is here rather than in PrerenderBrowserTest for testing convenience
1247 // only. If it breaks then this is a bug in the prerenderer.
1248 IN_PROC_BROWSER_TEST_F(WebViewTest, NoPrerenderer) {
1249   ASSERT_TRUE(StartEmbeddedTestServer());
1250   content::WebContents* guest_web_contents =
1251       LoadGuest(
1252           "/extensions/platform_apps/web_view/noprerenderer/guest.html",
1253           "web_view/noprerenderer");
1254   ASSERT_TRUE(guest_web_contents != NULL);
1255
1256   PrerenderLinkManager* prerender_link_manager =
1257       PrerenderLinkManagerFactory::GetForProfile(
1258           Profile::FromBrowserContext(guest_web_contents->GetBrowserContext()));
1259   ASSERT_TRUE(prerender_link_manager != NULL);
1260   EXPECT_TRUE(prerender_link_manager->IsEmpty());
1261 }
1262
1263 // Verify that existing <webview>'s are detected when the task manager starts
1264 // up.
1265 IN_PROC_BROWSER_TEST_F(WebViewTest, TaskManagerExistingWebView) {
1266   ASSERT_TRUE(StartEmbeddedTestServer());
1267
1268   LoadGuest("/extensions/platform_apps/web_view/task_manager/guest.html",
1269             "web_view/task_manager");
1270
1271   chrome::ShowTaskManager(browser());  // Show task manager AFTER guest loads.
1272
1273   const char* guest_title = "WebViewed test content";
1274   const char* app_name = "<webview> task manager test";
1275   ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(1, MatchWebView(guest_title)));
1276   ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(1, MatchAboutBlankTab()));
1277   ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(1, MatchApp(app_name)));
1278   ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(1, MatchBackground(app_name)));
1279
1280   ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(1, MatchAnyWebView()));
1281   ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(1, MatchAnyTab()));
1282   ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(1, MatchAnyApp()));
1283   ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(1, MatchAnyBackground()));
1284 }
1285
1286 // Verify that the task manager notices the creation of new <webview>'s.
1287 IN_PROC_BROWSER_TEST_F(WebViewTest, TaskManagerNewWebView) {
1288   ASSERT_TRUE(StartEmbeddedTestServer());
1289
1290   chrome::ShowTaskManager(browser());  // Show task manager BEFORE guest loads.
1291
1292   LoadGuest("/extensions/platform_apps/web_view/task_manager/guest.html",
1293             "web_view/task_manager");
1294
1295   const char* guest_title = "WebViewed test content";
1296   const char* app_name = "<webview> task manager test";
1297   ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(1, MatchWebView(guest_title)));
1298   ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(1, MatchAboutBlankTab()));
1299   ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(1, MatchApp(app_name)));
1300   ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(1, MatchBackground(app_name)));
1301
1302   ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(1, MatchAnyWebView()));
1303   ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(1, MatchAnyTab()));
1304   ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(1, MatchAnyApp()));
1305   ASSERT_NO_FATAL_FAILURE(WaitForTaskManagerRows(1, MatchAnyBackground()));
1306 }
1307
1308 // This tests cookie isolation for packaged apps with webview tags. It navigates
1309 // the main browser window to a page that sets a cookie and loads an app with
1310 // multiple webview tags. Each tag sets a cookie and the test checks the proper
1311 // storage isolation is enforced.
1312 IN_PROC_BROWSER_TEST_F(WebViewTest, CookieIsolation) {
1313   ASSERT_TRUE(StartEmbeddedTestServer());
1314   const std::string kExpire =
1315       "var expire = new Date(Date.now() + 24 * 60 * 60 * 1000);";
1316   std::string cookie_script1(kExpire);
1317   cookie_script1.append(
1318       "document.cookie = 'guest1=true; path=/; expires=' + expire + ';';");
1319   std::string cookie_script2(kExpire);
1320   cookie_script2.append(
1321       "document.cookie = 'guest2=true; path=/; expires=' + expire + ';';");
1322
1323   GURL::Replacements replace_host;
1324   std::string host_str("localhost");  // Must stay in scope with replace_host.
1325   replace_host.SetHostStr(host_str);
1326
1327   GURL set_cookie_url = embedded_test_server()->GetURL(
1328       "/extensions/platform_apps/isolation/set_cookie.html");
1329   set_cookie_url = set_cookie_url.ReplaceComponents(replace_host);
1330
1331   // The first two partitions will be used to set cookies and ensure they are
1332   // shared. The named partition is used to ensure that cookies are isolated
1333   // between partitions within the same app.
1334   content::WebContents* cookie_contents1;
1335   content::WebContents* cookie_contents2;
1336   content::WebContents* named_partition_contents1;
1337   content::WebContents* named_partition_contents2;
1338
1339   NavigateAndOpenAppForIsolation(set_cookie_url, &cookie_contents1,
1340                                  &cookie_contents2, &named_partition_contents1,
1341                                  &named_partition_contents2, NULL, NULL, NULL);
1342
1343   EXPECT_TRUE(content::ExecuteScript(cookie_contents1, cookie_script1));
1344   EXPECT_TRUE(content::ExecuteScript(cookie_contents2, cookie_script2));
1345
1346   int cookie_size;
1347   std::string cookie_value;
1348
1349   // Test the regular browser context to ensure we have only one cookie.
1350   ui_test_utils::GetCookies(GURL("http://localhost"),
1351                             browser()->tab_strip_model()->GetWebContentsAt(0),
1352                             &cookie_size, &cookie_value);
1353   EXPECT_EQ("testCookie=1", cookie_value);
1354
1355   // The default behavior is to combine webview tags with no explicit partition
1356   // declaration into the same in-memory partition. Test the webview tags to
1357   // ensure we have properly set the cookies and we have both cookies in both
1358   // tags.
1359   ui_test_utils::GetCookies(GURL("http://localhost"),
1360                             cookie_contents1,
1361                             &cookie_size, &cookie_value);
1362   EXPECT_EQ("guest1=true; guest2=true", cookie_value);
1363
1364   ui_test_utils::GetCookies(GURL("http://localhost"),
1365                             cookie_contents2,
1366                             &cookie_size, &cookie_value);
1367   EXPECT_EQ("guest1=true; guest2=true", cookie_value);
1368
1369   // The third tag should not have any cookies as it is in a separate partition.
1370   ui_test_utils::GetCookies(GURL("http://localhost"),
1371                             named_partition_contents1,
1372                             &cookie_size, &cookie_value);
1373   EXPECT_EQ("", cookie_value);
1374 }
1375
1376 // This tests that in-memory storage partitions are reset on browser restart,
1377 // but persistent ones maintain state for cookies and HTML5 storage.
1378 IN_PROC_BROWSER_TEST_F(WebViewTest, PRE_StoragePersistence) {
1379   ASSERT_TRUE(StartEmbeddedTestServer());
1380   const std::string kExpire =
1381       "var expire = new Date(Date.now() + 24 * 60 * 60 * 1000);";
1382   std::string cookie_script1(kExpire);
1383   cookie_script1.append(
1384       "document.cookie = 'inmemory=true; path=/; expires=' + expire + ';';");
1385   std::string cookie_script2(kExpire);
1386   cookie_script2.append(
1387       "document.cookie = 'persist1=true; path=/; expires=' + expire + ';';");
1388   std::string cookie_script3(kExpire);
1389   cookie_script3.append(
1390       "document.cookie = 'persist2=true; path=/; expires=' + expire + ';';");
1391
1392   // We don't care where the main browser is on this test.
1393   GURL blank_url("about:blank");
1394
1395   // The first two partitions will be used to set cookies and ensure they are
1396   // shared. The named partition is used to ensure that cookies are isolated
1397   // between partitions within the same app.
1398   content::WebContents* cookie_contents1;
1399   content::WebContents* cookie_contents2;
1400   content::WebContents* named_partition_contents1;
1401   content::WebContents* named_partition_contents2;
1402   content::WebContents* persistent_partition_contents1;
1403   content::WebContents* persistent_partition_contents2;
1404   content::WebContents* persistent_partition_contents3;
1405   NavigateAndOpenAppForIsolation(blank_url, &cookie_contents1,
1406                                  &cookie_contents2, &named_partition_contents1,
1407                                  &named_partition_contents2,
1408                                  &persistent_partition_contents1,
1409                                  &persistent_partition_contents2,
1410                                  &persistent_partition_contents3);
1411
1412   // Set the inmemory=true cookie for tags with inmemory partitions.
1413   EXPECT_TRUE(content::ExecuteScript(cookie_contents1, cookie_script1));
1414   EXPECT_TRUE(content::ExecuteScript(named_partition_contents1,
1415                                      cookie_script1));
1416
1417   // For the two different persistent storage partitions, set the
1418   // two different cookies so we can check that they aren't comingled below.
1419   EXPECT_TRUE(content::ExecuteScript(persistent_partition_contents1,
1420                                      cookie_script2));
1421
1422   EXPECT_TRUE(content::ExecuteScript(persistent_partition_contents3,
1423                                      cookie_script3));
1424
1425   int cookie_size;
1426   std::string cookie_value;
1427
1428   // Check that all in-memory partitions have a cookie set.
1429   ui_test_utils::GetCookies(GURL("http://localhost"),
1430                             cookie_contents1,
1431                             &cookie_size, &cookie_value);
1432   EXPECT_EQ("inmemory=true", cookie_value);
1433   ui_test_utils::GetCookies(GURL("http://localhost"),
1434                             cookie_contents2,
1435                             &cookie_size, &cookie_value);
1436   EXPECT_EQ("inmemory=true", cookie_value);
1437   ui_test_utils::GetCookies(GURL("http://localhost"),
1438                             named_partition_contents1,
1439                             &cookie_size, &cookie_value);
1440   EXPECT_EQ("inmemory=true", cookie_value);
1441   ui_test_utils::GetCookies(GURL("http://localhost"),
1442                             named_partition_contents2,
1443                             &cookie_size, &cookie_value);
1444   EXPECT_EQ("inmemory=true", cookie_value);
1445
1446   // Check that all persistent partitions kept their state.
1447   ui_test_utils::GetCookies(GURL("http://localhost"),
1448                             persistent_partition_contents1,
1449                             &cookie_size, &cookie_value);
1450   EXPECT_EQ("persist1=true", cookie_value);
1451   ui_test_utils::GetCookies(GURL("http://localhost"),
1452                             persistent_partition_contents2,
1453                             &cookie_size, &cookie_value);
1454   EXPECT_EQ("persist1=true", cookie_value);
1455   ui_test_utils::GetCookies(GURL("http://localhost"),
1456                             persistent_partition_contents3,
1457                             &cookie_size, &cookie_value);
1458   EXPECT_EQ("persist2=true", cookie_value);
1459 }
1460
1461 // This is the post-reset portion of the StoragePersistence test.  See
1462 // PRE_StoragePersistence for main comment.
1463 #if defined(OS_CHROMEOS)
1464 // http://crbug.com/223888
1465 #define MAYBE_StoragePersistence DISABLED_StoragePersistence
1466 #else
1467 #define MAYBE_StoragePersistence StoragePersistence
1468 #endif
1469 IN_PROC_BROWSER_TEST_F(WebViewTest, MAYBE_StoragePersistence) {
1470   ASSERT_TRUE(StartEmbeddedTestServer());
1471
1472   // We don't care where the main browser is on this test.
1473   GURL blank_url("about:blank");
1474
1475   // The first two partitions will be used to set cookies and ensure they are
1476   // shared. The named partition is used to ensure that cookies are isolated
1477   // between partitions within the same app.
1478   content::WebContents* cookie_contents1;
1479   content::WebContents* cookie_contents2;
1480   content::WebContents* named_partition_contents1;
1481   content::WebContents* named_partition_contents2;
1482   content::WebContents* persistent_partition_contents1;
1483   content::WebContents* persistent_partition_contents2;
1484   content::WebContents* persistent_partition_contents3;
1485   NavigateAndOpenAppForIsolation(blank_url, &cookie_contents1,
1486                                  &cookie_contents2, &named_partition_contents1,
1487                                  &named_partition_contents2,
1488                                  &persistent_partition_contents1,
1489                                  &persistent_partition_contents2,
1490                                  &persistent_partition_contents3);
1491
1492   int cookie_size;
1493   std::string cookie_value;
1494
1495   // Check that all in-memory partitions lost their state.
1496   ui_test_utils::GetCookies(GURL("http://localhost"),
1497                             cookie_contents1,
1498                             &cookie_size, &cookie_value);
1499   EXPECT_EQ("", cookie_value);
1500   ui_test_utils::GetCookies(GURL("http://localhost"),
1501                             cookie_contents2,
1502                             &cookie_size, &cookie_value);
1503   EXPECT_EQ("", cookie_value);
1504   ui_test_utils::GetCookies(GURL("http://localhost"),
1505                             named_partition_contents1,
1506                             &cookie_size, &cookie_value);
1507   EXPECT_EQ("", cookie_value);
1508   ui_test_utils::GetCookies(GURL("http://localhost"),
1509                             named_partition_contents2,
1510                             &cookie_size, &cookie_value);
1511   EXPECT_EQ("", cookie_value);
1512
1513   // Check that all persistent partitions kept their state.
1514   ui_test_utils::GetCookies(GURL("http://localhost"),
1515                             persistent_partition_contents1,
1516                             &cookie_size, &cookie_value);
1517   EXPECT_EQ("persist1=true", cookie_value);
1518   ui_test_utils::GetCookies(GURL("http://localhost"),
1519                             persistent_partition_contents2,
1520                             &cookie_size, &cookie_value);
1521   EXPECT_EQ("persist1=true", cookie_value);
1522   ui_test_utils::GetCookies(GURL("http://localhost"),
1523                             persistent_partition_contents3,
1524                             &cookie_size, &cookie_value);
1525   EXPECT_EQ("persist2=true", cookie_value);
1526 }
1527
1528 // This tests DOM storage isolation for packaged apps with webview tags. It
1529 // loads an app with multiple webview tags and each tag sets DOM storage
1530 // entries, which the test checks to ensure proper storage isolation is
1531 // enforced.
1532 IN_PROC_BROWSER_TEST_F(WebViewTest, DOMStorageIsolation) {
1533   ASSERT_TRUE(StartEmbeddedTestServer());
1534   GURL regular_url = embedded_test_server()->GetURL("/title1.html");
1535
1536   std::string output;
1537   std::string get_local_storage("window.domAutomationController.send("
1538       "window.localStorage.getItem('foo') || 'badval')");
1539   std::string get_session_storage("window.domAutomationController.send("
1540       "window.sessionStorage.getItem('bar') || 'badval')");
1541
1542   content::WebContents* default_tag_contents1;
1543   content::WebContents* default_tag_contents2;
1544   content::WebContents* storage_contents1;
1545   content::WebContents* storage_contents2;
1546
1547   NavigateAndOpenAppForIsolation(regular_url, &default_tag_contents1,
1548                                  &default_tag_contents2, &storage_contents1,
1549                                  &storage_contents2, NULL, NULL, NULL);
1550
1551   // Initialize the storage for the first of the two tags that share a storage
1552   // partition.
1553   EXPECT_TRUE(content::ExecuteScript(storage_contents1,
1554                                      "initDomStorage('page1')"));
1555
1556   // Let's test that the expected values are present in the first tag, as they
1557   // will be overwritten once we call the initDomStorage on the second tag.
1558   EXPECT_TRUE(ExecuteScriptAndExtractString(storage_contents1,
1559                                             get_local_storage.c_str(),
1560                                             &output));
1561   EXPECT_STREQ("local-page1", output.c_str());
1562   EXPECT_TRUE(ExecuteScriptAndExtractString(storage_contents1,
1563                                             get_session_storage.c_str(),
1564                                             &output));
1565   EXPECT_STREQ("session-page1", output.c_str());
1566
1567   // Now, init the storage in the second tag in the same storage partition,
1568   // which will overwrite the shared localStorage.
1569   EXPECT_TRUE(content::ExecuteScript(storage_contents2,
1570                                      "initDomStorage('page2')"));
1571
1572   // The localStorage value now should reflect the one written through the
1573   // second tag.
1574   EXPECT_TRUE(ExecuteScriptAndExtractString(storage_contents1,
1575                                             get_local_storage.c_str(),
1576                                             &output));
1577   EXPECT_STREQ("local-page2", output.c_str());
1578   EXPECT_TRUE(ExecuteScriptAndExtractString(storage_contents2,
1579                                             get_local_storage.c_str(),
1580                                             &output));
1581   EXPECT_STREQ("local-page2", output.c_str());
1582
1583   // Session storage is not shared though, as each webview tag has separate
1584   // instance, even if they are in the same storage partition.
1585   EXPECT_TRUE(ExecuteScriptAndExtractString(storage_contents1,
1586                                             get_session_storage.c_str(),
1587                                             &output));
1588   EXPECT_STREQ("session-page1", output.c_str());
1589   EXPECT_TRUE(ExecuteScriptAndExtractString(storage_contents2,
1590                                             get_session_storage.c_str(),
1591                                             &output));
1592   EXPECT_STREQ("session-page2", output.c_str());
1593
1594   // Also, let's check that the main browser and another tag that doesn't share
1595   // the same partition don't have those values stored.
1596   EXPECT_TRUE(ExecuteScriptAndExtractString(
1597       browser()->tab_strip_model()->GetWebContentsAt(0),
1598       get_local_storage.c_str(),
1599       &output));
1600   EXPECT_STREQ("badval", output.c_str());
1601   EXPECT_TRUE(ExecuteScriptAndExtractString(
1602       browser()->tab_strip_model()->GetWebContentsAt(0),
1603       get_session_storage.c_str(),
1604       &output));
1605   EXPECT_STREQ("badval", output.c_str());
1606   EXPECT_TRUE(ExecuteScriptAndExtractString(default_tag_contents1,
1607                                             get_local_storage.c_str(),
1608                                             &output));
1609   EXPECT_STREQ("badval", output.c_str());
1610   EXPECT_TRUE(ExecuteScriptAndExtractString(default_tag_contents1,
1611                                             get_session_storage.c_str(),
1612                                             &output));
1613   EXPECT_STREQ("badval", output.c_str());
1614 }
1615
1616 // This tests IndexedDB isolation for packaged apps with webview tags. It loads
1617 // an app with multiple webview tags and each tag creates an IndexedDB record,
1618 // which the test checks to ensure proper storage isolation is enforced.
1619 IN_PROC_BROWSER_TEST_F(WebViewTest, IndexedDBIsolation) {
1620   ASSERT_TRUE(StartEmbeddedTestServer());
1621   GURL regular_url = embedded_test_server()->GetURL("/title1.html");
1622
1623   content::WebContents* default_tag_contents1;
1624   content::WebContents* default_tag_contents2;
1625   content::WebContents* storage_contents1;
1626   content::WebContents* storage_contents2;
1627
1628   NavigateAndOpenAppForIsolation(regular_url, &default_tag_contents1,
1629                                  &default_tag_contents2, &storage_contents1,
1630                                  &storage_contents2, NULL, NULL, NULL);
1631
1632   // Initialize the storage for the first of the two tags that share a storage
1633   // partition.
1634   ExecuteScriptWaitForTitle(storage_contents1, "initIDB()", "idb created");
1635   ExecuteScriptWaitForTitle(storage_contents1, "addItemIDB(7, 'page1')",
1636                             "addItemIDB complete");
1637   ExecuteScriptWaitForTitle(storage_contents1, "readItemIDB(7)",
1638                             "readItemIDB complete");
1639
1640   std::string output;
1641   std::string get_value(
1642       "window.domAutomationController.send(getValueIDB() || 'badval')");
1643
1644   EXPECT_TRUE(ExecuteScriptAndExtractString(storage_contents1,
1645                                             get_value.c_str(), &output));
1646   EXPECT_STREQ("page1", output.c_str());
1647
1648   // Initialize the db in the second tag.
1649   ExecuteScriptWaitForTitle(storage_contents2, "initIDB()", "idb open");
1650
1651   // Since we share a partition, reading the value should return the existing
1652   // one.
1653   ExecuteScriptWaitForTitle(storage_contents2, "readItemIDB(7)",
1654                             "readItemIDB complete");
1655   EXPECT_TRUE(ExecuteScriptAndExtractString(storage_contents2,
1656                                             get_value.c_str(), &output));
1657   EXPECT_STREQ("page1", output.c_str());
1658
1659   // Now write through the second tag and read it back.
1660   ExecuteScriptWaitForTitle(storage_contents2, "addItemIDB(7, 'page2')",
1661                             "addItemIDB complete");
1662   ExecuteScriptWaitForTitle(storage_contents2, "readItemIDB(7)",
1663                             "readItemIDB complete");
1664   EXPECT_TRUE(ExecuteScriptAndExtractString(storage_contents2,
1665                                             get_value.c_str(), &output));
1666   EXPECT_STREQ("page2", output.c_str());
1667
1668   // Reset the document title, otherwise the next call will not see a change and
1669   // will hang waiting for it.
1670   EXPECT_TRUE(content::ExecuteScript(storage_contents1,
1671                                      "document.title = 'foo'"));
1672
1673   // Read through the first tag to ensure we have the second value.
1674   ExecuteScriptWaitForTitle(storage_contents1, "readItemIDB(7)",
1675                             "readItemIDB complete");
1676   EXPECT_TRUE(ExecuteScriptAndExtractString(storage_contents1,
1677                                             get_value.c_str(), &output));
1678   EXPECT_STREQ("page2", output.c_str());
1679
1680   // Now, let's confirm there is no database in the main browser and another
1681   // tag that doesn't share the same partition. Due to the IndexedDB API design,
1682   // open will succeed, but the version will be 1, since it creates the database
1683   // if it is not found. The two tags use database version 3, so we avoid
1684   // ambiguity.
1685   const char* script =
1686       "indexedDB.open('isolation').onsuccess = function(e) {"
1687       "  if (e.target.result.version == 1)"
1688       "    document.title = 'db not found';"
1689       "  else "
1690       "    document.title = 'error';"
1691       "}";
1692   ExecuteScriptWaitForTitle(browser()->tab_strip_model()->GetWebContentsAt(0),
1693                             script, "db not found");
1694   ExecuteScriptWaitForTitle(default_tag_contents1, script, "db not found");
1695 }
1696
1697 // This test ensures that closing app window on 'loadcommit' does not crash.
1698 // The test launches an app with guest and closes the window on loadcommit. It
1699 // then launches the app window again. The process is repeated 3 times.
1700 // http://crbug.com/291278
1701 #if defined(OS_WIN)
1702 #define MAYBE_CloseOnLoadcommit DISABLED_CloseOnLoadcommit
1703 #else
1704 #define MAYBE_CloseOnLoadcommit CloseOnLoadcommit
1705 #endif
1706 IN_PROC_BROWSER_TEST_F(WebViewTest, MAYBE_CloseOnLoadcommit) {
1707   LoadAndLaunchPlatformApp("web_view/close_on_loadcommit",
1708                            "done-close-on-loadcommit");
1709 }
1710
1711 IN_PROC_BROWSER_TEST_F(WebViewTest, MediaAccessAPIDeny_TestDeny) {
1712   MediaAccessAPIDenyTestHelper("testDeny");
1713 }
1714
1715 IN_PROC_BROWSER_TEST_F(WebViewTest,
1716                        MediaAccessAPIDeny_TestDenyThenAllowThrows) {
1717   MediaAccessAPIDenyTestHelper("testDenyThenAllowThrows");
1718
1719 }
1720
1721 IN_PROC_BROWSER_TEST_F(WebViewTest,
1722                        MediaAccessAPIDeny_TestDenyWithPreventDefault) {
1723   MediaAccessAPIDenyTestHelper("testDenyWithPreventDefault");
1724 }
1725
1726 IN_PROC_BROWSER_TEST_F(WebViewTest,
1727                        MediaAccessAPIDeny_TestNoListenersImplyDeny) {
1728   MediaAccessAPIDenyTestHelper("testNoListenersImplyDeny");
1729 }
1730
1731 IN_PROC_BROWSER_TEST_F(WebViewTest,
1732                        MediaAccessAPIDeny_TestNoPreventDefaultImpliesDeny) {
1733   MediaAccessAPIDenyTestHelper("testNoPreventDefaultImpliesDeny");
1734 }
1735
1736 void WebViewTest::MediaAccessAPIAllowTestHelper(const std::string& test_name) {
1737   ASSERT_TRUE(StartEmbeddedTestServer());  // For serving guest pages.
1738   LoadAndLaunchPlatformApp("web_view/media_access/allow", "Launched");
1739
1740   content::WebContents* embedder_web_contents = GetFirstAppWindowWebContents();
1741   ASSERT_TRUE(embedder_web_contents);
1742   scoped_ptr<MockWebContentsDelegate> mock(new MockWebContentsDelegate());
1743   embedder_web_contents->SetDelegate(mock.get());
1744
1745   ExtensionTestMessageListener done_listener("TEST_PASSED", false);
1746   done_listener.set_failure_message("TEST_FAILED");
1747   EXPECT_TRUE(
1748       content::ExecuteScript(
1749           embedder_web_contents,
1750           base::StringPrintf("startAllowTest('%s')",
1751                              test_name.c_str())));
1752   ASSERT_TRUE(done_listener.WaitUntilSatisfied());
1753
1754   mock->WaitForSetMediaPermission();
1755 }
1756
1757 IN_PROC_BROWSER_TEST_F(WebViewTest, ContextMenusAPI_Basic) {
1758   LoadAppWithGuest("web_view/context_menus/basic");
1759
1760   content::WebContents* guest_web_contents = GetGuestWebContents();
1761   content::WebContents* embedder = GetEmbedderWebContents();
1762   ASSERT_TRUE(embedder);
1763
1764   // 1. Basic property test.
1765   ExecuteScriptWaitForTitle(embedder, "checkProperties()", "ITEM_CHECKED");
1766
1767   // 2. Create a menu item and wait for created callback to be called.
1768   ExecuteScriptWaitForTitle(embedder, "createMenuItem()", "ITEM_CREATED");
1769
1770   // 3. Click the created item, wait for the click handlers to fire from JS.
1771   ExtensionTestMessageListener click_listener("ITEM_CLICKED", false);
1772   GURL page_url("http://www.google.com");
1773   // Create and build our test context menu.
1774   scoped_ptr<TestRenderViewContextMenu> menu(TestRenderViewContextMenu::Create(
1775       guest_web_contents, page_url, GURL(), GURL()));
1776
1777   // Look for the extension item in the menu, and execute it.
1778   int command_id = ContextMenuMatcher::ConvertToExtensionsCustomCommandId(0);
1779   ASSERT_TRUE(menu->IsCommandIdEnabled(command_id));
1780   menu->ExecuteCommand(command_id, 0);
1781
1782   // Wait for embedder's script to tell us its onclick fired, it does
1783   // chrome.test.sendMessage('ITEM_CLICKED')
1784   ASSERT_TRUE(click_listener.WaitUntilSatisfied());
1785
1786   // 4. Update the item's title and verify.
1787   ExecuteScriptWaitForTitle(embedder, "updateMenuItem()", "ITEM_UPDATED");
1788   MenuItem::List items = GetItems();
1789   ASSERT_EQ(1u, items.size());
1790   MenuItem* item = items.at(0);
1791   EXPECT_EQ("new_title", item->title());
1792
1793   // 5. Remove the item.
1794   ExecuteScriptWaitForTitle(embedder, "removeItem()", "ITEM_REMOVED");
1795   MenuItem::List items_after_removal = GetItems();
1796   ASSERT_EQ(0u, items_after_removal.size());
1797
1798   // 6. Add some more items.
1799   ExecuteScriptWaitForTitle(
1800       embedder, "createThreeMenuItems()", "ITEM_MULTIPLE_CREATED");
1801   MenuItem::List items_after_insertion = GetItems();
1802   ASSERT_EQ(3u, items_after_insertion.size());
1803
1804   // 7. Test removeAll().
1805   ExecuteScriptWaitForTitle(embedder, "removeAllItems()", "ITEM_ALL_REMOVED");
1806   MenuItem::List items_after_all_removal = GetItems();
1807   ASSERT_EQ(0u, items_after_all_removal.size());
1808 }
1809
1810 IN_PROC_BROWSER_TEST_F(WebViewTest, MediaAccessAPIAllow_TestAllow) {
1811   MediaAccessAPIAllowTestHelper("testAllow");
1812 }
1813
1814 IN_PROC_BROWSER_TEST_F(WebViewTest, MediaAccessAPIAllow_TestAllowAndThenDeny) {
1815   MediaAccessAPIAllowTestHelper("testAllowAndThenDeny");
1816 }
1817
1818 IN_PROC_BROWSER_TEST_F(WebViewTest, MediaAccessAPIAllow_TestAllowTwice) {
1819   MediaAccessAPIAllowTestHelper("testAllowTwice");
1820 }
1821
1822 IN_PROC_BROWSER_TEST_F(WebViewTest, MediaAccessAPIAllow_TestAllowAsync) {
1823   MediaAccessAPIAllowTestHelper("testAllowAsync");
1824 }
1825
1826 // Checks that window.screenX/screenY/screenLeft/screenTop works correctly for
1827 // guests.
1828 IN_PROC_BROWSER_TEST_F(WebViewTest, ScreenCoordinates) {
1829   ASSERT_TRUE(RunPlatformAppTestWithArg(
1830       "platform_apps/web_view/common", "screen_coordinates"))
1831           << message_;
1832 }
1833
1834 #if defined(OS_CHROMEOS)
1835 IN_PROC_BROWSER_TEST_F(WebViewTest, ChromeVoxInjection) {
1836   EXPECT_FALSE(
1837       chromeos::AccessibilityManager::Get()->IsSpokenFeedbackEnabled());
1838
1839   ASSERT_TRUE(StartEmbeddedTestServer());
1840   content::WebContents* guest_web_contents = LoadGuest(
1841       "/extensions/platform_apps/web_view/chromevox_injection/guest.html",
1842       "web_view/chromevox_injection");
1843   ASSERT_TRUE(guest_web_contents);
1844
1845   chromeos::SpeechMonitor monitor;
1846   chromeos::AccessibilityManager::Get()->EnableSpokenFeedback(
1847       true, ash::A11Y_NOTIFICATION_NONE);
1848   EXPECT_TRUE(monitor.SkipChromeVoxEnabledMessage());
1849
1850   EXPECT_EQ("chrome vox test title", monitor.GetNextUtterance());
1851 }
1852 #endif
1853
1854 // Flaky on Windows. http://crbug.com/303966
1855 #if defined(OS_WIN)
1856 #define MAYBE_TearDownTest DISABLED_TearDownTest
1857 #else
1858 #define MAYBE_TearDownTest TearDownTest
1859 #endif
1860 IN_PROC_BROWSER_TEST_F(WebViewTest, MAYBE_TearDownTest) {
1861   const extensions::Extension* extension =
1862       LoadAndLaunchPlatformApp("web_view/teardown", "guest-loaded");
1863   apps::AppWindow* window = NULL;
1864   if (!GetAppWindowCount())
1865     window = CreateAppWindow(extension);
1866   else
1867     window = GetFirstAppWindow();
1868   CloseAppWindow(window);
1869
1870   // Load the app again.
1871   LoadAndLaunchPlatformApp("web_view/teardown", "guest-loaded");
1872 }
1873
1874 // In following GeolocationAPIEmbedderHasNoAccess* tests, embedder (i.e. the
1875 // platform app) does not have geolocation permission for this test.
1876 // No matter what the API does, geolocation permission would be denied.
1877 // Note that the test name prefix must be "GeolocationAPI".
1878 IN_PROC_BROWSER_TEST_F(WebViewTest, GeolocationAPIEmbedderHasNoAccessAllow) {
1879   TestHelper("testDenyDenies",
1880              "web_view/geolocation/embedder_has_no_permission",
1881              NEEDS_TEST_SERVER);
1882 }
1883
1884 IN_PROC_BROWSER_TEST_F(WebViewTest, GeolocationAPIEmbedderHasNoAccessDeny) {
1885   TestHelper("testDenyDenies",
1886              "web_view/geolocation/embedder_has_no_permission",
1887              NEEDS_TEST_SERVER);
1888 }
1889
1890 // In following GeolocationAPIEmbedderHasAccess* tests, embedder (i.e. the
1891 // platform app) has geolocation permission
1892 //
1893 // Note that these test names must be "GeolocationAPI" prefixed (b/c we mock out
1894 // geolocation in this case).
1895 //
1896 // Also note that these are run separately because OverrideGeolocation() doesn't
1897 // mock out geolocation for multiple navigator.geolocation calls properly and
1898 // the tests become flaky.
1899 // GeolocationAPI* test 1 of 3.
1900 IN_PROC_BROWSER_TEST_F(WebViewTest, GeolocationAPIEmbedderHasAccessAllow) {
1901   TestHelper("testAllow",
1902              "web_view/geolocation/embedder_has_permission",
1903              NEEDS_TEST_SERVER);
1904 }
1905
1906 // GeolocationAPI* test 2 of 3.
1907 IN_PROC_BROWSER_TEST_F(WebViewTest, GeolocationAPIEmbedderHasAccessDeny) {
1908   TestHelper("testDeny",
1909              "web_view/geolocation/embedder_has_permission",
1910              NEEDS_TEST_SERVER);
1911 }
1912
1913 // GeolocationAPI* test 3 of 3.
1914 IN_PROC_BROWSER_TEST_F(WebViewTest,
1915                        GeolocationAPIEmbedderHasAccessMultipleBridgeIdAllow) {
1916   TestHelper("testMultipleBridgeIdAllow",
1917              "web_view/geolocation/embedder_has_permission",
1918              NEEDS_TEST_SERVER);
1919 }
1920
1921 // Tests that
1922 // BrowserPluginGeolocationPermissionContext::CancelGeolocationPermissionRequest
1923 // is handled correctly (and does not crash).
1924 IN_PROC_BROWSER_TEST_F(WebViewTest, GeolocationAPICancelGeolocation) {
1925   ASSERT_TRUE(StartEmbeddedTestServer());  // For serving guest pages.
1926   ASSERT_TRUE(RunPlatformAppTest(
1927         "platform_apps/web_view/geolocation/cancel_request")) << message_;
1928 }
1929
1930 IN_PROC_BROWSER_TEST_F(WebViewTest, DISABLED_GeolocationRequestGone) {
1931   ASSERT_TRUE(StartEmbeddedTestServer());  // For serving guest pages.
1932   ASSERT_TRUE(RunPlatformAppTest(
1933         "platform_apps/web_view/geolocation/geolocation_request_gone"))
1934             << message_;
1935 }
1936
1937 // In following FilesystemAPIRequestFromMainThread* tests, guest request
1938 // filesystem access from main thread of the guest.
1939 // FileSystemAPIRequestFromMainThread* test 1 of 3
1940 IN_PROC_BROWSER_TEST_F(WebViewTest, FileSystemAPIRequestFromMainThreadAllow) {
1941   TestHelper("testAllow", "web_view/filesystem/main", NEEDS_TEST_SERVER);
1942 }
1943
1944 // FileSystemAPIRequestFromMainThread* test 2 of 3.
1945 IN_PROC_BROWSER_TEST_F(WebViewTest, FileSystemAPIRequestFromMainThreadDeny) {
1946   TestHelper("testDeny", "web_view/filesystem/main", NEEDS_TEST_SERVER);
1947 }
1948
1949 // FileSystemAPIRequestFromMainThread* test 3 of 3.
1950 IN_PROC_BROWSER_TEST_F(WebViewTest,
1951                        FileSystemAPIRequestFromMainThreadDefaultAllow) {
1952   TestHelper("testDefaultAllow", "web_view/filesystem/main", NEEDS_TEST_SERVER);
1953 }
1954
1955 // In following FilesystemAPIRequestFromWorker* tests, guest create a worker
1956 // to request filesystem access from worker thread.
1957 // FileSystemAPIRequestFromWorker* test 1 of 3
1958 IN_PROC_BROWSER_TEST_F(WebViewTest, FileSystemAPIRequestFromWorkerAllow) {
1959   TestHelper("testAllow", "web_view/filesystem/worker", NEEDS_TEST_SERVER);
1960 }
1961
1962 // FileSystemAPIRequestFromWorker* test 2 of 3.
1963 IN_PROC_BROWSER_TEST_F(WebViewTest, FileSystemAPIRequestFromWorkerDeny) {
1964   TestHelper("testDeny", "web_view/filesystem/worker", NEEDS_TEST_SERVER);
1965 }
1966
1967 // FileSystemAPIRequestFromWorker* test 3 of 3.
1968 IN_PROC_BROWSER_TEST_F(WebViewTest,
1969                        FileSystemAPIRequestFromWorkerDefaultAllow) {
1970   TestHelper(
1971       "testDefaultAllow", "web_view/filesystem/worker", NEEDS_TEST_SERVER);
1972 }
1973
1974 // In following FilesystemAPIRequestFromSharedWorkerOfSingleWebViewGuest* tests,
1975 // embedder contains a single webview guest. The guest creates a shared worker
1976 // to request filesystem access from worker thread.
1977 // FileSystemAPIRequestFromSharedWorkerOfSingleWebViewGuest* test 1 of 3
1978 IN_PROC_BROWSER_TEST_F(
1979     WebViewTest,
1980     FileSystemAPIRequestFromSharedWorkerOfSingleWebViewGuestAllow) {
1981   TestHelper("testAllow",
1982              "web_view/filesystem/shared_worker/single",
1983              NEEDS_TEST_SERVER);
1984 }
1985
1986 // FileSystemAPIRequestFromSharedWorkerOfSingleWebViewGuest* test 2 of 3.
1987 IN_PROC_BROWSER_TEST_F(
1988     WebViewTest,
1989     FileSystemAPIRequestFromSharedWorkerOfSingleWebViewGuestDeny) {
1990   TestHelper("testDeny",
1991              "web_view/filesystem/shared_worker/single",
1992              NEEDS_TEST_SERVER);
1993 }
1994
1995 // FileSystemAPIRequestFromSharedWorkerOfSingleWebViewGuest* test 3 of 3.
1996 IN_PROC_BROWSER_TEST_F(
1997     WebViewTest,
1998     FileSystemAPIRequestFromSharedWorkerOfSingleWebViewGuestDefaultAllow) {
1999   TestHelper(
2000       "testDefaultAllow",
2001       "web_view/filesystem/shared_worker/single",
2002       NEEDS_TEST_SERVER);
2003 }
2004
2005 // In following FilesystemAPIRequestFromSharedWorkerOfMultiWebViewGuests* tests,
2006 // embedder contains mutiple webview guests. Each guest creates a shared worker
2007 // to request filesystem access from worker thread.
2008 // FileSystemAPIRequestFromSharedWorkerOfMultiWebViewGuests* test 1 of 3
2009 IN_PROC_BROWSER_TEST_F(
2010     WebViewTest,
2011     FileSystemAPIRequestFromSharedWorkerOfMultiWebViewGuestsAllow) {
2012   TestHelper("testAllow",
2013              "web_view/filesystem/shared_worker/multiple",
2014              NEEDS_TEST_SERVER);
2015 }
2016
2017 // FileSystemAPIRequestFromSharedWorkerOfMultiWebViewGuests* test 2 of 3.
2018 IN_PROC_BROWSER_TEST_F(
2019     WebViewTest,
2020     FileSystemAPIRequestFromSharedWorkerOfMultiWebViewGuestsDeny) {
2021   TestHelper("testDeny",
2022              "web_view/filesystem/shared_worker/multiple",
2023              NEEDS_TEST_SERVER);
2024 }
2025
2026 // FileSystemAPIRequestFromSharedWorkerOfMultiWebViewGuests* test 3 of 3.
2027 IN_PROC_BROWSER_TEST_F(
2028     WebViewTest,
2029     FileSystemAPIRequestFromSharedWorkerOfMultiWebViewGuestsDefaultAllow) {
2030   TestHelper(
2031       "testDefaultAllow",
2032       "web_view/filesystem/shared_worker/multiple",
2033       NEEDS_TEST_SERVER);
2034 }
2035
2036 IN_PROC_BROWSER_TEST_F(WebViewTest, ClearData) {
2037 #if defined(OS_WIN)
2038   // Flaky on XP bot http://crbug.com/282674
2039   if (base::win::GetVersion() <= base::win::VERSION_XP)
2040     return;
2041 #endif
2042
2043   ASSERT_TRUE(StartEmbeddedTestServer());  // For serving guest pages.
2044   ASSERT_TRUE(RunPlatformAppTestWithArg(
2045       "platform_apps/web_view/common", "cleardata"))
2046           << message_;
2047 }
2048
2049 // This test is disabled on Win due to being flaky. http://crbug.com/294592
2050 #if defined(OS_WIN)
2051 #define MAYBE_ConsoleMessage DISABLED_ConsoleMessage
2052 #else
2053 #define MAYBE_ConsoleMessage ConsoleMessage
2054 #endif
2055 IN_PROC_BROWSER_TEST_F(WebViewTest, MAYBE_ConsoleMessage) {
2056   ASSERT_TRUE(RunPlatformAppTestWithArg(
2057       "platform_apps/web_view/common", "console_messages"))
2058           << message_;
2059 }
2060
2061 IN_PROC_BROWSER_TEST_F(WebViewTest, DownloadPermission) {
2062   ASSERT_TRUE(StartEmbeddedTestServer());  // For serving guest pages.
2063   content::WebContents* guest_web_contents =
2064       LoadGuest("/extensions/platform_apps/web_view/download/guest.html",
2065                 "web_view/download");
2066   ASSERT_TRUE(guest_web_contents);
2067
2068   // Replace WebContentsDelegate with mock version so we can intercept download
2069   // requests.
2070   content::WebContentsDelegate* delegate = guest_web_contents->GetDelegate();
2071   scoped_ptr<MockDownloadWebContentsDelegate>
2072       mock_delegate(new MockDownloadWebContentsDelegate(delegate));
2073   guest_web_contents->SetDelegate(mock_delegate.get());
2074
2075   // Start test.
2076   // 1. Guest requests a download that its embedder denies.
2077   EXPECT_TRUE(content::ExecuteScript(guest_web_contents,
2078                                      "startDownload('download-link-1')"));
2079   mock_delegate->WaitForCanDownload(false); // Expect to not allow.
2080   mock_delegate->Reset();
2081
2082   // 2. Guest requests a download that its embedder allows.
2083   EXPECT_TRUE(content::ExecuteScript(guest_web_contents,
2084                                      "startDownload('download-link-2')"));
2085   mock_delegate->WaitForCanDownload(true); // Expect to allow.
2086   mock_delegate->Reset();
2087
2088   // 3. Guest requests a download that its embedder ignores, this implies deny.
2089   EXPECT_TRUE(content::ExecuteScript(guest_web_contents,
2090                                      "startDownload('download-link-3')"));
2091   mock_delegate->WaitForCanDownload(false); // Expect to not allow.
2092 }
2093
2094 // This test makes sure loading <webview> does not crash when there is an
2095 // extension which has content script whitelisted/forced.
2096 IN_PROC_BROWSER_TEST_F(WebViewTest, WhitelistedContentScript) {
2097   // Whitelist the extension for running content script we are going to load.
2098   extensions::ExtensionsClient::ScriptingWhitelist whitelist;
2099   const std::string extension_id = "imeongpbjoodlnmlakaldhlcmijmhpbb";
2100   whitelist.push_back(extension_id);
2101   extensions::ExtensionsClient::Get()->SetScriptingWhitelist(whitelist);
2102
2103   // Load the extension.
2104   const extensions::Extension* content_script_whitelisted_extension =
2105       LoadExtension(test_data_dir_.AppendASCII(
2106                         "platform_apps/web_view/extension_api/content_script"));
2107   ASSERT_TRUE(content_script_whitelisted_extension);
2108   ASSERT_EQ(extension_id, content_script_whitelisted_extension->id());
2109
2110   // Now load an app with <webview>.
2111   LoadAndLaunchPlatformApp("web_view/content_script_whitelisted",
2112                            "TEST_PASSED");
2113 }
2114
2115 IN_PROC_BROWSER_TEST_F(WebViewTest, SetPropertyOnDocumentReady) {
2116   ASSERT_TRUE(RunPlatformAppTest("platform_apps/web_view/document_ready"))
2117                   << message_;
2118 }
2119
2120 IN_PROC_BROWSER_TEST_F(WebViewTest, SetPropertyOnDocumentInteractive) {
2121   ASSERT_TRUE(RunPlatformAppTest("platform_apps/web_view/document_interactive"))
2122                   << message_;
2123 }
2124
2125 IN_PROC_BROWSER_TEST_F(WebViewTest, SpeechRecognitionAPI_HasPermissionAllow) {
2126   ASSERT_TRUE(
2127       RunPlatformAppTestWithArg("platform_apps/web_view/speech_recognition_api",
2128                                 "allowTest"))
2129           << message_;
2130 }
2131
2132 IN_PROC_BROWSER_TEST_F(WebViewTest, SpeechRecognitionAPI_HasPermissionDeny) {
2133   ASSERT_TRUE(
2134       RunPlatformAppTestWithArg("platform_apps/web_view/speech_recognition_api",
2135                                 "denyTest"))
2136           << message_;
2137 }
2138
2139 IN_PROC_BROWSER_TEST_F(WebViewTest, SpeechRecognitionAPI_NoPermission) {
2140   ASSERT_TRUE(
2141       RunPlatformAppTestWithArg("platform_apps/web_view/common",
2142                                 "speech_recognition_api_no_permission"))
2143           << message_;
2144 }
2145
2146 // Tests overriding user agent.
2147 IN_PROC_BROWSER_TEST_F(WebViewTest, UserAgent) {
2148   ASSERT_TRUE(RunPlatformAppTestWithArg(
2149               "platform_apps/web_view/common", "useragent")) << message_;
2150 }
2151
2152 IN_PROC_BROWSER_TEST_F(WebViewTest, UserAgent_NewWindow) {
2153   ASSERT_TRUE(RunPlatformAppTestWithArg(
2154               "platform_apps/web_view/common",
2155               "useragent_newwindow")) << message_;
2156 }
2157
2158 IN_PROC_BROWSER_TEST_F(WebViewTest, NoPermission) {
2159   ASSERT_TRUE(RunPlatformAppTest("platform_apps/web_view/nopermission"))
2160                   << message_;
2161 }
2162
2163 IN_PROC_BROWSER_TEST_F(WebViewTest, Dialog_TestAlertDialog) {
2164   TestHelper("testAlertDialog", "web_view/dialog", NO_TEST_SERVER);
2165 }
2166
2167 IN_PROC_BROWSER_TEST_F(WebViewTest, TestConfirmDialog) {
2168   TestHelper("testConfirmDialog", "web_view/dialog", NO_TEST_SERVER);
2169 }
2170
2171 IN_PROC_BROWSER_TEST_F(WebViewTest, Dialog_TestConfirmDialogCancel) {
2172   TestHelper("testConfirmDialogCancel", "web_view/dialog", NO_TEST_SERVER);
2173 }
2174
2175 IN_PROC_BROWSER_TEST_F(WebViewTest, Dialog_TestConfirmDialogDefaultCancel) {
2176   TestHelper("testConfirmDialogDefaultCancel",
2177              "web_view/dialog",
2178              NO_TEST_SERVER);
2179 }
2180
2181 IN_PROC_BROWSER_TEST_F(WebViewTest, Dialog_TestConfirmDialogDefaultGCCancel) {
2182   TestHelper("testConfirmDialogDefaultGCCancel",
2183              "web_view/dialog",
2184              NO_TEST_SERVER);
2185 }
2186
2187 IN_PROC_BROWSER_TEST_F(WebViewTest, Dialog_TestPromptDialog) {
2188   TestHelper("testPromptDialog", "web_view/dialog", NO_TEST_SERVER);
2189 }
2190
2191 IN_PROC_BROWSER_TEST_F(WebViewTest, NoContentSettingsAPI) {
2192   // Load the extension.
2193   const extensions::Extension* content_settings_extension =
2194       LoadExtension(
2195           test_data_dir_.AppendASCII(
2196               "platform_apps/web_view/extension_api/content_settings"));
2197   ASSERT_TRUE(content_settings_extension);
2198   TestHelper("testPostMessageCommChannel", "web_view/shim", NO_TEST_SERVER);
2199 }
2200
2201 #if defined(ENABLE_PLUGINS)
2202 class WebViewPluginTest : public WebViewTest {
2203  protected:
2204   virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
2205     WebViewTest::SetUpCommandLine(command_line);
2206
2207     // Append the switch to register the pepper plugin.
2208     // library name = <out dir>/<test_name>.<library_extension>
2209     // MIME type = application/x-ppapi-<test_name>
2210     base::FilePath plugin_dir;
2211     EXPECT_TRUE(PathService::Get(base::DIR_MODULE, &plugin_dir));
2212
2213     base::FilePath plugin_lib = plugin_dir.Append(library_name);
2214     EXPECT_TRUE(base::PathExists(plugin_lib));
2215     base::FilePath::StringType pepper_plugin = plugin_lib.value();
2216     pepper_plugin.append(FILE_PATH_LITERAL(";application/x-ppapi-tests"));
2217     command_line->AppendSwitchNative(switches::kRegisterPepperPlugins,
2218                                      pepper_plugin);
2219   }
2220 };
2221
2222 IN_PROC_BROWSER_TEST_F(WebViewPluginTest, TestLoadPluginEvent) {
2223   TestHelper("testPluginLoadPermission", "web_view/shim", NO_TEST_SERVER);
2224 }
2225 #endif  // defined(ENABLE_PLUGINS)
2226
2227 class WebViewCaptureTest : public WebViewTest {
2228  public:
2229   WebViewCaptureTest() {}
2230   virtual ~WebViewCaptureTest() {}
2231   virtual void SetUp() OVERRIDE {
2232     EnablePixelOutput();
2233     WebViewTest::SetUp();
2234   }
2235 };
2236
2237 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestZoomAPI) {
2238   TestHelper("testZoomAPI", "web_view/shim", NO_TEST_SERVER);
2239 }
2240
2241 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestFindAPI) {
2242   TestHelper("testFindAPI", "web_view/shim", NO_TEST_SERVER);
2243 }
2244
2245 IN_PROC_BROWSER_TEST_F(WebViewTest, Shim_TestFindAPI_findupdate) {
2246   TestHelper("testFindAPI_findupdate", "web_view/shim", NO_TEST_SERVER);
2247 }
2248
2249 // <webview> screenshot capture fails with ubercomp.
2250 // See http://crbug.com/327035.
2251 IN_PROC_BROWSER_TEST_F(WebViewCaptureTest,
2252                        DISABLED_Shim_ScreenshotCapture) {
2253   TestHelper("testScreenshotCapture", "web_view/shim", NO_TEST_SERVER);
2254 }
2255
2256 #if defined(OS_WIN)
2257 // Test is disabled on Windows because it times out often.
2258 // http://crbug.com/403325
2259 #define MAYBE_WebViewInBackgroundPage \
2260     DISABLED_WebViewInBackgroundPage
2261 #else
2262 #define MAYBE_WebViewInBackgroundPage WebViewInBackgroundPage
2263 #endif
2264 IN_PROC_BROWSER_TEST_F(WebViewTest, MAYBE_WebViewInBackgroundPage) {
2265   ASSERT_TRUE(RunExtensionTest("platform_apps/web_view/background"))
2266       << message_;
2267 }