json_pref_store_unittest.cc revision c2e0dbddbe15c98d52c4786dac06cb8952a8ae6d
1// Copyright (c) 2012 The Chromium Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5#include "base/prefs/json_pref_store.h"
6
7#include "base/file_util.h"
8#include "base/files/scoped_temp_dir.h"
9#include "base/memory/ref_counted.h"
10#include "base/memory/scoped_ptr.h"
11#include "base/path_service.h"
12#include "base/run_loop.h"
13#include "base/string_util.h"
14#include "base/strings/string_number_conversions.h"
15#include "base/threading/sequenced_worker_pool.h"
16#include "base/threading/thread.h"
17#include "base/utf_string_conversions.h"
18#include "base/values.h"
19#include "testing/gmock/include/gmock/gmock.h"
20#include "testing/gtest/include/gtest/gtest.h"
21
22namespace base {
23namespace {
24
25const char kHomePage[] = "homepage";
26
27class MockPrefStoreObserver : public PrefStore::Observer {
28 public:
29  MOCK_METHOD1(OnPrefValueChanged, void (const std::string&));
30  MOCK_METHOD1(OnInitializationCompleted, void (bool));
31};
32
33class MockReadErrorDelegate : public PersistentPrefStore::ReadErrorDelegate {
34 public:
35  MOCK_METHOD1(OnError, void(PersistentPrefStore::PrefReadError));
36};
37
38}  // namespace
39
40class JsonPrefStoreTest : public testing::Test {
41 protected:
42  virtual void SetUp() OVERRIDE {
43    ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
44
45    ASSERT_TRUE(PathService::Get(base::DIR_TEST_DATA, &data_dir_));
46    data_dir_ = data_dir_.AppendASCII("prefs");
47    ASSERT_TRUE(file_util::PathExists(data_dir_));
48  }
49
50  // The path to temporary directory used to contain the test operations.
51  base::ScopedTempDir temp_dir_;
52  // The path to the directory where the test data is stored.
53  base::FilePath data_dir_;
54  // A message loop that we can use as the file thread message loop.
55  MessageLoop message_loop_;
56};
57
58// Test fallback behavior for a nonexistent file.
59TEST_F(JsonPrefStoreTest, NonExistentFile) {
60  base::FilePath bogus_input_file = data_dir_.AppendASCII("read.txt");
61  ASSERT_FALSE(file_util::PathExists(bogus_input_file));
62  scoped_refptr<JsonPrefStore> pref_store =
63      new JsonPrefStore(
64          bogus_input_file, message_loop_.message_loop_proxy());
65  EXPECT_EQ(PersistentPrefStore::PREF_READ_ERROR_NO_FILE,
66            pref_store->ReadPrefs());
67  EXPECT_FALSE(pref_store->ReadOnly());
68}
69
70// Test fallback behavior for an invalid file.
71TEST_F(JsonPrefStoreTest, InvalidFile) {
72  base::FilePath invalid_file_original = data_dir_.AppendASCII("invalid.json");
73  base::FilePath invalid_file = temp_dir_.path().AppendASCII("invalid.json");
74  ASSERT_TRUE(file_util::CopyFile(invalid_file_original, invalid_file));
75  scoped_refptr<JsonPrefStore> pref_store =
76      new JsonPrefStore(
77          invalid_file, message_loop_.message_loop_proxy());
78  EXPECT_EQ(PersistentPrefStore::PREF_READ_ERROR_JSON_PARSE,
79            pref_store->ReadPrefs());
80  EXPECT_FALSE(pref_store->ReadOnly());
81
82  // The file should have been moved aside.
83  EXPECT_FALSE(file_util::PathExists(invalid_file));
84  base::FilePath moved_aside = temp_dir_.path().AppendASCII("invalid.bad");
85  EXPECT_TRUE(file_util::PathExists(moved_aside));
86  EXPECT_TRUE(file_util::TextContentsEqual(invalid_file_original,
87                                           moved_aside));
88}
89
90// This function is used to avoid code duplication while testing synchronous and
91// asynchronous version of the JsonPrefStore loading.
92void RunBasicJsonPrefStoreTest(JsonPrefStore* pref_store,
93                               const base::FilePath& output_file,
94                               const base::FilePath& golden_output_file) {
95  const char kNewWindowsInTabs[] = "tabs.new_windows_in_tabs";
96  const char kMaxTabs[] = "tabs.max_tabs";
97  const char kLongIntPref[] = "long_int.pref";
98
99  std::string cnn("http://www.cnn.com");
100
101  const Value* actual;
102  EXPECT_TRUE(pref_store->GetValue(kHomePage, &actual));
103  std::string string_value;
104  EXPECT_TRUE(actual->GetAsString(&string_value));
105  EXPECT_EQ(cnn, string_value);
106
107  const char kSomeDirectory[] = "some_directory";
108
109  EXPECT_TRUE(pref_store->GetValue(kSomeDirectory, &actual));
110  base::FilePath::StringType path;
111  EXPECT_TRUE(actual->GetAsString(&path));
112  EXPECT_EQ(base::FilePath::StringType(FILE_PATH_LITERAL("/usr/local/")), path);
113  base::FilePath some_path(FILE_PATH_LITERAL("/usr/sbin/"));
114
115  pref_store->SetValue(kSomeDirectory, new StringValue(some_path.value()));
116  EXPECT_TRUE(pref_store->GetValue(kSomeDirectory, &actual));
117  EXPECT_TRUE(actual->GetAsString(&path));
118  EXPECT_EQ(some_path.value(), path);
119
120  // Test reading some other data types from sub-dictionaries.
121  EXPECT_TRUE(pref_store->GetValue(kNewWindowsInTabs, &actual));
122  bool boolean = false;
123  EXPECT_TRUE(actual->GetAsBoolean(&boolean));
124  EXPECT_TRUE(boolean);
125
126  pref_store->SetValue(kNewWindowsInTabs, new FundamentalValue(false));
127  EXPECT_TRUE(pref_store->GetValue(kNewWindowsInTabs, &actual));
128  EXPECT_TRUE(actual->GetAsBoolean(&boolean));
129  EXPECT_FALSE(boolean);
130
131  EXPECT_TRUE(pref_store->GetValue(kMaxTabs, &actual));
132  int integer = 0;
133  EXPECT_TRUE(actual->GetAsInteger(&integer));
134  EXPECT_EQ(20, integer);
135  pref_store->SetValue(kMaxTabs, new FundamentalValue(10));
136  EXPECT_TRUE(pref_store->GetValue(kMaxTabs, &actual));
137  EXPECT_TRUE(actual->GetAsInteger(&integer));
138  EXPECT_EQ(10, integer);
139
140  pref_store->SetValue(kLongIntPref,
141                       new StringValue(base::Int64ToString(214748364842LL)));
142  EXPECT_TRUE(pref_store->GetValue(kLongIntPref, &actual));
143  EXPECT_TRUE(actual->GetAsString(&string_value));
144  int64 value;
145  base::StringToInt64(string_value, &value);
146  EXPECT_EQ(214748364842LL, value);
147
148  // Serialize and compare to expected output.
149  ASSERT_TRUE(file_util::PathExists(golden_output_file));
150  pref_store->CommitPendingWrite();
151  RunLoop().RunUntilIdle();
152  EXPECT_TRUE(file_util::TextContentsEqual(golden_output_file, output_file));
153  ASSERT_TRUE(file_util::Delete(output_file, false));
154}
155
156TEST_F(JsonPrefStoreTest, Basic) {
157  ASSERT_TRUE(file_util::CopyFile(data_dir_.AppendASCII("read.json"),
158                                  temp_dir_.path().AppendASCII("write.json")));
159
160  // Test that the persistent value can be loaded.
161  base::FilePath input_file = temp_dir_.path().AppendASCII("write.json");
162  ASSERT_TRUE(file_util::PathExists(input_file));
163  scoped_refptr<JsonPrefStore> pref_store =
164      new JsonPrefStore(
165          input_file, message_loop_.message_loop_proxy());
166  ASSERT_EQ(PersistentPrefStore::PREF_READ_ERROR_NONE, pref_store->ReadPrefs());
167  ASSERT_FALSE(pref_store->ReadOnly());
168
169  // The JSON file looks like this:
170  // {
171  //   "homepage": "http://www.cnn.com",
172  //   "some_directory": "/usr/local/",
173  //   "tabs": {
174  //     "new_windows_in_tabs": true,
175  //     "max_tabs": 20
176  //   }
177  // }
178
179  RunBasicJsonPrefStoreTest(pref_store,
180                            input_file,
181                            data_dir_.AppendASCII("write.golden.json"));
182}
183
184TEST_F(JsonPrefStoreTest, BasicAsync) {
185  ASSERT_TRUE(file_util::CopyFile(data_dir_.AppendASCII("read.json"),
186                                  temp_dir_.path().AppendASCII("write.json")));
187
188  // Test that the persistent value can be loaded.
189  base::FilePath input_file = temp_dir_.path().AppendASCII("write.json");
190  ASSERT_TRUE(file_util::PathExists(input_file));
191  scoped_refptr<JsonPrefStore> pref_store =
192      new JsonPrefStore(
193          input_file, message_loop_.message_loop_proxy());
194
195  {
196    MockPrefStoreObserver mock_observer;
197    pref_store->AddObserver(&mock_observer);
198
199    MockReadErrorDelegate* mock_error_delegate = new MockReadErrorDelegate;
200    pref_store->ReadPrefsAsync(mock_error_delegate);
201
202    EXPECT_CALL(mock_observer, OnInitializationCompleted(true)).Times(1);
203    EXPECT_CALL(*mock_error_delegate,
204                OnError(PersistentPrefStore::PREF_READ_ERROR_NONE)).Times(0);
205    RunLoop().RunUntilIdle();
206    pref_store->RemoveObserver(&mock_observer);
207
208    ASSERT_FALSE(pref_store->ReadOnly());
209  }
210
211  // The JSON file looks like this:
212  // {
213  //   "homepage": "http://www.cnn.com",
214  //   "some_directory": "/usr/local/",
215  //   "tabs": {
216  //     "new_windows_in_tabs": true,
217  //     "max_tabs": 20
218  //   }
219  // }
220
221  RunBasicJsonPrefStoreTest(pref_store,
222                            input_file,
223                            data_dir_.AppendASCII("write.golden.json"));
224}
225
226// Tests asynchronous reading of the file when there is no file.
227TEST_F(JsonPrefStoreTest, AsyncNonExistingFile) {
228  base::FilePath bogus_input_file = data_dir_.AppendASCII("read.txt");
229  ASSERT_FALSE(file_util::PathExists(bogus_input_file));
230  scoped_refptr<JsonPrefStore> pref_store =
231      new JsonPrefStore(
232          bogus_input_file, message_loop_.message_loop_proxy());
233  MockPrefStoreObserver mock_observer;
234  pref_store->AddObserver(&mock_observer);
235
236  MockReadErrorDelegate *mock_error_delegate = new MockReadErrorDelegate;
237  pref_store->ReadPrefsAsync(mock_error_delegate);
238
239  EXPECT_CALL(mock_observer, OnInitializationCompleted(true)).Times(1);
240  EXPECT_CALL(*mock_error_delegate,
241              OnError(PersistentPrefStore::PREF_READ_ERROR_NO_FILE)).Times(1);
242  RunLoop().RunUntilIdle();
243  pref_store->RemoveObserver(&mock_observer);
244
245  EXPECT_FALSE(pref_store->ReadOnly());
246}
247
248TEST_F(JsonPrefStoreTest, NeedsEmptyValue) {
249  base::FilePath pref_file = temp_dir_.path().AppendASCII("write.json");
250
251  ASSERT_TRUE(file_util::CopyFile(
252      data_dir_.AppendASCII("read.need_empty_value.json"),
253      pref_file));
254
255  // Test that the persistent value can be loaded.
256  ASSERT_TRUE(file_util::PathExists(pref_file));
257  scoped_refptr<JsonPrefStore> pref_store =
258      new JsonPrefStore(
259          pref_file, message_loop_.message_loop_proxy());
260  ASSERT_EQ(PersistentPrefStore::PREF_READ_ERROR_NONE, pref_store->ReadPrefs());
261  ASSERT_FALSE(pref_store->ReadOnly());
262
263  // The JSON file looks like this:
264  // {
265  //   "list": [ 1 ],
266  //   "list_needs_empty_value": [ 2 ],
267  //   "dict": {
268  //     "dummy": true,
269  //   },
270  //   "dict_needs_empty_value": {
271  //     "dummy": true,
272  //   },
273  // }
274
275  // Set flag to preserve empty values for the following keys.
276  pref_store->MarkNeedsEmptyValue("list_needs_empty_value");
277  pref_store->MarkNeedsEmptyValue("dict_needs_empty_value");
278
279  // Set all keys to empty values.
280  pref_store->SetValue("list", new base::ListValue);
281  pref_store->SetValue("list_needs_empty_value", new base::ListValue);
282  pref_store->SetValue("dict", new base::DictionaryValue);
283  pref_store->SetValue("dict_needs_empty_value", new base::DictionaryValue);
284
285  // Write to file.
286  pref_store->CommitPendingWrite();
287  RunLoop().RunUntilIdle();
288
289  // Compare to expected output.
290  base::FilePath golden_output_file =
291      data_dir_.AppendASCII("write.golden.need_empty_value.json");
292  ASSERT_TRUE(file_util::PathExists(golden_output_file));
293  EXPECT_TRUE(file_util::TextContentsEqual(golden_output_file, pref_file));
294}
295
296}  // namespace base
297