Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / chrome / browser / apps / app_browsertest.cc
1 // Copyright 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "apps/app_window.h"
6 #include "apps/app_window_registry.h"
7 #include "apps/common/api/app_runtime.h"
8 #include "apps/launcher.h"
9 #include "apps/ui/native_app_window.h"
10 #include "base/bind.h"
11 #include "base/command_line.h"
12 #include "base/file_util.h"
13 #include "base/files/scoped_temp_dir.h"
14 #include "base/prefs/pref_service.h"
15 #include "base/stl_util.h"
16 #include "base/strings/utf_string_conversions.h"
17 #include "chrome/app/chrome_command_ids.h"
18 #include "chrome/browser/apps/app_browsertest_util.h"
19 #include "chrome/browser/chrome_notification_types.h"
20 #include "chrome/browser/devtools/devtools_window.h"
21 #include "chrome/browser/extensions/api/permissions/permissions_api.h"
22 #include "chrome/browser/extensions/component_loader.h"
23 #include "chrome/browser/extensions/extension_browsertest.h"
24 #include "chrome/browser/extensions/extension_service.h"
25 #include "chrome/browser/extensions/extension_test_message_listener.h"
26 #include "chrome/browser/renderer_context_menu/render_view_context_menu.h"
27 #include "chrome/browser/ui/browser.h"
28 #include "chrome/browser/ui/extensions/application_launch.h"
29 #include "chrome/browser/ui/tabs/tab_strip_model.h"
30 #include "chrome/browser/ui/webui/print_preview/print_preview_ui.h"
31 #include "chrome/common/chrome_switches.h"
32 #include "chrome/common/pref_names.h"
33 #include "chrome/common/url_constants.h"
34 #include "chrome/test/base/test_switches.h"
35 #include "chrome/test/base/ui_test_utils.h"
36 #include "components/user_prefs/pref_registry_syncable.h"
37 #include "components/web_modal/web_contents_modal_dialog_manager.h"
38 #include "content/public/browser/devtools_agent_host.h"
39 #include "content/public/browser/render_process_host.h"
40 #include "content/public/browser/render_widget_host_view.h"
41 #include "content/public/test/test_utils.h"
42 #include "extensions/browser/event_router.h"
43 #include "extensions/browser/extension_system.h"
44 #include "extensions/browser/pref_names.h"
45 #include "net/test/embedded_test_server/embedded_test_server.h"
46 #include "url/gurl.h"
47
48 #if defined(OS_CHROMEOS)
49 #include "base/memory/scoped_ptr.h"
50 #include "chrome/browser/chromeos/login/mock_user_manager.h"
51 #include "chrome/browser/chromeos/login/user_manager.h"
52 #include "chromeos/dbus/dbus_thread_manager.h"
53 #include "chromeos/dbus/fake_dbus_thread_manager.h"
54 #include "chromeos/dbus/fake_power_manager_client.h"
55 #endif
56
57 using apps::AppWindow;
58 using apps::AppWindowRegistry;
59 using content::WebContents;
60 using web_modal::WebContentsModalDialogManager;
61
62 namespace app_runtime = apps::api::app_runtime;
63
64 namespace extensions {
65
66 namespace {
67
68 // Non-abstract RenderViewContextMenu class.
69 class PlatformAppContextMenu : public RenderViewContextMenu {
70  public:
71   PlatformAppContextMenu(content::RenderFrameHost* render_frame_host,
72                          const content::ContextMenuParams& params)
73       : RenderViewContextMenu(render_frame_host, params) {}
74
75   bool HasCommandWithId(int command_id) {
76     return menu_model_.GetIndexOfCommandId(command_id) != -1;
77   }
78
79  protected:
80   // RenderViewContextMenu implementation.
81   virtual bool GetAcceleratorForCommandId(
82       int command_id,
83       ui::Accelerator* accelerator) OVERRIDE {
84     return false;
85   }
86   virtual void PlatformInit() OVERRIDE {}
87   virtual void PlatformCancel() OVERRIDE {}
88 };
89
90 // This class keeps track of tabs as they are added to the browser. It will be
91 // "done" (i.e. won't block on Wait()) once |observations| tabs have been added.
92 class TabsAddedNotificationObserver
93     : public content::WindowedNotificationObserver {
94  public:
95   explicit TabsAddedNotificationObserver(size_t observations)
96       : content::WindowedNotificationObserver(
97             chrome::NOTIFICATION_TAB_ADDED,
98             content::NotificationService::AllSources()),
99         observations_(observations) {
100   }
101
102   virtual void Observe(int type,
103                        const content::NotificationSource& source,
104                        const content::NotificationDetails& details) OVERRIDE {
105     observed_tabs_.push_back(
106         content::Details<WebContents>(details).ptr());
107     if (observed_tabs_.size() == observations_)
108       content::WindowedNotificationObserver::Observe(type, source, details);
109   }
110
111   const std::vector<content::WebContents*>& tabs() { return observed_tabs_; }
112
113  private:
114   size_t observations_;
115   std::vector<content::WebContents*> observed_tabs_;
116
117   DISALLOW_COPY_AND_ASSIGN(TabsAddedNotificationObserver);
118 };
119
120 class ScopedPreviewTestingDelegate : PrintPreviewUI::TestingDelegate {
121  public:
122   explicit ScopedPreviewTestingDelegate(bool auto_cancel)
123       : auto_cancel_(auto_cancel),
124         total_page_count_(1),
125         rendered_page_count_(0) {
126     PrintPreviewUI::SetDelegateForTesting(this);
127   }
128
129   ~ScopedPreviewTestingDelegate() {
130     PrintPreviewUI::SetDelegateForTesting(NULL);
131   }
132
133   // PrintPreviewUI::TestingDelegate implementation.
134   virtual bool IsAutoCancelEnabled() OVERRIDE {
135     return auto_cancel_;
136   }
137
138   // PrintPreviewUI::TestingDelegate implementation.
139   virtual void DidGetPreviewPageCount(int page_count) OVERRIDE {
140     total_page_count_ = page_count;
141   }
142
143   // PrintPreviewUI::TestingDelegate implementation.
144   virtual void DidRenderPreviewPage(content::WebContents* preview_dialog)
145       OVERRIDE {
146     dialog_size_ = preview_dialog->GetContainerBounds().size();
147     ++rendered_page_count_;
148     CHECK(rendered_page_count_ <= total_page_count_);
149     if (waiting_runner_ && rendered_page_count_ == total_page_count_) {
150       waiting_runner_->Quit();
151     }
152   }
153
154   void WaitUntilPreviewIsReady() {
155     CHECK(!waiting_runner_);
156     if (rendered_page_count_ < total_page_count_) {
157       waiting_runner_ = new content::MessageLoopRunner;
158       waiting_runner_->Run();
159       waiting_runner_ = NULL;
160     }
161   }
162
163   gfx::Size dialog_size() {
164     return dialog_size_;
165   }
166
167  private:
168   bool auto_cancel_;
169   int total_page_count_;
170   int rendered_page_count_;
171   scoped_refptr<content::MessageLoopRunner> waiting_runner_;
172   gfx::Size dialog_size_;
173 };
174
175 #if !defined(OS_CHROMEOS) && !defined(OS_WIN)
176 bool CopyTestDataAndSetCommandLineArg(
177     const base::FilePath& test_data_file,
178     const base::FilePath& temp_dir,
179     const char* filename) {
180   base::FilePath path = temp_dir.AppendASCII(
181       filename).NormalizePathSeparators();
182   if (!(base::CopyFile(test_data_file, path)))
183     return false;
184
185   CommandLine* command_line = CommandLine::ForCurrentProcess();
186   command_line->AppendArgPath(path);
187   return true;
188 }
189 #endif  // !defined(OS_CHROMEOS) && !defined(OS_WIN)
190
191 #if !defined(OS_CHROMEOS)
192 const char kTestFilePath[] = "platform_apps/launch_files/test.txt";
193 #endif
194
195 }  // namespace
196
197 // Tests that CreateAppWindow doesn't crash if you close it straight away.
198 // LauncherPlatformAppBrowserTest relies on this behaviour, but is only run for
199 // ash, so we test that it works here.
200 IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, CreateAndCloseAppWindow) {
201   const Extension* extension = LoadAndLaunchPlatformApp("minimal");
202   AppWindow* window = CreateAppWindow(extension);
203   CloseAppWindow(window);
204 }
205
206 // Tests that platform apps received the "launch" event when launched.
207 IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, OnLaunchedEvent) {
208   ASSERT_TRUE(RunPlatformAppTest("platform_apps/launch")) << message_;
209 }
210
211 // Tests that platform apps cannot use certain disabled window properties, but
212 // can override them and then use them.
213 IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, DisabledWindowProperties) {
214   ASSERT_TRUE(RunPlatformAppTest("platform_apps/disabled_window_properties"))
215       << message_;
216 }
217
218 IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, EmptyContextMenu) {
219   ExtensionTestMessageListener launched_listener("Launched", false);
220   LoadAndLaunchPlatformApp("minimal");
221
222   ASSERT_TRUE(launched_listener.WaitUntilSatisfied());
223
224   // The empty app doesn't add any context menu items, so its menu should
225   // only include the developer tools.
226   WebContents* web_contents = GetFirstAppWindowWebContents();
227   ASSERT_TRUE(web_contents);
228   content::ContextMenuParams params;
229   scoped_ptr<PlatformAppContextMenu> menu;
230   menu.reset(new PlatformAppContextMenu(web_contents->GetMainFrame(), params));
231   menu->Init();
232   ASSERT_TRUE(menu->HasCommandWithId(IDC_CONTENT_CONTEXT_INSPECTELEMENT));
233   ASSERT_TRUE(
234       menu->HasCommandWithId(IDC_CONTENT_CONTEXT_INSPECTBACKGROUNDPAGE));
235   ASSERT_TRUE(menu->HasCommandWithId(IDC_CONTENT_CONTEXT_RELOAD_PACKAGED_APP));
236   ASSERT_FALSE(menu->HasCommandWithId(IDC_BACK));
237   ASSERT_FALSE(menu->HasCommandWithId(IDC_SAVE_PAGE));
238 }
239
240 IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, AppWithContextMenu) {
241   ExtensionTestMessageListener launched_listener("Launched", false);
242   LoadAndLaunchPlatformApp("context_menu");
243
244   // Wait for the extension to tell us it's initialized its context menus and
245   // launched a window.
246   ASSERT_TRUE(launched_listener.WaitUntilSatisfied());
247
248   // The context_menu app has two context menu items. These, along with a
249   // separator and the developer tools, is all that should be in the menu.
250   WebContents* web_contents = GetFirstAppWindowWebContents();
251   ASSERT_TRUE(web_contents);
252   content::ContextMenuParams params;
253   scoped_ptr<PlatformAppContextMenu> menu;
254   menu.reset(new PlatformAppContextMenu(web_contents->GetMainFrame(), params));
255   menu->Init();
256   ASSERT_TRUE(menu->HasCommandWithId(IDC_EXTENSIONS_CONTEXT_CUSTOM_FIRST));
257   ASSERT_TRUE(menu->HasCommandWithId(IDC_EXTENSIONS_CONTEXT_CUSTOM_FIRST + 1));
258   ASSERT_TRUE(menu->HasCommandWithId(IDC_CONTENT_CONTEXT_INSPECTELEMENT));
259   ASSERT_TRUE(
260       menu->HasCommandWithId(IDC_CONTENT_CONTEXT_INSPECTBACKGROUNDPAGE));
261   ASSERT_TRUE(menu->HasCommandWithId(IDC_CONTENT_CONTEXT_RELOAD_PACKAGED_APP));
262   ASSERT_FALSE(menu->HasCommandWithId(IDC_BACK));
263   ASSERT_FALSE(menu->HasCommandWithId(IDC_SAVE_PAGE));
264   ASSERT_FALSE(menu->HasCommandWithId(IDC_CONTENT_CONTEXT_UNDO));
265 }
266
267 IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, InstalledAppWithContextMenu) {
268   ExtensionTestMessageListener launched_listener("Launched", false);
269   InstallAndLaunchPlatformApp("context_menu");
270
271   // Wait for the extension to tell us it's initialized its context menus and
272   // launched a window.
273   ASSERT_TRUE(launched_listener.WaitUntilSatisfied());
274
275   // The context_menu app has two context menu items. For an installed app
276   // these are all that should be in the menu.
277   WebContents* web_contents = GetFirstAppWindowWebContents();
278   ASSERT_TRUE(web_contents);
279   content::ContextMenuParams params;
280   scoped_ptr<PlatformAppContextMenu> menu;
281   menu.reset(new PlatformAppContextMenu(web_contents->GetMainFrame(), params));
282   menu->Init();
283   ASSERT_TRUE(menu->HasCommandWithId(IDC_EXTENSIONS_CONTEXT_CUSTOM_FIRST));
284   ASSERT_TRUE(menu->HasCommandWithId(IDC_EXTENSIONS_CONTEXT_CUSTOM_FIRST + 1));
285   ASSERT_FALSE(menu->HasCommandWithId(IDC_CONTENT_CONTEXT_INSPECTELEMENT));
286   ASSERT_FALSE(
287       menu->HasCommandWithId(IDC_CONTENT_CONTEXT_INSPECTBACKGROUNDPAGE));
288   ASSERT_FALSE(menu->HasCommandWithId(IDC_CONTENT_CONTEXT_RELOAD_PACKAGED_APP));
289   ASSERT_FALSE(menu->HasCommandWithId(IDC_BACK));
290   ASSERT_FALSE(menu->HasCommandWithId(IDC_SAVE_PAGE));
291   ASSERT_FALSE(menu->HasCommandWithId(IDC_CONTENT_CONTEXT_UNDO));
292 }
293
294 IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, AppWithContextMenuTextField) {
295   ExtensionTestMessageListener launched_listener("Launched", false);
296   LoadAndLaunchPlatformApp("context_menu");
297
298   // Wait for the extension to tell us it's initialized its context menus and
299   // launched a window.
300   ASSERT_TRUE(launched_listener.WaitUntilSatisfied());
301
302   // The context_menu app has one context menu item. This, along with a
303   // separator and the developer tools, is all that should be in the menu.
304   WebContents* web_contents = GetFirstAppWindowWebContents();
305   ASSERT_TRUE(web_contents);
306   content::ContextMenuParams params;
307   params.is_editable = true;
308   scoped_ptr<PlatformAppContextMenu> menu;
309   menu.reset(new PlatformAppContextMenu(web_contents->GetMainFrame(), params));
310   menu->Init();
311   ASSERT_TRUE(menu->HasCommandWithId(IDC_EXTENSIONS_CONTEXT_CUSTOM_FIRST));
312   ASSERT_TRUE(menu->HasCommandWithId(IDC_CONTENT_CONTEXT_INSPECTELEMENT));
313   ASSERT_TRUE(
314       menu->HasCommandWithId(IDC_CONTENT_CONTEXT_INSPECTBACKGROUNDPAGE));
315   ASSERT_TRUE(menu->HasCommandWithId(IDC_CONTENT_CONTEXT_RELOAD_PACKAGED_APP));
316   ASSERT_TRUE(menu->HasCommandWithId(IDC_CONTENT_CONTEXT_UNDO));
317   ASSERT_TRUE(menu->HasCommandWithId(IDC_CONTENT_CONTEXT_COPY));
318   ASSERT_FALSE(menu->HasCommandWithId(IDC_BACK));
319   ASSERT_FALSE(menu->HasCommandWithId(IDC_SAVE_PAGE));
320 }
321
322 IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, AppWithContextMenuSelection) {
323   ExtensionTestMessageListener launched_listener("Launched", false);
324   LoadAndLaunchPlatformApp("context_menu");
325
326   // Wait for the extension to tell us it's initialized its context menus and
327   // launched a window.
328   ASSERT_TRUE(launched_listener.WaitUntilSatisfied());
329
330   // The context_menu app has one context menu item. This, along with a
331   // separator and the developer tools, is all that should be in the menu.
332   WebContents* web_contents = GetFirstAppWindowWebContents();
333   ASSERT_TRUE(web_contents);
334   content::ContextMenuParams params;
335   params.selection_text = base::ASCIIToUTF16("Hello World");
336   scoped_ptr<PlatformAppContextMenu> menu;
337   menu.reset(new PlatformAppContextMenu(web_contents->GetMainFrame(), params));
338   menu->Init();
339   ASSERT_TRUE(menu->HasCommandWithId(IDC_EXTENSIONS_CONTEXT_CUSTOM_FIRST));
340   ASSERT_TRUE(menu->HasCommandWithId(IDC_CONTENT_CONTEXT_INSPECTELEMENT));
341   ASSERT_TRUE(
342       menu->HasCommandWithId(IDC_CONTENT_CONTEXT_INSPECTBACKGROUNDPAGE));
343   ASSERT_TRUE(menu->HasCommandWithId(IDC_CONTENT_CONTEXT_RELOAD_PACKAGED_APP));
344   ASSERT_FALSE(menu->HasCommandWithId(IDC_CONTENT_CONTEXT_UNDO));
345   ASSERT_TRUE(menu->HasCommandWithId(IDC_CONTENT_CONTEXT_COPY));
346   ASSERT_FALSE(menu->HasCommandWithId(IDC_BACK));
347   ASSERT_FALSE(menu->HasCommandWithId(IDC_SAVE_PAGE));
348 }
349
350 IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, AppWithContextMenuClicked) {
351   ExtensionTestMessageListener launched_listener("Launched", false);
352   LoadAndLaunchPlatformApp("context_menu_click");
353
354   // Wait for the extension to tell us it's initialized its context menus and
355   // launched a window.
356   ASSERT_TRUE(launched_listener.WaitUntilSatisfied());
357
358   // Test that the menu item shows up
359   WebContents* web_contents = GetFirstAppWindowWebContents();
360   ASSERT_TRUE(web_contents);
361   content::ContextMenuParams params;
362   params.page_url = GURL("http://foo.bar");
363   scoped_ptr<PlatformAppContextMenu> menu;
364   menu.reset(new PlatformAppContextMenu(web_contents->GetMainFrame(), params));
365   menu->Init();
366   ASSERT_TRUE(menu->HasCommandWithId(IDC_EXTENSIONS_CONTEXT_CUSTOM_FIRST));
367
368   // Execute the menu item
369   ExtensionTestMessageListener onclicked_listener("onClicked fired for id1",
370                                                   false);
371   menu->ExecuteCommand(IDC_EXTENSIONS_CONTEXT_CUSTOM_FIRST, 0);
372
373   ASSERT_TRUE(onclicked_listener.WaitUntilSatisfied());
374 }
375
376 #if defined(OS_LINUX) && !defined(OS_CHROMEOS) && defined(USE_AURA)
377 // TODO(erg): linux_aura bringup: http://crbug.com/163931
378 #define MAYBE_DisallowNavigation DISABLED_DisallowNavigation
379 #else
380 #define MAYBE_DisallowNavigation DisallowNavigation
381 #endif
382
383 IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, MAYBE_DisallowNavigation) {
384   TabsAddedNotificationObserver observer(2);
385
386   ASSERT_TRUE(StartEmbeddedTestServer());
387   ASSERT_TRUE(RunPlatformAppTest("platform_apps/navigation")) << message_;
388
389   observer.Wait();
390   ASSERT_EQ(2U, observer.tabs().size());
391   EXPECT_EQ(std::string(chrome::kExtensionInvalidRequestURL),
392             observer.tabs()[0]->GetURL().spec());
393   EXPECT_EQ("http://chromium.org/",
394             observer.tabs()[1]->GetURL().spec());
395 }
396
397 // Failing on some Win and Linux buildbots.  See crbug.com/354425.
398 #if (defined(OS_WIN) || defined(OS_LINUX)) && defined(ARCH_CPU_X86)
399 #define MAYBE_Iframes DISABLED_Iframes
400 #else
401 #define MAYBE_Iframes Iframes
402 #endif
403 IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, MAYBE_Iframes) {
404   ASSERT_TRUE(StartEmbeddedTestServer());
405   ASSERT_TRUE(RunPlatformAppTest("platform_apps/iframes")) << message_;
406 }
407
408 // Tests that localStorage and WebSQL are disabled for platform apps.
409 IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, DisallowStorage) {
410   ASSERT_TRUE(RunPlatformAppTest("platform_apps/storage")) << message_;
411 }
412
413 IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, Restrictions) {
414   ASSERT_TRUE(RunPlatformAppTest("platform_apps/restrictions")) << message_;
415 }
416
417 // Tests that extensions can't use platform-app-only APIs.
418 IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, PlatformAppsOnly) {
419   ASSERT_TRUE(RunExtensionTestIgnoreManifestWarnings(
420       "platform_apps/apps_only")) << message_;
421 }
422
423 // Tests that platform apps have isolated storage by default.
424 IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, Isolation) {
425   ASSERT_TRUE(StartEmbeddedTestServer());
426
427   // Load a (non-app) page under the "localhost" origin that sets a cookie.
428   GURL set_cookie_url = embedded_test_server()->GetURL(
429       "/extensions/platform_apps/isolation/set_cookie.html");
430   GURL::Replacements replace_host;
431   std::string host_str("localhost");  // Must stay in scope with replace_host.
432   replace_host.SetHostStr(host_str);
433   set_cookie_url = set_cookie_url.ReplaceComponents(replace_host);
434
435   ui_test_utils::NavigateToURLWithDisposition(
436       browser(), set_cookie_url,
437       CURRENT_TAB, ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
438
439   // Make sure the cookie is set.
440   int cookie_size;
441   std::string cookie_value;
442   ui_test_utils::GetCookies(
443       set_cookie_url,
444       browser()->tab_strip_model()->GetWebContentsAt(0),
445       &cookie_size,
446       &cookie_value);
447   ASSERT_EQ("testCookie=1", cookie_value);
448
449   // Let the platform app request the same URL, and make sure that it doesn't
450   // see the cookie.
451   ASSERT_TRUE(RunPlatformAppTest("platform_apps/isolation")) << message_;
452 }
453
454 // See crbug.com/248441
455 #if defined(OS_WIN)
456 #define MAYBE_ExtensionWindowingApis DISABLED_ExtensionWindowingApis
457 #else
458 #define MAYBE_ExtensionWindowingApis ExtensionWindowingApis
459 #endif
460
461 IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, MAYBE_ExtensionWindowingApis) {
462   // Initially there should be just the one browser window visible to the
463   // extensions API.
464   const Extension* extension = LoadExtension(
465       test_data_dir_.AppendASCII("common/background_page"));
466   ASSERT_EQ(1U, RunGetWindowsFunctionForExtension(extension));
467
468   // And no app windows.
469   ASSERT_EQ(0U, GetAppWindowCount());
470
471   // Launch a platform app that shows a window.
472   ExtensionTestMessageListener launched_listener("Launched", false);
473   LoadAndLaunchPlatformApp("minimal");
474   ASSERT_TRUE(launched_listener.WaitUntilSatisfied());
475   ASSERT_EQ(1U, GetAppWindowCount());
476   int app_window_id = GetFirstAppWindow()->session_id().id();
477
478   // But it's not visible to the extensions API, it still thinks there's just
479   // one browser window.
480   ASSERT_EQ(1U, RunGetWindowsFunctionForExtension(extension));
481   // It can't look it up by ID either
482   ASSERT_FALSE(RunGetWindowFunctionForExtension(app_window_id, extension));
483
484   // The app can also only see one window (its own).
485   // TODO(jeremya): add an extension function to get an app window by ID, and
486   // to get a list of all the app windows, so we can test this.
487
488   // Launch another platform app that also shows a window.
489   ExtensionTestMessageListener launched_listener2("Launched", false);
490   LoadAndLaunchPlatformApp("context_menu");
491   ASSERT_TRUE(launched_listener2.WaitUntilSatisfied());
492
493   // There are two total app windows, but each app can only see its own.
494   ASSERT_EQ(2U, GetAppWindowCount());
495   // TODO(jeremya): as above, this requires more extension functions.
496 }
497
498 // ChromeOS does not support passing arguments on the command line, so the tests
499 // that rely on this functionality are disabled.
500 #if !defined(OS_CHROMEOS)
501 // Tests that command line parameters get passed through to platform apps
502 // via launchData correctly when launching with a file.
503 // TODO(benwells/jeremya): tests need a way to specify a handler ID.
504 IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, LaunchWithFile) {
505   SetCommandLineArg(kTestFilePath);
506   ASSERT_TRUE(RunPlatformAppTest("platform_apps/launch_file"))
507       << message_;
508 }
509
510 // Tests that relative paths can be passed through to the platform app.
511 // This test doesn't use the normal test infrastructure as it needs to open
512 // the application differently to all other platform app tests, by setting
513 // the AppLaunchParams.current_directory field.
514 IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, LaunchWithRelativeFile) {
515   // Setup the command line
516   ClearCommandLineArgs();
517   CommandLine* command_line = CommandLine::ForCurrentProcess();
518   base::FilePath relative_test_doc =
519       base::FilePath::FromUTF8Unsafe(kTestFilePath);
520   relative_test_doc = relative_test_doc.NormalizePathSeparators();
521   command_line->AppendArgPath(relative_test_doc);
522
523   // Load the extension
524   ResultCatcher catcher;
525   const Extension* extension = LoadExtension(
526       test_data_dir_.AppendASCII("platform_apps/launch_file"));
527   ASSERT_TRUE(extension);
528
529   // Run the test
530   AppLaunchParams params(
531       browser()->profile(), extension, LAUNCH_CONTAINER_NONE, NEW_WINDOW);
532   params.command_line = *CommandLine::ForCurrentProcess();
533   params.current_directory = test_data_dir_;
534   OpenApplication(params);
535
536   if (!catcher.GetNextResult()) {
537     message_ = catcher.message();
538     ASSERT_TRUE(0);
539   }
540 }
541
542 // Tests that launch data is sent through if the file extension matches.
543 IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, LaunchWithFileExtension) {
544   SetCommandLineArg(kTestFilePath);
545   ASSERT_TRUE(RunPlatformAppTest("platform_apps/launch_file_by_extension"))
546       << message_;
547 }
548
549 // Tests that launch data is sent through to a whitelisted extension if the file
550 // extension matches.
551 IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest,
552                        LaunchWhiteListedExtensionWithFile) {
553   SetCommandLineArg(kTestFilePath);
554   ASSERT_TRUE(RunPlatformAppTest(
555       "platform_apps/launch_whitelisted_ext_with_file"))
556           << message_;
557 }
558
559 #if defined(OS_LINUX) && !defined(OS_CHROMEOS) && defined(USE_AURA)
560 // TODO(erg): linux_aura bringup: http://crbug.com/163931
561 #define MAYBE_LaunchWithFileExtensionAndMimeType DISABLED_LaunchWithFileExtensionAndMimeType
562 #else
563 #define MAYBE_LaunchWithFileExtensionAndMimeType LaunchWithFileExtensionAndMimeType
564 #endif
565
566 // Tests that launch data is sent through if the file extension and MIME type
567 // both match.
568 IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest,
569                        MAYBE_LaunchWithFileExtensionAndMimeType) {
570   SetCommandLineArg(kTestFilePath);
571   ASSERT_TRUE(RunPlatformAppTest(
572       "platform_apps/launch_file_by_extension_and_type")) << message_;
573 }
574
575 // Tests that launch data is sent through for a file with no extension if a
576 // handler accepts "".
577 IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, LaunchWithFileWithoutExtension) {
578   SetCommandLineArg("platform_apps/launch_files/test");
579   ASSERT_TRUE(RunPlatformAppTest("platform_apps/launch_file_with_no_extension"))
580       << message_;
581 }
582
583 #if !defined(OS_WIN)
584 // Tests that launch data is sent through for a file with an empty extension if
585 // a handler accepts "".
586 IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, LaunchWithFileEmptyExtension) {
587   base::ScopedTempDir temp_dir;
588   ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
589   ClearCommandLineArgs();
590   ASSERT_TRUE(CopyTestDataAndSetCommandLineArg(
591       test_data_dir_.AppendASCII(kTestFilePath),
592       temp_dir.path(),
593       "test."));
594   ASSERT_TRUE(RunPlatformAppTest("platform_apps/launch_file_with_no_extension"))
595       << message_;
596 }
597
598 // Tests that launch data is sent through for a file with an empty extension if
599 // a handler accepts *.
600 IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest,
601                        LaunchWithFileEmptyExtensionAcceptAny) {
602   base::ScopedTempDir temp_dir;
603   ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
604   ClearCommandLineArgs();
605   ASSERT_TRUE(CopyTestDataAndSetCommandLineArg(
606       test_data_dir_.AppendASCII(kTestFilePath),
607       temp_dir.path(),
608       "test."));
609   ASSERT_TRUE(RunPlatformAppTest(
610       "platform_apps/launch_file_with_any_extension")) << message_;
611 }
612 #endif
613
614 // Tests that launch data is sent through for a file with no extension if a
615 // handler accepts *.
616 IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest,
617                        LaunchWithFileWithoutExtensionAcceptAny) {
618   SetCommandLineArg("platform_apps/launch_files/test");
619   ASSERT_TRUE(RunPlatformAppTest(
620       "platform_apps/launch_file_with_any_extension")) << message_;
621 }
622
623 // Tests that launch data is sent through for a file with an extension if a
624 // handler accepts *.
625 IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest,
626                        LaunchWithFileAcceptAnyExtension) {
627   SetCommandLineArg(kTestFilePath);
628   ASSERT_TRUE(RunPlatformAppTest(
629       "platform_apps/launch_file_with_any_extension")) << message_;
630 }
631
632 // Tests that no launch data is sent through if the file has the wrong
633 // extension.
634 IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, LaunchWithWrongExtension) {
635   SetCommandLineArg(kTestFilePath);
636   ASSERT_TRUE(RunPlatformAppTest("platform_apps/launch_wrong_extension"))
637       << message_;
638 }
639
640 // Tests that no launch data is sent through if the file has no extension but
641 // the handler requires a specific extension.
642 IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, LaunchWithWrongEmptyExtension) {
643   SetCommandLineArg("platform_apps/launch_files/test");
644   ASSERT_TRUE(RunPlatformAppTest("platform_apps/launch_wrong_extension"))
645       << message_;
646 }
647
648 // Tests that no launch data is sent through if the file is of the wrong MIME
649 // type.
650 IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, LaunchWithWrongType) {
651   SetCommandLineArg(kTestFilePath);
652   ASSERT_TRUE(RunPlatformAppTest("platform_apps/launch_wrong_type"))
653       << message_;
654 }
655
656 // Tests that no launch data is sent through if the platform app does not
657 // provide an intent.
658 IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, LaunchWithNoIntent) {
659   SetCommandLineArg(kTestFilePath);
660   ASSERT_TRUE(RunPlatformAppTest("platform_apps/launch_no_intent"))
661       << message_;
662 }
663
664 // Tests that launch data is sent through when the file has unknown extension
665 // but the MIME type can be sniffed and the sniffed type matches.
666 IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, LaunchWithSniffableType) {
667   SetCommandLineArg("platform_apps/launch_files/test.unknownextension");
668   ASSERT_TRUE(RunPlatformAppTest(
669       "platform_apps/launch_file_by_extension_and_type")) << message_;
670 }
671
672 // Tests that launch data is sent through with the MIME type set to
673 // application/octet-stream if the file MIME type cannot be read.
674 IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, LaunchNoType) {
675   SetCommandLineArg("platform_apps/launch_files/test_binary.unknownextension");
676   ASSERT_TRUE(RunPlatformAppTest(
677       "platform_apps/launch_application_octet_stream")) << message_;
678 }
679
680 // Tests that no launch data is sent through if the file does not exist.
681 IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, LaunchNoFile) {
682   SetCommandLineArg("platform_apps/launch_files/doesnotexist.txt");
683   ASSERT_TRUE(RunPlatformAppTest("platform_apps/launch_invalid"))
684       << message_;
685 }
686
687 // Tests that no launch data is sent through if the argument is a directory.
688 IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, LaunchWithDirectory) {
689   SetCommandLineArg("platform_apps/launch_files");
690   ASSERT_TRUE(RunPlatformAppTest("platform_apps/launch_invalid"))
691       << message_;
692 }
693
694 // Tests that no launch data is sent through if there are no arguments passed
695 // on the command line
696 IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, LaunchWithNothing) {
697   ClearCommandLineArgs();
698   ASSERT_TRUE(RunPlatformAppTest("platform_apps/launch_nothing"))
699       << message_;
700 }
701
702 // Test that platform apps can use the chrome.fileSystem.getDisplayPath
703 // function to get the native file system path of a file they are launched with.
704 IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, GetDisplayPath) {
705   SetCommandLineArg(kTestFilePath);
706   ASSERT_TRUE(RunPlatformAppTest("platform_apps/get_display_path"))
707       << message_;
708 }
709
710 // Tests that the file is created if the file does not exist and the app has the
711 // fileSystem.write permission.
712 IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, LaunchNewFile) {
713   base::ScopedTempDir temp_dir;
714   ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
715   ClearCommandLineArgs();
716   CommandLine* command_line = CommandLine::ForCurrentProcess();
717   command_line->AppendArgPath(temp_dir.path().AppendASCII("new_file.txt"));
718   ASSERT_TRUE(RunPlatformAppTest("platform_apps/launch_new_file")) << message_;
719 }
720
721 #endif  // !defined(OS_CHROMEOS)
722
723 IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, OpenLink) {
724   ASSERT_TRUE(StartEmbeddedTestServer());
725   content::WindowedNotificationObserver observer(
726       chrome::NOTIFICATION_TAB_ADDED,
727       content::Source<content::WebContentsDelegate>(browser()));
728   LoadAndLaunchPlatformApp("open_link");
729   observer.Wait();
730   ASSERT_EQ(2, browser()->tab_strip_model()->count());
731 }
732
733 IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, MutationEventsDisabled) {
734   ASSERT_TRUE(RunPlatformAppTest("platform_apps/mutation_events")) << message_;
735 }
736
737 // This appears to be unreliable on linux.
738 // TODO(stevenjb): Investigate and enable
739 #if defined(OS_LINUX) && !defined(USE_ASH)
740 #define MAYBE_AppWindowRestoreState DISABLED_AppWindowRestoreState
741 #else
742 #define MAYBE_AppWindowRestoreState AppWindowRestoreState
743 #endif
744 IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, MAYBE_AppWindowRestoreState) {
745   ASSERT_TRUE(RunPlatformAppTest("platform_apps/restore_state"));
746 }
747
748 IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest,
749                        AppWindowAdjustBoundsToBeVisibleOnScreen) {
750   const Extension* extension = LoadAndLaunchPlatformApp("minimal");
751   AppWindow* window = CreateAppWindow(extension);
752
753   // The screen bounds didn't change, the cached bounds didn't need to adjust.
754   gfx::Rect cached_bounds(80, 100, 400, 400);
755   gfx::Rect cached_screen_bounds(0, 0, 1600, 900);
756   gfx::Rect current_screen_bounds(0, 0, 1600, 900);
757   gfx::Size minimum_size(200, 200);
758   gfx::Rect bounds;
759   CallAdjustBoundsToBeVisibleOnScreenForAppWindow(window,
760                                                   cached_bounds,
761                                                   cached_screen_bounds,
762                                                   current_screen_bounds,
763                                                   minimum_size,
764                                                   &bounds);
765   EXPECT_EQ(bounds, cached_bounds);
766
767   // We have an empty screen bounds, the cached bounds didn't need to adjust.
768   gfx::Rect empty_screen_bounds;
769   CallAdjustBoundsToBeVisibleOnScreenForAppWindow(window,
770                                                   cached_bounds,
771                                                   empty_screen_bounds,
772                                                   current_screen_bounds,
773                                                   minimum_size,
774                                                   &bounds);
775   EXPECT_EQ(bounds, cached_bounds);
776
777   // Cached bounds is completely off the new screen bounds in horizontal
778   // locations. Expect to reposition the bounds.
779   gfx::Rect horizontal_out_of_screen_bounds(-800, 100, 400, 400);
780   CallAdjustBoundsToBeVisibleOnScreenForAppWindow(
781       window,
782       horizontal_out_of_screen_bounds,
783       gfx::Rect(-1366, 0, 1600, 900),
784       current_screen_bounds,
785       minimum_size,
786       &bounds);
787   EXPECT_EQ(bounds, gfx::Rect(0, 100, 400, 400));
788
789   // Cached bounds is completely off the new screen bounds in vertical
790   // locations. Expect to reposition the bounds.
791   gfx::Rect vertical_out_of_screen_bounds(10, 1000, 400, 400);
792   CallAdjustBoundsToBeVisibleOnScreenForAppWindow(
793       window,
794       vertical_out_of_screen_bounds,
795       gfx::Rect(-1366, 0, 1600, 900),
796       current_screen_bounds,
797       minimum_size,
798       &bounds);
799   EXPECT_EQ(bounds, gfx::Rect(10, 500, 400, 400));
800
801   // From a large screen resulotion to a small one. Expect it fit on screen.
802   gfx::Rect big_cache_bounds(10, 10, 1000, 1000);
803   CallAdjustBoundsToBeVisibleOnScreenForAppWindow(window,
804                                                   big_cache_bounds,
805                                                   gfx::Rect(0, 0, 1600, 1000),
806                                                   gfx::Rect(0, 0, 800, 600),
807                                                   minimum_size,
808                                                   &bounds);
809   EXPECT_EQ(bounds, gfx::Rect(0, 0, 800, 600));
810
811   // Don't resize the bounds smaller than minimum size, when the minimum size is
812   // larger than the screen.
813   CallAdjustBoundsToBeVisibleOnScreenForAppWindow(window,
814                                                   big_cache_bounds,
815                                                   gfx::Rect(0, 0, 1600, 1000),
816                                                   gfx::Rect(0, 0, 800, 600),
817                                                   gfx::Size(900, 900),
818                                                   &bounds);
819   EXPECT_EQ(bounds, gfx::Rect(0, 0, 900, 900));
820 }
821
822 namespace {
823
824 class PlatformAppDevToolsBrowserTest : public PlatformAppBrowserTest {
825  protected:
826   enum TestFlags {
827     RELAUNCH = 0x1,
828     HAS_ID = 0x2,
829   };
830   // Runs a test inside a harness that opens DevTools on an app window.
831   void RunTestWithDevTools(const char* name, int test_flags);
832 };
833
834 void PlatformAppDevToolsBrowserTest::RunTestWithDevTools(
835     const char* name, int test_flags) {
836   using content::DevToolsAgentHost;
837   ExtensionTestMessageListener launched_listener("Launched", false);
838   const Extension* extension = LoadAndLaunchPlatformApp(name);
839   ASSERT_TRUE(extension);
840   ASSERT_TRUE(launched_listener.WaitUntilSatisfied());
841   AppWindow* window = GetFirstAppWindow();
842   ASSERT_TRUE(window);
843   ASSERT_EQ(window->window_key().empty(), (test_flags & HAS_ID) == 0);
844   content::RenderViewHost* rvh = window->web_contents()->GetRenderViewHost();
845   ASSERT_TRUE(rvh);
846
847   // Ensure no DevTools open for the AppWindow, then open one.
848   ASSERT_FALSE(DevToolsAgentHost::HasFor(rvh));
849   DevToolsWindow::OpenDevToolsWindow(rvh);
850   ASSERT_TRUE(DevToolsAgentHost::HasFor(rvh));
851
852   if (test_flags & RELAUNCH) {
853     // Close the AppWindow, and ensure it is gone.
854     CloseAppWindow(window);
855     ASSERT_FALSE(GetFirstAppWindow());
856
857     // Relaunch the app and get a new AppWindow.
858     content::WindowedNotificationObserver app_loaded_observer(
859         content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME,
860         content::NotificationService::AllSources());
861     OpenApplication(AppLaunchParams(
862         browser()->profile(), extension, LAUNCH_CONTAINER_NONE, NEW_WINDOW));
863     app_loaded_observer.Wait();
864     window = GetFirstAppWindow();
865     ASSERT_TRUE(window);
866
867     // DevTools should have reopened with the relaunch.
868     rvh = window->web_contents()->GetRenderViewHost();
869     ASSERT_TRUE(rvh);
870     ASSERT_TRUE(DevToolsAgentHost::HasFor(rvh));
871   }
872 }
873
874 }  // namespace
875
876 // http://crbug.com/246634
877 #if defined(OS_CHROMEOS)
878 #define MAYBE_ReOpenedWithID DISABLED_ReOpenedWithID
879 #else
880 #define MAYBE_ReOpenedWithID ReOpenedWithID
881 #endif
882 IN_PROC_BROWSER_TEST_F(PlatformAppDevToolsBrowserTest, MAYBE_ReOpenedWithID) {
883 #if defined(OS_WIN) && defined(USE_ASH)
884   // Disable this test in Metro+Ash for now (http://crbug.com/262796).
885   if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshBrowserTests))
886     return;
887 #endif
888   RunTestWithDevTools("minimal_id", RELAUNCH | HAS_ID);
889 }
890
891 // http://crbug.com/246999
892 #if defined(OS_CHROMEOS) || defined(OS_WIN)
893 #define MAYBE_ReOpenedWithURL DISABLED_ReOpenedWithURL
894 #else
895 #define MAYBE_ReOpenedWithURL ReOpenedWithURL
896 #endif
897 IN_PROC_BROWSER_TEST_F(PlatformAppDevToolsBrowserTest, MAYBE_ReOpenedWithURL) {
898   RunTestWithDevTools("minimal", RELAUNCH);
899 }
900
901 // Test that showing a permission request as a constrained window works and is
902 // correctly parented.
903 #if defined(OS_MACOSX)
904 #define MAYBE_ConstrainedWindowRequest DISABLED_ConstrainedWindowRequest
905 #else
906 // TODO(sail): Enable this on other platforms once http://crbug.com/95455 is
907 // fixed.
908 #define MAYBE_ConstrainedWindowRequest DISABLED_ConstrainedWindowRequest
909 #endif
910
911 IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, MAYBE_ConstrainedWindowRequest) {
912   PermissionsRequestFunction::SetIgnoreUserGestureForTests(true);
913   const Extension* extension =
914       LoadAndLaunchPlatformApp("optional_permission_request");
915   ASSERT_TRUE(extension) << "Failed to load extension.";
916
917   WebContents* web_contents = GetFirstAppWindowWebContents();
918   ASSERT_TRUE(web_contents);
919
920   // Verify that the app window has a dialog attached.
921   WebContentsModalDialogManager* web_contents_modal_dialog_manager =
922       WebContentsModalDialogManager::FromWebContents(web_contents);
923   EXPECT_TRUE(web_contents_modal_dialog_manager->IsDialogActive());
924
925   // Close the constrained window and wait for the reply to the permission
926   // request.
927   ExtensionTestMessageListener listener("PermissionRequestDone", false);
928   WebContentsModalDialogManager::TestApi test_api(
929       web_contents_modal_dialog_manager);
930   test_api.CloseAllDialogs();
931   ASSERT_TRUE(listener.WaitUntilSatisfied());
932 }
933
934 // Tests that an app calling chrome.runtime.reload will reload the app and
935 // relaunch it if it was running.
936 IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, ReloadRelaunches) {
937   ExtensionTestMessageListener launched_listener("Launched", true);
938   const Extension* extension = LoadAndLaunchPlatformApp("reload");
939   ASSERT_TRUE(extension);
940   ASSERT_TRUE(launched_listener.WaitUntilSatisfied());
941   ASSERT_TRUE(GetFirstAppWindow());
942
943   // Now tell the app to reload itself
944   ExtensionTestMessageListener launched_listener2("Launched", false);
945   launched_listener.Reply("reload");
946   ASSERT_TRUE(launched_listener2.WaitUntilSatisfied());
947   ASSERT_TRUE(GetFirstAppWindow());
948 }
949
950 namespace {
951
952 // Simple observer to check for NOTIFICATION_EXTENSION_INSTALLED events to
953 // ensure installation does or does not occur in certain scenarios.
954 class CheckExtensionInstalledObserver : public content::NotificationObserver {
955  public:
956   CheckExtensionInstalledObserver() : seen_(false) {
957     registrar_.Add(this,
958                    chrome::NOTIFICATION_EXTENSION_INSTALLED,
959                    content::NotificationService::AllSources());
960   }
961
962   bool seen() const {
963     return seen_;
964   };
965
966   // NotificationObserver:
967   virtual void Observe(int type,
968                        const content::NotificationSource& source,
969                        const content::NotificationDetails& details) OVERRIDE {
970     EXPECT_FALSE(seen_);
971     seen_ = true;
972   }
973
974  private:
975   bool seen_;
976   content::NotificationRegistrar registrar_;
977 };
978
979 }  // namespace
980
981 // Component App Test 1 of 3: ensure that the initial load of a component
982 // extension utilizing a background page (e.g. a v2 platform app) has its
983 // background page run and is launchable. Waits for the Launched response from
984 // the script resource in the opened app window.
985 IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest,
986                        PRE_PRE_ComponentAppBackgroundPage) {
987   CheckExtensionInstalledObserver should_install;
988
989   // Ensure that we wait until the background page is run (to register the
990   // OnLaunched listener) before trying to open the application. This is similar
991   // to LoadAndLaunchPlatformApp, but we want to load as a component extension.
992   content::WindowedNotificationObserver app_loaded_observer(
993       content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME,
994       content::NotificationService::AllSources());
995
996   const Extension* extension = LoadExtensionAsComponent(
997       test_data_dir_.AppendASCII("platform_apps").AppendASCII("component"));
998   ASSERT_TRUE(extension);
999
1000   app_loaded_observer.Wait();
1001   ASSERT_TRUE(should_install.seen());
1002
1003   ExtensionTestMessageListener launched_listener("Launched", false);
1004   OpenApplication(AppLaunchParams(
1005       browser()->profile(), extension, LAUNCH_CONTAINER_NONE, NEW_WINDOW));
1006
1007   ASSERT_TRUE(launched_listener.WaitUntilSatisfied());
1008 }
1009
1010 // Component App Test 2 of 3: ensure an installed component app can be launched
1011 // on a subsequent browser start, without requiring any install/upgrade logic
1012 // to be run, then perform setup for step 3.
1013 IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest,
1014                        PRE_ComponentAppBackgroundPage) {
1015
1016   // Since the component app is now installed, re-adding it in the same profile
1017   // should not cause it to be re-installed. Instead, we wait for the OnLaunched
1018   // in a different observer (which would timeout if not the app was not
1019   // previously installed properly) and then check this observer to make sure it
1020   // never saw the NOTIFICATION_EXTENSION_INSTALLED event.
1021   CheckExtensionInstalledObserver should_not_install;
1022   const Extension* extension = LoadExtensionAsComponent(
1023       test_data_dir_.AppendASCII("platform_apps").AppendASCII("component"));
1024   ASSERT_TRUE(extension);
1025
1026   ExtensionTestMessageListener launched_listener("Launched", false);
1027   OpenApplication(AppLaunchParams(
1028       browser()->profile(), extension, LAUNCH_CONTAINER_NONE, NEW_WINDOW));
1029
1030   ASSERT_TRUE(launched_listener.WaitUntilSatisfied());
1031   ASSERT_FALSE(should_not_install.seen());
1032
1033   // Simulate a "downgrade" from version 2 in the test manifest.json to 1.
1034   ExtensionPrefs* extension_prefs = ExtensionPrefs::Get(browser()->profile());
1035
1036   // Clear the registered events to ensure they are updated.
1037   extensions::EventRouter::Get(browser()->profile())
1038       ->SetRegisteredEvents(extension->id(), std::set<std::string>());
1039
1040   DictionaryPrefUpdate update(extension_prefs->pref_service(),
1041                               extensions::pref_names::kExtensions);
1042   base::DictionaryValue* dict = update.Get();
1043   std::string key(extension->id());
1044   key += ".manifest.version";
1045   dict->SetString(key, "1");
1046 }
1047
1048 // Component App Test 3 of 3: simulate a component extension upgrade that
1049 // re-adds the OnLaunched event, and allows the app to be launched.
1050 IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, ComponentAppBackgroundPage) {
1051   CheckExtensionInstalledObserver should_install;
1052   // Since we are forcing an upgrade, we need to wait for the load again.
1053   content::WindowedNotificationObserver app_loaded_observer(
1054       content::NOTIFICATION_LOAD_COMPLETED_MAIN_FRAME,
1055       content::NotificationService::AllSources());
1056
1057   const Extension* extension = LoadExtensionAsComponent(
1058       test_data_dir_.AppendASCII("platform_apps").AppendASCII("component"));
1059   ASSERT_TRUE(extension);
1060   app_loaded_observer.Wait();
1061   ASSERT_TRUE(should_install.seen());
1062
1063   ExtensionTestMessageListener launched_listener("Launched", false);
1064   OpenApplication(AppLaunchParams(
1065       browser()->profile(), extension, LAUNCH_CONTAINER_NONE, NEW_WINDOW));
1066
1067   ASSERT_TRUE(launched_listener.WaitUntilSatisfied());
1068 }
1069
1070 // Flakes on Windows: http://crbug.com/171450
1071 #if defined(OS_WIN)
1072 #define MAYBE_Messaging DISABLED_Messaging
1073 #else
1074 #define MAYBE_Messaging Messaging
1075 #endif
1076 IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, MAYBE_Messaging) {
1077   ExtensionApiTest::ResultCatcher result_catcher;
1078   LoadAndLaunchPlatformApp("messaging/app2");
1079   LoadAndLaunchPlatformApp("messaging/app1");
1080   EXPECT_TRUE(result_catcher.GetNextResult());
1081 }
1082
1083 // TODO(linux_aura) http://crbug.com/163931
1084 #if defined(OS_LINUX) && !defined(OS_CHROMEOS) && defined(USE_AURA)
1085 #define MAYBE_WebContentsHasFocus DISABLED_WebContentsHasFocus
1086 #else
1087 // This test depends on focus and so needs to be in interactive_ui_tests.
1088 // http://crbug.com/227041
1089 #define MAYBE_WebContentsHasFocus DISABLED_WebContentsHasFocus
1090 #endif
1091 IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, MAYBE_WebContentsHasFocus) {
1092   ExtensionTestMessageListener launched_listener("Launched", true);
1093   LoadAndLaunchPlatformApp("minimal");
1094   ASSERT_TRUE(launched_listener.WaitUntilSatisfied());
1095
1096   EXPECT_EQ(1LU, GetAppWindowCount());
1097   EXPECT_TRUE(GetFirstAppWindow()
1098                   ->web_contents()
1099                   ->GetRenderWidgetHostView()
1100                   ->HasFocus());
1101 }
1102
1103 // The next three tests will only run automatically with Chrome branded builds
1104 // because they require the PDF preview plug-in. To run these tests manually for
1105 // Chromium (non-Chrome branded) builds in a development environment:
1106 //
1107 //   1) Remove "MAYBE_" in the first line of each test definition
1108 //   2) Build Chromium browser_tests
1109 //   3) Make a copy of the PDF plug-in from a recent version of Chrome (Canary
1110 //      or a recent development build) to your Chromium build:
1111 //      - On Linux and Chrome OS, copy /opt/google/chrome/libpdf.so to
1112 //        <path-to-your-src>/out/Debug
1113 //      - On OS X, copy PDF.plugin from
1114 //        <recent-chrome-app-folder>/*/*/*/*/"Internet Plug-Ins" to
1115 //        <path-to-your-src>/out/Debug/Chromium.app/*/*/*/*/"Internet Plug-Ins"
1116 //   4) Run browser_tests with the --enable-print-preview flag
1117
1118 #if !defined(GOOGLE_CHROME_BUILD) || \
1119     (defined(GOOGLE_CHROME_BUILD) && (defined(OS_WIN) || defined(OS_LINUX)))
1120 #define MAYBE_WindowDotPrintShouldBringUpPrintPreview \
1121     DISABLED_WindowDotPrintShouldBringUpPrintPreview
1122 #else
1123 #define MAYBE_WindowDotPrintShouldBringUpPrintPreview \
1124     WindowDotPrintShouldBringUpPrintPreview
1125 #endif
1126
1127 IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest,
1128                        MAYBE_WindowDotPrintShouldBringUpPrintPreview) {
1129   ScopedPreviewTestingDelegate preview_delegate(true);
1130   ASSERT_TRUE(RunPlatformAppTest("platform_apps/print_api")) << message_;
1131   preview_delegate.WaitUntilPreviewIsReady();
1132 }
1133
1134 #if !defined(GOOGLE_CHROME_BUILD)
1135 #define MAYBE_ClosingWindowWhilePrintingShouldNotCrash \
1136     DISABLED_ClosingWindowWhilePrintingShouldNotCrash
1137 #else
1138 #define MAYBE_ClosingWindowWhilePrintingShouldNotCrash \
1139     ClosingWindowWhilePrintingShouldNotCrash
1140 #endif
1141
1142 // This test verifies that http://crbug.com/297179 is fixed.
1143 IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest,
1144                        MAYBE_ClosingWindowWhilePrintingShouldNotCrash) {
1145   ScopedPreviewTestingDelegate preview_delegate(false);
1146   ASSERT_TRUE(RunPlatformAppTest("platform_apps/print_api")) << message_;
1147   preview_delegate.WaitUntilPreviewIsReady();
1148   GetFirstAppWindow()->GetBaseWindow()->Close();
1149 }
1150
1151 // This test currently only passes on OS X (on other platforms the print preview
1152 // dialog's size is limited by the size of the window being printed).
1153 #if !defined(GOOGLE_CHROME_BUILD) || !defined(OS_MACOSX)
1154 #define MAYBE_PrintPreviewShouldNotBeTooSmall \
1155     DISABLED_PrintPreviewShouldNotBeTooSmall
1156 #else
1157 #define MAYBE_PrintPreviewShouldNotBeTooSmall \
1158     PrintPreviewShouldNotBeTooSmall
1159 #endif
1160
1161 IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest,
1162                        MAYBE_PrintPreviewShouldNotBeTooSmall) {
1163   // Print preview dialogs with widths less than 410 pixels will have preview
1164   // areas that are too small, and ones with heights less than 191 pixels will
1165   // have vertical scrollers for their controls that are too small.
1166   gfx::Size minimum_dialog_size(410, 191);
1167   ScopedPreviewTestingDelegate preview_delegate(false);
1168   ASSERT_TRUE(RunPlatformAppTest("platform_apps/print_api")) << message_;
1169   preview_delegate.WaitUntilPreviewIsReady();
1170   EXPECT_GE(preview_delegate.dialog_size().width(),
1171             minimum_dialog_size.width());
1172   EXPECT_GE(preview_delegate.dialog_size().height(),
1173             minimum_dialog_size.height());
1174   GetFirstAppWindow()->GetBaseWindow()->Close();
1175 }
1176
1177
1178 #if defined(OS_CHROMEOS)
1179
1180 class PlatformAppIncognitoBrowserTest : public PlatformAppBrowserTest,
1181                                         public AppWindowRegistry::Observer {
1182  public:
1183   virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
1184     // Tell chromeos to launch in Guest mode, aka incognito.
1185     command_line->AppendSwitch(switches::kIncognito);
1186     PlatformAppBrowserTest::SetUpCommandLine(command_line);
1187   }
1188   virtual void SetUp() OVERRIDE {
1189     // Make sure the file manager actually gets loaded.
1190     ComponentLoader::EnableBackgroundExtensionsForTesting();
1191     PlatformAppBrowserTest::SetUp();
1192   }
1193
1194   // AppWindowRegistry::Observer implementation.
1195   virtual void OnAppWindowAdded(AppWindow* app_window) OVERRIDE {
1196     opener_app_ids_.insert(app_window->extension_id());
1197   }
1198
1199  protected:
1200   // A set of ids of apps we've seen open a app window.
1201   std::set<std::string> opener_app_ids_;
1202 };
1203
1204 IN_PROC_BROWSER_TEST_F(PlatformAppIncognitoBrowserTest, IncognitoComponentApp) {
1205   // Get the file manager app.
1206   const Extension* file_manager = extension_service()->GetExtensionById(
1207       "hhaomjibdihmijegdhdafkllkbggdgoj", false);
1208   ASSERT_TRUE(file_manager != NULL);
1209   Profile* incognito_profile = profile()->GetOffTheRecordProfile();
1210   ASSERT_TRUE(incognito_profile != NULL);
1211
1212   // Wait until the file manager has had a chance to register its listener
1213   // for the launch event.
1214   EventRouter* router = EventRouter::Get(incognito_profile);
1215   ASSERT_TRUE(router != NULL);
1216   while (!router->ExtensionHasEventListener(
1217       file_manager->id(), app_runtime::OnLaunched::kEventName)) {
1218     content::RunAllPendingInMessageLoop();
1219   }
1220
1221   // Listen for new app windows so we see the file manager app launch itself.
1222   AppWindowRegistry* registry = AppWindowRegistry::Get(incognito_profile);
1223   ASSERT_TRUE(registry != NULL);
1224   registry->AddObserver(this);
1225
1226   OpenApplication(AppLaunchParams(
1227       incognito_profile, file_manager, 0, chrome::HOST_DESKTOP_TYPE_NATIVE));
1228
1229   while (!ContainsKey(opener_app_ids_, file_manager->id())) {
1230     content::RunAllPendingInMessageLoop();
1231   }
1232 }
1233
1234 class RestartDeviceTest : public PlatformAppBrowserTest {
1235  public:
1236   RestartDeviceTest()
1237       : power_manager_client_(NULL),
1238         mock_user_manager_(NULL) {}
1239   virtual ~RestartDeviceTest() {}
1240
1241   // PlatformAppBrowserTest overrides
1242   virtual void SetUpInProcessBrowserTestFixture() OVERRIDE {
1243     PlatformAppBrowserTest::SetUpInProcessBrowserTestFixture();
1244
1245     chromeos::FakeDBusThreadManager* dbus_manager =
1246         new chromeos::FakeDBusThreadManager;
1247     dbus_manager->SetFakeClients();
1248     power_manager_client_ = new chromeos::FakePowerManagerClient;
1249     dbus_manager->SetPowerManagerClient(
1250         scoped_ptr<chromeos::PowerManagerClient>(power_manager_client_));
1251     chromeos::DBusThreadManager::SetInstanceForTesting(dbus_manager);
1252   }
1253
1254   virtual void SetUpOnMainThread() OVERRIDE {
1255     PlatformAppBrowserTest::SetUpOnMainThread();
1256
1257     mock_user_manager_ = new chromeos::MockUserManager;
1258     user_manager_enabler_.reset(
1259         new chromeos::ScopedUserManagerEnabler(mock_user_manager_));
1260
1261     EXPECT_CALL(*mock_user_manager_, IsUserLoggedIn())
1262         .WillRepeatedly(testing::Return(true));
1263     EXPECT_CALL(*mock_user_manager_, IsLoggedInAsKioskApp())
1264         .WillRepeatedly(testing::Return(true));
1265   }
1266
1267   virtual void CleanUpOnMainThread() OVERRIDE {
1268     user_manager_enabler_.reset();
1269     PlatformAppBrowserTest::CleanUpOnMainThread();
1270   }
1271
1272   virtual void TearDownInProcessBrowserTestFixture() OVERRIDE {
1273     PlatformAppBrowserTest::TearDownInProcessBrowserTestFixture();
1274   }
1275
1276   int num_request_restart_calls() const {
1277     return power_manager_client_->num_request_restart_calls();
1278   }
1279
1280  private:
1281   chromeos::FakePowerManagerClient* power_manager_client_;
1282   chromeos::MockUserManager* mock_user_manager_;
1283   scoped_ptr<chromeos::ScopedUserManagerEnabler> user_manager_enabler_;
1284
1285   DISALLOW_COPY_AND_ASSIGN(RestartDeviceTest);
1286 };
1287
1288 // Tests that chrome.runtime.restart would request device restart in
1289 // ChromeOS kiosk mode.
1290 IN_PROC_BROWSER_TEST_F(RestartDeviceTest, Restart) {
1291   ASSERT_EQ(0, num_request_restart_calls());
1292
1293   ExtensionTestMessageListener launched_listener("Launched", true);
1294   const Extension* extension = LoadAndLaunchPlatformApp("restart_device");
1295   ASSERT_TRUE(extension);
1296   ASSERT_TRUE(launched_listener.WaitUntilSatisfied());
1297
1298   launched_listener.Reply("restart");
1299   ExtensionTestMessageListener restart_requested_listener("restartRequested",
1300                                                           false);
1301   ASSERT_TRUE(restart_requested_listener.WaitUntilSatisfied());
1302
1303   EXPECT_EQ(1, num_request_restart_calls());
1304 }
1305
1306 #endif  // defined(OS_CHROMEOS)
1307
1308 // Test that when an application is uninstalled and re-install it does not have
1309 // access to the previously set data.
1310 IN_PROC_BROWSER_TEST_F(PlatformAppBrowserTest, ReinstallDataCleanup) {
1311   // The application is installed and launched. After the 'Launched' message is
1312   // acknowledged by the browser process, the application will test that some
1313   // data are not installed and then install them. The application will then be
1314   // uninstalled and the same process will be repeated.
1315   std::string extension_id;
1316
1317   {
1318     ExtensionTestMessageListener launched_listener("Launched", false);
1319     const Extension* extension =
1320         LoadAndLaunchPlatformApp("reinstall_data_cleanup");
1321     ASSERT_TRUE(extension);
1322     extension_id = extension->id();
1323
1324     ExtensionApiTest::ResultCatcher result_catcher;
1325     ASSERT_TRUE(launched_listener.WaitUntilSatisfied());
1326
1327     EXPECT_TRUE(result_catcher.GetNextResult());
1328   }
1329
1330   UninstallExtension(extension_id);
1331   content::RunAllPendingInMessageLoop();
1332
1333   {
1334     ExtensionTestMessageListener launched_listener("Launched", false);
1335     const Extension* extension =
1336         LoadAndLaunchPlatformApp("reinstall_data_cleanup");
1337     ASSERT_TRUE(extension);
1338     ASSERT_EQ(extension_id, extension->id());
1339
1340     ExtensionApiTest::ResultCatcher result_catcher;
1341
1342     ASSERT_TRUE(launched_listener.WaitUntilSatisfied());
1343
1344     EXPECT_TRUE(result_catcher.GetNextResult());
1345   }
1346 }
1347
1348 }  // namespace extensions