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/location.h"
6 #include "base/path_service.h"
7 #include "base/single_thread_task_runner.h"
8 #include "base/strings/stringprintf.h"
9 #include "base/strings/utf_string_conversions.h"
10 #include "base/thread_task_runner_handle.h"
11 #include "chrome/browser/background/background_contents_service.h"
12 #include "chrome/browser/background/background_contents_service_factory.h"
13 #include "chrome/browser/background/background_mode_manager.h"
14 #include "chrome/browser/browser_process.h"
15 #include "chrome/browser/chrome_notification_types.h"
16 #include "chrome/browser/extensions/extension_apitest.h"
17 #include "chrome/browser/extensions/extension_service.h"
18 #include "chrome/browser/profiles/profile.h"
19 #include "chrome/browser/ui/browser.h"
20 #include "chrome/browser/ui/browser_dialogs.h"
21 #include "chrome/browser/ui/browser_window.h"
22 #include "chrome/browser/ui/extensions/application_launch.h"
23 #include "chrome/common/chrome_paths.h"
24 #include "chrome/common/chrome_switches.h"
25 #include "content/public/browser/notification_service.h"
26 #include "content/public/test/test_notification_tracker.h"
27 #include "content/public/test/test_utils.h"
28 #include "extensions/browser/process_manager.h"
29 #include "extensions/common/extension.h"
30 #include "extensions/common/switches.h"
31 #include "extensions/test/extension_test_message_listener.h"
32 #include "net/dns/mock_host_resolver.h"
33 #include "net/test/embedded_test_server/embedded_test_server.h"
35 #if !defined(DISABLE_NACL)
36 #include "components/nacl/browser/nacl_process_host.h"
39 #if defined(OS_MACOSX)
40 #include "base/mac/scoped_nsautorelease_pool.h"
43 using base::ASCIIToUTF16
;
44 using extensions::Extension
;
46 class AppBackgroundPageApiTest
: public ExtensionApiTest
{
48 void SetUpCommandLine(base::CommandLine
* command_line
) override
{
49 ExtensionApiTest::SetUpCommandLine(command_line
);
50 command_line
->AppendSwitch(switches::kDisablePopupBlocking
);
51 command_line
->AppendSwitch(extensions::switches::kAllowHTTPBackgroundPage
);
54 bool CreateApp(const std::string
& app_manifest
,
55 base::FilePath
* app_dir
) {
56 if (!app_dir_
.CreateUniqueTempDir()) {
57 LOG(ERROR
) << "Unable to create a temporary directory.";
60 base::FilePath manifest_path
= app_dir_
.path().AppendASCII("manifest.json");
61 int bytes_written
= base::WriteFile(manifest_path
,
64 if (bytes_written
!= static_cast<int>(app_manifest
.size())) {
65 LOG(ERROR
) << "Unable to write complete manifest to file. Return code="
69 *app_dir
= app_dir_
.path();
73 bool WaitForBackgroundMode(bool expected_background_mode
) {
74 #if defined(OS_CHROMEOS)
75 // BackgroundMode is not supported on chromeos, so we should test the
76 // behavior of BackgroundContents, but not the background mode state itself.
79 BackgroundModeManager
* manager
=
80 g_browser_process
->background_mode_manager();
81 // If background mode is disabled on this platform (e.g. cros), then skip
83 if (!manager
|| !manager
->IsBackgroundModePrefEnabled()) {
84 DLOG(WARNING
) << "Skipping check - background mode disabled";
87 if (manager
->IsBackgroundModeActive() == expected_background_mode
)
90 // We are not currently in the expected state - wait for the state to
92 content::WindowedNotificationObserver
watcher(
93 chrome::NOTIFICATION_BACKGROUND_MODE_CHANGED
,
94 content::NotificationService::AllSources());
96 return manager
->IsBackgroundModeActive() == expected_background_mode
;
100 void CloseBrowser(Browser
* browser
) {
101 content::WindowedNotificationObserver
observer(
102 chrome::NOTIFICATION_BROWSER_CLOSED
,
103 content::NotificationService::AllSources());
104 browser
->window()->Close();
105 #if defined(OS_MACOSX)
106 // BrowserWindowController depends on the auto release pool being recycled
107 // in the message loop to delete itself, which frees the Browser object
108 // which fires this event.
109 AutoreleasePool()->Recycle();
114 void UnloadExtensionViaTask(const std::string
& id
) {
115 base::ThreadTaskRunnerHandle::Get()->PostTask(
117 base::Bind(&AppBackgroundPageApiTest::UnloadExtension
, this, id
));
121 base::ScopedTempDir app_dir_
;
126 // Fixture to assist in testing v2 app background pages containing
127 // Native Client embeds.
128 class AppBackgroundPageNaClTest
: public AppBackgroundPageApiTest
{
130 AppBackgroundPageNaClTest()
131 : extension_(NULL
) {}
132 ~AppBackgroundPageNaClTest() override
{}
134 void SetUpOnMainThread() override
{
135 AppBackgroundPageApiTest::SetUpOnMainThread();
136 #if !defined(DISABLE_NACL)
137 nacl::NaClProcessHost::SetPpapiKeepAliveThrottleForTesting(50);
139 extensions::ProcessManager::SetEventPageIdleTimeForTesting(1000);
140 extensions::ProcessManager::SetEventPageSuspendingTimeForTesting(1000);
143 const Extension
* extension() { return extension_
; }
146 void LaunchTestingApp() {
147 base::FilePath app_dir
;
148 PathService::Get(chrome::DIR_GEN_TEST_DATA
, &app_dir
);
149 app_dir
= app_dir
.AppendASCII(
150 "ppapi/tests/extensions/background_keepalive/newlib");
151 extension_
= LoadExtension(app_dir
);
152 ASSERT_TRUE(extension_
);
156 const Extension
* extension_
;
159 // Produces an extensions::ProcessManager::ImpulseCallbackForTesting callback
160 // that will match a specified goal and can be waited on.
161 class ImpulseCallbackCounter
{
163 explicit ImpulseCallbackCounter(extensions::ProcessManager
* manager
,
164 const std::string
& extension_id
)
168 extension_id_(extension_id
) {
171 extensions::ProcessManager::ImpulseCallbackForTesting
172 SetGoalAndGetCallback(int goal
) {
175 message_loop_runner_
= new content::MessageLoopRunner();
176 return base::Bind(&ImpulseCallbackCounter::ImpulseCallback
,
177 base::Unretained(this),
178 message_loop_runner_
->QuitClosure(),
183 message_loop_runner_
->Run();
186 void ImpulseCallback(
187 const base::Closure
& quit_callback
,
188 const std::string
& extension_id_from_test
,
189 const std::string
& extension_id_from_manager
) {
190 if (extension_id_from_test
== extension_id_from_manager
) {
191 if (++observed_
>= goal_
) {
192 // Clear callback to free reference to message loop.
193 manager_
->SetKeepaliveImpulseCallbackForTesting(
194 extensions::ProcessManager::ImpulseCallbackForTesting());
195 manager_
->SetKeepaliveImpulseDecrementCallbackForTesting(
196 extensions::ProcessManager::ImpulseCallbackForTesting());
204 extensions::ProcessManager
* manager_
;
205 const std::string extension_id_
;
206 scoped_refptr
<content::MessageLoopRunner
> message_loop_runner_
;
211 // Disable on Mac only. http://crbug.com/95139
212 #if defined(OS_MACOSX)
213 #define MAYBE_Basic DISABLED_Basic
215 #define MAYBE_Basic Basic
218 IN_PROC_BROWSER_TEST_F(AppBackgroundPageApiTest
, MAYBE_Basic
) {
219 host_resolver()->AddRule("a.com", "127.0.0.1");
220 ASSERT_TRUE(StartEmbeddedTestServer());
222 std::string app_manifest
= base::StringPrintf(
224 " \"name\": \"App\","
225 " \"version\": \"0.1\","
226 " \"manifest_version\": 2,"
232 " \"web_url\": \"http://a.com:%u/\""
235 " \"permissions\": [\"background\"]"
237 embedded_test_server()->port());
239 base::FilePath app_dir
;
240 ASSERT_TRUE(CreateApp(app_manifest
, &app_dir
));
241 ASSERT_TRUE(LoadExtension(app_dir
));
242 // Background mode should not be active until a background page is created.
243 ASSERT_TRUE(WaitForBackgroundMode(false));
244 ASSERT_TRUE(RunExtensionTest("app_background_page/basic")) << message_
;
245 // The test closes the background contents, so we should fall back to no
246 // background mode at the end.
247 ASSERT_TRUE(WaitForBackgroundMode(false));
250 // Crashy, http://crbug.com/69215.
251 IN_PROC_BROWSER_TEST_F(AppBackgroundPageApiTest
, DISABLED_LacksPermission
) {
252 host_resolver()->AddRule("a.com", "127.0.0.1");
253 ASSERT_TRUE(StartEmbeddedTestServer());
255 std::string app_manifest
= base::StringPrintf(
257 " \"name\": \"App\","
258 " \"version\": \"0.1\","
259 " \"manifest_version\": 2,"
265 " \"web_url\": \"http://a.com:%u/\""
269 embedded_test_server()->port());
271 base::FilePath app_dir
;
272 ASSERT_TRUE(CreateApp(app_manifest
, &app_dir
));
273 ASSERT_TRUE(LoadExtension(app_dir
));
274 ASSERT_TRUE(RunExtensionTest("app_background_page/lacks_permission"))
276 ASSERT_TRUE(WaitForBackgroundMode(false));
279 IN_PROC_BROWSER_TEST_F(AppBackgroundPageApiTest
, ManifestBackgroundPage
) {
280 host_resolver()->AddRule("a.com", "127.0.0.1");
281 ASSERT_TRUE(StartEmbeddedTestServer());
283 std::string app_manifest
= base::StringPrintf(
285 " \"name\": \"App\","
286 " \"version\": \"0.1\","
287 " \"manifest_version\": 2,"
293 " \"web_url\": \"http://a.com:%u/\""
296 " \"permissions\": [\"background\"],"
298 " \"page\": \"http://a.com:%u/test.html\""
301 embedded_test_server()->port(),
302 embedded_test_server()->port());
304 base::FilePath app_dir
;
305 ASSERT_TRUE(CreateApp(app_manifest
, &app_dir
));
306 // Background mode should not be active now because no background app was
308 ASSERT_TRUE(LoadExtension(app_dir
));
309 // Background mode be active now because a background page was created when
310 // the app was loaded.
311 ASSERT_TRUE(WaitForBackgroundMode(true));
313 const Extension
* extension
= GetSingleLoadedExtension();
315 BackgroundContentsServiceFactory::GetForProfile(browser()->profile())->
316 GetAppBackgroundContents(ASCIIToUTF16(extension
->id())));
317 UnloadExtension(extension
->id());
320 IN_PROC_BROWSER_TEST_F(AppBackgroundPageApiTest
, NoJsBackgroundPage
) {
321 // Keep the task manager up through this test to verify that a crash doesn't
322 // happen when window.open creates a background page that switches
323 // RenderViewHosts. See http://crbug.com/165138.
324 chrome::ShowTaskManager(browser());
326 // Make sure that no BackgroundContentses get deleted (a signal that repeated
327 // window.open calls recreate instances, instead of being no-ops).
328 content::TestNotificationTracker background_deleted_tracker
;
329 background_deleted_tracker
.ListenFor(
330 chrome::NOTIFICATION_BACKGROUND_CONTENTS_DELETED
,
331 content::Source
<Profile
>(browser()->profile()));
333 host_resolver()->AddRule("a.com", "127.0.0.1");
334 ASSERT_TRUE(StartEmbeddedTestServer());
336 std::string app_manifest
= base::StringPrintf(
338 " \"name\": \"App\","
339 " \"version\": \"0.1\","
340 " \"manifest_version\": 2,"
346 " \"web_url\": \"http://a.com:%u/test.html\""
349 " \"permissions\": [\"background\"],"
351 " \"allow_js_access\": false"
354 embedded_test_server()->port());
356 base::FilePath app_dir
;
357 ASSERT_TRUE(CreateApp(app_manifest
, &app_dir
));
358 ASSERT_TRUE(LoadExtension(app_dir
));
360 // There isn't a background page loaded initially.
361 const Extension
* extension
= GetSingleLoadedExtension();
363 BackgroundContentsServiceFactory::GetForProfile(browser()->profile())->
364 GetAppBackgroundContents(ASCIIToUTF16(extension
->id())));
365 // The test makes sure that window.open returns null.
366 ASSERT_TRUE(RunExtensionTest("app_background_page/no_js")) << message_
;
367 // And after it runs there should be a background page.
369 BackgroundContentsServiceFactory::GetForProfile(browser()->profile())->
370 GetAppBackgroundContents(ASCIIToUTF16(extension
->id())));
372 EXPECT_EQ(0u, background_deleted_tracker
.size());
373 UnloadExtension(extension
->id());
376 IN_PROC_BROWSER_TEST_F(AppBackgroundPageApiTest
, NoJsManifestBackgroundPage
) {
377 host_resolver()->AddRule("a.com", "127.0.0.1");
378 ASSERT_TRUE(StartEmbeddedTestServer());
380 std::string app_manifest
= base::StringPrintf(
382 " \"name\": \"App\","
383 " \"version\": \"0.1\","
384 " \"manifest_version\": 2,"
390 " \"web_url\": \"http://a.com:%u/\""
393 " \"permissions\": [\"background\"],"
395 " \"page\": \"http://a.com:%u/bg.html\","
396 " \"allow_js_access\": false"
399 embedded_test_server()->port(),
400 embedded_test_server()->port());
402 base::FilePath app_dir
;
403 ASSERT_TRUE(CreateApp(app_manifest
, &app_dir
));
404 ASSERT_TRUE(LoadExtension(app_dir
));
406 // The background page should load, but window.open should return null.
407 const Extension
* extension
= GetSingleLoadedExtension();
409 BackgroundContentsServiceFactory::GetForProfile(browser()->profile())->
410 GetAppBackgroundContents(ASCIIToUTF16(extension
->id())));
411 ASSERT_TRUE(RunExtensionTest("app_background_page/no_js_manifest")) <<
413 UnloadExtension(extension
->id());
416 IN_PROC_BROWSER_TEST_F(AppBackgroundPageApiTest
, OpenTwoBackgroundPages
) {
417 host_resolver()->AddRule("a.com", "127.0.0.1");
418 ASSERT_TRUE(StartEmbeddedTestServer());
420 std::string app_manifest
= base::StringPrintf(
422 " \"name\": \"App\","
423 " \"version\": \"0.1\","
424 " \"manifest_version\": 2,"
430 " \"web_url\": \"http://a.com:%u/\""
433 " \"permissions\": [\"background\"]"
435 embedded_test_server()->port());
437 base::FilePath app_dir
;
438 ASSERT_TRUE(CreateApp(app_manifest
, &app_dir
));
439 ASSERT_TRUE(LoadExtension(app_dir
));
440 const Extension
* extension
= GetSingleLoadedExtension();
441 ASSERT_TRUE(RunExtensionTest("app_background_page/two_pages")) << message_
;
442 UnloadExtension(extension
->id());
445 IN_PROC_BROWSER_TEST_F(AppBackgroundPageApiTest
, OpenTwoPagesWithManifest
) {
446 host_resolver()->AddRule("a.com", "127.0.0.1");
447 ASSERT_TRUE(StartEmbeddedTestServer());
449 std::string app_manifest
= base::StringPrintf(
451 " \"name\": \"App\","
452 " \"version\": \"0.1\","
453 " \"manifest_version\": 2,"
459 " \"web_url\": \"http://a.com:%u/\""
463 " \"page\": \"http://a.com:%u/bg.html\""
465 " \"permissions\": [\"background\"]"
467 embedded_test_server()->port(),
468 embedded_test_server()->port());
470 base::FilePath app_dir
;
471 ASSERT_TRUE(CreateApp(app_manifest
, &app_dir
));
472 ASSERT_TRUE(LoadExtension(app_dir
));
473 const Extension
* extension
= GetSingleLoadedExtension();
474 ASSERT_TRUE(RunExtensionTest("app_background_page/two_with_manifest")) <<
476 UnloadExtension(extension
->id());
479 // Times out occasionally -- see crbug.com/108493
480 IN_PROC_BROWSER_TEST_F(AppBackgroundPageApiTest
, DISABLED_OpenPopupFromBGPage
) {
481 host_resolver()->AddRule("a.com", "127.0.0.1");
482 ASSERT_TRUE(StartEmbeddedTestServer());
484 std::string app_manifest
= base::StringPrintf(
486 " \"name\": \"App\","
487 " \"version\": \"0.1\","
488 " \"manifest_version\": 2,"
494 " \"web_url\": \"http://a.com:%u/\""
497 " \"background\": { \"page\": \"http://a.com:%u/extensions/api_test/"
498 "app_background_page/bg_open/bg_open_bg.html\" },"
499 " \"permissions\": [\"background\"]"
501 embedded_test_server()->port(),
502 embedded_test_server()->port());
504 base::FilePath app_dir
;
505 ASSERT_TRUE(CreateApp(app_manifest
, &app_dir
));
506 ASSERT_TRUE(LoadExtension(app_dir
));
507 ASSERT_TRUE(RunExtensionTest("app_background_page/bg_open")) << message_
;
510 IN_PROC_BROWSER_TEST_F(AppBackgroundPageApiTest
, DISABLED_OpenThenClose
) {
511 host_resolver()->AddRule("a.com", "127.0.0.1");
512 ASSERT_TRUE(StartEmbeddedTestServer());
514 std::string app_manifest
= base::StringPrintf(
516 " \"name\": \"App\","
517 " \"version\": \"0.1\","
518 " \"manifest_version\": 2,"
524 " \"web_url\": \"http://a.com:%u/\""
527 " \"permissions\": [\"background\"]"
529 embedded_test_server()->port());
531 base::FilePath app_dir
;
532 ASSERT_TRUE(CreateApp(app_manifest
, &app_dir
));
533 ASSERT_TRUE(LoadExtension(app_dir
));
534 // There isn't a background page loaded initially.
535 const Extension
* extension
= GetSingleLoadedExtension();
537 BackgroundContentsServiceFactory::GetForProfile(browser()->profile())->
538 GetAppBackgroundContents(ASCIIToUTF16(extension
->id())));
539 // Background mode should not be active until a background page is created.
540 ASSERT_TRUE(WaitForBackgroundMode(false));
541 ASSERT_TRUE(RunExtensionTest("app_background_page/basic_open")) << message_
;
542 // Background mode should be active now because a background page was created.
543 ASSERT_TRUE(WaitForBackgroundMode(true));
545 BackgroundContentsServiceFactory::GetForProfile(browser()->profile())->
546 GetAppBackgroundContents(ASCIIToUTF16(extension
->id())));
547 // Now close the BackgroundContents.
548 ASSERT_TRUE(RunExtensionTest("app_background_page/basic_close")) << message_
;
549 // Background mode should no longer be active.
550 ASSERT_TRUE(WaitForBackgroundMode(false));
552 BackgroundContentsServiceFactory::GetForProfile(browser()->profile())->
553 GetAppBackgroundContents(ASCIIToUTF16(extension
->id())));
556 IN_PROC_BROWSER_TEST_F(AppBackgroundPageApiTest
, UnloadExtensionWhileHidden
) {
557 host_resolver()->AddRule("a.com", "127.0.0.1");
558 ASSERT_TRUE(StartEmbeddedTestServer());
560 std::string app_manifest
= base::StringPrintf(
562 " \"name\": \"App\","
563 " \"version\": \"0.1\","
564 " \"manifest_version\": 2,"
570 " \"web_url\": \"http://a.com:%u/\""
573 " \"permissions\": [\"background\"],"
575 " \"page\": \"http://a.com:%u/test.html\""
578 embedded_test_server()->port(),
579 embedded_test_server()->port());
581 base::FilePath app_dir
;
582 ASSERT_TRUE(CreateApp(app_manifest
, &app_dir
));
583 // Background mode should not be active now because no background app was
585 ASSERT_TRUE(LoadExtension(app_dir
));
586 // Background mode be active now because a background page was created when
587 // the app was loaded.
588 ASSERT_TRUE(WaitForBackgroundMode(true));
590 const Extension
* extension
= GetSingleLoadedExtension();
592 BackgroundContentsServiceFactory::GetForProfile(browser()->profile())->
593 GetAppBackgroundContents(ASCIIToUTF16(extension
->id())));
595 // Close all browsers - app should continue running.
596 set_exit_when_last_browser_closes(false);
597 CloseBrowser(browser());
599 // Post a task to unload the extension - this should cause Chrome to exit
600 // cleanly (not crash).
601 UnloadExtensionViaTask(extension
->id());
602 content::RunAllPendingInMessageLoop();
603 ASSERT_TRUE(WaitForBackgroundMode(false));
606 // Verify active NaCl embeds cause many keepalive impulses to be sent.
607 // Disabled on Windows due to flakiness: http://crbug.com/346278
609 #define MAYBE_BackgroundKeepaliveActive DISABLED_BackgroundKeepaliveActive
611 // Disabling other platforms too since the test started failing
612 // consistently. http://crbug.com/490440
613 #define MAYBE_BackgroundKeepaliveActive DISABLED_BackgroundKeepaliveActive
615 IN_PROC_BROWSER_TEST_F(AppBackgroundPageNaClTest
,
616 MAYBE_BackgroundKeepaliveActive
) {
617 #if !defined(DISABLE_NACL)
618 ExtensionTestMessageListener
nacl_modules_loaded("nacl_modules_loaded", true);
620 extensions::ProcessManager
* manager
=
621 extensions::ProcessManager::Get(browser()->profile());
622 ImpulseCallbackCounter
active_impulse_counter(manager
, extension()->id());
623 EXPECT_TRUE(nacl_modules_loaded
.WaitUntilSatisfied());
625 // Target .5 seconds: .5 seconds / 50ms throttle * 2 embeds == 20 impulses.
626 manager
->SetKeepaliveImpulseCallbackForTesting(
627 active_impulse_counter
.SetGoalAndGetCallback(20));
628 active_impulse_counter
.Wait();
632 // Verify that nacl modules that go idle will not send keepalive impulses.
633 // Disabled on windows due to Win XP failures:
634 // DesktopWindowTreeHostWin::HandleCreate not implemented. crbug.com/331954
636 #define MAYBE_BackgroundKeepaliveIdle DISABLED_BackgroundKeepaliveIdle
638 // ASAN errors appearing: https://crbug.com/332440
639 #define MAYBE_BackgroundKeepaliveIdle DISABLED_BackgroundKeepaliveIdle
641 IN_PROC_BROWSER_TEST_F(AppBackgroundPageNaClTest
,
642 MAYBE_BackgroundKeepaliveIdle
) {
643 #if !defined(DISABLE_NACL)
644 ExtensionTestMessageListener
nacl_modules_loaded("nacl_modules_loaded", true);
646 extensions::ProcessManager
* manager
=
647 extensions::ProcessManager::Get(browser()->profile());
648 ImpulseCallbackCounter
idle_impulse_counter(manager
, extension()->id());
649 EXPECT_TRUE(nacl_modules_loaded
.WaitUntilSatisfied());
651 manager
->SetKeepaliveImpulseDecrementCallbackForTesting(
652 idle_impulse_counter
.SetGoalAndGetCallback(1));
653 nacl_modules_loaded
.Reply("be idle");
654 idle_impulse_counter
.Wait();