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