user_cloud_policy_manager_chromeos_unittest.cc revision a3f7b4e666c476898878fa745f637129375cd889
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/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_bundle.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      : store_(NULL),
79        profile_(NULL),
80        signin_profile_(NULL) {}
81
82  virtual void SetUp() OVERRIDE {
83    // The initialization path that blocks on the initial policy fetch requires
84    // a signin Profile to use its URLRequestContext.
85    profile_manager_.reset(
86        new TestingProfileManager(TestingBrowserProcess::GetGlobal()));
87    ASSERT_TRUE(profile_manager_->SetUp());
88    profile_ = profile_manager_->CreateTestingProfile(
89        chrome::kInitialProfile, scoped_ptr<PrefServiceSyncable>(),
90        UTF8ToUTF16("testing_profile"), 0);
91    signin_profile_ = profile_manager_->CreateTestingProfile(kSigninProfile);
92    signin_profile_->set_incognito(true);
93    // Usually the signin Profile and the main Profile are separate, but since
94    // the signin Profile is an OTR Profile then for this test it suffices to
95    // attach it to the main Profile.
96    profile_->SetOffTheRecordProfile(signin_profile_);
97    signin_profile_->SetOriginalProfile(profile_);
98    ASSERT_EQ(signin_profile_, chromeos::ProfileHelper::GetSigninProfile());
99
100    chrome::RegisterLocalState(prefs_.registry());
101
102    // Set up a policy map for testing.
103    policy_map_.Set("HomepageLocation",
104                    POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
105                    base::Value::CreateStringValue("http://chromium.org"),
106                    NULL);
107    expected_bundle_.Get(PolicyNamespace(POLICY_DOMAIN_CHROME, std::string()))
108        .CopyFrom(policy_map_);
109
110    // Create fake policy blobs to deliver to the client.
111    em::DeviceRegisterResponse* register_response =
112        register_blob_.mutable_register_response();
113    register_response->set_device_management_token("dmtoken123");
114
115    em::CloudPolicySettings policy_proto;
116    policy_proto.mutable_homepagelocation()->set_value("http://chromium.org");
117    ASSERT_TRUE(
118        policy_proto.SerializeToString(policy_data_.mutable_policy_value()));
119    policy_data_.set_policy_type(dm_protocol::kChromeUserPolicyType);
120    policy_data_.set_request_token("dmtoken123");
121    policy_data_.set_device_id("id987");
122    em::PolicyFetchResponse* policy_response =
123        policy_blob_.mutable_policy_response()->add_response();
124    ASSERT_TRUE(policy_data_.SerializeToString(
125        policy_response->mutable_policy_data()));
126
127    EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
128        .Times(AnyNumber());
129  }
130
131  virtual void TearDown() OVERRIDE {
132    if (manager_) {
133      manager_->RemoveObserver(&observer_);
134      manager_->Shutdown();
135    }
136    signin_profile_ = NULL;
137    profile_ = NULL;
138    profile_manager_->DeleteTestingProfile(kSigninProfile);
139    profile_manager_->DeleteTestingProfile(chrome::kInitialProfile);
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 and
269  // for the cleanup of URLRequestContextGetter in the |signin_profile_|.
270  content::TestBrowserThreadBundle thread_bundle_;
271
272  // Convenience policy objects.
273  em::PolicyData policy_data_;
274  em::DeviceManagementResponse register_blob_;
275  em::DeviceManagementResponse policy_blob_;
276  PolicyMap policy_map_;
277  PolicyBundle expected_bundle_;
278
279  // Policy infrastructure.
280  net::TestURLFetcherFactory test_url_fetcher_factory_;
281  TestingPrefServiceSimple prefs_;
282  MockConfigurationPolicyObserver observer_;
283  MockDeviceManagementService device_management_service_;
284  MockCloudPolicyStore* store_;
285  scoped_ptr<UserCloudPolicyManagerChromeOS> manager_;
286  scoped_ptr<UserCloudPolicyTokenForwarder> token_forwarder_;
287
288  // Required by ProfileHelper to get the signin Profile context.
289  scoped_ptr<TestingProfileManager> profile_manager_;
290  TestingProfile* profile_;
291  TestingProfile* signin_profile_;
292
293  static const char kSigninProfile[];
294
295 private:
296  DISALLOW_COPY_AND_ASSIGN(UserCloudPolicyManagerChromeOSTest);
297};
298
299const char UserCloudPolicyManagerChromeOSTest::kSigninProfile[] =
300    "signin_profile";
301
302TEST_F(UserCloudPolicyManagerChromeOSTest, BlockingFirstFetch) {
303  // Tests the initialization of a manager whose Profile is waiting for the
304  // initial fetch, when the policy cache is empty.
305  ASSERT_NO_FATAL_FAILURE(CreateManager(true));
306
307  // Initialize the CloudPolicyService without any stored data.
308  EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete());
309  store_->NotifyStoreLoaded();
310  EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete());
311  EXPECT_FALSE(manager_->core()->client()->is_registered());
312
313  // This starts the OAuth2 policy token fetcher using the signin Profile.
314  // The manager will then issue the registration request.
315  MockDeviceManagementJob* register_request = IssueOAuthToken(false);
316  ASSERT_TRUE(register_request);
317
318  // Reply with a valid registration response. This triggers the initial policy
319  // fetch.
320  FetchPolicy(base::Bind(&MockDeviceManagementJob::SendResponse,
321                         base::Unretained(register_request),
322                         DM_STATUS_SUCCESS, register_blob_));
323}
324
325TEST_F(UserCloudPolicyManagerChromeOSTest, BlockingRefreshFetch) {
326  // Tests the initialization of a manager whose Profile is waiting for the
327  // initial fetch, when a previously cached policy and DMToken already exist.
328  ASSERT_NO_FATAL_FAILURE(CreateManager(true));
329
330  // Set the initially cached data and initialize the CloudPolicyService.
331  // The initial policy fetch is issued using the cached DMToken.
332  store_->policy_.reset(new em::PolicyData(policy_data_));
333  FetchPolicy(base::Bind(&MockCloudPolicyStore::NotifyStoreLoaded,
334                         base::Unretained(store_)));
335}
336
337TEST_F(UserCloudPolicyManagerChromeOSTest, BlockingFetchStoreError) {
338  // Tests the initialization of a manager whose Profile is waiting for the
339  // initial fetch, when the initial store load fails.
340  ASSERT_NO_FATAL_FAILURE(CreateManager(true));
341
342  // Initialize the CloudPolicyService without any stored data.
343  EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete());
344  store_->NotifyStoreError();
345  EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete());
346  EXPECT_FALSE(manager_->core()->client()->is_registered());
347
348  // This starts the OAuth2 policy token fetcher using the signin Profile.
349  // The manager will then issue the registration request.
350  MockDeviceManagementJob* register_request = IssueOAuthToken(false);
351  ASSERT_TRUE(register_request);
352
353  // Reply with a valid registration response. This triggers the initial policy
354  // fetch.
355  FetchPolicy(base::Bind(&MockDeviceManagementJob::SendResponse,
356                         base::Unretained(register_request),
357                         DM_STATUS_SUCCESS, register_blob_));
358}
359
360TEST_F(UserCloudPolicyManagerChromeOSTest, BlockingFetchOAuthError) {
361  // Tests the initialization of a manager whose Profile is waiting for the
362  // initial fetch, when the OAuth2 token fetch fails.
363  ASSERT_NO_FATAL_FAILURE(CreateManager(true));
364
365  // Initialize the CloudPolicyService without any stored data.
366  EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete());
367  store_->NotifyStoreLoaded();
368  EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete());
369  EXPECT_FALSE(manager_->core()->client()->is_registered());
370
371  // This starts the OAuth2 policy token fetcher using the signin Profile.
372  // The manager will initialize with no policy after the token fetcher fails.
373  EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));
374
375  // The PolicyOAuth2TokenFetcher posts delayed retries on some errors. This
376  // data will make it fail immediately.
377  net::TestURLFetcher* fetcher = PrepareOAuthFetcher(
378      GaiaUrls::GetInstance()->client_login_to_oauth2_url());
379  ASSERT_TRUE(fetcher);
380  fetcher->set_response_code(400);
381  fetcher->SetResponseString("Error=BadAuthentication");
382  EXPECT_FALSE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
383  fetcher->delegate()->OnURLFetchComplete(fetcher);
384  EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
385  EXPECT_TRUE(PolicyBundle().Equals(manager_->policies()));
386  Mock::VerifyAndClearExpectations(&observer_);
387}
388
389TEST_F(UserCloudPolicyManagerChromeOSTest, BlockingFetchRegisterError) {
390  // Tests the initialization of a manager whose Profile is waiting for the
391  // initial fetch, when the device management registration fails.
392  ASSERT_NO_FATAL_FAILURE(CreateManager(true));
393
394  // Initialize the CloudPolicyService without any stored data.
395  EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete());
396  store_->NotifyStoreError();
397  EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete());
398  EXPECT_FALSE(manager_->core()->client()->is_registered());
399
400  // This starts the OAuth2 policy token fetcher using the signin Profile.
401  // The manager will then issue the registration request.
402  MockDeviceManagementJob* register_request = IssueOAuthToken(false);
403  ASSERT_TRUE(register_request);
404
405  // Now make it fail.
406  EXPECT_FALSE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
407  EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));
408  register_request->SendResponse(DM_STATUS_TEMPORARY_UNAVAILABLE,
409                                 em::DeviceManagementResponse());
410  EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
411  EXPECT_TRUE(PolicyBundle().Equals(manager_->policies()));
412  Mock::VerifyAndClearExpectations(&observer_);
413}
414
415TEST_F(UserCloudPolicyManagerChromeOSTest, BlockingFetchPolicyFetchError) {
416  // Tests the initialization of a manager whose Profile is waiting for the
417  // initial fetch, when the policy fetch request fails.
418  ASSERT_NO_FATAL_FAILURE(CreateManager(true));
419
420  // Initialize the CloudPolicyService without any stored data.
421  EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete());
422  store_->NotifyStoreLoaded();
423  EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete());
424  EXPECT_FALSE(manager_->core()->client()->is_registered());
425
426  // This starts the OAuth2 policy token fetcher using the signin Profile.
427  // The manager will then issue the registration request.
428  MockDeviceManagementJob* register_request = IssueOAuthToken(false);
429  ASSERT_TRUE(register_request);
430
431  // Reply with a valid registration response. This triggers the initial policy
432  // fetch.
433  MockDeviceManagementJob* policy_request = NULL;
434  EXPECT_CALL(device_management_service_,
435              CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH))
436      .WillOnce(device_management_service_.CreateAsyncJob(&policy_request));
437  register_request->SendResponse(DM_STATUS_SUCCESS, register_blob_);
438  Mock::VerifyAndClearExpectations(&device_management_service_);
439  ASSERT_TRUE(policy_request);
440  EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete());
441  EXPECT_TRUE(manager_->core()->client()->is_registered());
442
443  // Make the policy fetch fail. The observer gets 2 notifications: one from the
444  // RefreshPolicies callback, and another from the OnClientError callback.
445  // A single notification suffices for this edge case, but this behavior is
446  // also correct and makes the implementation simpler.
447  EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get())).Times(AtLeast(1));
448  EXPECT_FALSE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
449  policy_request->SendResponse(DM_STATUS_TEMPORARY_UNAVAILABLE,
450                               em::DeviceManagementResponse());
451  Mock::VerifyAndClearExpectations(&observer_);
452  EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
453  EXPECT_TRUE(PolicyBundle().Equals(manager_->policies()));
454}
455
456TEST_F(UserCloudPolicyManagerChromeOSTest, NonBlockingFirstFetch) {
457  // Tests the first policy fetch request by a Profile that isn't managed.
458  ASSERT_NO_FATAL_FAILURE(CreateManager(false));
459
460  // Initialize the CloudPolicyService without any stored data. Since the
461  // manager is not waiting for the initial fetch, it will become initialized
462  // once the store is ready.
463  EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete());
464  EXPECT_FALSE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
465  EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));
466  store_->NotifyStoreLoaded();
467  Mock::VerifyAndClearExpectations(&observer_);
468  EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete());
469  EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
470  EXPECT_FALSE(manager_->core()->client()->is_registered());
471
472  // The manager is waiting for the refresh token, and hasn't started any
473  // fetchers.
474  EXPECT_FALSE(test_url_fetcher_factory_.GetFetcherByID(0));
475
476  // Set a fake refresh token at the TokenService.
477  TokenService* token_service = TokenServiceFactory::GetForProfile(profile_);
478  ASSERT_TRUE(token_service);
479  GaiaAuthConsumer::ClientOAuthResult tokens("refresh", "access", 3600);
480  EXPECT_FALSE(token_service->HasOAuthLoginToken());
481  token_service->UpdateCredentialsWithOAuth2(tokens);
482  EXPECT_TRUE(token_service->HasOAuthLoginToken());
483
484  // That should have notified the manager, which now issues the request for the
485  // policy oauth token.
486  MockDeviceManagementJob* register_request = IssueOAuthToken(true);
487  ASSERT_TRUE(register_request);
488  register_request->SendResponse(DM_STATUS_SUCCESS, register_blob_);
489
490  // The refresh scheduler takes care of the initial fetch for unmanaged users.
491  // It posts a delayed task with 0ms delay in this case, so spinning the loop
492  // issues the initial fetch.
493  base::RunLoop loop;
494  FetchPolicy(
495      base::Bind(&base::RunLoop::RunUntilIdle, base::Unretained(&loop)));
496}
497
498TEST_F(UserCloudPolicyManagerChromeOSTest, NonBlockingRefreshFetch) {
499  // Tests a non-blocking initial policy fetch for a Profile that already has
500  // a cached DMToken.
501  ASSERT_NO_FATAL_FAILURE(CreateManager(false));
502
503  // Set the initially cached data and initialize the CloudPolicyService.
504  // The initial policy fetch is issued using the cached DMToken.
505  EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete());
506  EXPECT_FALSE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
507  EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));
508  store_->policy_.reset(new em::PolicyData(policy_data_));
509  store_->NotifyStoreLoaded();
510  Mock::VerifyAndClearExpectations(&observer_);
511  EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete());
512  EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
513  EXPECT_TRUE(manager_->core()->client()->is_registered());
514
515  // The refresh scheduler takes care of the initial fetch for unmanaged users.
516  // It posts a delayed task with 0ms delay in this case, so spinning the loop
517  // issues the initial fetch.
518  base::RunLoop loop;
519  FetchPolicy(
520      base::Bind(&base::RunLoop::RunUntilIdle, base::Unretained(&loop)));
521}
522
523}  // namespace policy
524