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/basictypes.h"
6 #include "base/callback.h"
7 #include "base/command_line.h"
8 #include "base/compiler_specific.h"
9 #include "base/location.h"
10 #include "base/memory/scoped_ptr.h"
11 #include "base/run_loop.h"
12 #include "base/single_thread_task_runner.h"
13 #include "base/strings/string_number_conversions.h"
14 #include "base/strings/utf_string_conversions.h"
15 #include "base/thread_task_runner_handle.h"
16 #include "base/values.h"
17 #include "chrome/browser/invalidation/fake_invalidation_service.h"
18 #include "chrome/browser/invalidation/profile_invalidation_provider_factory.h"
19 #include "chrome/browser/signin/account_tracker_service_factory.h"
20 #include "chrome/browser/signin/fake_profile_oauth2_token_service_builder.h"
21 #include "chrome/browser/signin/profile_oauth2_token_service_factory.h"
22 #include "chrome/browser/signin/signin_manager_factory.h"
23 #include "chrome/browser/sync/glue/sync_backend_host_mock.h"
24 #include "chrome/browser/sync/profile_sync_components_factory_mock.h"
25 #include "chrome/browser/sync/profile_sync_service.h"
26 #include "chrome/common/chrome_switches.h"
27 #include "chrome/common/pref_names.h"
28 #include "chrome/grit/generated_resources.h"
29 #include "chrome/test/base/testing_browser_process.h"
30 #include "chrome/test/base/testing_profile.h"
31 #include "chrome/test/base/testing_profile_manager.h"
32 #include "components/invalidation/impl/profile_invalidation_provider.h"
33 #include "components/invalidation/public/invalidation_service.h"
34 #include "components/signin/core/browser/account_tracker_service.h"
35 #include "components/signin/core/browser/fake_profile_oauth2_token_service.h"
36 #include "components/signin/core/browser/signin_manager.h"
37 #include "components/signin/core/browser/signin_manager.h"
38 #include "components/sync_driver/data_type_manager.h"
39 #include "components/sync_driver/data_type_manager_observer.h"
40 #include "components/sync_driver/fake_data_type_controller.h"
41 #include "components/sync_driver/pref_names.h"
42 #include "components/sync_driver/signin_manager_wrapper.h"
43 #include "components/sync_driver/sync_driver_switches.h"
44 #include "components/sync_driver/sync_prefs.h"
45 #include "components/sync_driver/sync_service_observer.h"
46 #include "components/sync_driver/sync_util.h"
47 #include "components/syncable_prefs/testing_pref_service_syncable.h"
48 #include "components/version_info/version_info_values.h"
49 #include "content/public/test/test_browser_thread_bundle.h"
50 #include "google_apis/gaia/gaia_constants.h"
51 #include "testing/gmock/include/gmock/gmock.h"
52 #include "testing/gtest/include/gtest/gtest.h"
53 #include "ui/base/l10n/l10n_util.h"
59 namespace browser_sync
{
63 const char kGaiaId
[] = "12345";
64 const char kEmail
[] = "test_user@gmail.com";
66 class FakeDataTypeManager
: public sync_driver::DataTypeManager
{
68 typedef base::Callback
<void(syncer::ConfigureReason
)> ConfigureCalled
;
70 explicit FakeDataTypeManager(const ConfigureCalled
& configure_called
)
71 : configure_called_(configure_called
) {}
73 ~FakeDataTypeManager() override
{};
75 void Configure(syncer::ModelTypeSet desired_types
,
76 syncer::ConfigureReason reason
) override
{
77 DCHECK(!configure_called_
.is_null());
78 configure_called_
.Run(reason
);
81 void ReenableType(syncer::ModelType type
) override
{}
82 void ResetDataTypeErrors() override
{}
83 void PurgeForMigration(syncer::ModelTypeSet undesired_types
,
84 syncer::ConfigureReason reason
) override
{}
85 void Stop() override
{};
86 State
state() const override
{
87 return sync_driver::DataTypeManager::CONFIGURED
;
91 ConfigureCalled configure_called_
;
94 ACTION_P(ReturnNewDataTypeManager
, configure_called
) {
95 return new FakeDataTypeManager(configure_called
);
98 using testing::Return
;
99 using testing::StrictMock
;
102 class TestSyncServiceObserver
: public sync_driver::SyncServiceObserver
{
104 explicit TestSyncServiceObserver(ProfileSyncService
* service
)
105 : service_(service
), first_setup_in_progress_(false) {}
106 void OnStateChanged() override
{
107 first_setup_in_progress_
= service_
->IsFirstSetupInProgress();
109 bool first_setup_in_progress() const { return first_setup_in_progress_
; }
111 ProfileSyncService
* service_
;
112 bool first_setup_in_progress_
;
115 // A variant of the SyncBackendHostMock that won't automatically
116 // call back when asked to initialized. Allows us to test things
117 // that could happen while backend init is in progress.
118 class SyncBackendHostNoReturn
: public SyncBackendHostMock
{
120 sync_driver::SyncFrontend
* frontend
,
121 scoped_ptr
<base::Thread
> sync_thread
,
122 const scoped_refptr
<base::SingleThreadTaskRunner
>& db_thread
,
123 const scoped_refptr
<base::SingleThreadTaskRunner
>& file_thread
,
124 const syncer::WeakHandle
<syncer::JsEventHandler
>& event_handler
,
125 const GURL
& service_url
,
126 const std::string
& sync_user_agent
,
127 const syncer::SyncCredentials
& credentials
,
128 bool delete_sync_data_folder
,
129 scoped_ptr
<syncer::SyncManagerFactory
> sync_manager_factory
,
130 const syncer::WeakHandle
<syncer::UnrecoverableErrorHandler
>&
131 unrecoverable_error_handler
,
132 const base::Closure
& report_unrecoverable_error_function
,
133 syncer::NetworkResources
* network_resources
,
134 scoped_ptr
<syncer::SyncEncryptionHandler::NigoriState
> saved_nigori_state
)
138 class SyncBackendHostMockCollectDeleteDirParam
: public SyncBackendHostMock
{
140 explicit SyncBackendHostMockCollectDeleteDirParam(
141 std::vector
<bool>* delete_dir_param
)
142 : delete_dir_param_(delete_dir_param
) {}
145 sync_driver::SyncFrontend
* frontend
,
146 scoped_ptr
<base::Thread
> sync_thread
,
147 const scoped_refptr
<base::SingleThreadTaskRunner
>& db_thread
,
148 const scoped_refptr
<base::SingleThreadTaskRunner
>& file_thread
,
149 const syncer::WeakHandle
<syncer::JsEventHandler
>& event_handler
,
150 const GURL
& service_url
,
151 const std::string
& sync_user_agent
,
152 const syncer::SyncCredentials
& credentials
,
153 bool delete_sync_data_folder
,
154 scoped_ptr
<syncer::SyncManagerFactory
> sync_manager_factory
,
155 const syncer::WeakHandle
<syncer::UnrecoverableErrorHandler
>&
156 unrecoverable_error_handler
,
157 const base::Closure
& report_unrecoverable_error_function
,
158 syncer::NetworkResources
* network_resources
,
159 scoped_ptr
<syncer::SyncEncryptionHandler::NigoriState
> saved_nigori_state
)
161 delete_dir_param_
->push_back(delete_sync_data_folder
);
162 SyncBackendHostMock::Initialize(
163 frontend
, sync_thread
.Pass(), db_thread
, file_thread
, event_handler
,
164 service_url
, sync_user_agent
, credentials
, delete_sync_data_folder
,
165 sync_manager_factory
.Pass(), unrecoverable_error_handler
,
166 report_unrecoverable_error_function
, network_resources
,
167 saved_nigori_state
.Pass());
171 std::vector
<bool>* delete_dir_param_
;
174 // SyncBackendHostMock that calls an external callback when ClearServerData is
176 class SyncBackendHostCaptureClearServerData
: public SyncBackendHostMock
{
178 typedef base::Callback
<void(
179 const syncer::SyncManager::ClearServerDataCallback
&)>
180 ClearServerDataCalled
;
181 explicit SyncBackendHostCaptureClearServerData(
182 const ClearServerDataCalled
& clear_server_data_called
)
183 : clear_server_data_called_(clear_server_data_called
) {}
185 void ClearServerData(
186 const syncer::SyncManager::ClearServerDataCallback
& callback
) override
{
187 clear_server_data_called_
.Run(callback
);
191 ClearServerDataCalled clear_server_data_called_
;
194 ACTION(ReturnNewSyncBackendHostMock
) {
195 return new browser_sync::SyncBackendHostMock();
198 ACTION(ReturnNewSyncBackendHostNoReturn
) {
199 return new browser_sync::SyncBackendHostNoReturn();
202 ACTION_P(ReturnNewMockHostCollectDeleteDirParam
, delete_dir_param
) {
203 return new browser_sync::SyncBackendHostMockCollectDeleteDirParam(
207 void OnClearServerDataCalled(
208 syncer::SyncManager::ClearServerDataCallback
* captured_callback
,
209 const syncer::SyncManager::ClearServerDataCallback
& callback
) {
210 *captured_callback
= callback
;
213 ACTION_P(ReturnNewMockHostCaptureClearServerData
, captured_callback
) {
214 return new SyncBackendHostCaptureClearServerData(base::Bind(
215 &OnClearServerDataCalled
, base::Unretained(captured_callback
)));
218 scoped_ptr
<KeyedService
> BuildFakeProfileInvalidationProvider(
219 content::BrowserContext
* context
) {
220 return make_scoped_ptr(new invalidation::ProfileInvalidationProvider(
221 scoped_ptr
<invalidation::InvalidationService
>(
222 new invalidation::FakeInvalidationService
)));
225 // A test harness that uses a real ProfileSyncService and in most cases a
226 // MockSyncBackendHost.
228 // This is useful if we want to test the ProfileSyncService and don't care about
229 // testing the SyncBackendHost.
230 class ProfileSyncServiceTest
: public ::testing::Test
{
232 ProfileSyncServiceTest()
233 : thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP
),
234 profile_manager_(TestingBrowserProcess::GetGlobal()) {}
235 ~ProfileSyncServiceTest() override
{}
237 void SetUp() override
{
238 base::CommandLine::ForCurrentProcess()->AppendSwitchASCII(
239 switches::kSyncDeferredStartupTimeoutSeconds
, "0");
241 CHECK(profile_manager_
.SetUp());
243 TestingProfile::TestingFactories testing_factories
;
244 testing_factories
.push_back(
245 std::make_pair(ProfileOAuth2TokenServiceFactory::GetInstance(),
246 BuildAutoIssuingFakeProfileOAuth2TokenService
));
247 testing_factories
.push_back(std::make_pair(
248 invalidation::ProfileInvalidationProviderFactory::GetInstance(),
249 BuildFakeProfileInvalidationProvider
));
251 profile_
= profile_manager_
.CreateTestingProfile(
252 "sync-service-test", scoped_ptr
<syncable_prefs::PrefServiceSyncable
>(),
253 base::UTF8ToUTF16("sync-service-test"), 0, std::string(),
257 void TearDown() override
{
258 // Kill the service before the profile.
260 service_
->Shutdown();
265 void IssueTestTokens() {
266 std::string account_id
=
267 AccountTrackerServiceFactory::GetForProfile(profile_
)
268 ->SeedAccountInfo(kGaiaId
, kEmail
);
269 ProfileOAuth2TokenServiceFactory::GetForProfile(profile_
)
270 ->UpdateCredentials(account_id
, "oauth2_login_token");
273 void CreateService(ProfileSyncServiceStartBehavior behavior
) {
274 SigninManagerBase
* signin
=
275 SigninManagerFactory::GetForProfile(profile_
);
276 signin
->SetAuthenticatedAccountInfo(kGaiaId
, kEmail
);
277 ProfileOAuth2TokenService
* oauth2_token_service
=
278 ProfileOAuth2TokenServiceFactory::GetForProfile(profile_
);
279 components_factory_
= new ProfileSyncComponentsFactoryMock();
280 service_
.reset(new ProfileSyncService(
281 scoped_ptr
<sync_driver::SyncApiComponentFactory
>(components_factory_
),
283 make_scoped_ptr(new SigninManagerWrapper(signin
)),
284 oauth2_token_service
,
286 service_
->SetClearingBrowseringDataForTesting(
287 base::Bind(&ProfileSyncServiceTest::ClearBrowsingDataCallback
,
288 base::Unretained(this)));
289 service_
->RegisterDataTypeController(
290 new sync_driver::FakeDataTypeController(syncer::BOOKMARKS
));
293 #if defined(OS_WIN) || defined(OS_MACOSX) || (defined(OS_LINUX) && !defined(OS_CHROMEOS))
294 void CreateServiceWithoutSignIn() {
295 CreateService(browser_sync::AUTO_START
);
296 SigninManagerFactory::GetForProfile(profile())->SignOut(
297 signin_metrics::SIGNOUT_TEST
);
301 void ShutdownAndDeleteService() {
303 service_
->Shutdown();
307 void InitializeForNthSync() {
308 // Set first sync time before initialize to disable backup and simulate
309 // a complete sync setup.
310 sync_driver::SyncPrefs
sync_prefs(service()->profile()->GetPrefs());
311 sync_prefs
.SetFirstSyncTime(base::Time::Now());
312 sync_prefs
.SetSyncSetupCompleted();
313 sync_prefs
.SetKeepEverythingSynced(true);
314 service_
->Initialize();
317 void InitializeForFirstSync() {
318 service_
->Initialize();
321 void TriggerPassphraseRequired() {
322 service_
->OnPassphraseRequired(syncer::REASON_DECRYPTION
,
323 sync_pb::EncryptedData());
326 void TriggerDataTypeStartRequest() {
327 service_
->OnDataTypeRequestsSyncStartup(syncer::BOOKMARKS
);
330 void OnConfigureCalled(syncer::ConfigureReason configure_reason
) {
331 sync_driver::DataTypeManager::ConfigureResult result
;
332 result
.status
= sync_driver::DataTypeManager::OK
;
333 service()->OnConfigureDone(result
);
336 FakeDataTypeManager::ConfigureCalled
GetDefaultConfigureCalledCallback() {
337 return base::Bind(&ProfileSyncServiceTest::OnConfigureCalled
,
338 base::Unretained(this));
341 void OnConfigureCalledRecordReason(syncer::ConfigureReason
* reason_dest
,
342 syncer::ConfigureReason reason
) {
344 *reason_dest
= reason
;
347 FakeDataTypeManager::ConfigureCalled
GetRecordingConfigureCalledCallback(
348 syncer::ConfigureReason
* reason
) {
349 return base::Bind(&ProfileSyncServiceTest::OnConfigureCalledRecordReason
,
350 base::Unretained(this), reason
);
353 void ExpectDataTypeManagerCreation(
355 const FakeDataTypeManager::ConfigureCalled
& callback
) {
356 EXPECT_CALL(*components_factory_
, CreateDataTypeManager(_
, _
, _
, _
, _
))
358 .WillRepeatedly(ReturnNewDataTypeManager(callback
));
361 void ExpectSyncBackendHostCreation(int times
) {
362 EXPECT_CALL(*components_factory_
, CreateSyncBackendHost(_
, _
, _
, _
))
364 .WillRepeatedly(ReturnNewSyncBackendHostMock());
367 void ExpectSyncBackendHostCreationCollectDeleteDir(
368 int times
, std::vector
<bool> *delete_dir_param
) {
369 EXPECT_CALL(*components_factory_
, CreateSyncBackendHost(_
, _
, _
, _
))
371 .WillRepeatedly(ReturnNewMockHostCollectDeleteDirParam(
375 void ExpectSyncBackendHostCreationCaptureClearServerData(
376 syncer::SyncManager::ClearServerDataCallback
* captured_callback
) {
377 EXPECT_CALL(*components_factory_
, CreateSyncBackendHost(_
, _
, _
, _
))
379 .WillOnce(ReturnNewMockHostCaptureClearServerData(captured_callback
));
382 void PrepareDelayedInitSyncBackendHost() {
383 EXPECT_CALL(*components_factory_
, CreateSyncBackendHost(_
, _
, _
, _
)).
384 WillOnce(ReturnNewSyncBackendHostNoReturn());
387 TestingProfile
* profile() {
391 ProfileSyncService
* service() {
392 return service_
.get();
395 ProfileSyncComponentsFactoryMock
* components_factory() {
396 return components_factory_
;
399 void ClearBrowsingDataCallback(BrowsingDataRemover::Observer
* observer
,
403 EXPECT_EQ(profile_
, profile
);
404 clear_browsing_date_start_
= start
;
409 base::RunLoop run_loop
;
410 base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE
,
411 run_loop
.QuitClosure());
415 // The requested start time when ClearBrowsingDataCallback is called.
416 base::Time clear_browsing_date_start_
;
419 content::TestBrowserThreadBundle thread_bundle_
;
420 TestingProfileManager profile_manager_
;
421 TestingProfile
* profile_
;
422 scoped_ptr
<ProfileSyncService
> service_
;
424 // Pointer to the components factory. Not owned. May be null.
425 ProfileSyncComponentsFactoryMock
* components_factory_
;
428 // Verify that the server URLs are sane.
429 TEST_F(ProfileSyncServiceTest
, InitialState
) {
430 CreateService(browser_sync::AUTO_START
);
431 InitializeForNthSync();
432 const std::string
& url
= service()->sync_service_url().spec();
433 EXPECT_TRUE(url
== internal::kSyncServerUrl
||
434 url
== internal::kSyncDevServerUrl
);
437 // Verify a successful initialization.
438 TEST_F(ProfileSyncServiceTest
, SuccessfulInitialization
) {
439 profile()->GetTestingPrefService()->SetManagedPref(
440 sync_driver::prefs::kSyncManaged
, new base::FundamentalValue(false));
442 CreateService(browser_sync::AUTO_START
);
443 ExpectDataTypeManagerCreation(1, GetDefaultConfigureCalledCallback());
444 ExpectSyncBackendHostCreation(1);
445 InitializeForNthSync();
446 EXPECT_FALSE(service()->IsManaged());
447 EXPECT_TRUE(service()->IsSyncActive());
448 EXPECT_EQ(ProfileSyncService::SYNC
, service()->backend_mode());
452 // Verify that the SetSetupInProgress function call updates state
453 // and notifies observers.
454 TEST_F(ProfileSyncServiceTest
, SetupInProgress
) {
455 CreateService(browser_sync::AUTO_START
);
456 InitializeForFirstSync();
458 TestSyncServiceObserver
observer(service());
459 service()->AddObserver(&observer
);
461 service()->SetSetupInProgress(true);
462 EXPECT_TRUE(observer
.first_setup_in_progress());
463 service()->SetSetupInProgress(false);
464 EXPECT_FALSE(observer
.first_setup_in_progress());
466 service()->RemoveObserver(&observer
);
469 // Verify that disable by enterprise policy works.
470 TEST_F(ProfileSyncServiceTest
, DisabledByPolicyBeforeInit
) {
471 profile()->GetTestingPrefService()->SetManagedPref(
472 sync_driver::prefs::kSyncManaged
, new base::FundamentalValue(true));
474 CreateService(browser_sync::AUTO_START
);
475 InitializeForNthSync();
476 EXPECT_TRUE(service()->IsManaged());
477 EXPECT_FALSE(service()->IsSyncActive());
480 // Verify that disable by enterprise policy works even after the backend has
482 TEST_F(ProfileSyncServiceTest
, DisabledByPolicyAfterInit
) {
484 CreateService(browser_sync::AUTO_START
);
485 ExpectDataTypeManagerCreation(1, GetDefaultConfigureCalledCallback());
486 ExpectSyncBackendHostCreation(1);
487 InitializeForNthSync();
489 EXPECT_FALSE(service()->IsManaged());
490 EXPECT_TRUE(service()->IsSyncActive());
492 profile()->GetTestingPrefService()->SetManagedPref(
493 sync_driver::prefs::kSyncManaged
, new base::FundamentalValue(true));
495 EXPECT_TRUE(service()->IsManaged());
496 EXPECT_FALSE(service()->IsSyncActive());
499 // Exercies the ProfileSyncService's code paths related to getting shut down
500 // before the backend initialize call returns.
501 TEST_F(ProfileSyncServiceTest
, AbortedByShutdown
) {
502 CreateService(browser_sync::AUTO_START
);
503 PrepareDelayedInitSyncBackendHost();
506 InitializeForNthSync();
507 EXPECT_FALSE(service()->IsSyncActive());
509 ShutdownAndDeleteService();
512 // Test RequestStop() before we've initialized the backend.
513 TEST_F(ProfileSyncServiceTest
, EarlyRequestStop
) {
514 CreateService(browser_sync::AUTO_START
);
517 service()->RequestStop(ProfileSyncService::KEEP_DATA
);
518 EXPECT_TRUE(profile()->GetPrefs()->GetBoolean(
519 sync_driver::prefs::kSyncSuppressStart
));
521 // Because of suppression, this should fail.
522 sync_driver::SyncPrefs
sync_prefs(service()->profile()->GetPrefs());
523 sync_prefs
.SetFirstSyncTime(base::Time::Now());
524 service()->Initialize();
525 EXPECT_FALSE(service()->IsSyncActive());
527 // Request start. This should be enough to allow init to happen.
528 ExpectDataTypeManagerCreation(1, GetDefaultConfigureCalledCallback());
529 ExpectSyncBackendHostCreation(1);
530 service()->RequestStart();
531 EXPECT_TRUE(service()->IsSyncActive());
532 EXPECT_FALSE(profile()->GetPrefs()->GetBoolean(
533 sync_driver::prefs::kSyncSuppressStart
));
536 // Test RequestStop() after we've initialized the backend.
537 TEST_F(ProfileSyncServiceTest
, DisableAndEnableSyncTemporarily
) {
538 CreateService(browser_sync::AUTO_START
);
540 ExpectDataTypeManagerCreation(1, GetDefaultConfigureCalledCallback());
541 ExpectSyncBackendHostCreation(1);
542 InitializeForNthSync();
544 EXPECT_TRUE(service()->IsSyncActive());
545 EXPECT_FALSE(profile()->GetPrefs()->GetBoolean(
546 sync_driver::prefs::kSyncSuppressStart
));
548 testing::Mock::VerifyAndClearExpectations(components_factory());
550 service()->RequestStop(ProfileSyncService::KEEP_DATA
);
551 EXPECT_FALSE(service()->IsSyncActive());
552 EXPECT_TRUE(profile()->GetPrefs()->GetBoolean(
553 sync_driver::prefs::kSyncSuppressStart
));
555 ExpectDataTypeManagerCreation(1, GetDefaultConfigureCalledCallback());
556 ExpectSyncBackendHostCreation(1);
558 service()->RequestStart();
559 EXPECT_TRUE(service()->IsSyncActive());
560 EXPECT_FALSE(profile()->GetPrefs()->GetBoolean(
561 sync_driver::prefs::kSyncSuppressStart
));
564 // Certain ProfileSyncService tests don't apply to Chrome OS, for example
565 // things that deal with concepts like "signing out" and policy.
566 #if !defined (OS_CHROMEOS)
567 TEST_F(ProfileSyncServiceTest
, EnableSyncAndSignOut
) {
568 CreateService(browser_sync::AUTO_START
);
569 ExpectDataTypeManagerCreation(1, GetDefaultConfigureCalledCallback());
570 ExpectSyncBackendHostCreation(1);
572 InitializeForNthSync();
574 EXPECT_TRUE(service()->IsSyncActive());
575 EXPECT_FALSE(profile()->GetPrefs()->GetBoolean(
576 sync_driver::prefs::kSyncSuppressStart
));
578 SigninManagerFactory::GetForProfile(profile())->SignOut(
579 signin_metrics::SIGNOUT_TEST
);
580 EXPECT_FALSE(service()->IsSyncActive());
582 #endif // !defined(OS_CHROMEOS)
584 TEST_F(ProfileSyncServiceTest
, GetSyncTokenStatus
) {
585 CreateService(browser_sync::AUTO_START
);
587 ExpectDataTypeManagerCreation(1, GetDefaultConfigureCalledCallback());
588 ExpectSyncBackendHostCreation(1);
589 InitializeForNthSync();
592 ProfileSyncService::SyncTokenStatus token_status
=
593 service()->GetSyncTokenStatus();
594 EXPECT_EQ(syncer::CONNECTION_NOT_ATTEMPTED
, token_status
.connection_status
);
595 EXPECT_TRUE(token_status
.connection_status_update_time
.is_null());
596 EXPECT_TRUE(token_status
.token_request_time
.is_null());
597 EXPECT_TRUE(token_status
.token_receive_time
.is_null());
599 // Simulate an auth error.
600 service()->OnConnectionStatusChange(syncer::CONNECTION_AUTH_ERROR
);
602 // The token request will take the form of a posted task. Run it.
606 token_status
= service()->GetSyncTokenStatus();
607 EXPECT_EQ(syncer::CONNECTION_AUTH_ERROR
, token_status
.connection_status
);
608 EXPECT_FALSE(token_status
.connection_status_update_time
.is_null());
609 EXPECT_FALSE(token_status
.token_request_time
.is_null());
610 EXPECT_FALSE(token_status
.token_receive_time
.is_null());
611 EXPECT_EQ(GoogleServiceAuthError::AuthErrorNone(),
612 token_status
.last_get_token_error
);
613 EXPECT_TRUE(token_status
.next_token_request_time
.is_null());
615 // Simulate successful connection.
616 service()->OnConnectionStatusChange(syncer::CONNECTION_OK
);
617 token_status
= service()->GetSyncTokenStatus();
618 EXPECT_EQ(syncer::CONNECTION_OK
, token_status
.connection_status
);
621 #if defined(ENABLE_PRE_SYNC_BACKUP)
622 TEST_F(ProfileSyncServiceTest
, DontStartBackupOnBrowserStart
) {
623 CreateServiceWithoutSignIn();
624 InitializeForFirstSync();
626 EXPECT_EQ(ProfileSyncService::IDLE
, service()->backend_mode());
629 TEST_F(ProfileSyncServiceTest
, BackupBeforeFirstSync
) {
630 CreateServiceWithoutSignIn();
631 ExpectDataTypeManagerCreation(2, GetDefaultConfigureCalledCallback());
632 std::vector
<bool> delete_dir_param
;
633 ExpectSyncBackendHostCreationCollectDeleteDir(2, &delete_dir_param
);
634 InitializeForFirstSync();
636 SigninManagerFactory::GetForProfile(profile())
637 ->SetAuthenticatedAccountInfo(kGaiaId
, kEmail
);
641 // At this time, backup is finished. Task is posted to start sync again.
642 EXPECT_EQ(ProfileSyncService::BACKUP
, service()->backend_mode());
643 EXPECT_FALSE(service()->IsSyncActive());
644 EXPECT_EQ(1u, delete_dir_param
.size());
645 EXPECT_TRUE(delete_dir_param
[0]);
647 // Pump loop to start sync.
649 EXPECT_EQ(ProfileSyncService::SYNC
, service()->backend_mode());
650 EXPECT_TRUE(service()->IsSyncActive());
651 EXPECT_EQ(2u, delete_dir_param
.size());
652 EXPECT_TRUE(delete_dir_param
[0]);
655 // Test backup is done again on browser start if user signed in last session
656 // but backup didn't finish when last session was closed.
657 TEST_F(ProfileSyncServiceTest
, ResumeBackupIfAborted
) {
659 CreateService(AUTO_START
);
660 ExpectDataTypeManagerCreation(2, GetDefaultConfigureCalledCallback());
661 std::vector
<bool> delete_dir_param
;
662 ExpectSyncBackendHostCreationCollectDeleteDir(2, &delete_dir_param
);
663 InitializeForFirstSync();
666 // At this time, backup is finished. Task is posted to start sync again.
667 EXPECT_EQ(ProfileSyncService::BACKUP
, service()->backend_mode());
668 EXPECT_FALSE(service()->IsSyncActive());
669 EXPECT_EQ(1u, delete_dir_param
.size());
670 EXPECT_TRUE(delete_dir_param
[0]);
672 // Pump loop to start sync.
674 EXPECT_EQ(ProfileSyncService::SYNC
, service()->backend_mode());
675 EXPECT_TRUE(service()->IsSyncActive());
676 EXPECT_EQ(2u, delete_dir_param
.size());
677 EXPECT_TRUE(delete_dir_param
[0]);
680 TEST_F(ProfileSyncServiceTest
, Rollback
) {
681 CreateService(browser_sync::MANUAL_START
);
682 service()->SetSyncSetupCompleted();
683 ExpectDataTypeManagerCreation(2, GetDefaultConfigureCalledCallback());
684 std::vector
<bool> delete_dir_param
;
685 ExpectSyncBackendHostCreationCollectDeleteDir(2, &delete_dir_param
);
687 InitializeForNthSync();
688 EXPECT_TRUE(service()->IsSyncActive());
689 EXPECT_EQ(ProfileSyncService::SYNC
, service()->backend_mode());
691 // First sync time should be recorded.
692 sync_driver::SyncPrefs
sync_prefs(service()->profile()->GetPrefs());
693 base::Time first_sync_time
= sync_prefs
.GetFirstSyncTime();
694 EXPECT_FALSE(first_sync_time
.is_null());
696 syncer::SyncProtocolError client_cmd
;
697 client_cmd
.action
= syncer::DISABLE_SYNC_AND_ROLLBACK
;
698 service()->OnActionableError(client_cmd
);
699 EXPECT_EQ(ProfileSyncService::IDLE
, service()->backend_mode());
701 // Pump loop to run rollback.
703 EXPECT_EQ(ProfileSyncService::ROLLBACK
, service()->backend_mode());
705 // Browser data should be cleared during rollback.
706 EXPECT_EQ(first_sync_time
, clear_browsing_date_start_
);
708 client_cmd
.action
= syncer::ROLLBACK_DONE
;
709 service()->OnActionableError(client_cmd
);
710 EXPECT_EQ(ProfileSyncService::IDLE
, service()->backend_mode());
712 // First sync time is erased after rollback is done.
713 EXPECT_TRUE(sync_prefs
.GetFirstSyncTime().is_null());
715 EXPECT_EQ(2u, delete_dir_param
.size());
716 EXPECT_FALSE(delete_dir_param
[0]);
717 EXPECT_FALSE(delete_dir_param
[1]);
722 // Verify that LastSyncedTime is cleared when the user signs out.
723 TEST_F(ProfileSyncServiceTest
, ClearLastSyncedTimeOnSignOut
) {
725 CreateService(AUTO_START
);
726 ExpectDataTypeManagerCreation(1, GetDefaultConfigureCalledCallback());
727 ExpectSyncBackendHostCreation(1);
728 InitializeForNthSync();
729 EXPECT_TRUE(service()->IsSyncActive());
730 EXPECT_EQ(l10n_util::GetStringUTF16(IDS_SYNC_TIME_JUST_NOW
),
731 service()->GetLastSyncedTimeString());
734 service()->RequestStop(ProfileSyncService::CLEAR_DATA
);
737 EXPECT_EQ(l10n_util::GetStringUTF16(IDS_SYNC_TIME_NEVER
),
738 service()->GetLastSyncedTimeString());
741 // Verify that the disable sync flag disables sync.
742 TEST_F(ProfileSyncServiceTest
, DisableSyncFlag
) {
743 base::CommandLine::ForCurrentProcess()->AppendSwitch(switches::kDisableSync
);
744 EXPECT_FALSE(ProfileSyncService::IsSyncAllowedByFlag());
747 // Verify that no disable sync flag enables sync.
748 TEST_F(ProfileSyncServiceTest
, NoDisableSyncFlag
) {
749 EXPECT_TRUE(ProfileSyncService::IsSyncAllowedByFlag());
752 // Test Sync will stop after receive memory pressure
753 TEST_F(ProfileSyncServiceTest
, MemoryPressureRecording
) {
754 CreateService(browser_sync::AUTO_START
);
756 ExpectDataTypeManagerCreation(1, GetDefaultConfigureCalledCallback());
757 ExpectSyncBackendHostCreation(1);
758 InitializeForNthSync();
760 EXPECT_TRUE(service()->IsSyncActive());
761 EXPECT_FALSE(profile()->GetPrefs()->GetBoolean(
762 sync_driver::prefs::kSyncSuppressStart
));
764 testing::Mock::VerifyAndClearExpectations(components_factory());
766 sync_driver::SyncPrefs
sync_prefs(service()->profile()->GetPrefs());
768 EXPECT_EQ(profile()->GetPrefs()->GetInteger(
769 sync_driver::prefs::kSyncMemoryPressureWarningCount
),
771 EXPECT_FALSE(sync_prefs
.DidSyncShutdownCleanly());
773 // Simulate memory pressure notification.
774 base::MemoryPressureListener::NotifyMemoryPressure(
775 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL
);
776 base::RunLoop().RunUntilIdle();
778 // Verify memory pressure recorded.
779 EXPECT_EQ(profile()->GetPrefs()->GetInteger(
780 sync_driver::prefs::kSyncMemoryPressureWarningCount
),
782 EXPECT_FALSE(sync_prefs
.DidSyncShutdownCleanly());
784 // Simulate memory pressure notification.
785 base::MemoryPressureListener::NotifyMemoryPressure(
786 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL
);
787 base::RunLoop().RunUntilIdle();
788 ShutdownAndDeleteService();
790 // Verify memory pressure and shutdown recorded.
791 EXPECT_EQ(profile()->GetPrefs()->GetInteger(
792 sync_driver::prefs::kSyncMemoryPressureWarningCount
),
794 EXPECT_TRUE(sync_prefs
.DidSyncShutdownCleanly());
797 // Verify that OnLocalSetPassphraseEncryption triggers catch up configure sync
798 // cycle, calls ClearServerData, shuts down and restarts sync.
799 TEST_F(ProfileSyncServiceTest
, OnLocalSetPassphraseEncryption
) {
800 base::CommandLine::ForCurrentProcess()->AppendSwitch(
801 switches::kSyncEnableClearDataOnPassphraseEncryption
);
803 CreateService(browser_sync::AUTO_START
);
805 syncer::SyncManager::ClearServerDataCallback captured_callback
;
806 syncer::ConfigureReason configure_reason
= syncer::CONFIGURE_REASON_UNKNOWN
;
808 // Initialize sync, ensure that both DataTypeManager and SyncBackendHost are
809 // initialized and DTM::Configure is called with
810 // CONFIGURE_REASON_NEWLY_ENABLED_DATA_TYPE.
811 ExpectSyncBackendHostCreationCaptureClearServerData(&captured_callback
);
812 ExpectDataTypeManagerCreation(
813 1, GetRecordingConfigureCalledCallback(&configure_reason
));
814 InitializeForNthSync();
815 EXPECT_TRUE(service()->IsSyncActive());
816 EXPECT_EQ(ProfileSyncService::SYNC
, service()->backend_mode());
817 testing::Mock::VerifyAndClearExpectations(components_factory());
818 EXPECT_EQ(syncer::CONFIGURE_REASON_NEWLY_ENABLED_DATA_TYPE
, configure_reason
);
819 sync_driver::DataTypeManager::ConfigureResult result
;
820 result
.status
= sync_driver::DataTypeManager::OK
;
821 service()->OnConfigureDone(result
);
823 // Simulate user entering encryption passphrase. Ensure that catch up
824 // configure cycle is started (DTM::Configure is called with
825 // CONFIGURE_REASON_CATCH_UP).
826 const syncer::SyncEncryptionHandler::NigoriState nigori_state
;
827 service()->OnLocalSetPassphraseEncryption(nigori_state
);
828 EXPECT_EQ(syncer::CONFIGURE_REASON_CATCH_UP
, configure_reason
);
829 EXPECT_TRUE(captured_callback
.is_null());
831 // Simulate configure successful. Ensure that SBH::ClearServerData is called.
832 service()->OnConfigureDone(result
);
833 EXPECT_FALSE(captured_callback
.is_null());
835 // Once SBH::ClearServerData finishes successfully ensure that sync is
837 configure_reason
= syncer::CONFIGURE_REASON_UNKNOWN
;
838 ExpectSyncBackendHostCreation(1);
839 ExpectDataTypeManagerCreation(
840 1, GetRecordingConfigureCalledCallback(&configure_reason
));
841 captured_callback
.Run();
842 testing::Mock::VerifyAndClearExpectations(components_factory());
843 EXPECT_EQ(syncer::CONFIGURE_REASON_NEWLY_ENABLED_DATA_TYPE
, configure_reason
);
844 service()->OnConfigureDone(result
);
847 // Verify that if after OnLocalSetPassphraseEncryption catch up configure sync
848 // cycle gets interrupted, it starts again after browser restart.
849 TEST_F(ProfileSyncServiceTest
,
850 OnLocalSetPassphraseEncryption_RestartDuringCatchUp
) {
851 syncer::ConfigureReason configure_reason
= syncer::CONFIGURE_REASON_UNKNOWN
;
852 base::CommandLine::ForCurrentProcess()->AppendSwitch(
853 switches::kSyncEnableClearDataOnPassphraseEncryption
);
855 CreateService(browser_sync::AUTO_START
);
856 ExpectSyncBackendHostCreation(1);
857 ExpectDataTypeManagerCreation(
858 1, GetRecordingConfigureCalledCallback(&configure_reason
));
859 InitializeForNthSync();
860 EXPECT_EQ(ProfileSyncService::SYNC
, service()->backend_mode());
861 testing::Mock::VerifyAndClearExpectations(components_factory());
862 EXPECT_EQ(syncer::CONFIGURE_REASON_NEWLY_ENABLED_DATA_TYPE
, configure_reason
);
863 sync_driver::DataTypeManager::ConfigureResult result
;
864 result
.status
= sync_driver::DataTypeManager::OK
;
865 service()->OnConfigureDone(result
);
867 // Simulate user entering encryption passphrase. Ensure Configure was called
868 // but don't let it continue.
869 const syncer::SyncEncryptionHandler::NigoriState nigori_state
;
870 service()->OnLocalSetPassphraseEncryption(nigori_state
);
871 EXPECT_EQ(syncer::CONFIGURE_REASON_CATCH_UP
, configure_reason
);
873 // Simulate browser restart. First configuration is a regular one.
874 service()->Shutdown();
875 syncer::SyncManager::ClearServerDataCallback captured_callback
;
876 ExpectSyncBackendHostCreationCaptureClearServerData(&captured_callback
);
877 ExpectDataTypeManagerCreation(
878 1, GetRecordingConfigureCalledCallback(&configure_reason
));
879 service()->RequestStart();
880 testing::Mock::VerifyAndClearExpectations(components_factory());
881 EXPECT_EQ(syncer::CONFIGURE_REASON_NEWLY_ENABLED_DATA_TYPE
, configure_reason
);
882 EXPECT_TRUE(captured_callback
.is_null());
884 // Simulate configure successful. This time it should be catch up.
885 service()->OnConfigureDone(result
);
886 EXPECT_EQ(syncer::CONFIGURE_REASON_CATCH_UP
, configure_reason
);
887 EXPECT_TRUE(captured_callback
.is_null());
889 // Simulate catch up configure successful. Ensure that SBH::ClearServerData is
891 service()->OnConfigureDone(result
);
892 EXPECT_FALSE(captured_callback
.is_null());
894 ExpectSyncBackendHostCreation(1);
895 ExpectDataTypeManagerCreation(
896 1, GetRecordingConfigureCalledCallback(&configure_reason
));
897 captured_callback
.Run();
898 testing::Mock::VerifyAndClearExpectations(components_factory());
899 EXPECT_EQ(syncer::CONFIGURE_REASON_NEWLY_ENABLED_DATA_TYPE
, configure_reason
);
902 // Verify that if after OnLocalSetPassphraseEncryption ClearServerData gets
903 // interrupted, transition again from catch up sync cycle after browser restart.
904 TEST_F(ProfileSyncServiceTest
,
905 OnLocalSetPassphraseEncryption_RestartDuringClearServerData
) {
906 syncer::SyncManager::ClearServerDataCallback captured_callback
;
907 syncer::ConfigureReason configure_reason
= syncer::CONFIGURE_REASON_UNKNOWN
;
908 base::CommandLine::ForCurrentProcess()->AppendSwitch(
909 switches::kSyncEnableClearDataOnPassphraseEncryption
);
911 CreateService(browser_sync::AUTO_START
);
912 ExpectSyncBackendHostCreationCaptureClearServerData(&captured_callback
);
913 ExpectDataTypeManagerCreation(1, GetDefaultConfigureCalledCallback());
914 InitializeForNthSync();
915 EXPECT_EQ(ProfileSyncService::SYNC
, service()->backend_mode());
916 testing::Mock::VerifyAndClearExpectations(components_factory());
918 // Simulate user entering encryption passphrase.
919 const syncer::SyncEncryptionHandler::NigoriState nigori_state
;
920 service()->OnLocalSetPassphraseEncryption(nigori_state
);
921 EXPECT_FALSE(captured_callback
.is_null());
922 captured_callback
.Reset();
924 // Simulate browser restart. First configuration is a regular one.
925 service()->Shutdown();
926 ExpectSyncBackendHostCreationCaptureClearServerData(&captured_callback
);
927 ExpectDataTypeManagerCreation(
928 1, GetRecordingConfigureCalledCallback(&configure_reason
));
929 service()->RequestStart();
930 testing::Mock::VerifyAndClearExpectations(components_factory());
931 EXPECT_EQ(syncer::CONFIGURE_REASON_NEWLY_ENABLED_DATA_TYPE
, configure_reason
);
932 EXPECT_TRUE(captured_callback
.is_null());
934 // Simulate configure successful. This time it should be catch up.
935 sync_driver::DataTypeManager::ConfigureResult result
;
936 result
.status
= sync_driver::DataTypeManager::OK
;
937 service()->OnConfigureDone(result
);
938 EXPECT_EQ(syncer::CONFIGURE_REASON_CATCH_UP
, configure_reason
);
939 EXPECT_TRUE(captured_callback
.is_null());
941 // Simulate catch up configure successful. Ensure that SBH::ClearServerData is
943 service()->OnConfigureDone(result
);
944 EXPECT_FALSE(captured_callback
.is_null());
946 ExpectSyncBackendHostCreation(1);
947 ExpectDataTypeManagerCreation(
948 1, GetRecordingConfigureCalledCallback(&configure_reason
));
949 captured_callback
.Run();
950 testing::Mock::VerifyAndClearExpectations(components_factory());
951 EXPECT_EQ(syncer::CONFIGURE_REASON_NEWLY_ENABLED_DATA_TYPE
, configure_reason
);
954 // Test that the passphrase prompt due to version change logic gets triggered
955 // on a datatype type requesting startup, but only happens once.
956 TEST_F(ProfileSyncServiceTest
, PassphrasePromptDueToVersion
) {
958 CreateService(browser_sync::AUTO_START
);
959 ExpectDataTypeManagerCreation(1, GetDefaultConfigureCalledCallback());
960 ExpectSyncBackendHostCreation(1);
961 InitializeForNthSync();
963 sync_driver::SyncPrefs
sync_prefs(service()->profile()->GetPrefs());
964 EXPECT_EQ(PRODUCT_VERSION
, sync_prefs
.GetLastRunVersion());
966 sync_prefs
.SetPassphrasePrompted(true);
968 // Until a datatype requests startup while a passphrase is required the
969 // passphrase prompt bit should remain set.
970 EXPECT_TRUE(sync_prefs
.IsPassphrasePrompted());
971 TriggerPassphraseRequired();
972 EXPECT_TRUE(sync_prefs
.IsPassphrasePrompted());
974 // Because the last version was unset, this run should be treated as a new
975 // version and force a prompt.
976 TriggerDataTypeStartRequest();
977 EXPECT_FALSE(sync_prefs
.IsPassphrasePrompted());
979 // At this point further datatype startup request should have no effect.
980 sync_prefs
.SetPassphrasePrompted(true);
981 TriggerDataTypeStartRequest();
982 EXPECT_TRUE(sync_prefs
.IsPassphrasePrompted());
986 } // namespace browser_sync