config_dir_policy_provider_unittest.cc revision ddb351dbec246cf1fab5ec20d2d5520909041de1
1// Copyright (c) 2011 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.
4
5#include <algorithm>
6
7#include "base/file_util.h"
8#include "base/memory/scoped_temp_dir.h"
9#include "base/path_service.h"
10#include "base/string_number_conversions.h"
11#include "chrome/browser/policy/config_dir_policy_provider.h"
12#include "chrome/browser/policy/configuration_policy_pref_store.h"
13#include "chrome/browser/policy/mock_configuration_policy_store.h"
14#include "content/browser/browser_thread.h"
15#include "content/common/json_value_serializer.h"
16#include "policy/policy_constants.h"
17#include "testing/gtest/include/gtest/gtest.h"
18
19namespace policy {
20
21template<typename BASE>
22class ConfigDirPolicyProviderTestBase : public BASE {
23 protected:
24  ConfigDirPolicyProviderTestBase() {}
25
26  virtual void SetUp() {
27    ASSERT_TRUE(test_dir_.CreateUniqueTempDir());
28  }
29
30  // JSON-encode a dictionary and write it to a file.
31  void WriteConfigFile(const DictionaryValue& dict,
32                       const std::string& file_name) {
33    std::string data;
34    JSONStringValueSerializer serializer(&data);
35    serializer.Serialize(dict);
36    const FilePath file_path(test_dir().AppendASCII(file_name));
37    ASSERT_TRUE(file_util::WriteFile(file_path, data.c_str(), data.size()));
38  }
39
40  const FilePath& test_dir() { return test_dir_.path(); }
41
42 private:
43  ScopedTempDir test_dir_;
44};
45
46class ConfigDirPolicyLoaderTest
47    : public ConfigDirPolicyProviderTestBase<testing::Test> {
48};
49
50// The preferences dictionary is expected to be empty when there are no files to
51// load.
52TEST_F(ConfigDirPolicyLoaderTest, ReadPrefsEmpty) {
53  ConfigDirPolicyProviderDelegate loader(test_dir());
54  scoped_ptr<DictionaryValue> policy(loader.Load());
55  EXPECT_TRUE(policy.get());
56  EXPECT_TRUE(policy->empty());
57}
58
59// Reading from a non-existent directory should result in an empty preferences
60// dictionary.
61TEST_F(ConfigDirPolicyLoaderTest, ReadPrefsNonExistentDirectory) {
62  FilePath non_existent_dir(test_dir().Append(FILE_PATH_LITERAL("not_there")));
63  ConfigDirPolicyProviderDelegate loader(non_existent_dir);
64  scoped_ptr<DictionaryValue> policy(loader.Load());
65  EXPECT_TRUE(policy.get());
66  EXPECT_TRUE(policy->empty());
67}
68
69// Test reading back a single preference value.
70TEST_F(ConfigDirPolicyLoaderTest, ReadPrefsSinglePref) {
71  DictionaryValue test_dict;
72  test_dict.SetString("HomepageLocation", "http://www.google.com");
73  WriteConfigFile(test_dict, "config_file");
74
75  ConfigDirPolicyProviderDelegate loader(test_dir());
76  scoped_ptr<DictionaryValue> policy(loader.Load());
77  EXPECT_TRUE(policy.get());
78  EXPECT_TRUE(policy->Equals(&test_dict));
79}
80
81// Test merging values from different files.
82TEST_F(ConfigDirPolicyLoaderTest, ReadPrefsMergePrefs) {
83  // Write a bunch of data files in order to increase the chance to detect the
84  // provider not respecting lexicographic ordering when reading them. Since the
85  // filesystem may return files in arbitrary order, there is no way to be sure,
86  // but this is better than nothing.
87  DictionaryValue test_dict_bar;
88  test_dict_bar.SetString("HomepageLocation", "http://bar.com");
89  for (unsigned int i = 1; i <= 4; ++i)
90    WriteConfigFile(test_dict_bar, base::IntToString(i));
91  DictionaryValue test_dict_foo;
92  test_dict_foo.SetString("HomepageLocation", "http://foo.com");
93  WriteConfigFile(test_dict_foo, "9");
94  for (unsigned int i = 5; i <= 8; ++i)
95    WriteConfigFile(test_dict_bar, base::IntToString(i));
96
97  ConfigDirPolicyProviderDelegate loader(test_dir());
98  scoped_ptr<DictionaryValue> policy(loader.Load());
99  EXPECT_TRUE(policy.get());
100  EXPECT_TRUE(policy->Equals(&test_dict_foo));
101}
102
103// Holds policy type, corresponding policy key string and a valid value for use
104// in parametrized value tests.
105class ValueTestParams {
106 public:
107  // Assumes ownership of |test_value|.
108  ValueTestParams(ConfigurationPolicyType type,
109                  const char* policy_key,
110                  Value* test_value)
111      : type_(type),
112        policy_key_(policy_key),
113        test_value_(test_value) {}
114
115  // testing::TestWithParam does copying, so provide copy constructor and
116  // assignment operator.
117  ValueTestParams(const ValueTestParams& other)
118      : type_(other.type_),
119        policy_key_(other.policy_key_),
120        test_value_(other.test_value_->DeepCopy()) {}
121
122  const ValueTestParams& operator=(ValueTestParams other) {
123    swap(other);
124    return *this;
125  }
126
127  void swap(ValueTestParams& other) {
128    std::swap(type_, other.type_);
129    std::swap(policy_key_, other.policy_key_);
130    test_value_.swap(other.test_value_);
131  }
132
133  ConfigurationPolicyType type() const { return type_; }
134  const char* policy_key() const { return policy_key_; }
135  const Value* test_value() const { return test_value_.get(); }
136
137  // Factory methods that create parameter objects for different value types.
138  static ValueTestParams ForStringPolicy(
139      ConfigurationPolicyType type,
140      const char* policy_key) {
141    return ValueTestParams(type, policy_key, Value::CreateStringValue("test"));
142  }
143  static ValueTestParams ForBooleanPolicy(
144      ConfigurationPolicyType type,
145      const char* policy_key) {
146    return ValueTestParams(type, policy_key, Value::CreateBooleanValue(true));
147  }
148  static ValueTestParams ForIntegerPolicy(
149      ConfigurationPolicyType type,
150      const char* policy_key) {
151    return ValueTestParams(type, policy_key, Value::CreateIntegerValue(42));
152  }
153  static ValueTestParams ForListPolicy(
154      ConfigurationPolicyType type,
155      const char* policy_key) {
156    ListValue* value = new ListValue();
157    value->Set(0U, Value::CreateStringValue("first"));
158    value->Set(1U, Value::CreateStringValue("second"));
159    return ValueTestParams(type, policy_key, value);
160  }
161
162 private:
163  ConfigurationPolicyType type_;
164  const char* policy_key_;
165  scoped_ptr<Value> test_value_;
166};
167
168// Tests whether the provider correctly reads a value from the file and forwards
169// it to the store.
170class ConfigDirPolicyProviderValueTest
171    : public ConfigDirPolicyProviderTestBase<
172          testing::TestWithParam<ValueTestParams> > {
173 protected:
174  ConfigDirPolicyProviderValueTest()
175      : ui_thread_(BrowserThread::UI, &loop_),
176        file_thread_(BrowserThread::FILE, &loop_) {}
177
178  virtual void TearDown() {
179    loop_.RunAllPending();
180  }
181
182  MockConfigurationPolicyStore policy_store_;
183
184 private:
185  MessageLoop loop_;
186  BrowserThread ui_thread_;
187  BrowserThread file_thread_;
188};
189
190TEST_P(ConfigDirPolicyProviderValueTest, Default) {
191  ConfigDirPolicyProvider provider(
192      ConfigurationPolicyPrefStore::GetChromePolicyDefinitionList(),
193      test_dir());
194  EXPECT_TRUE(provider.Provide(&policy_store_));
195  EXPECT_TRUE(policy_store_.policy_map().empty());
196}
197
198TEST_P(ConfigDirPolicyProviderValueTest, NullValue) {
199  DictionaryValue dict;
200  dict.Set(GetParam().policy_key(), Value::CreateNullValue());
201  WriteConfigFile(dict, "empty");
202  ConfigDirPolicyProvider provider(
203      ConfigurationPolicyPrefStore::GetChromePolicyDefinitionList(),
204      test_dir());
205  EXPECT_TRUE(provider.Provide(&policy_store_));
206  EXPECT_TRUE(policy_store_.policy_map().empty());
207}
208
209TEST_P(ConfigDirPolicyProviderValueTest, TestValue) {
210  DictionaryValue dict;
211  dict.Set(GetParam().policy_key(), GetParam().test_value()->DeepCopy());
212  WriteConfigFile(dict, "policy");
213  ConfigDirPolicyProvider provider(
214      ConfigurationPolicyPrefStore::GetChromePolicyDefinitionList(),
215      test_dir());
216  EXPECT_TRUE(provider.Provide(&policy_store_));
217  EXPECT_EQ(1U, policy_store_.policy_map().size());
218  const Value* value = policy_store_.Get(GetParam().type());
219  ASSERT_TRUE(value);
220  EXPECT_TRUE(GetParam().test_value()->Equals(value));
221}
222
223// Test parameters for all supported policies.
224INSTANTIATE_TEST_CASE_P(
225    ConfigDirPolicyProviderValueTestInstance,
226    ConfigDirPolicyProviderValueTest,
227    testing::Values(
228        ValueTestParams::ForStringPolicy(
229            kPolicyHomepageLocation,
230            key::kHomepageLocation),
231        ValueTestParams::ForBooleanPolicy(
232            kPolicyHomepageIsNewTabPage,
233            key::kHomepageIsNewTabPage),
234        ValueTestParams::ForIntegerPolicy(
235            kPolicyRestoreOnStartup,
236            key::kRestoreOnStartup),
237        ValueTestParams::ForListPolicy(
238            kPolicyRestoreOnStartupURLs,
239            key::kRestoreOnStartupURLs),
240        ValueTestParams::ForBooleanPolicy(
241            kPolicyDefaultSearchProviderEnabled,
242            key::kDefaultSearchProviderEnabled),
243        ValueTestParams::ForStringPolicy(
244            kPolicyDefaultSearchProviderName,
245            key::kDefaultSearchProviderName),
246        ValueTestParams::ForStringPolicy(
247            kPolicyDefaultSearchProviderKeyword,
248            key::kDefaultSearchProviderKeyword),
249        ValueTestParams::ForStringPolicy(
250            kPolicyDefaultSearchProviderSearchURL,
251            key::kDefaultSearchProviderSearchURL),
252        ValueTestParams::ForStringPolicy(
253            kPolicyDefaultSearchProviderSuggestURL,
254            key::kDefaultSearchProviderSuggestURL),
255        ValueTestParams::ForStringPolicy(
256            kPolicyDefaultSearchProviderInstantURL,
257            key::kDefaultSearchProviderInstantURL),
258        ValueTestParams::ForStringPolicy(
259            kPolicyDefaultSearchProviderIconURL,
260            key::kDefaultSearchProviderIconURL),
261        ValueTestParams::ForStringPolicy(
262            kPolicyDefaultSearchProviderEncodings,
263            key::kDefaultSearchProviderEncodings),
264        ValueTestParams::ForStringPolicy(
265            kPolicyProxyMode,
266            key::kProxyMode),
267        ValueTestParams::ForIntegerPolicy(
268            kPolicyProxyServerMode,
269            key::kProxyServerMode),
270        ValueTestParams::ForStringPolicy(
271            kPolicyProxyServer,
272            key::kProxyServer),
273        ValueTestParams::ForStringPolicy(
274            kPolicyProxyPacUrl,
275            key::kProxyPacUrl),
276        ValueTestParams::ForStringPolicy(
277            kPolicyProxyBypassList,
278            key::kProxyBypassList),
279        ValueTestParams::ForBooleanPolicy(
280            kPolicyAlternateErrorPagesEnabled,
281            key::kAlternateErrorPagesEnabled),
282        ValueTestParams::ForBooleanPolicy(
283            kPolicySearchSuggestEnabled,
284            key::kSearchSuggestEnabled),
285        ValueTestParams::ForBooleanPolicy(
286            kPolicyDnsPrefetchingEnabled,
287            key::kDnsPrefetchingEnabled),
288        ValueTestParams::ForBooleanPolicy(
289            kPolicySafeBrowsingEnabled,
290            key::kSafeBrowsingEnabled),
291        ValueTestParams::ForBooleanPolicy(
292            kPolicyMetricsReportingEnabled,
293            key::kMetricsReportingEnabled),
294        ValueTestParams::ForBooleanPolicy(
295            kPolicyPasswordManagerEnabled,
296            key::kPasswordManagerEnabled),
297        ValueTestParams::ForBooleanPolicy(
298            kPolicyPasswordManagerAllowShowPasswords,
299            key::kPasswordManagerAllowShowPasswords),
300        ValueTestParams::ForListPolicy(
301            kPolicyDisabledPlugins,
302            key::kDisabledPlugins),
303        ValueTestParams::ForListPolicy(
304            kPolicyDisabledPluginsExceptions,
305            key::kDisabledPluginsExceptions),
306        ValueTestParams::ForListPolicy(
307            kPolicyEnabledPlugins,
308            key::kEnabledPlugins),
309        ValueTestParams::ForBooleanPolicy(
310            kPolicyAutoFillEnabled,
311            key::kAutoFillEnabled),
312        ValueTestParams::ForStringPolicy(
313            kPolicyApplicationLocaleValue,
314            key::kApplicationLocaleValue),
315        ValueTestParams::ForBooleanPolicy(
316            kPolicySyncDisabled,
317            key::kSyncDisabled),
318        ValueTestParams::ForListPolicy(
319            kPolicyExtensionInstallWhitelist,
320            key::kExtensionInstallWhitelist),
321        ValueTestParams::ForListPolicy(
322            kPolicyExtensionInstallBlacklist,
323            key::kExtensionInstallBlacklist),
324        ValueTestParams::ForBooleanPolicy(
325            kPolicyShowHomeButton,
326            key::kShowHomeButton),
327        ValueTestParams::ForBooleanPolicy(
328            kPolicyPrintingEnabled,
329            key::kPrintingEnabled),
330        ValueTestParams::ForIntegerPolicy(
331            kPolicyPolicyRefreshRate,
332            key::kPolicyRefreshRate),
333        ValueTestParams::ForBooleanPolicy(
334            kPolicyInstantEnabled,
335            key::kInstantEnabled),
336        ValueTestParams::ForBooleanPolicy(
337            kPolicyIncognitoEnabled,
338            key::kIncognitoEnabled),
339        ValueTestParams::ForBooleanPolicy(
340            kPolicyDisablePluginFinder,
341            key::kDisablePluginFinder),
342        ValueTestParams::ForBooleanPolicy(
343            kPolicyClearSiteDataOnExit,
344            key::kClearSiteDataOnExit),
345        ValueTestParams::ForStringPolicy(
346            kPolicyDownloadDirectory,
347            key::kDownloadDirectory),
348        ValueTestParams::ForBooleanPolicy(
349            kPolicyDefaultBrowserSettingEnabled,
350            key::kDefaultBrowserSettingEnabled),
351        ValueTestParams::ForBooleanPolicy(
352            kPolicyCloudPrintProxyEnabled,
353            key::kCloudPrintProxyEnabled),
354        ValueTestParams::ForBooleanPolicy(
355            kPolicyTranslateEnabled,
356            key::kTranslateEnabled),
357        ValueTestParams::ForBooleanPolicy(
358            kPolicyAllowOutdatedPlugins,
359            key::kAllowOutdatedPlugins),
360        ValueTestParams::ForBooleanPolicy(
361            kPolicyBookmarkBarEnabled,
362            key::kBookmarkBarEnabled),
363        ValueTestParams::ForBooleanPolicy(
364            kPolicyEditBookmarksEnabled,
365            key::kEditBookmarksEnabled),
366        ValueTestParams::ForListPolicy(
367            kPolicyDisabledSchemes,
368            key::kDisabledSchemes)));
369
370}  // namespace policy
371