user_cloud_policy_manager_chromeos_unittest.cc revision 7dbb3d5cf0c15f500944d211057644d6a2f37371
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/chromeos/policy/user_cloud_policy_manager_chromeos.h"
6
7#include "base/basictypes.h"
8#include "base/bind.h"
9#include "base/bind_helpers.h"
10#include "base/callback.h"
11#include "base/memory/scoped_ptr.h"
12#include "base/message_loop.h"
13#include "base/prefs/pref_registry_simple.h"
14#include "base/prefs/testing_pref_service.h"
15#include "base/run_loop.h"
16#include "base/strings/string_util.h"
17#include "base/strings/utf_string_conversions.h"
18#include "chrome/browser/chromeos/policy/user_cloud_policy_token_forwarder.h"
19#include "chrome/browser/chromeos/profiles/profile_helper.h"
20#include "chrome/browser/policy/cloud/cloud_policy_constants.h"
21#include "chrome/browser/policy/cloud/cloud_policy_service.h"
22#include "chrome/browser/policy/cloud/mock_cloud_policy_store.h"
23#include "chrome/browser/policy/cloud/mock_device_management_service.h"
24#include "chrome/browser/policy/cloud/resource_cache.h"
25#include "chrome/browser/policy/external_data_fetcher.h"
26#include "chrome/browser/policy/mock_configuration_policy_provider.h"
27#include "chrome/browser/policy/proto/cloud/device_management_backend.pb.h"
28#include "chrome/browser/prefs/browser_prefs.h"
29#include "chrome/browser/prefs/pref_service_syncable.h"
30#include "chrome/browser/signin/token_service.h"
31#include "chrome/browser/signin/token_service_factory.h"
32#include "chrome/common/chrome_constants.h"
33#include "chrome/test/base/testing_browser_process.h"
34#include "chrome/test/base/testing_profile.h"
35#include "chrome/test/base/testing_profile_manager.h"
36#include "content/public/test/test_browser_thread.h"
37#include "google_apis/gaia/gaia_auth_consumer.h"
38#include "google_apis/gaia/gaia_urls.h"
39#include "net/url_request/test_url_fetcher_factory.h"
40#include "net/url_request/url_fetcher_delegate.h"
41#include "net/url_request/url_request_context_getter.h"
42#include "net/url_request/url_request_status.h"
43#include "policy/policy_constants.h"
44#include "testing/gmock/include/gmock/gmock.h"
45#include "testing/gtest/include/gtest/gtest.h"
46
47namespace em = enterprise_management;
48
49using testing::AnyNumber;
50using testing::AtLeast;
51using testing::Mock;
52using testing::_;
53
54namespace policy {
55
56namespace {
57
58const char kOAuthTokenCookie[] = "oauth_token=1234";
59
60const char kOAuth2TokenPairData[] =
61    "{"
62    "  \"refresh_token\": \"1234\","
63    "  \"access_token\": \"5678\","
64    "  \"expires_in\": 3600"
65    "}";
66
67const char kOAuth2AccessTokenData[] =
68    "{"
69    "  \"access_token\": \"5678\","
70    "  \"expires_in\": 3600"
71    "}";
72
73}  // namespace
74
75class UserCloudPolicyManagerChromeOSTest : public testing::Test {
76 protected:
77  UserCloudPolicyManagerChromeOSTest()
78      : ui_thread_(content::BrowserThread::UI, &loop_),
79        io_thread_(content::BrowserThread::IO, &loop_),
80        store_(NULL),
81        profile_(NULL),
82        signin_profile_(NULL) {}
83
84  virtual void SetUp() OVERRIDE {
85    // The initialization path that blocks on the initial policy fetch requires
86    // a signin Profile to use its URLRequestContext.
87    profile_manager_.reset(
88        new TestingProfileManager(TestingBrowserProcess::GetGlobal()));
89    ASSERT_TRUE(profile_manager_->SetUp());
90    profile_ = profile_manager_->CreateTestingProfile(
91        chrome::kInitialProfile, scoped_ptr<PrefServiceSyncable>(),
92        UTF8ToUTF16("testing_profile"), 0);
93    signin_profile_ = profile_manager_->CreateTestingProfile("signin_profile");
94    signin_profile_->set_incognito(true);
95    // Usually the signin Profile and the main Profile are separate, but since
96    // the signin Profile is an OTR Profile then for this test it suffices to
97    // attach it to the main Profile.
98    profile_->SetOffTheRecordProfile(signin_profile_);
99    signin_profile_->SetOriginalProfile(profile_);
100    signin_profile_->CreateRequestContext();
101    ASSERT_EQ(signin_profile_, chromeos::ProfileHelper::GetSigninProfile());
102
103    chrome::RegisterLocalState(prefs_.registry());
104
105    // Set up a policy map for testing.
106    policy_map_.Set("HomepageLocation",
107                    POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
108                    base::Value::CreateStringValue("http://chromium.org"),
109                    NULL);
110    expected_bundle_.Get(PolicyNamespace(POLICY_DOMAIN_CHROME, std::string()))
111        .CopyFrom(policy_map_);
112
113    // Create fake policy blobs to deliver to the client.
114    em::DeviceRegisterResponse* register_response =
115        register_blob_.mutable_register_response();
116    register_response->set_device_management_token("dmtoken123");
117
118    em::CloudPolicySettings policy_proto;
119    policy_proto.mutable_homepagelocation()->set_value("http://chromium.org");
120    ASSERT_TRUE(
121        policy_proto.SerializeToString(policy_data_.mutable_policy_value()));
122    policy_data_.set_policy_type(dm_protocol::kChromeUserPolicyType);
123    policy_data_.set_request_token("dmtoken123");
124    policy_data_.set_device_id("id987");
125    em::PolicyFetchResponse* policy_response =
126        policy_blob_.mutable_policy_response()->add_response();
127    ASSERT_TRUE(policy_data_.SerializeToString(
128        policy_response->mutable_policy_data()));
129
130    EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
131        .Times(AnyNumber());
132  }
133
134  virtual void TearDown() OVERRIDE {
135    if (manager_) {
136      manager_->RemoveObserver(&observer_);
137      manager_->Shutdown();
138    }
139    signin_profile_->ResetRequestContext();
140  }
141
142  void CreateManager(bool wait_for_fetch) {
143    store_ = new MockCloudPolicyStore();
144    EXPECT_CALL(*store_, Load());
145    manager_.reset(new UserCloudPolicyManagerChromeOS(
146        scoped_ptr<CloudPolicyStore>(store_),
147        scoped_ptr<ResourceCache>(),
148        wait_for_fetch));
149    manager_->Init();
150    manager_->AddObserver(&observer_);
151    manager_->Connect(&prefs_, &device_management_service_, NULL,
152                      USER_AFFILIATION_NONE);
153    Mock::VerifyAndClearExpectations(store_);
154    EXPECT_FALSE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
155    EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete());
156
157    if (!wait_for_fetch) {
158      // Create the UserCloudPolicyTokenForwarder, which forwards the refresh
159      // token from the TokenService to the UserCloudPolicyManagerChromeOS.
160      // This service is automatically created for regular Profiles but not for
161      // testing Profiles.
162      TokenService* token_service =
163          TokenServiceFactory::GetForProfile(profile_);
164      ASSERT_TRUE(token_service);
165      token_forwarder_.reset(
166          new UserCloudPolicyTokenForwarder(manager_.get(), token_service));
167    }
168  }
169
170  // Expects a pending URLFetcher for the |expected_url|, and returns it with
171  // prepared to deliver a response to its delegate.
172  net::TestURLFetcher* PrepareOAuthFetcher(const std::string& expected_url) {
173    net::TestURLFetcher* fetcher = test_url_fetcher_factory_.GetFetcherByID(0);
174    EXPECT_TRUE(fetcher);
175    if (!fetcher)
176      return NULL;
177    EXPECT_TRUE(fetcher->delegate());
178    EXPECT_TRUE(StartsWithASCII(fetcher->GetOriginalURL().spec(),
179                                expected_url,
180                                true));
181    fetcher->set_url(fetcher->GetOriginalURL());
182    fetcher->set_response_code(200);
183    fetcher->set_status(net::URLRequestStatus());
184    return fetcher;
185  }
186
187  // Issues the OAuth2 tokens and returns the device management register job
188  // if the flow succeeded.
189  MockDeviceManagementJob* IssueOAuthToken(bool has_request_token) {
190    EXPECT_FALSE(manager_->core()->client()->is_registered());
191
192    GaiaUrls* gaia_urls = GaiaUrls::GetInstance();
193    net::TestURLFetcher* fetcher = NULL;
194
195    if (!has_request_token) {
196      // Issue the oauth_token cookie first.
197      fetcher = PrepareOAuthFetcher(gaia_urls->client_login_to_oauth2_url());
198      if (!fetcher)
199        return NULL;
200      net::ResponseCookies cookies;
201      cookies.push_back(kOAuthTokenCookie);
202      fetcher->set_cookies(cookies);
203      fetcher->delegate()->OnURLFetchComplete(fetcher);
204
205      // Issue the refresh token.
206      fetcher = PrepareOAuthFetcher(gaia_urls->oauth2_token_url());
207      if (!fetcher)
208        return NULL;
209      fetcher->SetResponseString(kOAuth2TokenPairData);
210      fetcher->delegate()->OnURLFetchComplete(fetcher);
211    }
212
213    // Issue the access token.
214    fetcher = PrepareOAuthFetcher(gaia_urls->oauth2_token_url());
215    if (!fetcher)
216      return NULL;
217    fetcher->SetResponseString(kOAuth2AccessTokenData);
218
219    // Issuing this token triggers the callback of the OAuth2PolicyFetcher,
220    // which triggers the registration request.
221    MockDeviceManagementJob* register_request = NULL;
222    EXPECT_CALL(device_management_service_,
223                CreateJob(DeviceManagementRequestJob::TYPE_REGISTRATION))
224        .WillOnce(device_management_service_.CreateAsyncJob(&register_request));
225    fetcher->delegate()->OnURLFetchComplete(fetcher);
226    EXPECT_TRUE(register_request);
227    EXPECT_FALSE(manager_->core()->client()->is_registered());
228
229    Mock::VerifyAndClearExpectations(&device_management_service_);
230    EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
231        .Times(AnyNumber());
232
233    return register_request;
234  }
235
236  // Expects a policy fetch request to be issued after invoking |trigger_fetch|.
237  // This method replies to that fetch request and verifies that the manager
238  // handled the response.
239  void FetchPolicy(const base::Closure& trigger_fetch) {
240    MockDeviceManagementJob* policy_request = NULL;
241    EXPECT_CALL(device_management_service_,
242                CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH))
243        .WillOnce(device_management_service_.CreateAsyncJob(&policy_request));
244    trigger_fetch.Run();
245    ASSERT_TRUE(policy_request);
246    EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete());
247    EXPECT_TRUE(manager_->core()->client()->is_registered());
248
249    Mock::VerifyAndClearExpectations(&device_management_service_);
250    EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
251        .Times(AnyNumber());
252
253    // Send the initial policy back. This completes the initialization flow.
254    EXPECT_CALL(*store_, Store(_));
255    policy_request->SendResponse(DM_STATUS_SUCCESS, policy_blob_);
256    Mock::VerifyAndClearExpectations(store_);
257
258    // Notifying that the store is has cached the fetched policy completes the
259    // process, and initializes the manager.
260    EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));
261    store_->policy_map_.CopyFrom(policy_map_);
262    store_->NotifyStoreLoaded();
263    EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
264    Mock::VerifyAndClearExpectations(&observer_);
265    EXPECT_TRUE(manager_->policies().Equals(expected_bundle_));
266  }
267
268  // Required by the refresh scheduler that's created by the manager.
269  base::MessageLoop loop_;
270  content::TestBrowserThread ui_thread_;
271  // Required to cleanup the URLRequestContextGetter of the |signin_profile_|.
272  content::TestBrowserThread io_thread_;
273
274  // Convenience policy objects.
275  em::PolicyData policy_data_;
276  em::DeviceManagementResponse register_blob_;
277  em::DeviceManagementResponse policy_blob_;
278  PolicyMap policy_map_;
279  PolicyBundle expected_bundle_;
280
281  // Policy infrastructure.
282  net::TestURLFetcherFactory test_url_fetcher_factory_;
283  TestingPrefServiceSimple prefs_;
284  MockConfigurationPolicyObserver observer_;
285  MockDeviceManagementService device_management_service_;
286  MockCloudPolicyStore* store_;
287  scoped_ptr<UserCloudPolicyManagerChromeOS> manager_;
288  scoped_ptr<UserCloudPolicyTokenForwarder> token_forwarder_;
289
290  // Required by ProfileHelper to get the signin Profile context.
291  scoped_ptr<TestingProfileManager> profile_manager_;
292  TestingProfile* profile_;
293  TestingProfile* signin_profile_;
294
295 private:
296  DISALLOW_COPY_AND_ASSIGN(UserCloudPolicyManagerChromeOSTest);
297};
298
299TEST_F(UserCloudPolicyManagerChromeOSTest, BlockingFirstFetch) {
300  // Tests the initialization of a manager whose Profile is waiting for the
301  // initial fetch, when the policy cache is empty.
302  ASSERT_NO_FATAL_FAILURE(CreateManager(true));
303
304  // Initialize the CloudPolicyService without any stored data.
305  EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete());
306  store_->NotifyStoreLoaded();
307  EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete());
308  EXPECT_FALSE(manager_->core()->client()->is_registered());
309
310  // This starts the OAuth2 policy token fetcher using the signin Profile.
311  // The manager will then issue the registration request.
312  MockDeviceManagementJob* register_request = IssueOAuthToken(false);
313  ASSERT_TRUE(register_request);
314
315  // Reply with a valid registration response. This triggers the initial policy
316  // fetch.
317  FetchPolicy(base::Bind(&MockDeviceManagementJob::SendResponse,
318                         base::Unretained(register_request),
319                         DM_STATUS_SUCCESS, register_blob_));
320}
321
322TEST_F(UserCloudPolicyManagerChromeOSTest, BlockingRefreshFetch) {
323  // Tests the initialization of a manager whose Profile is waiting for the
324  // initial fetch, when a previously cached policy and DMToken already exist.
325  ASSERT_NO_FATAL_FAILURE(CreateManager(true));
326
327  // Set the initially cached data and initialize the CloudPolicyService.
328  // The initial policy fetch is issued using the cached DMToken.
329  store_->policy_.reset(new em::PolicyData(policy_data_));
330  FetchPolicy(base::Bind(&MockCloudPolicyStore::NotifyStoreLoaded,
331                         base::Unretained(store_)));
332}
333
334TEST_F(UserCloudPolicyManagerChromeOSTest, BlockingFetchStoreError) {
335  // Tests the initialization of a manager whose Profile is waiting for the
336  // initial fetch, when the initial store load fails.
337  ASSERT_NO_FATAL_FAILURE(CreateManager(true));
338
339  // Initialize the CloudPolicyService without any stored data.
340  EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete());
341  store_->NotifyStoreError();
342  EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete());
343  EXPECT_FALSE(manager_->core()->client()->is_registered());
344
345  // This starts the OAuth2 policy token fetcher using the signin Profile.
346  // The manager will then issue the registration request.
347  MockDeviceManagementJob* register_request = IssueOAuthToken(false);
348  ASSERT_TRUE(register_request);
349
350  // Reply with a valid registration response. This triggers the initial policy
351  // fetch.
352  FetchPolicy(base::Bind(&MockDeviceManagementJob::SendResponse,
353                         base::Unretained(register_request),
354                         DM_STATUS_SUCCESS, register_blob_));
355}
356
357TEST_F(UserCloudPolicyManagerChromeOSTest, BlockingFetchOAuthError) {
358  // Tests the initialization of a manager whose Profile is waiting for the
359  // initial fetch, when the OAuth2 token fetch fails.
360  ASSERT_NO_FATAL_FAILURE(CreateManager(true));
361
362  // Initialize the CloudPolicyService without any stored data.
363  EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete());
364  store_->NotifyStoreLoaded();
365  EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete());
366  EXPECT_FALSE(manager_->core()->client()->is_registered());
367
368  // This starts the OAuth2 policy token fetcher using the signin Profile.
369  // The manager will initialize with no policy after the token fetcher fails.
370  EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));
371
372  // The PolicyOAuth2TokenFetcher posts delayed retries on some errors. This
373  // data will make it fail immediately.
374  net::TestURLFetcher* fetcher = PrepareOAuthFetcher(
375      GaiaUrls::GetInstance()->client_login_to_oauth2_url());
376  ASSERT_TRUE(fetcher);
377  fetcher->set_response_code(400);
378  fetcher->SetResponseString("Error=BadAuthentication");
379  EXPECT_FALSE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
380  fetcher->delegate()->OnURLFetchComplete(fetcher);
381  EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
382  EXPECT_TRUE(PolicyBundle().Equals(manager_->policies()));
383  Mock::VerifyAndClearExpectations(&observer_);
384}
385
386TEST_F(UserCloudPolicyManagerChromeOSTest, BlockingFetchRegisterError) {
387  // Tests the initialization of a manager whose Profile is waiting for the
388  // initial fetch, when the device management registration fails.
389  ASSERT_NO_FATAL_FAILURE(CreateManager(true));
390
391  // Initialize the CloudPolicyService without any stored data.
392  EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete());
393  store_->NotifyStoreError();
394  EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete());
395  EXPECT_FALSE(manager_->core()->client()->is_registered());
396
397  // This starts the OAuth2 policy token fetcher using the signin Profile.
398  // The manager will then issue the registration request.
399  MockDeviceManagementJob* register_request = IssueOAuthToken(false);
400  ASSERT_TRUE(register_request);
401
402  // Now make it fail.
403  EXPECT_FALSE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
404  EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));
405  register_request->SendResponse(DM_STATUS_TEMPORARY_UNAVAILABLE,
406                                 em::DeviceManagementResponse());
407  EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
408  EXPECT_TRUE(PolicyBundle().Equals(manager_->policies()));
409  Mock::VerifyAndClearExpectations(&observer_);
410}
411
412TEST_F(UserCloudPolicyManagerChromeOSTest, BlockingFetchPolicyFetchError) {
413  // Tests the initialization of a manager whose Profile is waiting for the
414  // initial fetch, when the policy fetch request fails.
415  ASSERT_NO_FATAL_FAILURE(CreateManager(true));
416
417  // Initialize the CloudPolicyService without any stored data.
418  EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete());
419  store_->NotifyStoreLoaded();
420  EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete());
421  EXPECT_FALSE(manager_->core()->client()->is_registered());
422
423  // This starts the OAuth2 policy token fetcher using the signin Profile.
424  // The manager will then issue the registration request.
425  MockDeviceManagementJob* register_request = IssueOAuthToken(false);
426  ASSERT_TRUE(register_request);
427
428  // Reply with a valid registration response. This triggers the initial policy
429  // fetch.
430  MockDeviceManagementJob* policy_request = NULL;
431  EXPECT_CALL(device_management_service_,
432              CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH))
433      .WillOnce(device_management_service_.CreateAsyncJob(&policy_request));
434  register_request->SendResponse(DM_STATUS_SUCCESS, register_blob_);
435  Mock::VerifyAndClearExpectations(&device_management_service_);
436  ASSERT_TRUE(policy_request);
437  EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete());
438  EXPECT_TRUE(manager_->core()->client()->is_registered());
439
440  // Make the policy fetch fail. The observer gets 2 notifications: one from the
441  // RefreshPolicies callback, and another from the OnClientError callback.
442  // A single notification suffices for this edge case, but this behavior is
443  // also correct and makes the implementation simpler.
444  EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get())).Times(AtLeast(1));
445  EXPECT_FALSE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
446  policy_request->SendResponse(DM_STATUS_TEMPORARY_UNAVAILABLE,
447                               em::DeviceManagementResponse());
448  Mock::VerifyAndClearExpectations(&observer_);
449  EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
450  EXPECT_TRUE(PolicyBundle().Equals(manager_->policies()));
451}
452
453TEST_F(UserCloudPolicyManagerChromeOSTest, NonBlockingFirstFetch) {
454  // Tests the first policy fetch request by a Profile that isn't managed.
455  ASSERT_NO_FATAL_FAILURE(CreateManager(false));
456
457  // Initialize the CloudPolicyService without any stored data. Since the
458  // manager is not waiting for the initial fetch, it will become initialized
459  // once the store is ready.
460  EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete());
461  EXPECT_FALSE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
462  EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));
463  store_->NotifyStoreLoaded();
464  Mock::VerifyAndClearExpectations(&observer_);
465  EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete());
466  EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
467  EXPECT_FALSE(manager_->core()->client()->is_registered());
468
469  // The manager is waiting for the refresh token, and hasn't started any
470  // fetchers.
471  EXPECT_FALSE(test_url_fetcher_factory_.GetFetcherByID(0));
472
473  // Set a fake refresh token at the TokenService.
474  TokenService* token_service = TokenServiceFactory::GetForProfile(profile_);
475  ASSERT_TRUE(token_service);
476  GaiaAuthConsumer::ClientOAuthResult tokens("refresh", "access", 3600);
477  EXPECT_FALSE(token_service->HasOAuthLoginToken());
478  token_service->UpdateCredentialsWithOAuth2(tokens);
479  EXPECT_TRUE(token_service->HasOAuthLoginToken());
480
481  // That should have notified the manager, which now issues the request for the
482  // policy oauth token.
483  MockDeviceManagementJob* register_request = IssueOAuthToken(true);
484  ASSERT_TRUE(register_request);
485  register_request->SendResponse(DM_STATUS_SUCCESS, register_blob_);
486
487  // The refresh scheduler takes care of the initial fetch for unmanaged users.
488  // It posts a delayed task with 0ms delay in this case, so spinning the loop
489  // issues the initial fetch.
490  base::RunLoop loop;
491  FetchPolicy(
492      base::Bind(&base::RunLoop::RunUntilIdle, base::Unretained(&loop)));
493}
494
495TEST_F(UserCloudPolicyManagerChromeOSTest, NonBlockingRefreshFetch) {
496  // Tests a non-blocking initial policy fetch for a Profile that already has
497  // a cached DMToken.
498  ASSERT_NO_FATAL_FAILURE(CreateManager(false));
499
500  // Set the initially cached data and initialize the CloudPolicyService.
501  // The initial policy fetch is issued using the cached DMToken.
502  EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete());
503  EXPECT_FALSE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
504  EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));
505  store_->policy_.reset(new em::PolicyData(policy_data_));
506  store_->NotifyStoreLoaded();
507  Mock::VerifyAndClearExpectations(&observer_);
508  EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete());
509  EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
510  EXPECT_TRUE(manager_->core()->client()->is_registered());
511
512  // The refresh scheduler takes care of the initial fetch for unmanaged users.
513  // It posts a delayed task with 0ms delay in this case, so spinning the loop
514  // issues the initial fetch.
515  base::RunLoop loop;
516  FetchPolicy(
517      base::Bind(&base::RunLoop::RunUntilIdle, base::Unretained(&loop)));
518}
519
520}  // namespace policy
521