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 "chrome/browser/prefs/scoped_user_pref_update.h"
6#include "chrome/browser/prefs/pref_change_registrar.h"
7#include "chrome/browser/prefs/pref_observer_mock.h"
8#include "chrome/test/testing_pref_service.h"
9#include "testing/gmock/include/gmock/gmock.h"
10#include "testing/gtest/include/gtest/gtest.h"
11
12using testing::_;
13using testing::Mock;
14
15class ScopedUserPrefUpdateTest : public testing::Test {
16 public:
17  ~ScopedUserPrefUpdateTest() {}
18
19 protected:
20  virtual void SetUp() {
21    prefs_.RegisterDictionaryPref(kPref);
22    registrar_.Init(&prefs_);
23    registrar_.Add(kPref, &observer_);
24  }
25
26  static const char kPref[];
27  static const char kKey[];
28  static const char kValue[];
29
30  TestingPrefService prefs_;
31  PrefObserverMock observer_;
32  PrefChangeRegistrar registrar_;
33};
34
35const char ScopedUserPrefUpdateTest::kPref[] = "name";
36const char ScopedUserPrefUpdateTest::kKey[] = "key";
37const char ScopedUserPrefUpdateTest::kValue[] = "value";
38
39TEST_F(ScopedUserPrefUpdateTest, RegularUse) {
40  // Dictionary that will be expected to be set at the end.
41  DictionaryValue expected_dictionary;
42  expected_dictionary.SetString(kKey, kValue);
43
44  {
45    EXPECT_CALL(observer_, Observe(_, _, _)).Times(0);
46    DictionaryPrefUpdate update(&prefs_, kPref);
47    DictionaryValue* value = update.Get();
48    ASSERT_TRUE(value);
49    value->SetString(kKey, kValue);
50
51    // The dictionary was created for us but the creation should have happened
52    // silently without notifications.
53    Mock::VerifyAndClearExpectations(&observer_);
54
55    // Modifications happen online and are instantly visible, though.
56    const DictionaryValue* current_value = prefs_.GetDictionary(kPref);
57    ASSERT_TRUE(current_value);
58    EXPECT_TRUE(expected_dictionary.Equals(current_value));
59
60    // Now we are leaving the scope of the update so we should be notified.
61    observer_.Expect(&prefs_, kPref, &expected_dictionary);
62  }
63  Mock::VerifyAndClearExpectations(&observer_);
64
65  const DictionaryValue* current_value = prefs_.GetDictionary(kPref);
66  ASSERT_TRUE(current_value);
67  EXPECT_TRUE(expected_dictionary.Equals(current_value));
68}
69
70TEST_F(ScopedUserPrefUpdateTest, NeverTouchAnything) {
71  const DictionaryValue* old_value = prefs_.GetDictionary(kPref);
72  EXPECT_CALL(observer_, Observe(_, _, _)).Times(0);
73  {
74    DictionaryPrefUpdate update(&prefs_, kPref);
75  }
76  const DictionaryValue* new_value = prefs_.GetDictionary(kPref);
77  EXPECT_EQ(old_value, new_value);
78  Mock::VerifyAndClearExpectations(&observer_);
79}
80