diff options
author | mnissler@chromium.org <mnissler@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98> | 2011-11-10 10:08:16 +0000 |
---|---|---|
committer | mnissler@chromium.org <mnissler@chromium.org@0039d316-1c4b-4281-b951-d872f2087c98> | 2011-11-10 10:08:16 +0000 |
commit | b779909d264c992707a12c63d209b99f0b9acb53 (patch) | |
tree | 1b9b42be4082af222f9a54d28814c21e943bc613 /chrome/browser/policy | |
parent | c5d094f0ad57ec224e3780f5171a555486b5e1ef (diff) | |
download | chromium_src-b779909d264c992707a12c63d209b99f0b9acb53.zip chromium_src-b779909d264c992707a12c63d209b99f0b9acb53.tar.gz chromium_src-b779909d264c992707a12c63d209b99f0b9acb53.tar.bz2 |
Include only policy definitions that apply to the platfrom in the policy definition list.
BUG=chromium-os:19411
TEST=compiles, unit tests pass.
Review URL: http://codereview.chromium.org/8467011
git-svn-id: svn://svn.chromium.org/chrome/trunk/src@109405 0039d316-1c4b-4281-b951-d872f2087c98
Diffstat (limited to 'chrome/browser/policy')
18 files changed, 698 insertions, 1172 deletions
diff --git a/chrome/browser/policy/asynchronous_policy_loader.cc b/chrome/browser/policy/asynchronous_policy_loader.cc index 5c45042..1a55b66 100644 --- a/chrome/browser/policy/asynchronous_policy_loader.cc +++ b/chrome/browser/policy/asynchronous_policy_loader.cc @@ -48,7 +48,7 @@ void AsynchronousPolicyLoader::Stop() { AsynchronousPolicyLoader::~AsynchronousPolicyLoader() { } -void AsynchronousPolicyLoader::Reload() { +void AsynchronousPolicyLoader::Reload(bool force) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); if (delegate_.get()) { PostUpdatePolicyTask(delegate_->Load()); @@ -81,7 +81,7 @@ void AsynchronousPolicyLoader::ScheduleFallbackReloadTask() { void AsynchronousPolicyLoader::ReloadFromTask() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); - Reload(); + Reload(false); } void AsynchronousPolicyLoader::InitOnFileThread() { diff --git a/chrome/browser/policy/asynchronous_policy_loader.h b/chrome/browser/policy/asynchronous_policy_loader.h index c9b93b5..63a81f8 100644 --- a/chrome/browser/policy/asynchronous_policy_loader.h +++ b/chrome/browser/policy/asynchronous_policy_loader.h @@ -32,8 +32,9 @@ class AsynchronousPolicyLoader virtual void Init(const base::Closure& callback); // Reloads policy, sending notification of changes if necessary. Must be - // called on the FILE thread. - virtual void Reload(); + // called on the FILE thread. When |force| is true, the loader should do an + // immediate full reload. + virtual void Reload(bool force); // Stops any pending reload tasks. Updates callbacks won't be performed // anymore once the loader is stopped. diff --git a/chrome/browser/policy/asynchronous_policy_loader_unittest.cc b/chrome/browser/policy/asynchronous_policy_loader_unittest.cc index f253a2b..3280b47 100644 --- a/chrome/browser/policy/asynchronous_policy_loader_unittest.cc +++ b/chrome/browser/policy/asynchronous_policy_loader_unittest.cc @@ -10,9 +10,10 @@ #include "chrome/browser/policy/mock_configuration_policy_provider.h" #include "testing/gmock/include/gmock/gmock.h" -using ::testing::_; using ::testing::InSequence; +using ::testing::Mock; using ::testing::Return; +using ::testing::_; namespace policy { @@ -66,9 +67,10 @@ ACTION(RescheduleImmediatePolicyReload) { TEST_F(AsynchronousPolicyLoaderTest, InitialLoad) { DictionaryValue* template_dict(new DictionaryValue()); - EXPECT_CALL(*delegate_, Load()).WillOnce(Return(template_dict)); + ProviderDelegateMock* delegate = new ProviderDelegateMock(); + EXPECT_CALL(*delegate, Load()).WillOnce(Return(template_dict)); scoped_refptr<AsynchronousPolicyLoader> loader = - new AsynchronousPolicyLoader(delegate_.release(), 10); + new AsynchronousPolicyLoader(delegate, 10); loader->Init(ignore_callback_); const DictionaryValue* loaded_dict(loader->policy()); EXPECT_TRUE(loaded_dict->Equals(template_dict)); @@ -78,15 +80,16 @@ TEST_F(AsynchronousPolicyLoaderTest, InitialLoad) { TEST_F(AsynchronousPolicyLoaderTest, InitialLoadWithFallback) { int dictionary_number = 0; InSequence s; - EXPECT_CALL(*delegate_, Load()).WillOnce( + ProviderDelegateMock* delegate = new ProviderDelegateMock(); + EXPECT_CALL(*delegate, Load()).WillOnce( CreateSequencedTestDictionary(&dictionary_number)); - EXPECT_CALL(*delegate_, Load()).WillOnce( + EXPECT_CALL(*delegate, Load()).WillOnce( CreateSequencedTestDictionary(&dictionary_number)); scoped_refptr<AsynchronousPolicyLoader> loader = - new AsynchronousPolicyLoader(delegate_.release(), 10); + new AsynchronousPolicyLoader(delegate, 10); loader->Init(ignore_callback_); loop_.RunAllPending(); - loader->Reload(); + loader->Reload(true); loop_.RunAllPending(); const DictionaryValue* loaded_dict(loader->policy()); @@ -98,15 +101,16 @@ TEST_F(AsynchronousPolicyLoaderTest, InitialLoadWithFallback) { // Ensure that calling stop on the loader stops subsequent reloads from // happening. TEST_F(AsynchronousPolicyLoaderTest, Stop) { - ON_CALL(*delegate_, Load()).WillByDefault(CreateTestDictionary()); - EXPECT_CALL(*delegate_, Load()).Times(1); + ProviderDelegateMock* delegate = new ProviderDelegateMock(); + ON_CALL(*delegate, Load()).WillByDefault(CreateTestDictionary()); + EXPECT_CALL(*delegate, Load()).Times(1); scoped_refptr<AsynchronousPolicyLoader> loader = - new AsynchronousPolicyLoader(delegate_.release(), 10); + new AsynchronousPolicyLoader(delegate, 10); loader->Init(ignore_callback_); loop_.RunAllPending(); loader->Stop(); loop_.RunAllPending(); - loader->Reload(); + loader->Reload(true); loop_.RunAllPending(); } @@ -116,30 +120,34 @@ TEST_F(AsynchronousPolicyLoaderTest, ProviderNotificationOnPolicyChange) { MockConfigurationPolicyObserver observer; int dictionary_number_1 = 0; int dictionary_number_2 = 0; - EXPECT_CALL(*delegate_, Load()).WillOnce( - CreateSequencedTestDictionary(&dictionary_number_1)); - EXPECT_CALL(*delegate_, Load()).WillOnce( - CreateSequencedTestDictionary(&dictionary_number_2)); - EXPECT_CALL(observer, OnUpdatePolicy()).Times(1); - EXPECT_CALL(*delegate_, Load()).WillOnce( - CreateSequencedTestDictionary(&dictionary_number_2)); - EXPECT_CALL(observer, OnUpdatePolicy()).Times(1); - EXPECT_CALL(*delegate_, Load()).WillOnce( + + ProviderDelegateMock* delegate = new ProviderDelegateMock(); + EXPECT_CALL(*delegate, Load()).WillOnce( CreateSequencedTestDictionary(&dictionary_number_1)); - EXPECT_CALL(observer, OnUpdatePolicy()).Times(1); + scoped_refptr<AsynchronousPolicyLoader> loader = - new AsynchronousPolicyLoader(delegate_.release(), 10); + new AsynchronousPolicyLoader(delegate, 10); AsynchronousPolicyProvider provider(NULL, loader); // |registrar| must be declared last so that it is destroyed first. ConfigurationPolicyObserverRegistrar registrar; registrar.Init(&provider, &observer); + Mock::VerifyAndClearExpectations(delegate); + + EXPECT_CALL(*delegate, Load()).WillOnce( + CreateSequencedTestDictionary(&dictionary_number_2)); + EXPECT_CALL(observer, OnUpdatePolicy()).Times(1); + loader->Reload(true); loop_.RunAllPending(); - loader->Reload(); - loop_.RunAllPending(); - loader->Reload(); - loop_.RunAllPending(); - loader->Reload(); + Mock::VerifyAndClearExpectations(delegate); + Mock::VerifyAndClearExpectations(&observer); + + EXPECT_CALL(*delegate, Load()).WillOnce( + CreateSequencedTestDictionary(&dictionary_number_1)); + EXPECT_CALL(observer, OnUpdatePolicy()).Times(1); + loader->Reload(true); loop_.RunAllPending(); + Mock::VerifyAndClearExpectations(delegate); + Mock::VerifyAndClearExpectations(&observer); } } // namespace policy diff --git a/chrome/browser/policy/asynchronous_policy_provider.cc b/chrome/browser/policy/asynchronous_policy_provider.cc index 8161465..54057ab 100644 --- a/chrome/browser/policy/asynchronous_policy_provider.cc +++ b/chrome/browser/policy/asynchronous_policy_provider.cc @@ -27,6 +27,10 @@ AsynchronousPolicyProvider::~AsynchronousPolicyProvider() { loader_->Stop(); } +void AsynchronousPolicyProvider::ForceReload() { + loader_->Reload(true); +} + bool AsynchronousPolicyProvider::ProvideInternal(PolicyMap* map) { DCHECK(CalledOnValidThread()); DCHECK(loader_->policy()); @@ -34,8 +38,4 @@ bool AsynchronousPolicyProvider::ProvideInternal(PolicyMap* map) { return true; } -scoped_refptr<AsynchronousPolicyLoader> AsynchronousPolicyProvider::loader() { - return loader_; -} - } // namespace policy diff --git a/chrome/browser/policy/asynchronous_policy_provider.h b/chrome/browser/policy/asynchronous_policy_provider.h index 7ae1170..b0dbed3 100644 --- a/chrome/browser/policy/asynchronous_policy_provider.h +++ b/chrome/browser/policy/asynchronous_policy_provider.h @@ -37,13 +37,13 @@ class AsynchronousPolicyProvider scoped_refptr<AsynchronousPolicyLoader> loader); virtual ~AsynchronousPolicyProvider(); + // Force a policy reload from the underlying data source. + void ForceReload(); + + protected: // ConfigurationPolicyProvider implementation. virtual bool ProvideInternal(PolicyMap* map) OVERRIDE; - // For tests to trigger reloads. - scoped_refptr<AsynchronousPolicyLoader> loader(); - - protected: // The loader object used internally. scoped_refptr<AsynchronousPolicyLoader> loader_; diff --git a/chrome/browser/policy/asynchronous_policy_provider_unittest.cc b/chrome/browser/policy/asynchronous_policy_provider_unittest.cc index fec42a1..95c51ab 100644 --- a/chrome/browser/policy/asynchronous_policy_provider_unittest.cc +++ b/chrome/browser/policy/asynchronous_policy_provider_unittest.cc @@ -11,9 +11,9 @@ #include "testing/gmock/include/gmock/gmock.h" #include "testing/gtest/include/gtest/gtest.h" -using ::testing::_; using ::testing::InSequence; using ::testing::Return; +using ::testing::_; namespace policy { @@ -22,10 +22,11 @@ TEST_F(AsynchronousPolicyTestBase, Provide) { InSequence s; DictionaryValue* policies = new DictionaryValue(); policies->SetBoolean(policy::key::kSyncDisabled, true); - EXPECT_CALL(*delegate_, Load()).WillOnce(Return(policies)); + ProviderDelegateMock* delegate = new ProviderDelegateMock(); + EXPECT_CALL(*delegate, Load()).WillOnce(Return(policies)); AsynchronousPolicyProvider provider( GetChromePolicyDefinitionList(), - new AsynchronousPolicyLoader(delegate_.release(), 10)); + new AsynchronousPolicyLoader(delegate, 10)); PolicyMap policy_map; provider.Provide(&policy_map); EXPECT_TRUE(policy_map.Get(policy::kPolicySyncDisabled)); @@ -38,17 +39,17 @@ TEST_F(AsynchronousPolicyTestBase, ProvideAfterRefresh) { InSequence s; DictionaryValue* original_policies = new DictionaryValue(); original_policies->SetBoolean(policy::key::kSyncDisabled, true); - EXPECT_CALL(*delegate_, Load()).WillOnce(Return(original_policies)); + ProviderDelegateMock* delegate = new ProviderDelegateMock(); + EXPECT_CALL(*delegate, Load()).WillOnce(Return(original_policies)); DictionaryValue* refresh_policies = new DictionaryValue(); refresh_policies->SetBoolean( policy::key::kJavascriptEnabled, true); - EXPECT_CALL(*delegate_, Load()).WillOnce(Return(refresh_policies)); - AsynchronousPolicyLoader* loader = - new AsynchronousPolicyLoader(delegate_.release(), 10); + EXPECT_CALL(*delegate, Load()).WillOnce(Return(refresh_policies)); + AsynchronousPolicyLoader* loader = new AsynchronousPolicyLoader(delegate, 10); AsynchronousPolicyProvider provider(GetChromePolicyDefinitionList(), loader); loop_.RunAllPending(); - loader->Reload(); + provider.ForceReload(); PolicyMap policy_map; provider.Provide(&policy_map); EXPECT_TRUE(policy_map.Get(policy::kPolicySyncDisabled)); diff --git a/chrome/browser/policy/asynchronous_policy_test_base.cc b/chrome/browser/policy/asynchronous_policy_test_base.cc index 50510ec..68887fe 100644 --- a/chrome/browser/policy/asynchronous_policy_test_base.cc +++ b/chrome/browser/policy/asynchronous_policy_test_base.cc @@ -19,10 +19,6 @@ AsynchronousPolicyTestBase::AsynchronousPolicyTestBase() AsynchronousPolicyTestBase::~AsynchronousPolicyTestBase() {} -void AsynchronousPolicyTestBase::SetUp() { - delegate_.reset(new ProviderDelegateMock()); -} - void AsynchronousPolicyTestBase::TearDown() { loop_.RunAllPending(); } diff --git a/chrome/browser/policy/asynchronous_policy_test_base.h b/chrome/browser/policy/asynchronous_policy_test_base.h index 7e11d29..7771490 100644 --- a/chrome/browser/policy/asynchronous_policy_test_base.h +++ b/chrome/browser/policy/asynchronous_policy_test_base.h @@ -34,15 +34,11 @@ class AsynchronousPolicyTestBase : public testing::Test { virtual ~AsynchronousPolicyTestBase(); // testing::Test: - virtual void SetUp(); virtual void TearDown(); protected: - MessageLoop loop_; - - // The mocks that are used in the test must outlive the scope of the test - // because they still get accessed in the RunAllPending of the TearDown. - scoped_ptr<ProviderDelegateMock> delegate_; + // Create an actual IO loop (needed by FilePathWatcher). + MessageLoopForIO loop_; private: content::TestBrowserThread ui_thread_; diff --git a/chrome/browser/policy/config_dir_policy_provider_unittest.cc b/chrome/browser/policy/config_dir_policy_provider_unittest.cc index bb71813..4a43a55 100644 --- a/chrome/browser/policy/config_dir_policy_provider_unittest.cc +++ b/chrome/browser/policy/config_dir_policy_provider_unittest.cc @@ -2,58 +2,136 @@ // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. -#include <algorithm> - +#include "base/compiler_specific.h" #include "base/file_util.h" #include "base/json/json_value_serializer.h" -#include "base/path_service.h" #include "base/scoped_temp_dir.h" #include "base/string_number_conversions.h" +#include "base/values.h" #include "chrome/browser/policy/config_dir_policy_provider.h" -#include "chrome/browser/policy/configuration_policy_pref_store.h" -#include "chrome/browser/policy/policy_map.h" -#include "content/test/test_browser_thread.h" -#include "policy/policy_constants.h" -#include "testing/gtest/include/gtest/gtest.h" - -using content::BrowserThread; +#include "chrome/browser/policy/configuration_policy_provider_test.h" namespace policy { -template<typename BASE> -class ConfigDirPolicyProviderTestBase : public BASE { - protected: - ConfigDirPolicyProviderTestBase() {} +namespace { - virtual void SetUp() { - ASSERT_TRUE(test_dir_.CreateUniqueTempDir()); - } +class TestHarness : public PolicyProviderTestHarness { + public: + TestHarness(); + virtual ~TestHarness(); - // JSON-encode a dictionary and write it to a file. - void WriteConfigFile(const DictionaryValue& dict, - const std::string& file_name) { - std::string data; - JSONStringValueSerializer serializer(&data); - serializer.Serialize(dict); - const FilePath file_path(test_dir().AppendASCII(file_name)); - ASSERT_TRUE(file_util::WriteFile(file_path, data.c_str(), data.size())); - } + virtual void SetUp() OVERRIDE; + + virtual AsynchronousPolicyProvider* CreateProvider( + const PolicyDefinitionList* policy_definition_list) OVERRIDE; + + virtual void InstallEmptyPolicy() OVERRIDE; + virtual void InstallStringPolicy(const std::string& policy_name, + const std::string& policy_value) OVERRIDE; + virtual void InstallIntegerPolicy(const std::string& policy_name, + int policy_value) OVERRIDE; + virtual void InstallBooleanPolicy(const std::string& policy_name, + bool policy_value) OVERRIDE; + virtual void InstallStringListPolicy(const std::string& policy_name, + const ListValue* policy_value) OVERRIDE; const FilePath& test_dir() { return test_dir_.path(); } + // JSON-encode a dictionary and write it to a file. + void WriteConfigFile(const base::DictionaryValue& dict, + const std::string& file_name); + + static PolicyProviderTestHarness* Create(); + private: ScopedTempDir test_dir_; + + DISALLOW_COPY_AND_ASSIGN(TestHarness); }; -class ConfigDirPolicyLoaderTest - : public ConfigDirPolicyProviderTestBase<testing::Test> { +TestHarness::TestHarness() {} + +TestHarness::~TestHarness() {} + +void TestHarness::SetUp() { + ASSERT_TRUE(test_dir_.CreateUniqueTempDir()); +} + +AsynchronousPolicyProvider* TestHarness::CreateProvider( + const PolicyDefinitionList* policy_definition_list) { + return new ConfigDirPolicyProvider(policy_definition_list, test_dir()); +} + +void TestHarness::InstallEmptyPolicy() { + DictionaryValue dict; + WriteConfigFile(dict, "policy"); +} + +void TestHarness::InstallStringPolicy(const std::string& policy_name, + const std::string& policy_value) { + DictionaryValue dict; + dict.SetString(policy_name, policy_value); + WriteConfigFile(dict, "policy"); +} + +void TestHarness::InstallIntegerPolicy(const std::string& policy_name, + int policy_value) { + DictionaryValue dict; + dict.SetInteger(policy_name, policy_value); + WriteConfigFile(dict, "policy"); +} + +void TestHarness::InstallBooleanPolicy(const std::string& policy_name, + bool policy_value) { + DictionaryValue dict; + dict.SetBoolean(policy_name, policy_value); + WriteConfigFile(dict, "policy"); +} + +void TestHarness::InstallStringListPolicy(const std::string& policy_name, + const ListValue* policy_value) { + DictionaryValue dict; + dict.Set(policy_name, policy_value->DeepCopy()); + WriteConfigFile(dict, "policy"); +} + +void TestHarness::WriteConfigFile(const base::DictionaryValue& dict, + const std::string& file_name) { + std::string data; + JSONStringValueSerializer serializer(&data); + serializer.Serialize(dict); + const FilePath file_path(test_dir().AppendASCII(file_name)); + ASSERT_TRUE(file_util::WriteFile(file_path, data.c_str(), data.size())); +} + +// static +PolicyProviderTestHarness* TestHarness::Create() { + return new TestHarness(); +} + +} // namespace + +// Instantiate abstract test case for basic policy reading tests. +INSTANTIATE_TEST_CASE_P( + ConfigDirPolicyProviderTest, + ConfigurationPolicyProviderTest, + testing::Values(TestHarness::Create)); + +// Some tests that exercise special functionality in ConfigDirPolicyLoader. +class ConfigDirPolicyLoaderTest : public testing::Test { + protected: + void SetUp() { + harness_.SetUp(); + } + + TestHarness harness_; }; // The preferences dictionary is expected to be empty when there are no files to // load. TEST_F(ConfigDirPolicyLoaderTest, ReadPrefsEmpty) { - ConfigDirPolicyProviderDelegate loader(test_dir()); - scoped_ptr<DictionaryValue> policy(loader.Load()); + ConfigDirPolicyProviderDelegate loader(harness_.test_dir()); + scoped_ptr<base::DictionaryValue> policy(loader.Load()); EXPECT_TRUE(policy.get()); EXPECT_TRUE(policy->empty()); } @@ -61,330 +139,34 @@ TEST_F(ConfigDirPolicyLoaderTest, ReadPrefsEmpty) { // Reading from a non-existent directory should result in an empty preferences // dictionary. TEST_F(ConfigDirPolicyLoaderTest, ReadPrefsNonExistentDirectory) { - FilePath non_existent_dir(test_dir().Append(FILE_PATH_LITERAL("not_there"))); + FilePath non_existent_dir( + harness_.test_dir().Append(FILE_PATH_LITERAL("not_there"))); ConfigDirPolicyProviderDelegate loader(non_existent_dir); - scoped_ptr<DictionaryValue> policy(loader.Load()); + scoped_ptr<base::DictionaryValue> policy(loader.Load()); EXPECT_TRUE(policy.get()); EXPECT_TRUE(policy->empty()); } -// Test reading back a single preference value. -TEST_F(ConfigDirPolicyLoaderTest, ReadPrefsSinglePref) { - DictionaryValue test_dict; - test_dict.SetString("HomepageLocation", "http://www.google.com"); - WriteConfigFile(test_dict, "config_file"); - - ConfigDirPolicyProviderDelegate loader(test_dir()); - scoped_ptr<DictionaryValue> policy(loader.Load()); - EXPECT_TRUE(policy.get()); - EXPECT_TRUE(policy->Equals(&test_dict)); -} - // Test merging values from different files. TEST_F(ConfigDirPolicyLoaderTest, ReadPrefsMergePrefs) { // Write a bunch of data files in order to increase the chance to detect the // provider not respecting lexicographic ordering when reading them. Since the // filesystem may return files in arbitrary order, there is no way to be sure, // but this is better than nothing. - DictionaryValue test_dict_bar; + base::DictionaryValue test_dict_bar; test_dict_bar.SetString("HomepageLocation", "http://bar.com"); for (unsigned int i = 1; i <= 4; ++i) - WriteConfigFile(test_dict_bar, base::IntToString(i)); - DictionaryValue test_dict_foo; + harness_.WriteConfigFile(test_dict_bar, base::IntToString(i)); + base::DictionaryValue test_dict_foo; test_dict_foo.SetString("HomepageLocation", "http://foo.com"); - WriteConfigFile(test_dict_foo, "9"); + harness_.WriteConfigFile(test_dict_foo, "9"); for (unsigned int i = 5; i <= 8; ++i) - WriteConfigFile(test_dict_bar, base::IntToString(i)); + harness_.WriteConfigFile(test_dict_bar, base::IntToString(i)); - ConfigDirPolicyProviderDelegate loader(test_dir()); - scoped_ptr<DictionaryValue> policy(loader.Load()); + ConfigDirPolicyProviderDelegate loader(harness_.test_dir()); + scoped_ptr<base::DictionaryValue> policy(loader.Load()); EXPECT_TRUE(policy.get()); EXPECT_TRUE(policy->Equals(&test_dict_foo)); } -// Holds policy type, corresponding policy key string and a valid value for use -// in parametrized value tests. -class ValueTestParams { - public: - // Assumes ownership of |test_value|. - ValueTestParams(ConfigurationPolicyType type, - const char* policy_key, - Value* test_value) - : type_(type), - policy_key_(policy_key), - test_value_(test_value) {} - - // testing::TestWithParam does copying, so provide copy constructor and - // assignment operator. - ValueTestParams(const ValueTestParams& other) - : type_(other.type_), - policy_key_(other.policy_key_), - test_value_(other.test_value_->DeepCopy()) {} - - const ValueTestParams& operator=(ValueTestParams other) { - swap(other); - return *this; - } - - void swap(ValueTestParams& other) { - std::swap(type_, other.type_); - std::swap(policy_key_, other.policy_key_); - test_value_.swap(other.test_value_); - } - - ConfigurationPolicyType type() const { return type_; } - const char* policy_key() const { return policy_key_; } - const Value* test_value() const { return test_value_.get(); } - - // Factory methods that create parameter objects for different value types. - static ValueTestParams ForStringPolicy( - ConfigurationPolicyType type, - const char* policy_key) { - return ValueTestParams(type, policy_key, Value::CreateStringValue("test")); - } - static ValueTestParams ForBooleanPolicy( - ConfigurationPolicyType type, - const char* policy_key) { - return ValueTestParams(type, policy_key, Value::CreateBooleanValue(true)); - } - static ValueTestParams ForIntegerPolicy( - ConfigurationPolicyType type, - const char* policy_key) { - return ValueTestParams(type, policy_key, Value::CreateIntegerValue(42)); - } - static ValueTestParams ForListPolicy( - ConfigurationPolicyType type, - const char* policy_key) { - ListValue* value = new ListValue(); - value->Set(0U, Value::CreateStringValue("first")); - value->Set(1U, Value::CreateStringValue("second")); - return ValueTestParams(type, policy_key, value); - } - - private: - ConfigurationPolicyType type_; - const char* policy_key_; - scoped_ptr<Value> test_value_; -}; - -// Tests whether the provider correctly reads a value from the file and forwards -// it to the store. -class ConfigDirPolicyProviderValueTest - : public ConfigDirPolicyProviderTestBase< - testing::TestWithParam<ValueTestParams> > { - protected: - ConfigDirPolicyProviderValueTest() - : ui_thread_(BrowserThread::UI, &loop_), - file_thread_(BrowserThread::FILE, &loop_) {} - - virtual void TearDown() { - loop_.RunAllPending(); - } - - private: - MessageLoop loop_; - content::TestBrowserThread ui_thread_; - content::TestBrowserThread file_thread_; -}; - -TEST_P(ConfigDirPolicyProviderValueTest, Default) { - ConfigDirPolicyProvider provider(GetChromePolicyDefinitionList(), test_dir()); - PolicyMap policy_map; - EXPECT_TRUE(provider.Provide(&policy_map)); - EXPECT_TRUE(policy_map.empty()); -} - -TEST_P(ConfigDirPolicyProviderValueTest, TestValue) { - DictionaryValue dict; - dict.Set(GetParam().policy_key(), GetParam().test_value()->DeepCopy()); - WriteConfigFile(dict, "policy"); - ConfigDirPolicyProvider provider(GetChromePolicyDefinitionList(), test_dir()); - PolicyMap policy_map; - EXPECT_TRUE(provider.Provide(&policy_map)); - EXPECT_EQ(1U, policy_map.size()); - const Value* value = policy_map.Get(GetParam().type()); - ASSERT_TRUE(value); - EXPECT_TRUE(GetParam().test_value()->Equals(value)); -} - -// Test parameters for all supported policies. testing::Values() has a limit of -// 50 parameters which is reached in this instantiation; new policies should go -// in a new instantiation. -INSTANTIATE_TEST_CASE_P( - ConfigDirPolicyProviderValueTestInstance, - ConfigDirPolicyProviderValueTest, - testing::Values( - ValueTestParams::ForStringPolicy( - kPolicyHomepageLocation, - key::kHomepageLocation), - ValueTestParams::ForBooleanPolicy( - kPolicyHomepageIsNewTabPage, - key::kHomepageIsNewTabPage), - ValueTestParams::ForIntegerPolicy( - kPolicyRestoreOnStartup, - key::kRestoreOnStartup), - ValueTestParams::ForListPolicy( - kPolicyRestoreOnStartupURLs, - key::kRestoreOnStartupURLs), - ValueTestParams::ForBooleanPolicy( - kPolicyDefaultSearchProviderEnabled, - key::kDefaultSearchProviderEnabled), - ValueTestParams::ForStringPolicy( - kPolicyDefaultSearchProviderName, - key::kDefaultSearchProviderName), - ValueTestParams::ForStringPolicy( - kPolicyDefaultSearchProviderKeyword, - key::kDefaultSearchProviderKeyword), - ValueTestParams::ForStringPolicy( - kPolicyDefaultSearchProviderSearchURL, - key::kDefaultSearchProviderSearchURL), - ValueTestParams::ForStringPolicy( - kPolicyDefaultSearchProviderSuggestURL, - key::kDefaultSearchProviderSuggestURL), - ValueTestParams::ForStringPolicy( - kPolicyDefaultSearchProviderInstantURL, - key::kDefaultSearchProviderInstantURL), - ValueTestParams::ForStringPolicy( - kPolicyDefaultSearchProviderIconURL, - key::kDefaultSearchProviderIconURL), - ValueTestParams::ForListPolicy( - kPolicyDefaultSearchProviderEncodings, - key::kDefaultSearchProviderEncodings), - ValueTestParams::ForStringPolicy( - kPolicyProxyMode, - key::kProxyMode), - ValueTestParams::ForIntegerPolicy( - kPolicyProxyServerMode, - key::kProxyServerMode), - ValueTestParams::ForStringPolicy( - kPolicyProxyServer, - key::kProxyServer), - ValueTestParams::ForStringPolicy( - kPolicyProxyPacUrl, - key::kProxyPacUrl), - ValueTestParams::ForStringPolicy( - kPolicyProxyBypassList, - key::kProxyBypassList), - ValueTestParams::ForBooleanPolicy( - kPolicyAlternateErrorPagesEnabled, - key::kAlternateErrorPagesEnabled), - ValueTestParams::ForBooleanPolicy( - kPolicySearchSuggestEnabled, - key::kSearchSuggestEnabled), - ValueTestParams::ForBooleanPolicy( - kPolicyDnsPrefetchingEnabled, - key::kDnsPrefetchingEnabled), - ValueTestParams::ForBooleanPolicy( - kPolicySafeBrowsingEnabled, - key::kSafeBrowsingEnabled), - ValueTestParams::ForBooleanPolicy( - kPolicyMetricsReportingEnabled, - key::kMetricsReportingEnabled), - ValueTestParams::ForBooleanPolicy( - kPolicyPasswordManagerEnabled, - key::kPasswordManagerEnabled), - ValueTestParams::ForBooleanPolicy( - kPolicyPasswordManagerAllowShowPasswords, - key::kPasswordManagerAllowShowPasswords), - ValueTestParams::ForListPolicy( - kPolicyDisabledPlugins, - key::kDisabledPlugins), - ValueTestParams::ForListPolicy( - kPolicyDisabledPluginsExceptions, - key::kDisabledPluginsExceptions), - ValueTestParams::ForListPolicy( - kPolicyEnabledPlugins, - key::kEnabledPlugins), - ValueTestParams::ForBooleanPolicy( - kPolicyAutoFillEnabled, - key::kAutoFillEnabled), - ValueTestParams::ForStringPolicy( - kPolicyApplicationLocaleValue, - key::kApplicationLocaleValue), - ValueTestParams::ForBooleanPolicy( - kPolicySyncDisabled, - key::kSyncDisabled), - ValueTestParams::ForListPolicy( - kPolicyExtensionInstallWhitelist, - key::kExtensionInstallWhitelist), - ValueTestParams::ForListPolicy( - kPolicyExtensionInstallBlacklist, - key::kExtensionInstallBlacklist), - ValueTestParams::ForBooleanPolicy( - kPolicyShowHomeButton, - key::kShowHomeButton), - ValueTestParams::ForBooleanPolicy( - kPolicyPrintingEnabled, - key::kPrintingEnabled), - ValueTestParams::ForBooleanPolicy( - kPolicyInstantEnabled, - key::kInstantEnabled), - ValueTestParams::ForIntegerPolicy( - kPolicyIncognitoModeAvailability, - key::kIncognitoModeAvailability), - ValueTestParams::ForBooleanPolicy( - kPolicyDisablePluginFinder, - key::kDisablePluginFinder), - ValueTestParams::ForBooleanPolicy( - kPolicyClearSiteDataOnExit, - key::kClearSiteDataOnExit), - ValueTestParams::ForStringPolicy( - kPolicyDownloadDirectory, - key::kDownloadDirectory), - ValueTestParams::ForBooleanPolicy( - kPolicyDefaultBrowserSettingEnabled, - key::kDefaultBrowserSettingEnabled), - ValueTestParams::ForBooleanPolicy( - kPolicyCloudPrintProxyEnabled, - key::kCloudPrintProxyEnabled), - ValueTestParams::ForBooleanPolicy( - kPolicyTranslateEnabled, - key::kTranslateEnabled), - ValueTestParams::ForBooleanPolicy( - kPolicyAllowOutdatedPlugins, - key::kAllowOutdatedPlugins), - ValueTestParams::ForBooleanPolicy( - kPolicyAlwaysAuthorizePlugins, - key::kAlwaysAuthorizePlugins), - ValueTestParams::ForBooleanPolicy( - kPolicyBookmarkBarEnabled, - key::kBookmarkBarEnabled), - ValueTestParams::ForBooleanPolicy( - kPolicyEditBookmarksEnabled, - key::kEditBookmarksEnabled), - ValueTestParams::ForListPolicy( - kPolicyDisabledSchemes, - key::kDisabledSchemes), - ValueTestParams::ForStringPolicy( - kPolicyDiskCacheDir, - key::kDiskCacheDir), - ValueTestParams::ForListPolicy( - kPolicyURLBlacklist, - key::kURLBlacklist), - ValueTestParams::ForListPolicy( - kPolicyURLWhitelist, - key::kURLWhitelist))); - -// Adds additional cases that can't be included in -// ConfigDirPolicyProviderValueTestInstance since testing::Values is limited -// to 50 entries. -INSTANTIATE_TEST_CASE_P( - ConfigDirPolicyProviderValueTestInstanceContinued, - ConfigDirPolicyProviderValueTest, - testing::Values( - ValueTestParams::ForBooleanPolicy( - kPolicyCloudPrintSubmitEnabled, - key::kCloudPrintSubmitEnabled))); - -// Test parameters for all policies that are supported on ChromeOS only. -#if defined(OS_CHROMEOS) -INSTANTIATE_TEST_CASE_P( - ConfigDirPolicyProviderValueTestChromeOSInstance, - ConfigDirPolicyProviderValueTest, - testing::Values( - ValueTestParams::ForIntegerPolicy( - kPolicyPolicyRefreshRate, - key::kPolicyRefreshRate))); -#endif - } // namespace policy diff --git a/chrome/browser/policy/configuration_policy_loader_win.cc b/chrome/browser/policy/configuration_policy_loader_win.cc index 49b1053..03d12d1 100644 --- a/chrome/browser/policy/configuration_policy_loader_win.cc +++ b/chrome/browser/policy/configuration_policy_loader_win.cc @@ -33,6 +33,14 @@ ConfigurationPolicyLoaderWin::ConfigurationPolicyLoaderWin( } } +void ConfigurationPolicyLoaderWin::Reload(bool force) { + DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); + // Reset the watches BEFORE reading the individual policies to avoid + // missing a change notification. + SetupWatches(); + AsynchronousPolicyLoader::Reload(force); +} + void ConfigurationPolicyLoaderWin::InitOnFileThread() { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); AsynchronousPolicyLoader::InitOnFileThread(); @@ -69,21 +77,13 @@ void ConfigurationPolicyLoaderWin::SetupWatches() { ScheduleFallbackReloadTask(); } -void ConfigurationPolicyLoaderWin::Reload() { - DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); - // Reset the watches BEFORE reading the individual policies to avoid - // missing a change notification. - SetupWatches(); - AsynchronousPolicyLoader::Reload(); -} - void ConfigurationPolicyLoaderWin::OnObjectSignaled(HANDLE object) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); DCHECK(object == user_policy_changed_event_.handle() || object == machine_policy_changed_event_.handle()) << "unexpected object signaled policy reload, obj = " << std::showbase << std::hex << object; - Reload(); + Reload(false); } } // namespace policy diff --git a/chrome/browser/policy/configuration_policy_loader_win.h b/chrome/browser/policy/configuration_policy_loader_win.h index 88fafe4..d0317a9 100644 --- a/chrome/browser/policy/configuration_policy_loader_win.h +++ b/chrome/browser/policy/configuration_policy_loader_win.h @@ -23,6 +23,9 @@ class ConfigurationPolicyLoaderWin int reload_interval_minutes); virtual ~ConfigurationPolicyLoaderWin() {} + // AsynchronousPolicyLoader overrides: + virtual void Reload(bool force) OVERRIDE; + protected: // AsynchronousPolicyLoader overrides: virtual void InitOnFileThread() OVERRIDE; @@ -32,9 +35,6 @@ class ConfigurationPolicyLoaderWin // Updates the watchers and schedules the reload task if appropriate. void SetupWatches(); - // Post a reload notification and update the watch machinery. - void Reload(); - // ObjectWatcher::Delegate overrides: virtual void OnObjectSignaled(HANDLE object) OVERRIDE; diff --git a/chrome/browser/policy/configuration_policy_provider_mac_unittest.cc b/chrome/browser/policy/configuration_policy_provider_mac_unittest.cc index c2f7ce4..46ebc91 100644 --- a/chrome/browser/policy/configuration_policy_provider_mac_unittest.cc +++ b/chrome/browser/policy/configuration_policy_provider_mac_unittest.cc @@ -4,11 +4,12 @@ #include <gtest/gtest.h> +#include "base/basictypes.h" #include "base/mac/scoped_cftyperef.h" -#include "base/stl_util.h" #include "base/sys_string_conversions.h" -#include "chrome/browser/policy/configuration_policy_pref_store.h" +#include "chrome/browser/policy/asynchronous_policy_test_base.h" #include "chrome/browser/policy/configuration_policy_provider_mac.h" +#include "chrome/browser/policy/configuration_policy_provider_test.h" #include "chrome/browser/policy/policy_map.h" #include "chrome/browser/preferences_mock_mac.h" #include "policy/policy_constants.h" @@ -16,354 +17,141 @@ namespace policy { -// Holds parameters for the parametrized policy tests. -class PolicyTestParams { +namespace { + +class TestHarness : public PolicyProviderTestHarness { public: - // Takes ownership of |test_value|. - PolicyTestParams(ConfigurationPolicyType type, - const char* policy_name, - Value* test_value) - : type_(type), - policy_name_(policy_name), - test_value_(test_value) {} + TestHarness(); + virtual ~TestHarness(); - // testing::TestWithParam does copying, so provide copy constructor and - // assignment operator. - PolicyTestParams(const PolicyTestParams& other) - : type_(other.type_), - policy_name_(other.policy_name_), - test_value_(other.test_value_->DeepCopy()) {} + virtual void SetUp() OVERRIDE; - const PolicyTestParams& operator=(PolicyTestParams other) { - swap(other); - return *this; - } + virtual AsynchronousPolicyProvider* CreateProvider( + const PolicyDefinitionList* policy_definition_list) OVERRIDE; - void swap(PolicyTestParams& other) { - std::swap(type_, other.type_); - std::swap(policy_name_, other.policy_name_); - test_value_.swap(other.test_value_); - } + virtual void InstallEmptyPolicy() OVERRIDE; + virtual void InstallStringPolicy(const std::string& policy_name, + const std::string& policy_value) OVERRIDE; + virtual void InstallIntegerPolicy(const std::string& policy_name, + int policy_value) OVERRIDE; + virtual void InstallBooleanPolicy(const std::string& policy_name, + bool policy_value) OVERRIDE; + virtual void InstallStringListPolicy(const std::string& policy_name, + const ListValue* policy_value) OVERRIDE; - ConfigurationPolicyType type() const { return type_; } - const char* policy_name() const { return policy_name_; } - const Value* test_value() const { return test_value_.get(); } - - // Get the test value in the appropriate CFPropertyListRef representation. - CFPropertyListRef GetPropertyListValue() const { - switch (test_value_->GetType()) { - case Value::TYPE_BOOLEAN: { - bool v; - if (!test_value_->GetAsBoolean(&v)) - return NULL; - return CFRetain(v ? kCFBooleanTrue : kCFBooleanFalse); - } - case Value::TYPE_INTEGER: { - int v; - if (!test_value_->GetAsInteger(&v)) - return NULL; - return CFNumberCreate(NULL, kCFNumberIntType, &v); - } - case Value::TYPE_STRING: { - std::string v; - if (!test_value_->GetAsString(&v)) - return NULL; - return base::SysUTF8ToCFStringRef(v); - } - case Value::TYPE_LIST: { - const ListValue* list = - static_cast<const ListValue*>(test_value_.get()); - base::mac::ScopedCFTypeRef<CFMutableArrayRef> array( - CFArrayCreateMutable(NULL, list->GetSize(), - &kCFTypeArrayCallBacks)); - for (ListValue::const_iterator element(list->begin()); - element != list->end(); ++element) { - if (!(*element)->IsType(Value::TYPE_STRING)) - return NULL; - std::string element_value; - if (!(*element)->GetAsString(&element_value)) - return NULL; - base::mac::ScopedCFTypeRef<CFStringRef> cf_element_value( - base::SysUTF8ToCFStringRef(element_value)); - CFArrayAppendValue(array, cf_element_value.get()); - } - return array.release(); - } - default: - return NULL; - } - } - - // Factory methods that create parameter objects for different value types. - static PolicyTestParams ForStringPolicy( - ConfigurationPolicyType type, - const char* name) { - return PolicyTestParams(type, name, Value::CreateStringValue("test")); - } - static PolicyTestParams ForBooleanPolicy( - ConfigurationPolicyType type, - const char* name) { - return PolicyTestParams(type, name, Value::CreateBooleanValue(true)); - } - static PolicyTestParams ForIntegerPolicy( - ConfigurationPolicyType type, - const char* name) { - return PolicyTestParams(type, name, Value::CreateIntegerValue(42)); - } - static PolicyTestParams ForListPolicy( - ConfigurationPolicyType type, - const char* name) { - ListValue* value = new ListValue; - value->Set(0U, Value::CreateStringValue("first")); - value->Set(1U, Value::CreateStringValue("second")); - return PolicyTestParams(type, name, value); - } + static PolicyProviderTestHarness* Create(); private: - ConfigurationPolicyType type_; - const char* policy_name_; - scoped_ptr<Value> test_value_; + MockPreferences* prefs_; + + DISALLOW_COPY_AND_ASSIGN(TestHarness); }; -// Parametrized test class for testing whether ConfigurationPolicyProviderMac -// can handle all policies correctly. -class ConfigurationPolicyProviderMacTest - : public testing::TestWithParam<PolicyTestParams> { - public: - virtual void SetUp() { - prefs_ = new MockPreferences; +TestHarness::TestHarness() {} + +TestHarness::~TestHarness() {} + +void TestHarness::SetUp() {} + +AsynchronousPolicyProvider* TestHarness::CreateProvider( + const PolicyDefinitionList* policy_definition_list) { + prefs_ = new MockPreferences(); + return new ConfigurationPolicyProviderMac(policy_definition_list, prefs_); +} + +void TestHarness::InstallEmptyPolicy() {} + +void TestHarness::InstallStringPolicy(const std::string& policy_name, + const std::string& policy_value) { + prefs_->AddTestItem(base::SysUTF8ToCFStringRef(policy_name), + base::SysUTF8ToCFStringRef(policy_value), + true); +} + +void TestHarness::InstallIntegerPolicy(const std::string& policy_name, + int policy_value) { + prefs_->AddTestItem(base::SysUTF8ToCFStringRef(policy_name), + CFNumberCreate(NULL, kCFNumberIntType, &policy_value), + true); +} + +void TestHarness::InstallBooleanPolicy(const std::string& policy_name, + bool policy_value) { + prefs_->AddTestItem(base::SysUTF8ToCFStringRef(policy_name), + CFRetain(policy_value ? kCFBooleanTrue : kCFBooleanFalse), + true); +} + +void TestHarness::InstallStringListPolicy(const std::string& policy_name, + const ListValue* policy_value) { + base::mac::ScopedCFTypeRef<CFMutableArrayRef> array( + CFArrayCreateMutable(NULL, policy_value->GetSize(), + &kCFTypeArrayCallBacks)); + for (ListValue::const_iterator element(policy_value->begin()); + element != policy_value->end(); ++element) { + std::string element_value; + if (!(*element)->GetAsString(&element_value)) + continue; + CFArrayAppendValue(array, base::SysUTF8ToCFStringRef(element_value)); } + prefs_->AddTestItem(base::SysUTF8ToCFStringRef(policy_name), + array.release(), + true); +} + +// static +PolicyProviderTestHarness* TestHarness::Create() { + return new TestHarness(); +} + +} // namespace + +// Instantiate abstract test case for basic policy reading tests. +INSTANTIATE_TEST_CASE_P( + ConfigurationPolicyProviderMacTest, + ConfigurationPolicyProviderTest, + testing::Values(TestHarness::Create)); + +// Special test cases for some mac preferences details. +class ConfigurationPolicyProviderMacTest : public AsynchronousPolicyTestBase { protected: + ConfigurationPolicyProviderMacTest() + : prefs_(new MockPreferences()), + provider_(&test_policy_definitions::kList, prefs_) {} + virtual ~ConfigurationPolicyProviderMacTest() {} + MockPreferences* prefs_; + ConfigurationPolicyProviderMac provider_; }; -TEST_P(ConfigurationPolicyProviderMacTest, Default) { - ConfigurationPolicyProviderMac provider( - GetChromePolicyDefinitionList(), prefs_); - PolicyMap policy_map; - EXPECT_TRUE(provider.Provide(&policy_map)); - EXPECT_TRUE(policy_map.empty()); -} - -TEST_P(ConfigurationPolicyProviderMacTest, Invalid) { +TEST_F(ConfigurationPolicyProviderMacTest, Invalid) { base::mac::ScopedCFTypeRef<CFStringRef> name( - base::SysUTF8ToCFStringRef(GetParam().policy_name())); + base::SysUTF8ToCFStringRef(test_policy_definitions::kKeyString)); base::mac::ScopedCFTypeRef<CFDataRef> invalid_data( CFDataCreate(NULL, NULL, 0)); prefs_->AddTestItem(name, invalid_data.get(), true); // Create the provider and have it read |prefs_|. - ConfigurationPolicyProviderMac provider( - GetChromePolicyDefinitionList(), prefs_); + provider_.ForceReload(); PolicyMap policy_map; - EXPECT_TRUE(provider.Provide(&policy_map)); + EXPECT_TRUE(provider_.Provide(&policy_map)); EXPECT_TRUE(policy_map.empty()); } -TEST_P(ConfigurationPolicyProviderMacTest, TestNonForcedValue) { +TEST_F(ConfigurationPolicyProviderMacTest, TestNonForcedValue) { base::mac::ScopedCFTypeRef<CFStringRef> name( - base::SysUTF8ToCFStringRef(GetParam().policy_name())); + base::SysUTF8ToCFStringRef(test_policy_definitions::kKeyString)); base::mac::ScopedCFTypeRef<CFPropertyListRef> test_value( - GetParam().GetPropertyListValue()); + base::SysUTF8ToCFStringRef("string value")); ASSERT_TRUE(test_value.get()); prefs_->AddTestItem(name, test_value.get(), false); // Create the provider and have it read |prefs_|. - ConfigurationPolicyProviderMac provider( - GetChromePolicyDefinitionList(), prefs_); + provider_.ForceReload(); PolicyMap policy_map; - EXPECT_TRUE(provider.Provide(&policy_map)); + EXPECT_TRUE(provider_.Provide(&policy_map)); EXPECT_TRUE(policy_map.empty()); } -TEST_P(ConfigurationPolicyProviderMacTest, TestValue) { - base::mac::ScopedCFTypeRef<CFStringRef> name( - base::SysUTF8ToCFStringRef(GetParam().policy_name())); - base::mac::ScopedCFTypeRef<CFPropertyListRef> test_value( - GetParam().GetPropertyListValue()); - ASSERT_TRUE(test_value.get()); - prefs_->AddTestItem(name, test_value, true); - - // Create the provider and have it read |prefs_|. - ConfigurationPolicyProviderMac provider( - GetChromePolicyDefinitionList(), prefs_); - PolicyMap policy_map; - EXPECT_TRUE(provider.Provide(&policy_map)); - ASSERT_EQ(1U, policy_map.size()); - const Value* value = policy_map.Get(GetParam().type()); - ASSERT_TRUE(value); - EXPECT_TRUE(GetParam().test_value()->Equals(value)); -} - -// Test parameters for all supported policies. testing::Values() has a limit of -// 50 parameters which is reached in this instantiation; new policies should go -// in the next instantiation after this one. -INSTANTIATE_TEST_CASE_P( - ConfigurationPolicyProviderMacTestInstance, - ConfigurationPolicyProviderMacTest, - testing::Values( - PolicyTestParams::ForStringPolicy( - kPolicyHomepageLocation, - key::kHomepageLocation), - PolicyTestParams::ForBooleanPolicy( - kPolicyHomepageIsNewTabPage, - key::kHomepageIsNewTabPage), - PolicyTestParams::ForIntegerPolicy( - kPolicyRestoreOnStartup, - key::kRestoreOnStartup), - PolicyTestParams::ForListPolicy( - kPolicyRestoreOnStartupURLs, - key::kRestoreOnStartupURLs), - PolicyTestParams::ForBooleanPolicy( - kPolicyDefaultSearchProviderEnabled, - key::kDefaultSearchProviderEnabled), - PolicyTestParams::ForStringPolicy( - kPolicyDefaultSearchProviderName, - key::kDefaultSearchProviderName), - PolicyTestParams::ForStringPolicy( - kPolicyDefaultSearchProviderKeyword, - key::kDefaultSearchProviderKeyword), - PolicyTestParams::ForStringPolicy( - kPolicyDefaultSearchProviderSearchURL, - key::kDefaultSearchProviderSearchURL), - PolicyTestParams::ForStringPolicy( - kPolicyDefaultSearchProviderSuggestURL, - key::kDefaultSearchProviderSuggestURL), - PolicyTestParams::ForStringPolicy( - kPolicyDefaultSearchProviderInstantURL, - key::kDefaultSearchProviderInstantURL), - PolicyTestParams::ForStringPolicy( - kPolicyDefaultSearchProviderIconURL, - key::kDefaultSearchProviderIconURL), - PolicyTestParams::ForListPolicy( - kPolicyDefaultSearchProviderEncodings, - key::kDefaultSearchProviderEncodings), - PolicyTestParams::ForStringPolicy( - kPolicyProxyMode, - key::kProxyMode), - PolicyTestParams::ForIntegerPolicy( - kPolicyProxyServerMode, - key::kProxyServerMode), - PolicyTestParams::ForStringPolicy( - kPolicyProxyServer, - key::kProxyServer), - PolicyTestParams::ForStringPolicy( - kPolicyProxyPacUrl, - key::kProxyPacUrl), - PolicyTestParams::ForStringPolicy( - kPolicyProxyBypassList, - key::kProxyBypassList), - PolicyTestParams::ForBooleanPolicy( - kPolicyAlternateErrorPagesEnabled, - key::kAlternateErrorPagesEnabled), - PolicyTestParams::ForBooleanPolicy( - kPolicySearchSuggestEnabled, - key::kSearchSuggestEnabled), - PolicyTestParams::ForBooleanPolicy( - kPolicyDnsPrefetchingEnabled, - key::kDnsPrefetchingEnabled), - PolicyTestParams::ForBooleanPolicy( - kPolicySafeBrowsingEnabled, - key::kSafeBrowsingEnabled), - PolicyTestParams::ForBooleanPolicy( - kPolicyMetricsReportingEnabled, - key::kMetricsReportingEnabled), - PolicyTestParams::ForBooleanPolicy( - kPolicyPasswordManagerEnabled, - key::kPasswordManagerEnabled), - PolicyTestParams::ForBooleanPolicy( - kPolicyPasswordManagerAllowShowPasswords, - key::kPasswordManagerAllowShowPasswords), - PolicyTestParams::ForListPolicy( - kPolicyDisabledPlugins, - key::kDisabledPlugins), - PolicyTestParams::ForListPolicy( - kPolicyDisabledPluginsExceptions, - key::kDisabledPluginsExceptions), - PolicyTestParams::ForListPolicy( - kPolicyEnabledPlugins, - key::kEnabledPlugins), - PolicyTestParams::ForBooleanPolicy( - kPolicyAutoFillEnabled, - key::kAutoFillEnabled), - PolicyTestParams::ForStringPolicy( - kPolicyApplicationLocaleValue, - key::kApplicationLocaleValue), - PolicyTestParams::ForBooleanPolicy( - kPolicySyncDisabled, - key::kSyncDisabled), - PolicyTestParams::ForListPolicy( - kPolicyExtensionInstallWhitelist, - key::kExtensionInstallWhitelist), - PolicyTestParams::ForListPolicy( - kPolicyExtensionInstallBlacklist, - key::kExtensionInstallBlacklist), - PolicyTestParams::ForBooleanPolicy( - kPolicyShowHomeButton, - key::kShowHomeButton), - PolicyTestParams::ForBooleanPolicy( - kPolicyPrintingEnabled, - key::kPrintingEnabled), - PolicyTestParams::ForBooleanPolicy( - kPolicyInstantEnabled, - key::kInstantEnabled), - PolicyTestParams::ForBooleanPolicy( - kPolicyDisablePluginFinder, - key::kDisablePluginFinder), - PolicyTestParams::ForBooleanPolicy( - kPolicyClearSiteDataOnExit, - key::kClearSiteDataOnExit), - PolicyTestParams::ForStringPolicy( - kPolicyDownloadDirectory, - key::kDownloadDirectory), - PolicyTestParams::ForBooleanPolicy( - kPolicyDefaultBrowserSettingEnabled, - key::kDefaultBrowserSettingEnabled), - PolicyTestParams::ForBooleanPolicy( - kPolicyCloudPrintProxyEnabled, - key::kCloudPrintProxyEnabled), - PolicyTestParams::ForBooleanPolicy( - kPolicyTranslateEnabled, - key::kTranslateEnabled), - PolicyTestParams::ForBooleanPolicy( - kPolicyAllowOutdatedPlugins, - key::kAllowOutdatedPlugins), - PolicyTestParams::ForBooleanPolicy( - kPolicyAlwaysAuthorizePlugins, - key::kAlwaysAuthorizePlugins), - PolicyTestParams::ForBooleanPolicy( - kPolicyBookmarkBarEnabled, - key::kBookmarkBarEnabled), - PolicyTestParams::ForBooleanPolicy( - kPolicyEditBookmarksEnabled, - key::kEditBookmarksEnabled), - PolicyTestParams::ForBooleanPolicy( - kPolicyAllowFileSelectionDialogs, - key::kAllowFileSelectionDialogs), - PolicyTestParams::ForListPolicy( - kPolicyDisabledSchemes, - key::kDisabledSchemes), - PolicyTestParams::ForStringPolicy( - kPolicyDiskCacheDir, - key::kDiskCacheDir), - PolicyTestParams::ForIntegerPolicy( - kPolicyMaxConnectionsPerProxy, - key::kMaxConnectionsPerProxy), - PolicyTestParams::ForListPolicy( - kPolicyURLBlacklist, - key::kURLBlacklist))); - -// testing::Values has a limit of 50 test templates, which is reached by the -// instantiations above. Add tests for new policies here: -INSTANTIATE_TEST_CASE_P( - ConfigurationPolicyProviderMacTestInstance2, - ConfigurationPolicyProviderMacTest, - testing::Values( - PolicyTestParams::ForListPolicy( - kPolicyURLWhitelist, - key::kURLWhitelist), - PolicyTestParams::ForBooleanPolicy( - kPolicyCloudPrintSubmitEnabled, - key::kCloudPrintSubmitEnabled))); } // namespace policy diff --git a/chrome/browser/policy/configuration_policy_provider_test.cc b/chrome/browser/policy/configuration_policy_provider_test.cc new file mode 100644 index 0000000..6997e61 --- /dev/null +++ b/chrome/browser/policy/configuration_policy_provider_test.cc @@ -0,0 +1,143 @@ +// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#include "chrome/browser/policy/configuration_policy_provider_test.h" + +#include "base/bind.h" +#include "base/values.h" +#include "chrome/browser/policy/asynchronous_policy_loader.h" +#include "chrome/browser/policy/asynchronous_policy_provider.h" +#include "chrome/browser/policy/configuration_policy_provider.h" +#include "chrome/browser/policy/policy_map.h" +#include "policy/policy_constants.h" + +namespace policy { + +namespace test_policy_definitions { + +const char kKeyString[] = "StringPolicy"; +const char kKeyBoolean[] = "BooleanPolicy"; +const char kKeyInteger[] = "IntegerPolicy"; +const char kKeyStringList[] = "StringListPolicy"; + +// In order to have correct enum values, we alias these to some actual policies. +const ConfigurationPolicyType kPolicyString = kPolicyHomepageLocation; +const ConfigurationPolicyType kPolicyBoolean = kPolicyHomepageIsNewTabPage; +const ConfigurationPolicyType kPolicyInteger = kPolicyRestoreOnStartup; +const ConfigurationPolicyType kPolicyStringList = kPolicyRestoreOnStartupURLs; + +static const PolicyDefinitionList::Entry kEntries[] = { + { kPolicyString, base::Value::TYPE_STRING, kKeyString }, + { kPolicyBoolean, base::Value::TYPE_BOOLEAN, kKeyBoolean }, + { kPolicyInteger, base::Value::TYPE_INTEGER, kKeyInteger }, + { kPolicyStringList, base::Value::TYPE_LIST, kKeyStringList }, +}; + +const PolicyDefinitionList kList = { + kEntries, kEntries + arraysize(kEntries) +}; + +} // namespace test_policy_definitions + +PolicyProviderTestHarness::PolicyProviderTestHarness() {} + +PolicyProviderTestHarness::~PolicyProviderTestHarness() {} + +ConfigurationPolicyProviderTest::ConfigurationPolicyProviderTest() {} + +ConfigurationPolicyProviderTest::~ConfigurationPolicyProviderTest() {} + +void ConfigurationPolicyProviderTest::SetUp() { + AsynchronousPolicyTestBase::SetUp(); + + test_harness_.reset((*GetParam())()); + test_harness_->SetUp(); + + provider_.reset( + test_harness_->CreateProvider(&test_policy_definitions::kList)); + + PolicyMap policy_map; + EXPECT_TRUE(provider_->Provide(&policy_map)); + EXPECT_TRUE(policy_map.empty()); +} + +void ConfigurationPolicyProviderTest::TearDown() { + // Give providers the chance to clean up after themselves on the file thread. + provider_.reset(); + + AsynchronousPolicyTestBase::TearDown(); +} + +void ConfigurationPolicyProviderTest::CheckValue( + const char* policy_name, + ConfigurationPolicyType policy_type, + const base::Value& expected_value, + base::Closure install_value) { + // Install the value, reload policy and check the provider for the value. + install_value.Run(); + provider_->ForceReload(); + loop_.RunAllPending(); + PolicyMap policy_map; + EXPECT_TRUE(provider_->Provide(&policy_map)); + EXPECT_EQ(1U, policy_map.size()); + EXPECT_TRUE(base::Value::Equals(&expected_value, + policy_map.Get(policy_type))); +} + +TEST_P(ConfigurationPolicyProviderTest, Empty) { + provider_->ForceReload(); + loop_.RunAllPending(); + PolicyMap policy_map; + EXPECT_TRUE(provider_->Provide(&policy_map)); + EXPECT_TRUE(policy_map.empty()); +} + +TEST_P(ConfigurationPolicyProviderTest, StringValue) { + const char kTestString[] = "string_value"; + StringValue expected_value(kTestString); + CheckValue(test_policy_definitions::kKeyString, + test_policy_definitions::kPolicyString, + expected_value, + base::Bind(&PolicyProviderTestHarness::InstallStringPolicy, + base::Unretained(test_harness_.get()), + test_policy_definitions::kKeyString, + kTestString)); +} + +TEST_P(ConfigurationPolicyProviderTest, BooleanValue) { + base::FundamentalValue expected_value(true); + CheckValue(test_policy_definitions::kKeyBoolean, + test_policy_definitions::kPolicyBoolean, + expected_value, + base::Bind(&PolicyProviderTestHarness::InstallBooleanPolicy, + base::Unretained(test_harness_.get()), + test_policy_definitions::kKeyBoolean, + true)); +} + +TEST_P(ConfigurationPolicyProviderTest, IntegerValue) { + base::FundamentalValue expected_value(42); + CheckValue(test_policy_definitions::kKeyInteger, + test_policy_definitions::kPolicyInteger, + expected_value, + base::Bind(&PolicyProviderTestHarness::InstallIntegerPolicy, + base::Unretained(test_harness_.get()), + test_policy_definitions::kKeyInteger, + 42)); +} + +TEST_P(ConfigurationPolicyProviderTest, StringListValue) { + base::ListValue expected_value; + expected_value.Set(0U, base::Value::CreateStringValue("first")); + expected_value.Set(1U, base::Value::CreateStringValue("second")); + CheckValue(test_policy_definitions::kKeyStringList, + test_policy_definitions::kPolicyStringList, + expected_value, + base::Bind(&PolicyProviderTestHarness::InstallStringListPolicy, + base::Unretained(test_harness_.get()), + test_policy_definitions::kKeyStringList, + &expected_value)); +} + +} // namespace policy diff --git a/chrome/browser/policy/configuration_policy_provider_test.h b/chrome/browser/policy/configuration_policy_provider_test.h new file mode 100644 index 0000000..90b36f0 --- /dev/null +++ b/chrome/browser/policy/configuration_policy_provider_test.h @@ -0,0 +1,112 @@ +// Copyright (c) 2011 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. + +#ifndef CHROME_BROWSER_POLICY_CONFIGURATION_POLICY_PROVIDER_TEST_H_ +#define CHROME_BROWSER_POLICY_CONFIGURATION_POLICY_PROVIDER_TEST_H_ +#pragma once + +#include <string> + +#include "base/basictypes.h" +#include "base/callback.h" +#include "base/memory/scoped_ptr.h" +#include "base/message_loop.h" +#include "chrome/browser/policy/asynchronous_policy_test_base.h" +#include "content/test/test_browser_thread.h" +#include "policy/configuration_policy_type.h" +#include "testing/gtest/include/gtest/gtest.h" + +namespace base { +class ListValue; +} + +namespace policy { + +class AsynchronousPolicyProvider; +struct PolicyDefinitionList; + +// A stripped-down policy definition list that contains entries for the +// different policy setting types supported. +namespace test_policy_definitions { + +// String policy keys. +extern const char kKeyString[]; +extern const char kKeyBoolean[]; +extern const char kKeyInteger[]; +extern const char kKeyStringList[]; + +// Corresponding type constants. +extern const ConfigurationPolicyType kPolicyString; +extern const ConfigurationPolicyType kPolicyBoolean; +extern const ConfigurationPolicyType kPolicyInteger; +extern const ConfigurationPolicyType kPolicyStringList; + +// Policy definition list that contains entries for the keys above. +extern const PolicyDefinitionList kList; + +} // namespace test_policy_definitions + +// An interface for creating a test policy provider and creating a policy +// provider instance for testing. Used as the parameter to the abstract +// ConfigurationPolicyProviderTest below. +class PolicyProviderTestHarness { + public: + PolicyProviderTestHarness(); + virtual ~PolicyProviderTestHarness(); + + // Actions to run at gtest SetUp() time. + virtual void SetUp() = 0; + + // Create a new policy provider. + virtual AsynchronousPolicyProvider* CreateProvider( + const PolicyDefinitionList* policy_definition_list) = 0; + + // Helpers to configure the environment the policy provider reads from. + virtual void InstallEmptyPolicy() = 0; + virtual void InstallStringPolicy(const std::string& policy_name, + const std::string& policy_value) = 0; + virtual void InstallIntegerPolicy(const std::string& policy_name, + int policy_value) = 0; + virtual void InstallBooleanPolicy(const std::string& policy_name, + bool policy_value) = 0; + virtual void InstallStringListPolicy(const std::string& policy_name, + const ListValue* policy_value) = 0; + + private: + DISALLOW_COPY_AND_ASSIGN(PolicyProviderTestHarness); +}; + +// A factory method for creating a test harness. +typedef PolicyProviderTestHarness* (*CreatePolicyProviderTestHarness)(); + +// Abstract policy provider test. This is meant to be instantiated for each +// policy provider implementation, passing in a suitable harness factory +// function as the test parameter. +class ConfigurationPolicyProviderTest + : public AsynchronousPolicyTestBase, + public testing::WithParamInterface<CreatePolicyProviderTestHarness> { + protected: + ConfigurationPolicyProviderTest(); + virtual ~ConfigurationPolicyProviderTest(); + + virtual void SetUp(); + virtual void TearDown(); + + // Installs a valid policy and checks whether the provider returns the + // |expected_value|. + void CheckValue(const char* policy_name, + ConfigurationPolicyType policy_type, + const base::Value& expected_value, + base::Closure install_value); + + scoped_ptr<PolicyProviderTestHarness> test_harness_; + scoped_ptr<AsynchronousPolicyProvider> provider_; + + private: + DISALLOW_COPY_AND_ASSIGN(ConfigurationPolicyProviderTest); +}; + +} // namespace policy + +#endif // CHROME_BROWSER_POLICY_CONFIGURATION_POLICY_PROVIDER_TEST_H_ diff --git a/chrome/browser/policy/configuration_policy_provider_win_unittest.cc b/chrome/browser/policy/configuration_policy_provider_win_unittest.cc index dc03bdb..bab9997 100644 --- a/chrome/browser/policy/configuration_policy_provider_win_unittest.cc +++ b/chrome/browser/policy/configuration_policy_provider_win_unittest.cc @@ -5,24 +5,18 @@ #include <gtest/gtest.h> #include <windows.h> -#include "base/memory/scoped_ptr.h" -#include "base/message_loop.h" -#include "base/stl_util.h" +#include "base/string16.h" #include "base/string_number_conversions.h" -#include "base/string_piece.h" #include "base/utf_string_conversions.h" #include "base/win/registry.h" -#include "chrome/browser/policy/asynchronous_policy_loader.h" -#include "chrome/browser/policy/configuration_policy_pref_store.h" +#include "chrome/browser/policy/asynchronous_policy_test_base.h" +#include "chrome/browser/policy/configuration_policy_provider_test.h" #include "chrome/browser/policy/configuration_policy_provider_win.h" #include "chrome/browser/policy/policy_map.h" -#include "chrome/common/pref_names.h" -#include "content/test/test_browser_thread.h" #include "policy/policy_constants.h" #include "testing/gtest/include/gtest/gtest.h" using base::win::RegKey; -using content::BrowserThread; namespace policy { @@ -34,153 +28,69 @@ const wchar_t kUnitTestMachineOverrideSubKey[] = const wchar_t kUnitTestUserOverrideSubKey[] = L"SOFTWARE\\Chromium Unit Tests\\HKCU Override"; -// Holds policy type, corresponding policy name string and a valid value for use -// in parametrized value tests. -class PolicyTestParams { +// This class provides sandboxing and mocking for the parts of the Windows +// Registry implementing Group Policy. It prepares two temporary sandbox keys +// in |kUnitTestRegistrySubKey|, one for HKLM and one for HKCU. A test's calls +// to the registry are redirected by Windows to these sandboxes, allowing the +// tests to manipulate and access policy as if it were active, but without +// actually changing the parts of the Registry that are managed by Group +// Policy. +class ScopedGroupPolicyRegistrySandbox { public: - // Assumes ownership of |hklm_value| and |hkcu_value|. - PolicyTestParams(ConfigurationPolicyType type, - const char* policy_name, - Value* hklm_value, - Value* hkcu_value) - : type_(type), - policy_name_(policy_name), - hklm_value_(hklm_value), - hkcu_value_(hkcu_value) {} - - // testing::TestWithParam does copy the parameters, so provide copy - // constructor and assignment operator. - PolicyTestParams(const PolicyTestParams& other) - : type_(other.type_), - policy_name_(other.policy_name_), - hklm_value_(other.hklm_value_->DeepCopy()), - hkcu_value_(other.hkcu_value_->DeepCopy()) {} - - const PolicyTestParams& operator=(PolicyTestParams other) { - swap(other); - return *this; - } - - void swap(PolicyTestParams& other) { - std::swap(type_, other.type_); - std::swap(policy_name_, other.policy_name_); - hklm_value_.swap(other.hklm_value_); - hkcu_value_.swap(other.hkcu_value_); - } - - ConfigurationPolicyType type() const { return type_; } - const char* policy_name() const { return policy_name_; } - const Value* hklm_value() const { return hklm_value_.get(); } - const Value* hkcu_value() const { return hkcu_value_.get(); } - - // Factory methods for different value types. - static PolicyTestParams ForStringPolicy( - ConfigurationPolicyType type, - const char* policy_name) { - return PolicyTestParams(type, - policy_name, - Value::CreateStringValue("string_a"), - Value::CreateStringValue("string_b")); - } - static PolicyTestParams ForBooleanPolicy( - ConfigurationPolicyType type, - const char* policy_name) { - return PolicyTestParams(type, - policy_name, - Value::CreateBooleanValue(true), - Value::CreateBooleanValue(false)); - } - static PolicyTestParams ForIntegerPolicy( - ConfigurationPolicyType type, - const char* policy_name) { - return PolicyTestParams(type, - policy_name, - Value::CreateIntegerValue(42), - Value::CreateIntegerValue(17)); - } - static PolicyTestParams ForListPolicy( - ConfigurationPolicyType type, - const char* policy_name) { - ListValue* hklm_value = new ListValue; - hklm_value->Set(0U, Value::CreateStringValue("It's a plane!")); - ListValue* hkcu_value = new ListValue; - hkcu_value->Set(0U, Value::CreateStringValue("It's a bird!")); - hkcu_value->Set(0U, Value::CreateStringValue("It's a flying carpet!")); - return PolicyTestParams(type, policy_name, hklm_value, hkcu_value); - } + ScopedGroupPolicyRegistrySandbox(); + ~ScopedGroupPolicyRegistrySandbox(); private: - ConfigurationPolicyType type_; - const char* policy_name_; - scoped_ptr<Value> hklm_value_; - scoped_ptr<Value> hkcu_value_; -}; + void ActivateOverrides(); + void RemoveOverrides(); -} // namespace + // Deletes the sandbox keys. + void DeleteKeys(); -// This test class provides sandboxing and mocking for the parts of the -// Windows Registry implementing Group Policy. The |SetUp| method prepares -// two temporary sandbox keys in |kUnitTestRegistrySubKey|, one for HKLM and one -// for HKCU. A test's calls to the registry are redirected by Windows to these -// sandboxes, allowing the tests to manipulate and access policy as if it -// were active, but without actually changing the parts of the Registry that -// are managed by Group Policy. -class ConfigurationPolicyProviderWinTest - : public testing::TestWithParam<PolicyTestParams> { - public: - ConfigurationPolicyProviderWinTest(); - - // testing::Test method overrides: - virtual void SetUp(); - virtual void TearDown(); + // Keys are created for the lifetime of a test to contain + // the sandboxed HKCU and HKLM hives, respectively. + RegKey temp_hkcu_hive_key_; + RegKey temp_hklm_hive_key_; - void ActivateOverrides(); - void DeactivateOverrides(); + DISALLOW_COPY_AND_ASSIGN(ScopedGroupPolicyRegistrySandbox); +}; - // Deletes the registry key created during the tests. - void DeleteRegistrySandbox(); +class TestHarness : public PolicyProviderTestHarness { + public: + explicit TestHarness(HKEY hive); + virtual ~TestHarness(); - // Write a string value to the registry. - void WriteString(HKEY hive, const char* name, const wchar_t* value); - // Write a DWORD value to the registry. - void WriteDWORD(HKEY hive, const char* name, DWORD value); + virtual void SetUp() OVERRIDE; - // Write the given value to the registry. - void WriteValue(HKEY hive, const char* name, const Value* value); - // Write a value that is not compatible with the given |value|. - void WriteInvalidValue(HKEY hive, const char* name, const Value* value); + virtual AsynchronousPolicyProvider* CreateProvider( + const PolicyDefinitionList* policy_definition_list) OVERRIDE; - protected: - scoped_ptr<ConfigurationPolicyProviderWin> provider_; + virtual void InstallEmptyPolicy() OVERRIDE; + virtual void InstallStringPolicy(const std::string& policy_name, + const std::string& policy_value) OVERRIDE; + virtual void InstallIntegerPolicy(const std::string& policy_name, + int policy_value) OVERRIDE; + virtual void InstallBooleanPolicy(const std::string& policy_name, + bool policy_value) OVERRIDE; + virtual void InstallStringListPolicy(const std::string& policy_name, + const ListValue* policy_value) OVERRIDE; - // A message loop must be declared and instantiated for these tests, - // because Windows policy provider create WaitableEvents and - // ObjectWatchers that require the tests to have a MessageLoop associated - // with the thread executing the tests. - MessageLoop loop_; + // Creates a harness instance that will install policy in HKCU or HKLM, + // respectively. + static PolicyProviderTestHarness* CreateHKCU(); + static PolicyProviderTestHarness* CreateHKLM(); private: - content::TestBrowserThread ui_thread_; - content::TestBrowserThread file_thread_; + HKEY hive_; - // Keys are created for the lifetime of a test to contain - // the sandboxed HKCU and HKLM hives, respectively. - RegKey temp_hkcu_hive_key_; - RegKey temp_hklm_hive_key_; -}; + ScopedGroupPolicyRegistrySandbox registry_sandbox_; -ConfigurationPolicyProviderWinTest::ConfigurationPolicyProviderWinTest() - : ui_thread_(BrowserThread::UI, &loop_), - file_thread_(BrowserThread::FILE, &loop_), - temp_hklm_hive_key_(HKEY_CURRENT_USER, kUnitTestMachineOverrideSubKey, - KEY_READ), - temp_hkcu_hive_key_(HKEY_CURRENT_USER, kUnitTestUserOverrideSubKey, - KEY_READ) { -} + DISALLOW_COPY_AND_ASSIGN(TestHarness); +}; -void ConfigurationPolicyProviderWinTest::SetUp() { +ScopedGroupPolicyRegistrySandbox::ScopedGroupPolicyRegistrySandbox() { // Cleanup any remnants of previous tests. - DeleteRegistrySandbox(); + DeleteKeys(); // Create the subkeys to hold the overridden HKLM and HKCU // policy settings. @@ -192,339 +102,128 @@ void ConfigurationPolicyProviderWinTest::SetUp() { KEY_ALL_ACCESS); ActivateOverrides(); - - provider_.reset(new ConfigurationPolicyProviderWin( - GetChromePolicyDefinitionList())); } -void ConfigurationPolicyProviderWinTest::TearDown() { - DeactivateOverrides(); - DeleteRegistrySandbox(); - loop_.RunAllPending(); +ScopedGroupPolicyRegistrySandbox::~ScopedGroupPolicyRegistrySandbox() { + RemoveOverrides(); + DeleteKeys(); } -void ConfigurationPolicyProviderWinTest::ActivateOverrides() { - HRESULT result = RegOverridePredefKey(HKEY_LOCAL_MACHINE, - temp_hklm_hive_key_.Handle()); - EXPECT_EQ(ERROR_SUCCESS, result); - result = RegOverridePredefKey(HKEY_CURRENT_USER, - temp_hkcu_hive_key_.Handle()); - EXPECT_EQ(ERROR_SUCCESS, result); +void ScopedGroupPolicyRegistrySandbox::ActivateOverrides() { + ASSERT_HRESULT_SUCCEEDED(RegOverridePredefKey(HKEY_LOCAL_MACHINE, + temp_hklm_hive_key_.Handle())); + ASSERT_HRESULT_SUCCEEDED(RegOverridePredefKey(HKEY_CURRENT_USER, + temp_hkcu_hive_key_.Handle())); } -void ConfigurationPolicyProviderWinTest::DeactivateOverrides() { - uint32 result = RegOverridePredefKey(HKEY_LOCAL_MACHINE, 0); - EXPECT_EQ(ERROR_SUCCESS, result); - result = RegOverridePredefKey(HKEY_CURRENT_USER, 0); - EXPECT_EQ(ERROR_SUCCESS, result); +void ScopedGroupPolicyRegistrySandbox::RemoveOverrides() { + ASSERT_HRESULT_SUCCEEDED(RegOverridePredefKey(HKEY_LOCAL_MACHINE, 0)); + ASSERT_HRESULT_SUCCEEDED(RegOverridePredefKey(HKEY_CURRENT_USER, 0)); } -void ConfigurationPolicyProviderWinTest::DeleteRegistrySandbox() { - temp_hklm_hive_key_.Close(); - temp_hkcu_hive_key_.Close(); +void ScopedGroupPolicyRegistrySandbox::DeleteKeys() { RegKey key(HKEY_CURRENT_USER, kUnitTestRegistrySubKey, KEY_ALL_ACCESS); key.DeleteKey(L""); } -void ConfigurationPolicyProviderWinTest::WriteString(HKEY hive, - const char* name, - const wchar_t* value) { - RegKey key(hive, policy::kRegistrySubKey, KEY_ALL_ACCESS); - key.WriteValue(UTF8ToUTF16(name).c_str(), value); -} +TestHarness::TestHarness(HKEY hive) + : hive_(hive) {} -void ConfigurationPolicyProviderWinTest::WriteDWORD(HKEY hive, - const char* name, - DWORD value) { - RegKey key(hive, policy::kRegistrySubKey, KEY_ALL_ACCESS); - key.WriteValue(UTF8ToUTF16(name).c_str(), value); -} +TestHarness::~TestHarness() {} -void ConfigurationPolicyProviderWinTest::WriteValue(HKEY hive, - const char* name, - const Value* value) { - switch (value->GetType()) { - case Value::TYPE_BOOLEAN: { - bool v; - ASSERT_TRUE(value->GetAsBoolean(&v)); - WriteDWORD(hive, name, v); - break; - } - case Value::TYPE_INTEGER: { - int v; - ASSERT_TRUE(value->GetAsInteger(&v)); - WriteDWORD(hive, name, v); - break; - } - case Value::TYPE_STRING: { - std::string v; - ASSERT_TRUE(value->GetAsString(&v)); - WriteString(hive, name, UTF8ToUTF16(v).c_str()); - break; - } - case Value::TYPE_LIST: { - const ListValue* list = static_cast<const ListValue*>(value); - RegKey key(hive, - (string16(policy::kRegistrySubKey) + ASCIIToUTF16("\\") + - UTF8ToUTF16(name)).c_str(), - KEY_ALL_ACCESS); - int index = 1; - for (ListValue::const_iterator element(list->begin()); - element != list->end(); ++element) { - ASSERT_TRUE((*element)->IsType(Value::TYPE_STRING)); - std::string element_value; - ASSERT_TRUE((*element)->GetAsString(&element_value)); - key.WriteValue(base::IntToString16(index++).c_str(), - UTF8ToUTF16(element_value).c_str()); - } - break; - } - default: - FAIL() << "Unsupported value type " << value->GetType(); - break; - } +void TestHarness::SetUp() {} + +AsynchronousPolicyProvider* TestHarness::CreateProvider( + const PolicyDefinitionList* policy_definition_list) { + return new ConfigurationPolicyProviderWin(policy_definition_list); } -void ConfigurationPolicyProviderWinTest::WriteInvalidValue(HKEY hive, - const char* name, - const Value* value) { - if (value->IsType(Value::TYPE_STRING)) - WriteDWORD(hive, name, -1); - else - WriteString(hive, name, L"bad value"); +void TestHarness::InstallEmptyPolicy() {} + +void TestHarness::InstallStringPolicy(const std::string& policy_name, + const std::string& policy_value) { + RegKey key(hive_, policy::kRegistrySubKey, KEY_ALL_ACCESS); + key.WriteValue(UTF8ToUTF16(policy_name).c_str(), + UTF8ToUTF16(policy_value).c_str()); } -TEST_P(ConfigurationPolicyProviderWinTest, Default) { - PolicyMap policy_map; - provider_->Provide(&policy_map); - EXPECT_TRUE(policy_map.empty()); +void TestHarness::InstallIntegerPolicy(const std::string& policy_name, + int policy_value) { + RegKey key(hive_, policy::kRegistrySubKey, KEY_ALL_ACCESS); + key.WriteValue(UTF8ToUTF16(policy_name).c_str(), + static_cast<DWORD>(policy_value)); } -TEST_P(ConfigurationPolicyProviderWinTest, InvalidValue) { - WriteInvalidValue(HKEY_LOCAL_MACHINE, - GetParam().policy_name(), - GetParam().hklm_value()); - WriteInvalidValue(HKEY_CURRENT_USER, - GetParam().policy_name(), - GetParam().hkcu_value()); - provider_->loader()->Reload(); - loop_.RunAllPending(); - PolicyMap policy_map; - provider_->Provide(&policy_map); - EXPECT_TRUE(policy_map.empty()); +void TestHarness::InstallBooleanPolicy(const std::string& policy_name, + bool policy_value) { + RegKey key(hive_, policy::kRegistrySubKey, KEY_ALL_ACCESS); + key.WriteValue(UTF8ToUTF16(policy_name).c_str(), + static_cast<DWORD>(policy_value)); } -TEST_P(ConfigurationPolicyProviderWinTest, HKLM) { - WriteValue(HKEY_LOCAL_MACHINE, - GetParam().policy_name(), - GetParam().hklm_value()); - provider_->loader()->Reload(); - loop_.RunAllPending(); - PolicyMap policy_map; - provider_->Provide(&policy_map); - const Value* value = policy_map.Get(GetParam().type()); - ASSERT_TRUE(value); - EXPECT_TRUE(value->Equals(GetParam().hklm_value())); +void TestHarness::InstallStringListPolicy(const std::string& policy_name, + const ListValue* policy_value) { + RegKey key(hive_, + (string16(policy::kRegistrySubKey) + ASCIIToUTF16("\\") + + UTF8ToUTF16(policy_name)).c_str(), + KEY_ALL_ACCESS); + int index = 1; + for (ListValue::const_iterator element(policy_value->begin()); + element != policy_value->end(); + ++element) { + std::string element_value; + if (!(*element)->GetAsString(&element_value)) + continue; + std::string name(base::IntToString(index++)); + key.WriteValue(UTF8ToUTF16(name).c_str(), + UTF8ToUTF16(element_value).c_str()); + } } -TEST_P(ConfigurationPolicyProviderWinTest, HKCU) { - WriteValue(HKEY_CURRENT_USER, - GetParam().policy_name(), - GetParam().hkcu_value()); - provider_->loader()->Reload(); - loop_.RunAllPending(); - PolicyMap policy_map; - provider_->Provide(&policy_map); - const Value* value = policy_map.Get(GetParam().type()); - ASSERT_TRUE(value); - EXPECT_TRUE(value->Equals(GetParam().hkcu_value())); +// static +PolicyProviderTestHarness* TestHarness::CreateHKCU() { + return new TestHarness(HKEY_CURRENT_USER); } -TEST_P(ConfigurationPolicyProviderWinTest, HKLMOverHKCU) { - WriteValue(HKEY_LOCAL_MACHINE, - GetParam().policy_name(), - GetParam().hklm_value()); - WriteValue(HKEY_CURRENT_USER, - GetParam().policy_name(), - GetParam().hkcu_value()); - provider_->loader()->Reload(); - loop_.RunAllPending(); - PolicyMap policy_map; - provider_->Provide(&policy_map); - const Value* value = policy_map.Get(GetParam().type()); - ASSERT_TRUE(value); - EXPECT_TRUE(value->Equals(GetParam().hklm_value())); +// static +PolicyProviderTestHarness* TestHarness::CreateHKLM() { + return new TestHarness(HKEY_LOCAL_MACHINE); } -// Test parameters for all supported policies. testing::Values() has a limit of -// 50 parameters which is reached in this instantiation; new policies should go -// in the next instantiation after this one. -INSTANTIATE_TEST_CASE_P( - ConfigurationPolicyProviderWinTestInstance, - ConfigurationPolicyProviderWinTest, - testing::Values( - PolicyTestParams::ForStringPolicy( - kPolicyHomepageLocation, - key::kHomepageLocation), - PolicyTestParams::ForBooleanPolicy( - kPolicyHomepageIsNewTabPage, - key::kHomepageIsNewTabPage), - PolicyTestParams::ForIntegerPolicy( - kPolicyRestoreOnStartup, - key::kRestoreOnStartup), - PolicyTestParams::ForListPolicy( - kPolicyRestoreOnStartupURLs, - key::kRestoreOnStartupURLs), - PolicyTestParams::ForBooleanPolicy( - kPolicyDefaultSearchProviderEnabled, - key::kDefaultSearchProviderEnabled), - PolicyTestParams::ForStringPolicy( - kPolicyDefaultSearchProviderName, - key::kDefaultSearchProviderName), - PolicyTestParams::ForStringPolicy( - kPolicyDefaultSearchProviderKeyword, - key::kDefaultSearchProviderKeyword), - PolicyTestParams::ForStringPolicy( - kPolicyDefaultSearchProviderSearchURL, - key::kDefaultSearchProviderSearchURL), - PolicyTestParams::ForStringPolicy( - kPolicyDefaultSearchProviderSuggestURL, - key::kDefaultSearchProviderSuggestURL), - PolicyTestParams::ForStringPolicy( - kPolicyDefaultSearchProviderInstantURL, - key::kDefaultSearchProviderInstantURL), - PolicyTestParams::ForStringPolicy( - kPolicyDefaultSearchProviderIconURL, - key::kDefaultSearchProviderIconURL), - PolicyTestParams::ForListPolicy( - kPolicyDefaultSearchProviderEncodings, - key::kDefaultSearchProviderEncodings), - PolicyTestParams::ForStringPolicy( - kPolicyProxyMode, - key::kProxyMode), - PolicyTestParams::ForIntegerPolicy( - kPolicyProxyServerMode, - key::kProxyServerMode), - PolicyTestParams::ForStringPolicy( - kPolicyProxyServer, - key::kProxyServer), - PolicyTestParams::ForStringPolicy( - kPolicyProxyPacUrl, - key::kProxyPacUrl), - PolicyTestParams::ForStringPolicy( - kPolicyProxyBypassList, - key::kProxyBypassList), - PolicyTestParams::ForBooleanPolicy( - kPolicyAlternateErrorPagesEnabled, - key::kAlternateErrorPagesEnabled), - PolicyTestParams::ForBooleanPolicy( - kPolicySearchSuggestEnabled, - key::kSearchSuggestEnabled), - PolicyTestParams::ForBooleanPolicy( - kPolicyDnsPrefetchingEnabled, - key::kDnsPrefetchingEnabled), - PolicyTestParams::ForBooleanPolicy( - kPolicySafeBrowsingEnabled, - key::kSafeBrowsingEnabled), - PolicyTestParams::ForBooleanPolicy( - kPolicyMetricsReportingEnabled, - key::kMetricsReportingEnabled), - PolicyTestParams::ForBooleanPolicy( - kPolicyPasswordManagerEnabled, - key::kPasswordManagerEnabled), - PolicyTestParams::ForListPolicy( - kPolicyDisabledPlugins, - key::kDisabledPlugins), - PolicyTestParams::ForListPolicy( - kPolicyDisabledPluginsExceptions, - key::kDisabledPluginsExceptions), - PolicyTestParams::ForListPolicy( - kPolicyEnabledPlugins, - key::kEnabledPlugins), - PolicyTestParams::ForBooleanPolicy( - kPolicyAutoFillEnabled, - key::kAutoFillEnabled), - PolicyTestParams::ForBooleanPolicy( - kPolicySyncDisabled, - key::kSyncDisabled), - PolicyTestParams::ForStringPolicy( - kPolicyApplicationLocaleValue, - key::kApplicationLocaleValue), - PolicyTestParams::ForListPolicy( - kPolicyExtensionInstallWhitelist, - key::kExtensionInstallWhitelist), - PolicyTestParams::ForListPolicy( - kPolicyExtensionInstallBlacklist, - key::kExtensionInstallBlacklist), - PolicyTestParams::ForBooleanPolicy( - kPolicyShowHomeButton, - key::kShowHomeButton), - PolicyTestParams::ForBooleanPolicy( - kPolicyPrintingEnabled, - key::kPrintingEnabled), - PolicyTestParams::ForBooleanPolicy( - kPolicyInstantEnabled, - key::kInstantEnabled), - PolicyTestParams::ForIntegerPolicy( - kPolicyIncognitoModeAvailability, - key::kIncognitoModeAvailability), - PolicyTestParams::ForBooleanPolicy( - kPolicyDisablePluginFinder, - key::kDisablePluginFinder), - PolicyTestParams::ForBooleanPolicy( - kPolicyClearSiteDataOnExit, - key::kClearSiteDataOnExit), - PolicyTestParams::ForStringPolicy( - kPolicyDownloadDirectory, - key::kDownloadDirectory), - PolicyTestParams::ForBooleanPolicy( - kPolicyDefaultBrowserSettingEnabled, - key::kDefaultBrowserSettingEnabled), - PolicyTestParams::ForBooleanPolicy( - kPolicyCloudPrintProxyEnabled, - key::kCloudPrintProxyEnabled), - PolicyTestParams::ForBooleanPolicy( - kPolicyTranslateEnabled, - key::kTranslateEnabled), - PolicyTestParams::ForBooleanPolicy( - kPolicyAllowOutdatedPlugins, - key::kAllowOutdatedPlugins), - PolicyTestParams::ForBooleanPolicy( - kPolicyAlwaysAuthorizePlugins, - key::kAlwaysAuthorizePlugins), - PolicyTestParams::ForBooleanPolicy( - kPolicyBookmarkBarEnabled, - key::kBookmarkBarEnabled), - PolicyTestParams::ForBooleanPolicy( - kPolicyEditBookmarksEnabled, - key::kEditBookmarksEnabled), - PolicyTestParams::ForBooleanPolicy( - kPolicyAllowFileSelectionDialogs, - key::kAllowFileSelectionDialogs), - PolicyTestParams::ForListPolicy( - kPolicyDisabledSchemes, - key::kDisabledSchemes), - PolicyTestParams::ForStringPolicy( - kPolicyDiskCacheDir, - key::kDiskCacheDir), - PolicyTestParams::ForIntegerPolicy( - kPolicyMaxConnectionsPerProxy, - key::kMaxConnectionsPerProxy), - PolicyTestParams::ForListPolicy( - kPolicyURLBlacklist, - key::kURLBlacklist))); - -// testing::Values has a limit of 50 test templates, which is reached by the -// instantiations above. Add tests for new policies here: +} // namespace + +// Instantiate abstract test case for basic policy reading tests. INSTANTIATE_TEST_CASE_P( - ConfigurationPolicyProviderWinTestInstance2, ConfigurationPolicyProviderWinTest, - testing::Values( - PolicyTestParams::ForListPolicy( - kPolicyURLWhitelist, - key::kURLWhitelist), - PolicyTestParams::ForBooleanPolicy( - kPolicyCloudPrintSubmitEnabled, - key::kCloudPrintSubmitEnabled))); + ConfigurationPolicyProviderTest, + testing::Values(TestHarness::CreateHKCU, TestHarness::CreateHKLM)); + +// Test cases for windows policy provider specific functionality. +class ConfigurationPolicyProviderWinTest : public AsynchronousPolicyTestBase { + protected: + ConfigurationPolicyProviderWinTest() + : provider_(&test_policy_definitions::kList) {} + virtual ~ConfigurationPolicyProviderWinTest() {} + + ScopedGroupPolicyRegistrySandbox registry_sandbox_; + ConfigurationPolicyProviderWin provider_; +}; + +TEST_F(ConfigurationPolicyProviderWinTest, HKLMOverHKCU) { + RegKey hklm_key(HKEY_LOCAL_MACHINE, policy::kRegistrySubKey, KEY_ALL_ACCESS); + hklm_key.WriteValue(UTF8ToUTF16(test_policy_definitions::kKeyString).c_str(), + UTF8ToUTF16("hklm").c_str()); + RegKey hkcu_key(HKEY_CURRENT_USER, policy::kRegistrySubKey, KEY_ALL_ACCESS); + hkcu_key.WriteValue(UTF8ToUTF16(test_policy_definitions::kKeyString).c_str(), + UTF8ToUTF16("hkcu").c_str()); + + provider_.ForceReload(); + loop_.RunAllPending(); + + PolicyMap policy_map; + provider_.Provide(&policy_map); + const Value* value = policy_map.Get(test_policy_definitions::kPolicyString); + EXPECT_TRUE(StringValue("hklm").Equals(value)); +} } // namespace policy diff --git a/chrome/browser/policy/file_based_policy_loader.cc b/chrome/browser/policy/file_based_policy_loader.cc index c7a8691..343e320 100644 --- a/chrome/browser/policy/file_based_policy_loader.cc +++ b/chrome/browser/policy/file_based_policy_loader.cc @@ -61,7 +61,7 @@ class FileBasedPolicyWatcherDelegate : public FilePathWatcher::Delegate { void FileBasedPolicyLoader::OnFilePathChanged( const FilePath& path) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); - Reload(); + Reload(false); } void FileBasedPolicyLoader::OnFilePathError(const FilePath& path) { @@ -69,7 +69,7 @@ void FileBasedPolicyLoader::OnFilePathError(const FilePath& path) { << " failed."; } -void FileBasedPolicyLoader::Reload() { +void FileBasedPolicyLoader::Reload(bool force) { DCHECK(BrowserThread::CurrentlyOn(BrowserThread::FILE)); if (!delegate()) @@ -78,7 +78,7 @@ void FileBasedPolicyLoader::Reload() { // Check the directory time in order to see whether a reload is required. base::TimeDelta delay; base::Time now = base::Time::Now(); - if (!IsSafeToReloadPolicy(now, &delay)) { + if (!force && !IsSafeToReloadPolicy(now, &delay)) { ScheduleReloadTask(delay); return; } @@ -87,7 +87,7 @@ void FileBasedPolicyLoader::Reload() { scoped_ptr<DictionaryValue> new_policy(delegate()->Load()); // Check again in case the directory has changed while reading it. - if (!IsSafeToReloadPolicy(now, &delay)) { + if (!force && !IsSafeToReloadPolicy(now, &delay)) { ScheduleReloadTask(delay); return; } @@ -109,7 +109,7 @@ void FileBasedPolicyLoader::InitOnFileThread() { // There might have been changes to the directory in the time between // construction of the loader and initialization of the watcher. Call reload // to detect if that is the case. - Reload(); + Reload(false); ScheduleFallbackReloadTask(); } diff --git a/chrome/browser/policy/file_based_policy_loader.h b/chrome/browser/policy/file_based_policy_loader.h index e31d72c..e82a26e 100644 --- a/chrome/browser/policy/file_based_policy_loader.h +++ b/chrome/browser/policy/file_based_policy_loader.h @@ -33,7 +33,7 @@ class FileBasedPolicyLoader : public AsynchronousPolicyLoader { FileBasedPolicyProvider::ProviderDelegate* provider_delegate); // AsynchronousPolicyLoader overrides: - virtual void Reload() OVERRIDE; + virtual void Reload(bool force) OVERRIDE; void OnFilePathChanged(const FilePath& path); void OnFilePathError(const FilePath& path); diff --git a/chrome/browser/policy/file_based_policy_provider_unittest.cc b/chrome/browser/policy/file_based_policy_provider_unittest.cc index a6537d2..ba0f004 100644 --- a/chrome/browser/policy/file_based_policy_provider_unittest.cc +++ b/chrome/browser/policy/file_based_policy_provider_unittest.cc @@ -72,7 +72,7 @@ TEST_F(AsynchronousPolicyTestBase, ProviderRefresh) { DictionaryValue* policies = new DictionaryValue(); policies->SetBoolean(policy::key::kSyncDisabled, true); EXPECT_CALL(*provider_delegate, Load()).WillOnce(Return(policies)); - file_based_provider.loader()->Reload(); + file_based_provider.ForceReload(); loop_.RunAllPending(); PolicyMap policy_map; file_based_provider.Provide(&policy_map); |