ProfilePolicyConnectorFactory: Refactoring from Profile to BrowserContext.
[chromium-blink-merge.git] / chrome / browser / policy / policy_prefs_browsertest.cc
blob32d3edd3d35507df1f27a74d811229c958aa861b
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include <algorithm>
6 #include <cstdlib>
7 #include <map>
8 #include <sstream>
9 #include <string>
10 #include <vector>
12 #include "base/basictypes.h"
13 #include "base/files/file_path.h"
14 #include "base/files/file_util.h"
15 #include "base/json/json_reader.h"
16 #include "base/logging.h"
17 #include "base/memory/scoped_ptr.h"
18 #include "base/memory/scoped_vector.h"
19 #include "base/memory/weak_ptr.h"
20 #include "base/prefs/pref_service.h"
21 #include "base/run_loop.h"
22 #include "base/stl_util.h"
23 #include "base/strings/string_util.h"
24 #include "base/strings/utf_string_conversions.h"
25 #include "base/values.h"
26 #include "chrome/browser/browser_process.h"
27 #include "chrome/browser/profiles/profile.h"
28 #include "chrome/browser/search_engines/template_url_service_factory.h"
29 #include "chrome/browser/ui/browser.h"
30 #include "chrome/browser/ui/tabs/tab_strip_model.h"
31 #include "chrome/test/base/in_process_browser_test.h"
32 #include "chrome/test/base/ui_test_utils.h"
33 #include "components/policy/core/browser/browser_policy_connector.h"
34 #include "components/policy/core/common/external_data_fetcher.h"
35 #include "components/policy/core/common/external_data_manager.h"
36 #include "components/policy/core/common/mock_configuration_policy_provider.h"
37 #include "components/policy/core/common/policy_details.h"
38 #include "components/policy/core/common/policy_map.h"
39 #include "components/policy/core/common/schema.h"
40 #include "content/public/browser/web_contents.h"
41 #include "content/public/test/browser_test_utils.h"
42 #include "policy/policy_constants.h"
43 #include "testing/gmock/include/gmock/gmock.h"
44 #include "testing/gtest/include/gtest/gtest.h"
45 #include "url/gurl.h"
47 using testing::Return;
48 using testing::_;
50 namespace policy {
52 namespace {
54 const char kCrosSettingsPrefix[] = "cros.";
56 std::string GetPolicyName(const std::string& policy_name_decorated) {
57 const size_t offset = policy_name_decorated.find('.');
58 if (offset != std::string::npos)
59 return policy_name_decorated.substr(0, offset);
60 return policy_name_decorated;
63 // Contains the details of a single test case verifying that the controlled
64 // setting indicators for a pref affected by a policy work correctly. This is
65 // part of the data loaded from chrome/test/data/policy/policy_test_cases.json.
66 class IndicatorTestCase {
67 public:
68 IndicatorTestCase(const base::DictionaryValue& policy,
69 const std::string& value,
70 bool readonly)
71 : policy_(policy.DeepCopy()), value_(value), readonly_(readonly) {}
72 ~IndicatorTestCase() {}
74 const base::DictionaryValue& policy() const { return *policy_; }
76 const std::string& value() const { return value_; }
78 bool readonly() const { return readonly_; }
80 private:
81 scoped_ptr<base::DictionaryValue> policy_;
82 std::string value_;
83 bool readonly_;
85 DISALLOW_COPY_AND_ASSIGN(IndicatorTestCase);
88 // Contains the testing details for a single pref affected by a policy. This is
89 // part of the data loaded from chrome/test/data/policy/policy_test_cases.json.
90 class PrefMapping {
91 public:
92 PrefMapping(const std::string& pref,
93 bool is_local_state,
94 bool check_for_mandatory,
95 bool check_for_recommended,
96 const std::string& indicator_test_setup_js,
97 const std::string& indicator_selector)
98 : pref_(pref),
99 is_local_state_(is_local_state),
100 check_for_mandatory_(check_for_mandatory),
101 check_for_recommended_(check_for_recommended),
102 indicator_test_setup_js_(indicator_test_setup_js),
103 indicator_selector_(indicator_selector) {}
104 ~PrefMapping() {}
106 const std::string& pref() const { return pref_; }
108 bool is_local_state() const { return is_local_state_; }
110 bool check_for_mandatory() const { return check_for_mandatory_; }
112 bool check_for_recommended() const { return check_for_recommended_; }
114 const std::string& indicator_test_setup_js() const {
115 return indicator_test_setup_js_;
118 const std::string& indicator_selector() const {
119 return indicator_selector_;
122 const ScopedVector<IndicatorTestCase>& indicator_test_cases() const {
123 return indicator_test_cases_;
125 void AddIndicatorTestCase(IndicatorTestCase* test_case) {
126 indicator_test_cases_.push_back(test_case);
129 private:
130 const std::string pref_;
131 const bool is_local_state_;
132 const bool check_for_mandatory_;
133 const bool check_for_recommended_;
134 const std::string indicator_test_setup_js_;
135 const std::string indicator_selector_;
136 ScopedVector<IndicatorTestCase> indicator_test_cases_;
138 DISALLOW_COPY_AND_ASSIGN(PrefMapping);
141 // Contains the testing details for a single policy. This is part of the data
142 // loaded from chrome/test/data/policy/policy_test_cases.json.
143 class PolicyTestCase {
144 public:
145 PolicyTestCase(const std::string& name,
146 bool is_official_only,
147 bool can_be_recommended,
148 const std::string& indicator_selector)
149 : name_(name),
150 is_official_only_(is_official_only),
151 can_be_recommended_(can_be_recommended),
152 indicator_selector_(indicator_selector) {}
153 ~PolicyTestCase() {}
155 const std::string& name() const { return name_; }
157 bool is_official_only() const { return is_official_only_; }
159 bool can_be_recommended() const { return can_be_recommended_; }
161 bool IsOsSupported() const {
162 #if defined(OS_WIN)
163 const std::string os("win");
164 #elif defined(OS_MACOSX)
165 const std::string os("mac");
166 #elif defined(OS_CHROMEOS)
167 const std::string os("chromeos");
168 #elif defined(OS_LINUX)
169 const std::string os("linux");
170 #else
171 #error "Unknown platform"
172 #endif
173 return std::find(supported_os_.begin(), supported_os_.end(), os) !=
174 supported_os_.end();
176 void AddSupportedOs(const std::string& os) { supported_os_.push_back(os); }
178 bool IsSupported() const {
179 #if !defined(GOOGLE_CHROME_BUILD)
180 if (is_official_only())
181 return false;
182 #endif
183 return IsOsSupported();
186 const base::DictionaryValue& test_policy() const { return test_policy_; }
187 void SetTestPolicy(const base::DictionaryValue& policy) {
188 test_policy_.Clear();
189 test_policy_.MergeDictionary(&policy);
192 const ScopedVector<PrefMapping>& pref_mappings() const {
193 return pref_mappings_;
195 void AddPrefMapping(PrefMapping* pref_mapping) {
196 pref_mappings_.push_back(pref_mapping);
199 const std::string& indicator_selector() const { return indicator_selector_; }
201 private:
202 std::string name_;
203 bool is_official_only_;
204 bool can_be_recommended_;
205 std::vector<std::string> supported_os_;
206 base::DictionaryValue test_policy_;
207 ScopedVector<PrefMapping> pref_mappings_;
208 std::string indicator_selector_;
210 DISALLOW_COPY_AND_ASSIGN(PolicyTestCase);
213 // Parses all policy test cases and makes then available in a map.
214 class PolicyTestCases {
215 public:
216 typedef std::vector<PolicyTestCase*> PolicyTestCaseVector;
217 typedef std::map<std::string, PolicyTestCaseVector> PolicyTestCaseMap;
218 typedef PolicyTestCaseMap::const_iterator iterator;
220 PolicyTestCases() {
221 base::FilePath path = ui_test_utils::GetTestFilePath(
222 base::FilePath(FILE_PATH_LITERAL("policy")),
223 base::FilePath(FILE_PATH_LITERAL("policy_test_cases.json")));
224 std::string json;
225 if (!base::ReadFileToString(path, &json)) {
226 ADD_FAILURE();
227 return;
229 int error_code = -1;
230 std::string error_string;
231 base::DictionaryValue* dict = NULL;
232 scoped_ptr<base::Value> value(base::JSONReader::ReadAndReturnError(
233 json, base::JSON_PARSE_RFC, &error_code, &error_string));
234 if (!value.get() || !value->GetAsDictionary(&dict)) {
235 ADD_FAILURE() << "Error parsing policy_test_cases.json: " << error_string;
236 return;
238 Schema chrome_schema = Schema::Wrap(GetChromeSchemaData());
239 if (!chrome_schema.valid()) {
240 ADD_FAILURE();
241 return;
243 for (base::DictionaryValue::Iterator it(*dict); !it.IsAtEnd();
244 it.Advance()) {
245 const std::string policy_name = GetPolicyName(it.key());
246 if (!chrome_schema.GetKnownProperty(policy_name).valid())
247 continue;
248 PolicyTestCase* policy_test_case = GetPolicyTestCase(dict, it.key());
249 if (policy_test_case)
250 policy_test_cases_[policy_name].push_back(policy_test_case);
254 ~PolicyTestCases() {
255 for (iterator policy = policy_test_cases_.begin();
256 policy != policy_test_cases_.end();
257 ++policy) {
258 for (PolicyTestCaseVector::const_iterator test_case =
259 policy->second.begin();
260 test_case != policy->second.end();
261 ++test_case) {
262 delete *test_case;
267 const PolicyTestCaseVector* Get(const std::string& name) const {
268 const iterator it = policy_test_cases_.find(name);
269 return it == end() ? NULL : &it->second;
272 const PolicyTestCaseMap& map() const { return policy_test_cases_; }
273 iterator begin() const { return policy_test_cases_.begin(); }
274 iterator end() const { return policy_test_cases_.end(); }
276 private:
277 PolicyTestCase* GetPolicyTestCase(const base::DictionaryValue* tests,
278 const std::string& name) {
279 const base::DictionaryValue* policy_test_dict = NULL;
280 if (!tests->GetDictionaryWithoutPathExpansion(name, &policy_test_dict))
281 return NULL;
282 bool is_official_only = false;
283 policy_test_dict->GetBoolean("official_only", &is_official_only);
284 bool can_be_recommended = false;
285 policy_test_dict->GetBoolean("can_be_recommended", &can_be_recommended);
286 std::string indicator_selector;
287 policy_test_dict->GetString("indicator_selector", &indicator_selector);
288 PolicyTestCase* policy_test_case = new PolicyTestCase(name,
289 is_official_only,
290 can_be_recommended,
291 indicator_selector);
292 const base::ListValue* os_list = NULL;
293 if (policy_test_dict->GetList("os", &os_list)) {
294 for (size_t i = 0; i < os_list->GetSize(); ++i) {
295 std::string os;
296 if (os_list->GetString(i, &os))
297 policy_test_case->AddSupportedOs(os);
300 const base::DictionaryValue* policy = NULL;
301 if (policy_test_dict->GetDictionary("test_policy", &policy))
302 policy_test_case->SetTestPolicy(*policy);
303 const base::ListValue* pref_mappings = NULL;
304 if (policy_test_dict->GetList("pref_mappings", &pref_mappings)) {
305 for (size_t i = 0; i < pref_mappings->GetSize(); ++i) {
306 const base::DictionaryValue* pref_mapping_dict = NULL;
307 std::string pref;
308 if (!pref_mappings->GetDictionary(i, &pref_mapping_dict) ||
309 !pref_mapping_dict->GetString("pref", &pref)) {
310 ADD_FAILURE() << "Malformed pref_mappings entry in "
311 << "policy_test_cases.json.";
312 continue;
314 bool is_local_state = false;
315 pref_mapping_dict->GetBoolean("local_state", &is_local_state);
316 bool check_for_mandatory = true;
317 pref_mapping_dict->GetBoolean("check_for_mandatory",
318 &check_for_mandatory);
319 bool check_for_recommended = true;
320 pref_mapping_dict->GetBoolean("check_for_recommended",
321 &check_for_recommended);
322 std::string indicator_test_setup_js;
323 pref_mapping_dict->GetString("indicator_test_setup_js",
324 &indicator_test_setup_js);
325 std::string indicator_selector;
326 pref_mapping_dict->GetString("indicator_selector", &indicator_selector);
327 PrefMapping* pref_mapping = new PrefMapping(pref,
328 is_local_state,
329 check_for_mandatory,
330 check_for_recommended,
331 indicator_test_setup_js,
332 indicator_selector);
333 const base::ListValue* indicator_tests = NULL;
334 if (pref_mapping_dict->GetList("indicator_tests", &indicator_tests)) {
335 for (size_t i = 0; i < indicator_tests->GetSize(); ++i) {
336 const base::DictionaryValue* indicator_test_dict = NULL;
337 const base::DictionaryValue* policy = NULL;
338 if (!indicator_tests->GetDictionary(i, &indicator_test_dict) ||
339 !indicator_test_dict->GetDictionary("policy", &policy)) {
340 ADD_FAILURE() << "Malformed indicator_tests entry in "
341 << "policy_test_cases.json.";
342 continue;
344 std::string value;
345 indicator_test_dict->GetString("value", &value);
346 bool readonly = false;
347 indicator_test_dict->GetBoolean("readonly", &readonly);
348 pref_mapping->AddIndicatorTestCase(
349 new IndicatorTestCase(*policy, value, readonly));
352 policy_test_case->AddPrefMapping(pref_mapping);
355 return policy_test_case;
358 PolicyTestCaseMap policy_test_cases_;
360 DISALLOW_COPY_AND_ASSIGN(PolicyTestCases);
363 } // namespace
365 typedef InProcessBrowserTest PolicyPrefsTestCoverageTest;
367 IN_PROC_BROWSER_TEST_F(PolicyPrefsTestCoverageTest, AllPoliciesHaveATestCase) {
368 // Verifies that all known policies have a test case in the JSON file.
369 // This test fails when a policy is added to
370 // components/policy/resources/policy_templates.json but a test case is not
371 // added to chrome/test/data/policy/policy_test_cases.json.
372 Schema chrome_schema = Schema::Wrap(GetChromeSchemaData());
373 ASSERT_TRUE(chrome_schema.valid());
375 PolicyTestCases policy_test_cases;
376 for (Schema::Iterator it = chrome_schema.GetPropertiesIterator();
377 !it.IsAtEnd(); it.Advance()) {
378 EXPECT_TRUE(ContainsKey(policy_test_cases.map(), it.key()))
379 << "Missing policy test case for: " << it.key();
383 // Base class for tests that change policy.
384 class PolicyPrefsTest : public InProcessBrowserTest {
385 protected:
386 void SetUpInProcessBrowserTestFixture() override {
387 EXPECT_CALL(provider_, IsInitializationComplete(_))
388 .WillRepeatedly(Return(true));
389 BrowserPolicyConnector::SetPolicyProviderForTesting(&provider_);
392 void SetUpOnMainThread() override {
393 ui_test_utils::WaitForTemplateURLServiceToLoad(
394 TemplateURLServiceFactory::GetForProfile(browser()->profile()));
397 void TearDownOnMainThread() override { ClearProviderPolicy(); }
399 void ClearProviderPolicy() {
400 provider_.UpdateChromePolicy(PolicyMap());
401 base::RunLoop().RunUntilIdle();
404 void SetProviderPolicy(const base::DictionaryValue& policies,
405 PolicyLevel level) {
406 PolicyMap policy_map;
407 for (base::DictionaryValue::Iterator it(policies);
408 !it.IsAtEnd(); it.Advance()) {
409 const PolicyDetails* policy_details = GetChromePolicyDetails(it.key());
410 ASSERT_TRUE(policy_details);
411 policy_map.Set(
412 it.key(),
413 level,
414 POLICY_SCOPE_USER,
415 it.value().DeepCopy(),
416 policy_details->max_external_data_size ?
417 new ExternalDataFetcher(base::WeakPtr<ExternalDataManager>(),
418 it.key()) :
419 NULL);
421 provider_.UpdateChromePolicy(policy_map);
422 base::RunLoop().RunUntilIdle();
425 MockConfigurationPolicyProvider provider_;
428 // Verifies that policies make their corresponding preferences become managed,
429 // and that the user can't override that setting.
430 IN_PROC_BROWSER_TEST_F(PolicyPrefsTest, PolicyToPrefsMapping) {
431 PrefService* local_state = g_browser_process->local_state();
432 PrefService* user_prefs = browser()->profile()->GetPrefs();
434 const PolicyTestCases test_cases;
435 for (PolicyTestCases::iterator policy = test_cases.begin();
436 policy != test_cases.end();
437 ++policy) {
438 for (PolicyTestCases::PolicyTestCaseVector::const_iterator test_case =
439 policy->second.begin();
440 test_case != policy->second.end();
441 ++test_case) {
442 const ScopedVector<PrefMapping>& pref_mappings =
443 (*test_case)->pref_mappings();
444 if (!(*test_case)->IsSupported() || pref_mappings.empty())
445 continue;
447 LOG(INFO) << "Testing policy: " << policy->first;
449 for (ScopedVector<PrefMapping>::const_iterator pref_mapping =
450 pref_mappings.begin();
451 pref_mapping != pref_mappings.end();
452 ++pref_mapping) {
453 // Skip Chrome OS preferences that use a different backend and cannot be
454 // retrieved through the prefs mechanism.
455 if (StartsWithASCII((*pref_mapping)->pref(), kCrosSettingsPrefix, true))
456 continue;
458 // Skip preferences that should not be checked when the policy is set to
459 // a mandatory value.
460 if (!(*pref_mapping)->check_for_mandatory())
461 continue;
463 PrefService* prefs =
464 (*pref_mapping)->is_local_state() ? local_state : user_prefs;
465 // The preference must have been registered.
466 const PrefService::Preference* pref =
467 prefs->FindPreference((*pref_mapping)->pref().c_str());
468 ASSERT_TRUE(pref);
470 // Verify that setting the policy overrides the pref.
471 ClearProviderPolicy();
472 prefs->ClearPref((*pref_mapping)->pref().c_str());
473 EXPECT_TRUE(pref->IsDefaultValue());
474 EXPECT_TRUE(pref->IsUserModifiable());
475 EXPECT_FALSE(pref->IsUserControlled());
476 EXPECT_FALSE(pref->IsManaged());
478 SetProviderPolicy((*test_case)->test_policy(), POLICY_LEVEL_MANDATORY);
479 EXPECT_FALSE(pref->IsDefaultValue());
480 EXPECT_FALSE(pref->IsUserModifiable());
481 EXPECT_FALSE(pref->IsUserControlled());
482 EXPECT_TRUE(pref->IsManaged());
488 // Failing on cros official build. crbug.com/431791
489 #if !defined(OS_CHROMEOS) || !defined(OFFICIAL_BUILD)
490 namespace {
492 const char kMainSettingsPage[] = "chrome://settings-frame";
494 void VerifyControlledSettingIndicators(Browser* browser,
495 const std::string& selector,
496 const std::string& value,
497 const std::string& controlled_by,
498 bool readonly) {
499 std::stringstream javascript;
500 javascript << "var nodes = document.querySelectorAll("
501 << " 'span.controlled-setting-indicator"
502 << selector.c_str() << "');"
503 << "var indicators = [];"
504 << "for (var i = 0; i < nodes.length; i++) {"
505 << " var node = nodes[i];"
506 << " var indicator = {};"
507 << " indicator.value = node.value || '';"
508 << " indicator.controlledBy = node.controlledBy || '';"
509 << " indicator.readOnly = node.readOnly || false;"
510 << " indicator.visible ="
511 << " window.getComputedStyle(node).display != 'none';"
512 << " indicators.push(indicator)"
513 << "}"
514 << "domAutomationController.send(JSON.stringify(indicators));";
515 content::WebContents* contents =
516 browser->tab_strip_model()->GetActiveWebContents();
517 std::string json;
518 // Retrieve the state of all controlled setting indicators matching the
519 // |selector| as JSON.
520 ASSERT_TRUE(content::ExecuteScriptAndExtractString(contents, javascript.str(),
521 &json));
522 scoped_ptr<base::Value> value_ptr(base::JSONReader::Read(json));
523 const base::ListValue* indicators = NULL;
524 ASSERT_TRUE(value_ptr.get());
525 ASSERT_TRUE(value_ptr->GetAsList(&indicators));
526 // Verify that controlled setting indicators representing |value| are visible
527 // and have the correct state while those not representing |value| are
528 // invisible.
529 if (!controlled_by.empty()) {
530 EXPECT_GT(indicators->GetSize(), 0u)
531 << "Expected to find at least one controlled setting indicator.";
533 bool have_visible_indicators = false;
534 for (base::ListValue::const_iterator indicator = indicators->begin();
535 indicator != indicators->end(); ++indicator) {
536 const base::DictionaryValue* properties = NULL;
537 ASSERT_TRUE((*indicator)->GetAsDictionary(&properties));
538 std::string indicator_value;
539 std::string indicator_controlled_by;
540 bool indicator_readonly;
541 bool indicator_visible;
542 EXPECT_TRUE(properties->GetString("value", &indicator_value));
543 EXPECT_TRUE(properties->GetString("controlledBy",
544 &indicator_controlled_by));
545 EXPECT_TRUE(properties->GetBoolean("readOnly", &indicator_readonly));
546 EXPECT_TRUE(properties->GetBoolean("visible", &indicator_visible));
547 if (!controlled_by.empty() && (indicator_value == value)) {
548 EXPECT_EQ(controlled_by, indicator_controlled_by);
549 EXPECT_EQ(readonly, indicator_readonly);
550 EXPECT_TRUE(indicator_visible);
551 have_visible_indicators = true;
552 } else {
553 EXPECT_FALSE(indicator_visible);
556 if (!controlled_by.empty()) {
557 EXPECT_TRUE(have_visible_indicators)
558 << "Expected to find at least one visible controlled setting "
559 << "indicator.";
563 // Returns a pseudo-random integer distributed in [0, range).
564 int GetRandomNumber(int range) {
565 return rand() % range;
568 // Splits all known policies into subsets of the given |chunk_size|. The
569 // policies are shuffled so that there is no correlation between their initial
570 // alphabetic ordering and the assignment to chunks. This ensures that the
571 // expected number of policies with long-running test cases is equal for each
572 // subset. The shuffle algorithm uses a fixed seed, ensuring that no randomness
573 // is introduced into the testing process.
574 std::vector<std::vector<std::string> > SplitPoliciesIntoChunks(int chunk_size) {
575 Schema chrome_schema = Schema::Wrap(GetChromeSchemaData());
576 if (!chrome_schema.valid())
577 ADD_FAILURE();
579 std::vector<std::string> policies;
580 for (Schema::Iterator it = chrome_schema.GetPropertiesIterator();
581 !it.IsAtEnd(); it.Advance()) {
582 policies.push_back(it.key());
585 // Use a fixed random seed to obtain a reproducible shuffle.
586 srand(1);
587 std::random_shuffle(policies.begin(), policies.end(), GetRandomNumber);
589 std::vector<std::vector<std::string> > chunks;
590 std::vector<std::string>::const_iterator it = policies.begin();
591 const std::vector<std::string>::const_iterator end = policies.end();
592 for ( ; end - it >= chunk_size; it += chunk_size)
593 chunks.push_back(std::vector<std::string>(it, it + chunk_size));
594 if (it != end)
595 chunks.push_back(std::vector<std::string>(it, end));
596 return chunks;
599 } // namespace
601 class PolicyPrefIndicatorTest
602 : public PolicyPrefsTest,
603 public testing::WithParamInterface<std::vector<std::string> > {
606 // Verifies that controlled setting indicators correctly show whether a pref's
607 // value is recommended or enforced by a corresponding policy.
608 IN_PROC_BROWSER_TEST_P(PolicyPrefIndicatorTest, CheckPolicyIndicators) {
609 const PolicyTestCases test_cases;
610 PrefService* local_state = g_browser_process->local_state();
611 PrefService* user_prefs = browser()->profile()->GetPrefs();
613 ui_test_utils::NavigateToURL(browser(), GURL(kMainSettingsPage));
615 for (std::vector<std::string>::const_iterator policy = GetParam().begin();
616 policy != GetParam().end();
617 ++policy) {
618 const std::vector<PolicyTestCase*>* policy_test_cases =
619 test_cases.Get(*policy);
620 ASSERT_TRUE(policy_test_cases) << "PolicyTestCase not found for "
621 << *policy;
622 for (std::vector<PolicyTestCase*>::const_iterator test_case =
623 policy_test_cases->begin();
624 test_case != policy_test_cases->end();
625 ++test_case) {
626 PolicyTestCase* policy_test_case = *test_case;
627 if (!policy_test_case->IsSupported())
628 continue;
629 const ScopedVector<PrefMapping>& pref_mappings =
630 policy_test_case->pref_mappings();
631 if (policy_test_case->indicator_selector().empty()) {
632 bool has_pref_indicator_tests = false;
633 for (ScopedVector<PrefMapping>::const_iterator pref_mapping =
634 pref_mappings.begin();
635 pref_mapping != pref_mappings.end();
636 ++pref_mapping) {
637 if (!(*pref_mapping)->indicator_test_cases().empty()) {
638 has_pref_indicator_tests = true;
639 break;
642 if (!has_pref_indicator_tests)
643 continue;
646 LOG(INFO) << "Testing policy: " << *policy;
648 if (!policy_test_case->indicator_selector().empty()) {
649 // Check that no controlled setting indicator is visible when no value
650 // is set by policy.
651 ClearProviderPolicy();
652 VerifyControlledSettingIndicators(
653 browser(),
654 policy_test_case->indicator_selector(),
655 std::string(),
656 std::string(),
657 false);
658 // Check that the appropriate controlled setting indicator is shown when
659 // a value is enforced by policy.
660 SetProviderPolicy(policy_test_case->test_policy(),
661 POLICY_LEVEL_MANDATORY);
662 VerifyControlledSettingIndicators(
663 browser(),
664 policy_test_case->indicator_selector(),
665 std::string(),
666 "policy",
667 false);
668 // Check that no controlled setting indicator is visible when previously
669 // enforced value is removed.
670 ClearProviderPolicy();
671 VerifyControlledSettingIndicators(
672 browser(),
673 policy_test_case->indicator_selector(),
674 std::string(),
675 std::string(),
676 false);
679 for (ScopedVector<PrefMapping>::const_iterator
680 pref_mapping = pref_mappings.begin();
681 pref_mapping != pref_mappings.end();
682 ++pref_mapping) {
683 const ScopedVector<IndicatorTestCase>& indicator_test_cases =
684 (*pref_mapping)->indicator_test_cases();
685 if (indicator_test_cases.empty())
686 continue;
688 if (!(*pref_mapping)->indicator_test_setup_js().empty()) {
689 ASSERT_TRUE(content::ExecuteScript(
690 browser()->tab_strip_model()->GetActiveWebContents(),
691 (*pref_mapping)->indicator_test_setup_js()));
694 std::string indicator_selector = (*pref_mapping)->indicator_selector();
695 if (indicator_selector.empty())
696 indicator_selector = "[pref=\"" + (*pref_mapping)->pref() + "\"]";
697 for (ScopedVector<IndicatorTestCase>::const_iterator
698 indicator_test_case = indicator_test_cases.begin();
699 indicator_test_case != indicator_test_cases.end();
700 ++indicator_test_case) {
701 // Check that no controlled setting indicator is visible when no value
702 // is set by policy.
703 ClearProviderPolicy();
704 VerifyControlledSettingIndicators(browser(),
705 indicator_selector,
706 std::string(),
707 std::string(),
708 false);
710 if ((*pref_mapping)->check_for_mandatory()) {
711 // Check that the appropriate controlled setting indicator is shown
712 // when a value is enforced by policy.
713 SetProviderPolicy((*indicator_test_case)->policy(),
714 POLICY_LEVEL_MANDATORY);
716 VerifyControlledSettingIndicators(
717 browser(),
718 indicator_selector,
719 (*indicator_test_case)->value(),
720 "policy",
721 (*indicator_test_case)->readonly());
724 if (!policy_test_case->can_be_recommended() ||
725 !(*pref_mapping)->check_for_recommended()) {
726 continue;
729 PrefService* prefs =
730 (*pref_mapping)->is_local_state() ? local_state : user_prefs;
731 // The preference must have been registered.
732 const PrefService::Preference* pref =
733 prefs->FindPreference((*pref_mapping)->pref().c_str());
734 ASSERT_TRUE(pref);
736 // Check that the appropriate controlled setting indicator is shown
737 // when a value is recommended by policy and the user has not
738 // overridden the recommendation.
739 SetProviderPolicy((*indicator_test_case)->policy(),
740 POLICY_LEVEL_RECOMMENDED);
741 VerifyControlledSettingIndicators(browser(),
742 indicator_selector,
743 (*indicator_test_case)->value(),
744 "recommended",
745 (*indicator_test_case)->readonly());
746 // Check that the appropriate controlled setting indicator is shown
747 // when a value is recommended by policy and the user has overridden
748 // the recommendation.
749 prefs->Set((*pref_mapping)->pref().c_str(), *pref->GetValue());
750 VerifyControlledSettingIndicators(browser(),
751 indicator_selector,
752 (*indicator_test_case)->value(),
753 "hasRecommendation",
754 (*indicator_test_case)->readonly());
755 prefs->ClearPref((*pref_mapping)->pref().c_str());
762 INSTANTIATE_TEST_CASE_P(PolicyPrefIndicatorTestInstance,
763 PolicyPrefIndicatorTest,
764 testing::ValuesIn(SplitPoliciesIntoChunks(10)));
765 #endif // !defined(OS_CHROMEOS) || !defined(OFFICIAL_BUILD)
767 } // namespace policy