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