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