Revert of Add button to add new FSP services to Files app. (patchset #8 id:140001...
[chromium-blink-merge.git] / chrome / browser / chromeos / policy / user_cloud_policy_manager_chromeos_unittest.cc
blob7d7f3994f3340c20819ad56f74c7193f163b4d43
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.
5 #include "chrome/browser/chromeos/policy/user_cloud_policy_manager_chromeos.h"
7 #include "base/bind.h"
8 #include "base/bind_helpers.h"
9 #include "base/callback.h"
10 #include "base/message_loop/message_loop.h"
11 #include "base/prefs/pref_registry_simple.h"
12 #include "base/prefs/testing_pref_service.h"
13 #include "base/run_loop.h"
14 #include "base/sequenced_task_runner.h"
15 #include "base/strings/string_util.h"
16 #include "base/strings/utf_string_conversions.h"
17 #include "base/test/test_simple_task_runner.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/prefs/browser_prefs.h"
21 #include "chrome/browser/prefs/pref_service_syncable.h"
22 #include "chrome/browser/signin/fake_profile_oauth2_token_service.h"
23 #include "chrome/browser/signin/fake_profile_oauth2_token_service_builder.h"
24 #include "chrome/browser/signin/profile_oauth2_token_service_factory.h"
25 #include "chrome/browser/signin/signin_manager_factory.h"
26 #include "chrome/common/chrome_constants.h"
27 #include "chrome/test/base/testing_browser_process.h"
28 #include "chrome/test/base/testing_profile.h"
29 #include "chrome/test/base/testing_profile_manager.h"
30 #include "components/policy/core/common/cloud/cloud_external_data_manager.h"
31 #include "components/policy/core/common/cloud/mock_cloud_external_data_manager.h"
32 #include "components/policy/core/common/cloud/mock_cloud_policy_store.h"
33 #include "components/policy/core/common/cloud/mock_device_management_service.h"
34 #include "components/policy/core/common/external_data_fetcher.h"
35 #include "components/policy/core/common/mock_configuration_policy_provider.h"
36 #include "components/policy/core/common/schema_registry.h"
37 #include "components/signin/core/browser/profile_oauth2_token_service.h"
38 #include "components/signin/core/browser/signin_manager.h"
39 #include "content/public/test/test_browser_thread_bundle.h"
40 #include "google_apis/gaia/gaia_auth_consumer.h"
41 #include "google_apis/gaia/gaia_constants.h"
42 #include "google_apis/gaia/gaia_urls.h"
43 #include "net/url_request/test_url_fetcher_factory.h"
44 #include "net/url_request/url_fetcher_delegate.h"
45 #include "net/url_request/url_request_context_getter.h"
46 #include "net/url_request/url_request_status.h"
47 #include "policy/policy_constants.h"
48 #include "policy/proto/device_management_backend.pb.h"
49 #include "testing/gmock/include/gmock/gmock.h"
50 #include "testing/gtest/include/gtest/gtest.h"
52 namespace em = enterprise_management;
54 using testing::AnyNumber;
55 using testing::AtLeast;
56 using testing::Mock;
57 using testing::_;
59 namespace policy {
61 const char kOAuthCodeCookie[] = "oauth_code=1234; Secure; HttpOnly";
63 const char kOAuth2TokenPairData[] =
64 "{"
65 " \"refresh_token\": \"1234\","
66 " \"access_token\": \"5678\","
67 " \"expires_in\": 3600"
68 "}";
70 const char kOAuth2AccessTokenData[] =
71 "{"
72 " \"access_token\": \"5678\","
73 " \"expires_in\": 3600"
74 "}";
76 class UserCloudPolicyManagerChromeOSTest : public testing::Test {
77 protected:
78 UserCloudPolicyManagerChromeOSTest()
79 : store_(NULL),
80 external_data_manager_(NULL),
81 task_runner_(new base::TestSimpleTaskRunner()),
82 profile_(NULL),
83 signin_profile_(NULL) {}
85 void SetUp() override {
86 // The initialization path that blocks on the initial policy fetch requires
87 // a signin Profile to use its URLRequestContext.
88 profile_manager_.reset(
89 new TestingProfileManager(TestingBrowserProcess::GetGlobal()));
90 ASSERT_TRUE(profile_manager_->SetUp());
91 TestingProfile::TestingFactories factories;
92 factories.push_back(
93 std::make_pair(ProfileOAuth2TokenServiceFactory::GetInstance(),
94 BuildFakeProfileOAuth2TokenService));
95 profile_ = profile_manager_->CreateTestingProfile(
96 chrome::kInitialProfile,
97 scoped_ptr<PrefServiceSyncable>(),
98 base::UTF8ToUTF16(""),
100 std::string(),
101 factories);
102 // Usually the signin Profile and the main Profile are separate, but since
103 // the signin Profile is an OTR Profile then for this test it suffices to
104 // attach it to the main Profile.
105 signin_profile_ = TestingProfile::Builder().BuildIncognito(profile_);
106 ASSERT_EQ(signin_profile_, chromeos::ProfileHelper::GetSigninProfile());
108 chrome::RegisterLocalState(prefs_.registry());
110 // Set up a policy map for testing.
111 policy_map_.Set(key::kHomepageLocation,
112 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
113 new base::StringValue("http://chromium.org"),
114 NULL);
115 policy_map_.Set(key::kChromeOsMultiProfileUserBehavior,
116 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
117 new base::StringValue("primary-only"),
118 NULL);
119 policy_map_.Set(key::kEasyUnlockAllowed,
120 POLICY_LEVEL_MANDATORY, POLICY_SCOPE_USER,
121 new base::FundamentalValue(false),
122 NULL);
123 policy_map_.Set(key::kCaptivePortalAuthenticationIgnoresProxy,
124 POLICY_LEVEL_MANDATORY,
125 POLICY_SCOPE_USER,
126 new base::FundamentalValue(false),
127 NULL);
128 expected_bundle_.Get(PolicyNamespace(POLICY_DOMAIN_CHROME, std::string()))
129 .CopyFrom(policy_map_);
131 // Create fake policy blobs to deliver to the client.
132 em::DeviceRegisterResponse* register_response =
133 register_blob_.mutable_register_response();
134 register_response->set_device_management_token("dmtoken123");
136 em::CloudPolicySettings policy_proto;
137 policy_proto.mutable_homepagelocation()->set_value("http://chromium.org");
138 ASSERT_TRUE(
139 policy_proto.SerializeToString(policy_data_.mutable_policy_value()));
140 policy_data_.set_policy_type(dm_protocol::kChromeUserPolicyType);
141 policy_data_.set_request_token("dmtoken123");
142 policy_data_.set_device_id("id987");
143 em::PolicyFetchResponse* policy_response =
144 policy_blob_.mutable_policy_response()->add_response();
145 ASSERT_TRUE(policy_data_.SerializeToString(
146 policy_response->mutable_policy_data()));
148 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
149 .Times(AnyNumber());
152 void TearDown() override {
153 if (token_forwarder_)
154 token_forwarder_->Shutdown();
155 if (manager_) {
156 manager_->RemoveObserver(&observer_);
157 manager_->Shutdown();
159 signin_profile_ = NULL;
160 profile_ = NULL;
161 profile_manager_->DeleteTestingProfile(chrome::kInitialProfile);
164 void CreateManager(bool wait_for_fetch, int fetch_timeout) {
165 store_ = new MockCloudPolicyStore();
166 external_data_manager_ = new MockCloudExternalDataManager;
167 external_data_manager_->SetPolicyStore(store_);
168 EXPECT_CALL(*store_, Load());
169 manager_.reset(new UserCloudPolicyManagerChromeOS(
170 scoped_ptr<CloudPolicyStore>(store_),
171 scoped_ptr<CloudExternalDataManager>(external_data_manager_),
172 base::FilePath(),
173 wait_for_fetch,
174 base::TimeDelta::FromSeconds(fetch_timeout),
175 task_runner_,
176 task_runner_,
177 task_runner_));
178 manager_->Init(&schema_registry_);
179 manager_->AddObserver(&observer_);
180 manager_->Connect(&prefs_, &device_management_service_, NULL,
181 USER_AFFILIATION_NONE);
182 Mock::VerifyAndClearExpectations(store_);
183 EXPECT_FALSE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
184 EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete());
186 if (!wait_for_fetch) {
187 // Create the UserCloudPolicyTokenForwarder, which fetches the access
188 // token using the OAuth2PolicyFetcher and forwards it to the
189 // UserCloudPolicyManagerChromeOS. This service is automatically created
190 // for regular Profiles but not for testing Profiles.
191 ProfileOAuth2TokenService* token_service =
192 ProfileOAuth2TokenServiceFactory::GetForProfile(profile_);
193 ASSERT_TRUE(token_service);
194 SigninManagerBase* signin_manager =
195 SigninManagerFactory::GetForProfile(profile_);
196 ASSERT_TRUE(signin_manager);
197 token_forwarder_.reset(
198 new UserCloudPolicyTokenForwarder(manager_.get(), token_service,
199 signin_manager));
203 // Expects a pending URLFetcher for the |expected_url|, and returns it with
204 // prepared to deliver a response to its delegate.
205 net::TestURLFetcher* PrepareOAuthFetcher(const GURL& expected_url) {
206 net::TestURLFetcher* fetcher = test_url_fetcher_factory_.GetFetcherByID(0);
207 EXPECT_TRUE(fetcher);
208 if (!fetcher)
209 return NULL;
210 EXPECT_TRUE(fetcher->delegate());
211 EXPECT_TRUE(StartsWithASCII(fetcher->GetOriginalURL().spec(),
212 expected_url.spec(),
213 true));
214 fetcher->set_url(fetcher->GetOriginalURL());
215 fetcher->set_response_code(200);
216 fetcher->set_status(net::URLRequestStatus());
217 return fetcher;
220 // Issues the OAuth2 tokens and returns the device management register job
221 // if the flow succeeded.
222 MockDeviceManagementJob* IssueOAuthToken(bool has_request_token) {
223 EXPECT_FALSE(manager_->core()->client()->is_registered());
225 // Issuing this token triggers the callback of the OAuth2PolicyFetcher,
226 // which triggers the registration request.
227 MockDeviceManagementJob* register_request = NULL;
228 EXPECT_CALL(device_management_service_,
229 CreateJob(DeviceManagementRequestJob::TYPE_REGISTRATION, _))
230 .WillOnce(device_management_service_.CreateAsyncJob(&register_request));
232 if (!has_request_token) {
233 GaiaUrls* gaia_urls = GaiaUrls::GetInstance();
234 net::TestURLFetcher* fetcher = NULL;
236 // Issue the oauth_token cookie first.
237 fetcher = PrepareOAuthFetcher(gaia_urls->client_login_to_oauth2_url());
238 if (!fetcher)
239 return NULL;
240 net::ResponseCookies cookies;
241 cookies.push_back(kOAuthCodeCookie);
243 fetcher->set_cookies(cookies);
244 fetcher->delegate()->OnURLFetchComplete(fetcher);
246 // Issue the refresh token.
247 fetcher = PrepareOAuthFetcher(gaia_urls->oauth2_token_url());
248 if (!fetcher)
249 return NULL;
250 fetcher->SetResponseString(kOAuth2TokenPairData);
251 fetcher->delegate()->OnURLFetchComplete(fetcher);
253 // Issue the access token.
254 fetcher = PrepareOAuthFetcher(gaia_urls->oauth2_token_url());
255 if (!fetcher)
256 return NULL;
257 fetcher->SetResponseString(kOAuth2AccessTokenData);
258 fetcher->delegate()->OnURLFetchComplete(fetcher);
259 } else {
260 // Since the refresh token is available, OAuth2TokenService was used
261 // to request the access token and not UserCloudPolicyTokenForwarder.
262 // Issue the access token with the former.
263 FakeProfileOAuth2TokenService* token_service =
264 static_cast<FakeProfileOAuth2TokenService*>(
265 ProfileOAuth2TokenServiceFactory::GetForProfile(profile_));
266 EXPECT_TRUE(token_service);
267 OAuth2TokenService::ScopeSet scopes;
268 scopes.insert(GaiaConstants::kDeviceManagementServiceOAuth);
269 scopes.insert(GaiaConstants::kOAuthWrapBridgeUserInfoScope);
270 token_service->IssueTokenForScope(
271 scopes, "5678",
272 base::Time::Now() + base::TimeDelta::FromSeconds(3600));
275 EXPECT_TRUE(register_request);
276 EXPECT_FALSE(manager_->core()->client()->is_registered());
278 Mock::VerifyAndClearExpectations(&device_management_service_);
279 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
280 .Times(AnyNumber());
282 return register_request;
285 // Expects a policy fetch request to be issued after invoking |trigger_fetch|.
286 // This method replies to that fetch request and verifies that the manager
287 // handled the response.
288 void FetchPolicy(const base::Closure& trigger_fetch) {
289 MockDeviceManagementJob* policy_request = NULL;
290 EXPECT_CALL(device_management_service_,
291 CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH, _))
292 .WillOnce(device_management_service_.CreateAsyncJob(&policy_request));
293 trigger_fetch.Run();
294 ASSERT_TRUE(policy_request);
295 EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete());
296 EXPECT_TRUE(manager_->core()->client()->is_registered());
298 Mock::VerifyAndClearExpectations(&device_management_service_);
299 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
300 .Times(AnyNumber());
302 // Send the initial policy back. This completes the initialization flow.
303 EXPECT_CALL(*store_, Store(_));
304 policy_request->SendResponse(DM_STATUS_SUCCESS, policy_blob_);
305 Mock::VerifyAndClearExpectations(store_);
307 // Notifying that the store is has cached the fetched policy completes the
308 // process, and initializes the manager.
309 EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));
310 store_->policy_map_.CopyFrom(policy_map_);
311 store_->NotifyStoreLoaded();
312 EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
313 Mock::VerifyAndClearExpectations(&observer_);
314 EXPECT_TRUE(manager_->policies().Equals(expected_bundle_));
317 // Required by the refresh scheduler that's created by the manager and
318 // for the cleanup of URLRequestContextGetter in the |signin_profile_|.
319 content::TestBrowserThreadBundle thread_bundle_;
321 // Convenience policy objects.
322 em::PolicyData policy_data_;
323 em::DeviceManagementResponse register_blob_;
324 em::DeviceManagementResponse policy_blob_;
325 PolicyMap policy_map_;
326 PolicyBundle expected_bundle_;
328 // Policy infrastructure.
329 net::TestURLFetcherFactory test_url_fetcher_factory_;
330 TestingPrefServiceSimple prefs_;
331 MockConfigurationPolicyObserver observer_;
332 MockDeviceManagementService device_management_service_;
333 MockCloudPolicyStore* store_; // Not owned.
334 MockCloudExternalDataManager* external_data_manager_; // Not owned.
335 scoped_refptr<base::TestSimpleTaskRunner> task_runner_;
336 SchemaRegistry schema_registry_;
337 scoped_ptr<UserCloudPolicyManagerChromeOS> manager_;
338 scoped_ptr<UserCloudPolicyTokenForwarder> token_forwarder_;
340 // Required by ProfileHelper to get the signin Profile context.
341 scoped_ptr<TestingProfileManager> profile_manager_;
342 TestingProfile* profile_;
343 TestingProfile* signin_profile_;
345 private:
346 DISALLOW_COPY_AND_ASSIGN(UserCloudPolicyManagerChromeOSTest);
349 TEST_F(UserCloudPolicyManagerChromeOSTest, BlockingFirstFetch) {
350 // Tests the initialization of a manager whose Profile is waiting for the
351 // initial fetch, when the policy cache is empty.
352 ASSERT_NO_FATAL_FAILURE(CreateManager(true, 1000));
354 // Initialize the CloudPolicyService without any stored data.
355 EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete());
356 store_->NotifyStoreLoaded();
357 EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete());
358 EXPECT_FALSE(manager_->core()->client()->is_registered());
360 // This starts the OAuth2 policy token fetcher using the signin Profile.
361 // The manager will then issue the registration request.
362 MockDeviceManagementJob* register_request = IssueOAuthToken(false);
363 ASSERT_TRUE(register_request);
365 // Reply with a valid registration response. This triggers the initial policy
366 // fetch.
367 FetchPolicy(base::Bind(&MockDeviceManagementJob::SendResponse,
368 base::Unretained(register_request),
369 DM_STATUS_SUCCESS, register_blob_));
372 TEST_F(UserCloudPolicyManagerChromeOSTest, BlockingRefreshFetch) {
373 // Tests the initialization of a manager whose Profile is waiting for the
374 // initial fetch, when a previously cached policy and DMToken already exist.
375 ASSERT_NO_FATAL_FAILURE(CreateManager(true, 1000));
377 // Set the initially cached data and initialize the CloudPolicyService.
378 // The initial policy fetch is issued using the cached DMToken.
379 store_->policy_.reset(new em::PolicyData(policy_data_));
380 FetchPolicy(base::Bind(&MockCloudPolicyStore::NotifyStoreLoaded,
381 base::Unretained(store_)));
384 TEST_F(UserCloudPolicyManagerChromeOSTest, BlockingFetchStoreError) {
385 // Tests the initialization of a manager whose Profile is waiting for the
386 // initial fetch, when the initial store load fails.
387 ASSERT_NO_FATAL_FAILURE(CreateManager(true, 1000));
389 // Initialize the CloudPolicyService without any stored data.
390 EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete());
391 store_->NotifyStoreError();
392 EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete());
393 EXPECT_FALSE(manager_->core()->client()->is_registered());
395 // This starts the OAuth2 policy token fetcher using the signin Profile.
396 // The manager will then issue the registration request.
397 MockDeviceManagementJob* register_request = IssueOAuthToken(false);
398 ASSERT_TRUE(register_request);
400 // Reply with a valid registration response. This triggers the initial policy
401 // fetch.
402 FetchPolicy(base::Bind(&MockDeviceManagementJob::SendResponse,
403 base::Unretained(register_request),
404 DM_STATUS_SUCCESS, register_blob_));
407 TEST_F(UserCloudPolicyManagerChromeOSTest, BlockingFetchOAuthError) {
408 // Tests the initialization of a manager whose Profile is waiting for the
409 // initial fetch, when the OAuth2 token fetch fails.
410 ASSERT_NO_FATAL_FAILURE(CreateManager(true, 1000));
412 // Initialize the CloudPolicyService without any stored data.
413 EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete());
414 store_->NotifyStoreLoaded();
415 EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete());
416 EXPECT_FALSE(manager_->core()->client()->is_registered());
418 // This starts the OAuth2 policy token fetcher using the signin Profile.
419 // The manager will initialize with no policy after the token fetcher fails.
420 EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));
422 // The PolicyOAuth2TokenFetcher posts delayed retries on some errors. This
423 // data will make it fail immediately.
424 net::TestURLFetcher* fetcher = PrepareOAuthFetcher(
425 GaiaUrls::GetInstance()->client_login_to_oauth2_url());
426 ASSERT_TRUE(fetcher);
427 fetcher->set_response_code(400);
428 fetcher->SetResponseString("Error=BadAuthentication");
429 EXPECT_FALSE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
430 fetcher->delegate()->OnURLFetchComplete(fetcher);
431 EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
432 EXPECT_TRUE(PolicyBundle().Equals(manager_->policies()));
433 Mock::VerifyAndClearExpectations(&observer_);
436 TEST_F(UserCloudPolicyManagerChromeOSTest, BlockingFetchRegisterError) {
437 // Tests the initialization of a manager whose Profile is waiting for the
438 // initial fetch, when the device management registration fails.
439 ASSERT_NO_FATAL_FAILURE(CreateManager(true, 1000));
441 // Initialize the CloudPolicyService without any stored data.
442 EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete());
443 store_->NotifyStoreError();
444 EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete());
445 EXPECT_FALSE(manager_->core()->client()->is_registered());
447 // This starts the OAuth2 policy token fetcher using the signin Profile.
448 // The manager will then issue the registration request.
449 MockDeviceManagementJob* register_request = IssueOAuthToken(false);
450 ASSERT_TRUE(register_request);
452 // Now make it fail.
453 EXPECT_FALSE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
454 EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));
455 register_request->SendResponse(DM_STATUS_TEMPORARY_UNAVAILABLE,
456 em::DeviceManagementResponse());
457 EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
458 EXPECT_TRUE(PolicyBundle().Equals(manager_->policies()));
459 Mock::VerifyAndClearExpectations(&observer_);
462 TEST_F(UserCloudPolicyManagerChromeOSTest, BlockingFetchPolicyFetchError) {
463 // Tests the initialization of a manager whose Profile is waiting for the
464 // initial fetch, when the policy fetch request fails.
465 ASSERT_NO_FATAL_FAILURE(CreateManager(true, 1000));
467 // Initialize the CloudPolicyService without any stored data.
468 EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete());
469 store_->NotifyStoreLoaded();
470 EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete());
471 EXPECT_FALSE(manager_->core()->client()->is_registered());
473 // This starts the OAuth2 policy token fetcher using the signin Profile.
474 // The manager will then issue the registration request.
475 MockDeviceManagementJob* register_request = IssueOAuthToken(false);
476 ASSERT_TRUE(register_request);
478 // Reply with a valid registration response. This triggers the initial policy
479 // fetch.
480 MockDeviceManagementJob* policy_request = NULL;
481 EXPECT_CALL(device_management_service_,
482 CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH, _))
483 .WillOnce(device_management_service_.CreateAsyncJob(&policy_request));
484 register_request->SendResponse(DM_STATUS_SUCCESS, register_blob_);
485 Mock::VerifyAndClearExpectations(&device_management_service_);
486 ASSERT_TRUE(policy_request);
487 EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete());
488 EXPECT_TRUE(manager_->core()->client()->is_registered());
490 // Make the policy fetch fail. The observer gets 2 notifications: one from the
491 // RefreshPolicies callback, and another from the OnClientError callback.
492 // A single notification suffices for this edge case, but this behavior is
493 // also correct and makes the implementation simpler.
494 EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get())).Times(AtLeast(1));
495 EXPECT_FALSE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
496 policy_request->SendResponse(DM_STATUS_TEMPORARY_UNAVAILABLE,
497 em::DeviceManagementResponse());
498 Mock::VerifyAndClearExpectations(&observer_);
499 EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
500 EXPECT_TRUE(PolicyBundle().Equals(manager_->policies()));
503 TEST_F(UserCloudPolicyManagerChromeOSTest, BlockingFetchTimeout) {
504 // The blocking fetch should be abandoned after the timeout.
505 ASSERT_NO_FATAL_FAILURE(CreateManager(true, 0));
507 // Initialize the CloudPolicyService without any stored data.
508 EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete());
509 store_->NotifyStoreLoaded();
510 EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete());
511 EXPECT_FALSE(manager_->core()->client()->is_registered());
513 // Running the message loop should trigger the timeout.
514 EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get())).Times(AtLeast(1));
515 EXPECT_FALSE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
516 base::RunLoop().RunUntilIdle();
517 Mock::VerifyAndClearExpectations(&observer_);
518 EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
519 EXPECT_TRUE(PolicyBundle().Equals(manager_->policies()));
523 TEST_F(UserCloudPolicyManagerChromeOSTest, NonBlockingFirstFetch) {
524 // Tests the first policy fetch request by a Profile that isn't managed.
525 ASSERT_NO_FATAL_FAILURE(CreateManager(false, 1000));
527 // Initialize the CloudPolicyService without any stored data. Since the
528 // manager is not waiting for the initial fetch, it will become initialized
529 // once the store is ready.
530 EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete());
531 EXPECT_FALSE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
532 EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));
533 store_->NotifyStoreLoaded();
534 Mock::VerifyAndClearExpectations(&observer_);
535 EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete());
536 EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
537 EXPECT_FALSE(manager_->core()->client()->is_registered());
539 // The manager is waiting for the refresh token, and hasn't started any
540 // fetchers.
541 EXPECT_FALSE(test_url_fetcher_factory_.GetFetcherByID(0));
543 // Set a fake refresh token at the OAuth2TokenService.
544 FakeProfileOAuth2TokenService* token_service =
545 static_cast<FakeProfileOAuth2TokenService*>(
546 ProfileOAuth2TokenServiceFactory::GetForProfile(profile_));
547 ASSERT_TRUE(token_service);
548 SigninManagerBase* signin_manager =
549 SigninManagerFactory::GetForProfile(profile_);
550 ASSERT_TRUE(signin_manager);
551 const std::string& account_id = signin_manager->GetAuthenticatedAccountId();
552 EXPECT_FALSE(token_service->RefreshTokenIsAvailable(account_id));
553 token_service->UpdateCredentials(account_id, "refresh_token");
554 EXPECT_TRUE(token_service->RefreshTokenIsAvailable(account_id));
556 // That should have notified the manager, which now issues the request for the
557 // policy oauth token.
558 MockDeviceManagementJob* register_request = IssueOAuthToken(true);
559 ASSERT_TRUE(register_request);
560 register_request->SendResponse(DM_STATUS_SUCCESS, register_blob_);
562 // The refresh scheduler takes care of the initial fetch for unmanaged users.
563 // Running the task runner issues the initial fetch.
564 FetchPolicy(
565 base::Bind(&base::TestSimpleTaskRunner::RunUntilIdle, task_runner_));
568 TEST_F(UserCloudPolicyManagerChromeOSTest, NonBlockingRefreshFetch) {
569 // Tests a non-blocking initial policy fetch for a Profile that already has
570 // a cached DMToken.
571 ASSERT_NO_FATAL_FAILURE(CreateManager(false, 1000));
573 // Set the initially cached data and initialize the CloudPolicyService.
574 // The initial policy fetch is issued using the cached DMToken.
575 EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete());
576 EXPECT_FALSE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
577 EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));
578 store_->policy_.reset(new em::PolicyData(policy_data_));
579 store_->NotifyStoreLoaded();
580 Mock::VerifyAndClearExpectations(&observer_);
581 EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete());
582 EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
583 EXPECT_TRUE(manager_->core()->client()->is_registered());
585 // The refresh scheduler takes care of the initial fetch for unmanaged users.
586 // Running the task runner issues the initial fetch.
587 FetchPolicy(
588 base::Bind(&base::TestSimpleTaskRunner::RunUntilIdle, task_runner_));
591 } // namespace policy