ozone: evdev: Sync caps lock LED state to evdev
[chromium-blink-merge.git] / chrome / browser / chromeos / policy / user_cloud_policy_manager_chromeos_unittest.cc
blobd2699d4d78811af2536ec57aad1ac1b05c94d0e2
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 expected_bundle_.Get(PolicyNamespace(POLICY_DOMAIN_CHROME, std::string()))
124 .CopyFrom(policy_map_);
126 // Create fake policy blobs to deliver to the client.
127 em::DeviceRegisterResponse* register_response =
128 register_blob_.mutable_register_response();
129 register_response->set_device_management_token("dmtoken123");
131 em::CloudPolicySettings policy_proto;
132 policy_proto.mutable_homepagelocation()->set_value("http://chromium.org");
133 ASSERT_TRUE(
134 policy_proto.SerializeToString(policy_data_.mutable_policy_value()));
135 policy_data_.set_policy_type(dm_protocol::kChromeUserPolicyType);
136 policy_data_.set_request_token("dmtoken123");
137 policy_data_.set_device_id("id987");
138 em::PolicyFetchResponse* policy_response =
139 policy_blob_.mutable_policy_response()->add_response();
140 ASSERT_TRUE(policy_data_.SerializeToString(
141 policy_response->mutable_policy_data()));
143 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
144 .Times(AnyNumber());
147 void TearDown() override {
148 if (token_forwarder_)
149 token_forwarder_->Shutdown();
150 if (manager_) {
151 manager_->RemoveObserver(&observer_);
152 manager_->Shutdown();
154 signin_profile_ = NULL;
155 profile_ = NULL;
156 profile_manager_->DeleteTestingProfile(chrome::kInitialProfile);
159 void CreateManager(bool wait_for_fetch, int fetch_timeout) {
160 store_ = new MockCloudPolicyStore();
161 external_data_manager_ = new MockCloudExternalDataManager;
162 external_data_manager_->SetPolicyStore(store_);
163 EXPECT_CALL(*store_, Load());
164 manager_.reset(new UserCloudPolicyManagerChromeOS(
165 scoped_ptr<CloudPolicyStore>(store_),
166 scoped_ptr<CloudExternalDataManager>(external_data_manager_),
167 base::FilePath(),
168 wait_for_fetch,
169 base::TimeDelta::FromSeconds(fetch_timeout),
170 task_runner_,
171 task_runner_,
172 task_runner_));
173 manager_->Init(&schema_registry_);
174 manager_->AddObserver(&observer_);
175 manager_->Connect(&prefs_, &device_management_service_, NULL,
176 USER_AFFILIATION_NONE);
177 Mock::VerifyAndClearExpectations(store_);
178 EXPECT_FALSE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
179 EXPECT_FALSE(manager_->core()->service()->IsInitializationComplete());
181 if (!wait_for_fetch) {
182 // Create the UserCloudPolicyTokenForwarder, which fetches the access
183 // token using the OAuth2PolicyFetcher and forwards it to the
184 // UserCloudPolicyManagerChromeOS. This service is automatically created
185 // for regular Profiles but not for testing Profiles.
186 ProfileOAuth2TokenService* token_service =
187 ProfileOAuth2TokenServiceFactory::GetForProfile(profile_);
188 ASSERT_TRUE(token_service);
189 SigninManagerBase* signin_manager =
190 SigninManagerFactory::GetForProfile(profile_);
191 ASSERT_TRUE(signin_manager);
192 token_forwarder_.reset(
193 new UserCloudPolicyTokenForwarder(manager_.get(), token_service,
194 signin_manager));
198 // Expects a pending URLFetcher for the |expected_url|, and returns it with
199 // prepared to deliver a response to its delegate.
200 net::TestURLFetcher* PrepareOAuthFetcher(const GURL& expected_url) {
201 net::TestURLFetcher* fetcher = test_url_fetcher_factory_.GetFetcherByID(0);
202 EXPECT_TRUE(fetcher);
203 if (!fetcher)
204 return NULL;
205 EXPECT_TRUE(fetcher->delegate());
206 EXPECT_TRUE(StartsWithASCII(fetcher->GetOriginalURL().spec(),
207 expected_url.spec(),
208 true));
209 fetcher->set_url(fetcher->GetOriginalURL());
210 fetcher->set_response_code(200);
211 fetcher->set_status(net::URLRequestStatus());
212 return fetcher;
215 // Issues the OAuth2 tokens and returns the device management register job
216 // if the flow succeeded.
217 MockDeviceManagementJob* IssueOAuthToken(bool has_request_token) {
218 EXPECT_FALSE(manager_->core()->client()->is_registered());
220 // Issuing this token triggers the callback of the OAuth2PolicyFetcher,
221 // which triggers the registration request.
222 MockDeviceManagementJob* register_request = NULL;
223 EXPECT_CALL(device_management_service_,
224 CreateJob(DeviceManagementRequestJob::TYPE_REGISTRATION, _))
225 .WillOnce(device_management_service_.CreateAsyncJob(&register_request));
227 if (!has_request_token) {
228 GaiaUrls* gaia_urls = GaiaUrls::GetInstance();
229 net::TestURLFetcher* fetcher = NULL;
231 // Issue the oauth_token cookie first.
232 fetcher = PrepareOAuthFetcher(gaia_urls->client_login_to_oauth2_url());
233 if (!fetcher)
234 return NULL;
235 net::ResponseCookies cookies;
236 cookies.push_back(kOAuthCodeCookie);
238 fetcher->set_cookies(cookies);
239 fetcher->delegate()->OnURLFetchComplete(fetcher);
241 // Issue the refresh token.
242 fetcher = PrepareOAuthFetcher(gaia_urls->oauth2_token_url());
243 if (!fetcher)
244 return NULL;
245 fetcher->SetResponseString(kOAuth2TokenPairData);
246 fetcher->delegate()->OnURLFetchComplete(fetcher);
248 // Issue the access token.
249 fetcher = PrepareOAuthFetcher(gaia_urls->oauth2_token_url());
250 if (!fetcher)
251 return NULL;
252 fetcher->SetResponseString(kOAuth2AccessTokenData);
253 fetcher->delegate()->OnURLFetchComplete(fetcher);
254 } else {
255 // Since the refresh token is available, OAuth2TokenService was used
256 // to request the access token and not UserCloudPolicyTokenForwarder.
257 // Issue the access token with the former.
258 FakeProfileOAuth2TokenService* token_service =
259 static_cast<FakeProfileOAuth2TokenService*>(
260 ProfileOAuth2TokenServiceFactory::GetForProfile(profile_));
261 EXPECT_TRUE(token_service);
262 OAuth2TokenService::ScopeSet scopes;
263 scopes.insert(GaiaConstants::kDeviceManagementServiceOAuth);
264 scopes.insert(GaiaConstants::kOAuthWrapBridgeUserInfoScope);
265 token_service->IssueTokenForScope(
266 scopes, "5678",
267 base::Time::Now() + base::TimeDelta::FromSeconds(3600));
270 EXPECT_TRUE(register_request);
271 EXPECT_FALSE(manager_->core()->client()->is_registered());
273 Mock::VerifyAndClearExpectations(&device_management_service_);
274 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
275 .Times(AnyNumber());
277 return register_request;
280 // Expects a policy fetch request to be issued after invoking |trigger_fetch|.
281 // This method replies to that fetch request and verifies that the manager
282 // handled the response.
283 void FetchPolicy(const base::Closure& trigger_fetch) {
284 MockDeviceManagementJob* policy_request = NULL;
285 EXPECT_CALL(device_management_service_,
286 CreateJob(DeviceManagementRequestJob::TYPE_POLICY_FETCH, _))
287 .WillOnce(device_management_service_.CreateAsyncJob(&policy_request));
288 trigger_fetch.Run();
289 ASSERT_TRUE(policy_request);
290 EXPECT_TRUE(manager_->core()->service()->IsInitializationComplete());
291 EXPECT_TRUE(manager_->core()->client()->is_registered());
293 Mock::VerifyAndClearExpectations(&device_management_service_);
294 EXPECT_CALL(device_management_service_, StartJob(_, _, _, _, _, _, _))
295 .Times(AnyNumber());
297 // Send the initial policy back. This completes the initialization flow.
298 EXPECT_CALL(*store_, Store(_));
299 policy_request->SendResponse(DM_STATUS_SUCCESS, policy_blob_);
300 Mock::VerifyAndClearExpectations(store_);
302 // Notifying that the store is has cached the fetched policy completes the
303 // process, and initializes the manager.
304 EXPECT_CALL(observer_, OnUpdatePolicy(manager_.get()));
305 store_->policy_map_.CopyFrom(policy_map_);
306 store_->NotifyStoreLoaded();
307 EXPECT_TRUE(manager_->IsInitializationComplete(POLICY_DOMAIN_CHROME));
308 Mock::VerifyAndClearExpectations(&observer_);
309 EXPECT_TRUE(manager_->policies().Equals(expected_bundle_));
312 // Required by the refresh scheduler that's created by the manager and
313 // for the cleanup of URLRequestContextGetter in the |signin_profile_|.
314 content::TestBrowserThreadBundle thread_bundle_;
316 // Convenience policy objects.
317 em::PolicyData policy_data_;
318 em::DeviceManagementResponse register_blob_;
319 em::DeviceManagementResponse policy_blob_;
320 PolicyMap policy_map_;
321 PolicyBundle expected_bundle_;
323 // Policy infrastructure.
324 net::TestURLFetcherFactory test_url_fetcher_factory_;
325 TestingPrefServiceSimple prefs_;
326 MockConfigurationPolicyObserver observer_;
327 MockDeviceManagementService device_management_service_;
328 MockCloudPolicyStore* store_; // Not owned.
329 MockCloudExternalDataManager* external_data_manager_; // Not owned.
330 scoped_refptr<base::TestSimpleTaskRunner> task_runner_;
331 SchemaRegistry schema_registry_;
332 scoped_ptr<UserCloudPolicyManagerChromeOS> manager_;
333 scoped_ptr<UserCloudPolicyTokenForwarder> token_forwarder_;
335 // Required by ProfileHelper to get the signin Profile context.
336 scoped_ptr<TestingProfileManager> profile_manager_;
337 TestingProfile* profile_;
338 TestingProfile* signin_profile_;
340 static const char kSigninProfile[];
342 private:
343 DISALLOW_COPY_AND_ASSIGN(UserCloudPolicyManagerChromeOSTest);
346 const char UserCloudPolicyManagerChromeOSTest::kSigninProfile[] =
347 "signin_profile";
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