1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "base/path_service.h"
6 #include "base/strings/stringprintf.h"
7 #include "base/strings/utf_string_conversions.h"
8 #include "chrome/browser/background/background_contents_service.h"
9 #include "chrome/browser/background/background_contents_service_factory.h"
10 #include "chrome/browser/background/background_mode_manager.h"
11 #include "chrome/browser/browser_process.h"
12 #include "chrome/browser/chrome_notification_types.h"
13 #include "chrome/browser/extensions/extension_apitest.h"
14 #include "chrome/browser/extensions/extension_service.h"
15 #include "chrome/browser/extensions/extension_test_message_listener.h"
16 #include "chrome/browser/profiles/profile.h"
17 #include "chrome/browser/ui/browser.h"
18 #include "chrome/browser/ui/browser_dialogs.h"
19 #include "chrome/browser/ui/browser_window.h"
20 #include "chrome/browser/ui/extensions/application_launch.h"
21 #include "chrome/common/chrome_paths.h"
22 #include "chrome/common/chrome_switches.h"
23 #include "content/public/browser/notification_service.h"
24 #include "content/public/test/test_notification_tracker.h"
25 #include "content/public/test/test_utils.h"
26 #include "extensions/common/extension.h"
27 #include "extensions/common/switches.h"
28 #include "net/dns/mock_host_resolver.h"
29 #include "net/test/embedded_test_server/embedded_test_server.h"
30 #include "ppapi/shared_impl/ppapi_switches.h"
32 #if defined(OS_MACOSX)
33 #include "base/mac/scoped_nsautorelease_pool.h"
36 using base::ASCIIToUTF16
;
37 using extensions::Extension
;
39 class AppBackgroundPageApiTest
: public ExtensionApiTest
{
41 virtual void SetUpCommandLine(CommandLine
* command_line
) OVERRIDE
{
42 ExtensionApiTest::SetUpCommandLine(command_line
);
43 command_line
->AppendSwitch(switches::kDisablePopupBlocking
);
44 command_line
->AppendSwitch(extensions::switches::kAllowHTTPBackgroundPage
);
47 bool CreateApp(const std::string
& app_manifest
,
48 base::FilePath
* app_dir
) {
49 if (!app_dir_
.CreateUniqueTempDir()) {
50 LOG(ERROR
) << "Unable to create a temporary directory.";
53 base::FilePath manifest_path
= app_dir_
.path().AppendASCII("manifest.json");
54 int bytes_written
= file_util::WriteFile(manifest_path
,
57 if (bytes_written
!= static_cast<int>(app_manifest
.size())) {
58 LOG(ERROR
) << "Unable to write complete manifest to file. Return code="
62 *app_dir
= app_dir_
.path();
66 bool WaitForBackgroundMode(bool expected_background_mode
) {
67 #if defined(OS_CHROMEOS)
68 // BackgroundMode is not supported on chromeos, so we should test the
69 // behavior of BackgroundContents, but not the background mode state itself.
72 BackgroundModeManager
* manager
=
73 g_browser_process
->background_mode_manager();
74 // If background mode is disabled on this platform (e.g. cros), then skip
76 if (!manager
|| !manager
->IsBackgroundModePrefEnabled()) {
77 DLOG(WARNING
) << "Skipping check - background mode disabled";
80 if (manager
->IsBackgroundModeActive() == expected_background_mode
)
83 // We are not currently in the expected state - wait for the state to
85 content::WindowedNotificationObserver
watcher(
86 chrome::NOTIFICATION_BACKGROUND_MODE_CHANGED
,
87 content::NotificationService::AllSources());
89 return manager
->IsBackgroundModeActive() == expected_background_mode
;
93 void CloseBrowser(Browser
* browser
) {
94 content::WindowedNotificationObserver
observer(
95 chrome::NOTIFICATION_BROWSER_CLOSED
,
96 content::NotificationService::AllSources());
97 browser
->window()->Close();
98 #if defined(OS_MACOSX)
99 // BrowserWindowController depends on the auto release pool being recycled
100 // in the message loop to delete itself, which frees the Browser object
101 // which fires this event.
102 AutoreleasePool()->Recycle();
107 void UnloadExtensionViaTask(const std::string
& id
) {
108 base::MessageLoop::current()->PostTask(
110 base::Bind(&AppBackgroundPageApiTest::UnloadExtension
, this, id
));
114 base::ScopedTempDir app_dir_
;
119 // Fixture to assist in testing v2 app background pages containing
120 // Native Client embeds.
121 class AppBackgroundPageNaClTest
: public AppBackgroundPageApiTest
{
123 AppBackgroundPageNaClTest()
125 PathService::Get(chrome::DIR_GEN_TEST_DATA
, &app_dir_
);
126 app_dir_
= app_dir_
.AppendASCII(
127 "ppapi/tests/extensions/background_keepalive/newlib");
129 virtual ~AppBackgroundPageNaClTest() {
132 virtual void SetUpCommandLine(CommandLine
* command_line
) OVERRIDE
{
133 AppBackgroundPageApiTest::SetUpCommandLine(command_line
);
134 command_line
->AppendSwitchASCII(
135 switches::kPpapiKeepAliveThrottle
, "50");
136 command_line
->AppendSwitchASCII(
137 extensions::switches::kEventPageIdleTime
, "1000");
138 command_line
->AppendSwitchASCII(
139 extensions::switches::kEventPageSuspendingTime
, "1000");
142 const Extension
* extension() { return extension_
; }
145 void LaunchTestingApp() {
146 extension_
= LoadExtension(app_dir_
);
147 ASSERT_TRUE(extension_
);
151 base::FilePath app_dir_
;
152 const Extension
* extension_
;
155 // Produces an extensions::ProcessManager::ImpulseCallbackForTesting callback
156 // that will match a specified goal and can be waited on.
157 class ImpulseCallbackCounter
{
159 explicit ImpulseCallbackCounter(extensions::ProcessManager
* manager
,
160 const std::string
& extension_id
)
164 extension_id_(extension_id
) {
167 extensions::ProcessManager::ImpulseCallbackForTesting
168 SetGoalAndGetCallback(int goal
) {
171 message_loop_runner_
= new content::MessageLoopRunner();
172 return base::Bind(&ImpulseCallbackCounter::ImpulseCallback
,
173 base::Unretained(this),
174 message_loop_runner_
->QuitClosure(),
179 message_loop_runner_
->Run();
182 void ImpulseCallback(
183 const base::Closure
& quit_callback
,
184 const std::string
& extension_id_from_test
,
185 const std::string
& extension_id_from_manager
) {
186 if (extension_id_from_test
== extension_id_from_manager
) {
187 if (++observed_
>= goal_
) {
188 // Clear callback to free reference to message loop.
189 manager_
->SetKeepaliveImpulseCallbackForTesting(
190 extensions::ProcessManager::ImpulseCallbackForTesting());
191 manager_
->SetKeepaliveImpulseDecrementCallbackForTesting(
192 extensions::ProcessManager::ImpulseCallbackForTesting());
200 extensions::ProcessManager
* manager_
;
201 const std::string extension_id_
;
202 scoped_refptr
<content::MessageLoopRunner
> message_loop_runner_
;
207 // Disable on Mac only. http://crbug.com/95139
208 #if defined(OS_MACOSX)
209 #define MAYBE_Basic DISABLED_Basic
211 #define MAYBE_Basic Basic
214 IN_PROC_BROWSER_TEST_F(AppBackgroundPageApiTest
, MAYBE_Basic
) {
215 host_resolver()->AddRule("a.com", "127.0.0.1");
216 ASSERT_TRUE(StartEmbeddedTestServer());
218 std::string app_manifest
= base::StringPrintf(
220 " \"name\": \"App\","
221 " \"version\": \"0.1\","
222 " \"manifest_version\": 2,"
228 " \"web_url\": \"http://a.com:%d/\""
231 " \"permissions\": [\"background\"]"
233 embedded_test_server()->port());
235 base::FilePath app_dir
;
236 ASSERT_TRUE(CreateApp(app_manifest
, &app_dir
));
237 ASSERT_TRUE(LoadExtension(app_dir
));
238 // Background mode should not be active until a background page is created.
239 ASSERT_TRUE(WaitForBackgroundMode(false));
240 ASSERT_TRUE(RunExtensionTest("app_background_page/basic")) << message_
;
241 // The test closes the background contents, so we should fall back to no
242 // background mode at the end.
243 ASSERT_TRUE(WaitForBackgroundMode(false));
246 // Crashy, http://crbug.com/69215.
247 IN_PROC_BROWSER_TEST_F(AppBackgroundPageApiTest
, DISABLED_LacksPermission
) {
248 host_resolver()->AddRule("a.com", "127.0.0.1");
249 ASSERT_TRUE(StartEmbeddedTestServer());
251 std::string app_manifest
= base::StringPrintf(
253 " \"name\": \"App\","
254 " \"version\": \"0.1\","
255 " \"manifest_version\": 2,"
261 " \"web_url\": \"http://a.com:%d/\""
265 embedded_test_server()->port());
267 base::FilePath app_dir
;
268 ASSERT_TRUE(CreateApp(app_manifest
, &app_dir
));
269 ASSERT_TRUE(LoadExtension(app_dir
));
270 ASSERT_TRUE(RunExtensionTest("app_background_page/lacks_permission"))
272 ASSERT_TRUE(WaitForBackgroundMode(false));
275 IN_PROC_BROWSER_TEST_F(AppBackgroundPageApiTest
, ManifestBackgroundPage
) {
276 host_resolver()->AddRule("a.com", "127.0.0.1");
277 ASSERT_TRUE(StartEmbeddedTestServer());
279 std::string app_manifest
= base::StringPrintf(
281 " \"name\": \"App\","
282 " \"version\": \"0.1\","
283 " \"manifest_version\": 2,"
289 " \"web_url\": \"http://a.com:%d/\""
292 " \"permissions\": [\"background\"],"
294 " \"page\": \"http://a.com:%d/test.html\""
297 embedded_test_server()->port(),
298 embedded_test_server()->port());
300 base::FilePath app_dir
;
301 ASSERT_TRUE(CreateApp(app_manifest
, &app_dir
));
302 // Background mode should not be active now because no background app was
304 ASSERT_TRUE(LoadExtension(app_dir
));
305 // Background mode be active now because a background page was created when
306 // the app was loaded.
307 ASSERT_TRUE(WaitForBackgroundMode(true));
309 const Extension
* extension
= GetSingleLoadedExtension();
311 BackgroundContentsServiceFactory::GetForProfile(browser()->profile())->
312 GetAppBackgroundContents(ASCIIToUTF16(extension
->id())));
313 UnloadExtension(extension
->id());
316 IN_PROC_BROWSER_TEST_F(AppBackgroundPageApiTest
, NoJsBackgroundPage
) {
317 // Keep the task manager up through this test to verify that a crash doesn't
318 // happen when window.open creates a background page that switches
319 // RenderViewHosts. See http://crbug.com/165138.
320 chrome::ShowTaskManager(browser());
322 // Make sure that no BackgroundContentses get deleted (a signal that repeated
323 // window.open calls recreate instances, instead of being no-ops).
324 content::TestNotificationTracker background_deleted_tracker
;
325 background_deleted_tracker
.ListenFor(
326 chrome::NOTIFICATION_BACKGROUND_CONTENTS_DELETED
,
327 content::Source
<Profile
>(browser()->profile()));
329 host_resolver()->AddRule("a.com", "127.0.0.1");
330 ASSERT_TRUE(StartEmbeddedTestServer());
332 std::string app_manifest
= base::StringPrintf(
334 " \"name\": \"App\","
335 " \"version\": \"0.1\","
336 " \"manifest_version\": 2,"
342 " \"web_url\": \"http://a.com:%d/test.html\""
345 " \"permissions\": [\"background\"],"
347 " \"allow_js_access\": false"
350 embedded_test_server()->port());
352 base::FilePath app_dir
;
353 ASSERT_TRUE(CreateApp(app_manifest
, &app_dir
));
354 ASSERT_TRUE(LoadExtension(app_dir
));
356 // There isn't a background page loaded initially.
357 const Extension
* extension
= GetSingleLoadedExtension();
359 BackgroundContentsServiceFactory::GetForProfile(browser()->profile())->
360 GetAppBackgroundContents(ASCIIToUTF16(extension
->id())));
361 // The test makes sure that window.open returns null.
362 ASSERT_TRUE(RunExtensionTest("app_background_page/no_js")) << message_
;
363 // And after it runs there should be a background page.
365 BackgroundContentsServiceFactory::GetForProfile(browser()->profile())->
366 GetAppBackgroundContents(ASCIIToUTF16(extension
->id())));
368 EXPECT_EQ(0u, background_deleted_tracker
.size());
369 UnloadExtension(extension
->id());
372 IN_PROC_BROWSER_TEST_F(AppBackgroundPageApiTest
, NoJsManifestBackgroundPage
) {
373 host_resolver()->AddRule("a.com", "127.0.0.1");
374 ASSERT_TRUE(StartEmbeddedTestServer());
376 std::string app_manifest
= base::StringPrintf(
378 " \"name\": \"App\","
379 " \"version\": \"0.1\","
380 " \"manifest_version\": 2,"
386 " \"web_url\": \"http://a.com:%d/\""
389 " \"permissions\": [\"background\"],"
391 " \"page\": \"http://a.com:%d/bg.html\","
392 " \"allow_js_access\": false"
395 embedded_test_server()->port(),
396 embedded_test_server()->port());
398 base::FilePath app_dir
;
399 ASSERT_TRUE(CreateApp(app_manifest
, &app_dir
));
400 ASSERT_TRUE(LoadExtension(app_dir
));
402 // The background page should load, but window.open should return null.
403 const Extension
* extension
= GetSingleLoadedExtension();
405 BackgroundContentsServiceFactory::GetForProfile(browser()->profile())->
406 GetAppBackgroundContents(ASCIIToUTF16(extension
->id())));
407 ASSERT_TRUE(RunExtensionTest("app_background_page/no_js_manifest")) <<
409 UnloadExtension(extension
->id());
412 IN_PROC_BROWSER_TEST_F(AppBackgroundPageApiTest
, OpenTwoBackgroundPages
) {
413 host_resolver()->AddRule("a.com", "127.0.0.1");
414 ASSERT_TRUE(StartEmbeddedTestServer());
416 std::string app_manifest
= base::StringPrintf(
418 " \"name\": \"App\","
419 " \"version\": \"0.1\","
420 " \"manifest_version\": 2,"
426 " \"web_url\": \"http://a.com:%d/\""
429 " \"permissions\": [\"background\"]"
431 embedded_test_server()->port());
433 base::FilePath app_dir
;
434 ASSERT_TRUE(CreateApp(app_manifest
, &app_dir
));
435 ASSERT_TRUE(LoadExtension(app_dir
));
436 const Extension
* extension
= GetSingleLoadedExtension();
437 ASSERT_TRUE(RunExtensionTest("app_background_page/two_pages")) << message_
;
438 UnloadExtension(extension
->id());
441 IN_PROC_BROWSER_TEST_F(AppBackgroundPageApiTest
, OpenTwoPagesWithManifest
) {
442 host_resolver()->AddRule("a.com", "127.0.0.1");
443 ASSERT_TRUE(StartEmbeddedTestServer());
445 std::string app_manifest
= base::StringPrintf(
447 " \"name\": \"App\","
448 " \"version\": \"0.1\","
449 " \"manifest_version\": 2,"
455 " \"web_url\": \"http://a.com:%d/\""
459 " \"page\": \"http://a.com:%d/bg.html\""
461 " \"permissions\": [\"background\"]"
463 embedded_test_server()->port(),
464 embedded_test_server()->port());
466 base::FilePath app_dir
;
467 ASSERT_TRUE(CreateApp(app_manifest
, &app_dir
));
468 ASSERT_TRUE(LoadExtension(app_dir
));
469 const Extension
* extension
= GetSingleLoadedExtension();
470 ASSERT_TRUE(RunExtensionTest("app_background_page/two_with_manifest")) <<
472 UnloadExtension(extension
->id());
475 // Times out occasionally -- see crbug.com/108493
476 IN_PROC_BROWSER_TEST_F(AppBackgroundPageApiTest
, DISABLED_OpenPopupFromBGPage
) {
477 host_resolver()->AddRule("a.com", "127.0.0.1");
478 ASSERT_TRUE(StartEmbeddedTestServer());
480 std::string app_manifest
= base::StringPrintf(
482 " \"name\": \"App\","
483 " \"version\": \"0.1\","
484 " \"manifest_version\": 2,"
490 " \"web_url\": \"http://a.com:%d/\""
493 " \"background\": { \"page\": \"http://a.com:%d/extensions/api_test/"
494 "app_background_page/bg_open/bg_open_bg.html\" },"
495 " \"permissions\": [\"background\"]"
497 embedded_test_server()->port(),
498 embedded_test_server()->port());
500 base::FilePath app_dir
;
501 ASSERT_TRUE(CreateApp(app_manifest
, &app_dir
));
502 ASSERT_TRUE(LoadExtension(app_dir
));
503 ASSERT_TRUE(RunExtensionTest("app_background_page/bg_open")) << message_
;
506 IN_PROC_BROWSER_TEST_F(AppBackgroundPageApiTest
, DISABLED_OpenThenClose
) {
507 host_resolver()->AddRule("a.com", "127.0.0.1");
508 ASSERT_TRUE(StartEmbeddedTestServer());
510 std::string app_manifest
= base::StringPrintf(
512 " \"name\": \"App\","
513 " \"version\": \"0.1\","
514 " \"manifest_version\": 2,"
520 " \"web_url\": \"http://a.com:%d/\""
523 " \"permissions\": [\"background\"]"
525 embedded_test_server()->port());
527 base::FilePath app_dir
;
528 ASSERT_TRUE(CreateApp(app_manifest
, &app_dir
));
529 ASSERT_TRUE(LoadExtension(app_dir
));
530 // There isn't a background page loaded initially.
531 const Extension
* extension
= GetSingleLoadedExtension();
533 BackgroundContentsServiceFactory::GetForProfile(browser()->profile())->
534 GetAppBackgroundContents(ASCIIToUTF16(extension
->id())));
535 // Background mode should not be active until a background page is created.
536 ASSERT_TRUE(WaitForBackgroundMode(false));
537 ASSERT_TRUE(RunExtensionTest("app_background_page/basic_open")) << message_
;
538 // Background mode should be active now because a background page was created.
539 ASSERT_TRUE(WaitForBackgroundMode(true));
541 BackgroundContentsServiceFactory::GetForProfile(browser()->profile())->
542 GetAppBackgroundContents(ASCIIToUTF16(extension
->id())));
543 // Now close the BackgroundContents.
544 ASSERT_TRUE(RunExtensionTest("app_background_page/basic_close")) << message_
;
545 // Background mode should no longer be active.
546 ASSERT_TRUE(WaitForBackgroundMode(false));
548 BackgroundContentsServiceFactory::GetForProfile(browser()->profile())->
549 GetAppBackgroundContents(ASCIIToUTF16(extension
->id())));
552 IN_PROC_BROWSER_TEST_F(AppBackgroundPageApiTest
, UnloadExtensionWhileHidden
) {
553 host_resolver()->AddRule("a.com", "127.0.0.1");
554 ASSERT_TRUE(StartEmbeddedTestServer());
556 std::string app_manifest
= base::StringPrintf(
558 " \"name\": \"App\","
559 " \"version\": \"0.1\","
560 " \"manifest_version\": 2,"
566 " \"web_url\": \"http://a.com:%d/\""
569 " \"permissions\": [\"background\"],"
571 " \"page\": \"http://a.com:%d/test.html\""
574 embedded_test_server()->port(),
575 embedded_test_server()->port());
577 base::FilePath app_dir
;
578 ASSERT_TRUE(CreateApp(app_manifest
, &app_dir
));
579 // Background mode should not be active now because no background app was
581 ASSERT_TRUE(LoadExtension(app_dir
));
582 // Background mode be active now because a background page was created when
583 // the app was loaded.
584 ASSERT_TRUE(WaitForBackgroundMode(true));
586 const Extension
* extension
= GetSingleLoadedExtension();
588 BackgroundContentsServiceFactory::GetForProfile(browser()->profile())->
589 GetAppBackgroundContents(ASCIIToUTF16(extension
->id())));
591 // Close all browsers - app should continue running.
592 set_exit_when_last_browser_closes(false);
593 CloseBrowser(browser());
595 // Post a task to unload the extension - this should cause Chrome to exit
596 // cleanly (not crash).
597 UnloadExtensionViaTask(extension
->id());
598 content::RunAllPendingInMessageLoop();
599 ASSERT_TRUE(WaitForBackgroundMode(false));
602 // Verify active NaCl embeds cause many keepalive impulses to be sent.
603 IN_PROC_BROWSER_TEST_F(AppBackgroundPageNaClTest
, BackgroundKeepaliveActive
) {
604 ExtensionTestMessageListener
nacl_modules_loaded("nacl_modules_loaded", true);
606 extensions::ProcessManager
* manager
=
607 extensions::ExtensionSystem::Get(browser()->profile())->process_manager();
608 ImpulseCallbackCounter
active_impulse_counter(manager
, extension()->id());
609 EXPECT_TRUE(nacl_modules_loaded
.WaitUntilSatisfied());
611 // Target .5 seconds: .5 seconds / 50ms throttle * 2 embeds == 20 impulses.
612 manager
->SetKeepaliveImpulseCallbackForTesting(
613 active_impulse_counter
.SetGoalAndGetCallback(20));
614 active_impulse_counter
.Wait();
617 // Verify that nacl modules that go idle will not send keepalive impulses.
618 // Disabled on windows due to Win XP failures:
619 // DesktopWindowTreeHostWin::HandleCreate not implemented. crbug.com/331954
621 #define MAYBE_BackgroundKeepaliveIdle DISABLED_BackgroundKeepaliveIdle
623 // ASAN errors appearing: https://crbug.com/332440
624 #define MAYBE_BackgroundKeepaliveIdle DISABLED_BackgroundKeepaliveIdle
626 IN_PROC_BROWSER_TEST_F(AppBackgroundPageNaClTest
,
627 MAYBE_BackgroundKeepaliveIdle
) {
628 ExtensionTestMessageListener
nacl_modules_loaded("nacl_modules_loaded", true);
630 extensions::ProcessManager
* manager
=
631 extensions::ExtensionSystem::Get(browser()->profile())->process_manager();
632 ImpulseCallbackCounter
idle_impulse_counter(manager
, extension()->id());
633 EXPECT_TRUE(nacl_modules_loaded
.WaitUntilSatisfied());
635 manager
->SetKeepaliveImpulseDecrementCallbackForTesting(
636 idle_impulse_counter
.SetGoalAndGetCallback(1));
637 nacl_modules_loaded
.Reply("be idle");
638 idle_impulse_counter
.Wait();