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.
10 #include "base/bind_helpers.h"
11 #include "base/callback.h"
12 #include "base/command_line.h"
13 #include "base/file_util.h"
14 #include "base/files/file_enumerator.h"
15 #include "base/files/file_path.h"
16 #include "base/files/scoped_temp_dir.h"
17 #include "base/memory/ref_counted.h"
18 #include "base/path_service.h"
19 #include "base/prefs/pref_service.h"
20 #include "base/run_loop.h"
21 #include "base/strings/string16.h"
22 #include "base/strings/string_util.h"
23 #include "base/strings/stringprintf.h"
24 #include "base/strings/utf_string_conversions.h"
25 #include "base/test/test_file_util.h"
26 #include "base/time/time.h"
27 #include "base/values.h"
28 #include "chrome/app/chrome_command_ids.h"
29 #include "chrome/browser/autocomplete/autocomplete_controller.h"
30 #include "chrome/browser/background/background_contents_service.h"
31 #include "chrome/browser/browser_process.h"
32 #include "chrome/browser/chrome_notification_types.h"
33 #include "chrome/browser/content_settings/tab_specific_content_settings.h"
34 #include "chrome/browser/devtools/devtools_window.h"
35 #include "chrome/browser/download/download_prefs.h"
36 #include "chrome/browser/extensions/api/messaging/native_message_process_host.h"
37 #include "chrome/browser/extensions/crx_installer.h"
38 #include "chrome/browser/extensions/extension_service.h"
39 #include "chrome/browser/extensions/unpacked_installer.h"
40 #include "chrome/browser/extensions/updater/extension_cache_fake.h"
41 #include "chrome/browser/extensions/updater/extension_updater.h"
42 #include "chrome/browser/infobars/infobar_service.h"
43 #include "chrome/browser/media/media_capture_devices_dispatcher.h"
44 #include "chrome/browser/media/media_stream_devices_controller.h"
45 #include "chrome/browser/metrics/variations/variations_service.h"
46 #include "chrome/browser/net/url_request_mock_util.h"
47 #include "chrome/browser/plugins/plugin_prefs.h"
48 #include "chrome/browser/policy/cloud/test_request_interceptor.h"
49 #include "chrome/browser/policy/profile_policy_connector.h"
50 #include "chrome/browser/policy/profile_policy_connector_factory.h"
51 #include "chrome/browser/prefs/session_startup_pref.h"
52 #include "chrome/browser/profiles/profile.h"
53 #include "chrome/browser/search/instant_service.h"
54 #include "chrome/browser/search/instant_service_factory.h"
55 #include "chrome/browser/search/search.h"
56 #include "chrome/browser/search_engines/template_url.h"
57 #include "chrome/browser/search_engines/template_url_service.h"
58 #include "chrome/browser/search_engines/template_url_service_factory.h"
59 #include "chrome/browser/translate/translate_infobar_delegate.h"
60 #include "chrome/browser/translate/translate_service.h"
61 #include "chrome/browser/translate/translate_tab_helper.h"
62 #include "chrome/browser/ui/bookmarks/bookmark_bar.h"
63 #include "chrome/browser/ui/browser.h"
64 #include "chrome/browser/ui/browser_commands.h"
65 #include "chrome/browser/ui/browser_list.h"
66 #include "chrome/browser/ui/browser_tabstrip.h"
67 #include "chrome/browser/ui/browser_window.h"
68 #include "chrome/browser/ui/host_desktop.h"
69 #include "chrome/browser/ui/omnibox/location_bar.h"
70 #include "chrome/browser/ui/omnibox/omnibox_edit_model.h"
71 #include "chrome/browser/ui/omnibox/omnibox_view.h"
72 #include "chrome/browser/ui/tabs/tab_strip_model.h"
73 #include "chrome/common/chrome_paths.h"
74 #include "chrome/common/chrome_switches.h"
75 #include "chrome/common/content_settings.h"
76 #include "chrome/common/content_settings_pattern.h"
77 #include "chrome/common/extensions/extension_constants.h"
78 #include "chrome/common/pref_names.h"
79 #include "chrome/common/url_constants.h"
80 #include "chrome/test/base/in_process_browser_test.h"
81 #include "chrome/test/base/test_switches.h"
82 #include "chrome/test/base/ui_test_utils.h"
83 #include "components/infobars/core/infobar.h"
84 #include "components/policy/core/browser/browser_policy_connector.h"
85 #include "components/policy/core/common/external_data_fetcher.h"
86 #include "components/policy/core/common/mock_configuration_policy_provider.h"
87 #include "components/policy/core/common/policy_map.h"
88 #include "components/policy/core/common/policy_pref_names.h"
89 #include "components/policy/core/common/policy_service.h"
90 #include "components/policy/core/common/policy_service_impl.h"
91 #include "content/public/browser/browser_child_process_host_iterator.h"
92 #include "content/public/browser/browser_context.h"
93 #include "content/public/browser/browser_thread.h"
94 #include "content/public/browser/child_process_data.h"
95 #include "content/public/browser/download_item.h"
96 #include "content/public/browser/download_manager.h"
97 #include "content/public/browser/gpu_data_manager.h"
98 #include "content/public/browser/notification_details.h"
99 #include "content/public/browser/notification_observer.h"
100 #include "content/public/browser/notification_registrar.h"
101 #include "content/public/browser/notification_service.h"
102 #include "content/public/browser/notification_source.h"
103 #include "content/public/browser/notification_types.h"
104 #include "content/public/browser/plugin_service.h"
105 #include "content/public/browser/render_process_host.h"
106 #include "content/public/browser/render_view_host.h"
107 #include "content/public/browser/web_contents.h"
108 #include "content/public/common/content_constants.h"
109 #include "content/public/common/content_paths.h"
110 #include "content/public/common/page_transition_types.h"
111 #include "content/public/common/process_type.h"
112 #include "content/public/common/result_codes.h"
113 #include "content/public/common/url_constants.h"
114 #include "content/public/common/webplugininfo.h"
115 #include "content/public/test/browser_test_utils.h"
116 #include "content/public/test/download_test_observer.h"
117 #include "content/public/test/mock_notification_observer.h"
118 #include "content/public/test/test_navigation_observer.h"
119 #include "content/public/test/test_utils.h"
120 #include "content/test/net/url_request_failed_job.h"
121 #include "content/test/net/url_request_mock_http_job.h"
122 #include "extensions/browser/extension_host.h"
123 #include "extensions/browser/extension_system.h"
124 #include "extensions/browser/process_manager.h"
125 #include "extensions/common/constants.h"
126 #include "extensions/common/extension.h"
127 #include "extensions/common/extension_set.h"
128 #include "grit/generated_resources.h"
129 #include "net/base/net_errors.h"
130 #include "net/base/net_util.h"
131 #include "net/base/url_util.h"
132 #include "net/http/http_stream_factory.h"
133 #include "net/url_request/url_request.h"
134 #include "net/url_request/url_request_filter.h"
135 #include "policy/policy_constants.h"
136 #include "testing/gmock/include/gmock/gmock.h"
137 #include "testing/gtest/include/gtest/gtest.h"
138 #include "third_party/WebKit/public/web/WebInputEvent.h"
139 #include "ui/base/l10n/l10n_util.h"
140 #include "ui/base/resource/resource_bundle.h"
141 #include "url/gurl.h"
143 #if defined(OS_CHROMEOS)
144 #include "ash/accelerators/accelerator_controller.h"
145 #include "ash/accelerators/accelerator_table.h"
146 #include "ash/magnifier/magnifier_constants.h"
147 #include "ash/shell.h"
148 #include "chrome/browser/chromeos/accessibility/accessibility_manager.h"
149 #include "chrome/browser/chromeos/accessibility/magnification_manager.h"
150 #include "chrome/browser/profiles/profile_manager.h"
151 #include "chrome/browser/ui/ash/screenshot_taker.h"
152 #include "chromeos/audio/cras_audio_handler.h"
155 #if !defined(OS_MACOSX)
156 #include "apps/app_window.h"
157 #include "apps/app_window_registry.h"
158 #include "apps/ui/native_app_window.h"
159 #include "base/basictypes.h"
160 #include "base/compiler_specific.h"
161 #include "chrome/browser/ui/extensions/application_launch.h"
162 #include "ui/base/window_open_disposition.h"
165 using content::BrowserThread;
166 using content::URLRequestMockHTTPJob;
168 using testing::Return;
175 #if defined(OS_CHROMEOS)
176 const int kOneHourInMs = 60 * 60 * 1000;
177 const int kThreeHoursInMs = 180 * 60 * 1000;
180 const char kURL[] = "http://example.com";
181 const char kCookieValue[] = "converted=true";
182 // Assigned to Philip J. Fry to fix eventually.
183 const char kCookieOptions[] = ";expires=Wed Jan 01 3000 00:00:00 GMT";
185 const base::FilePath::CharType kTestExtensionsDir[] =
186 FILE_PATH_LITERAL("extensions");
187 const base::FilePath::CharType kGoodCrxName[] = FILE_PATH_LITERAL("good.crx");
188 const base::FilePath::CharType kAdBlockCrxName[] =
189 FILE_PATH_LITERAL("adblock.crx");
190 const base::FilePath::CharType kHostedAppCrxName[] =
191 FILE_PATH_LITERAL("hosted_app.crx");
193 const char kGoodCrxId[] = "ldnnhddmnhbkjipkidpdiheffobcpfmf";
194 const char kAdBlockCrxId[] = "dojnnbeimaimaojcialkkgajdnefpgcn";
195 const char kHostedAppCrxId[] = "kbmnembihfiondgfjekmnmcbddelicoi";
197 const base::FilePath::CharType kGood2CrxManifestName[] =
198 FILE_PATH_LITERAL("good2_update_manifest.xml");
199 const base::FilePath::CharType kGoodV1CrxManifestName[] =
200 FILE_PATH_LITERAL("good_v1_update_manifest.xml");
201 const base::FilePath::CharType kGoodUnpackedExt[] =
202 FILE_PATH_LITERAL("good_unpacked");
203 const base::FilePath::CharType kAppUnpackedExt[] =
204 FILE_PATH_LITERAL("app");
206 #if !defined(OS_MACOSX)
207 const base::FilePath::CharType kUnpackedFullscreenAppName[] =
208 FILE_PATH_LITERAL("fullscreen_app");
209 #endif // !defined(OS_MACOSX)
211 // Filters requests to the hosts in |urls| and redirects them to the test data
212 // dir through URLRequestMockHTTPJobs.
213 void RedirectHostsToTestData(const char* const urls[], size_t size) {
214 // Map the given hosts to the test data dir.
215 net::URLRequestFilter* filter = net::URLRequestFilter::GetInstance();
216 base::FilePath base_path;
217 PathService::Get(chrome::DIR_TEST_DATA, &base_path);
218 for (size_t i = 0; i < size; ++i) {
219 const GURL url(urls[i]);
220 EXPECT_TRUE(url.is_valid());
221 filter->AddUrlProtocolHandler(url,
222 URLRequestMockHTTPJob::CreateProtocolHandler(base_path));
226 // Remove filters for requests to the hosts in |urls|.
227 void UndoRedirectHostsToTestData(const char* const urls[], size_t size) {
228 // Map the given hosts to the test data dir.
229 net::URLRequestFilter* filter = net::URLRequestFilter::GetInstance();
230 for (size_t i = 0; i < size; ++i) {
231 const GURL url(urls[i]);
232 EXPECT_TRUE(url.is_valid());
233 filter->RemoveUrlHandler(url);
237 // Fails requests using ERR_CONNECTION_RESET.
238 net::URLRequestJob* FailedJobFactory(
239 net::URLRequest* request,
240 net::NetworkDelegate* network_delegate,
241 const std::string& scheme) {
242 return new content::URLRequestFailedJob(
243 request, network_delegate, net::ERR_CONNECTION_RESET);
246 // While |MakeRequestFail| is in scope URLRequests to |host| will fail.
247 class MakeRequestFail {
249 // Sets up the filter on IO thread such that requests to |host| fail.
250 explicit MakeRequestFail(const std::string& host) : host_(host) {
251 BrowserThread::PostTaskAndReply(
252 BrowserThread::IO, FROM_HERE,
253 base::Bind(MakeRequestFailOnIO, host_),
254 base::MessageLoop::QuitClosure());
255 content::RunMessageLoop();
258 BrowserThread::PostTaskAndReply(
259 BrowserThread::IO, FROM_HERE,
260 base::Bind(UndoMakeRequestFailOnIO, host_),
261 base::MessageLoop::QuitClosure());
262 content::RunMessageLoop();
266 // Filters requests to the |host| such that they fail. Run on IO thread.
267 static void MakeRequestFailOnIO(const std::string& host) {
268 net::URLRequestFilter* filter = net::URLRequestFilter::GetInstance();
269 filter->AddHostnameHandler("http", host, &FailedJobFactory);
270 filter->AddHostnameHandler("https", host, &FailedJobFactory);
273 // Remove filters for requests to the |host|. Run on IO thread.
274 static void UndoMakeRequestFailOnIO(const std::string& host) {
275 net::URLRequestFilter* filter = net::URLRequestFilter::GetInstance();
276 filter->RemoveHostnameHandler("http", host);
277 filter->RemoveHostnameHandler("https", host);
280 const std::string host_;
283 // Verifies that the given url |spec| can be opened. This assumes that |spec|
284 // points at empty.html in the test data dir.
285 void CheckCanOpenURL(Browser* browser, const char* spec) {
287 ui_test_utils::NavigateToURL(browser, url);
288 content::WebContents* contents =
289 browser->tab_strip_model()->GetActiveWebContents();
290 EXPECT_EQ(url, contents->GetURL());
291 base::string16 title = base::UTF8ToUTF16(url.spec() + " was blocked");
292 EXPECT_NE(title, contents->GetTitle());
295 // Verifies that access to the given url |spec| is blocked.
296 void CheckURLIsBlocked(Browser* browser, const char* spec) {
298 ui_test_utils::NavigateToURL(browser, url);
299 content::WebContents* contents =
300 browser->tab_strip_model()->GetActiveWebContents();
301 EXPECT_EQ(url, contents->GetURL());
302 base::string16 title = base::UTF8ToUTF16(url.spec() + " was blocked");
303 EXPECT_EQ(title, contents->GetTitle());
305 // Verify that the expected error page is being displayed.
307 EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
309 "var textContent = document.body.textContent;"
310 "var hasError = textContent.indexOf('ERR_BLOCKED_BY_ADMINISTRATOR') >= 0;"
311 "domAutomationController.send(hasError);",
316 // Downloads a file named |file| and expects it to be saved to |dir|, which
318 void DownloadAndVerifyFile(
319 Browser* browser, const base::FilePath& dir, const base::FilePath& file) {
320 content::DownloadManager* download_manager =
321 content::BrowserContext::GetDownloadManager(browser->profile());
322 content::DownloadTestObserverTerminal observer(
324 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL);
325 GURL url(URLRequestMockHTTPJob::GetMockUrl(file));
326 base::FilePath downloaded = dir.Append(file);
327 EXPECT_FALSE(base::PathExists(downloaded));
328 ui_test_utils::NavigateToURLWithDisposition(
329 browser, url, CURRENT_TAB,
330 ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION);
331 observer.WaitForFinished();
333 1u, observer.NumDownloadsSeenInState(content::DownloadItem::COMPLETE));
334 EXPECT_TRUE(base::PathExists(downloaded));
335 base::FileEnumerator enumerator(dir, false, base::FileEnumerator::FILES);
336 EXPECT_EQ(file, enumerator.Next().BaseName());
337 EXPECT_EQ(base::FilePath(), enumerator.Next());
340 #if defined(OS_CHROMEOS)
341 int CountScreenshots() {
342 DownloadPrefs* download_prefs = DownloadPrefs::FromBrowserContext(
343 ProfileManager::GetActiveUserProfile());
344 base::FileEnumerator enumerator(download_prefs->DownloadPath(),
345 false, base::FileEnumerator::FILES,
348 while (!enumerator.Next().empty())
354 // Checks if WebGL is enabled in the given WebContents.
355 bool IsWebGLEnabled(content::WebContents* contents) {
357 EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
359 "var canvas = document.createElement('canvas');"
360 "var context = canvas.getContext('webgl');"
361 "domAutomationController.send(context != null);",
366 bool IsJavascriptEnabled(content::WebContents* contents) {
367 scoped_ptr<base::Value> value = content::ExecuteScriptAndGetValue(
368 contents->GetMainFrame(), "123");
370 if (!value->GetAsInteger(&result))
371 EXPECT_EQ(base::Value::TYPE_NULL, value->GetType());
372 return result == 123;
375 void CopyPluginListAndQuit(std::vector<content::WebPluginInfo>* out,
376 const std::vector<content::WebPluginInfo>& in) {
378 base::MessageLoop::current()->QuitWhenIdle();
382 void CopyValueAndQuit(T* out, T in) {
384 base::MessageLoop::current()->QuitWhenIdle();
387 void GetPluginList(std::vector<content::WebPluginInfo>* plugins) {
388 content::PluginService* service = content::PluginService::GetInstance();
389 service->GetPlugins(base::Bind(CopyPluginListAndQuit, plugins));
390 content::RunMessageLoop();
393 const content::WebPluginInfo* GetFlashPlugin(
394 const std::vector<content::WebPluginInfo>& plugins) {
395 const content::WebPluginInfo* flash = NULL;
396 for (size_t i = 0; i < plugins.size(); ++i) {
397 if (plugins[i].name == base::ASCIIToUTF16(content::kFlashPluginName)) {
402 #if defined(OFFICIAL_BUILD)
403 // Official builds bundle Flash.
407 LOG(INFO) << "Test skipped because the Flash plugin couldn't be found.";
412 bool SetPluginEnabled(PluginPrefs* plugin_prefs,
413 const content::WebPluginInfo* plugin,
416 plugin_prefs->EnablePlugin(enabled, plugin->path,
417 base::Bind(CopyValueAndQuit<bool>, &ok));
418 content::RunMessageLoop();
422 int CountPluginsOnIOThread() {
424 for (content::BrowserChildProcessHostIterator iter; !iter.Done(); ++iter) {
425 if (iter.GetData().process_type == content::PROCESS_TYPE_PLUGIN ||
426 iter.GetData().process_type == content::PROCESS_TYPE_PPAPI_PLUGIN) {
435 BrowserThread::PostTaskAndReplyWithResult(
436 BrowserThread::IO, FROM_HERE,
437 base::Bind(CountPluginsOnIOThread),
438 base::Bind(CopyValueAndQuit<int>, &count));
439 content::RunMessageLoop();
444 void FlushBlacklistPolicy() {
445 // Updates of the URLBlacklist are done on IO, after building the blacklist
446 // on FILE, which is initiated from IO.
447 content::RunAllPendingInMessageLoop(BrowserThread::IO);
448 content::RunAllPendingInMessageLoop(BrowserThread::FILE);
449 content::RunAllPendingInMessageLoop(BrowserThread::IO);
452 bool ContainsVisibleElement(content::WebContents* contents,
453 const std::string& id) {
455 EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
457 "var elem = document.getElementById('" + id + "');"
458 "domAutomationController.send(!!elem && !elem.hidden);",
463 #if defined(OS_CHROMEOS)
464 class TestAudioObserver : public chromeos::CrasAudioHandler::AudioObserver {
466 TestAudioObserver() : output_mute_changed_count_(0) {
469 int output_mute_changed_count() const {
470 return output_mute_changed_count_;
473 virtual ~TestAudioObserver() {}
476 // chromeos::CrasAudioHandler::AudioObserver overrides.
477 virtual void OnOutputMuteChanged() OVERRIDE {
478 ++output_mute_changed_count_;
482 int output_mute_changed_count_;
484 DISALLOW_COPY_AND_ASSIGN(TestAudioObserver);
488 // This class waits until either a load stops or the WebContents is destroyed.
489 class WebContentsLoadedOrDestroyedWatcher
490 : public content::WebContentsObserver {
492 explicit WebContentsLoadedOrDestroyedWatcher(
493 content::WebContents* web_contents);
494 virtual ~WebContentsLoadedOrDestroyedWatcher();
496 // Waits until the WebContents's load is done or until it is destroyed.
499 // Overridden WebContentsObserver methods.
500 virtual void WebContentsDestroyed() OVERRIDE;
501 virtual void DidStopLoading(
502 content::RenderViewHost* render_view_host) OVERRIDE;
505 scoped_refptr<content::MessageLoopRunner> message_loop_runner_;
507 DISALLOW_COPY_AND_ASSIGN(WebContentsLoadedOrDestroyedWatcher);
510 WebContentsLoadedOrDestroyedWatcher::WebContentsLoadedOrDestroyedWatcher(
511 content::WebContents* web_contents)
512 : content::WebContentsObserver(web_contents),
513 message_loop_runner_(new content::MessageLoopRunner) {
516 WebContentsLoadedOrDestroyedWatcher::~WebContentsLoadedOrDestroyedWatcher() {}
518 void WebContentsLoadedOrDestroyedWatcher::Wait() {
519 message_loop_runner_->Run();
522 void WebContentsLoadedOrDestroyedWatcher::WebContentsDestroyed() {
523 message_loop_runner_->Quit();
526 void WebContentsLoadedOrDestroyedWatcher::DidStopLoading(
527 content::RenderViewHost* render_view_host) {
528 message_loop_runner_->Quit();
531 #if !defined(OS_MACOSX)
533 // Observer used to wait for the creation of a new app window.
534 class TestAddAppWindowObserver : public apps::AppWindowRegistry::Observer {
536 explicit TestAddAppWindowObserver(apps::AppWindowRegistry* registry);
537 virtual ~TestAddAppWindowObserver();
539 // apps::AppWindowRegistry::Observer:
540 virtual void OnAppWindowAdded(apps::AppWindow* app_window) OVERRIDE;
542 apps::AppWindow* WaitForAppWindow();
545 apps::AppWindowRegistry* registry_; // Not owned.
546 apps::AppWindow* window_; // Not owned.
547 base::RunLoop run_loop_;
549 DISALLOW_COPY_AND_ASSIGN(TestAddAppWindowObserver);
552 TestAddAppWindowObserver::TestAddAppWindowObserver(
553 apps::AppWindowRegistry* registry)
554 : registry_(registry), window_(NULL) {
555 registry_->AddObserver(this);
558 TestAddAppWindowObserver::~TestAddAppWindowObserver() {
559 registry_->RemoveObserver(this);
562 void TestAddAppWindowObserver::OnAppWindowAdded(apps::AppWindow* app_window) {
563 window_ = app_window;
567 apps::AppWindow* TestAddAppWindowObserver::WaitForAppWindow() {
576 class PolicyTest : public InProcessBrowserTest {
579 virtual ~PolicyTest() {}
581 virtual void SetUp() OVERRIDE {
582 test_extension_cache_.reset(new extensions::ExtensionCacheFake());
583 InProcessBrowserTest::SetUp();
586 virtual void SetUpInProcessBrowserTestFixture() OVERRIDE {
587 CommandLine::ForCurrentProcess()->AppendSwitch("noerrdialogs");
588 EXPECT_CALL(provider_, IsInitializationComplete(_))
589 .WillRepeatedly(Return(true));
590 BrowserPolicyConnector::SetPolicyProviderForTesting(&provider_);
593 virtual void SetUpOnMainThread() OVERRIDE {
594 BrowserThread::PostTask(
595 BrowserThread::IO, FROM_HERE,
596 base::Bind(chrome_browser_net::SetUrlRequestMocksEnabled, true));
599 // Makes URLRequestMockHTTPJobs serve data from content::DIR_TEST_DATA
600 // instead of chrome::DIR_TEST_DATA.
601 void ServeContentTestData() {
602 base::FilePath root_http;
603 PathService::Get(content::DIR_TEST_DATA, &root_http);
604 BrowserThread::PostTaskAndReply(
605 BrowserThread::IO, FROM_HERE,
606 base::Bind(URLRequestMockHTTPJob::AddUrlHandler, root_http),
607 base::MessageLoop::current()->QuitWhenIdleClosure());
608 content::RunMessageLoop();
611 void SetScreenshotPolicy(bool enabled) {
613 policies.Set(key::kDisableScreenshots,
614 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
615 base::Value::CreateBooleanValue(!enabled), NULL);
616 UpdateProviderPolicy(policies);
619 #if defined(OS_CHROMEOS)
620 class QuitMessageLoopAfterScreenshot : public ScreenshotTakerObserver {
622 virtual void OnScreenshotCompleted(
623 ScreenshotTakerObserver::Result screenshot_result,
624 const base::FilePath& screenshot_path) OVERRIDE {
625 BrowserThread::PostTaskAndReply(BrowserThread::IO,
627 base::Bind(base::DoNothing),
628 base::MessageLoop::QuitClosure());
631 virtual ~QuitMessageLoopAfterScreenshot() {}
634 void TestScreenshotFile(bool enabled) {
635 // AddObserver is an ash-specific method, so just replace the screenshot
636 // taker with one we've created here.
637 scoped_ptr<ScreenshotTaker> screenshot_taker(new ScreenshotTaker);
638 // ScreenshotTaker doesn't own this observer, so the observer's lifetime
639 // is tied to the test instead.
640 screenshot_taker->AddObserver(&observer_);
641 ash::Shell::GetInstance()->accelerator_controller()->SetScreenshotDelegate(
642 screenshot_taker.PassAs<ash::ScreenshotDelegate>());
644 SetScreenshotPolicy(enabled);
645 ash::Shell::GetInstance()->accelerator_controller()->PerformAction(
646 ash::TAKE_SCREENSHOT, ui::Accelerator());
648 content::RunMessageLoop();
652 ExtensionService* extension_service() {
653 extensions::ExtensionSystem* system =
654 extensions::ExtensionSystem::Get(browser()->profile());
655 return system->extension_service();
658 const extensions::Extension* InstallExtension(
659 const base::FilePath::StringType& name) {
660 base::FilePath extension_path(ui_test_utils::GetTestFilePath(
661 base::FilePath(kTestExtensionsDir), base::FilePath(name)));
662 scoped_refptr<extensions::CrxInstaller> installer =
663 extensions::CrxInstaller::CreateSilent(extension_service());
664 installer->set_allow_silent_install(true);
665 installer->set_install_cause(extension_misc::INSTALL_CAUSE_UPDATE);
666 installer->set_creation_flags(extensions::Extension::FROM_WEBSTORE);
668 content::WindowedNotificationObserver observer(
669 chrome::NOTIFICATION_CRX_INSTALLER_DONE,
670 content::NotificationService::AllSources());
671 installer->InstallCrx(extension_path);
673 content::Details<const extensions::Extension> details = observer.details();
674 return details.ptr();
677 const extensions::Extension* LoadUnpackedExtension(
678 const base::FilePath::StringType& name, bool expect_success) {
679 base::FilePath extension_path(ui_test_utils::GetTestFilePath(
680 base::FilePath(kTestExtensionsDir), base::FilePath(name)));
681 scoped_refptr<extensions::UnpackedInstaller> installer =
682 extensions::UnpackedInstaller::Create(extension_service());
683 content::WindowedNotificationObserver observer(
684 expect_success ? chrome::NOTIFICATION_EXTENSION_LOADED_DEPRECATED
685 : chrome::NOTIFICATION_EXTENSION_LOAD_ERROR,
686 content::NotificationService::AllSources());
687 installer->Load(extension_path);
690 const extensions::ExtensionSet* extensions =
691 extension_service()->extensions();
692 for (extensions::ExtensionSet::const_iterator it = extensions->begin();
693 it != extensions->end(); ++it) {
694 if ((*it)->path() == extension_path)
700 void UninstallExtension(const std::string& id, bool expect_success) {
701 content::WindowedNotificationObserver observer(
702 expect_success ? chrome::NOTIFICATION_EXTENSION_UNINSTALLED
703 : chrome::NOTIFICATION_EXTENSION_UNINSTALL_NOT_ALLOWED,
704 content::NotificationService::AllSources());
705 extension_service()->UninstallExtension(id, false, NULL);
709 void UpdateProviderPolicy(const PolicyMap& policy) {
710 provider_.UpdateChromePolicy(policy);
711 DCHECK(base::MessageLoop::current());
716 // Sends a mouse click at the given coordinates to the current renderer.
717 void PerformClick(int x, int y) {
718 content::WebContents* contents =
719 browser()->tab_strip_model()->GetActiveWebContents();
720 blink::WebMouseEvent click_event;
721 click_event.type = blink::WebInputEvent::MouseDown;
722 click_event.button = blink::WebMouseEvent::ButtonLeft;
723 click_event.clickCount = 1;
726 contents->GetRenderViewHost()->ForwardMouseEvent(click_event);
727 click_event.type = blink::WebInputEvent::MouseUp;
728 contents->GetRenderViewHost()->ForwardMouseEvent(click_event);
731 MockConfigurationPolicyProvider provider_;
732 scoped_ptr<extensions::ExtensionCacheFake> test_extension_cache_;
733 #if defined(OS_CHROMEOS)
734 QuitMessageLoopAfterScreenshot observer_;
739 // This policy only exists on Windows.
741 // Sets the locale policy before the browser is started.
742 class LocalePolicyTest : public PolicyTest {
744 LocalePolicyTest() {}
745 virtual ~LocalePolicyTest() {}
747 virtual void SetUpInProcessBrowserTestFixture() OVERRIDE {
748 PolicyTest::SetUpInProcessBrowserTestFixture();
751 key::kApplicationLocaleValue, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
752 base::Value::CreateStringValue("fr"), NULL);
753 provider_.UpdateChromePolicy(policies);
754 // The "en-US" ResourceBundle is always loaded before this step for tests,
755 // but in this test we want the browser to load the bundle as it
757 ResourceBundle::CleanupSharedInstance();
761 IN_PROC_BROWSER_TEST_F(LocalePolicyTest, ApplicationLocaleValue) {
762 // Verifies that the default locale can be overridden with policy.
763 EXPECT_EQ("fr", g_browser_process->GetApplicationLocale());
764 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL));
765 base::string16 french_title = l10n_util::GetStringUTF16(IDS_NEW_TAB_TITLE);
766 base::string16 title;
767 EXPECT_TRUE(ui_test_utils::GetCurrentTabTitle(browser(), &title));
768 EXPECT_EQ(french_title, title);
770 // Make sure this is really French and differs from the English title.
772 ui::ResourceBundle::GetSharedInstance().ReloadLocaleResources("en-US");
773 EXPECT_EQ("en-US", loaded);
774 base::string16 english_title = l10n_util::GetStringUTF16(IDS_NEW_TAB_TITLE);
775 EXPECT_NE(french_title, english_title);
779 IN_PROC_BROWSER_TEST_F(PolicyTest, BookmarkBarEnabled) {
780 #if defined(OS_WIN) && defined(USE_ASH)
781 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
782 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshBrowserTests))
786 // Verifies that the bookmarks bar can be forced to always or never show up.
788 // Test starts in about:blank.
789 PrefService* prefs = browser()->profile()->GetPrefs();
790 EXPECT_FALSE(prefs->IsManagedPreference(prefs::kShowBookmarkBar));
791 EXPECT_FALSE(prefs->GetBoolean(prefs::kShowBookmarkBar));
792 EXPECT_EQ(BookmarkBar::HIDDEN, browser()->bookmark_bar_state());
795 policies.Set(key::kBookmarkBarEnabled, POLICY_LEVEL_MANDATORY,
796 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL);
797 UpdateProviderPolicy(policies);
798 EXPECT_TRUE(prefs->IsManagedPreference(prefs::kShowBookmarkBar));
799 EXPECT_TRUE(prefs->GetBoolean(prefs::kShowBookmarkBar));
800 EXPECT_EQ(BookmarkBar::SHOW, browser()->bookmark_bar_state());
802 // The NTP has special handling of the bookmark bar.
803 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL));
804 EXPECT_EQ(BookmarkBar::SHOW, browser()->bookmark_bar_state());
806 policies.Set(key::kBookmarkBarEnabled, POLICY_LEVEL_MANDATORY,
807 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(false), NULL);
808 UpdateProviderPolicy(policies);
809 EXPECT_TRUE(prefs->IsManagedPreference(prefs::kShowBookmarkBar));
810 EXPECT_FALSE(prefs->GetBoolean(prefs::kShowBookmarkBar));
811 // The bookmark bar is hidden in the NTP when disabled by policy.
812 EXPECT_EQ(BookmarkBar::HIDDEN, browser()->bookmark_bar_state());
815 UpdateProviderPolicy(policies);
816 EXPECT_FALSE(prefs->IsManagedPreference(prefs::kShowBookmarkBar));
817 EXPECT_FALSE(prefs->GetBoolean(prefs::kShowBookmarkBar));
818 // The bookmark bar is shown detached in the NTP, when disabled by prefs only.
819 EXPECT_EQ(BookmarkBar::DETACHED, browser()->bookmark_bar_state());
822 IN_PROC_BROWSER_TEST_F(PolicyTest, PRE_PRE_DefaultCookiesSetting) {
823 // Verifies that cookies are deleted on shutdown. This test is split in 3
824 // parts because it spans 2 browser restarts.
826 Profile* profile = browser()->profile();
828 // No cookies at startup.
829 EXPECT_TRUE(content::GetCookies(profile, url).empty());
831 std::string value = std::string(kCookieValue) + std::string(kCookieOptions);
832 EXPECT_TRUE(content::SetCookie(profile, url, value));
833 // Verify it was set.
834 EXPECT_EQ(kCookieValue, GetCookies(profile, url));
837 IN_PROC_BROWSER_TEST_F(PolicyTest, PRE_DefaultCookiesSetting) {
838 // Verify that the cookie persists across restarts.
839 EXPECT_EQ(kCookieValue, GetCookies(browser()->profile(), GURL(kURL)));
840 // Now set the policy and the cookie should be gone after another restart.
842 policies.Set(key::kDefaultCookiesSetting, POLICY_LEVEL_MANDATORY,
843 POLICY_SCOPE_USER, base::Value::CreateIntegerValue(4), NULL);
844 UpdateProviderPolicy(policies);
847 IN_PROC_BROWSER_TEST_F(PolicyTest, DefaultCookiesSetting) {
848 // Verify that the cookie is gone.
849 EXPECT_TRUE(GetCookies(browser()->profile(), GURL(kURL)).empty());
852 IN_PROC_BROWSER_TEST_F(PolicyTest, DefaultSearchProvider) {
853 MakeRequestFail make_request_fail("search.example");
855 // Verifies that a default search is made using the provider configured via
856 // policy. Also checks that default search can be completely disabled.
857 const base::string16 kKeyword(base::ASCIIToUTF16("testsearch"));
858 const std::string kSearchURL("http://search.example/search?q={searchTerms}");
859 const std::string kAlternateURL0(
860 "http://search.example/search#q={searchTerms}");
861 const std::string kAlternateURL1("http://search.example/#q={searchTerms}");
862 const std::string kSearchTermsReplacementKey("zekey");
863 const std::string kImageURL("http://test.com/searchbyimage/upload");
864 const std::string kImageURLPostParams(
865 "image_content=content,image_url=http://test.com/test.png");
866 const std::string kNewTabURL("http://search.example/newtab");
868 TemplateURLService* service = TemplateURLServiceFactory::GetForProfile(
869 browser()->profile());
870 ui_test_utils::WaitForTemplateURLServiceToLoad(service);
871 TemplateURL* default_search = service->GetDefaultSearchProvider();
872 ASSERT_TRUE(default_search);
873 EXPECT_NE(kKeyword, default_search->keyword());
874 EXPECT_NE(kSearchURL, default_search->url());
876 default_search->alternate_urls().size() == 2 &&
877 default_search->alternate_urls()[0] == kAlternateURL0 &&
878 default_search->alternate_urls()[1] == kAlternateURL1 &&
879 default_search->search_terms_replacement_key() ==
880 kSearchTermsReplacementKey &&
881 default_search->image_url() == kImageURL &&
882 default_search->image_url_post_params() == kImageURLPostParams &&
883 default_search->new_tab_url() == kNewTabURL);
885 // Override the default search provider using policies.
887 policies.Set(key::kDefaultSearchProviderEnabled, POLICY_LEVEL_MANDATORY,
888 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL);
889 policies.Set(key::kDefaultSearchProviderKeyword,
890 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
891 base::Value::CreateStringValue(kKeyword), NULL);
892 policies.Set(key::kDefaultSearchProviderSearchURL,
893 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
894 base::Value::CreateStringValue(kSearchURL), NULL);
895 base::ListValue* alternate_urls = new base::ListValue();
896 alternate_urls->AppendString(kAlternateURL0);
897 alternate_urls->AppendString(kAlternateURL1);
898 policies.Set(key::kDefaultSearchProviderAlternateURLs, POLICY_LEVEL_MANDATORY,
899 POLICY_SCOPE_USER, alternate_urls, NULL);
900 policies.Set(key::kDefaultSearchProviderSearchTermsReplacementKey,
901 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
902 base::Value::CreateStringValue(kSearchTermsReplacementKey),
904 policies.Set(key::kDefaultSearchProviderImageURL,
905 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
906 base::Value::CreateStringValue(kImageURL),
908 policies.Set(key::kDefaultSearchProviderImageURLPostParams,
909 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
910 base::Value::CreateStringValue(kImageURLPostParams),
912 policies.Set(key::kDefaultSearchProviderNewTabURL,
913 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
914 base::Value::CreateStringValue(kNewTabURL),
916 UpdateProviderPolicy(policies);
917 default_search = service->GetDefaultSearchProvider();
918 ASSERT_TRUE(default_search);
919 EXPECT_EQ(kKeyword, default_search->keyword());
920 EXPECT_EQ(kSearchURL, default_search->url());
921 EXPECT_EQ(2U, default_search->alternate_urls().size());
922 EXPECT_EQ(kAlternateURL0, default_search->alternate_urls()[0]);
923 EXPECT_EQ(kAlternateURL1, default_search->alternate_urls()[1]);
924 EXPECT_EQ(kSearchTermsReplacementKey,
925 default_search->search_terms_replacement_key());
926 EXPECT_EQ(kImageURL, default_search->image_url());
927 EXPECT_EQ(kImageURLPostParams, default_search->image_url_post_params());
928 EXPECT_EQ(kNewTabURL, default_search->new_tab_url());
930 // Verify that searching from the omnibox uses kSearchURL.
931 chrome::FocusLocationBar(browser());
932 LocationBar* location_bar = browser()->window()->GetLocationBar();
933 ui_test_utils::SendToOmniboxAndSubmit(location_bar, "stuff to search for");
934 OmniboxEditModel* model = location_bar->GetOmniboxView()->model();
935 EXPECT_TRUE(model->CurrentMatch(NULL).destination_url.is_valid());
936 content::WebContents* web_contents =
937 browser()->tab_strip_model()->GetActiveWebContents();
938 GURL expected("http://search.example/search?q=stuff+to+search+for");
939 EXPECT_EQ(expected, web_contents->GetURL());
941 // Verify that searching from the omnibox can be disabled.
942 ui_test_utils::NavigateToURL(browser(), GURL(content::kAboutBlankURL));
943 policies.Set(key::kDefaultSearchProviderEnabled, POLICY_LEVEL_MANDATORY,
944 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(false), NULL);
945 EXPECT_TRUE(service->GetDefaultSearchProvider());
946 UpdateProviderPolicy(policies);
947 EXPECT_FALSE(service->GetDefaultSearchProvider());
948 ui_test_utils::SendToOmniboxAndSubmit(location_bar, "should not work");
949 // This means that submitting won't trigger any action.
950 EXPECT_FALSE(model->CurrentMatch(NULL).destination_url.is_valid());
951 EXPECT_EQ(GURL(content::kAboutBlankURL), web_contents->GetURL());
954 IN_PROC_BROWSER_TEST_F(PolicyTest, PolicyPreprocessing) {
955 // Add an individual proxy policy value.
957 policies.Set(key::kProxyServerMode,
958 POLICY_LEVEL_MANDATORY,
960 base::Value::CreateIntegerValue(3),
962 UpdateProviderPolicy(policies);
964 // It should be removed and replaced with a dictionary.
966 scoped_ptr<base::DictionaryValue> expected_value(new base::DictionaryValue);
967 expected_value->SetInteger(key::kProxyServerMode, 3);
968 expected.Set(key::kProxySettings,
969 POLICY_LEVEL_MANDATORY,
971 expected_value.release(),
974 // Check both the browser and the profile.
975 const PolicyMap& actual_from_browser =
976 g_browser_process->browser_policy_connector()
978 ->GetPolicies(PolicyNamespace(POLICY_DOMAIN_CHROME, std::string()));
979 EXPECT_TRUE(expected.Equals(actual_from_browser));
980 const PolicyMap& actual_from_profile =
981 ProfilePolicyConnectorFactory::GetForProfile(browser()->profile())
983 ->GetPolicies(PolicyNamespace(POLICY_DOMAIN_CHROME, std::string()));
984 EXPECT_TRUE(expected.Equals(actual_from_profile));
987 IN_PROC_BROWSER_TEST_F(PolicyTest, ForceSafeSearch) {
988 // Makes the requests fail since all we want to check is that the redirection
990 MakeRequestFail make_request_fail("google.com");
992 // Verifies that requests to Google Search engine with the SafeSearch
993 // enabled set the safe=active&ssui=on parameters at the end of the query.
994 TemplateURLService* service = TemplateURLServiceFactory::GetForProfile(
995 browser()->profile());
996 ui_test_utils::WaitForTemplateURLServiceToLoad(service);
998 // First check that nothing happens.
999 content::TestNavigationObserver no_safesearch_observer(
1000 browser()->tab_strip_model()->GetActiveWebContents());
1001 chrome::FocusLocationBar(browser());
1002 LocationBar* location_bar = browser()->window()->GetLocationBar();
1003 ui_test_utils::SendToOmniboxAndSubmit(location_bar, "http://google.com/");
1004 OmniboxEditModel* model = location_bar->GetOmniboxView()->model();
1005 no_safesearch_observer.Wait();
1006 EXPECT_TRUE(model->CurrentMatch(NULL).destination_url.is_valid());
1007 content::WebContents* web_contents =
1008 browser()->tab_strip_model()->GetActiveWebContents();
1009 GURL expected_without("http://google.com/");
1010 EXPECT_EQ(expected_without, web_contents->GetURL());
1012 PrefService* prefs = browser()->profile()->GetPrefs();
1013 EXPECT_FALSE(prefs->IsManagedPreference(prefs::kForceSafeSearch));
1014 EXPECT_FALSE(prefs->GetBoolean(prefs::kForceSafeSearch));
1016 // Override the default SafeSearch setting using policies.
1018 policies.Set(key::kForceSafeSearch, POLICY_LEVEL_MANDATORY,
1019 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL);
1020 UpdateProviderPolicy(policies);
1022 EXPECT_TRUE(prefs->IsManagedPreference(prefs::kForceSafeSearch));
1023 EXPECT_TRUE(prefs->GetBoolean(prefs::kForceSafeSearch));
1025 content::TestNavigationObserver safesearch_observer(
1026 browser()->tab_strip_model()->GetActiveWebContents());
1028 // Verify that searching from google.com works.
1029 chrome::FocusLocationBar(browser());
1030 ui_test_utils::SendToOmniboxAndSubmit(location_bar, "http://google.com/");
1031 safesearch_observer.Wait();
1032 EXPECT_TRUE(model->CurrentMatch(NULL).destination_url.is_valid());
1033 web_contents = browser()->tab_strip_model()->GetActiveWebContents();
1034 std::string expected_url("http://google.com/?");
1035 expected_url += std::string(chrome::kSafeSearchSafeParameter) + "&" +
1036 chrome::kSafeSearchSsuiParameter;
1037 GURL expected_with_parameters(expected_url);
1038 EXPECT_EQ(expected_with_parameters, web_contents->GetURL());
1041 IN_PROC_BROWSER_TEST_F(PolicyTest, ReplaceSearchTerms) {
1042 MakeRequestFail make_request_fail("search.example");
1044 chrome::EnableQueryExtractionForTesting();
1046 // Verifies that a default search is made using the provider configured via
1047 // policy. Also checks that default search can be completely disabled.
1048 const base::string16 kKeyword(base::ASCIIToUTF16("testsearch"));
1049 const std::string kSearchURL("https://www.google.com/search?q={searchTerms}");
1050 const std::string kInstantURL("http://does/not/exist");
1051 const std::string kAlternateURL0(
1052 "https://www.google.com/search#q={searchTerms}");
1053 const std::string kAlternateURL1("https://www.google.com/#q={searchTerms}");
1054 const std::string kSearchTermsReplacementKey(
1055 "{google:instantExtendedEnabledKey}");
1057 TemplateURLService* service = TemplateURLServiceFactory::GetForProfile(
1058 browser()->profile());
1059 ui_test_utils::WaitForTemplateURLServiceToLoad(service);
1060 TemplateURL* default_search = service->GetDefaultSearchProvider();
1061 ASSERT_TRUE(default_search);
1062 EXPECT_NE(kKeyword, default_search->keyword());
1063 EXPECT_NE(kSearchURL, default_search->url());
1064 EXPECT_NE(kInstantURL, default_search->instant_url());
1066 default_search->alternate_urls().size() == 2 &&
1067 default_search->alternate_urls()[0] == kAlternateURL0 &&
1068 default_search->alternate_urls()[1] == kAlternateURL1);
1070 // Override the default search provider using policies.
1072 policies.Set(key::kDefaultSearchProviderEnabled, POLICY_LEVEL_MANDATORY,
1073 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL);
1074 policies.Set(key::kDefaultSearchProviderKeyword,
1075 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
1076 base::Value::CreateStringValue(kKeyword), NULL);
1077 policies.Set(key::kDefaultSearchProviderSearchURL,
1078 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
1079 base::Value::CreateStringValue(kSearchURL), NULL);
1080 policies.Set(key::kDefaultSearchProviderInstantURL,
1081 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
1082 base::Value::CreateStringValue(kInstantURL), NULL);
1083 base::ListValue* alternate_urls = new base::ListValue();
1084 alternate_urls->AppendString(kAlternateURL0);
1085 alternate_urls->AppendString(kAlternateURL1);
1086 policies.Set(key::kDefaultSearchProviderAlternateURLs, POLICY_LEVEL_MANDATORY,
1087 POLICY_SCOPE_USER, alternate_urls, NULL);
1088 policies.Set(key::kDefaultSearchProviderSearchTermsReplacementKey,
1089 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
1090 base::Value::CreateStringValue(kSearchTermsReplacementKey),
1092 UpdateProviderPolicy(policies);
1093 default_search = service->GetDefaultSearchProvider();
1094 ASSERT_TRUE(default_search);
1095 EXPECT_EQ(kKeyword, default_search->keyword());
1096 EXPECT_EQ(kSearchURL, default_search->url());
1097 EXPECT_EQ(kInstantURL, default_search->instant_url());
1098 EXPECT_EQ(2U, default_search->alternate_urls().size());
1099 EXPECT_EQ(kAlternateURL0, default_search->alternate_urls()[0]);
1100 EXPECT_EQ(kAlternateURL1, default_search->alternate_urls()[1]);
1102 // Query terms replacement requires that the renderer process be a recognized
1103 // Instant renderer. Fake it.
1104 InstantService* instant_service =
1105 InstantServiceFactory::GetForProfile(browser()->profile());
1106 instant_service->AddInstantProcess(browser()->tab_strip_model()->
1107 GetActiveWebContents()->GetRenderProcessHost()->GetID());
1109 // Verify that searching from the omnibox does search term replacement with
1110 // first URL pattern.
1111 chrome::FocusLocationBar(browser());
1112 LocationBar* location_bar = browser()->window()->GetLocationBar();
1113 OmniboxView* omnibox_view = location_bar->GetOmniboxView();
1114 ui_test_utils::SendToOmniboxAndSubmit(location_bar,
1115 "https://www.google.com/?espv=1#q=foobar");
1117 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1118 EXPECT_EQ(base::ASCIIToUTF16("foobar"), omnibox_view->GetText());
1120 // Verify that not using espv=1 does not do search term replacement.
1121 chrome::FocusLocationBar(browser());
1122 ui_test_utils::SendToOmniboxAndSubmit(location_bar,
1123 "https://www.google.com/?q=foobar");
1125 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1126 EXPECT_EQ(base::ASCIIToUTF16("https://www.google.com/?q=foobar"),
1127 omnibox_view->GetText());
1129 // Verify that searching from the omnibox does search term replacement with
1130 // second URL pattern.
1131 chrome::FocusLocationBar(browser());
1132 ui_test_utils::SendToOmniboxAndSubmit(location_bar,
1133 "https://www.google.com/search?espv=1#q=banana");
1135 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1136 EXPECT_EQ(base::ASCIIToUTF16("banana"), omnibox_view->GetText());
1138 // Verify that searching from the omnibox does search term replacement with
1139 // standard search URL pattern.
1140 chrome::FocusLocationBar(browser());
1141 ui_test_utils::SendToOmniboxAndSubmit(location_bar,
1142 "https://www.google.com/search?q=tractor+parts&espv=1");
1144 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1145 EXPECT_EQ(base::ASCIIToUTF16("tractor parts"), omnibox_view->GetText());
1147 // Verify that searching from the omnibox prioritizes hash over query.
1148 chrome::FocusLocationBar(browser());
1149 ui_test_utils::SendToOmniboxAndSubmit(location_bar,
1150 "https://www.google.com/search?q=tractor+parts&espv=1#q=foobar");
1152 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1153 EXPECT_EQ(base::ASCIIToUTF16("foobar"), omnibox_view->GetText());
1156 IN_PROC_BROWSER_TEST_F(PolicyTest, Disable3DAPIs) {
1157 // This test assumes Gpu access.
1158 if (!content::GpuDataManager::GetInstance()->GpuAccessAllowed(NULL))
1161 ui_test_utils::NavigateToURL(browser(), GURL(content::kAboutBlankURL));
1162 // WebGL is enabled by default.
1163 content::WebContents* contents =
1164 browser()->tab_strip_model()->GetActiveWebContents();
1165 EXPECT_TRUE(IsWebGLEnabled(contents));
1166 // Disable with a policy.
1168 policies.Set(key::kDisable3DAPIs, POLICY_LEVEL_MANDATORY,
1169 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL);
1170 UpdateProviderPolicy(policies);
1171 // Crash and reload the tab to get a new renderer.
1172 content::CrashTab(contents);
1173 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_RELOAD));
1174 EXPECT_FALSE(IsWebGLEnabled(contents));
1175 // Enable with a policy.
1176 policies.Set(key::kDisable3DAPIs, POLICY_LEVEL_MANDATORY,
1177 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(false), NULL);
1178 UpdateProviderPolicy(policies);
1179 content::CrashTab(contents);
1180 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_RELOAD));
1181 EXPECT_TRUE(IsWebGLEnabled(contents));
1184 IN_PROC_BROWSER_TEST_F(PolicyTest, DisableSpdy) {
1185 // Verifies that SPDY can be disable by policy.
1186 EXPECT_TRUE(net::HttpStreamFactory::spdy_enabled());
1188 policies.Set(key::kDisableSpdy, POLICY_LEVEL_MANDATORY,
1189 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL);
1190 UpdateProviderPolicy(policies);
1191 content::RunAllPendingInMessageLoop();
1192 EXPECT_FALSE(net::HttpStreamFactory::spdy_enabled());
1193 // Verify that it can be force-enabled too.
1194 browser()->profile()->GetPrefs()->SetBoolean(prefs::kDisableSpdy, true);
1195 policies.Set(key::kDisableSpdy, POLICY_LEVEL_MANDATORY,
1196 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(false), NULL);
1197 UpdateProviderPolicy(policies);
1198 content::RunAllPendingInMessageLoop();
1199 EXPECT_TRUE(net::HttpStreamFactory::spdy_enabled());
1202 IN_PROC_BROWSER_TEST_F(PolicyTest, DisabledPlugins) {
1203 // Verifies that plugins can be forced to be disabled by policy.
1205 // Verify that the Flash plugin exists and that it can be enabled and disabled
1207 std::vector<content::WebPluginInfo> plugins;
1208 GetPluginList(&plugins);
1209 const content::WebPluginInfo* flash = GetFlashPlugin(plugins);
1212 PluginPrefs* plugin_prefs =
1213 PluginPrefs::GetForProfile(browser()->profile()).get();
1214 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1215 EXPECT_TRUE(SetPluginEnabled(plugin_prefs, flash, false));
1216 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1217 EXPECT_TRUE(SetPluginEnabled(plugin_prefs, flash, true));
1218 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1220 // Now disable it with a policy.
1221 base::ListValue disabled_plugins;
1222 disabled_plugins.Append(base::Value::CreateStringValue("*Flash*"));
1224 policies.Set(key::kDisabledPlugins, POLICY_LEVEL_MANDATORY,
1225 POLICY_SCOPE_USER, disabled_plugins.DeepCopy(), NULL);
1226 UpdateProviderPolicy(policies);
1227 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1228 // The user shouldn't be able to enable it.
1229 EXPECT_FALSE(SetPluginEnabled(plugin_prefs, flash, true));
1230 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1233 IN_PROC_BROWSER_TEST_F(PolicyTest, DisabledPluginsExceptions) {
1234 // Verifies that plugins with an exception in the blacklist can be enabled.
1236 // Verify that the Flash plugin exists and that it can be enabled and disabled
1238 std::vector<content::WebPluginInfo> plugins;
1239 GetPluginList(&plugins);
1240 const content::WebPluginInfo* flash = GetFlashPlugin(plugins);
1243 PluginPrefs* plugin_prefs =
1244 PluginPrefs::GetForProfile(browser()->profile()).get();
1245 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1247 // Disable all plugins.
1248 base::ListValue disabled_plugins;
1249 disabled_plugins.Append(base::Value::CreateStringValue("*"));
1251 policies.Set(key::kDisabledPlugins, POLICY_LEVEL_MANDATORY,
1252 POLICY_SCOPE_USER, disabled_plugins.DeepCopy(), NULL);
1253 UpdateProviderPolicy(policies);
1254 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1255 // The user shouldn't be able to enable it.
1256 EXPECT_FALSE(SetPluginEnabled(plugin_prefs, flash, true));
1257 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1259 // Now open an exception for flash.
1260 base::ListValue disabled_plugins_exceptions;
1261 disabled_plugins_exceptions.Append(
1262 base::Value::CreateStringValue("*Flash*"));
1263 policies.Set(key::kDisabledPluginsExceptions, POLICY_LEVEL_MANDATORY,
1264 POLICY_SCOPE_USER, disabled_plugins_exceptions.DeepCopy(), NULL);
1265 UpdateProviderPolicy(policies);
1266 // It should revert to the user's preference automatically.
1267 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1268 // And the user should be able to disable and enable again.
1269 EXPECT_TRUE(SetPluginEnabled(plugin_prefs, flash, false));
1270 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1271 EXPECT_TRUE(SetPluginEnabled(plugin_prefs, flash, true));
1272 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1275 IN_PROC_BROWSER_TEST_F(PolicyTest, EnabledPlugins) {
1276 // Verifies that a plugin can be force-installed with a policy.
1277 std::vector<content::WebPluginInfo> plugins;
1278 GetPluginList(&plugins);
1279 const content::WebPluginInfo* flash = GetFlashPlugin(plugins);
1282 PluginPrefs* plugin_prefs =
1283 PluginPrefs::GetForProfile(browser()->profile()).get();
1284 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1286 // The user disables it and then a policy forces it to be enabled.
1287 EXPECT_TRUE(SetPluginEnabled(plugin_prefs, flash, false));
1288 EXPECT_FALSE(plugin_prefs->IsPluginEnabled(*flash));
1289 base::ListValue plugin_list;
1290 plugin_list.Append(base::Value::CreateStringValue(content::kFlashPluginName));
1292 policies.Set(key::kEnabledPlugins, POLICY_LEVEL_MANDATORY,
1293 POLICY_SCOPE_USER, plugin_list.DeepCopy(), NULL);
1294 UpdateProviderPolicy(policies);
1295 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1296 // The user can't disable it anymore.
1297 EXPECT_FALSE(SetPluginEnabled(plugin_prefs, flash, false));
1298 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1300 // When a plugin is both enabled and disabled, the whitelist takes precedence.
1301 policies.Set(key::kDisabledPlugins, POLICY_LEVEL_MANDATORY,
1302 POLICY_SCOPE_USER, plugin_list.DeepCopy(), NULL);
1303 UpdateProviderPolicy(policies);
1304 EXPECT_TRUE(plugin_prefs->IsPluginEnabled(*flash));
1307 IN_PROC_BROWSER_TEST_F(PolicyTest, AlwaysAuthorizePlugins) {
1308 // Verifies that dangerous plugins can be always authorized to run with
1311 // Verify that the test page exists. It is only present in checkouts with
1313 if (!base::PathExists(ui_test_utils::GetTestFilePath(
1314 base::FilePath(FILE_PATH_LITERAL("plugin")),
1315 base::FilePath(FILE_PATH_LITERAL("quicktime.html"))))) {
1317 "Test skipped because plugin/quicktime.html test file wasn't found.";
1321 ServeContentTestData();
1322 // No plugins at startup.
1323 EXPECT_EQ(0, CountPlugins());
1325 content::WebContents* contents =
1326 browser()->tab_strip_model()->GetActiveWebContents();
1327 ASSERT_TRUE(contents);
1328 InfoBarService* infobar_service = InfoBarService::FromWebContents(contents);
1329 ASSERT_TRUE(infobar_service);
1330 EXPECT_EQ(0u, infobar_service->infobar_count());
1332 base::FilePath path(FILE_PATH_LITERAL("plugin/quicktime.html"));
1333 GURL url(URLRequestMockHTTPJob::GetMockUrl(path));
1334 ui_test_utils::NavigateToURL(browser(), url);
1335 // This should have triggered the dangerous plugin infobar.
1336 ASSERT_EQ(1u, infobar_service->infobar_count());
1338 infobar_service->infobar_at(0)->delegate()->AsConfirmInfoBarDelegate());
1339 // And the plugin isn't running.
1340 EXPECT_EQ(0, CountPlugins());
1342 // Now set a policy to always authorize this.
1344 policies.Set(key::kAlwaysAuthorizePlugins, POLICY_LEVEL_MANDATORY,
1345 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL);
1346 UpdateProviderPolicy(policies);
1347 // Reloading the page shouldn't trigger the infobar this time.
1348 ui_test_utils::NavigateToURL(browser(), url);
1349 EXPECT_EQ(0u, infobar_service->infobar_count());
1350 // And the plugin started automatically.
1351 EXPECT_EQ(1, CountPlugins());
1354 IN_PROC_BROWSER_TEST_F(PolicyTest, DeveloperToolsDisabled) {
1355 // Verifies that access to the developer tools can be disabled.
1358 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_DEV_TOOLS));
1359 content::WebContents* contents =
1360 browser()->tab_strip_model()->GetActiveWebContents();
1361 DevToolsWindow *devtools_window =
1362 DevToolsWindow::GetInstanceForInspectedRenderViewHost(
1363 contents->GetRenderViewHost());
1364 EXPECT_TRUE(devtools_window);
1366 // Disable devtools via policy.
1368 policies.Set(key::kDeveloperToolsDisabled, POLICY_LEVEL_MANDATORY,
1369 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL);
1370 content::WindowedNotificationObserver close_observer(
1371 content::NOTIFICATION_WEB_CONTENTS_DESTROYED,
1372 content::Source<content::WebContents>(devtools_window->web_contents()));
1373 UpdateProviderPolicy(policies);
1374 // wait for devtools close
1375 close_observer.Wait();
1376 // The existing devtools window should have closed.
1377 EXPECT_FALSE(DevToolsWindow::GetInstanceForInspectedRenderViewHost(
1378 contents->GetRenderViewHost()));
1379 // And it's not possible to open it again.
1380 EXPECT_FALSE(chrome::ExecuteCommand(browser(), IDC_DEV_TOOLS));
1381 EXPECT_FALSE(DevToolsWindow::GetInstanceForInspectedRenderViewHost(
1382 contents->GetRenderViewHost()));
1385 // TODO(samarth): remove along with rest of NTP4 code.
1386 IN_PROC_BROWSER_TEST_F(PolicyTest, DISABLED_WebStoreIconHidden) {
1387 #if defined(OS_WIN) && defined(USE_ASH)
1388 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
1389 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshBrowserTests))
1393 // Verifies that the web store icons can be hidden from the new tab page.
1395 // Open new tab page and look for the web store icons.
1396 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL));
1397 content::WebContents* contents =
1398 browser()->tab_strip_model()->GetActiveWebContents();
1400 #if !defined(OS_CHROMEOS)
1401 // Look for web store's app ID in the apps page.
1402 EXPECT_TRUE(ContainsVisibleElement(contents,
1403 "ahfgeienlihckogmohjhadlkjgocpleb"));
1406 // The next NTP has no footer.
1407 if (ContainsVisibleElement(contents, "footer"))
1408 EXPECT_TRUE(ContainsVisibleElement(contents, "chrome-web-store-link"));
1410 // Turn off the web store icons.
1412 policies.Set(key::kHideWebStoreIcon, POLICY_LEVEL_MANDATORY,
1413 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL);
1414 UpdateProviderPolicy(policies);
1416 // The web store icons should now be hidden.
1417 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL));
1418 EXPECT_FALSE(ContainsVisibleElement(contents,
1419 "ahfgeienlihckogmohjhadlkjgocpleb"));
1420 EXPECT_FALSE(ContainsVisibleElement(contents, "chrome-web-store-link"));
1423 IN_PROC_BROWSER_TEST_F(PolicyTest, DownloadDirectory) {
1424 // Verifies that the download directory can be forced by policy.
1426 // Set the initial download directory.
1427 base::ScopedTempDir initial_dir;
1428 ASSERT_TRUE(initial_dir.CreateUniqueTempDir());
1429 browser()->profile()->GetPrefs()->SetFilePath(
1430 prefs::kDownloadDefaultDirectory, initial_dir.path());
1431 // Don't prompt for the download location during this test.
1432 browser()->profile()->GetPrefs()->SetBoolean(
1433 prefs::kPromptForDownload, false);
1435 // Verify that downloads end up on the default directory.
1436 base::FilePath file(FILE_PATH_LITERAL("download-test1.lib"));
1437 DownloadAndVerifyFile(browser(), initial_dir.path(), file);
1438 base::DieFileDie(initial_dir.path().Append(file), false);
1440 // Override the download directory with the policy and verify a download.
1441 base::ScopedTempDir forced_dir;
1442 ASSERT_TRUE(forced_dir.CreateUniqueTempDir());
1444 policies.Set(key::kDownloadDirectory, POLICY_LEVEL_MANDATORY,
1446 base::Value::CreateStringValue(forced_dir.path().value()), NULL);
1447 UpdateProviderPolicy(policies);
1448 DownloadAndVerifyFile(browser(), forced_dir.path(), file);
1449 // Verify that the first download location wasn't affected.
1450 EXPECT_FALSE(base::PathExists(initial_dir.path().Append(file)));
1453 IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionInstallBlacklistSelective) {
1454 // Verifies that blacklisted extensions can't be installed.
1455 ExtensionService* service = extension_service();
1456 ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1457 ASSERT_FALSE(service->GetExtensionById(kAdBlockCrxId, true));
1458 base::ListValue blacklist;
1459 blacklist.Append(base::Value::CreateStringValue(kGoodCrxId));
1461 policies.Set(key::kExtensionInstallBlacklist, POLICY_LEVEL_MANDATORY,
1462 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
1463 UpdateProviderPolicy(policies);
1465 // "good.crx" is blacklisted.
1466 EXPECT_FALSE(InstallExtension(kGoodCrxName));
1467 EXPECT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1469 // "adblock.crx" is not.
1470 const extensions::Extension* adblock = InstallExtension(kAdBlockCrxName);
1471 ASSERT_TRUE(adblock);
1472 EXPECT_EQ(kAdBlockCrxId, adblock->id());
1474 service->GetExtensionById(kAdBlockCrxId, true));
1477 // Flaky on windows; http://crbug.com/307994.
1479 #define MAYBE_ExtensionInstallBlacklistWildcard DISABLED_ExtensionInstallBlacklistWildcard
1481 #define MAYBE_ExtensionInstallBlacklistWildcard ExtensionInstallBlacklistWildcard
1483 IN_PROC_BROWSER_TEST_F(PolicyTest, MAYBE_ExtensionInstallBlacklistWildcard) {
1484 // Verify that a wildcard blacklist takes effect.
1485 EXPECT_TRUE(InstallExtension(kAdBlockCrxName));
1486 ExtensionService* service = extension_service();
1487 ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1488 ASSERT_TRUE(service->GetExtensionById(kAdBlockCrxId, true));
1489 base::ListValue blacklist;
1490 blacklist.Append(base::Value::CreateStringValue("*"));
1492 policies.Set(key::kExtensionInstallBlacklist, POLICY_LEVEL_MANDATORY,
1493 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
1494 UpdateProviderPolicy(policies);
1496 // AdBlock was automatically removed.
1497 ASSERT_FALSE(service->GetExtensionById(kAdBlockCrxId, true));
1499 // And can't be installed again, nor can good.crx.
1500 EXPECT_FALSE(InstallExtension(kAdBlockCrxName));
1501 EXPECT_FALSE(service->GetExtensionById(kAdBlockCrxId, true));
1502 EXPECT_FALSE(InstallExtension(kGoodCrxName));
1503 EXPECT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1506 IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionInstallWhitelist) {
1507 // Verifies that the whitelist can open exceptions to the blacklist.
1508 ExtensionService* service = extension_service();
1509 ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1510 ASSERT_FALSE(service->GetExtensionById(kAdBlockCrxId, true));
1511 base::ListValue blacklist;
1512 blacklist.Append(base::Value::CreateStringValue("*"));
1513 base::ListValue whitelist;
1514 whitelist.Append(base::Value::CreateStringValue(kGoodCrxId));
1516 policies.Set(key::kExtensionInstallBlacklist, POLICY_LEVEL_MANDATORY,
1517 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
1518 policies.Set(key::kExtensionInstallWhitelist, POLICY_LEVEL_MANDATORY,
1519 POLICY_SCOPE_USER, whitelist.DeepCopy(), NULL);
1520 UpdateProviderPolicy(policies);
1521 // "adblock.crx" is blacklisted.
1522 EXPECT_FALSE(InstallExtension(kAdBlockCrxName));
1523 EXPECT_FALSE(service->GetExtensionById(kAdBlockCrxId, true));
1524 // "good.crx" has a whitelist exception.
1525 const extensions::Extension* good = InstallExtension(kGoodCrxName);
1527 EXPECT_EQ(kGoodCrxId, good->id());
1528 EXPECT_EQ(good, service->GetExtensionById(kGoodCrxId, true));
1529 // The user can also remove this extension.
1530 UninstallExtension(kGoodCrxId, true);
1533 IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionInstallForcelist) {
1534 // Verifies that extensions that are force-installed by policies are
1535 // installed and can't be uninstalled.
1536 ExtensionService* service = extension_service();
1537 ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1539 // Extensions that are force-installed come from an update URL, which defaults
1540 // to the webstore. Use a mock URL for this test with an update manifest
1541 // that includes "good_v1.crx".
1542 base::FilePath path =
1543 base::FilePath(kTestExtensionsDir).Append(kGoodV1CrxManifestName);
1544 GURL url(URLRequestMockHTTPJob::GetMockUrl(path));
1546 // Setting the forcelist extension should install "good_v1.crx".
1547 base::ListValue forcelist;
1548 forcelist.Append(base::Value::CreateStringValue(base::StringPrintf(
1549 "%s;%s", kGoodCrxId, url.spec().c_str())));
1551 policies.Set(key::kExtensionInstallForcelist, POLICY_LEVEL_MANDATORY,
1552 POLICY_SCOPE_USER, forcelist.DeepCopy(), NULL);
1553 content::WindowedNotificationObserver observer(
1554 chrome::NOTIFICATION_EXTENSION_INSTALLED,
1555 content::NotificationService::AllSources());
1556 UpdateProviderPolicy(policies);
1558 // Note: Cannot check that the notification details match the expected
1559 // exception, since the details object has already been freed prior to
1560 // the completion of observer.Wait().
1562 EXPECT_TRUE(service->GetExtensionById(kGoodCrxId, true));
1564 // The user is not allowed to uninstall force-installed extensions.
1565 UninstallExtension(kGoodCrxId, false);
1567 // The user is not allowed to load an unpacked extension with the
1568 // same ID as a force-installed extension.
1569 LoadUnpackedExtension(kGoodUnpackedExt, false);
1571 // Loading other unpacked extensions are not blocked.
1572 LoadUnpackedExtension(kAppUnpackedExt, true);
1574 const std::string old_version_number =
1575 service->GetExtensionById(kGoodCrxId, true)->version()->GetString();
1577 base::FilePath test_path;
1578 ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA, &test_path));
1580 TestRequestInterceptor interceptor(
1582 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO));
1583 interceptor.PushJobCallback(
1584 TestRequestInterceptor::FileJob(
1585 test_path.Append(kTestExtensionsDir).Append(kGood2CrxManifestName)));
1587 // Updating the force-installed extension.
1588 extensions::ExtensionUpdater* updater = service->updater();
1589 extensions::ExtensionUpdater::CheckParams params;
1590 params.install_immediately = true;
1591 content::WindowedNotificationObserver update_observer(
1592 chrome::NOTIFICATION_EXTENSION_INSTALLED,
1593 content::NotificationService::AllSources());
1594 updater->CheckNow(params);
1595 update_observer.Wait();
1597 const base::Version* new_version =
1598 service->GetExtensionById(kGoodCrxId, true)->version();
1599 ASSERT_TRUE(new_version->IsValid());
1600 base::Version old_version(old_version_number);
1601 ASSERT_TRUE(old_version.IsValid());
1603 EXPECT_EQ(1, new_version->CompareTo(old_version));
1605 EXPECT_EQ(0u, interceptor.GetPendingSize());
1607 // Wait until any background pages belonging to force-installed extensions
1608 // have been loaded.
1609 extensions::ProcessManager* manager =
1610 extensions::ExtensionSystem::Get(browser()->profile())->process_manager();
1611 extensions::ProcessManager::ViewSet all_views = manager->GetAllViews();
1612 for (extensions::ProcessManager::ViewSet::const_iterator iter =
1614 iter != all_views.end();) {
1615 if (!(*iter)->IsLoading()) {
1618 content::WebContents* web_contents =
1619 content::WebContents::FromRenderViewHost(*iter);
1620 ASSERT_TRUE(web_contents);
1621 WebContentsLoadedOrDestroyedWatcher(web_contents).Wait();
1623 // Test activity may have modified the set of extension processes during
1624 // message processing, so re-start the iteration to catch added/removed
1626 all_views = manager->GetAllViews();
1627 iter = all_views.begin();
1631 // Test policy-installed extensions are reloaded when killed.
1632 BackgroundContentsService::
1633 SetRestartDelayForForceInstalledAppsAndExtensionsForTesting(0);
1634 content::WindowedNotificationObserver extension_crashed_observer(
1635 chrome::NOTIFICATION_EXTENSION_PROCESS_TERMINATED,
1636 content::NotificationService::AllSources());
1637 content::WindowedNotificationObserver extension_loaded_observer(
1638 chrome::NOTIFICATION_EXTENSION_LOADED_DEPRECATED,
1639 content::NotificationService::AllSources());
1640 extensions::ExtensionHost* extension_host =
1641 extensions::ExtensionSystem::Get(browser()->profile())->
1642 process_manager()->GetBackgroundHostForExtension(kGoodCrxId);
1643 base::KillProcess(extension_host->render_process_host()->GetHandle(),
1644 content::RESULT_CODE_KILLED, false);
1645 extension_crashed_observer.Wait();
1646 extension_loaded_observer.Wait();
1649 IN_PROC_BROWSER_TEST_F(PolicyTest, ExtensionAllowedTypes) {
1650 // Verifies that extensions are blocked if policy specifies an allowed types
1651 // list and the extension's type is not on that list.
1652 ExtensionService* service = extension_service();
1653 ASSERT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1654 ASSERT_FALSE(service->GetExtensionById(kHostedAppCrxId, true));
1656 base::ListValue allowed_types;
1657 allowed_types.AppendString("hosted_app");
1659 policies.Set(key::kExtensionAllowedTypes, POLICY_LEVEL_MANDATORY,
1660 POLICY_SCOPE_USER, allowed_types.DeepCopy(), NULL);
1661 UpdateProviderPolicy(policies);
1663 // "good.crx" is blocked.
1664 EXPECT_FALSE(InstallExtension(kGoodCrxName));
1665 EXPECT_FALSE(service->GetExtensionById(kGoodCrxId, true));
1667 // "hosted_app.crx" is of a whitelisted type.
1668 const extensions::Extension* hosted_app = InstallExtension(kHostedAppCrxName);
1669 ASSERT_TRUE(hosted_app);
1670 EXPECT_EQ(kHostedAppCrxId, hosted_app->id());
1671 EXPECT_EQ(hosted_app, service->GetExtensionById(kHostedAppCrxId, true));
1673 // The user can remove the extension.
1674 UninstallExtension(kHostedAppCrxId, true);
1677 // Checks that a click on an extension CRX download triggers the extension
1678 // installation prompt without further user interaction when the source is
1679 // whitelisted by policy.
1680 // Flaky on windows; http://crbug.com/295729 .
1682 #define MAYBE_ExtensionInstallSources DISABLED_ExtensionInstallSources
1684 #define MAYBE_ExtensionInstallSources ExtensionInstallSources
1686 IN_PROC_BROWSER_TEST_F(PolicyTest, MAYBE_ExtensionInstallSources) {
1687 CommandLine::ForCurrentProcess()->AppendSwitchASCII(
1688 switches::kAppsGalleryInstallAutoConfirmForTests, "accept");
1690 const GURL install_source_url(URLRequestMockHTTPJob::GetMockUrl(
1691 base::FilePath(FILE_PATH_LITERAL("extensions/*"))));
1692 const GURL referrer_url(URLRequestMockHTTPJob::GetMockUrl(
1693 base::FilePath(FILE_PATH_LITERAL("policy/*"))));
1695 const GURL download_page_url(URLRequestMockHTTPJob::GetMockUrl(base::FilePath(
1696 FILE_PATH_LITERAL("policy/extension_install_sources_test.html"))));
1697 ui_test_utils::NavigateToURL(browser(), download_page_url);
1699 // As long as the policy is not present, extensions are considered dangerous.
1700 content::DownloadTestObserverTerminal download_observer(
1701 content::BrowserContext::GetDownloadManager(browser()->profile()), 1,
1702 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_DENY);
1704 download_observer.WaitForFinished();
1706 // Install the policy and trigger another download.
1707 base::ListValue install_sources;
1708 install_sources.AppendString(install_source_url.spec());
1709 install_sources.AppendString(referrer_url.spec());
1711 policies.Set(key::kExtensionInstallSources, POLICY_LEVEL_MANDATORY,
1712 POLICY_SCOPE_USER, install_sources.DeepCopy(), NULL);
1713 UpdateProviderPolicy(policies);
1715 content::WindowedNotificationObserver observer(
1716 chrome::NOTIFICATION_EXTENSION_INSTALLED,
1717 content::NotificationService::AllSources());
1720 // Note: Cannot check that the notification details match the expected
1721 // exception, since the details object has already been freed prior to
1722 // the completion of observer.Wait().
1724 // The first extension shouldn't be present, the second should be there.
1725 EXPECT_FALSE(extension_service()->GetExtensionById(kGoodCrxId, true));
1726 EXPECT_TRUE(extension_service()->GetExtensionById(kAdBlockCrxId, false));
1729 IN_PROC_BROWSER_TEST_F(PolicyTest, HomepageLocation) {
1730 #if defined(OS_WIN) && defined(USE_ASH)
1731 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
1732 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshBrowserTests))
1736 // Verifies that the homepage can be configured with policies.
1737 // Set a default, and check that the home button navigates there.
1738 browser()->profile()->GetPrefs()->SetString(
1739 prefs::kHomePage, chrome::kChromeUIPolicyURL);
1740 browser()->profile()->GetPrefs()->SetBoolean(
1741 prefs::kHomePageIsNewTabPage, false);
1742 EXPECT_EQ(GURL(chrome::kChromeUIPolicyURL),
1743 browser()->profile()->GetHomePage());
1744 content::WebContents* contents =
1745 browser()->tab_strip_model()->GetActiveWebContents();
1746 EXPECT_EQ(GURL(content::kAboutBlankURL), contents->GetURL());
1747 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_HOME));
1748 EXPECT_EQ(GURL(chrome::kChromeUIPolicyURL), contents->GetURL());
1750 // Now override with policy.
1752 policies.Set(key::kHomepageLocation, POLICY_LEVEL_MANDATORY,
1754 base::Value::CreateStringValue(chrome::kChromeUICreditsURL),
1756 UpdateProviderPolicy(policies);
1757 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_HOME));
1758 content::WaitForLoadStop(contents);
1759 EXPECT_EQ(GURL(chrome::kChromeUICreditsURL), contents->GetURL());
1761 policies.Set(key::kHomepageIsNewTabPage, POLICY_LEVEL_MANDATORY,
1762 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL);
1763 UpdateProviderPolicy(policies);
1764 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_HOME));
1765 content::WaitForLoadStop(contents);
1766 EXPECT_EQ(GURL(chrome::kChromeUINewTabURL), contents->GetURL());
1769 IN_PROC_BROWSER_TEST_F(PolicyTest, IncognitoEnabled) {
1770 // Verifies that incognito windows can't be opened when disabled by policy.
1772 const BrowserList* active_browser_list =
1773 BrowserList::GetInstance(chrome::GetActiveDesktop());
1775 // Disable incognito via policy and verify that incognito windows can't be
1777 EXPECT_EQ(1u, active_browser_list->size());
1778 EXPECT_FALSE(BrowserList::IsOffTheRecordSessionActive());
1780 policies.Set(key::kIncognitoEnabled, POLICY_LEVEL_MANDATORY,
1781 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(false), NULL);
1782 UpdateProviderPolicy(policies);
1783 EXPECT_FALSE(chrome::ExecuteCommand(browser(), IDC_NEW_INCOGNITO_WINDOW));
1784 EXPECT_EQ(1u, active_browser_list->size());
1785 EXPECT_FALSE(BrowserList::IsOffTheRecordSessionActive());
1787 // Enable via policy and verify that incognito windows can be opened.
1788 policies.Set(key::kIncognitoEnabled, POLICY_LEVEL_MANDATORY,
1789 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL);
1790 UpdateProviderPolicy(policies);
1791 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_NEW_INCOGNITO_WINDOW));
1792 EXPECT_EQ(2u, active_browser_list->size());
1793 EXPECT_TRUE(BrowserList::IsOffTheRecordSessionActive());
1796 IN_PROC_BROWSER_TEST_F(PolicyTest, Javascript) {
1797 // Verifies that Javascript can be disabled.
1798 content::WebContents* contents =
1799 browser()->tab_strip_model()->GetActiveWebContents();
1800 EXPECT_TRUE(IsJavascriptEnabled(contents));
1801 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS));
1802 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS_CONSOLE));
1803 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS_DEVICES));
1805 // Disable Javascript via policy.
1807 policies.Set(key::kJavascriptEnabled, POLICY_LEVEL_MANDATORY,
1808 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(false), NULL);
1809 UpdateProviderPolicy(policies);
1811 ui_test_utils::NavigateToURL(browser(), GURL(content::kAboutBlankURL));
1812 EXPECT_FALSE(IsJavascriptEnabled(contents));
1813 // Developer tools still work when javascript is disabled.
1814 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS));
1815 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS_CONSOLE));
1816 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS_DEVICES));
1817 // Javascript is always enabled for the internal pages.
1818 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUIAboutURL));
1819 EXPECT_TRUE(IsJavascriptEnabled(contents));
1821 // The javascript content setting policy overrides the javascript policy.
1822 ui_test_utils::NavigateToURL(browser(), GURL(content::kAboutBlankURL));
1823 EXPECT_FALSE(IsJavascriptEnabled(contents));
1824 policies.Set(key::kDefaultJavaScriptSetting, POLICY_LEVEL_MANDATORY,
1826 base::Value::CreateIntegerValue(CONTENT_SETTING_ALLOW), NULL);
1827 UpdateProviderPolicy(policies);
1828 ui_test_utils::NavigateToURL(browser(), GURL(content::kAboutBlankURL));
1829 EXPECT_TRUE(IsJavascriptEnabled(contents));
1832 IN_PROC_BROWSER_TEST_F(PolicyTest, SavingBrowserHistoryDisabled) {
1833 // Verifies that browsing history is not saved.
1835 policies.Set(key::kSavingBrowserHistoryDisabled, POLICY_LEVEL_MANDATORY,
1836 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL);
1837 UpdateProviderPolicy(policies);
1838 GURL url = ui_test_utils::GetTestUrl(
1839 base::FilePath(base::FilePath::kCurrentDirectory),
1840 base::FilePath(FILE_PATH_LITERAL("empty.html")));
1841 ui_test_utils::NavigateToURL(browser(), url);
1842 // Verify that the navigation wasn't saved in the history.
1843 ui_test_utils::HistoryEnumerator enumerator1(browser()->profile());
1844 EXPECT_EQ(0u, enumerator1.urls().size());
1846 // Now flip the policy and try again.
1847 policies.Set(key::kSavingBrowserHistoryDisabled, POLICY_LEVEL_MANDATORY,
1848 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(false), NULL);
1849 UpdateProviderPolicy(policies);
1850 ui_test_utils::NavigateToURL(browser(), url);
1851 // Verify that the navigation was saved in the history.
1852 ui_test_utils::HistoryEnumerator enumerator2(browser()->profile());
1853 ASSERT_EQ(1u, enumerator2.urls().size());
1854 EXPECT_EQ(url, enumerator2.urls()[0]);
1857 // http://crbug.com/241691 PolicyTest.TranslateEnabled is failing regularly.
1858 IN_PROC_BROWSER_TEST_F(PolicyTest, DISABLED_TranslateEnabled) {
1859 TranslateService::SetUseInfobar(true);
1861 // Verifies that translate can be forced enabled or disabled by policy.
1863 // Get the InfoBarService, and verify that there are no infobars on startup.
1864 content::WebContents* contents =
1865 browser()->tab_strip_model()->GetActiveWebContents();
1866 ASSERT_TRUE(contents);
1867 InfoBarService* infobar_service = InfoBarService::FromWebContents(contents);
1868 ASSERT_TRUE(infobar_service);
1869 EXPECT_EQ(0u, infobar_service->infobar_count());
1871 // Force enable the translate feature.
1873 policies.Set(key::kTranslateEnabled, POLICY_LEVEL_MANDATORY,
1874 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL);
1875 UpdateProviderPolicy(policies);
1876 // Instead of waiting for NOTIFICATION_TAB_CONTENTS_INFOBAR_ADDED, this test
1877 // waits for NOTIFICATION_TAB_LANGUAGE_DETERMINED because that's what the
1878 // TranslateManager observes. This allows checking that an infobar is NOT
1879 // shown below, without polling for infobars for some indeterminate amount
1881 GURL url = ui_test_utils::GetTestUrl(
1883 base::FilePath(FILE_PATH_LITERAL("translate/fr_test.html")));
1884 content::WindowedNotificationObserver language_observer1(
1885 chrome::NOTIFICATION_TAB_LANGUAGE_DETERMINED,
1886 content::NotificationService::AllSources());
1887 ui_test_utils::NavigateToURL(browser(), url);
1888 language_observer1.Wait();
1890 // Verify the translation detected for this tab.
1891 TranslateTabHelper* translate_tab_helper =
1892 TranslateTabHelper::FromWebContents(contents);
1893 ASSERT_TRUE(translate_tab_helper);
1894 LanguageState& language_state = translate_tab_helper->GetLanguageState();
1895 EXPECT_EQ("fr", language_state.original_language());
1896 EXPECT_TRUE(language_state.page_needs_translation());
1897 EXPECT_FALSE(language_state.translation_pending());
1898 EXPECT_FALSE(language_state.translation_declined());
1899 EXPECT_FALSE(language_state.IsPageTranslated());
1901 // Verify that the translate infobar showed up.
1902 ASSERT_EQ(1u, infobar_service->infobar_count());
1903 infobars::InfoBar* infobar = infobar_service->infobar_at(0);
1904 TranslateInfoBarDelegate* translate_infobar_delegate =
1905 infobar->delegate()->AsTranslateInfoBarDelegate();
1906 ASSERT_TRUE(translate_infobar_delegate);
1907 EXPECT_EQ(translate::TRANSLATE_STEP_BEFORE_TRANSLATE,
1908 translate_infobar_delegate->translate_step());
1909 EXPECT_EQ("fr", translate_infobar_delegate->original_language_code());
1911 // Now force disable translate.
1912 infobar_service->RemoveInfoBar(infobar);
1913 EXPECT_EQ(0u, infobar_service->infobar_count());
1914 policies.Set(key::kTranslateEnabled, POLICY_LEVEL_MANDATORY,
1915 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(false), NULL);
1916 UpdateProviderPolicy(policies);
1917 // Navigating to the same URL now doesn't trigger an infobar.
1918 content::WindowedNotificationObserver language_observer2(
1919 chrome::NOTIFICATION_TAB_LANGUAGE_DETERMINED,
1920 content::NotificationService::AllSources());
1921 ui_test_utils::NavigateToURL(browser(), url);
1922 language_observer2.Wait();
1923 EXPECT_EQ(0u, infobar_service->infobar_count());
1926 IN_PROC_BROWSER_TEST_F(PolicyTest, URLBlacklist) {
1927 // Checks that URLs can be blacklisted, and that exceptions can be made to
1930 // Filter |kURLS| on IO thread, so that requests to those hosts end up
1931 // as URLRequestMockHTTPJobs.
1932 const char* kURLS[] = {
1933 "http://aaa.com/empty.html",
1934 "http://bbb.com/empty.html",
1935 "http://sub.bbb.com/empty.html",
1936 "http://bbb.com/policy/blank.html",
1940 BrowserThread::PostTaskAndReply(
1941 BrowserThread::IO, FROM_HERE,
1942 base::Bind(RedirectHostsToTestData, kURLS, arraysize(kURLS)),
1943 loop.QuitClosure());
1947 // Verify that "bbb.com" opens before applying the blacklist.
1948 CheckCanOpenURL(browser(), kURLS[1]);
1951 base::ListValue blacklist;
1952 blacklist.Append(base::Value::CreateStringValue("bbb.com"));
1954 policies.Set(key::kURLBlacklist, POLICY_LEVEL_MANDATORY,
1955 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
1956 UpdateProviderPolicy(policies);
1957 FlushBlacklistPolicy();
1958 // All bbb.com URLs are blocked, and "aaa.com" is still unblocked.
1959 CheckCanOpenURL(browser(), kURLS[0]);
1960 for (size_t i = 1; i < arraysize(kURLS); ++i)
1961 CheckURLIsBlocked(browser(), kURLS[i]);
1963 // Whitelist some sites of bbb.com.
1964 base::ListValue whitelist;
1965 whitelist.Append(base::Value::CreateStringValue("sub.bbb.com"));
1966 whitelist.Append(base::Value::CreateStringValue("bbb.com/policy"));
1967 policies.Set(key::kURLWhitelist, POLICY_LEVEL_MANDATORY,
1968 POLICY_SCOPE_USER, whitelist.DeepCopy(), NULL);
1969 UpdateProviderPolicy(policies);
1970 FlushBlacklistPolicy();
1971 CheckURLIsBlocked(browser(), kURLS[1]);
1972 CheckCanOpenURL(browser(), kURLS[2]);
1973 CheckCanOpenURL(browser(), kURLS[3]);
1977 BrowserThread::PostTaskAndReply(
1978 BrowserThread::IO, FROM_HERE,
1979 base::Bind(UndoRedirectHostsToTestData, kURLS, arraysize(kURLS)),
1980 loop.QuitClosure());
1985 // This test is flaky on all platforms; see http://crbug.com/339240
1986 IN_PROC_BROWSER_TEST_F(PolicyTest, DISABLED_FileURLBlacklist) {
1987 // Check that FileURLs can be blacklisted and DisabledSchemes works together
1988 // with URLblacklisting and URLwhitelisting.
1990 base::FilePath test_path;
1991 PathService::Get(chrome::DIR_TEST_DATA, &test_path);
1992 const std::string base_path = "file://" + test_path.AsUTF8Unsafe() +"/";
1993 const std::string folder_path = base_path + "apptest/";
1994 const std::string file_path1 = base_path + "title1.html";
1995 const std::string file_path2 = folder_path + "basic.html";
1997 CheckCanOpenURL(browser(), file_path1.c_str());
1998 CheckCanOpenURL(browser(), file_path2.c_str());
2000 // Set a blacklist for all the files.
2001 base::ListValue blacklist;
2002 blacklist.Append(base::Value::CreateStringValue("file://*"));
2004 policies.Set(key::kURLBlacklist, POLICY_LEVEL_MANDATORY,
2005 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
2006 UpdateProviderPolicy(policies);
2007 FlushBlacklistPolicy();
2009 CheckURLIsBlocked(browser(), file_path1.c_str());
2010 CheckURLIsBlocked(browser(), file_path2.c_str());
2012 // Replace the URLblacklist with disabling the file scheme.
2013 blacklist.Remove(base::StringValue("file://*"), NULL);
2014 policies.Set(key::kURLBlacklist, POLICY_LEVEL_MANDATORY,
2015 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
2016 UpdateProviderPolicy(policies);
2017 FlushBlacklistPolicy();
2019 PrefService* prefs = browser()->profile()->GetPrefs();
2020 const base::ListValue* list_url = prefs->GetList(policy_prefs::kUrlBlacklist);
2021 EXPECT_EQ(list_url->Find(base::StringValue("file://*")),
2024 base::ListValue disabledscheme;
2025 disabledscheme.Append(base::Value::CreateStringValue("file"));
2026 policies.Set(key::kDisabledSchemes, POLICY_LEVEL_MANDATORY,
2027 POLICY_SCOPE_USER, disabledscheme.DeepCopy(), NULL);
2028 UpdateProviderPolicy(policies);
2029 FlushBlacklistPolicy();
2031 list_url = prefs->GetList(policy_prefs::kUrlBlacklist);
2032 EXPECT_NE(list_url->Find(base::StringValue("file://*")),
2035 // Whitelist one folder and blacklist an another just inside.
2036 base::ListValue whitelist;
2037 whitelist.Append(base::Value::CreateStringValue(base_path));
2038 policies.Set(key::kURLWhitelist, POLICY_LEVEL_MANDATORY,
2039 POLICY_SCOPE_USER, whitelist.DeepCopy(), NULL);
2040 blacklist.Append(base::Value::CreateStringValue(folder_path));
2041 policies.Set(key::kURLBlacklist, POLICY_LEVEL_MANDATORY,
2042 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
2043 UpdateProviderPolicy(policies);
2044 FlushBlacklistPolicy();
2046 CheckCanOpenURL(browser(), file_path1.c_str());
2047 CheckURLIsBlocked(browser(), file_path2.c_str());
2050 #if !defined(OS_MACOSX)
2051 IN_PROC_BROWSER_TEST_F(PolicyTest, FullscreenAllowedBrowser) {
2053 policies.Set(key::kFullscreenAllowed,
2054 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2055 base::Value::CreateBooleanValue(false), NULL);
2056 UpdateProviderPolicy(policies);
2058 BrowserWindow* browser_window = browser()->window();
2059 ASSERT_TRUE(browser_window);
2061 EXPECT_FALSE(browser_window->IsFullscreen());
2062 chrome::ToggleFullscreenMode(browser());
2063 EXPECT_FALSE(browser_window->IsFullscreen());
2066 IN_PROC_BROWSER_TEST_F(PolicyTest, FullscreenAllowedApp) {
2068 policies.Set(key::kFullscreenAllowed,
2069 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2070 base::Value::CreateBooleanValue(false), NULL);
2071 UpdateProviderPolicy(policies);
2073 const extensions::Extension* extension =
2074 LoadUnpackedExtension(kUnpackedFullscreenAppName, true);
2075 ASSERT_TRUE(extension);
2077 // Launch an app that tries to open a fullscreen window.
2078 TestAddAppWindowObserver add_window_observer(
2079 apps::AppWindowRegistry::Get(browser()->profile()));
2080 OpenApplication(AppLaunchParams(browser()->profile(),
2082 extensions::LAUNCH_CONTAINER_NONE,
2084 apps::AppWindow* window = add_window_observer.WaitForAppWindow();
2085 ASSERT_TRUE(window);
2087 // Verify that the window is not in fullscreen mode.
2088 EXPECT_FALSE(window->GetBaseWindow()->IsFullscreen());
2090 // Verify that the window cannot be toggled into fullscreen mode via apps
2092 EXPECT_TRUE(content::ExecuteScript(
2093 window->web_contents(),
2094 "chrome.app.window.current().fullscreen();"));
2095 EXPECT_FALSE(window->GetBaseWindow()->IsFullscreen());
2097 // Verify that the window cannot be toggled into fullscreen mode from within
2098 // Chrome (e.g., using keyboard accelerators).
2099 window->Fullscreen();
2100 EXPECT_FALSE(window->GetBaseWindow()->IsFullscreen());
2104 #if defined(OS_CHROMEOS)
2105 IN_PROC_BROWSER_TEST_F(PolicyTest, DisableScreenshotsFile) {
2106 int screenshot_count = CountScreenshots();
2108 // Make sure screenshots are counted correctly.
2109 TestScreenshotFile(true);
2110 ASSERT_EQ(CountScreenshots(), screenshot_count + 1);
2112 // Check if trying to take a screenshot fails when disabled by policy.
2113 TestScreenshotFile(false);
2114 ASSERT_EQ(CountScreenshots(), screenshot_count + 1);
2117 IN_PROC_BROWSER_TEST_F(PolicyTest, DisableAudioOutput) {
2118 // Set up the mock observer.
2119 chromeos::CrasAudioHandler* audio_handler = chromeos::CrasAudioHandler::Get();
2120 scoped_ptr<TestAudioObserver> test_observer(new TestAudioObserver);
2121 audio_handler->AddAudioObserver(test_observer.get());
2123 bool prior_state = audio_handler->IsOutputMuted();
2124 // Make sure the audio is not muted and then toggle the policy and observe
2125 // if the output mute changed event is fired.
2126 audio_handler->SetOutputMute(false);
2127 EXPECT_FALSE(audio_handler->IsOutputMuted());
2128 EXPECT_EQ(1, test_observer->output_mute_changed_count());
2130 policies.Set(key::kAudioOutputAllowed, POLICY_LEVEL_MANDATORY,
2131 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(false), NULL);
2132 UpdateProviderPolicy(policies);
2133 EXPECT_TRUE(audio_handler->IsOutputMuted());
2134 // This should not change the state now and should not trigger output mute
2136 audio_handler->SetOutputMute(false);
2137 EXPECT_TRUE(audio_handler->IsOutputMuted());
2138 EXPECT_EQ(1, test_observer->output_mute_changed_count());
2140 // Toggle back and observe if the output mute changed event is fired.
2141 policies.Set(key::kAudioOutputAllowed, POLICY_LEVEL_MANDATORY,
2142 POLICY_SCOPE_USER, base::Value::CreateBooleanValue(true), NULL);
2143 UpdateProviderPolicy(policies);
2144 EXPECT_FALSE(audio_handler->IsOutputMuted());
2145 EXPECT_EQ(1, test_observer->output_mute_changed_count());
2146 audio_handler->SetOutputMute(true);
2147 EXPECT_TRUE(audio_handler->IsOutputMuted());
2148 EXPECT_EQ(2, test_observer->output_mute_changed_count());
2149 // Revert the prior state.
2150 audio_handler->SetOutputMute(prior_state);
2151 audio_handler->RemoveAudioObserver(test_observer.get());
2154 // Disabled, see http://crbug.com/315308.
2155 IN_PROC_BROWSER_TEST_F(PolicyTest, DISABLED_PRE_SessionLengthLimit) {
2156 // Indicate that the session started 2 hours ago and no user activity has
2158 g_browser_process->local_state()->SetInt64(
2159 prefs::kSessionStartTime,
2160 (base::TimeTicks::Now() - base::TimeDelta::FromHours(2))
2161 .ToInternalValue());
2164 // Disabled, see http://crbug.com/315308.
2165 IN_PROC_BROWSER_TEST_F(PolicyTest, DISABLED_SessionLengthLimit) {
2166 content::MockNotificationObserver observer;
2167 content::NotificationRegistrar registrar;
2168 registrar.Add(&observer,
2169 chrome::NOTIFICATION_APP_TERMINATING,
2170 content::NotificationService::AllSources());
2172 // Set the session length limit to 3 hours. Verify that the session is not
2174 EXPECT_CALL(observer, Observe(chrome::NOTIFICATION_APP_TERMINATING, _, _))
2177 policies.Set(key::kSessionLengthLimit, POLICY_LEVEL_MANDATORY,
2179 base::Value::CreateIntegerValue(kThreeHoursInMs),
2181 UpdateProviderPolicy(policies);
2182 base::RunLoop().RunUntilIdle();
2183 Mock::VerifyAndClearExpectations(&observer);
2185 // Decrease the session length limit to 1 hour. Verify that the session is
2186 // terminated immediately.
2187 EXPECT_CALL(observer, Observe(chrome::NOTIFICATION_APP_TERMINATING, _, _));
2188 policies.Set(key::kSessionLengthLimit, POLICY_LEVEL_MANDATORY,
2190 base::Value::CreateIntegerValue(kOneHourInMs),
2192 UpdateProviderPolicy(policies);
2193 base::RunLoop().RunUntilIdle();
2194 Mock::VerifyAndClearExpectations(&observer);
2197 // Disabled, see http://crbug.com/315308.
2198 IN_PROC_BROWSER_TEST_F(PolicyTest,
2199 DISABLED_PRE_WaitForInitialUserActivityUsatisfied) {
2200 // Indicate that the session started 2 hours ago and no user activity has
2202 g_browser_process->local_state()->SetInt64(
2203 prefs::kSessionStartTime,
2204 (base::TimeTicks::Now() - base::TimeDelta::FromHours(2))
2205 .ToInternalValue());
2208 // Disabled, see http://crbug.com/315308.
2209 IN_PROC_BROWSER_TEST_F(PolicyTest,
2210 DISABLED_WaitForInitialUserActivityUsatisfied) {
2211 content::MockNotificationObserver observer;
2212 content::NotificationRegistrar registrar;
2213 registrar.Add(&observer,
2214 chrome::NOTIFICATION_APP_TERMINATING,
2215 content::NotificationService::AllSources());
2217 // Require initial user activity.
2219 policies.Set(key::kWaitForInitialUserActivity, POLICY_LEVEL_MANDATORY,
2221 new base::FundamentalValue(true),
2223 UpdateProviderPolicy(policies);
2224 base::RunLoop().RunUntilIdle();
2226 // Set the session length limit to 1 hour. Verify that the session is not
2228 EXPECT_CALL(observer, Observe(chrome::NOTIFICATION_APP_TERMINATING, _, _))
2230 policies.Set(key::kSessionLengthLimit, POLICY_LEVEL_MANDATORY,
2232 base::Value::CreateIntegerValue(kOneHourInMs),
2234 UpdateProviderPolicy(policies);
2235 base::RunLoop().RunUntilIdle();
2236 Mock::VerifyAndClearExpectations(&observer);
2239 // Disabled, see http://crbug.com/315308.
2240 IN_PROC_BROWSER_TEST_F(PolicyTest,
2241 DISABLED_PRE_WaitForInitialUserActivitySatisfied) {
2242 // Indicate that initial user activity in this session occurred 2 hours ago.
2243 g_browser_process->local_state()->SetInt64(
2244 prefs::kSessionStartTime,
2245 (base::TimeTicks::Now() - base::TimeDelta::FromHours(2))
2246 .ToInternalValue());
2247 g_browser_process->local_state()->SetBoolean(
2248 prefs::kSessionUserActivitySeen,
2252 // Disabled, see http://crbug.com/315308.
2253 IN_PROC_BROWSER_TEST_F(PolicyTest,
2254 DISABLED_WaitForInitialUserActivitySatisfied) {
2255 content::MockNotificationObserver observer;
2256 content::NotificationRegistrar registrar;
2257 registrar.Add(&observer,
2258 chrome::NOTIFICATION_APP_TERMINATING,
2259 content::NotificationService::AllSources());
2261 // Require initial user activity and set the session length limit to 3 hours.
2262 // Verify that the session is not terminated.
2263 EXPECT_CALL(observer, Observe(chrome::NOTIFICATION_APP_TERMINATING, _, _))
2266 policies.Set(key::kWaitForInitialUserActivity, POLICY_LEVEL_MANDATORY,
2268 new base::FundamentalValue(true),
2270 policies.Set(key::kSessionLengthLimit, POLICY_LEVEL_MANDATORY,
2272 base::Value::CreateIntegerValue(kThreeHoursInMs),
2274 UpdateProviderPolicy(policies);
2275 base::RunLoop().RunUntilIdle();
2276 Mock::VerifyAndClearExpectations(&observer);
2278 // Decrease the session length limit to 1 hour. Verify that the session is
2279 // terminated immediately.
2280 EXPECT_CALL(observer, Observe(chrome::NOTIFICATION_APP_TERMINATING, _, _));
2281 policies.Set(key::kSessionLengthLimit, POLICY_LEVEL_MANDATORY,
2283 base::Value::CreateIntegerValue(kOneHourInMs),
2285 UpdateProviderPolicy(policies);
2286 base::RunLoop().RunUntilIdle();
2287 Mock::VerifyAndClearExpectations(&observer);
2290 IN_PROC_BROWSER_TEST_F(PolicyTest, LargeCursorEnabled) {
2291 // Verifies that the large cursor accessibility feature can be controlled
2293 chromeos::AccessibilityManager* accessibility_manager =
2294 chromeos::AccessibilityManager::Get();
2296 // Manually enable the large cursor.
2297 accessibility_manager->EnableLargeCursor(true);
2298 EXPECT_TRUE(accessibility_manager->IsLargeCursorEnabled());
2300 // Verify that policy overrides the manual setting.
2302 policies.Set(key::kLargeCursorEnabled, POLICY_LEVEL_MANDATORY,
2304 base::Value::CreateBooleanValue(false), NULL);
2305 UpdateProviderPolicy(policies);
2306 EXPECT_FALSE(accessibility_manager->IsLargeCursorEnabled());
2308 // Verify that the large cursor cannot be enabled manually anymore.
2309 accessibility_manager->EnableLargeCursor(true);
2310 EXPECT_FALSE(accessibility_manager->IsLargeCursorEnabled());
2313 IN_PROC_BROWSER_TEST_F(PolicyTest, SpokenFeedbackEnabled) {
2314 // Verifies that the spoken feedback accessibility feature can be controlled
2316 chromeos::AccessibilityManager* accessibility_manager =
2317 chromeos::AccessibilityManager::Get();
2319 // Manually enable spoken feedback.
2320 accessibility_manager->EnableSpokenFeedback(
2321 true, ash::A11Y_NOTIFICATION_NONE);
2322 EXPECT_TRUE(accessibility_manager->IsSpokenFeedbackEnabled());
2324 // Verify that policy overrides the manual setting.
2326 policies.Set(key::kSpokenFeedbackEnabled, POLICY_LEVEL_MANDATORY,
2328 base::Value::CreateBooleanValue(false), NULL);
2329 UpdateProviderPolicy(policies);
2330 EXPECT_FALSE(accessibility_manager->IsSpokenFeedbackEnabled());
2332 // Verify that spoken feedback cannot be enabled manually anymore.
2333 accessibility_manager->EnableSpokenFeedback(
2334 true, ash::A11Y_NOTIFICATION_NONE);
2335 EXPECT_FALSE(accessibility_manager->IsSpokenFeedbackEnabled());
2338 IN_PROC_BROWSER_TEST_F(PolicyTest, HighContrastEnabled) {
2339 // Verifies that the high contrast mode accessibility feature can be
2340 // controlled through policy.
2341 chromeos::AccessibilityManager* accessibility_manager =
2342 chromeos::AccessibilityManager::Get();
2344 // Manually enable high contrast mode.
2345 accessibility_manager->EnableHighContrast(true);
2346 EXPECT_TRUE(accessibility_manager->IsHighContrastEnabled());
2348 // Verify that policy overrides the manual setting.
2350 policies.Set(key::kHighContrastEnabled, POLICY_LEVEL_MANDATORY,
2352 base::Value::CreateBooleanValue(false), NULL);
2353 UpdateProviderPolicy(policies);
2354 EXPECT_FALSE(accessibility_manager->IsHighContrastEnabled());
2356 // Verify that high contrast mode cannot be enabled manually anymore.
2357 accessibility_manager->EnableHighContrast(true);
2358 EXPECT_FALSE(accessibility_manager->IsHighContrastEnabled());
2361 IN_PROC_BROWSER_TEST_F(PolicyTest, ScreenMagnifierTypeNone) {
2362 // Verifies that the screen magnifier can be disabled through policy.
2363 chromeos::MagnificationManager* magnification_manager =
2364 chromeos::MagnificationManager::Get();
2366 // Manually enable the full-screen magnifier.
2367 magnification_manager->SetMagnifierType(ash::MAGNIFIER_FULL);
2368 magnification_manager->SetMagnifierEnabled(true);
2369 EXPECT_EQ(ash::MAGNIFIER_FULL, magnification_manager->GetMagnifierType());
2370 EXPECT_TRUE(magnification_manager->IsMagnifierEnabled());
2372 // Verify that policy overrides the manual setting.
2374 policies.Set(key::kScreenMagnifierType, POLICY_LEVEL_MANDATORY,
2376 base::Value::CreateIntegerValue(0), NULL);
2377 UpdateProviderPolicy(policies);
2378 EXPECT_FALSE(magnification_manager->IsMagnifierEnabled());
2380 // Verify that the screen magnifier cannot be enabled manually anymore.
2381 magnification_manager->SetMagnifierEnabled(true);
2382 EXPECT_FALSE(magnification_manager->IsMagnifierEnabled());
2385 IN_PROC_BROWSER_TEST_F(PolicyTest, ScreenMagnifierTypeFull) {
2386 // Verifies that the full-screen magnifier can be enabled through policy.
2387 chromeos::MagnificationManager* magnification_manager =
2388 chromeos::MagnificationManager::Get();
2390 // Verify that the screen magnifier is initially disabled.
2391 EXPECT_FALSE(magnification_manager->IsMagnifierEnabled());
2393 // Verify that policy can enable the full-screen magnifier.
2395 policies.Set(key::kScreenMagnifierType, POLICY_LEVEL_MANDATORY,
2397 base::Value::CreateIntegerValue(ash::MAGNIFIER_FULL), NULL);
2398 UpdateProviderPolicy(policies);
2399 EXPECT_EQ(ash::MAGNIFIER_FULL, magnification_manager->GetMagnifierType());
2400 EXPECT_TRUE(magnification_manager->IsMagnifierEnabled());
2402 // Verify that the screen magnifier cannot be disabled manually anymore.
2403 magnification_manager->SetMagnifierEnabled(false);
2404 EXPECT_TRUE(magnification_manager->IsMagnifierEnabled());
2407 IN_PROC_BROWSER_TEST_F(PolicyTest, VirtualKeyboardEnabled) {
2408 // Verifies that the on-screen keyboard accessibility feature can be
2409 // controlled through policy.
2410 chromeos::AccessibilityManager* accessibility_manager =
2411 chromeos::AccessibilityManager::Get();
2413 // Manually enable the on-screen keyboard.
2414 accessibility_manager->EnableVirtualKeyboard(true);
2415 EXPECT_TRUE(accessibility_manager->IsVirtualKeyboardEnabled());
2417 // Verify that policy overrides the manual setting.
2419 policies.Set(key::kVirtualKeyboardEnabled, POLICY_LEVEL_MANDATORY,
2421 base::Value::CreateBooleanValue(false), NULL);
2422 UpdateProviderPolicy(policies);
2423 EXPECT_FALSE(accessibility_manager->IsVirtualKeyboardEnabled());
2425 // Verify that the on-screen keyboard cannot be enabled manually anymore.
2426 accessibility_manager->EnableVirtualKeyboard(true);
2427 EXPECT_FALSE(accessibility_manager->IsVirtualKeyboardEnabled());
2434 static const char* kRestoredURLs[] = {
2435 "http://aaa.com/empty.html",
2436 "http://bbb.com/empty.html",
2439 bool IsNonSwitchArgument(const CommandLine::StringType& s) {
2440 return s.empty() || s[0] != '-';
2445 // Similar to PolicyTest but allows setting policies before the browser is
2446 // created. Each test parameter is a method that sets up the early policies
2447 // and stores the expected startup URLs in |expected_urls_|.
2448 class RestoreOnStartupPolicyTest
2449 : public PolicyTest,
2450 public testing::WithParamInterface<
2451 void (RestoreOnStartupPolicyTest::*)(void)> {
2453 RestoreOnStartupPolicyTest() {}
2454 virtual ~RestoreOnStartupPolicyTest() {}
2456 #if defined(OS_CHROMEOS)
2457 virtual void SetUpCommandLine(CommandLine* command_line) OVERRIDE {
2458 // TODO(nkostylev): Investigate if we can remove this switch.
2459 command_line->AppendSwitch(switches::kCreateBrowserOnStartupForTests);
2460 PolicyTest::SetUpCommandLine(command_line);
2464 virtual void SetUpInProcessBrowserTestFixture() OVERRIDE {
2465 PolicyTest::SetUpInProcessBrowserTestFixture();
2466 // Set early policies now, before the browser is created.
2467 (this->*(GetParam()))();
2469 // Remove the non-switch arguments, so that session restore kicks in for
2471 CommandLine* command_line = CommandLine::ForCurrentProcess();
2472 CommandLine::StringVector argv = command_line->argv();
2473 argv.erase(std::remove_if(++argv.begin(), argv.end(), IsNonSwitchArgument),
2475 command_line->InitFromArgv(argv);
2476 ASSERT_TRUE(std::equal(argv.begin(), argv.end(),
2477 command_line->argv().begin()));
2479 // Redirect the test URLs to the test data directory.
2480 RedirectHostsToTestData(kRestoredURLs, arraysize(kRestoredURLs));
2483 void HomepageIsNotNTP() {
2484 // Verifies that policy can set the startup pages to the homepage, when
2485 // the homepage is not the NTP.
2488 key::kRestoreOnStartup, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2489 base::Value::CreateIntegerValue(
2490 SessionStartupPref::kPrefValueHomePage),
2493 key::kHomepageIsNewTabPage, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2494 base::Value::CreateBooleanValue(false), NULL);
2496 key::kHomepageLocation, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2497 base::Value::CreateStringValue(kRestoredURLs[1]), NULL);
2498 provider_.UpdateChromePolicy(policies);
2500 expected_urls_.push_back(GURL(kRestoredURLs[1]));
2503 void HomepageIsNTP() {
2504 // Verifies that policy can set the startup pages to the homepage, when
2505 // the homepage is the NTP.
2508 key::kRestoreOnStartup, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2509 base::Value::CreateIntegerValue(
2510 SessionStartupPref::kPrefValueHomePage),
2513 key::kHomepageIsNewTabPage, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2514 base::Value::CreateBooleanValue(true), NULL);
2515 provider_.UpdateChromePolicy(policies);
2517 expected_urls_.push_back(GURL(chrome::kChromeUINewTabURL));
2521 // Verifies that policy can set the startup pages to a list of URLs.
2522 base::ListValue urls;
2523 for (size_t i = 0; i < arraysize(kRestoredURLs); ++i) {
2524 urls.Append(base::Value::CreateStringValue(kRestoredURLs[i]));
2525 expected_urls_.push_back(GURL(kRestoredURLs[i]));
2529 key::kRestoreOnStartup, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2530 base::Value::CreateIntegerValue(SessionStartupPref::kPrefValueURLs),
2533 key::kRestoreOnStartupURLs, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2534 urls.DeepCopy(), NULL);
2535 provider_.UpdateChromePolicy(policies);
2539 // Verifies that policy can set the startup page to the NTP.
2542 key::kRestoreOnStartup, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2543 base::Value::CreateIntegerValue(SessionStartupPref::kPrefValueNewTab),
2545 provider_.UpdateChromePolicy(policies);
2546 expected_urls_.push_back(GURL(chrome::kChromeUINewTabURL));
2550 // Verifies that policy can set the startup pages to the last session.
2553 key::kRestoreOnStartup, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2554 base::Value::CreateIntegerValue(SessionStartupPref::kPrefValueLast),
2556 provider_.UpdateChromePolicy(policies);
2557 // This should restore the tabs opened at PRE_RunTest below.
2558 for (size_t i = 0; i < arraysize(kRestoredURLs); ++i)
2559 expected_urls_.push_back(GURL(kRestoredURLs[i]));
2562 std::vector<GURL> expected_urls_;
2565 IN_PROC_BROWSER_TEST_P(RestoreOnStartupPolicyTest, PRE_RunTest) {
2566 // Open some tabs to verify if they are restored after the browser restarts.
2567 // Most policy settings override this, except kPrefValueLast which enforces
2569 ui_test_utils::NavigateToURL(browser(), GURL(kRestoredURLs[0]));
2570 for (size_t i = 1; i < arraysize(kRestoredURLs); ++i) {
2571 content::WindowedNotificationObserver observer(
2572 content::NOTIFICATION_LOAD_STOP,
2573 content::NotificationService::AllSources());
2574 chrome::AddSelectedTabWithURL(browser(), GURL(kRestoredURLs[i]),
2575 content::PAGE_TRANSITION_LINK);
2580 IN_PROC_BROWSER_TEST_P(RestoreOnStartupPolicyTest, RunTest) {
2581 #if defined(OS_WIN) && defined(USE_ASH)
2582 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
2583 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshBrowserTests))
2587 TabStripModel* model = browser()->tab_strip_model();
2588 int size = static_cast<int>(expected_urls_.size());
2589 EXPECT_EQ(size, model->count());
2590 for (int i = 0; i < size && i < model->count(); ++i) {
2591 EXPECT_EQ(expected_urls_[i], model->GetWebContentsAt(i)->GetURL());
2595 INSTANTIATE_TEST_CASE_P(
2596 RestoreOnStartupPolicyTestInstance,
2597 RestoreOnStartupPolicyTest,
2598 testing::Values(&RestoreOnStartupPolicyTest::HomepageIsNotNTP,
2599 &RestoreOnStartupPolicyTest::HomepageIsNTP,
2600 &RestoreOnStartupPolicyTest::ListOfURLs,
2601 &RestoreOnStartupPolicyTest::NTP,
2602 &RestoreOnStartupPolicyTest::Last));
2604 // Similar to PolicyTest but sets a couple of policies before the browser is
2606 class PolicyStatisticsCollectorTest : public PolicyTest {
2608 PolicyStatisticsCollectorTest() {}
2609 virtual ~PolicyStatisticsCollectorTest() {}
2611 virtual void SetUpInProcessBrowserTestFixture() OVERRIDE {
2612 PolicyTest::SetUpInProcessBrowserTestFixture();
2615 key::kShowHomeButton, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2616 base::Value::CreateBooleanValue(true), NULL);
2618 key::kBookmarkBarEnabled, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2619 base::Value::CreateBooleanValue(false), NULL);
2621 key::kHomepageLocation, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2622 base::Value::CreateStringValue("http://chromium.org"), NULL);
2623 provider_.UpdateChromePolicy(policies);
2627 IN_PROC_BROWSER_TEST_F(PolicyStatisticsCollectorTest, Startup) {
2628 // Verifies that policy usage histograms are collected at startup.
2630 // BrowserPolicyConnector::Init() has already been called. Make sure the
2631 // CompleteInitialization() task has executed as well.
2632 content::RunAllPendingInMessageLoop();
2634 GURL kAboutHistograms = GURL(std::string(content::kAboutScheme) +
2635 std::string(content::kStandardSchemeSeparator) +
2636 std::string(content::kChromeUIHistogramHost));
2637 ui_test_utils::NavigateToURL(browser(), kAboutHistograms);
2638 content::WebContents* contents =
2639 browser()->tab_strip_model()->GetActiveWebContents();
2641 ASSERT_TRUE(content::ExecuteScriptAndExtractString(
2643 "var nodes = document.querySelectorAll('body > pre');"
2645 "for (var i = 0; i < nodes.length; ++i) {"
2646 " var text = nodes[i].innerHTML;"
2647 " if (text.indexOf('Histogram: Enterprise.Policies') === 0) {"
2652 "domAutomationController.send(result);",
2654 ASSERT_FALSE(text.empty());
2655 const std::string kExpectedLabel =
2656 "Histogram: Enterprise.Policies recorded 3 samples";
2657 EXPECT_EQ(kExpectedLabel, text.substr(0, kExpectedLabel.size()));
2658 // HomepageLocation has policy ID 1.
2659 EXPECT_NE(std::string::npos, text.find("<br>1 ---"));
2660 // ShowHomeButton has policy ID 35.
2661 EXPECT_NE(std::string::npos, text.find("<br>35 ---"));
2662 // BookmarkBarEnabled has policy ID 82.
2663 EXPECT_NE(std::string::npos, text.find("<br>82 ---"));
2666 class MediaStreamDevicesControllerBrowserTest
2667 : public PolicyTest,
2668 public testing::WithParamInterface<bool> {
2670 MediaStreamDevicesControllerBrowserTest()
2671 : request_url_allowed_via_whitelist_(false) {
2672 policy_value_ = GetParam();
2674 virtual ~MediaStreamDevicesControllerBrowserTest() {}
2676 // Configure a given policy map.
2677 // The |policy_name| is the name of either the audio or video capture allow
2678 // policy and must never be NULL.
2679 // |whitelist_policy| and |allow_rule| are optional. If NULL, no whitelist
2680 // policy is set. If non-NULL, the request_url_ will be set to be non empty
2681 // and the whitelist policy is set to contain either the |allow_rule| (if
2682 // non-NULL) or an "allow all" wildcard.
2683 void ConfigurePolicyMap(PolicyMap* policies, const char* policy_name,
2684 const char* whitelist_policy,
2685 const char* allow_rule) {
2686 policies->Set(policy_name, POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
2687 base::Value::CreateBooleanValue(policy_value_), NULL);
2689 if (whitelist_policy) {
2690 // TODO(tommi): Remove the kiosk mode flag when the whitelist is visible
2691 // in the media exceptions UI.
2692 // See discussion here: https://codereview.chromium.org/15738004/
2693 CommandLine::ForCurrentProcess()->AppendSwitch(switches::kKioskMode);
2695 // Add an entry to the whitelist that allows the specified URL regardless
2696 // of the setting of kAudioCapturedAllowed.
2697 request_url_ = GURL("http://www.example.com/foo");
2698 base::ListValue* list = new base::ListValue();
2700 list->AppendString(allow_rule);
2701 request_url_allowed_via_whitelist_ = true;
2703 list->AppendString(ContentSettingsPattern::Wildcard().ToString());
2704 // We should ignore all wildcard entries in the whitelist, so even
2705 // though we've added an entry, it should be ignored and our expectation
2706 // is that the request has not been allowed via the whitelist.
2707 request_url_allowed_via_whitelist_ = false;
2709 policies->Set(whitelist_policy, POLICY_LEVEL_MANDATORY,
2710 POLICY_SCOPE_USER, list, NULL);
2714 void Accept(const content::MediaStreamDevices& devices,
2715 content::MediaStreamRequestResult result,
2716 scoped_ptr<content::MediaStreamUI> ui) {
2717 if (policy_value_ || request_url_allowed_via_whitelist_) {
2718 ASSERT_EQ(1U, devices.size());
2719 ASSERT_EQ("fake_dev", devices[0].id);
2721 ASSERT_EQ(0U, devices.size());
2725 void FinishAudioTest() {
2726 content::MediaStreamRequest request(0, 0, 0,
2727 request_url_.GetOrigin(), false,
2728 content::MEDIA_DEVICE_ACCESS,
2729 std::string(), std::string(),
2730 content::MEDIA_DEVICE_AUDIO_CAPTURE,
2731 content::MEDIA_NO_SERVICE);
2732 // TODO(raymes): Test MEDIA_DEVICE_OPEN (Pepper) which grants both webcam
2733 // and microphone permissions at the same time.
2734 MediaStreamDevicesController controller(
2735 browser()->tab_strip_model()->GetActiveWebContents(), request,
2736 base::Bind(&MediaStreamDevicesControllerBrowserTest::Accept, this));
2737 controller.Accept(false);
2739 base::MessageLoop::current()->QuitWhenIdle();
2742 void FinishVideoTest() {
2743 // TODO(raymes): Test MEDIA_DEVICE_OPEN (Pepper) which grants both webcam
2744 // and microphone permissions at the same time.
2745 content::MediaStreamRequest request(0, 0, 0,
2746 request_url_.GetOrigin(), false,
2747 content::MEDIA_DEVICE_ACCESS,
2750 content::MEDIA_NO_SERVICE,
2751 content::MEDIA_DEVICE_VIDEO_CAPTURE);
2752 MediaStreamDevicesController controller(
2753 browser()->tab_strip_model()->GetActiveWebContents(), request,
2754 base::Bind(&MediaStreamDevicesControllerBrowserTest::Accept, this));
2755 controller.Accept(false);
2757 base::MessageLoop::current()->QuitWhenIdle();
2761 bool request_url_allowed_via_whitelist_;
2763 static const char kExampleRequestPattern[];
2767 const char MediaStreamDevicesControllerBrowserTest::kExampleRequestPattern[] =
2768 "http://[*.]example.com/";
2770 IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerBrowserTest,
2771 AudioCaptureAllowed) {
2772 content::MediaStreamDevices audio_devices;
2773 content::MediaStreamDevice fake_audio_device(
2774 content::MEDIA_DEVICE_AUDIO_CAPTURE, "fake_dev", "Fake Audio Device");
2775 audio_devices.push_back(fake_audio_device);
2778 ConfigurePolicyMap(&policies, key::kAudioCaptureAllowed, NULL, NULL);
2779 UpdateProviderPolicy(policies);
2781 content::BrowserThread::PostTaskAndReply(
2782 content::BrowserThread::IO, FROM_HERE,
2783 base::Bind(&MediaCaptureDevicesDispatcher::SetTestAudioCaptureDevices,
2784 base::Unretained(MediaCaptureDevicesDispatcher::GetInstance()),
2786 base::Bind(&MediaStreamDevicesControllerBrowserTest::FinishAudioTest,
2789 base::MessageLoop::current()->Run();
2792 IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerBrowserTest,
2793 AudioCaptureAllowedUrls) {
2794 content::MediaStreamDevices audio_devices;
2795 content::MediaStreamDevice fake_audio_device(
2796 content::MEDIA_DEVICE_AUDIO_CAPTURE, "fake_dev", "Fake Audio Device");
2797 audio_devices.push_back(fake_audio_device);
2799 const char* allow_pattern[] = {
2800 kExampleRequestPattern,
2801 // This will set an allow-all policy whitelist. Since we do not allow
2802 // setting an allow-all entry in the whitelist, this entry should be ignored
2803 // and therefore the request should be denied.
2807 for (size_t i = 0; i < arraysize(allow_pattern); ++i) {
2809 ConfigurePolicyMap(&policies, key::kAudioCaptureAllowed,
2810 key::kAudioCaptureAllowedUrls, allow_pattern[i]);
2811 UpdateProviderPolicy(policies);
2813 content::BrowserThread::PostTaskAndReply(
2814 content::BrowserThread::IO, FROM_HERE,
2816 &MediaCaptureDevicesDispatcher::SetTestAudioCaptureDevices,
2817 base::Unretained(MediaCaptureDevicesDispatcher::GetInstance()),
2820 &MediaStreamDevicesControllerBrowserTest::FinishAudioTest,
2823 base::MessageLoop::current()->Run();
2827 IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerBrowserTest,
2828 VideoCaptureAllowed) {
2829 content::MediaStreamDevices video_devices;
2830 content::MediaStreamDevice fake_video_device(
2831 content::MEDIA_DEVICE_VIDEO_CAPTURE, "fake_dev", "Fake Video Device");
2832 video_devices.push_back(fake_video_device);
2835 ConfigurePolicyMap(&policies, key::kVideoCaptureAllowed, NULL, NULL);
2836 UpdateProviderPolicy(policies);
2838 content::BrowserThread::PostTaskAndReply(
2839 content::BrowserThread::IO, FROM_HERE,
2840 base::Bind(&MediaCaptureDevicesDispatcher::SetTestVideoCaptureDevices,
2841 base::Unretained(MediaCaptureDevicesDispatcher::GetInstance()),
2843 base::Bind(&MediaStreamDevicesControllerBrowserTest::FinishVideoTest,
2846 base::MessageLoop::current()->Run();
2849 IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerBrowserTest,
2850 VideoCaptureAllowedUrls) {
2851 content::MediaStreamDevices video_devices;
2852 content::MediaStreamDevice fake_video_device(
2853 content::MEDIA_DEVICE_VIDEO_CAPTURE, "fake_dev", "Fake Video Device");
2854 video_devices.push_back(fake_video_device);
2856 const char* allow_pattern[] = {
2857 kExampleRequestPattern,
2858 // This will set an allow-all policy whitelist. Since we do not allow
2859 // setting an allow-all entry in the whitelist, this entry should be ignored
2860 // and therefore the request should be denied.
2864 for (size_t i = 0; i < arraysize(allow_pattern); ++i) {
2866 ConfigurePolicyMap(&policies, key::kVideoCaptureAllowed,
2867 key::kVideoCaptureAllowedUrls, allow_pattern[i]);
2868 UpdateProviderPolicy(policies);
2870 content::BrowserThread::PostTaskAndReply(
2871 content::BrowserThread::IO, FROM_HERE,
2872 base::Bind(&MediaCaptureDevicesDispatcher::SetTestVideoCaptureDevices,
2873 base::Unretained(MediaCaptureDevicesDispatcher::GetInstance()),
2876 &MediaStreamDevicesControllerBrowserTest::FinishVideoTest,
2879 base::MessageLoop::current()->Run();
2883 INSTANTIATE_TEST_CASE_P(MediaStreamDevicesControllerBrowserTestInstance,
2884 MediaStreamDevicesControllerBrowserTest,
2887 #if !defined(OS_CHROMEOS)
2888 // Similar to PolicyTest but sets the proper policy before the browser is
2890 class PolicyVariationsServiceTest : public PolicyTest {
2892 virtual void SetUpInProcessBrowserTestFixture() OVERRIDE {
2893 PolicyTest::SetUpInProcessBrowserTestFixture();
2896 key::kVariationsRestrictParameter,
2897 POLICY_LEVEL_MANDATORY,
2899 base::Value::CreateStringValue("restricted"),
2901 provider_.UpdateChromePolicy(policies);
2905 IN_PROC_BROWSER_TEST_F(PolicyVariationsServiceTest, VariationsURLIsValid) {
2906 const std::string default_variations_url =
2907 chrome_variations::VariationsService::
2908 GetDefaultVariationsServerURLForTesting();
2911 chrome_variations::VariationsService::GetVariationsServerURL(
2912 g_browser_process->local_state());
2913 EXPECT_TRUE(StartsWithASCII(url.spec(), default_variations_url, true));
2915 EXPECT_TRUE(net::GetValueForKeyInQuery(url, "restrict", &value));
2916 EXPECT_EQ("restricted", value);
2919 IN_PROC_BROWSER_TEST_F(PolicyTest, NativeMessagingBlacklistSelective) {
2920 base::ListValue blacklist;
2921 blacklist.Append(base::Value::CreateStringValue("host.name"));
2923 policies.Set(key::kNativeMessagingBlacklist, POLICY_LEVEL_MANDATORY,
2924 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
2925 UpdateProviderPolicy(policies);
2927 PrefService* prefs = browser()->profile()->GetPrefs();
2928 EXPECT_FALSE(extensions::NativeMessageProcessHost::IsHostAllowed(
2929 prefs, "host.name"));
2930 EXPECT_TRUE(extensions::NativeMessageProcessHost::IsHostAllowed(
2931 prefs, "other.host.name"));
2934 IN_PROC_BROWSER_TEST_F(PolicyTest, NativeMessagingBlacklistWildcard) {
2935 base::ListValue blacklist;
2936 blacklist.Append(base::Value::CreateStringValue("*"));
2938 policies.Set(key::kNativeMessagingBlacklist, POLICY_LEVEL_MANDATORY,
2939 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
2940 UpdateProviderPolicy(policies);
2942 PrefService* prefs = browser()->profile()->GetPrefs();
2943 EXPECT_FALSE(extensions::NativeMessageProcessHost::IsHostAllowed(
2944 prefs, "host.name"));
2945 EXPECT_FALSE(extensions::NativeMessageProcessHost::IsHostAllowed(
2946 prefs, "other.host.name"));
2949 IN_PROC_BROWSER_TEST_F(PolicyTest, NativeMessagingWhitelist) {
2950 base::ListValue blacklist;
2951 blacklist.Append(base::Value::CreateStringValue("*"));
2952 base::ListValue whitelist;
2953 whitelist.Append(base::Value::CreateStringValue("host.name"));
2955 policies.Set(key::kNativeMessagingBlacklist, POLICY_LEVEL_MANDATORY,
2956 POLICY_SCOPE_USER, blacklist.DeepCopy(), NULL);
2957 policies.Set(key::kNativeMessagingWhitelist, POLICY_LEVEL_MANDATORY,
2958 POLICY_SCOPE_USER, whitelist.DeepCopy(), NULL);
2959 UpdateProviderPolicy(policies);
2961 PrefService* prefs = browser()->profile()->GetPrefs();
2962 EXPECT_TRUE(extensions::NativeMessageProcessHost::IsHostAllowed(
2963 prefs, "host.name"));
2964 EXPECT_FALSE(extensions::NativeMessageProcessHost::IsHostAllowed(
2965 prefs, "other.host.name"));
2968 #endif // !defined(CHROME_OS)
2970 } // namespace policy