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