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/files/file_enumerator.h"
14 #include "base/files/file_path.h"
15 #include "base/files/file_util.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/threading/sequenced_worker_pool.h"
27 #include "base/time/time.h"
28 #include "base/values.h"
29 #include "chrome/app/chrome_command_ids.h"
30 #include "chrome/browser/autocomplete/autocomplete_controller.h"
31 #include "chrome/browser/background/background_contents_service.h"
32 #include "chrome/browser/browser_process.h"
33 #include "chrome/browser/chrome_notification_types.h"
34 #include "chrome/browser/content_settings/tab_specific_content_settings.h"
35 #include "chrome/browser/devtools/devtools_window_testing.h"
36 #include "chrome/browser/download/download_prefs.h"
37 #include "chrome/browser/extensions/api/messaging/message_service.h"
38 #include "chrome/browser/extensions/crx_installer.h"
39 #include "chrome/browser/extensions/extension_management_constants.h"
40 #include "chrome/browser/extensions/extension_service.h"
41 #include "chrome/browser/extensions/unpacked_installer.h"
42 #include "chrome/browser/extensions/updater/extension_cache_fake.h"
43 #include "chrome/browser/extensions/updater/extension_updater.h"
44 #include "chrome/browser/infobars/infobar_service.h"
45 #include "chrome/browser/media/media_capture_devices_dispatcher.h"
46 #include "chrome/browser/media/media_stream_devices_controller.h"
47 #include "chrome/browser/metrics/variations/variations_service.h"
48 #include "chrome/browser/net/prediction_options.h"
49 #include "chrome/browser/net/ssl_config_service_manager.h"
50 #include "chrome/browser/net/url_request_mock_util.h"
51 #include "chrome/browser/plugins/plugin_prefs.h"
52 #include "chrome/browser/policy/cloud/test_request_interceptor.h"
53 #include "chrome/browser/policy/profile_policy_connector.h"
54 #include "chrome/browser/policy/profile_policy_connector_factory.h"
55 #include "chrome/browser/prefs/session_startup_pref.h"
56 #include "chrome/browser/profiles/profile.h"
57 #include "chrome/browser/search/instant_service.h"
58 #include "chrome/browser/search/instant_service_factory.h"
59 #include "chrome/browser/search/search.h"
60 #include "chrome/browser/search_engines/template_url_service_factory.h"
61 #include "chrome/browser/translate/chrome_translate_client.h"
62 #include "chrome/browser/translate/cld_data_harness.h"
63 #include "chrome/browser/translate/translate_service.h"
64 #include "chrome/browser/ui/bookmarks/bookmark_bar.h"
65 #include "chrome/browser/ui/browser.h"
66 #include "chrome/browser/ui/browser_commands.h"
67 #include "chrome/browser/ui/browser_list.h"
68 #include "chrome/browser/ui/browser_tabstrip.h"
69 #include "chrome/browser/ui/browser_window.h"
70 #include "chrome/browser/ui/host_desktop.h"
71 #include "chrome/browser/ui/location_bar/location_bar.h"
72 #include "chrome/browser/ui/omnibox/omnibox_edit_model.h"
73 #include "chrome/browser/ui/omnibox/omnibox_view.h"
74 #include "chrome/browser/ui/tabs/tab_strip_model.h"
75 #include "chrome/common/chrome_paths.h"
76 #include "chrome/common/chrome_switches.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/grit/generated_resources.h"
81 #include "chrome/test/base/in_process_browser_test.h"
82 #include "chrome/test/base/test_switches.h"
83 #include "chrome/test/base/ui_test_utils.h"
84 #include "components/content_settings/core/common/content_settings.h"
85 #include "components/content_settings/core/common/content_settings_pattern.h"
86 #include "components/infobars/core/infobar.h"
87 #include "components/policy/core/browser/browser_policy_connector.h"
88 #include "components/policy/core/common/external_data_fetcher.h"
89 #include "components/policy/core/common/mock_configuration_policy_provider.h"
90 #include "components/policy/core/common/policy_map.h"
91 #include "components/policy/core/common/policy_pref_names.h"
92 #include "components/policy/core/common/policy_service.h"
93 #include "components/policy/core/common/policy_service_impl.h"
94 #include "components/search_engines/template_url.h"
95 #include "components/search_engines/template_url_service.h"
96 #include "components/translate/core/browser/language_state.h"
97 #include "components/translate/core/browser/translate_infobar_delegate.h"
98 #include "content/public/browser/browser_child_process_host_iterator.h"
99 #include "content/public/browser/browser_context.h"
100 #include "content/public/browser/browser_thread.h"
101 #include "content/public/browser/child_process_data.h"
102 #include "content/public/browser/download_item.h"
103 #include "content/public/browser/download_manager.h"
104 #include "content/public/browser/gpu_data_manager.h"
105 #include "content/public/browser/notification_details.h"
106 #include "content/public/browser/notification_observer.h"
107 #include "content/public/browser/notification_registrar.h"
108 #include "content/public/browser/notification_service.h"
109 #include "content/public/browser/notification_source.h"
110 #include "content/public/browser/notification_types.h"
111 #include "content/public/browser/plugin_service.h"
112 #include "content/public/browser/render_process_host.h"
113 #include "content/public/browser/render_view_host.h"
114 #include "content/public/browser/web_contents.h"
115 #include "content/public/common/content_constants.h"
116 #include "content/public/common/content_paths.h"
117 #include "content/public/common/process_type.h"
118 #include "content/public/common/result_codes.h"
119 #include "content/public/common/url_constants.h"
120 #include "content/public/common/webplugininfo.h"
121 #include "content/public/test/browser_test_utils.h"
122 #include "content/public/test/download_test_observer.h"
123 #include "content/public/test/mock_notification_observer.h"
124 #include "content/public/test/test_navigation_observer.h"
125 #include "content/public/test/test_utils.h"
126 #include "extensions/browser/extension_host.h"
127 #include "extensions/browser/extension_system.h"
128 #include "extensions/browser/process_manager.h"
129 #include "extensions/browser/uninstall_reason.h"
130 #include "extensions/common/constants.h"
131 #include "extensions/common/extension.h"
132 #include "extensions/common/extension_set.h"
133 #include "net/base/net_errors.h"
134 #include "net/base/net_util.h"
135 #include "net/base/url_util.h"
136 #include "net/http/http_stream_factory.h"
137 #include "net/ssl/ssl_config.h"
138 #include "net/ssl/ssl_config_service.h"
139 #include "net/test/url_request/url_request_failed_job.h"
140 #include "net/test/url_request/url_request_mock_http_job.h"
141 #include "net/url_request/url_request.h"
142 #include "net/url_request/url_request_filter.h"
143 #include "policy/policy_constants.h"
144 #include "testing/gmock/include/gmock/gmock.h"
145 #include "testing/gtest/include/gtest/gtest.h"
146 #include "third_party/WebKit/public/web/WebInputEvent.h"
147 #include "ui/base/l10n/l10n_util.h"
148 #include "ui/base/page_transition_types.h"
149 #include "ui/base/resource/resource_bundle.h"
150 #include "url/gurl.h"
152 #if defined(OS_CHROMEOS)
153 #include "ash/accelerators/accelerator_controller.h"
154 #include "ash/accelerators/accelerator_table.h"
155 #include "ash/magnifier/magnifier_constants.h"
156 #include "ash/shell.h"
157 #include "chrome/browser/chromeos/accessibility/accessibility_manager.h"
158 #include "chrome/browser/chromeos/accessibility/magnification_manager.h"
159 #include "chrome/browser/profiles/profile_manager.h"
160 #include "chrome/browser/ui/ash/screenshot_taker.h"
161 #include "chromeos/audio/cras_audio_handler.h"
162 #include "ui/keyboard/keyboard_util.h"
165 #if !defined(OS_MACOSX)
166 #include "base/basictypes.h"
167 #include "base/compiler_specific.h"
168 #include "chrome/browser/ui/extensions/application_launch.h"
169 #include "extensions/browser/app_window/app_window.h"
170 #include "extensions/browser/app_window/app_window_registry.h"
171 #include "extensions/browser/app_window/native_app_window.h"
172 #include "ui/base/window_open_disposition.h"
175 using content::BrowserThread
;
176 using net::URLRequestMockHTTPJob
;
178 using testing::Return
;
185 #if defined(OS_CHROMEOS)
186 const int kOneHourInMs
= 60 * 60 * 1000;
187 const int kThreeHoursInMs
= 180 * 60 * 1000;
190 const char kURL
[] = "http://example.com";
191 const char kCookieValue
[] = "converted=true";
192 // Assigned to Philip J. Fry to fix eventually.
193 const char kCookieOptions
[] = ";expires=Wed Jan 01 3000 00:00:00 GMT";
195 const base::FilePath::CharType kTestExtensionsDir
[] =
196 FILE_PATH_LITERAL("extensions");
197 const base::FilePath::CharType kGoodCrxName
[] = FILE_PATH_LITERAL("good.crx");
198 const base::FilePath::CharType kAdBlockCrxName
[] =
199 FILE_PATH_LITERAL("adblock.crx");
200 const base::FilePath::CharType kHostedAppCrxName
[] =
201 FILE_PATH_LITERAL("hosted_app.crx");
203 const char kGoodCrxId
[] = "ldnnhddmnhbkjipkidpdiheffobcpfmf";
204 const char kAdBlockCrxId
[] = "dojnnbeimaimaojcialkkgajdnefpgcn";
205 const char kHostedAppCrxId
[] = "kbmnembihfiondgfjekmnmcbddelicoi";
207 const base::FilePath::CharType kGood2CrxManifestName
[] =
208 FILE_PATH_LITERAL("good2_update_manifest.xml");
209 const base::FilePath::CharType kGoodV1CrxManifestName
[] =
210 FILE_PATH_LITERAL("good_v1_update_manifest.xml");
211 const base::FilePath::CharType kGoodUnpackedExt
[] =
212 FILE_PATH_LITERAL("good_unpacked");
213 const base::FilePath::CharType kAppUnpackedExt
[] =
214 FILE_PATH_LITERAL("app");
216 #if !defined(OS_MACOSX)
217 const base::FilePath::CharType kUnpackedFullscreenAppName
[] =
218 FILE_PATH_LITERAL("fullscreen_app");
219 #endif // !defined(OS_MACOSX)
221 // Filters requests to the hosts in |urls| and redirects them to the test data
222 // dir through URLRequestMockHTTPJobs.
223 void RedirectHostsToTestData(const char* const urls
[], size_t size
) {
224 // Map the given hosts to the test data dir.
225 net::URLRequestFilter
* filter
= net::URLRequestFilter::GetInstance();
226 base::FilePath base_path
;
227 PathService::Get(chrome::DIR_TEST_DATA
, &base_path
);
228 for (size_t i
= 0; i
< size
; ++i
) {
229 const GURL
url(urls
[i
]);
230 EXPECT_TRUE(url
.is_valid());
231 filter
->AddUrlInterceptor(url
,
232 URLRequestMockHTTPJob::CreateInterceptor(
233 base_path
, BrowserThread::GetBlockingPool()));
237 // Remove filters for requests to the hosts in |urls|.
238 void UndoRedirectHostsToTestData(const char* const urls
[], size_t size
) {
239 // Map the given hosts to the test data dir.
240 net::URLRequestFilter
* filter
= net::URLRequestFilter::GetInstance();
241 for (size_t i
= 0; i
< size
; ++i
) {
242 const GURL
url(urls
[i
]);
243 EXPECT_TRUE(url
.is_valid());
244 filter
->RemoveUrlHandler(url
);
248 // Fails requests using ERR_CONNECTION_RESET.
249 net::URLRequestJob
* FailedJobFactory(
250 net::URLRequest
* request
,
251 net::NetworkDelegate
* network_delegate
,
252 const std::string
& scheme
) {
253 return new net::URLRequestFailedJob(
254 request
, network_delegate
, net::ERR_CONNECTION_RESET
);
257 // While |MakeRequestFail| is in scope URLRequests to |host| will fail.
258 class MakeRequestFail
{
260 // Sets up the filter on IO thread such that requests to |host| fail.
261 explicit MakeRequestFail(const std::string
& host
) : host_(host
) {
262 BrowserThread::PostTaskAndReply(
263 BrowserThread::IO
, FROM_HERE
,
264 base::Bind(MakeRequestFailOnIO
, host_
),
265 base::MessageLoop::QuitClosure());
266 content::RunMessageLoop();
269 BrowserThread::PostTaskAndReply(
270 BrowserThread::IO
, FROM_HERE
,
271 base::Bind(UndoMakeRequestFailOnIO
, host_
),
272 base::MessageLoop::QuitClosure());
273 content::RunMessageLoop();
277 // Filters requests to the |host| such that they fail. Run on IO thread.
278 static void MakeRequestFailOnIO(const std::string
& host
) {
279 net::URLRequestFilter
* filter
= net::URLRequestFilter::GetInstance();
280 filter
->AddHostnameHandler("http", host
, &FailedJobFactory
);
281 filter
->AddHostnameHandler("https", host
, &FailedJobFactory
);
284 // Remove filters for requests to the |host|. Run on IO thread.
285 static void UndoMakeRequestFailOnIO(const std::string
& host
) {
286 net::URLRequestFilter
* filter
= net::URLRequestFilter::GetInstance();
287 filter
->RemoveHostnameHandler("http", host
);
288 filter
->RemoveHostnameHandler("https", host
);
291 const std::string host_
;
294 // Verifies that the given url |spec| can be opened. This assumes that |spec|
295 // points at empty.html in the test data dir.
296 void CheckCanOpenURL(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 spec16
= base::UTF8ToUTF16(url
.spec());
303 base::string16 title
=
304 l10n_util::GetStringFUTF16(IDS_ERRORPAGES_TITLE_BLOCKED
, spec16
);
305 EXPECT_NE(title
, contents
->GetTitle());
308 // Verifies that access to the given url |spec| is blocked.
309 void CheckURLIsBlocked(Browser
* browser
, const char* spec
) {
311 ui_test_utils::NavigateToURL(browser
, url
);
312 content::WebContents
* contents
=
313 browser
->tab_strip_model()->GetActiveWebContents();
314 EXPECT_EQ(url
, contents
->GetURL());
315 base::string16 spec16
= base::UTF8ToUTF16(url
.spec());
316 base::string16 title
=
317 l10n_util::GetStringFUTF16(IDS_ERRORPAGES_TITLE_BLOCKED
, spec16
);
318 EXPECT_EQ(title
, contents
->GetTitle());
320 // Verify that the expected error page is being displayed.
322 EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
324 "var textContent = document.body.textContent;"
325 "var hasError = textContent.indexOf('ERR_BLOCKED_BY_ADMINISTRATOR') >= 0;"
326 "domAutomationController.send(hasError);",
331 // Downloads a file named |file| and expects it to be saved to |dir|, which
333 void DownloadAndVerifyFile(
334 Browser
* browser
, const base::FilePath
& dir
, const base::FilePath
& file
) {
335 content::DownloadManager
* download_manager
=
336 content::BrowserContext::GetDownloadManager(browser
->profile());
337 content::DownloadTestObserverTerminal
observer(
339 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_FAIL
);
340 GURL
url(URLRequestMockHTTPJob::GetMockUrl(file
));
341 base::FilePath downloaded
= dir
.Append(file
);
342 EXPECT_FALSE(base::PathExists(downloaded
));
343 ui_test_utils::NavigateToURLWithDisposition(
344 browser
, url
, CURRENT_TAB
,
345 ui_test_utils::BROWSER_TEST_WAIT_FOR_NAVIGATION
);
346 observer
.WaitForFinished();
348 1u, observer
.NumDownloadsSeenInState(content::DownloadItem::COMPLETE
));
349 EXPECT_TRUE(base::PathExists(downloaded
));
350 base::FileEnumerator
enumerator(dir
, false, base::FileEnumerator::FILES
);
351 EXPECT_EQ(file
, enumerator
.Next().BaseName());
352 EXPECT_EQ(base::FilePath(), enumerator
.Next());
355 #if defined(OS_CHROMEOS)
356 int CountScreenshots() {
357 DownloadPrefs
* download_prefs
= DownloadPrefs::FromBrowserContext(
358 ProfileManager::GetActiveUserProfile());
359 base::FileEnumerator
enumerator(download_prefs
->DownloadPath(),
360 false, base::FileEnumerator::FILES
,
363 while (!enumerator
.Next().empty())
369 // Checks if WebGL is enabled in the given WebContents.
370 bool IsWebGLEnabled(content::WebContents
* contents
) {
372 EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
374 "var canvas = document.createElement('canvas');"
375 "var context = canvas.getContext('webgl');"
376 "domAutomationController.send(context != null);",
381 bool IsJavascriptEnabled(content::WebContents
* contents
) {
382 scoped_ptr
<base::Value
> value
= content::ExecuteScriptAndGetValue(
383 contents
->GetMainFrame(), "123");
385 if (!value
->GetAsInteger(&result
))
386 EXPECT_EQ(base::Value::TYPE_NULL
, value
->GetType());
387 return result
== 123;
390 bool IsNetworkPredictionEnabled(PrefService
* prefs
) {
391 return chrome_browser_net::CanPrefetchAndPrerenderUI(prefs
);
394 void CopyPluginListAndQuit(std::vector
<content::WebPluginInfo
>* out
,
395 const std::vector
<content::WebPluginInfo
>& in
) {
397 base::MessageLoop::current()->QuitWhenIdle();
401 void CopyValueAndQuit(T
* out
, T in
) {
403 base::MessageLoop::current()->QuitWhenIdle();
406 void GetPluginList(std::vector
<content::WebPluginInfo
>* plugins
) {
407 content::PluginService
* service
= content::PluginService::GetInstance();
408 service
->GetPlugins(base::Bind(CopyPluginListAndQuit
, plugins
));
409 content::RunMessageLoop();
412 const content::WebPluginInfo
* GetFlashPlugin(
413 const std::vector
<content::WebPluginInfo
>& plugins
) {
414 const content::WebPluginInfo
* flash
= NULL
;
415 for (size_t i
= 0; i
< plugins
.size(); ++i
) {
416 if (plugins
[i
].name
== base::ASCIIToUTF16(content::kFlashPluginName
)) {
421 #if defined(OFFICIAL_BUILD)
422 // Official builds bundle Flash.
426 LOG(INFO
) << "Test skipped because the Flash plugin couldn't be found.";
431 bool SetPluginEnabled(PluginPrefs
* plugin_prefs
,
432 const content::WebPluginInfo
* plugin
,
435 plugin_prefs
->EnablePlugin(enabled
, plugin
->path
,
436 base::Bind(CopyValueAndQuit
<bool>, &ok
));
437 content::RunMessageLoop();
441 int CountPluginsOnIOThread() {
443 for (content::BrowserChildProcessHostIterator iter
; !iter
.Done(); ++iter
) {
444 if (iter
.GetData().process_type
== content::PROCESS_TYPE_PLUGIN
||
445 iter
.GetData().process_type
== content::PROCESS_TYPE_PPAPI_PLUGIN
) {
454 BrowserThread::PostTaskAndReplyWithResult(
455 BrowserThread::IO
, FROM_HERE
,
456 base::Bind(CountPluginsOnIOThread
),
457 base::Bind(CopyValueAndQuit
<int>, &count
));
458 content::RunMessageLoop();
463 void FlushBlacklistPolicy() {
464 // Updates of the URLBlacklist are done on IO, after building the blacklist
465 // on the blocking pool, which is initiated from IO.
466 content::RunAllPendingInMessageLoop(BrowserThread::IO
);
467 BrowserThread::GetBlockingPool()->FlushForTesting();
468 content::RunAllPendingInMessageLoop(BrowserThread::IO
);
471 bool ContainsVisibleElement(content::WebContents
* contents
,
472 const std::string
& id
) {
474 EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
476 "var elem = document.getElementById('" + id
+ "');"
477 "domAutomationController.send(!!elem && !elem.hidden);",
482 #if defined(OS_CHROMEOS)
483 class TestAudioObserver
: public chromeos::CrasAudioHandler::AudioObserver
{
485 TestAudioObserver() : output_mute_changed_count_(0) {
488 int output_mute_changed_count() const {
489 return output_mute_changed_count_
;
492 virtual ~TestAudioObserver() {}
495 // chromeos::CrasAudioHandler::AudioObserver overrides.
496 virtual void OnOutputMuteChanged() override
{
497 ++output_mute_changed_count_
;
501 int output_mute_changed_count_
;
503 DISALLOW_COPY_AND_ASSIGN(TestAudioObserver
);
507 // This class waits until either a load stops or the WebContents is destroyed.
508 class WebContentsLoadedOrDestroyedWatcher
509 : public content::WebContentsObserver
{
511 explicit WebContentsLoadedOrDestroyedWatcher(
512 content::WebContents
* web_contents
);
513 virtual ~WebContentsLoadedOrDestroyedWatcher();
515 // Waits until the WebContents's load is done or until it is destroyed.
518 // Overridden WebContentsObserver methods.
519 virtual void WebContentsDestroyed() override
;
520 virtual void DidStopLoading(
521 content::RenderViewHost
* render_view_host
) override
;
524 scoped_refptr
<content::MessageLoopRunner
> message_loop_runner_
;
526 DISALLOW_COPY_AND_ASSIGN(WebContentsLoadedOrDestroyedWatcher
);
529 WebContentsLoadedOrDestroyedWatcher::WebContentsLoadedOrDestroyedWatcher(
530 content::WebContents
* web_contents
)
531 : content::WebContentsObserver(web_contents
),
532 message_loop_runner_(new content::MessageLoopRunner
) {
535 WebContentsLoadedOrDestroyedWatcher::~WebContentsLoadedOrDestroyedWatcher() {}
537 void WebContentsLoadedOrDestroyedWatcher::Wait() {
538 message_loop_runner_
->Run();
541 void WebContentsLoadedOrDestroyedWatcher::WebContentsDestroyed() {
542 message_loop_runner_
->Quit();
545 void WebContentsLoadedOrDestroyedWatcher::DidStopLoading(
546 content::RenderViewHost
* render_view_host
) {
547 message_loop_runner_
->Quit();
550 #if !defined(OS_MACOSX)
552 // Observer used to wait for the creation of a new app window.
553 class TestAddAppWindowObserver
554 : public extensions::AppWindowRegistry::Observer
{
556 explicit TestAddAppWindowObserver(extensions::AppWindowRegistry
* registry
);
557 virtual ~TestAddAppWindowObserver();
559 // extensions::AppWindowRegistry::Observer:
560 virtual void OnAppWindowAdded(extensions::AppWindow
* app_window
) override
;
562 extensions::AppWindow
* WaitForAppWindow();
565 extensions::AppWindowRegistry
* registry_
; // Not owned.
566 extensions::AppWindow
* window_
; // Not owned.
567 base::RunLoop run_loop_
;
569 DISALLOW_COPY_AND_ASSIGN(TestAddAppWindowObserver
);
572 TestAddAppWindowObserver::TestAddAppWindowObserver(
573 extensions::AppWindowRegistry
* registry
)
574 : registry_(registry
), window_(NULL
) {
575 registry_
->AddObserver(this);
578 TestAddAppWindowObserver::~TestAddAppWindowObserver() {
579 registry_
->RemoveObserver(this);
582 void TestAddAppWindowObserver::OnAppWindowAdded(
583 extensions::AppWindow
* app_window
) {
584 window_
= app_window
;
588 extensions::AppWindow
* TestAddAppWindowObserver::WaitForAppWindow() {
597 class PolicyTest
: public InProcessBrowserTest
{
600 virtual ~PolicyTest() {}
602 virtual void SetUp() override
{
603 test_extension_cache_
.reset(new extensions::ExtensionCacheFake());
604 InProcessBrowserTest::SetUp();
607 virtual void SetUpInProcessBrowserTestFixture() override
{
608 CommandLine::ForCurrentProcess()->AppendSwitch("noerrdialogs");
609 EXPECT_CALL(provider_
, IsInitializationComplete(_
))
610 .WillRepeatedly(Return(true));
611 BrowserPolicyConnector::SetPolicyProviderForTesting(&provider_
);
614 virtual void SetUpOnMainThread() override
{
615 BrowserThread::PostTask(
616 BrowserThread::IO
, FROM_HERE
,
617 base::Bind(chrome_browser_net::SetUrlRequestMocksEnabled
, true));
618 if (extension_service()->updater()) {
619 extension_service()->updater()->SetExtensionCacheForTesting(
620 test_extension_cache_
.get());
624 // Makes URLRequestMockHTTPJobs serve data from content::DIR_TEST_DATA
625 // instead of chrome::DIR_TEST_DATA.
626 void ServeContentTestData() {
627 base::FilePath root_http
;
628 PathService::Get(content::DIR_TEST_DATA
, &root_http
);
629 BrowserThread::PostTaskAndReply(
632 base::Bind(URLRequestMockHTTPJob::AddUrlHandler
,
634 make_scoped_refptr(BrowserThread::GetBlockingPool())),
635 base::MessageLoop::current()->QuitWhenIdleClosure());
636 content::RunMessageLoop();
639 void SetScreenshotPolicy(bool enabled
) {
641 policies
.Set(key::kDisableScreenshots
,
642 POLICY_LEVEL_MANDATORY
,
644 new base::FundamentalValue(!enabled
),
646 UpdateProviderPolicy(policies
);
649 #if defined(OS_CHROMEOS)
650 class QuitMessageLoopAfterScreenshot
: public ScreenshotTakerObserver
{
652 virtual void OnScreenshotCompleted(
653 ScreenshotTakerObserver::Result screenshot_result
,
654 const base::FilePath
& screenshot_path
) override
{
655 BrowserThread::PostTaskAndReply(BrowserThread::IO
,
657 base::Bind(base::DoNothing
),
658 base::MessageLoop::QuitClosure());
661 virtual ~QuitMessageLoopAfterScreenshot() {}
664 void TestScreenshotFile(bool enabled
) {
665 // AddObserver is an ash-specific method, so just replace the screenshot
666 // taker with one we've created here.
667 scoped_ptr
<ScreenshotTaker
> screenshot_taker(new ScreenshotTaker
);
668 // ScreenshotTaker doesn't own this observer, so the observer's lifetime
669 // is tied to the test instead.
670 screenshot_taker
->AddObserver(&observer_
);
671 ash::Shell::GetInstance()->accelerator_controller()->SetScreenshotDelegate(
672 screenshot_taker
.Pass());
674 SetScreenshotPolicy(enabled
);
675 ash::Shell::GetInstance()->accelerator_controller()->PerformAction(
676 ash::TAKE_SCREENSHOT
, ui::Accelerator());
678 content::RunMessageLoop();
682 ExtensionService
* extension_service() {
683 extensions::ExtensionSystem
* system
=
684 extensions::ExtensionSystem::Get(browser()->profile());
685 return system
->extension_service();
688 const extensions::Extension
* InstallExtension(
689 const base::FilePath::StringType
& name
) {
690 base::FilePath
extension_path(ui_test_utils::GetTestFilePath(
691 base::FilePath(kTestExtensionsDir
), base::FilePath(name
)));
692 scoped_refptr
<extensions::CrxInstaller
> installer
=
693 extensions::CrxInstaller::CreateSilent(extension_service());
694 installer
->set_allow_silent_install(true);
695 installer
->set_install_cause(extension_misc::INSTALL_CAUSE_UPDATE
);
696 installer
->set_creation_flags(extensions::Extension::FROM_WEBSTORE
);
698 content::WindowedNotificationObserver
observer(
699 extensions::NOTIFICATION_CRX_INSTALLER_DONE
,
700 content::NotificationService::AllSources());
701 installer
->InstallCrx(extension_path
);
703 content::Details
<const extensions::Extension
> details
= observer
.details();
704 return details
.ptr();
707 const extensions::Extension
* LoadUnpackedExtension(
708 const base::FilePath::StringType
& name
, bool expect_success
) {
709 base::FilePath
extension_path(ui_test_utils::GetTestFilePath(
710 base::FilePath(kTestExtensionsDir
), base::FilePath(name
)));
711 scoped_refptr
<extensions::UnpackedInstaller
> installer
=
712 extensions::UnpackedInstaller::Create(extension_service());
713 content::WindowedNotificationObserver
observer(
714 expect_success
? extensions::NOTIFICATION_EXTENSION_LOADED_DEPRECATED
715 : extensions::NOTIFICATION_EXTENSION_LOAD_ERROR
,
716 content::NotificationService::AllSources());
717 installer
->Load(extension_path
);
720 const extensions::ExtensionSet
* extensions
=
721 extension_service()->extensions();
722 for (extensions::ExtensionSet::const_iterator it
= extensions
->begin();
723 it
!= extensions
->end(); ++it
) {
724 if ((*it
)->path() == extension_path
)
730 void UninstallExtension(const std::string
& id
, bool expect_success
) {
731 content::WindowedNotificationObserver
observer(
733 ? extensions::NOTIFICATION_EXTENSION_UNINSTALLED_DEPRECATED
734 : extensions::NOTIFICATION_EXTENSION_UNINSTALL_NOT_ALLOWED
,
735 content::NotificationService::AllSources());
736 extension_service()->UninstallExtension(
738 extensions::UNINSTALL_REASON_FOR_TESTING
,
739 base::Bind(&base::DoNothing
),
744 void DisableExtension(const std::string
& id
) {
745 content::WindowedNotificationObserver
observer(
746 extensions::NOTIFICATION_EXTENSION_UNLOADED_DEPRECATED
,
747 content::NotificationService::AllSources());
748 extension_service()->DisableExtension(id
,
749 extensions::Extension::DISABLE_NONE
);
753 void UpdateProviderPolicy(const PolicyMap
& policy
) {
754 provider_
.UpdateChromePolicy(policy
);
755 DCHECK(base::MessageLoop::current());
760 // Sends a mouse click at the given coordinates to the current renderer.
761 void PerformClick(int x
, int y
) {
762 content::WebContents
* contents
=
763 browser()->tab_strip_model()->GetActiveWebContents();
764 blink::WebMouseEvent click_event
;
765 click_event
.type
= blink::WebInputEvent::MouseDown
;
766 click_event
.button
= blink::WebMouseEvent::ButtonLeft
;
767 click_event
.clickCount
= 1;
770 contents
->GetRenderViewHost()->ForwardMouseEvent(click_event
);
771 click_event
.type
= blink::WebInputEvent::MouseUp
;
772 contents
->GetRenderViewHost()->ForwardMouseEvent(click_event
);
775 MockConfigurationPolicyProvider provider_
;
776 scoped_ptr
<extensions::ExtensionCacheFake
> test_extension_cache_
;
777 #if defined(OS_CHROMEOS)
778 QuitMessageLoopAfterScreenshot observer_
;
783 // This policy only exists on Windows.
785 // Sets the locale policy before the browser is started.
786 class LocalePolicyTest
: public PolicyTest
{
788 LocalePolicyTest() {}
789 virtual ~LocalePolicyTest() {}
791 virtual void SetUpInProcessBrowserTestFixture() override
{
792 PolicyTest::SetUpInProcessBrowserTestFixture();
794 policies
.Set(key::kApplicationLocaleValue
,
795 POLICY_LEVEL_MANDATORY
,
797 new base::StringValue("fr"),
799 provider_
.UpdateChromePolicy(policies
);
800 // The "en-US" ResourceBundle is always loaded before this step for tests,
801 // but in this test we want the browser to load the bundle as it
803 ResourceBundle::CleanupSharedInstance();
807 IN_PROC_BROWSER_TEST_F(LocalePolicyTest
, ApplicationLocaleValue
) {
808 // Verifies that the default locale can be overridden with policy.
809 EXPECT_EQ("fr", g_browser_process
->GetApplicationLocale());
810 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL
));
811 base::string16 french_title
= l10n_util::GetStringUTF16(IDS_NEW_TAB_TITLE
);
812 base::string16 title
;
813 EXPECT_TRUE(ui_test_utils::GetCurrentTabTitle(browser(), &title
));
814 EXPECT_EQ(french_title
, title
);
816 // Make sure this is really French and differs from the English title.
818 ui::ResourceBundle::GetSharedInstance().ReloadLocaleResources("en-US");
819 EXPECT_EQ("en-US", loaded
);
820 base::string16 english_title
= l10n_util::GetStringUTF16(IDS_NEW_TAB_TITLE
);
821 EXPECT_NE(french_title
, english_title
);
825 IN_PROC_BROWSER_TEST_F(PolicyTest
, BookmarkBarEnabled
) {
826 #if defined(OS_WIN) && defined(USE_ASH)
827 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
828 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshBrowserTests
))
832 // Verifies that the bookmarks bar can be forced to always or never show up.
834 // Test starts in about:blank.
835 PrefService
* prefs
= browser()->profile()->GetPrefs();
836 EXPECT_FALSE(prefs
->IsManagedPreference(bookmarks::prefs::kShowBookmarkBar
));
837 EXPECT_FALSE(prefs
->GetBoolean(bookmarks::prefs::kShowBookmarkBar
));
838 EXPECT_EQ(BookmarkBar::HIDDEN
, browser()->bookmark_bar_state());
841 policies
.Set(key::kBookmarkBarEnabled
,
842 POLICY_LEVEL_MANDATORY
,
844 new base::FundamentalValue(true),
846 UpdateProviderPolicy(policies
);
847 EXPECT_TRUE(prefs
->IsManagedPreference(bookmarks::prefs::kShowBookmarkBar
));
848 EXPECT_TRUE(prefs
->GetBoolean(bookmarks::prefs::kShowBookmarkBar
));
849 EXPECT_EQ(BookmarkBar::SHOW
, browser()->bookmark_bar_state());
851 // The NTP has special handling of the bookmark bar.
852 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL
));
853 EXPECT_EQ(BookmarkBar::SHOW
, browser()->bookmark_bar_state());
855 policies
.Set(key::kBookmarkBarEnabled
,
856 POLICY_LEVEL_MANDATORY
,
858 new base::FundamentalValue(false),
860 UpdateProviderPolicy(policies
);
861 EXPECT_TRUE(prefs
->IsManagedPreference(bookmarks::prefs::kShowBookmarkBar
));
862 EXPECT_FALSE(prefs
->GetBoolean(bookmarks::prefs::kShowBookmarkBar
));
863 // The bookmark bar is hidden in the NTP when disabled by policy.
864 EXPECT_EQ(BookmarkBar::HIDDEN
, browser()->bookmark_bar_state());
867 UpdateProviderPolicy(policies
);
868 EXPECT_FALSE(prefs
->IsManagedPreference(bookmarks::prefs::kShowBookmarkBar
));
869 EXPECT_FALSE(prefs
->GetBoolean(bookmarks::prefs::kShowBookmarkBar
));
870 // The bookmark bar is shown detached in the NTP, when disabled by prefs only.
871 EXPECT_EQ(BookmarkBar::DETACHED
, browser()->bookmark_bar_state());
874 IN_PROC_BROWSER_TEST_F(PolicyTest
, PRE_PRE_DefaultCookiesSetting
) {
875 // Verifies that cookies are deleted on shutdown. This test is split in 3
876 // parts because it spans 2 browser restarts.
878 Profile
* profile
= browser()->profile();
880 // No cookies at startup.
881 EXPECT_TRUE(content::GetCookies(profile
, url
).empty());
883 std::string value
= std::string(kCookieValue
) + std::string(kCookieOptions
);
884 EXPECT_TRUE(content::SetCookie(profile
, url
, value
));
885 // Verify it was set.
886 EXPECT_EQ(kCookieValue
, GetCookies(profile
, url
));
889 IN_PROC_BROWSER_TEST_F(PolicyTest
, PRE_DefaultCookiesSetting
) {
890 // Verify that the cookie persists across restarts.
891 EXPECT_EQ(kCookieValue
, GetCookies(browser()->profile(), GURL(kURL
)));
892 // Now set the policy and the cookie should be gone after another restart.
894 policies
.Set(key::kDefaultCookiesSetting
,
895 POLICY_LEVEL_MANDATORY
,
897 new base::FundamentalValue(4),
899 UpdateProviderPolicy(policies
);
902 IN_PROC_BROWSER_TEST_F(PolicyTest
, DefaultCookiesSetting
) {
903 // Verify that the cookie is gone.
904 EXPECT_TRUE(GetCookies(browser()->profile(), GURL(kURL
)).empty());
907 IN_PROC_BROWSER_TEST_F(PolicyTest
, DefaultSearchProvider
) {
908 MakeRequestFail
make_request_fail("search.example");
910 // Verifies that a default search is made using the provider configured via
911 // policy. Also checks that default search can be completely disabled.
912 const base::string16
kKeyword(base::ASCIIToUTF16("testsearch"));
913 const std::string
kSearchURL("http://search.example/search?q={searchTerms}");
914 const std::string
kAlternateURL0(
915 "http://search.example/search#q={searchTerms}");
916 const std::string
kAlternateURL1("http://search.example/#q={searchTerms}");
917 const std::string
kSearchTermsReplacementKey("zekey");
918 const std::string
kImageURL("http://test.com/searchbyimage/upload");
919 const std::string
kImageURLPostParams(
920 "image_content=content,image_url=http://test.com/test.png");
921 const std::string
kNewTabURL("http://search.example/newtab");
923 TemplateURLService
* service
= TemplateURLServiceFactory::GetForProfile(
924 browser()->profile());
925 ui_test_utils::WaitForTemplateURLServiceToLoad(service
);
926 TemplateURL
* default_search
= service
->GetDefaultSearchProvider();
927 ASSERT_TRUE(default_search
);
928 EXPECT_NE(kKeyword
, default_search
->keyword());
929 EXPECT_NE(kSearchURL
, default_search
->url());
931 default_search
->alternate_urls().size() == 2 &&
932 default_search
->alternate_urls()[0] == kAlternateURL0
&&
933 default_search
->alternate_urls()[1] == kAlternateURL1
&&
934 default_search
->search_terms_replacement_key() ==
935 kSearchTermsReplacementKey
&&
936 default_search
->image_url() == kImageURL
&&
937 default_search
->image_url_post_params() == kImageURLPostParams
&&
938 default_search
->new_tab_url() == kNewTabURL
);
940 // Override the default search provider using policies.
942 policies
.Set(key::kDefaultSearchProviderEnabled
,
943 POLICY_LEVEL_MANDATORY
,
945 new base::FundamentalValue(true),
947 policies
.Set(key::kDefaultSearchProviderKeyword
,
948 POLICY_LEVEL_MANDATORY
,
950 new base::StringValue(kKeyword
),
952 policies
.Set(key::kDefaultSearchProviderSearchURL
,
953 POLICY_LEVEL_MANDATORY
,
955 new base::StringValue(kSearchURL
),
957 base::ListValue
* alternate_urls
= new base::ListValue();
958 alternate_urls
->AppendString(kAlternateURL0
);
959 alternate_urls
->AppendString(kAlternateURL1
);
960 policies
.Set(key::kDefaultSearchProviderAlternateURLs
, POLICY_LEVEL_MANDATORY
,
961 POLICY_SCOPE_USER
, alternate_urls
, NULL
);
962 policies
.Set(key::kDefaultSearchProviderSearchTermsReplacementKey
,
963 POLICY_LEVEL_MANDATORY
,
965 new base::StringValue(kSearchTermsReplacementKey
),
967 policies
.Set(key::kDefaultSearchProviderImageURL
,
968 POLICY_LEVEL_MANDATORY
,
970 new base::StringValue(kImageURL
),
972 policies
.Set(key::kDefaultSearchProviderImageURLPostParams
,
973 POLICY_LEVEL_MANDATORY
,
975 new base::StringValue(kImageURLPostParams
),
977 policies
.Set(key::kDefaultSearchProviderNewTabURL
,
978 POLICY_LEVEL_MANDATORY
,
980 new base::StringValue(kNewTabURL
),
982 UpdateProviderPolicy(policies
);
983 default_search
= service
->GetDefaultSearchProvider();
984 ASSERT_TRUE(default_search
);
985 EXPECT_EQ(kKeyword
, default_search
->keyword());
986 EXPECT_EQ(kSearchURL
, default_search
->url());
987 EXPECT_EQ(2U, default_search
->alternate_urls().size());
988 EXPECT_EQ(kAlternateURL0
, default_search
->alternate_urls()[0]);
989 EXPECT_EQ(kAlternateURL1
, default_search
->alternate_urls()[1]);
990 EXPECT_EQ(kSearchTermsReplacementKey
,
991 default_search
->search_terms_replacement_key());
992 EXPECT_EQ(kImageURL
, default_search
->image_url());
993 EXPECT_EQ(kImageURLPostParams
, default_search
->image_url_post_params());
994 EXPECT_EQ(kNewTabURL
, default_search
->new_tab_url());
996 // Verify that searching from the omnibox uses kSearchURL.
997 chrome::FocusLocationBar(browser());
998 LocationBar
* location_bar
= browser()->window()->GetLocationBar();
999 ui_test_utils::SendToOmniboxAndSubmit(location_bar
, "stuff to search for");
1000 OmniboxEditModel
* model
= location_bar
->GetOmniboxView()->model();
1001 EXPECT_TRUE(model
->CurrentMatch(NULL
).destination_url
.is_valid());
1002 content::WebContents
* web_contents
=
1003 browser()->tab_strip_model()->GetActiveWebContents();
1004 GURL
expected("http://search.example/search?q=stuff+to+search+for");
1005 EXPECT_EQ(expected
, web_contents
->GetURL());
1007 // Verify that searching from the omnibox can be disabled.
1008 ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL
));
1009 policies
.Set(key::kDefaultSearchProviderEnabled
,
1010 POLICY_LEVEL_MANDATORY
,
1012 new base::FundamentalValue(false),
1014 EXPECT_TRUE(service
->GetDefaultSearchProvider());
1015 UpdateProviderPolicy(policies
);
1016 EXPECT_FALSE(service
->GetDefaultSearchProvider());
1017 ui_test_utils::SendToOmniboxAndSubmit(location_bar
, "should not work");
1018 // This means that submitting won't trigger any action.
1019 EXPECT_FALSE(model
->CurrentMatch(NULL
).destination_url
.is_valid());
1020 EXPECT_EQ(GURL(url::kAboutBlankURL
), web_contents
->GetURL());
1023 IN_PROC_BROWSER_TEST_F(PolicyTest
, PolicyPreprocessing
) {
1024 // Add an individual proxy policy value.
1026 policies
.Set(key::kProxyServerMode
,
1027 POLICY_LEVEL_MANDATORY
,
1029 new base::FundamentalValue(3),
1031 UpdateProviderPolicy(policies
);
1033 // It should be removed and replaced with a dictionary.
1035 scoped_ptr
<base::DictionaryValue
> expected_value(new base::DictionaryValue
);
1036 expected_value
->SetInteger(key::kProxyServerMode
, 3);
1037 expected
.Set(key::kProxySettings
,
1038 POLICY_LEVEL_MANDATORY
,
1040 expected_value
.release(),
1043 // Check both the browser and the profile.
1044 const PolicyMap
& actual_from_browser
=
1045 g_browser_process
->browser_policy_connector()
1046 ->GetPolicyService()
1047 ->GetPolicies(PolicyNamespace(POLICY_DOMAIN_CHROME
, std::string()));
1048 EXPECT_TRUE(expected
.Equals(actual_from_browser
));
1049 const PolicyMap
& actual_from_profile
=
1050 ProfilePolicyConnectorFactory::GetForProfile(browser()->profile())
1052 ->GetPolicies(PolicyNamespace(POLICY_DOMAIN_CHROME
, std::string()));
1053 EXPECT_TRUE(expected
.Equals(actual_from_profile
));
1056 IN_PROC_BROWSER_TEST_F(PolicyTest
, ForceSafeSearch
) {
1057 // Makes the requests fail since all we want to check is that the redirection
1058 // is done properly.
1059 MakeRequestFail
make_request_fail("google.com");
1061 // Verifies that requests to Google Search engine with the SafeSearch
1062 // enabled set the safe=active&ssui=on parameters at the end of the query.
1063 TemplateURLService
* service
= TemplateURLServiceFactory::GetForProfile(
1064 browser()->profile());
1065 ui_test_utils::WaitForTemplateURLServiceToLoad(service
);
1067 // First check that nothing happens.
1068 content::TestNavigationObserver
no_safesearch_observer(
1069 browser()->tab_strip_model()->GetActiveWebContents());
1070 chrome::FocusLocationBar(browser());
1071 LocationBar
* location_bar
= browser()->window()->GetLocationBar();
1072 ui_test_utils::SendToOmniboxAndSubmit(location_bar
, "http://google.com/");
1073 OmniboxEditModel
* model
= location_bar
->GetOmniboxView()->model();
1074 no_safesearch_observer
.Wait();
1075 EXPECT_TRUE(model
->CurrentMatch(NULL
).destination_url
.is_valid());
1076 content::WebContents
* web_contents
=
1077 browser()->tab_strip_model()->GetActiveWebContents();
1078 GURL
expected_without("http://google.com/");
1079 EXPECT_EQ(expected_without
, web_contents
->GetURL());
1081 PrefService
* prefs
= browser()->profile()->GetPrefs();
1082 EXPECT_FALSE(prefs
->IsManagedPreference(prefs::kForceSafeSearch
));
1083 EXPECT_FALSE(prefs
->GetBoolean(prefs::kForceSafeSearch
));
1085 // Override the default SafeSearch setting using policies.
1087 policies
.Set(key::kForceSafeSearch
,
1088 POLICY_LEVEL_MANDATORY
,
1090 new base::FundamentalValue(true),
1092 UpdateProviderPolicy(policies
);
1094 EXPECT_TRUE(prefs
->IsManagedPreference(prefs::kForceSafeSearch
));
1095 EXPECT_TRUE(prefs
->GetBoolean(prefs::kForceSafeSearch
));
1097 content::TestNavigationObserver
safesearch_observer(
1098 browser()->tab_strip_model()->GetActiveWebContents());
1100 // Verify that searching from google.com works.
1101 chrome::FocusLocationBar(browser());
1102 ui_test_utils::SendToOmniboxAndSubmit(location_bar
, "http://google.com/");
1103 safesearch_observer
.Wait();
1104 EXPECT_TRUE(model
->CurrentMatch(NULL
).destination_url
.is_valid());
1105 web_contents
= browser()->tab_strip_model()->GetActiveWebContents();
1106 std::string
expected_url("http://google.com/?");
1107 expected_url
+= std::string(chrome::kSafeSearchSafeParameter
) + "&" +
1108 chrome::kSafeSearchSsuiParameter
;
1109 GURL
expected_with_parameters(expected_url
);
1110 EXPECT_EQ(expected_with_parameters
, web_contents
->GetURL());
1113 IN_PROC_BROWSER_TEST_F(PolicyTest
, ReplaceSearchTerms
) {
1114 MakeRequestFail
make_request_fail("search.example");
1116 chrome::EnableQueryExtractionForTesting();
1118 // Verifies that a default search is made using the provider configured via
1119 // policy. Also checks that default search can be completely disabled.
1120 const base::string16
kKeyword(base::ASCIIToUTF16("testsearch"));
1121 const std::string
kSearchURL("https://www.google.com/search?q={searchTerms}");
1122 const std::string
kInstantURL("http://does/not/exist");
1123 const std::string
kAlternateURL0(
1124 "https://www.google.com/search#q={searchTerms}");
1125 const std::string
kAlternateURL1("https://www.google.com/#q={searchTerms}");
1126 const std::string
kSearchTermsReplacementKey(
1127 "{google:instantExtendedEnabledKey}");
1129 TemplateURLService
* service
= TemplateURLServiceFactory::GetForProfile(
1130 browser()->profile());
1131 ui_test_utils::WaitForTemplateURLServiceToLoad(service
);
1132 TemplateURL
* default_search
= service
->GetDefaultSearchProvider();
1133 ASSERT_TRUE(default_search
);
1134 EXPECT_NE(kKeyword
, default_search
->keyword());
1135 EXPECT_NE(kSearchURL
, default_search
->url());
1136 EXPECT_NE(kInstantURL
, default_search
->instant_url());
1138 default_search
->alternate_urls().size() == 2 &&
1139 default_search
->alternate_urls()[0] == kAlternateURL0
&&
1140 default_search
->alternate_urls()[1] == kAlternateURL1
);
1142 // Override the default search provider using policies.
1144 policies
.Set(key::kDefaultSearchProviderEnabled
,
1145 POLICY_LEVEL_MANDATORY
,
1147 new base::FundamentalValue(true),
1149 policies
.Set(key::kDefaultSearchProviderKeyword
,
1150 POLICY_LEVEL_MANDATORY
,
1152 new base::StringValue(kKeyword
),
1154 policies
.Set(key::kDefaultSearchProviderSearchURL
,
1155 POLICY_LEVEL_MANDATORY
,
1157 new base::StringValue(kSearchURL
),
1159 policies
.Set(key::kDefaultSearchProviderInstantURL
,
1160 POLICY_LEVEL_MANDATORY
,
1162 new base::StringValue(kInstantURL
),
1164 base::ListValue
* alternate_urls
= new base::ListValue();
1165 alternate_urls
->AppendString(kAlternateURL0
);
1166 alternate_urls
->AppendString(kAlternateURL1
);
1167 policies
.Set(key::kDefaultSearchProviderAlternateURLs
, POLICY_LEVEL_MANDATORY
,
1168 POLICY_SCOPE_USER
, alternate_urls
, NULL
);
1169 policies
.Set(key::kDefaultSearchProviderSearchTermsReplacementKey
,
1170 POLICY_LEVEL_MANDATORY
,
1172 new base::StringValue(kSearchTermsReplacementKey
),
1174 UpdateProviderPolicy(policies
);
1175 default_search
= service
->GetDefaultSearchProvider();
1176 ASSERT_TRUE(default_search
);
1177 EXPECT_EQ(kKeyword
, default_search
->keyword());
1178 EXPECT_EQ(kSearchURL
, default_search
->url());
1179 EXPECT_EQ(kInstantURL
, default_search
->instant_url());
1180 EXPECT_EQ(2U, default_search
->alternate_urls().size());
1181 EXPECT_EQ(kAlternateURL0
, default_search
->alternate_urls()[0]);
1182 EXPECT_EQ(kAlternateURL1
, default_search
->alternate_urls()[1]);
1184 // Query terms replacement requires that the renderer process be a recognized
1185 // Instant renderer. Fake it.
1186 InstantService
* instant_service
=
1187 InstantServiceFactory::GetForProfile(browser()->profile());
1188 instant_service
->AddInstantProcess(browser()->tab_strip_model()->
1189 GetActiveWebContents()->GetRenderProcessHost()->GetID());
1191 // Verify that searching from the omnibox does search term replacement with
1192 // first URL pattern.
1193 chrome::FocusLocationBar(browser());
1194 LocationBar
* location_bar
= browser()->window()->GetLocationBar();
1195 OmniboxView
* omnibox_view
= location_bar
->GetOmniboxView();
1196 ui_test_utils::SendToOmniboxAndSubmit(location_bar
,
1197 "https://www.google.com/?espv=1#q=foobar");
1199 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1200 EXPECT_EQ(base::ASCIIToUTF16("foobar"), omnibox_view
->GetText());
1202 // Verify that not using espv=1 does not do search term replacement.
1203 chrome::FocusLocationBar(browser());
1204 ui_test_utils::SendToOmniboxAndSubmit(location_bar
,
1205 "https://www.google.com/?q=foobar");
1207 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1208 EXPECT_EQ(base::ASCIIToUTF16("https://www.google.com/?q=foobar"),
1209 omnibox_view
->GetText());
1211 // Verify that searching from the omnibox does search term replacement with
1212 // second URL pattern.
1213 chrome::FocusLocationBar(browser());
1214 ui_test_utils::SendToOmniboxAndSubmit(location_bar
,
1215 "https://www.google.com/search?espv=1#q=banana");
1217 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1218 EXPECT_EQ(base::ASCIIToUTF16("banana"), omnibox_view
->GetText());
1220 // Verify that searching from the omnibox does search term replacement with
1221 // standard search URL pattern.
1222 chrome::FocusLocationBar(browser());
1223 ui_test_utils::SendToOmniboxAndSubmit(location_bar
,
1224 "https://www.google.com/search?q=tractor+parts&espv=1");
1226 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1227 EXPECT_EQ(base::ASCIIToUTF16("tractor parts"), omnibox_view
->GetText());
1229 // Verify that searching from the omnibox prioritizes hash over query.
1230 chrome::FocusLocationBar(browser());
1231 ui_test_utils::SendToOmniboxAndSubmit(location_bar
,
1232 "https://www.google.com/search?q=tractor+parts&espv=1#q=foobar");
1234 browser()->toolbar_model()->WouldPerformSearchTermReplacement(false));
1235 EXPECT_EQ(base::ASCIIToUTF16("foobar"), omnibox_view
->GetText());
1238 IN_PROC_BROWSER_TEST_F(PolicyTest
, Disable3DAPIs
) {
1239 // This test assumes Gpu access.
1240 if (!content::GpuDataManager::GetInstance()->GpuAccessAllowed(NULL
))
1243 ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL
));
1244 // WebGL is enabled by default.
1245 content::WebContents
* contents
=
1246 browser()->tab_strip_model()->GetActiveWebContents();
1247 EXPECT_TRUE(IsWebGLEnabled(contents
));
1248 // Disable with a policy.
1250 policies
.Set(key::kDisable3DAPIs
,
1251 POLICY_LEVEL_MANDATORY
,
1253 new base::FundamentalValue(true),
1255 UpdateProviderPolicy(policies
);
1256 // Crash and reload the tab to get a new renderer.
1257 content::CrashTab(contents
);
1258 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_RELOAD
));
1259 EXPECT_FALSE(IsWebGLEnabled(contents
));
1260 // Enable with a policy.
1261 policies
.Set(key::kDisable3DAPIs
,
1262 POLICY_LEVEL_MANDATORY
,
1264 new base::FundamentalValue(false),
1266 UpdateProviderPolicy(policies
);
1267 content::CrashTab(contents
);
1268 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_RELOAD
));
1269 EXPECT_TRUE(IsWebGLEnabled(contents
));
1272 IN_PROC_BROWSER_TEST_F(PolicyTest
, DisableSpdy
) {
1273 // Verifies that SPDY can be disable by policy.
1274 EXPECT_TRUE(net::HttpStreamFactory::spdy_enabled());
1276 policies
.Set(key::kDisableSpdy
,
1277 POLICY_LEVEL_MANDATORY
,
1279 new base::FundamentalValue(true),
1281 UpdateProviderPolicy(policies
);
1282 content::RunAllPendingInMessageLoop();
1283 EXPECT_FALSE(net::HttpStreamFactory::spdy_enabled());
1284 // Verify that it can be force-enabled too.
1285 browser()->profile()->GetPrefs()->SetBoolean(prefs::kDisableSpdy
, true);
1286 policies
.Set(key::kDisableSpdy
,
1287 POLICY_LEVEL_MANDATORY
,
1289 new base::FundamentalValue(false),
1291 UpdateProviderPolicy(policies
);
1292 content::RunAllPendingInMessageLoop();
1293 EXPECT_TRUE(net::HttpStreamFactory::spdy_enabled());
1296 IN_PROC_BROWSER_TEST_F(PolicyTest
, DisabledPlugins
) {
1297 // Verifies that plugins can be forced to be disabled by policy.
1299 // Verify that the Flash plugin exists and that it can be enabled and disabled
1301 std::vector
<content::WebPluginInfo
> plugins
;
1302 GetPluginList(&plugins
);
1303 const content::WebPluginInfo
* flash
= GetFlashPlugin(plugins
);
1306 PluginPrefs
* plugin_prefs
=
1307 PluginPrefs::GetForProfile(browser()->profile()).get();
1308 EXPECT_TRUE(plugin_prefs
->IsPluginEnabled(*flash
));
1309 EXPECT_TRUE(SetPluginEnabled(plugin_prefs
, flash
, false));
1310 EXPECT_FALSE(plugin_prefs
->IsPluginEnabled(*flash
));
1311 EXPECT_TRUE(SetPluginEnabled(plugin_prefs
, flash
, true));
1312 EXPECT_TRUE(plugin_prefs
->IsPluginEnabled(*flash
));
1314 // Now disable it with a policy.
1315 base::ListValue disabled_plugins
;
1316 disabled_plugins
.Append(new base::StringValue("*Flash*"));
1318 policies
.Set(key::kDisabledPlugins
, POLICY_LEVEL_MANDATORY
,
1319 POLICY_SCOPE_USER
, disabled_plugins
.DeepCopy(), NULL
);
1320 UpdateProviderPolicy(policies
);
1321 EXPECT_FALSE(plugin_prefs
->IsPluginEnabled(*flash
));
1322 // The user shouldn't be able to enable it.
1323 EXPECT_FALSE(SetPluginEnabled(plugin_prefs
, flash
, true));
1324 EXPECT_FALSE(plugin_prefs
->IsPluginEnabled(*flash
));
1327 IN_PROC_BROWSER_TEST_F(PolicyTest
, DisabledPluginsExceptions
) {
1328 // Verifies that plugins with an exception in the blacklist can be enabled.
1330 // Verify that the Flash plugin exists and that it can be enabled and disabled
1332 std::vector
<content::WebPluginInfo
> plugins
;
1333 GetPluginList(&plugins
);
1334 const content::WebPluginInfo
* flash
= GetFlashPlugin(plugins
);
1337 PluginPrefs
* plugin_prefs
=
1338 PluginPrefs::GetForProfile(browser()->profile()).get();
1339 EXPECT_TRUE(plugin_prefs
->IsPluginEnabled(*flash
));
1341 // Disable all plugins.
1342 base::ListValue disabled_plugins
;
1343 disabled_plugins
.Append(new base::StringValue("*"));
1345 policies
.Set(key::kDisabledPlugins
, POLICY_LEVEL_MANDATORY
,
1346 POLICY_SCOPE_USER
, disabled_plugins
.DeepCopy(), NULL
);
1347 UpdateProviderPolicy(policies
);
1348 EXPECT_FALSE(plugin_prefs
->IsPluginEnabled(*flash
));
1349 // The user shouldn't be able to enable it.
1350 EXPECT_FALSE(SetPluginEnabled(plugin_prefs
, flash
, true));
1351 EXPECT_FALSE(plugin_prefs
->IsPluginEnabled(*flash
));
1353 // Now open an exception for flash.
1354 base::ListValue disabled_plugins_exceptions
;
1355 disabled_plugins_exceptions
.Append(new base::StringValue("*Flash*"));
1356 policies
.Set(key::kDisabledPluginsExceptions
, POLICY_LEVEL_MANDATORY
,
1357 POLICY_SCOPE_USER
, disabled_plugins_exceptions
.DeepCopy(), NULL
);
1358 UpdateProviderPolicy(policies
);
1359 // It should revert to the user's preference automatically.
1360 EXPECT_TRUE(plugin_prefs
->IsPluginEnabled(*flash
));
1361 // And the user should be able to disable and enable again.
1362 EXPECT_TRUE(SetPluginEnabled(plugin_prefs
, flash
, false));
1363 EXPECT_FALSE(plugin_prefs
->IsPluginEnabled(*flash
));
1364 EXPECT_TRUE(SetPluginEnabled(plugin_prefs
, flash
, true));
1365 EXPECT_TRUE(plugin_prefs
->IsPluginEnabled(*flash
));
1368 IN_PROC_BROWSER_TEST_F(PolicyTest
, EnabledPlugins
) {
1369 // Verifies that a plugin can be force-installed with a policy.
1370 std::vector
<content::WebPluginInfo
> plugins
;
1371 GetPluginList(&plugins
);
1372 const content::WebPluginInfo
* flash
= GetFlashPlugin(plugins
);
1375 PluginPrefs
* plugin_prefs
=
1376 PluginPrefs::GetForProfile(browser()->profile()).get();
1377 EXPECT_TRUE(plugin_prefs
->IsPluginEnabled(*flash
));
1379 // The user disables it and then a policy forces it to be enabled.
1380 EXPECT_TRUE(SetPluginEnabled(plugin_prefs
, flash
, false));
1381 EXPECT_FALSE(plugin_prefs
->IsPluginEnabled(*flash
));
1382 base::ListValue plugin_list
;
1383 plugin_list
.Append(new base::StringValue(content::kFlashPluginName
));
1385 policies
.Set(key::kEnabledPlugins
, POLICY_LEVEL_MANDATORY
,
1386 POLICY_SCOPE_USER
, plugin_list
.DeepCopy(), NULL
);
1387 UpdateProviderPolicy(policies
);
1388 EXPECT_TRUE(plugin_prefs
->IsPluginEnabled(*flash
));
1389 // The user can't disable it anymore.
1390 EXPECT_FALSE(SetPluginEnabled(plugin_prefs
, flash
, false));
1391 EXPECT_TRUE(plugin_prefs
->IsPluginEnabled(*flash
));
1393 // When a plugin is both enabled and disabled, the whitelist takes precedence.
1394 policies
.Set(key::kDisabledPlugins
, POLICY_LEVEL_MANDATORY
,
1395 POLICY_SCOPE_USER
, plugin_list
.DeepCopy(), NULL
);
1396 UpdateProviderPolicy(policies
);
1397 EXPECT_TRUE(plugin_prefs
->IsPluginEnabled(*flash
));
1400 IN_PROC_BROWSER_TEST_F(PolicyTest
, AlwaysAuthorizePlugins
) {
1401 // Verifies that dangerous plugins can be always authorized to run with
1404 // Verify that the test page exists. It is only present in checkouts with
1406 if (!base::PathExists(ui_test_utils::GetTestFilePath(
1407 base::FilePath(FILE_PATH_LITERAL("plugin")),
1408 base::FilePath(FILE_PATH_LITERAL("quicktime.html"))))) {
1410 "Test skipped because plugin/quicktime.html test file wasn't found.";
1414 ServeContentTestData();
1415 // No plugins at startup.
1416 EXPECT_EQ(0, CountPlugins());
1418 content::WebContents
* contents
=
1419 browser()->tab_strip_model()->GetActiveWebContents();
1420 ASSERT_TRUE(contents
);
1421 InfoBarService
* infobar_service
= InfoBarService::FromWebContents(contents
);
1422 ASSERT_TRUE(infobar_service
);
1423 EXPECT_EQ(0u, infobar_service
->infobar_count());
1425 base::FilePath
path(FILE_PATH_LITERAL("plugin/quicktime.html"));
1426 GURL
url(URLRequestMockHTTPJob::GetMockUrl(path
));
1427 ui_test_utils::NavigateToURL(browser(), url
);
1428 // This should have triggered the dangerous plugin infobar.
1429 ASSERT_EQ(1u, infobar_service
->infobar_count());
1431 infobar_service
->infobar_at(0)->delegate()->AsConfirmInfoBarDelegate());
1432 // And the plugin isn't running.
1433 EXPECT_EQ(0, CountPlugins());
1435 // Now set a policy to always authorize this.
1437 policies
.Set(key::kAlwaysAuthorizePlugins
,
1438 POLICY_LEVEL_MANDATORY
,
1440 new base::FundamentalValue(true),
1442 UpdateProviderPolicy(policies
);
1443 // Reloading the page shouldn't trigger the infobar this time.
1444 ui_test_utils::NavigateToURL(browser(), url
);
1445 EXPECT_EQ(0u, infobar_service
->infobar_count());
1446 // And the plugin started automatically.
1447 EXPECT_EQ(1, CountPlugins());
1450 IN_PROC_BROWSER_TEST_F(PolicyTest
, DeveloperToolsDisabled
) {
1451 // Verifies that access to the developer tools can be disabled.
1454 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_DEV_TOOLS
));
1455 content::WebContents
* contents
=
1456 browser()->tab_strip_model()->GetActiveWebContents();
1457 DevToolsWindow
*devtools_window
=
1458 DevToolsWindow::GetInstanceForInspectedWebContents(contents
);
1459 EXPECT_TRUE(devtools_window
);
1461 // Disable devtools via policy.
1463 policies
.Set(key::kDeveloperToolsDisabled
,
1464 POLICY_LEVEL_MANDATORY
,
1466 new base::FundamentalValue(true),
1468 content::WindowedNotificationObserver
close_observer(
1469 content::NOTIFICATION_WEB_CONTENTS_DESTROYED
,
1470 content::Source
<content::WebContents
>(
1471 DevToolsWindowTesting::Get(devtools_window
)->main_web_contents()));
1472 UpdateProviderPolicy(policies
);
1473 // wait for devtools close
1474 close_observer
.Wait();
1475 // The existing devtools window should have closed.
1476 EXPECT_FALSE(DevToolsWindow::GetInstanceForInspectedWebContents(contents
));
1477 // And it's not possible to open it again.
1478 EXPECT_FALSE(chrome::ExecuteCommand(browser(), IDC_DEV_TOOLS
));
1479 EXPECT_FALSE(DevToolsWindow::GetInstanceForInspectedWebContents(contents
));
1482 // TODO(samarth): remove along with rest of NTP4 code.
1483 IN_PROC_BROWSER_TEST_F(PolicyTest
, DISABLED_WebStoreIconHidden
) {
1484 #if defined(OS_WIN) && defined(USE_ASH)
1485 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
1486 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshBrowserTests
))
1490 // Verifies that the web store icons can be hidden from the new tab page.
1492 // Open new tab page and look for the web store icons.
1493 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL
));
1494 content::WebContents
* contents
=
1495 browser()->tab_strip_model()->GetActiveWebContents();
1497 #if !defined(OS_CHROMEOS)
1498 // Look for web store's app ID in the apps page.
1499 EXPECT_TRUE(ContainsVisibleElement(contents
,
1500 "ahfgeienlihckogmohjhadlkjgocpleb"));
1503 // The next NTP has no footer.
1504 if (ContainsVisibleElement(contents
, "footer"))
1505 EXPECT_TRUE(ContainsVisibleElement(contents
, "chrome-web-store-link"));
1507 // Turn off the web store icons.
1509 policies
.Set(key::kHideWebStoreIcon
,
1510 POLICY_LEVEL_MANDATORY
,
1512 new base::FundamentalValue(true),
1514 UpdateProviderPolicy(policies
);
1516 // The web store icons should now be hidden.
1517 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUINewTabURL
));
1518 EXPECT_FALSE(ContainsVisibleElement(contents
,
1519 "ahfgeienlihckogmohjhadlkjgocpleb"));
1520 EXPECT_FALSE(ContainsVisibleElement(contents
, "chrome-web-store-link"));
1523 IN_PROC_BROWSER_TEST_F(PolicyTest
, DownloadDirectory
) {
1524 // Verifies that the download directory can be forced by policy.
1526 // Set the initial download directory.
1527 base::ScopedTempDir initial_dir
;
1528 ASSERT_TRUE(initial_dir
.CreateUniqueTempDir());
1529 browser()->profile()->GetPrefs()->SetFilePath(
1530 prefs::kDownloadDefaultDirectory
, initial_dir
.path());
1531 // Don't prompt for the download location during this test.
1532 browser()->profile()->GetPrefs()->SetBoolean(
1533 prefs::kPromptForDownload
, false);
1535 // Verify that downloads end up on the default directory.
1536 base::FilePath
file(FILE_PATH_LITERAL("download-test1.lib"));
1537 DownloadAndVerifyFile(browser(), initial_dir
.path(), file
);
1538 base::DieFileDie(initial_dir
.path().Append(file
), false);
1540 // Override the download directory with the policy and verify a download.
1541 base::ScopedTempDir forced_dir
;
1542 ASSERT_TRUE(forced_dir
.CreateUniqueTempDir());
1544 policies
.Set(key::kDownloadDirectory
,
1545 POLICY_LEVEL_MANDATORY
,
1547 new base::StringValue(forced_dir
.path().value()),
1549 UpdateProviderPolicy(policies
);
1550 DownloadAndVerifyFile(browser(), forced_dir
.path(), file
);
1551 // Verify that the first download location wasn't affected.
1552 EXPECT_FALSE(base::PathExists(initial_dir
.path().Append(file
)));
1555 IN_PROC_BROWSER_TEST_F(PolicyTest
, ExtensionInstallBlacklistSelective
) {
1556 // Verifies that blacklisted extensions can't be installed.
1557 ExtensionService
* service
= extension_service();
1558 ASSERT_FALSE(service
->GetExtensionById(kGoodCrxId
, true));
1559 ASSERT_FALSE(service
->GetExtensionById(kAdBlockCrxId
, true));
1560 base::ListValue blacklist
;
1561 blacklist
.Append(new base::StringValue(kGoodCrxId
));
1563 policies
.Set(key::kExtensionInstallBlacklist
, POLICY_LEVEL_MANDATORY
,
1564 POLICY_SCOPE_USER
, blacklist
.DeepCopy(), NULL
);
1565 UpdateProviderPolicy(policies
);
1567 // "good.crx" is blacklisted.
1568 EXPECT_FALSE(InstallExtension(kGoodCrxName
));
1569 EXPECT_FALSE(service
->GetExtensionById(kGoodCrxId
, true));
1571 // "adblock.crx" is not.
1572 const extensions::Extension
* adblock
= InstallExtension(kAdBlockCrxName
);
1573 ASSERT_TRUE(adblock
);
1574 EXPECT_EQ(kAdBlockCrxId
, adblock
->id());
1576 service
->GetExtensionById(kAdBlockCrxId
, true));
1579 // Flaky on windows; http://crbug.com/307994.
1581 #define MAYBE_ExtensionInstallBlacklistWildcard DISABLED_ExtensionInstallBlacklistWildcard
1583 #define MAYBE_ExtensionInstallBlacklistWildcard ExtensionInstallBlacklistWildcard
1585 IN_PROC_BROWSER_TEST_F(PolicyTest
, MAYBE_ExtensionInstallBlacklistWildcard
) {
1586 // Verify that a wildcard blacklist takes effect.
1587 EXPECT_TRUE(InstallExtension(kAdBlockCrxName
));
1588 ExtensionService
* service
= extension_service();
1589 ASSERT_FALSE(service
->GetExtensionById(kGoodCrxId
, true));
1590 ASSERT_TRUE(service
->GetExtensionById(kAdBlockCrxId
, true));
1591 base::ListValue blacklist
;
1592 blacklist
.Append(new base::StringValue("*"));
1594 policies
.Set(key::kExtensionInstallBlacklist
, POLICY_LEVEL_MANDATORY
,
1595 POLICY_SCOPE_USER
, blacklist
.DeepCopy(), NULL
);
1596 UpdateProviderPolicy(policies
);
1598 // AdBlock was automatically removed.
1599 ASSERT_FALSE(service
->GetExtensionById(kAdBlockCrxId
, true));
1601 // And can't be installed again, nor can good.crx.
1602 EXPECT_FALSE(InstallExtension(kAdBlockCrxName
));
1603 EXPECT_FALSE(service
->GetExtensionById(kAdBlockCrxId
, true));
1604 EXPECT_FALSE(InstallExtension(kGoodCrxName
));
1605 EXPECT_FALSE(service
->GetExtensionById(kGoodCrxId
, true));
1608 IN_PROC_BROWSER_TEST_F(PolicyTest
, ExtensionInstallWhitelist
) {
1609 // Verifies that the whitelist can open exceptions to the blacklist.
1610 ExtensionService
* service
= extension_service();
1611 ASSERT_FALSE(service
->GetExtensionById(kGoodCrxId
, true));
1612 ASSERT_FALSE(service
->GetExtensionById(kAdBlockCrxId
, true));
1613 base::ListValue blacklist
;
1614 blacklist
.Append(new base::StringValue("*"));
1615 base::ListValue whitelist
;
1616 whitelist
.Append(new base::StringValue(kGoodCrxId
));
1618 policies
.Set(key::kExtensionInstallBlacklist
, POLICY_LEVEL_MANDATORY
,
1619 POLICY_SCOPE_USER
, blacklist
.DeepCopy(), NULL
);
1620 policies
.Set(key::kExtensionInstallWhitelist
, POLICY_LEVEL_MANDATORY
,
1621 POLICY_SCOPE_USER
, whitelist
.DeepCopy(), NULL
);
1622 UpdateProviderPolicy(policies
);
1623 // "adblock.crx" is blacklisted.
1624 EXPECT_FALSE(InstallExtension(kAdBlockCrxName
));
1625 EXPECT_FALSE(service
->GetExtensionById(kAdBlockCrxId
, true));
1626 // "good.crx" has a whitelist exception.
1627 const extensions::Extension
* good
= InstallExtension(kGoodCrxName
);
1629 EXPECT_EQ(kGoodCrxId
, good
->id());
1630 EXPECT_EQ(good
, service
->GetExtensionById(kGoodCrxId
, true));
1631 // The user can also remove this extension.
1632 UninstallExtension(kGoodCrxId
, true);
1635 IN_PROC_BROWSER_TEST_F(PolicyTest
, ExtensionInstallForcelist
) {
1636 // Verifies that extensions that are force-installed by policies are
1637 // installed and can't be uninstalled.
1638 ExtensionService
* service
= extension_service();
1639 ASSERT_FALSE(service
->GetExtensionById(kGoodCrxId
, true));
1641 // Extensions that are force-installed come from an update URL, which defaults
1642 // to the webstore. Use a mock URL for this test with an update manifest
1643 // that includes "good_v1.crx".
1644 base::FilePath path
=
1645 base::FilePath(kTestExtensionsDir
).Append(kGoodV1CrxManifestName
);
1646 GURL
url(URLRequestMockHTTPJob::GetMockUrl(path
));
1648 // Setting the forcelist extension should install "good_v1.crx".
1649 base::ListValue forcelist
;
1650 forcelist
.Append(new base::StringValue(
1651 base::StringPrintf("%s;%s", kGoodCrxId
, url
.spec().c_str())));
1653 policies
.Set(key::kExtensionInstallForcelist
, POLICY_LEVEL_MANDATORY
,
1654 POLICY_SCOPE_USER
, forcelist
.DeepCopy(), NULL
);
1655 content::WindowedNotificationObserver
observer(
1656 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED
,
1657 content::NotificationService::AllSources());
1658 UpdateProviderPolicy(policies
);
1660 // Note: Cannot check that the notification details match the expected
1661 // exception, since the details object has already been freed prior to
1662 // the completion of observer.Wait().
1664 EXPECT_TRUE(service
->GetExtensionById(kGoodCrxId
, true));
1666 // The user is not allowed to uninstall force-installed extensions.
1667 UninstallExtension(kGoodCrxId
, false);
1669 // The user is not allowed to load an unpacked extension with the
1670 // same ID as a force-installed extension.
1671 LoadUnpackedExtension(kGoodUnpackedExt
, false);
1673 // Loading other unpacked extensions are not blocked.
1674 LoadUnpackedExtension(kAppUnpackedExt
, true);
1676 const std::string old_version_number
=
1677 service
->GetExtensionById(kGoodCrxId
, true)->version()->GetString();
1679 base::FilePath test_path
;
1680 ASSERT_TRUE(PathService::Get(chrome::DIR_TEST_DATA
, &test_path
));
1682 TestRequestInterceptor
interceptor(
1684 BrowserThread::GetMessageLoopProxyForThread(BrowserThread::IO
));
1685 interceptor
.PushJobCallback(
1686 TestRequestInterceptor::FileJob(
1687 test_path
.Append(kTestExtensionsDir
).Append(kGood2CrxManifestName
)));
1689 // Updating the force-installed extension.
1690 extensions::ExtensionUpdater
* updater
= service
->updater();
1691 extensions::ExtensionUpdater::CheckParams params
;
1692 params
.install_immediately
= true;
1693 content::WindowedNotificationObserver
update_observer(
1694 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED
,
1695 content::NotificationService::AllSources());
1696 updater
->CheckNow(params
);
1697 update_observer
.Wait();
1699 const base::Version
* new_version
=
1700 service
->GetExtensionById(kGoodCrxId
, true)->version();
1701 ASSERT_TRUE(new_version
->IsValid());
1702 base::Version
old_version(old_version_number
);
1703 ASSERT_TRUE(old_version
.IsValid());
1705 EXPECT_EQ(1, new_version
->CompareTo(old_version
));
1707 EXPECT_EQ(0u, interceptor
.GetPendingSize());
1709 // Wait until any background pages belonging to force-installed extensions
1710 // have been loaded.
1711 extensions::ProcessManager
* manager
=
1712 extensions::ExtensionSystem::Get(browser()->profile())->process_manager();
1713 extensions::ProcessManager::ViewSet all_views
= manager
->GetAllViews();
1714 for (extensions::ProcessManager::ViewSet::const_iterator iter
=
1716 iter
!= all_views
.end();) {
1717 if (!(*iter
)->IsLoading()) {
1720 content::WebContents
* web_contents
=
1721 content::WebContents::FromRenderViewHost(*iter
);
1722 ASSERT_TRUE(web_contents
);
1723 WebContentsLoadedOrDestroyedWatcher(web_contents
).Wait();
1725 // Test activity may have modified the set of extension processes during
1726 // message processing, so re-start the iteration to catch added/removed
1728 all_views
= manager
->GetAllViews();
1729 iter
= all_views
.begin();
1733 // Test policy-installed extensions are reloaded when killed.
1734 BackgroundContentsService::
1735 SetRestartDelayForForceInstalledAppsAndExtensionsForTesting(0);
1736 content::WindowedNotificationObserver
extension_crashed_observer(
1737 extensions::NOTIFICATION_EXTENSION_PROCESS_TERMINATED
,
1738 content::NotificationService::AllSources());
1739 content::WindowedNotificationObserver
extension_loaded_observer(
1740 extensions::NOTIFICATION_EXTENSION_LOADED_DEPRECATED
,
1741 content::NotificationService::AllSources());
1742 extensions::ExtensionHost
* extension_host
=
1743 extensions::ExtensionSystem::Get(browser()->profile())->
1744 process_manager()->GetBackgroundHostForExtension(kGoodCrxId
);
1745 base::KillProcess(extension_host
->render_process_host()->GetHandle(),
1746 content::RESULT_CODE_KILLED
, false);
1747 extension_crashed_observer
.Wait();
1748 extension_loaded_observer
.Wait();
1751 IN_PROC_BROWSER_TEST_F(PolicyTest
, ExtensionRecommendedInstallationMode
) {
1752 // Verifies that extensions that are recommended-installed by policies are
1753 // installed, can be disabled but not uninstalled.
1754 ExtensionService
* service
= extension_service();
1755 ASSERT_FALSE(service
->GetExtensionById(kGoodCrxId
, true));
1757 base::FilePath path
=
1758 base::FilePath(kTestExtensionsDir
).Append(kGoodV1CrxManifestName
);
1759 GURL
url(URLRequestMockHTTPJob::GetMockUrl(path
));
1761 // Setting the forcelist extension should install "good_v1.crx".
1762 base::DictionaryValue dict_value
;
1763 dict_value
.SetString(std::string(kGoodCrxId
) + "." +
1764 extensions::schema_constants::kInstallationMode
,
1765 extensions::schema_constants::kNormalInstalled
);
1766 dict_value
.SetString(
1767 std::string(kGoodCrxId
) + "." + extensions::schema_constants::kUpdateUrl
,
1770 policies
.Set(key::kExtensionSettings
,
1771 POLICY_LEVEL_MANDATORY
,
1773 dict_value
.DeepCopy(),
1775 content::WindowedNotificationObserver
observer(
1776 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED
,
1777 content::NotificationService::AllSources());
1778 UpdateProviderPolicy(policies
);
1781 EXPECT_TRUE(service
->GetExtensionById(kGoodCrxId
, true));
1783 // The user is not allowed to uninstall recommended-installed extensions.
1784 UninstallExtension(kGoodCrxId
, false);
1786 // Explictly re-enables the extension.
1787 service
->EnableExtension(kGoodCrxId
);
1789 // But the user is allowed to disable them.
1790 EXPECT_TRUE(service
->IsExtensionEnabled(kGoodCrxId
));
1791 DisableExtension(kGoodCrxId
);
1792 EXPECT_FALSE(service
->IsExtensionEnabled(kGoodCrxId
));
1795 IN_PROC_BROWSER_TEST_F(PolicyTest
, ExtensionAllowedTypes
) {
1796 // Verifies that extensions are blocked if policy specifies an allowed types
1797 // list and the extension's type is not on that list.
1798 ExtensionService
* service
= extension_service();
1799 ASSERT_FALSE(service
->GetExtensionById(kGoodCrxId
, true));
1800 ASSERT_FALSE(service
->GetExtensionById(kHostedAppCrxId
, true));
1802 base::ListValue allowed_types
;
1803 allowed_types
.AppendString("hosted_app");
1805 policies
.Set(key::kExtensionAllowedTypes
, POLICY_LEVEL_MANDATORY
,
1806 POLICY_SCOPE_USER
, allowed_types
.DeepCopy(), NULL
);
1807 UpdateProviderPolicy(policies
);
1809 // "good.crx" is blocked.
1810 EXPECT_FALSE(InstallExtension(kGoodCrxName
));
1811 EXPECT_FALSE(service
->GetExtensionById(kGoodCrxId
, true));
1813 // "hosted_app.crx" is of a whitelisted type.
1814 const extensions::Extension
* hosted_app
= InstallExtension(kHostedAppCrxName
);
1815 ASSERT_TRUE(hosted_app
);
1816 EXPECT_EQ(kHostedAppCrxId
, hosted_app
->id());
1817 EXPECT_EQ(hosted_app
, service
->GetExtensionById(kHostedAppCrxId
, true));
1819 // The user can remove the extension.
1820 UninstallExtension(kHostedAppCrxId
, true);
1823 // Checks that a click on an extension CRX download triggers the extension
1824 // installation prompt without further user interaction when the source is
1825 // whitelisted by policy.
1826 // Flaky on windows; http://crbug.com/295729 .
1828 #define MAYBE_ExtensionInstallSources DISABLED_ExtensionInstallSources
1830 #define MAYBE_ExtensionInstallSources ExtensionInstallSources
1832 IN_PROC_BROWSER_TEST_F(PolicyTest
, MAYBE_ExtensionInstallSources
) {
1833 ExtensionInstallPrompt::g_auto_confirm_for_tests
=
1834 ExtensionInstallPrompt::ACCEPT
;
1836 const GURL
install_source_url(URLRequestMockHTTPJob::GetMockUrl(
1837 base::FilePath(FILE_PATH_LITERAL("extensions/*"))));
1838 const GURL
referrer_url(URLRequestMockHTTPJob::GetMockUrl(
1839 base::FilePath(FILE_PATH_LITERAL("policy/*"))));
1841 base::ScopedTempDir download_directory
;
1842 ASSERT_TRUE(download_directory
.CreateUniqueTempDir());
1843 DownloadPrefs
* download_prefs
=
1844 DownloadPrefs::FromBrowserContext(browser()->profile());
1845 download_prefs
->SetDownloadPath(download_directory
.path());
1847 const GURL
download_page_url(URLRequestMockHTTPJob::GetMockUrl(base::FilePath(
1848 FILE_PATH_LITERAL("policy/extension_install_sources_test.html"))));
1849 ui_test_utils::NavigateToURL(browser(), download_page_url
);
1851 // As long as the policy is not present, extensions are considered dangerous.
1852 content::DownloadTestObserverTerminal
download_observer(
1853 content::BrowserContext::GetDownloadManager(browser()->profile()), 1,
1854 content::DownloadTestObserver::ON_DANGEROUS_DOWNLOAD_DENY
);
1856 download_observer
.WaitForFinished();
1858 // Install the policy and trigger another download.
1859 base::ListValue install_sources
;
1860 install_sources
.AppendString(install_source_url
.spec());
1861 install_sources
.AppendString(referrer_url
.spec());
1863 policies
.Set(key::kExtensionInstallSources
, POLICY_LEVEL_MANDATORY
,
1864 POLICY_SCOPE_USER
, install_sources
.DeepCopy(), NULL
);
1865 UpdateProviderPolicy(policies
);
1867 content::WindowedNotificationObserver
observer(
1868 extensions::NOTIFICATION_EXTENSION_WILL_BE_INSTALLED_DEPRECATED
,
1869 content::NotificationService::AllSources());
1872 // Note: Cannot check that the notification details match the expected
1873 // exception, since the details object has already been freed prior to
1874 // the completion of observer.Wait().
1876 // The first extension shouldn't be present, the second should be there.
1877 EXPECT_FALSE(extension_service()->GetExtensionById(kGoodCrxId
, true));
1878 EXPECT_TRUE(extension_service()->GetExtensionById(kAdBlockCrxId
, false));
1881 IN_PROC_BROWSER_TEST_F(PolicyTest
, HomepageLocation
) {
1882 #if defined(OS_WIN) && defined(USE_ASH)
1883 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
1884 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshBrowserTests
))
1888 // Verifies that the homepage can be configured with policies.
1889 // Set a default, and check that the home button navigates there.
1890 browser()->profile()->GetPrefs()->SetString(
1891 prefs::kHomePage
, chrome::kChromeUIPolicyURL
);
1892 browser()->profile()->GetPrefs()->SetBoolean(
1893 prefs::kHomePageIsNewTabPage
, false);
1894 EXPECT_EQ(GURL(chrome::kChromeUIPolicyURL
),
1895 browser()->profile()->GetHomePage());
1896 content::WebContents
* contents
=
1897 browser()->tab_strip_model()->GetActiveWebContents();
1898 EXPECT_EQ(GURL(url::kAboutBlankURL
), contents
->GetURL());
1899 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_HOME
));
1900 EXPECT_EQ(GURL(chrome::kChromeUIPolicyURL
), contents
->GetURL());
1902 // Now override with policy.
1904 policies
.Set(key::kHomepageLocation
,
1905 POLICY_LEVEL_MANDATORY
,
1907 new base::StringValue(chrome::kChromeUICreditsURL
),
1909 UpdateProviderPolicy(policies
);
1910 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_HOME
));
1911 content::WaitForLoadStop(contents
);
1912 EXPECT_EQ(GURL(chrome::kChromeUICreditsURL
), contents
->GetURL());
1914 policies
.Set(key::kHomepageIsNewTabPage
,
1915 POLICY_LEVEL_MANDATORY
,
1917 new base::FundamentalValue(true),
1919 UpdateProviderPolicy(policies
);
1920 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_HOME
));
1921 content::WaitForLoadStop(contents
);
1922 EXPECT_EQ(GURL(chrome::kChromeUINewTabURL
), contents
->GetURL());
1925 IN_PROC_BROWSER_TEST_F(PolicyTest
, IncognitoEnabled
) {
1926 // Verifies that incognito windows can't be opened when disabled by policy.
1928 const BrowserList
* active_browser_list
=
1929 BrowserList::GetInstance(chrome::GetActiveDesktop());
1931 // Disable incognito via policy and verify that incognito windows can't be
1933 EXPECT_EQ(1u, active_browser_list
->size());
1934 EXPECT_FALSE(BrowserList::IsOffTheRecordSessionActive());
1936 policies
.Set(key::kIncognitoEnabled
,
1937 POLICY_LEVEL_MANDATORY
,
1939 new base::FundamentalValue(false),
1941 UpdateProviderPolicy(policies
);
1942 EXPECT_FALSE(chrome::ExecuteCommand(browser(), IDC_NEW_INCOGNITO_WINDOW
));
1943 EXPECT_EQ(1u, active_browser_list
->size());
1944 EXPECT_FALSE(BrowserList::IsOffTheRecordSessionActive());
1946 // Enable via policy and verify that incognito windows can be opened.
1947 policies
.Set(key::kIncognitoEnabled
,
1948 POLICY_LEVEL_MANDATORY
,
1950 new base::FundamentalValue(true),
1952 UpdateProviderPolicy(policies
);
1953 EXPECT_TRUE(chrome::ExecuteCommand(browser(), IDC_NEW_INCOGNITO_WINDOW
));
1954 EXPECT_EQ(2u, active_browser_list
->size());
1955 EXPECT_TRUE(BrowserList::IsOffTheRecordSessionActive());
1958 IN_PROC_BROWSER_TEST_F(PolicyTest
, Javascript
) {
1959 // Verifies that Javascript can be disabled.
1960 content::WebContents
* contents
=
1961 browser()->tab_strip_model()->GetActiveWebContents();
1962 EXPECT_TRUE(IsJavascriptEnabled(contents
));
1963 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS
));
1964 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS_CONSOLE
));
1965 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS_DEVICES
));
1967 // Disable Javascript via policy.
1969 policies
.Set(key::kJavascriptEnabled
,
1970 POLICY_LEVEL_MANDATORY
,
1972 new base::FundamentalValue(false),
1974 UpdateProviderPolicy(policies
);
1976 ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL
));
1977 EXPECT_FALSE(IsJavascriptEnabled(contents
));
1978 // Developer tools still work when javascript is disabled.
1979 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS
));
1980 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS_CONSOLE
));
1981 EXPECT_TRUE(chrome::IsCommandEnabled(browser(), IDC_DEV_TOOLS_DEVICES
));
1982 // Javascript is always enabled for the internal pages.
1983 ui_test_utils::NavigateToURL(browser(), GURL(chrome::kChromeUIAboutURL
));
1984 EXPECT_TRUE(IsJavascriptEnabled(contents
));
1986 // The javascript content setting policy overrides the javascript policy.
1987 ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL
));
1988 EXPECT_FALSE(IsJavascriptEnabled(contents
));
1989 policies
.Set(key::kDefaultJavaScriptSetting
,
1990 POLICY_LEVEL_MANDATORY
,
1992 new base::FundamentalValue(CONTENT_SETTING_ALLOW
),
1994 UpdateProviderPolicy(policies
);
1995 ui_test_utils::NavigateToURL(browser(), GURL(url::kAboutBlankURL
));
1996 EXPECT_TRUE(IsJavascriptEnabled(contents
));
1999 IN_PROC_BROWSER_TEST_F(PolicyTest
, NetworkPrediction
) {
2000 PrefService
* prefs
= browser()->profile()->GetPrefs();
2002 // Enabled by default.
2003 EXPECT_TRUE(IsNetworkPredictionEnabled(prefs
));
2005 // Disable by old, deprecated policy.
2007 policies
.Set(key::kDnsPrefetchingEnabled
,
2008 POLICY_LEVEL_MANDATORY
,
2010 new base::FundamentalValue(false),
2012 UpdateProviderPolicy(policies
);
2014 EXPECT_FALSE(IsNetworkPredictionEnabled(prefs
));
2016 // Enabled by new policy, this should override old one.
2018 key::kNetworkPredictionOptions
,
2019 POLICY_LEVEL_MANDATORY
,
2021 new base::FundamentalValue(chrome_browser_net::NETWORK_PREDICTION_ALWAYS
),
2023 UpdateProviderPolicy(policies
);
2025 EXPECT_TRUE(IsNetworkPredictionEnabled(prefs
));
2028 IN_PROC_BROWSER_TEST_F(PolicyTest
, SavingBrowserHistoryDisabled
) {
2029 // Verifies that browsing history is not saved.
2031 policies
.Set(key::kSavingBrowserHistoryDisabled
,
2032 POLICY_LEVEL_MANDATORY
,
2034 new base::FundamentalValue(true),
2036 UpdateProviderPolicy(policies
);
2037 GURL url
= ui_test_utils::GetTestUrl(
2038 base::FilePath(base::FilePath::kCurrentDirectory
),
2039 base::FilePath(FILE_PATH_LITERAL("empty.html")));
2040 ui_test_utils::NavigateToURL(browser(), url
);
2041 // Verify that the navigation wasn't saved in the history.
2042 ui_test_utils::HistoryEnumerator
enumerator1(browser()->profile());
2043 EXPECT_EQ(0u, enumerator1
.urls().size());
2045 // Now flip the policy and try again.
2046 policies
.Set(key::kSavingBrowserHistoryDisabled
,
2047 POLICY_LEVEL_MANDATORY
,
2049 new base::FundamentalValue(false),
2051 UpdateProviderPolicy(policies
);
2052 ui_test_utils::NavigateToURL(browser(), url
);
2053 // Verify that the navigation was saved in the history.
2054 ui_test_utils::HistoryEnumerator
enumerator2(browser()->profile());
2055 ASSERT_EQ(1u, enumerator2
.urls().size());
2056 EXPECT_EQ(url
, enumerator2
.urls()[0]);
2059 // http://crbug.com/241691 PolicyTest.TranslateEnabled is failing regularly.
2060 IN_PROC_BROWSER_TEST_F(PolicyTest
, DISABLED_TranslateEnabled
) {
2061 // TODO(port): Test corresponding bubble translate UX: http://crbug.com/383235
2062 if (TranslateService::IsTranslateBubbleEnabled())
2065 scoped_ptr
<test::CldDataHarness
> cld_data_scope
=
2066 test::CreateCldDataHarness();
2067 ASSERT_NO_FATAL_FAILURE(cld_data_scope
->Init());
2069 // Verifies that translate can be forced enabled or disabled by policy.
2071 // Get the InfoBarService, and verify that there are no infobars on startup.
2072 content::WebContents
* contents
=
2073 browser()->tab_strip_model()->GetActiveWebContents();
2074 ASSERT_TRUE(contents
);
2075 InfoBarService
* infobar_service
= InfoBarService::FromWebContents(contents
);
2076 ASSERT_TRUE(infobar_service
);
2077 EXPECT_EQ(0u, infobar_service
->infobar_count());
2079 // Force enable the translate feature.
2081 policies
.Set(key::kTranslateEnabled
,
2082 POLICY_LEVEL_MANDATORY
,
2084 new base::FundamentalValue(true),
2086 UpdateProviderPolicy(policies
);
2087 // Instead of waiting for NOTIFICATION_TAB_CONTENTS_INFOBAR_ADDED, this test
2088 // waits for NOTIFICATION_TAB_LANGUAGE_DETERMINED because that's what the
2089 // TranslateManager observes. This allows checking that an infobar is NOT
2090 // shown below, without polling for infobars for some indeterminate amount
2092 GURL url
= ui_test_utils::GetTestUrl(
2094 base::FilePath(FILE_PATH_LITERAL("translate/fr_test.html")));
2095 content::WindowedNotificationObserver
language_observer1(
2096 chrome::NOTIFICATION_TAB_LANGUAGE_DETERMINED
,
2097 content::NotificationService::AllSources());
2098 ui_test_utils::NavigateToURL(browser(), url
);
2099 language_observer1
.Wait();
2101 // Verify the translation detected for this tab.
2102 ChromeTranslateClient
* chrome_translate_client
=
2103 ChromeTranslateClient::FromWebContents(contents
);
2104 ASSERT_TRUE(chrome_translate_client
);
2105 translate::LanguageState
& language_state
=
2106 chrome_translate_client
->GetLanguageState();
2107 EXPECT_EQ("fr", language_state
.original_language());
2108 EXPECT_TRUE(language_state
.page_needs_translation());
2109 EXPECT_FALSE(language_state
.translation_pending());
2110 EXPECT_FALSE(language_state
.translation_declined());
2111 EXPECT_FALSE(language_state
.IsPageTranslated());
2113 // Verify that the translate infobar showed up.
2114 ASSERT_EQ(1u, infobar_service
->infobar_count());
2115 infobars::InfoBar
* infobar
= infobar_service
->infobar_at(0);
2116 translate::TranslateInfoBarDelegate
* translate_infobar_delegate
=
2117 infobar
->delegate()->AsTranslateInfoBarDelegate();
2118 ASSERT_TRUE(translate_infobar_delegate
);
2119 EXPECT_EQ(translate::TRANSLATE_STEP_BEFORE_TRANSLATE
,
2120 translate_infobar_delegate
->translate_step());
2121 EXPECT_EQ("fr", translate_infobar_delegate
->original_language_code());
2123 // Now force disable translate.
2124 infobar_service
->RemoveInfoBar(infobar
);
2125 EXPECT_EQ(0u, infobar_service
->infobar_count());
2126 policies
.Set(key::kTranslateEnabled
,
2127 POLICY_LEVEL_MANDATORY
,
2129 new base::FundamentalValue(false),
2131 UpdateProviderPolicy(policies
);
2132 // Navigating to the same URL now doesn't trigger an infobar.
2133 content::WindowedNotificationObserver
language_observer2(
2134 chrome::NOTIFICATION_TAB_LANGUAGE_DETERMINED
,
2135 content::NotificationService::AllSources());
2136 ui_test_utils::NavigateToURL(browser(), url
);
2137 language_observer2
.Wait();
2138 EXPECT_EQ(0u, infobar_service
->infobar_count());
2141 IN_PROC_BROWSER_TEST_F(PolicyTest
, URLBlacklist
) {
2142 // Checks that URLs can be blacklisted, and that exceptions can be made to
2145 // Filter |kURLS| on IO thread, so that requests to those hosts end up
2146 // as URLRequestMockHTTPJobs.
2147 const char* kURLS
[] = {
2148 "http://aaa.com/empty.html",
2149 "http://bbb.com/empty.html",
2150 "http://sub.bbb.com/empty.html",
2151 "http://bbb.com/policy/blank.html",
2155 BrowserThread::PostTaskAndReply(
2156 BrowserThread::IO
, FROM_HERE
,
2157 base::Bind(RedirectHostsToTestData
, kURLS
, arraysize(kURLS
)),
2158 loop
.QuitClosure());
2162 // Verify that "bbb.com" opens before applying the blacklist.
2163 CheckCanOpenURL(browser(), kURLS
[1]);
2166 base::ListValue blacklist
;
2167 blacklist
.Append(new base::StringValue("bbb.com"));
2169 policies
.Set(key::kURLBlacklist
, POLICY_LEVEL_MANDATORY
,
2170 POLICY_SCOPE_USER
, blacklist
.DeepCopy(), NULL
);
2171 UpdateProviderPolicy(policies
);
2172 FlushBlacklistPolicy();
2173 // All bbb.com URLs are blocked, and "aaa.com" is still unblocked.
2174 CheckCanOpenURL(browser(), kURLS
[0]);
2175 for (size_t i
= 1; i
< arraysize(kURLS
); ++i
)
2176 CheckURLIsBlocked(browser(), kURLS
[i
]);
2178 // Whitelist some sites of bbb.com.
2179 base::ListValue whitelist
;
2180 whitelist
.Append(new base::StringValue("sub.bbb.com"));
2181 whitelist
.Append(new base::StringValue("bbb.com/policy"));
2182 policies
.Set(key::kURLWhitelist
, POLICY_LEVEL_MANDATORY
,
2183 POLICY_SCOPE_USER
, whitelist
.DeepCopy(), NULL
);
2184 UpdateProviderPolicy(policies
);
2185 FlushBlacklistPolicy();
2186 CheckURLIsBlocked(browser(), kURLS
[1]);
2187 CheckCanOpenURL(browser(), kURLS
[2]);
2188 CheckCanOpenURL(browser(), kURLS
[3]);
2192 BrowserThread::PostTaskAndReply(
2193 BrowserThread::IO
, FROM_HERE
,
2194 base::Bind(UndoRedirectHostsToTestData
, kURLS
, arraysize(kURLS
)),
2195 loop
.QuitClosure());
2200 #if defined(OS_MACOSX)
2201 // http://crbug.com/339240
2202 #define MAYBE_FileURLBlacklist DISABLED_FileURLBlacklist
2204 #define MAYBE_FileURLBlacklist FileURLBlacklist
2206 IN_PROC_BROWSER_TEST_F(PolicyTest
, MAYBE_FileURLBlacklist
) {
2207 // Check that FileURLs can be blacklisted and DisabledSchemes works together
2208 // with URLblacklisting and URLwhitelisting.
2210 base::FilePath test_path
;
2211 PathService::Get(chrome::DIR_TEST_DATA
, &test_path
);
2212 const std::string base_path
= "file://" + test_path
.AsUTF8Unsafe() +"/";
2213 const std::string folder_path
= base_path
+ "apptest/";
2214 const std::string file_path1
= base_path
+ "title1.html";
2215 const std::string file_path2
= folder_path
+ "basic.html";
2217 CheckCanOpenURL(browser(), file_path1
.c_str());
2218 CheckCanOpenURL(browser(), file_path2
.c_str());
2220 // Set a blacklist for all the files.
2221 base::ListValue blacklist
;
2222 blacklist
.Append(new base::StringValue("file://*"));
2224 policies
.Set(key::kURLBlacklist
, POLICY_LEVEL_MANDATORY
,
2225 POLICY_SCOPE_USER
, blacklist
.DeepCopy(), NULL
);
2226 UpdateProviderPolicy(policies
);
2227 FlushBlacklistPolicy();
2229 CheckURLIsBlocked(browser(), file_path1
.c_str());
2230 CheckURLIsBlocked(browser(), file_path2
.c_str());
2232 // Replace the URLblacklist with disabling the file scheme.
2233 blacklist
.Remove(base::StringValue("file://*"), NULL
);
2234 policies
.Set(key::kURLBlacklist
, POLICY_LEVEL_MANDATORY
,
2235 POLICY_SCOPE_USER
, blacklist
.DeepCopy(), NULL
);
2236 UpdateProviderPolicy(policies
);
2237 FlushBlacklistPolicy();
2239 PrefService
* prefs
= browser()->profile()->GetPrefs();
2240 const base::ListValue
* list_url
= prefs
->GetList(policy_prefs::kUrlBlacklist
);
2241 EXPECT_EQ(list_url
->Find(base::StringValue("file://*")),
2244 base::ListValue disabledscheme
;
2245 disabledscheme
.Append(new base::StringValue("file"));
2246 policies
.Set(key::kDisabledSchemes
, POLICY_LEVEL_MANDATORY
,
2247 POLICY_SCOPE_USER
, disabledscheme
.DeepCopy(), NULL
);
2248 UpdateProviderPolicy(policies
);
2249 FlushBlacklistPolicy();
2251 list_url
= prefs
->GetList(policy_prefs::kUrlBlacklist
);
2252 EXPECT_NE(list_url
->Find(base::StringValue("file://*")),
2255 // Whitelist one folder and blacklist an another just inside.
2256 base::ListValue whitelist
;
2257 whitelist
.Append(new base::StringValue(base_path
));
2258 policies
.Set(key::kURLWhitelist
, POLICY_LEVEL_MANDATORY
,
2259 POLICY_SCOPE_USER
, whitelist
.DeepCopy(), NULL
);
2260 blacklist
.Append(new base::StringValue(folder_path
));
2261 policies
.Set(key::kURLBlacklist
, POLICY_LEVEL_MANDATORY
,
2262 POLICY_SCOPE_USER
, blacklist
.DeepCopy(), NULL
);
2263 UpdateProviderPolicy(policies
);
2264 FlushBlacklistPolicy();
2266 CheckCanOpenURL(browser(), file_path1
.c_str());
2267 CheckURLIsBlocked(browser(), file_path2
.c_str());
2270 static bool IsMinSSLVersionTLS12(Profile
* profile
) {
2271 scoped_refptr
<net::SSLConfigService
> config_service(
2272 profile
->GetSSLConfigService());
2273 net::SSLConfig config
;
2274 config_service
->GetSSLConfig(&config
);
2275 return config
.version_min
== net::SSL_PROTOCOL_VERSION_TLS1_2
;
2278 IN_PROC_BROWSER_TEST_F(PolicyTest
, SSLVersionMin
) {
2279 PrefService
* prefs
= g_browser_process
->local_state();
2281 const std::string
new_value("tls1.2");
2282 const std::string
default_value(prefs
->GetString(prefs::kSSLVersionMin
));
2284 EXPECT_NE(default_value
, new_value
);
2285 EXPECT_FALSE(IsMinSSLVersionTLS12(browser()->profile()));
2288 policies
.Set(key::kSSLVersionMin
,
2289 POLICY_LEVEL_MANDATORY
,
2291 new base::StringValue(new_value
),
2293 UpdateProviderPolicy(policies
);
2295 EXPECT_TRUE(IsMinSSLVersionTLS12(browser()->profile()));
2298 static bool IsMinSSLFallbackVersionTLS12(Profile
* profile
) {
2299 scoped_refptr
<net::SSLConfigService
> config_service(
2300 profile
->GetSSLConfigService());
2301 net::SSLConfig config
;
2302 config_service
->GetSSLConfig(&config
);
2303 return config
.version_fallback_min
== net::SSL_PROTOCOL_VERSION_TLS1_2
;
2306 IN_PROC_BROWSER_TEST_F(PolicyTest
, SSLVersionFallbackMin
) {
2307 PrefService
* prefs
= g_browser_process
->local_state();
2309 const std::string
new_value("tls1.2");
2310 const std::string
default_value(
2311 prefs
->GetString(prefs::kSSLVersionFallbackMin
));
2313 EXPECT_NE(default_value
, new_value
);
2314 EXPECT_FALSE(IsMinSSLFallbackVersionTLS12(browser()->profile()));
2317 policies
.Set(key::kSSLVersionFallbackMin
,
2318 POLICY_LEVEL_MANDATORY
,
2320 new base::StringValue(new_value
),
2322 UpdateProviderPolicy(policies
);
2324 EXPECT_TRUE(IsMinSSLFallbackVersionTLS12(browser()->profile()));
2327 #if !defined(OS_MACOSX)
2328 IN_PROC_BROWSER_TEST_F(PolicyTest
, FullscreenAllowedBrowser
) {
2330 policies
.Set(key::kFullscreenAllowed
,
2331 POLICY_LEVEL_MANDATORY
,
2333 new base::FundamentalValue(false),
2335 UpdateProviderPolicy(policies
);
2337 BrowserWindow
* browser_window
= browser()->window();
2338 ASSERT_TRUE(browser_window
);
2340 EXPECT_FALSE(browser_window
->IsFullscreen());
2341 chrome::ToggleFullscreenMode(browser());
2342 EXPECT_FALSE(browser_window
->IsFullscreen());
2345 IN_PROC_BROWSER_TEST_F(PolicyTest
, FullscreenAllowedApp
) {
2347 policies
.Set(key::kFullscreenAllowed
,
2348 POLICY_LEVEL_MANDATORY
,
2350 new base::FundamentalValue(false),
2352 UpdateProviderPolicy(policies
);
2354 const extensions::Extension
* extension
=
2355 LoadUnpackedExtension(kUnpackedFullscreenAppName
, true);
2356 ASSERT_TRUE(extension
);
2358 // Launch an app that tries to open a fullscreen window.
2359 TestAddAppWindowObserver
add_window_observer(
2360 extensions::AppWindowRegistry::Get(browser()->profile()));
2361 OpenApplication(AppLaunchParams(browser()->profile(),
2363 extensions::LAUNCH_CONTAINER_NONE
,
2365 extensions::AppWindow
* window
= add_window_observer
.WaitForAppWindow();
2366 ASSERT_TRUE(window
);
2368 // Verify that the window is not in fullscreen mode.
2369 EXPECT_FALSE(window
->GetBaseWindow()->IsFullscreen());
2371 // Verify that the window cannot be toggled into fullscreen mode via apps
2373 EXPECT_TRUE(content::ExecuteScript(
2374 window
->web_contents(),
2375 "chrome.app.window.current().fullscreen();"));
2376 EXPECT_FALSE(window
->GetBaseWindow()->IsFullscreen());
2378 // Verify that the window cannot be toggled into fullscreen mode from within
2379 // Chrome (e.g., using keyboard accelerators).
2380 window
->Fullscreen();
2381 EXPECT_FALSE(window
->GetBaseWindow()->IsFullscreen());
2385 #if defined(OS_CHROMEOS)
2386 IN_PROC_BROWSER_TEST_F(PolicyTest
, DisableScreenshotsFile
) {
2387 int screenshot_count
= CountScreenshots();
2389 // Make sure screenshots are counted correctly.
2390 TestScreenshotFile(true);
2391 ASSERT_EQ(CountScreenshots(), screenshot_count
+ 1);
2393 // Check if trying to take a screenshot fails when disabled by policy.
2394 TestScreenshotFile(false);
2395 ASSERT_EQ(CountScreenshots(), screenshot_count
+ 1);
2398 IN_PROC_BROWSER_TEST_F(PolicyTest
, DisableAudioOutput
) {
2399 // Set up the mock observer.
2400 chromeos::CrasAudioHandler
* audio_handler
= chromeos::CrasAudioHandler::Get();
2401 scoped_ptr
<TestAudioObserver
> test_observer(new TestAudioObserver
);
2402 audio_handler
->AddAudioObserver(test_observer
.get());
2404 bool prior_state
= audio_handler
->IsOutputMuted();
2405 // Make sure the audio is not muted and then toggle the policy and observe
2406 // if the output mute changed event is fired.
2407 audio_handler
->SetOutputMute(false);
2408 EXPECT_FALSE(audio_handler
->IsOutputMuted());
2409 EXPECT_EQ(1, test_observer
->output_mute_changed_count());
2411 policies
.Set(key::kAudioOutputAllowed
,
2412 POLICY_LEVEL_MANDATORY
,
2414 new base::FundamentalValue(false),
2416 UpdateProviderPolicy(policies
);
2417 EXPECT_TRUE(audio_handler
->IsOutputMuted());
2418 // This should not change the state now and should not trigger output mute
2420 audio_handler
->SetOutputMute(false);
2421 EXPECT_TRUE(audio_handler
->IsOutputMuted());
2422 EXPECT_EQ(1, test_observer
->output_mute_changed_count());
2424 // Toggle back and observe if the output mute changed event is fired.
2425 policies
.Set(key::kAudioOutputAllowed
,
2426 POLICY_LEVEL_MANDATORY
,
2428 new base::FundamentalValue(true),
2430 UpdateProviderPolicy(policies
);
2431 EXPECT_FALSE(audio_handler
->IsOutputMuted());
2432 EXPECT_EQ(1, test_observer
->output_mute_changed_count());
2433 audio_handler
->SetOutputMute(true);
2434 EXPECT_TRUE(audio_handler
->IsOutputMuted());
2435 EXPECT_EQ(2, test_observer
->output_mute_changed_count());
2436 // Revert the prior state.
2437 audio_handler
->SetOutputMute(prior_state
);
2438 audio_handler
->RemoveAudioObserver(test_observer
.get());
2441 // Disabled, see http://crbug.com/315308.
2442 IN_PROC_BROWSER_TEST_F(PolicyTest
, DISABLED_PRE_SessionLengthLimit
) {
2443 // Indicate that the session started 2 hours ago and no user activity has
2445 g_browser_process
->local_state()->SetInt64(
2446 prefs::kSessionStartTime
,
2447 (base::TimeTicks::Now() - base::TimeDelta::FromHours(2))
2448 .ToInternalValue());
2451 // Disabled, see http://crbug.com/315308.
2452 IN_PROC_BROWSER_TEST_F(PolicyTest
, DISABLED_SessionLengthLimit
) {
2453 content::MockNotificationObserver observer
;
2454 content::NotificationRegistrar registrar
;
2455 registrar
.Add(&observer
,
2456 chrome::NOTIFICATION_APP_TERMINATING
,
2457 content::NotificationService::AllSources());
2459 // Set the session length limit to 3 hours. Verify that the session is not
2461 EXPECT_CALL(observer
, Observe(chrome::NOTIFICATION_APP_TERMINATING
, _
, _
))
2464 policies
.Set(key::kSessionLengthLimit
,
2465 POLICY_LEVEL_MANDATORY
,
2467 new base::FundamentalValue(kThreeHoursInMs
),
2469 UpdateProviderPolicy(policies
);
2470 base::RunLoop().RunUntilIdle();
2471 Mock::VerifyAndClearExpectations(&observer
);
2473 // Decrease the session length limit to 1 hour. Verify that the session is
2474 // terminated immediately.
2475 EXPECT_CALL(observer
, Observe(chrome::NOTIFICATION_APP_TERMINATING
, _
, _
));
2476 policies
.Set(key::kSessionLengthLimit
,
2477 POLICY_LEVEL_MANDATORY
,
2479 new base::FundamentalValue(kOneHourInMs
),
2481 UpdateProviderPolicy(policies
);
2482 base::RunLoop().RunUntilIdle();
2483 Mock::VerifyAndClearExpectations(&observer
);
2486 // Disabled, see http://crbug.com/315308.
2487 IN_PROC_BROWSER_TEST_F(PolicyTest
,
2488 DISABLED_PRE_WaitForInitialUserActivityUsatisfied
) {
2489 // Indicate that the session started 2 hours ago and no user activity has
2491 g_browser_process
->local_state()->SetInt64(
2492 prefs::kSessionStartTime
,
2493 (base::TimeTicks::Now() - base::TimeDelta::FromHours(2))
2494 .ToInternalValue());
2497 // Disabled, see http://crbug.com/315308.
2498 IN_PROC_BROWSER_TEST_F(PolicyTest
,
2499 DISABLED_WaitForInitialUserActivityUsatisfied
) {
2500 content::MockNotificationObserver observer
;
2501 content::NotificationRegistrar registrar
;
2502 registrar
.Add(&observer
,
2503 chrome::NOTIFICATION_APP_TERMINATING
,
2504 content::NotificationService::AllSources());
2506 // Require initial user activity.
2508 policies
.Set(key::kWaitForInitialUserActivity
, POLICY_LEVEL_MANDATORY
,
2510 new base::FundamentalValue(true),
2512 UpdateProviderPolicy(policies
);
2513 base::RunLoop().RunUntilIdle();
2515 // Set the session length limit to 1 hour. Verify that the session is not
2517 EXPECT_CALL(observer
, Observe(chrome::NOTIFICATION_APP_TERMINATING
, _
, _
))
2519 policies
.Set(key::kSessionLengthLimit
,
2520 POLICY_LEVEL_MANDATORY
,
2522 new base::FundamentalValue(kOneHourInMs
),
2524 UpdateProviderPolicy(policies
);
2525 base::RunLoop().RunUntilIdle();
2526 Mock::VerifyAndClearExpectations(&observer
);
2529 // Disabled, see http://crbug.com/315308.
2530 IN_PROC_BROWSER_TEST_F(PolicyTest
,
2531 DISABLED_PRE_WaitForInitialUserActivitySatisfied
) {
2532 // Indicate that initial user activity in this session occurred 2 hours ago.
2533 g_browser_process
->local_state()->SetInt64(
2534 prefs::kSessionStartTime
,
2535 (base::TimeTicks::Now() - base::TimeDelta::FromHours(2))
2536 .ToInternalValue());
2537 g_browser_process
->local_state()->SetBoolean(
2538 prefs::kSessionUserActivitySeen
,
2542 // Disabled, see http://crbug.com/315308.
2543 IN_PROC_BROWSER_TEST_F(PolicyTest
,
2544 DISABLED_WaitForInitialUserActivitySatisfied
) {
2545 content::MockNotificationObserver observer
;
2546 content::NotificationRegistrar registrar
;
2547 registrar
.Add(&observer
,
2548 chrome::NOTIFICATION_APP_TERMINATING
,
2549 content::NotificationService::AllSources());
2551 // Require initial user activity and set the session length limit to 3 hours.
2552 // Verify that the session is not terminated.
2553 EXPECT_CALL(observer
, Observe(chrome::NOTIFICATION_APP_TERMINATING
, _
, _
))
2556 policies
.Set(key::kWaitForInitialUserActivity
, POLICY_LEVEL_MANDATORY
,
2558 new base::FundamentalValue(true),
2560 policies
.Set(key::kSessionLengthLimit
,
2561 POLICY_LEVEL_MANDATORY
,
2563 new base::FundamentalValue(kThreeHoursInMs
),
2565 UpdateProviderPolicy(policies
);
2566 base::RunLoop().RunUntilIdle();
2567 Mock::VerifyAndClearExpectations(&observer
);
2569 // Decrease the session length limit to 1 hour. Verify that the session is
2570 // terminated immediately.
2571 EXPECT_CALL(observer
, Observe(chrome::NOTIFICATION_APP_TERMINATING
, _
, _
));
2572 policies
.Set(key::kSessionLengthLimit
,
2573 POLICY_LEVEL_MANDATORY
,
2575 new base::FundamentalValue(kOneHourInMs
),
2577 UpdateProviderPolicy(policies
);
2578 base::RunLoop().RunUntilIdle();
2579 Mock::VerifyAndClearExpectations(&observer
);
2582 IN_PROC_BROWSER_TEST_F(PolicyTest
, LargeCursorEnabled
) {
2583 // Verifies that the large cursor accessibility feature can be controlled
2585 chromeos::AccessibilityManager
* accessibility_manager
=
2586 chromeos::AccessibilityManager::Get();
2588 // Manually enable the large cursor.
2589 accessibility_manager
->EnableLargeCursor(true);
2590 EXPECT_TRUE(accessibility_manager
->IsLargeCursorEnabled());
2592 // Verify that policy overrides the manual setting.
2594 policies
.Set(key::kLargeCursorEnabled
,
2595 POLICY_LEVEL_MANDATORY
,
2597 new base::FundamentalValue(false),
2599 UpdateProviderPolicy(policies
);
2600 EXPECT_FALSE(accessibility_manager
->IsLargeCursorEnabled());
2602 // Verify that the large cursor cannot be enabled manually anymore.
2603 accessibility_manager
->EnableLargeCursor(true);
2604 EXPECT_FALSE(accessibility_manager
->IsLargeCursorEnabled());
2607 IN_PROC_BROWSER_TEST_F(PolicyTest
, SpokenFeedbackEnabled
) {
2608 // Verifies that the spoken feedback accessibility feature can be controlled
2610 chromeos::AccessibilityManager
* accessibility_manager
=
2611 chromeos::AccessibilityManager::Get();
2613 // Manually enable spoken feedback.
2614 accessibility_manager
->EnableSpokenFeedback(
2615 true, ash::A11Y_NOTIFICATION_NONE
);
2616 EXPECT_TRUE(accessibility_manager
->IsSpokenFeedbackEnabled());
2618 // Verify that policy overrides the manual setting.
2620 policies
.Set(key::kSpokenFeedbackEnabled
,
2621 POLICY_LEVEL_MANDATORY
,
2623 new base::FundamentalValue(false),
2625 UpdateProviderPolicy(policies
);
2626 EXPECT_FALSE(accessibility_manager
->IsSpokenFeedbackEnabled());
2628 // Verify that spoken feedback cannot be enabled manually anymore.
2629 accessibility_manager
->EnableSpokenFeedback(
2630 true, ash::A11Y_NOTIFICATION_NONE
);
2631 EXPECT_FALSE(accessibility_manager
->IsSpokenFeedbackEnabled());
2634 IN_PROC_BROWSER_TEST_F(PolicyTest
, HighContrastEnabled
) {
2635 // Verifies that the high contrast mode accessibility feature can be
2636 // controlled through policy.
2637 chromeos::AccessibilityManager
* accessibility_manager
=
2638 chromeos::AccessibilityManager::Get();
2640 // Manually enable high contrast mode.
2641 accessibility_manager
->EnableHighContrast(true);
2642 EXPECT_TRUE(accessibility_manager
->IsHighContrastEnabled());
2644 // Verify that policy overrides the manual setting.
2646 policies
.Set(key::kHighContrastEnabled
,
2647 POLICY_LEVEL_MANDATORY
,
2649 new base::FundamentalValue(false),
2651 UpdateProviderPolicy(policies
);
2652 EXPECT_FALSE(accessibility_manager
->IsHighContrastEnabled());
2654 // Verify that high contrast mode cannot be enabled manually anymore.
2655 accessibility_manager
->EnableHighContrast(true);
2656 EXPECT_FALSE(accessibility_manager
->IsHighContrastEnabled());
2659 IN_PROC_BROWSER_TEST_F(PolicyTest
, ScreenMagnifierTypeNone
) {
2660 // Verifies that the screen magnifier can be disabled through policy.
2661 chromeos::MagnificationManager
* magnification_manager
=
2662 chromeos::MagnificationManager::Get();
2664 // Manually enable the full-screen magnifier.
2665 magnification_manager
->SetMagnifierType(ash::MAGNIFIER_FULL
);
2666 magnification_manager
->SetMagnifierEnabled(true);
2667 EXPECT_EQ(ash::MAGNIFIER_FULL
, magnification_manager
->GetMagnifierType());
2668 EXPECT_TRUE(magnification_manager
->IsMagnifierEnabled());
2670 // Verify that policy overrides the manual setting.
2672 policies
.Set(key::kScreenMagnifierType
,
2673 POLICY_LEVEL_MANDATORY
,
2675 new base::FundamentalValue(0),
2677 UpdateProviderPolicy(policies
);
2678 EXPECT_FALSE(magnification_manager
->IsMagnifierEnabled());
2680 // Verify that the screen magnifier cannot be enabled manually anymore.
2681 magnification_manager
->SetMagnifierEnabled(true);
2682 EXPECT_FALSE(magnification_manager
->IsMagnifierEnabled());
2685 IN_PROC_BROWSER_TEST_F(PolicyTest
, ScreenMagnifierTypeFull
) {
2686 // Verifies that the full-screen magnifier can be enabled through policy.
2687 chromeos::MagnificationManager
* magnification_manager
=
2688 chromeos::MagnificationManager::Get();
2690 // Verify that the screen magnifier is initially disabled.
2691 EXPECT_FALSE(magnification_manager
->IsMagnifierEnabled());
2693 // Verify that policy can enable the full-screen magnifier.
2695 policies
.Set(key::kScreenMagnifierType
,
2696 POLICY_LEVEL_MANDATORY
,
2698 new base::FundamentalValue(ash::MAGNIFIER_FULL
),
2700 UpdateProviderPolicy(policies
);
2701 EXPECT_EQ(ash::MAGNIFIER_FULL
, magnification_manager
->GetMagnifierType());
2702 EXPECT_TRUE(magnification_manager
->IsMagnifierEnabled());
2704 // Verify that the screen magnifier cannot be disabled manually anymore.
2705 magnification_manager
->SetMagnifierEnabled(false);
2706 EXPECT_TRUE(magnification_manager
->IsMagnifierEnabled());
2709 IN_PROC_BROWSER_TEST_F(PolicyTest
, AccessibilityVirtualKeyboardEnabled
) {
2710 // Verifies that the on-screen keyboard accessibility feature can be
2711 // controlled through policy.
2712 chromeos::AccessibilityManager
* accessibility_manager
=
2713 chromeos::AccessibilityManager::Get();
2715 // Manually enable the on-screen keyboard.
2716 accessibility_manager
->EnableVirtualKeyboard(true);
2717 EXPECT_TRUE(accessibility_manager
->IsVirtualKeyboardEnabled());
2719 // Verify that policy overrides the manual setting.
2721 policies
.Set(key::kVirtualKeyboardEnabled
,
2722 POLICY_LEVEL_MANDATORY
,
2724 new base::FundamentalValue(false),
2726 UpdateProviderPolicy(policies
);
2727 EXPECT_FALSE(accessibility_manager
->IsVirtualKeyboardEnabled());
2729 // Verify that the on-screen keyboard cannot be enabled manually anymore.
2730 accessibility_manager
->EnableVirtualKeyboard(true);
2731 EXPECT_FALSE(accessibility_manager
->IsVirtualKeyboardEnabled());
2734 IN_PROC_BROWSER_TEST_F(PolicyTest
, VirtualKeyboardEnabled
) {
2735 // Verify keyboard disabled by default.
2736 EXPECT_FALSE(keyboard::IsKeyboardEnabled());
2737 // Verify keyboard can be toggled by default.
2738 keyboard::SetTouchKeyboardEnabled(true);
2739 EXPECT_TRUE(keyboard::IsKeyboardEnabled());
2740 keyboard::SetTouchKeyboardEnabled(false);
2741 EXPECT_FALSE(keyboard::IsKeyboardEnabled());
2743 // Verify enabling the policy takes effect immediately and that that user
2744 // cannot disable the keyboard..
2746 policies
.Set(key::kTouchVirtualKeyboardEnabled
,
2747 POLICY_LEVEL_MANDATORY
,
2749 new base::FundamentalValue(true),
2751 UpdateProviderPolicy(policies
);
2752 EXPECT_TRUE(keyboard::IsKeyboardEnabled());
2753 keyboard::SetTouchKeyboardEnabled(false);
2754 EXPECT_TRUE(keyboard::IsKeyboardEnabled());
2756 // Verify that disabling the policy takes effect immediately and that the user
2757 // cannot enable the keyboard.
2758 policies
.Set(key::kTouchVirtualKeyboardEnabled
,
2759 POLICY_LEVEL_MANDATORY
,
2761 new base::FundamentalValue(false),
2763 UpdateProviderPolicy(policies
);
2764 EXPECT_FALSE(keyboard::IsKeyboardEnabled());
2765 keyboard::SetTouchKeyboardEnabled(true);
2766 EXPECT_FALSE(keyboard::IsKeyboardEnabled());
2773 static const char* kRestoredURLs
[] = {
2774 "http://aaa.com/empty.html",
2775 "http://bbb.com/empty.html",
2778 bool IsNonSwitchArgument(const CommandLine::StringType
& s
) {
2779 return s
.empty() || s
[0] != '-';
2784 // Similar to PolicyTest but allows setting policies before the browser is
2785 // created. Each test parameter is a method that sets up the early policies
2786 // and stores the expected startup URLs in |expected_urls_|.
2787 class RestoreOnStartupPolicyTest
2788 : public PolicyTest
,
2789 public testing::WithParamInterface
<
2790 void (RestoreOnStartupPolicyTest::*)(void)> {
2792 RestoreOnStartupPolicyTest() {}
2793 virtual ~RestoreOnStartupPolicyTest() {}
2795 #if defined(OS_CHROMEOS)
2796 virtual void SetUpCommandLine(CommandLine
* command_line
) override
{
2797 // TODO(nkostylev): Investigate if we can remove this switch.
2798 command_line
->AppendSwitch(switches::kCreateBrowserOnStartupForTests
);
2799 PolicyTest::SetUpCommandLine(command_line
);
2803 virtual void SetUpInProcessBrowserTestFixture() override
{
2804 PolicyTest::SetUpInProcessBrowserTestFixture();
2805 // Set early policies now, before the browser is created.
2806 (this->*(GetParam()))();
2808 // Remove the non-switch arguments, so that session restore kicks in for
2810 CommandLine
* command_line
= CommandLine::ForCurrentProcess();
2811 CommandLine::StringVector argv
= command_line
->argv();
2812 argv
.erase(std::remove_if(++argv
.begin(), argv
.end(), IsNonSwitchArgument
),
2814 command_line
->InitFromArgv(argv
);
2815 ASSERT_TRUE(std::equal(argv
.begin(), argv
.end(),
2816 command_line
->argv().begin()));
2819 virtual void SetUpOnMainThread() override
{
2820 BrowserThread::PostTask(
2824 RedirectHostsToTestData
, kRestoredURLs
, arraysize(kRestoredURLs
)));
2827 void HomepageIsNotNTP() {
2828 // Verifies that policy can set the startup pages to the homepage, when
2829 // the homepage is not the NTP.
2832 key::kRestoreOnStartup
,
2833 POLICY_LEVEL_MANDATORY
,
2835 new base::FundamentalValue(SessionStartupPref::kPrefValueHomePage
),
2837 policies
.Set(key::kHomepageIsNewTabPage
,
2838 POLICY_LEVEL_MANDATORY
,
2840 new base::FundamentalValue(false),
2842 policies
.Set(key::kHomepageLocation
,
2843 POLICY_LEVEL_MANDATORY
,
2845 new base::StringValue(kRestoredURLs
[1]),
2847 provider_
.UpdateChromePolicy(policies
);
2849 expected_urls_
.push_back(GURL(kRestoredURLs
[1]));
2852 void HomepageIsNTP() {
2853 // Verifies that policy can set the startup pages to the homepage, when
2854 // the homepage is the NTP.
2857 key::kRestoreOnStartup
,
2858 POLICY_LEVEL_MANDATORY
,
2860 new base::FundamentalValue(SessionStartupPref::kPrefValueHomePage
),
2862 policies
.Set(key::kHomepageIsNewTabPage
,
2863 POLICY_LEVEL_MANDATORY
,
2865 new base::FundamentalValue(true),
2867 provider_
.UpdateChromePolicy(policies
);
2869 expected_urls_
.push_back(GURL(chrome::kChromeUINewTabURL
));
2873 // Verifies that policy can set the startup pages to a list of URLs.
2874 base::ListValue urls
;
2875 for (size_t i
= 0; i
< arraysize(kRestoredURLs
); ++i
) {
2876 urls
.Append(new base::StringValue(kRestoredURLs
[i
]));
2877 expected_urls_
.push_back(GURL(kRestoredURLs
[i
]));
2880 policies
.Set(key::kRestoreOnStartup
,
2881 POLICY_LEVEL_MANDATORY
,
2883 new base::FundamentalValue(SessionStartupPref::kPrefValueURLs
),
2886 key::kRestoreOnStartupURLs
, POLICY_LEVEL_MANDATORY
, POLICY_SCOPE_USER
,
2887 urls
.DeepCopy(), NULL
);
2888 provider_
.UpdateChromePolicy(policies
);
2892 // Verifies that policy can set the startup page to the NTP.
2895 key::kRestoreOnStartup
,
2896 POLICY_LEVEL_MANDATORY
,
2898 new base::FundamentalValue(SessionStartupPref::kPrefValueNewTab
),
2900 provider_
.UpdateChromePolicy(policies
);
2901 expected_urls_
.push_back(GURL(chrome::kChromeUINewTabURL
));
2905 // Verifies that policy can set the startup pages to the last session.
2907 policies
.Set(key::kRestoreOnStartup
,
2908 POLICY_LEVEL_MANDATORY
,
2910 new base::FundamentalValue(SessionStartupPref::kPrefValueLast
),
2912 provider_
.UpdateChromePolicy(policies
);
2913 // This should restore the tabs opened at PRE_RunTest below.
2914 for (size_t i
= 0; i
< arraysize(kRestoredURLs
); ++i
)
2915 expected_urls_
.push_back(GURL(kRestoredURLs
[i
]));
2918 std::vector
<GURL
> expected_urls_
;
2921 IN_PROC_BROWSER_TEST_P(RestoreOnStartupPolicyTest
, PRE_RunTest
) {
2922 // Open some tabs to verify if they are restored after the browser restarts.
2923 // Most policy settings override this, except kPrefValueLast which enforces
2925 ui_test_utils::NavigateToURL(browser(), GURL(kRestoredURLs
[0]));
2926 for (size_t i
= 1; i
< arraysize(kRestoredURLs
); ++i
) {
2927 content::WindowedNotificationObserver
observer(
2928 content::NOTIFICATION_LOAD_STOP
,
2929 content::NotificationService::AllSources());
2930 chrome::AddSelectedTabWithURL(browser(), GURL(kRestoredURLs
[i
]),
2931 ui::PAGE_TRANSITION_LINK
);
2936 IN_PROC_BROWSER_TEST_P(RestoreOnStartupPolicyTest
, RunTest
) {
2937 #if defined(OS_WIN) && defined(USE_ASH)
2938 // Disable this test in Metro+Ash for now (http://crbug.com/262796).
2939 if (CommandLine::ForCurrentProcess()->HasSwitch(switches::kAshBrowserTests
))
2943 TabStripModel
* model
= browser()->tab_strip_model();
2944 int size
= static_cast<int>(expected_urls_
.size());
2945 EXPECT_EQ(size
, model
->count());
2946 for (int i
= 0; i
< size
&& i
< model
->count(); ++i
) {
2947 EXPECT_EQ(expected_urls_
[i
], model
->GetWebContentsAt(i
)->GetURL());
2951 INSTANTIATE_TEST_CASE_P(
2952 RestoreOnStartupPolicyTestInstance
,
2953 RestoreOnStartupPolicyTest
,
2954 testing::Values(&RestoreOnStartupPolicyTest::HomepageIsNotNTP
,
2955 &RestoreOnStartupPolicyTest::HomepageIsNTP
,
2956 &RestoreOnStartupPolicyTest::ListOfURLs
,
2957 &RestoreOnStartupPolicyTest::NTP
,
2958 &RestoreOnStartupPolicyTest::Last
));
2960 // Similar to PolicyTest but sets a couple of policies before the browser is
2962 class PolicyStatisticsCollectorTest
: public PolicyTest
{
2964 PolicyStatisticsCollectorTest() {}
2965 virtual ~PolicyStatisticsCollectorTest() {}
2967 virtual void SetUpInProcessBrowserTestFixture() override
{
2968 PolicyTest::SetUpInProcessBrowserTestFixture();
2970 policies
.Set(key::kShowHomeButton
,
2971 POLICY_LEVEL_MANDATORY
,
2973 new base::FundamentalValue(true),
2975 policies
.Set(key::kBookmarkBarEnabled
,
2976 POLICY_LEVEL_MANDATORY
,
2978 new base::FundamentalValue(false),
2980 policies
.Set(key::kHomepageLocation
,
2981 POLICY_LEVEL_MANDATORY
,
2983 new base::StringValue("http://chromium.org"),
2985 provider_
.UpdateChromePolicy(policies
);
2989 IN_PROC_BROWSER_TEST_F(PolicyStatisticsCollectorTest
, Startup
) {
2990 // Verifies that policy usage histograms are collected at startup.
2992 // BrowserPolicyConnector::Init() has already been called. Make sure the
2993 // CompleteInitialization() task has executed as well.
2994 content::RunAllPendingInMessageLoop();
2996 GURL kAboutHistograms
= GURL(std::string(url::kAboutScheme
) +
2997 std::string(url::kStandardSchemeSeparator
) +
2998 std::string(content::kChromeUIHistogramHost
));
2999 ui_test_utils::NavigateToURL(browser(), kAboutHistograms
);
3000 content::WebContents
* contents
=
3001 browser()->tab_strip_model()->GetActiveWebContents();
3003 ASSERT_TRUE(content::ExecuteScriptAndExtractString(
3005 "var nodes = document.querySelectorAll('body > pre');"
3007 "for (var i = 0; i < nodes.length; ++i) {"
3008 " var text = nodes[i].innerHTML;"
3009 " if (text.indexOf('Histogram: Enterprise.Policies') === 0) {"
3014 "domAutomationController.send(result);",
3016 ASSERT_FALSE(text
.empty());
3017 const std::string kExpectedLabel
=
3018 "Histogram: Enterprise.Policies recorded 3 samples";
3019 EXPECT_EQ(kExpectedLabel
, text
.substr(0, kExpectedLabel
.size()));
3020 // HomepageLocation has policy ID 1.
3021 EXPECT_NE(std::string::npos
, text
.find("<br>1 ---"));
3022 // ShowHomeButton has policy ID 35.
3023 EXPECT_NE(std::string::npos
, text
.find("<br>35 ---"));
3024 // BookmarkBarEnabled has policy ID 82.
3025 EXPECT_NE(std::string::npos
, text
.find("<br>82 ---"));
3028 class MediaStreamDevicesControllerBrowserTest
3029 : public PolicyTest
,
3030 public testing::WithParamInterface
<bool> {
3032 MediaStreamDevicesControllerBrowserTest()
3033 : request_url_allowed_via_whitelist_(false) {
3034 policy_value_
= GetParam();
3036 virtual ~MediaStreamDevicesControllerBrowserTest() {}
3038 // Configure a given policy map.
3039 // The |policy_name| is the name of either the audio or video capture allow
3040 // policy and must never be NULL.
3041 // |whitelist_policy| and |allow_rule| are optional. If NULL, no whitelist
3042 // policy is set. If non-NULL, the request_url_ will be set to be non empty
3043 // and the whitelist policy is set to contain either the |allow_rule| (if
3044 // non-NULL) or an "allow all" wildcard.
3045 void ConfigurePolicyMap(PolicyMap
* policies
, const char* policy_name
,
3046 const char* whitelist_policy
,
3047 const char* allow_rule
) {
3048 policies
->Set(policy_name
,
3049 POLICY_LEVEL_MANDATORY
,
3051 new base::FundamentalValue(policy_value_
),
3054 if (whitelist_policy
) {
3055 // TODO(tommi): Remove the kiosk mode flag when the whitelist is visible
3056 // in the media exceptions UI.
3057 // See discussion here: https://codereview.chromium.org/15738004/
3058 CommandLine::ForCurrentProcess()->AppendSwitch(switches::kKioskMode
);
3060 // Add an entry to the whitelist that allows the specified URL regardless
3061 // of the setting of kAudioCapturedAllowed.
3062 request_url_
= GURL("http://www.example.com/foo");
3063 base::ListValue
* list
= new base::ListValue();
3065 list
->AppendString(allow_rule
);
3066 request_url_allowed_via_whitelist_
= true;
3068 list
->AppendString(ContentSettingsPattern::Wildcard().ToString());
3069 // We should ignore all wildcard entries in the whitelist, so even
3070 // though we've added an entry, it should be ignored and our expectation
3071 // is that the request has not been allowed via the whitelist.
3072 request_url_allowed_via_whitelist_
= false;
3074 policies
->Set(whitelist_policy
, POLICY_LEVEL_MANDATORY
,
3075 POLICY_SCOPE_USER
, list
, NULL
);
3079 void Accept(const content::MediaStreamDevices
& devices
,
3080 content::MediaStreamRequestResult result
,
3081 scoped_ptr
<content::MediaStreamUI
> ui
) {
3082 if (policy_value_
|| request_url_allowed_via_whitelist_
) {
3083 ASSERT_EQ(1U, devices
.size());
3084 ASSERT_EQ("fake_dev", devices
[0].id
);
3086 ASSERT_EQ(0U, devices
.size());
3090 void FinishAudioTest() {
3091 content::MediaStreamRequest
request(0, 0, 0,
3092 request_url_
.GetOrigin(), false,
3093 content::MEDIA_DEVICE_ACCESS
,
3094 std::string(), std::string(),
3095 content::MEDIA_DEVICE_AUDIO_CAPTURE
,
3096 content::MEDIA_NO_SERVICE
);
3097 // TODO(raymes): Test MEDIA_DEVICE_OPEN (Pepper) which grants both webcam
3098 // and microphone permissions at the same time.
3099 MediaStreamDevicesController
controller(
3100 browser()->tab_strip_model()->GetActiveWebContents(), request
,
3101 base::Bind(&MediaStreamDevicesControllerBrowserTest::Accept
, this));
3102 controller
.Accept(false);
3104 base::MessageLoop::current()->QuitWhenIdle();
3107 void FinishVideoTest() {
3108 // TODO(raymes): Test MEDIA_DEVICE_OPEN (Pepper) which grants both webcam
3109 // and microphone permissions at the same time.
3110 content::MediaStreamRequest
request(0, 0, 0,
3111 request_url_
.GetOrigin(), false,
3112 content::MEDIA_DEVICE_ACCESS
,
3115 content::MEDIA_NO_SERVICE
,
3116 content::MEDIA_DEVICE_VIDEO_CAPTURE
);
3117 MediaStreamDevicesController
controller(
3118 browser()->tab_strip_model()->GetActiveWebContents(), request
,
3119 base::Bind(&MediaStreamDevicesControllerBrowserTest::Accept
, this));
3120 controller
.Accept(false);
3122 base::MessageLoop::current()->QuitWhenIdle();
3126 bool request_url_allowed_via_whitelist_
;
3128 static const char kExampleRequestPattern
[];
3132 const char MediaStreamDevicesControllerBrowserTest::kExampleRequestPattern
[] =
3133 "http://[*.]example.com/";
3135 IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerBrowserTest
,
3136 AudioCaptureAllowed
) {
3137 content::MediaStreamDevices audio_devices
;
3138 content::MediaStreamDevice
fake_audio_device(
3139 content::MEDIA_DEVICE_AUDIO_CAPTURE
, "fake_dev", "Fake Audio Device");
3140 audio_devices
.push_back(fake_audio_device
);
3143 ConfigurePolicyMap(&policies
, key::kAudioCaptureAllowed
, NULL
, NULL
);
3144 UpdateProviderPolicy(policies
);
3146 content::BrowserThread::PostTaskAndReply(
3147 content::BrowserThread::IO
, FROM_HERE
,
3148 base::Bind(&MediaCaptureDevicesDispatcher::SetTestAudioCaptureDevices
,
3149 base::Unretained(MediaCaptureDevicesDispatcher::GetInstance()),
3151 base::Bind(&MediaStreamDevicesControllerBrowserTest::FinishAudioTest
,
3154 base::MessageLoop::current()->Run();
3157 IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerBrowserTest
,
3158 AudioCaptureAllowedUrls
) {
3159 content::MediaStreamDevices audio_devices
;
3160 content::MediaStreamDevice
fake_audio_device(
3161 content::MEDIA_DEVICE_AUDIO_CAPTURE
, "fake_dev", "Fake Audio Device");
3162 audio_devices
.push_back(fake_audio_device
);
3164 const char* allow_pattern
[] = {
3165 kExampleRequestPattern
,
3166 // This will set an allow-all policy whitelist. Since we do not allow
3167 // setting an allow-all entry in the whitelist, this entry should be ignored
3168 // and therefore the request should be denied.
3172 for (size_t i
= 0; i
< arraysize(allow_pattern
); ++i
) {
3174 ConfigurePolicyMap(&policies
, key::kAudioCaptureAllowed
,
3175 key::kAudioCaptureAllowedUrls
, allow_pattern
[i
]);
3176 UpdateProviderPolicy(policies
);
3178 content::BrowserThread::PostTaskAndReply(
3179 content::BrowserThread::IO
, FROM_HERE
,
3181 &MediaCaptureDevicesDispatcher::SetTestAudioCaptureDevices
,
3182 base::Unretained(MediaCaptureDevicesDispatcher::GetInstance()),
3185 &MediaStreamDevicesControllerBrowserTest::FinishAudioTest
,
3188 base::MessageLoop::current()->Run();
3192 IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerBrowserTest
,
3193 VideoCaptureAllowed
) {
3194 content::MediaStreamDevices video_devices
;
3195 content::MediaStreamDevice
fake_video_device(
3196 content::MEDIA_DEVICE_VIDEO_CAPTURE
, "fake_dev", "Fake Video Device");
3197 video_devices
.push_back(fake_video_device
);
3200 ConfigurePolicyMap(&policies
, key::kVideoCaptureAllowed
, NULL
, NULL
);
3201 UpdateProviderPolicy(policies
);
3203 content::BrowserThread::PostTaskAndReply(
3204 content::BrowserThread::IO
, FROM_HERE
,
3205 base::Bind(&MediaCaptureDevicesDispatcher::SetTestVideoCaptureDevices
,
3206 base::Unretained(MediaCaptureDevicesDispatcher::GetInstance()),
3208 base::Bind(&MediaStreamDevicesControllerBrowserTest::FinishVideoTest
,
3211 base::MessageLoop::current()->Run();
3214 IN_PROC_BROWSER_TEST_P(MediaStreamDevicesControllerBrowserTest
,
3215 VideoCaptureAllowedUrls
) {
3216 content::MediaStreamDevices video_devices
;
3217 content::MediaStreamDevice
fake_video_device(
3218 content::MEDIA_DEVICE_VIDEO_CAPTURE
, "fake_dev", "Fake Video Device");
3219 video_devices
.push_back(fake_video_device
);
3221 const char* allow_pattern
[] = {
3222 kExampleRequestPattern
,
3223 // This will set an allow-all policy whitelist. Since we do not allow
3224 // setting an allow-all entry in the whitelist, this entry should be ignored
3225 // and therefore the request should be denied.
3229 for (size_t i
= 0; i
< arraysize(allow_pattern
); ++i
) {
3231 ConfigurePolicyMap(&policies
, key::kVideoCaptureAllowed
,
3232 key::kVideoCaptureAllowedUrls
, allow_pattern
[i
]);
3233 UpdateProviderPolicy(policies
);
3235 content::BrowserThread::PostTaskAndReply(
3236 content::BrowserThread::IO
, FROM_HERE
,
3237 base::Bind(&MediaCaptureDevicesDispatcher::SetTestVideoCaptureDevices
,
3238 base::Unretained(MediaCaptureDevicesDispatcher::GetInstance()),
3241 &MediaStreamDevicesControllerBrowserTest::FinishVideoTest
,
3244 base::MessageLoop::current()->Run();
3248 INSTANTIATE_TEST_CASE_P(MediaStreamDevicesControllerBrowserTestInstance
,
3249 MediaStreamDevicesControllerBrowserTest
,
3252 #if !defined(OS_CHROMEOS)
3253 // Similar to PolicyTest but sets the proper policy before the browser is
3255 class PolicyVariationsServiceTest
: public PolicyTest
{
3257 virtual void SetUpInProcessBrowserTestFixture() override
{
3258 PolicyTest::SetUpInProcessBrowserTestFixture();
3260 policies
.Set(key::kVariationsRestrictParameter
,
3261 POLICY_LEVEL_MANDATORY
,
3263 new base::StringValue("restricted"),
3265 provider_
.UpdateChromePolicy(policies
);
3269 IN_PROC_BROWSER_TEST_F(PolicyVariationsServiceTest
, VariationsURLIsValid
) {
3270 const std::string default_variations_url
=
3271 chrome_variations::VariationsService::
3272 GetDefaultVariationsServerURLForTesting();
3275 chrome_variations::VariationsService::GetVariationsServerURL(
3276 g_browser_process
->local_state());
3277 EXPECT_TRUE(StartsWithASCII(url
.spec(), default_variations_url
, true));
3279 EXPECT_TRUE(net::GetValueForKeyInQuery(url
, "restrict", &value
));
3280 EXPECT_EQ("restricted", value
);
3283 IN_PROC_BROWSER_TEST_F(PolicyTest
, NativeMessagingBlacklistSelective
) {
3284 base::ListValue blacklist
;
3285 blacklist
.Append(new base::StringValue("host.name"));
3287 policies
.Set(key::kNativeMessagingBlacklist
, POLICY_LEVEL_MANDATORY
,
3288 POLICY_SCOPE_USER
, blacklist
.DeepCopy(), NULL
);
3289 UpdateProviderPolicy(policies
);
3291 PrefService
* prefs
= browser()->profile()->GetPrefs();
3292 EXPECT_FALSE(extensions::MessageService::IsNativeMessagingHostAllowed(
3293 prefs
, "host.name"));
3294 EXPECT_TRUE(extensions::MessageService::IsNativeMessagingHostAllowed(
3295 prefs
, "other.host.name"));
3298 IN_PROC_BROWSER_TEST_F(PolicyTest
, NativeMessagingBlacklistWildcard
) {
3299 base::ListValue blacklist
;
3300 blacklist
.Append(new base::StringValue("*"));
3302 policies
.Set(key::kNativeMessagingBlacklist
, POLICY_LEVEL_MANDATORY
,
3303 POLICY_SCOPE_USER
, blacklist
.DeepCopy(), NULL
);
3304 UpdateProviderPolicy(policies
);
3306 PrefService
* prefs
= browser()->profile()->GetPrefs();
3307 EXPECT_FALSE(extensions::MessageService::IsNativeMessagingHostAllowed(
3308 prefs
, "host.name"));
3309 EXPECT_FALSE(extensions::MessageService::IsNativeMessagingHostAllowed(
3310 prefs
, "other.host.name"));
3313 IN_PROC_BROWSER_TEST_F(PolicyTest
, NativeMessagingWhitelist
) {
3314 base::ListValue blacklist
;
3315 blacklist
.Append(new base::StringValue("*"));
3316 base::ListValue whitelist
;
3317 whitelist
.Append(new base::StringValue("host.name"));
3319 policies
.Set(key::kNativeMessagingBlacklist
, POLICY_LEVEL_MANDATORY
,
3320 POLICY_SCOPE_USER
, blacklist
.DeepCopy(), NULL
);
3321 policies
.Set(key::kNativeMessagingWhitelist
, POLICY_LEVEL_MANDATORY
,
3322 POLICY_SCOPE_USER
, whitelist
.DeepCopy(), NULL
);
3323 UpdateProviderPolicy(policies
);
3325 PrefService
* prefs
= browser()->profile()->GetPrefs();
3326 EXPECT_TRUE(extensions::MessageService::IsNativeMessagingHostAllowed(
3327 prefs
, "host.name"));
3328 EXPECT_FALSE(extensions::MessageService::IsNativeMessagingHostAllowed(
3329 prefs
, "other.host.name"));
3332 IN_PROC_BROWSER_TEST_F(PolicyTest
,
3333 EnableDeprecatedWebPlatformFeatures_ShowModalDialog
) {
3334 base::ListValue enabled_features
;
3335 enabled_features
.Append(new base::StringValue(
3336 "ShowModalDialog_EffectiveUntil20150430"));
3338 policies
.Set(key::kEnableDeprecatedWebPlatformFeatures
,
3339 POLICY_LEVEL_MANDATORY
,
3341 enabled_features
.DeepCopy(),
3343 UpdateProviderPolicy(policies
);
3345 // Policy only takes effect on new browsers, not existing browsers, so create
3347 Browser
* browser2
= CreateBrowser(browser()->profile());
3348 ui_test_utils::NavigateToURL(browser2
, GURL(url::kAboutBlankURL
));
3349 bool result
= false;
3350 EXPECT_TRUE(content::ExecuteScriptAndExtractBool(
3351 browser2
->tab_strip_model()->GetActiveWebContents(),
3352 "domAutomationController.send(window.showModalDialog !== undefined);",
3354 EXPECT_TRUE(result
);
3357 #endif // !defined(CHROME_OS)
3359 } // namespace policy