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 "base/file_util.h"
6 #include "base/memory/scoped_ptr.h"
7 #include "base/prefs/pref_service.h"
8 #include "chrome/browser/chrome_notification_types.h"
9 #include "chrome/browser/signin/fake_signin_manager.h"
10 #include "chrome/browser/signin/profile_oauth2_token_service.h"
11 #include "chrome/browser/signin/profile_oauth2_token_service_factory.h"
12 #include "chrome/browser/signin/signin_manager.h"
13 #include "chrome/browser/signin/signin_manager_factory.h"
14 #include "chrome/browser/sync/fake_oauth2_token_service_for_sync.h"
15 #include "chrome/browser/sync/glue/data_type_manager.h"
16 #include "chrome/browser/sync/glue/data_type_manager_mock.h"
17 #include "chrome/browser/sync/glue/sync_backend_host_mock.h"
18 #include "chrome/browser/sync/profile_sync_components_factory_mock.h"
19 #include "chrome/browser/sync/profile_sync_service_factory.h"
20 #include "chrome/browser/sync/profile_sync_test_util.h"
21 #include "chrome/browser/sync/sync_prefs.h"
22 #include "chrome/common/pref_names.h"
23 #include "chrome/test/base/testing_profile.h"
24 #include "content/public/browser/notification_service.h"
25 #include "content/public/browser/notification_source.h"
26 #include "content/public/test/test_browser_thread_bundle.h"
27 #include "content/public/test/test_utils.h"
28 #include "google_apis/gaia/gaia_auth_consumer.h"
29 #include "google_apis/gaia/gaia_constants.h"
30 #include "google_apis/gaia/oauth2_token_service.h"
31 #include "testing/gmock/include/gmock/gmock.h"
32 #include "testing/gtest/include/gtest/gtest.h"
34 using browser_sync::DataTypeManager
;
35 using browser_sync::DataTypeManagerMock
;
36 using browser_sync::SyncBackendHostMock
;
37 using content::BrowserThread
;
39 using testing::AnyNumber
;
41 using testing::InvokeArgument
;
43 using testing::Return
;
45 ACTION_P(InvokeOnConfigureStart
, pss
) {
46 ProfileSyncService
* service
=
47 static_cast<ProfileSyncService
*>(pss
);
48 service
->OnConfigureStart();
51 ACTION_P2(InvokeOnConfigureDone
, pss
, result
) {
52 ProfileSyncService
* service
=
53 static_cast<ProfileSyncService
*>(pss
);
54 DataTypeManager::ConfigureResult configure_result
=
55 static_cast<DataTypeManager::ConfigureResult
>(result
);
56 service
->OnConfigureDone(configure_result
);
59 class ProfileSyncServiceStartupTest
: public testing::Test
{
61 ProfileSyncServiceStartupTest()
62 : thread_bundle_(content::TestBrowserThreadBundle::REAL_DB_THREAD
|
63 content::TestBrowserThreadBundle::REAL_FILE_THREAD
|
64 content::TestBrowserThreadBundle::REAL_IO_THREAD
),
67 virtual ~ProfileSyncServiceStartupTest() {
70 virtual void SetUp() {
71 profile_
= CreateProfile();
74 virtual scoped_ptr
<TestingProfile
> CreateProfile() {
75 TestingProfile::Builder builder
;
76 #if defined(OS_CHROMEOS)
77 builder
.AddTestingFactory(SigninManagerFactory::GetInstance(),
78 FakeSigninManagerBase::Build
);
80 builder
.AddTestingFactory(SigninManagerFactory::GetInstance(),
81 FakeSigninManager::Build
);
83 builder
.AddTestingFactory(ProfileOAuth2TokenServiceFactory::GetInstance(),
84 FakeOAuth2TokenServiceForSync::BuildTokenService
);
85 builder
.AddTestingFactory(ProfileSyncServiceFactory::GetInstance(),
87 return builder
.Build();
90 virtual void TearDown() {
91 sync_
->RemoveObserver(&observer_
);
95 static BrowserContextKeyedService
* BuildService(
96 content::BrowserContext
* browser_context
) {
97 Profile
* profile
= static_cast<Profile
*>(browser_context
);
98 return new ProfileSyncService(
99 new ProfileSyncComponentsFactoryMock(),
101 SigninManagerFactory::GetForProfile(profile
),
102 ProfileOAuth2TokenServiceFactory::GetForProfile(profile
),
103 ProfileSyncService::MANUAL_START
);
106 void CreateSyncService() {
107 sync_
= static_cast<ProfileSyncService
*>(
108 ProfileSyncServiceFactory::GetForProfile(profile_
.get()));
109 sync_
->AddObserver(&observer_
);
112 void IssueTestTokens() {
113 ProfileOAuth2TokenServiceFactory::GetForProfile(profile_
.get())
114 ->UpdateCredentials("test_user@gmail.com", "oauth2_login_token");
117 ProfileSyncComponentsFactoryMock
* components_factory_mock() {
118 return static_cast<ProfileSyncComponentsFactoryMock
*>(sync_
->factory());
122 DataTypeManagerMock
* SetUpDataTypeManager() {
123 DataTypeManagerMock
* data_type_manager
= new DataTypeManagerMock();
124 EXPECT_CALL(*components_factory_mock(),
125 CreateDataTypeManager(_
, _
, _
, _
, _
, _
)).
126 WillOnce(Return(data_type_manager
));
127 return data_type_manager
;
130 browser_sync::SyncBackendHostMock
* SetUpSyncBackendHost() {
131 browser_sync::SyncBackendHostMock
* sync_backend_host
=
132 new browser_sync::SyncBackendHostMock();
133 EXPECT_CALL(*components_factory_mock(),
134 CreateSyncBackendHost(_
, _
, _
)).
135 WillOnce(Return(sync_backend_host
));
136 return sync_backend_host
;
139 content::TestBrowserThreadBundle thread_bundle_
;
140 scoped_ptr
<TestingProfile
> profile_
;
141 ProfileSyncService
* sync_
;
142 ProfileSyncServiceObserverMock observer_
;
143 ProfileSyncComponentsFactoryMock
* mock_components_factory_
;
146 class ProfileSyncServiceStartupCrosTest
: public ProfileSyncServiceStartupTest
{
148 virtual void SetUp() {
149 ProfileSyncServiceStartupTest::SetUp();
150 sync_
= static_cast<ProfileSyncService
*>(
151 ProfileSyncServiceFactory::GetInstance()->SetTestingFactoryAndUse(
152 profile_
.get(), BuildCrosService
));
153 sync_
->AddObserver(&observer_
);
156 static BrowserContextKeyedService
* BuildCrosService(
157 content::BrowserContext
* context
) {
158 Profile
* profile
= static_cast<Profile
*>(context
);
159 SigninManagerBase
* signin
=
160 SigninManagerFactory::GetForProfile(profile
);
161 profile
->GetPrefs()->SetString(prefs::kGoogleServicesUsername
,
162 "test_user@gmail.com");
163 ProfileOAuth2TokenService
* oauth2_token_service
=
164 ProfileOAuth2TokenServiceFactory::GetForProfile(profile
);
165 signin
->Initialize(profile
, NULL
);
166 EXPECT_FALSE(signin
->GetAuthenticatedUsername().empty());
167 return new ProfileSyncService(
168 new ProfileSyncComponentsFactoryMock(),
171 oauth2_token_service
,
172 ProfileSyncService::AUTO_START
);
176 TEST_F(ProfileSyncServiceStartupTest
, StartFirstTime
) {
177 // We've never completed startup.
178 profile_
->GetPrefs()->ClearPref(prefs::kSyncHasSetupCompleted
);
179 SigninManagerFactory::GetForProfile(
180 profile_
.get())->Initialize(profile_
.get(), NULL
);
182 SetUpSyncBackendHost();
183 DataTypeManagerMock
* data_type_manager
= SetUpDataTypeManager();
184 EXPECT_CALL(*data_type_manager
, Configure(_
, _
)).Times(0);
186 // Should not actually start, rather just clean things up and wait
188 EXPECT_CALL(observer_
, OnStateChanged()).Times(AnyNumber());
191 // Preferences should be back to defaults.
192 EXPECT_EQ(0, profile_
->GetPrefs()->GetInt64(prefs::kSyncLastSyncedTime
));
193 EXPECT_FALSE(profile_
->GetPrefs()->GetBoolean(prefs::kSyncHasSetupCompleted
));
194 Mock::VerifyAndClearExpectations(data_type_manager
);
196 // Then start things up.
197 EXPECT_CALL(*data_type_manager
, Configure(_
, _
)).Times(1);
198 EXPECT_CALL(*data_type_manager
, state()).
199 WillOnce(Return(DataTypeManager::CONFIGURED
)).
200 WillOnce(Return(DataTypeManager::CONFIGURED
));
201 EXPECT_CALL(*data_type_manager
, Stop()).Times(1);
202 EXPECT_CALL(observer_
, OnStateChanged()).Times(AnyNumber());
204 sync_
->SetSetupInProgress(true);
206 // Simulate successful signin as test_user.
207 profile_
->GetPrefs()->SetString(prefs::kGoogleServicesUsername
,
208 "test_user@gmail.com");
209 sync_
->signin()->SetAuthenticatedUsername("test_user@gmail.com");
210 GoogleServiceSigninSuccessDetails
details("test_user@gmail.com", "");
211 content::NotificationService::current()->Notify(
212 chrome::NOTIFICATION_GOOGLE_SIGNIN_SUCCESSFUL
,
213 content::Source
<Profile
>(profile_
.get()),
214 content::Details
<const GoogleServiceSigninSuccessDetails
>(&details
));
216 // Create some tokens in the token service.
219 // Simulate the UI telling sync it has finished setting up.
220 sync_
->SetSetupInProgress(false);
221 EXPECT_TRUE(sync_
->ShouldPushChanges());
224 // TODO(pavely): Reenable test once android is switched to oauth2.
225 TEST_F(ProfileSyncServiceStartupTest
, DISABLED_StartNoCredentials
) {
226 // We've never completed startup.
227 profile_
->GetPrefs()->ClearPref(prefs::kSyncHasSetupCompleted
);
228 SigninManagerFactory::GetForProfile(
229 profile_
.get())->Initialize(profile_
.get(), NULL
);
232 // Should not actually start, rather just clean things up and wait
234 EXPECT_CALL(*components_factory_mock(),
235 CreateDataTypeManager(_
, _
, _
, _
, _
, _
)).Times(0);
236 EXPECT_CALL(observer_
, OnStateChanged()).Times(AnyNumber());
239 // Preferences should be back to defaults.
240 EXPECT_EQ(0, profile_
->GetPrefs()->GetInt64(prefs::kSyncLastSyncedTime
));
241 EXPECT_FALSE(profile_
->GetPrefs()->GetBoolean(prefs::kSyncHasSetupCompleted
));
243 // Then start things up.
244 sync_
->SetSetupInProgress(true);
246 // Simulate successful signin as test_user.
247 profile_
->GetPrefs()->SetString(prefs::kGoogleServicesUsername
,
248 "test_user@gmail.com");
249 sync_
->signin()->SetAuthenticatedUsername("test_user@gmail.com");
250 GoogleServiceSigninSuccessDetails
details("test_user@gmail.com", "");
251 content::NotificationService::current()->Notify(
252 chrome::NOTIFICATION_GOOGLE_SIGNIN_SUCCESSFUL
,
253 content::Source
<Profile
>(profile_
.get()),
254 content::Details
<const GoogleServiceSigninSuccessDetails
>(&details
));
255 ProfileOAuth2TokenService
* token_service
=
256 ProfileOAuth2TokenServiceFactory::GetForProfile(profile_
.get());
257 token_service
->LoadCredentials();
259 sync_
->SetSetupInProgress(false);
260 // ProfileSyncService should try to start by requesting access token.
261 // This request should fail as login token was not issued.
262 EXPECT_FALSE(sync_
->ShouldPushChanges());
263 EXPECT_EQ(GoogleServiceAuthError::USER_NOT_SIGNED_UP
,
264 sync_
->GetAuthError().state());
267 // TODO(pavely): Reenable test once android is switched to oauth2.
268 TEST_F(ProfileSyncServiceStartupTest
, DISABLED_StartInvalidCredentials
) {
269 profile_
->GetPrefs()->SetString(prefs::kGoogleServicesUsername
,
270 "test_user@gmail.com");
271 SigninManagerFactory::GetForProfile(
272 profile_
.get())->Initialize(profile_
.get(), NULL
);
274 SyncBackendHostMock
* mock_sbh
= SetUpSyncBackendHost();
276 // Tell the backend to stall while downloading control types (simulating an
278 mock_sbh
->set_fail_initial_download(true);
280 DataTypeManagerMock
* data_type_manager
= SetUpDataTypeManager();
281 EXPECT_CALL(*data_type_manager
, Configure(_
, _
)).Times(0);
283 EXPECT_CALL(observer_
, OnStateChanged()).Times(AnyNumber());
285 EXPECT_FALSE(sync_
->sync_initialized());
286 Mock::VerifyAndClearExpectations(data_type_manager
);
288 // Update the credentials, unstalling the backend.
289 EXPECT_CALL(*data_type_manager
, Configure(_
, _
));
290 EXPECT_CALL(*data_type_manager
, state()).
291 WillRepeatedly(Return(DataTypeManager::CONFIGURED
));
292 EXPECT_CALL(*data_type_manager
, Stop()).Times(1);
293 EXPECT_CALL(observer_
, OnStateChanged()).Times(AnyNumber());
294 sync_
->SetSetupInProgress(true);
296 // Simulate successful signin.
297 GoogleServiceSigninSuccessDetails
details("test_user@gmail.com",
299 content::NotificationService::current()->Notify(
300 chrome::NOTIFICATION_GOOGLE_SIGNIN_SUCCESSFUL
,
301 content::Source
<Profile
>(profile_
.get()),
302 content::Details
<const GoogleServiceSigninSuccessDetails
>(&details
));
304 sync_
->SetSetupInProgress(false);
306 // Verify we successfully finish startup and configuration.
307 EXPECT_TRUE(sync_
->ShouldPushChanges());
310 TEST_F(ProfileSyncServiceStartupCrosTest
, StartCrosNoCredentials
) {
311 EXPECT_CALL(*components_factory_mock(),
312 CreateDataTypeManager(_
, _
, _
, _
, _
, _
)).Times(0);
313 EXPECT_CALL(*components_factory_mock(),
314 CreateSyncBackendHost(_
, _
, _
)).Times(0);
315 profile_
->GetPrefs()->ClearPref(prefs::kSyncHasSetupCompleted
);
316 EXPECT_CALL(observer_
, OnStateChanged()).Times(AnyNumber());
317 ProfileOAuth2TokenService
* token_service
=
318 ProfileOAuth2TokenServiceFactory::GetForProfile(profile_
.get());
321 // Sync should not start because there are no tokens yet.
322 EXPECT_FALSE(sync_
->ShouldPushChanges());
323 token_service
->LoadCredentials();
324 sync_
->SetSetupInProgress(false);
326 // Sync should not start because there are still no tokens.
327 EXPECT_FALSE(sync_
->ShouldPushChanges());
330 TEST_F(ProfileSyncServiceStartupCrosTest
, StartFirstTime
) {
331 SetUpSyncBackendHost();
332 DataTypeManagerMock
* data_type_manager
= SetUpDataTypeManager();
333 profile_
->GetPrefs()->ClearPref(prefs::kSyncHasSetupCompleted
);
334 EXPECT_CALL(*data_type_manager
, Configure(_
, _
));
335 EXPECT_CALL(*data_type_manager
, state()).
336 WillRepeatedly(Return(DataTypeManager::CONFIGURED
));
337 EXPECT_CALL(*data_type_manager
, Stop()).Times(1);
338 EXPECT_CALL(observer_
, OnStateChanged()).Times(AnyNumber());
342 EXPECT_TRUE(sync_
->ShouldPushChanges());
345 TEST_F(ProfileSyncServiceStartupTest
, StartNormal
) {
346 // Pre load the tokens
347 profile_
->GetPrefs()->SetString(prefs::kGoogleServicesUsername
,
348 "test_user@gmail.com");
349 SigninManagerFactory::GetForProfile(profile_
.get())->Initialize(
350 profile_
.get(), NULL
);
352 sync_
->SetSyncSetupCompleted();
353 SetUpSyncBackendHost();
354 DataTypeManagerMock
* data_type_manager
= SetUpDataTypeManager();
355 EXPECT_CALL(*data_type_manager
, Configure(_
, _
));
356 EXPECT_CALL(*data_type_manager
, state()).
357 WillRepeatedly(Return(DataTypeManager::CONFIGURED
));
358 EXPECT_CALL(*data_type_manager
, Stop()).Times(1);
359 EXPECT_CALL(observer_
, OnStateChanged()).Times(AnyNumber());
366 // Test that we can recover from a case where a bug in the code resulted in
367 // OnUserChoseDatatypes not being properly called and datatype preferences
368 // therefore being left unset.
369 TEST_F(ProfileSyncServiceStartupTest
, StartRecoverDatatypePrefs
) {
370 // Clear the datatype preference fields (simulating bug 154940).
371 profile_
->GetPrefs()->ClearPref(prefs::kSyncKeepEverythingSynced
);
372 syncer::ModelTypeSet user_types
= syncer::UserTypes();
373 for (syncer::ModelTypeSet::Iterator iter
= user_types
.First();
374 iter
.Good(); iter
.Inc()) {
375 profile_
->GetPrefs()->ClearPref(
376 browser_sync::SyncPrefs::GetPrefNameForDataType(iter
.Get()));
379 // Pre load the tokens
380 profile_
->GetPrefs()->SetString(prefs::kGoogleServicesUsername
,
381 "test_user@gmail.com");
382 SigninManagerFactory::GetForProfile(profile_
.get())->Initialize(
383 profile_
.get(), NULL
);
385 sync_
->SetSyncSetupCompleted();
386 SetUpSyncBackendHost();
387 DataTypeManagerMock
* data_type_manager
= SetUpDataTypeManager();
388 EXPECT_CALL(*data_type_manager
, Configure(_
, _
));
389 EXPECT_CALL(*data_type_manager
, state()).
390 WillRepeatedly(Return(DataTypeManager::CONFIGURED
));
391 EXPECT_CALL(*data_type_manager
, Stop()).Times(1);
392 EXPECT_CALL(observer_
, OnStateChanged()).Times(AnyNumber());
397 EXPECT_TRUE(profile_
->GetPrefs()->GetBoolean(
398 prefs::kSyncKeepEverythingSynced
));
401 // Verify that the recovery of datatype preferences doesn't overwrite a valid
402 // case where only bookmarks are enabled.
403 TEST_F(ProfileSyncServiceStartupTest
, StartDontRecoverDatatypePrefs
) {
404 // Explicitly set Keep Everything Synced to false and have only bookmarks
406 profile_
->GetPrefs()->SetBoolean(prefs::kSyncKeepEverythingSynced
, false);
408 // Pre load the tokens
409 profile_
->GetPrefs()->SetString(prefs::kGoogleServicesUsername
,
410 "test_user@gmail.com");
411 SigninManagerFactory::GetForProfile(profile_
.get())->Initialize(
412 profile_
.get(), NULL
);
414 sync_
->SetSyncSetupCompleted();
415 SetUpSyncBackendHost();
416 DataTypeManagerMock
* data_type_manager
= SetUpDataTypeManager();
417 EXPECT_CALL(*data_type_manager
, Configure(_
, _
));
418 EXPECT_CALL(*data_type_manager
, state()).
419 WillRepeatedly(Return(DataTypeManager::CONFIGURED
));
420 EXPECT_CALL(*data_type_manager
, Stop()).Times(1);
421 EXPECT_CALL(observer_
, OnStateChanged()).Times(AnyNumber());
425 EXPECT_FALSE(profile_
->GetPrefs()->GetBoolean(
426 prefs::kSyncKeepEverythingSynced
));
429 TEST_F(ProfileSyncServiceStartupTest
, ManagedStartup
) {
430 // Service should not be started by Initialize() since it's managed.
431 profile_
->GetPrefs()->SetString(prefs::kGoogleServicesUsername
,
432 "test_user@gmail.com");
433 SigninManagerFactory::GetForProfile(profile_
.get())->Initialize(
434 profile_
.get(), NULL
);
437 // Disable sync through policy.
438 profile_
->GetPrefs()->SetBoolean(prefs::kSyncManaged
, true);
439 EXPECT_CALL(*components_factory_mock(),
440 CreateDataTypeManager(_
, _
, _
, _
, _
, _
)).Times(0);
441 EXPECT_CALL(observer_
, OnStateChanged()).Times(AnyNumber());
446 TEST_F(ProfileSyncServiceStartupTest
, SwitchManaged
) {
447 profile_
->GetPrefs()->SetString(prefs::kGoogleServicesUsername
,
448 "test_user@gmail.com");
449 SigninManagerFactory::GetForProfile(profile_
.get())->Initialize(
450 profile_
.get(), NULL
);
452 sync_
->SetSyncSetupCompleted();
453 SetUpSyncBackendHost();
454 DataTypeManagerMock
* data_type_manager
= SetUpDataTypeManager();
455 EXPECT_CALL(*data_type_manager
, Configure(_
, _
));
456 EXPECT_CALL(observer_
, OnStateChanged()).Times(AnyNumber());
460 // The service should stop when switching to managed mode.
461 Mock::VerifyAndClearExpectations(data_type_manager
);
462 EXPECT_CALL(*data_type_manager
, state()).
463 WillOnce(Return(DataTypeManager::CONFIGURED
));
464 EXPECT_CALL(*data_type_manager
, Stop()).Times(1);
465 EXPECT_CALL(observer_
, OnStateChanged()).Times(AnyNumber());
466 profile_
->GetPrefs()->SetBoolean(prefs::kSyncManaged
, true);
468 // When switching back to unmanaged, the state should change, but the service
469 // should not start up automatically (kSyncSetupCompleted will be false).
470 Mock::VerifyAndClearExpectations(data_type_manager
);
471 EXPECT_CALL(*components_factory_mock(),
472 CreateDataTypeManager(_
, _
, _
, _
, _
, _
)).Times(0);
473 EXPECT_CALL(observer_
, OnStateChanged()).Times(AnyNumber());
474 profile_
->GetPrefs()->ClearPref(prefs::kSyncManaged
);
477 TEST_F(ProfileSyncServiceStartupTest
, StartFailure
) {
478 profile_
->GetPrefs()->SetString(prefs::kGoogleServicesUsername
,
479 "test_user@gmail.com");
480 SigninManagerFactory::GetForProfile(profile_
.get())->Initialize(
481 profile_
.get(), NULL
);
483 sync_
->SetSyncSetupCompleted();
484 SetUpSyncBackendHost();
485 DataTypeManagerMock
* data_type_manager
= SetUpDataTypeManager();
486 DataTypeManager::ConfigureStatus status
= DataTypeManager::ABORTED
;
487 syncer::SyncError
error(
489 syncer::SyncError::DATATYPE_ERROR
,
490 "Association failed.",
492 std::map
<syncer::ModelType
, syncer::SyncError
> errors
;
493 errors
[syncer::BOOKMARKS
] = error
;
494 DataTypeManager::ConfigureResult
result(
496 syncer::ModelTypeSet(),
498 syncer::ModelTypeSet(),
499 syncer::ModelTypeSet());
500 EXPECT_CALL(*data_type_manager
, Configure(_
, _
)).
502 DoAll(InvokeOnConfigureStart(sync_
),
503 InvokeOnConfigureDone(sync_
, result
)));
504 EXPECT_CALL(*data_type_manager
, state()).
505 WillOnce(Return(DataTypeManager::STOPPED
));
506 EXPECT_CALL(observer_
, OnStateChanged()).Times(AnyNumber());
509 EXPECT_TRUE(sync_
->HasUnrecoverableError());
512 TEST_F(ProfileSyncServiceStartupTest
, StartDownloadFailed
) {
513 // Pre load the tokens
514 profile_
->GetPrefs()->SetString(prefs::kGoogleServicesUsername
,
515 "test_user@gmail.com");
516 SigninManagerFactory::GetForProfile(profile_
.get())->Initialize(
517 profile_
.get(), NULL
);
519 SyncBackendHostMock
* mock_sbh
= SetUpSyncBackendHost();
520 mock_sbh
->set_fail_initial_download(true);
522 profile_
->GetPrefs()->ClearPref(prefs::kSyncHasSetupCompleted
);
524 EXPECT_CALL(observer_
, OnStateChanged()).Times(AnyNumber());
527 sync_
->SetSetupInProgress(true);
529 sync_
->SetSetupInProgress(false);
530 EXPECT_FALSE(sync_
->sync_initialized());