- add sources.
[platform/framework/web/crosswalk.git] / src / chrome / browser / policy / cloud / cloud_policy_manager_unittest.cc
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 "chrome/browser/policy/cloud/cloud_policy_manager.h"
6
7 #include "base/basictypes.h"
8 #include "base/callback.h"
9 #include "base/compiler_specific.h"
10 #include "base/memory/scoped_ptr.h"
11 #include "base/message_loop/message_loop.h"
12 #include "chrome/browser/policy/cloud/cloud_policy_constants.h"
13 #include "chrome/browser/policy/cloud/mock_cloud_policy_client.h"
14 #include "chrome/browser/policy/cloud/mock_cloud_policy_store.h"
15 #include "chrome/browser/policy/cloud/policy_builder.h"
16 #include "chrome/browser/policy/configuration_policy_provider_test.h"
17 #include "chrome/browser/policy/external_data_fetcher.h"
18 #include "chrome/browser/policy/mock_configuration_policy_provider.h"
19 #include "testing/gmock/include/gmock/gmock.h"
20 #include "testing/gtest/include/gtest/gtest.h"
21
22 using testing::Mock;
23 using testing::_;
24
25 namespace em = enterprise_management;
26
27 namespace policy {
28 namespace {
29
30 class TestHarness : public PolicyProviderTestHarness {
31  public:
32   explicit TestHarness(PolicyLevel level);
33   virtual ~TestHarness();
34
35   virtual void SetUp() OVERRIDE;
36
37   virtual ConfigurationPolicyProvider* CreateProvider(
38       scoped_refptr<base::SequencedTaskRunner> task_runner,
39       const PolicyDefinitionList* policy_definition_list) OVERRIDE;
40
41   virtual void InstallEmptyPolicy() OVERRIDE;
42   virtual void InstallStringPolicy(const std::string& policy_name,
43                                    const std::string& policy_value) OVERRIDE;
44   virtual void InstallIntegerPolicy(const std::string& policy_name,
45                                     int policy_value) OVERRIDE;
46   virtual void InstallBooleanPolicy(const std::string& policy_name,
47                                     bool policy_value) OVERRIDE;
48   virtual void InstallStringListPolicy(
49       const std::string& policy_name,
50       const base::ListValue* policy_value) OVERRIDE;
51   virtual void InstallDictionaryPolicy(
52       const std::string& policy_name,
53       const base::DictionaryValue* policy_value) OVERRIDE;
54
55   // Creates harnesses for mandatory and recommended levels, respectively.
56   static PolicyProviderTestHarness* CreateMandatory();
57   static PolicyProviderTestHarness* CreateRecommended();
58
59  private:
60   MockCloudPolicyStore store_;
61
62   DISALLOW_COPY_AND_ASSIGN(TestHarness);
63 };
64
65 TestHarness::TestHarness(PolicyLevel level)
66     : PolicyProviderTestHarness(level, POLICY_SCOPE_USER) {}
67
68 TestHarness::~TestHarness() {}
69
70 void TestHarness::SetUp() {}
71
72 ConfigurationPolicyProvider* TestHarness::CreateProvider(
73     scoped_refptr<base::SequencedTaskRunner> task_runner,
74     const PolicyDefinitionList* policy_definition_list) {
75   // Create and initialize the store.
76   store_.NotifyStoreLoaded();
77   ConfigurationPolicyProvider* provider = new CloudPolicyManager(
78       PolicyNamespaceKey(dm_protocol::kChromeUserPolicyType, std::string()),
79       &store_,
80       task_runner);
81   Mock::VerifyAndClearExpectations(&store_);
82   return provider;
83 }
84
85 void TestHarness::InstallEmptyPolicy() {}
86
87 void TestHarness::InstallStringPolicy(const std::string& policy_name,
88                                       const std::string& policy_value) {
89   store_.policy_map_.Set(policy_name, policy_level(), policy_scope(),
90                          base::Value::CreateStringValue(policy_value), NULL);
91 }
92
93 void TestHarness::InstallIntegerPolicy(const std::string& policy_name,
94                                        int policy_value) {
95   store_.policy_map_.Set(policy_name, policy_level(), policy_scope(),
96                          base::Value::CreateIntegerValue(policy_value), NULL);
97 }
98
99 void TestHarness::InstallBooleanPolicy(const std::string& policy_name,
100                                        bool policy_value) {
101   store_.policy_map_.Set(policy_name, policy_level(), policy_scope(),
102                          base::Value::CreateBooleanValue(policy_value), NULL);
103 }
104
105 void TestHarness::InstallStringListPolicy(const std::string& policy_name,
106                                           const base::ListValue* policy_value) {
107   store_.policy_map_.Set(policy_name, policy_level(), policy_scope(),
108                          policy_value->DeepCopy(), NULL);
109 }
110
111 void TestHarness::InstallDictionaryPolicy(
112     const std::string& policy_name,
113     const base::DictionaryValue* policy_value) {
114   store_.policy_map_.Set(policy_name, policy_level(), policy_scope(),
115                          policy_value->DeepCopy(), NULL);
116 }
117
118 // static
119 PolicyProviderTestHarness* TestHarness::CreateMandatory() {
120   return new TestHarness(POLICY_LEVEL_MANDATORY);
121 }
122
123 // static
124 PolicyProviderTestHarness* TestHarness::CreateRecommended() {
125   return new TestHarness(POLICY_LEVEL_RECOMMENDED);
126 }
127
128 // Instantiate abstract test case for basic policy reading tests.
129 INSTANTIATE_TEST_CASE_P(
130     UserCloudPolicyManagerProviderTest,
131     ConfigurationPolicyProviderTest,
132     testing::Values(TestHarness::CreateMandatory,
133                     TestHarness::CreateRecommended));
134
135 class TestCloudPolicyManager : public CloudPolicyManager {
136  public:
137   TestCloudPolicyManager(
138       CloudPolicyStore* store,
139       const scoped_refptr<base::SequencedTaskRunner>& task_runner)
140       : CloudPolicyManager(PolicyNamespaceKey(
141                                dm_protocol::kChromeUserPolicyType,
142                                std::string()),
143                            store,
144                            task_runner) {}
145   virtual ~TestCloudPolicyManager() {}
146
147   // Publish the protected members for testing.
148   using CloudPolicyManager::client;
149   using CloudPolicyManager::store;
150   using CloudPolicyManager::service;
151   using CloudPolicyManager::CheckAndPublishPolicy;
152
153  private:
154   DISALLOW_COPY_AND_ASSIGN(TestCloudPolicyManager);
155 };
156
157 MATCHER_P(ProtoMatches, proto, "") {
158   return arg.SerializePartialAsString() == proto.SerializePartialAsString();
159 }
160
161 class CloudPolicyManagerTest : public testing::Test {
162  protected:
163   CloudPolicyManagerTest()
164       : policy_ns_key_(dm_protocol::kChromeUserPolicyType, std::string()) {}
165
166   virtual void SetUp() OVERRIDE {
167     // Set up a policy map for testing.
168     policy_map_.Set("key", POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
169                     base::Value::CreateStringValue("value"), NULL);
170     expected_bundle_.Get(PolicyNamespace(POLICY_DOMAIN_CHROME, std::string()))
171         .CopyFrom(policy_map_);
172
173     policy_.payload().mutable_passwordmanagerenabled()->set_value(false);
174     policy_.Build();
175
176     EXPECT_CALL(store_, Load());
177     manager_.reset(new TestCloudPolicyManager(&store_,
178                                               loop_.message_loop_proxy()));
179     manager_->Init();
180     Mock::VerifyAndClearExpectations(&store_);
181     manager_->AddObserver(&observer_);
182   }
183
184   virtual void TearDown() OVERRIDE {
185     manager_->RemoveObserver(&observer_);
186     manager_->Shutdown();
187   }
188
189   // Required by the refresh scheduler that's created by the manager.
190   base::MessageLoop loop_;
191
192   // Testing policy.
193   const PolicyNamespaceKey policy_ns_key_;
194   UserPolicyBuilder policy_;
195   PolicyMap policy_map_;
196   PolicyBundle expected_bundle_;
197
198   // Policy infrastructure.
199   MockConfigurationPolicyObserver observer_;
200   MockCloudPolicyStore store_;
201   scoped_ptr<TestCloudPolicyManager> manager_;
202
203  private:
204   DISALLOW_COPY_AND_ASSIGN(CloudPolicyManagerTest);
205 };
206
207 TEST_F(CloudPolicyManagerTest, InitAndShutdown) {
208   PolicyBundle empty_bundle;
209   EXPECT_TRUE(empty_bundle.Equals(manager_->policies()));
210   EXPECT_FALSE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
211
212   EXPECT_CALL(observer_, OnUpdatePolicy(_)).Times(0);
213   manager_->CheckAndPublishPolicy();
214   Mock::VerifyAndClearExpectations(&observer_);
215
216   store_.policy_map_.CopyFrom(policy_map_);
217   store_.policy_.reset(new em::PolicyData(policy_.policy_data()));
218   EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));
219   store_.NotifyStoreLoaded();
220   Mock::VerifyAndClearExpectations(&observer_);
221   EXPECT_TRUE(expected_bundle_.Equals(manager_->policies()));
222   EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
223
224   MockCloudPolicyClient* client = new MockCloudPolicyClient();
225   EXPECT_CALL(*client, SetupRegistration(_, _));
226   manager_->core()->Connect(scoped_ptr<CloudPolicyClient>(client));
227   Mock::VerifyAndClearExpectations(client);
228   EXPECT_TRUE(manager_->client());
229   EXPECT_TRUE(manager_->service());
230
231   EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));
232   manager_->CheckAndPublishPolicy();
233   Mock::VerifyAndClearExpectations(&observer_);
234
235   manager_->core()->Disconnect();
236   EXPECT_FALSE(manager_->client());
237   EXPECT_FALSE(manager_->service());
238 }
239
240 TEST_F(CloudPolicyManagerTest, RegistrationAndFetch) {
241   EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));
242   store_.NotifyStoreLoaded();
243   Mock::VerifyAndClearExpectations(&observer_);
244   EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
245
246   MockCloudPolicyClient* client = new MockCloudPolicyClient();
247   manager_->core()->Connect(scoped_ptr<CloudPolicyClient>(client));
248
249   client->SetDMToken(policy_.policy_data().request_token());
250   client->NotifyRegistrationStateChanged();
251
252   client->SetPolicy(policy_ns_key_, policy_.policy());
253   EXPECT_CALL(store_, Store(ProtoMatches(policy_.policy())));
254   client->NotifyPolicyFetched();
255   Mock::VerifyAndClearExpectations(&store_);
256
257   store_.policy_map_.CopyFrom(policy_map_);
258   EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));
259   store_.NotifyStoreLoaded();
260   Mock::VerifyAndClearExpectations(&observer_);
261   EXPECT_TRUE(expected_bundle_.Equals(manager_->policies()));
262 }
263
264 TEST_F(CloudPolicyManagerTest, Update) {
265   EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));
266   store_.NotifyStoreLoaded();
267   Mock::VerifyAndClearExpectations(&observer_);
268   EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
269   PolicyBundle empty_bundle;
270   EXPECT_TRUE(empty_bundle.Equals(manager_->policies()));
271
272   store_.policy_map_.CopyFrom(policy_map_);
273   EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));
274   store_.NotifyStoreLoaded();
275   Mock::VerifyAndClearExpectations(&observer_);
276   EXPECT_TRUE(expected_bundle_.Equals(manager_->policies()));
277   EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
278 }
279
280 TEST_F(CloudPolicyManagerTest, RefreshNotRegistered) {
281   MockCloudPolicyClient* client = new MockCloudPolicyClient();
282   manager_->core()->Connect(scoped_ptr<CloudPolicyClient>(client));
283
284   EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));
285   store_.NotifyStoreLoaded();
286   Mock::VerifyAndClearExpectations(&observer_);
287
288   // A refresh on a non-registered store should not block.
289   EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));
290   manager_->RefreshPolicies();
291   Mock::VerifyAndClearExpectations(&observer_);
292 }
293
294 TEST_F(CloudPolicyManagerTest, RefreshSuccessful) {
295   MockCloudPolicyClient* client = new MockCloudPolicyClient();
296   manager_->core()->Connect(scoped_ptr<CloudPolicyClient>(client));
297
298   // Simulate a store load.
299   store_.policy_.reset(new em::PolicyData(policy_.policy_data()));
300   EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));
301   EXPECT_CALL(*client, SetupRegistration(_, _));
302   store_.NotifyStoreLoaded();
303   Mock::VerifyAndClearExpectations(client);
304   Mock::VerifyAndClearExpectations(&observer_);
305
306   // Acknowledge registration.
307   client->SetDMToken(policy_.policy_data().request_token());
308
309   // Start a refresh.
310   EXPECT_CALL(observer_, OnUpdatePolicy(_)).Times(0);
311   EXPECT_CALL(*client, FetchPolicy());
312   manager_->RefreshPolicies();
313   Mock::VerifyAndClearExpectations(client);
314   Mock::VerifyAndClearExpectations(&observer_);
315   store_.policy_map_.CopyFrom(policy_map_);
316
317   // A stray reload should be suppressed until the refresh completes.
318   EXPECT_CALL(observer_, OnUpdatePolicy(_)).Times(0);
319   store_.NotifyStoreLoaded();
320   Mock::VerifyAndClearExpectations(&observer_);
321
322   // Respond to the policy fetch, which should trigger a write to |store_|.
323   EXPECT_CALL(observer_, OnUpdatePolicy(_)).Times(0);
324   EXPECT_CALL(store_, Store(_));
325   client->SetPolicy(policy_ns_key_, policy_.policy());
326   client->NotifyPolicyFetched();
327   Mock::VerifyAndClearExpectations(&observer_);
328   Mock::VerifyAndClearExpectations(&store_);
329
330   // The load notification from |store_| should trigger the policy update.
331   EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));
332   store_.NotifyStoreLoaded();
333   EXPECT_TRUE(expected_bundle_.Equals(manager_->policies()));
334   Mock::VerifyAndClearExpectations(&observer_);
335 }
336
337 TEST_F(CloudPolicyManagerTest, SignalOnError) {
338   // Simulate a failed load and verify that it triggers OnUpdatePolicy().
339   store_.policy_.reset(new em::PolicyData(policy_.policy_data()));
340   EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));
341   store_.NotifyStoreError();
342   Mock::VerifyAndClearExpectations(&observer_);
343
344   EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
345 }
346
347 }  // namespace
348 }  // namespace policy