Only grant permissions to new extensions from sync if they have the expected version
[chromium-blink-merge.git] / chrome / browser / sync / profile_sync_service_unittest.cc
blob64f81277658b2685a4b27a7f9704249364aa5ee7
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_pref_service_syncable.h"
31 #include "chrome/test/base/testing_profile.h"
32 #include "chrome/test/base/testing_profile_manager.h"
33 #include "components/invalidation/impl/profile_invalidation_provider.h"
34 #include "components/invalidation/public/invalidation_service.h"
35 #include "components/signin/core/browser/account_tracker_service.h"
36 #include "components/signin/core/browser/fake_profile_oauth2_token_service.h"
37 #include "components/signin/core/browser/signin_manager.h"
38 #include "components/signin/core/browser/signin_manager.h"
39 #include "components/sync_driver/data_type_manager.h"
40 #include "components/sync_driver/data_type_manager_observer.h"
41 #include "components/sync_driver/fake_data_type_controller.h"
42 #include "components/sync_driver/pref_names.h"
43 #include "components/sync_driver/signin_manager_wrapper.h"
44 #include "components/sync_driver/sync_driver_switches.h"
45 #include "components/sync_driver/sync_prefs.h"
46 #include "components/sync_driver/sync_service_observer.h"
47 #include "components/sync_driver/sync_util.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"
55 namespace content {
56 class BrowserContext;
59 namespace browser_sync {
61 namespace {
63 const char kGaiaId[] = "12345";
64 const char kEmail[] = "test_user@gmail.com";
66 class FakeDataTypeManager : public sync_driver::DataTypeManager {
67 public:
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;
90 private:
91 ConfigureCalled configure_called_;
94 ACTION_P(ReturnNewDataTypeManager, configure_called) {
95 return new FakeDataTypeManager(configure_called);
98 using testing::Return;
99 using testing::StrictMock;
100 using testing::_;
102 class TestSyncServiceObserver : public sync_driver::SyncServiceObserver {
103 public:
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_; }
110 private:
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 {
119 void Initialize(
120 sync_driver::SyncFrontend* frontend,
121 scoped_ptr<base::Thread> sync_thread,
122 const syncer::WeakHandle<syncer::JsEventHandler>& event_handler,
123 const GURL& service_url,
124 const std::string& sync_user_agent,
125 const syncer::SyncCredentials& credentials,
126 bool delete_sync_data_folder,
127 scoped_ptr<syncer::SyncManagerFactory> sync_manager_factory,
128 const syncer::WeakHandle<syncer::UnrecoverableErrorHandler>&
129 unrecoverable_error_handler,
130 const base::Closure& report_unrecoverable_error_function,
131 syncer::NetworkResources* network_resources,
132 scoped_ptr<syncer::SyncEncryptionHandler::NigoriState> saved_nigori_state)
133 override {}
136 class SyncBackendHostMockCollectDeleteDirParam : public SyncBackendHostMock {
137 public:
138 explicit SyncBackendHostMockCollectDeleteDirParam(
139 std::vector<bool>* delete_dir_param)
140 : delete_dir_param_(delete_dir_param) {}
142 void Initialize(
143 sync_driver::SyncFrontend* frontend,
144 scoped_ptr<base::Thread> sync_thread,
145 const syncer::WeakHandle<syncer::JsEventHandler>& event_handler,
146 const GURL& service_url,
147 const std::string& sync_user_agent,
148 const syncer::SyncCredentials& credentials,
149 bool delete_sync_data_folder,
150 scoped_ptr<syncer::SyncManagerFactory> sync_manager_factory,
151 const syncer::WeakHandle<syncer::UnrecoverableErrorHandler>&
152 unrecoverable_error_handler,
153 const base::Closure& report_unrecoverable_error_function,
154 syncer::NetworkResources* network_resources,
155 scoped_ptr<syncer::SyncEncryptionHandler::NigoriState> saved_nigori_state)
156 override {
157 delete_dir_param_->push_back(delete_sync_data_folder);
158 SyncBackendHostMock::Initialize(frontend, sync_thread.Pass(),
159 event_handler, service_url, sync_user_agent,
160 credentials, delete_sync_data_folder,
161 sync_manager_factory.Pass(),
162 unrecoverable_error_handler,
163 report_unrecoverable_error_function,
164 network_resources,
165 saved_nigori_state.Pass());
168 private:
169 std::vector<bool>* delete_dir_param_;
172 // SyncBackendHostMock that calls an external callback when ClearServerData is
173 // called.
174 class SyncBackendHostCaptureClearServerData : public SyncBackendHostMock {
175 public:
176 typedef base::Callback<void(
177 const syncer::SyncManager::ClearServerDataCallback&)>
178 ClearServerDataCalled;
179 explicit SyncBackendHostCaptureClearServerData(
180 const ClearServerDataCalled& clear_server_data_called)
181 : clear_server_data_called_(clear_server_data_called) {}
183 void ClearServerData(
184 const syncer::SyncManager::ClearServerDataCallback& callback) override {
185 clear_server_data_called_.Run(callback);
188 private:
189 ClearServerDataCalled clear_server_data_called_;
192 ACTION(ReturnNewSyncBackendHostMock) {
193 return new browser_sync::SyncBackendHostMock();
196 ACTION(ReturnNewSyncBackendHostNoReturn) {
197 return new browser_sync::SyncBackendHostNoReturn();
200 ACTION_P(ReturnNewMockHostCollectDeleteDirParam, delete_dir_param) {
201 return new browser_sync::SyncBackendHostMockCollectDeleteDirParam(
202 delete_dir_param);
205 void OnClearServerDataCalled(
206 syncer::SyncManager::ClearServerDataCallback* captured_callback,
207 const syncer::SyncManager::ClearServerDataCallback& callback) {
208 *captured_callback = callback;
211 ACTION_P(ReturnNewMockHostCaptureClearServerData, captured_callback) {
212 return new SyncBackendHostCaptureClearServerData(base::Bind(
213 &OnClearServerDataCalled, base::Unretained(captured_callback)));
216 scoped_ptr<KeyedService> BuildFakeProfileInvalidationProvider(
217 content::BrowserContext* context) {
218 return make_scoped_ptr(new invalidation::ProfileInvalidationProvider(
219 scoped_ptr<invalidation::InvalidationService>(
220 new invalidation::FakeInvalidationService)));
223 // A test harness that uses a real ProfileSyncService and in most cases a
224 // MockSyncBackendHost.
226 // This is useful if we want to test the ProfileSyncService and don't care about
227 // testing the SyncBackendHost.
228 class ProfileSyncServiceTest : public ::testing::Test {
229 protected:
230 ProfileSyncServiceTest()
231 : thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP),
232 profile_manager_(TestingBrowserProcess::GetGlobal()) {}
233 ~ProfileSyncServiceTest() override {}
235 void SetUp() override {
236 base::CommandLine::ForCurrentProcess()->AppendSwitchASCII(
237 switches::kSyncDeferredStartupTimeoutSeconds, "0");
239 CHECK(profile_manager_.SetUp());
241 TestingProfile::TestingFactories testing_factories;
242 testing_factories.push_back(
243 std::make_pair(ProfileOAuth2TokenServiceFactory::GetInstance(),
244 BuildAutoIssuingFakeProfileOAuth2TokenService));
245 testing_factories.push_back(std::make_pair(
246 invalidation::ProfileInvalidationProviderFactory::GetInstance(),
247 BuildFakeProfileInvalidationProvider));
249 profile_ = profile_manager_.CreateTestingProfile(
250 "sync-service-test", scoped_ptr<PrefServiceSyncable>(),
251 base::UTF8ToUTF16("sync-service-test"), 0, std::string(),
252 testing_factories);
255 void TearDown() override {
256 // Kill the service before the profile.
257 if (service_)
258 service_->Shutdown();
260 service_.reset();
263 void IssueTestTokens() {
264 std::string account_id =
265 AccountTrackerServiceFactory::GetForProfile(profile_)
266 ->SeedAccountInfo(kGaiaId, kEmail);
267 ProfileOAuth2TokenServiceFactory::GetForProfile(profile_)
268 ->UpdateCredentials(account_id, "oauth2_login_token");
271 void CreateService(ProfileSyncServiceStartBehavior behavior) {
272 SigninManagerBase* signin =
273 SigninManagerFactory::GetForProfile(profile_);
274 signin->SetAuthenticatedAccountInfo(kGaiaId, kEmail);
275 ProfileOAuth2TokenService* oauth2_token_service =
276 ProfileOAuth2TokenServiceFactory::GetForProfile(profile_);
277 components_factory_ = new ProfileSyncComponentsFactoryMock();
278 service_.reset(new ProfileSyncService(
279 scoped_ptr<sync_driver::SyncApiComponentFactory>(components_factory_),
280 profile_,
281 make_scoped_ptr(new SigninManagerWrapper(signin)),
282 oauth2_token_service,
283 behavior));
284 service_->SetClearingBrowseringDataForTesting(
285 base::Bind(&ProfileSyncServiceTest::ClearBrowsingDataCallback,
286 base::Unretained(this)));
287 service_->RegisterDataTypeController(
288 new sync_driver::FakeDataTypeController(syncer::BOOKMARKS));
291 #if defined(OS_WIN) || defined(OS_MACOSX) || (defined(OS_LINUX) && !defined(OS_CHROMEOS))
292 void CreateServiceWithoutSignIn() {
293 CreateService(browser_sync::AUTO_START);
294 SigninManagerFactory::GetForProfile(profile())->SignOut(
295 signin_metrics::SIGNOUT_TEST);
297 #endif
299 void ShutdownAndDeleteService() {
300 if (service_)
301 service_->Shutdown();
302 service_.reset();
305 void InitializeForNthSync() {
306 // Set first sync time before initialize to disable backup and simulate
307 // a complete sync setup.
308 sync_driver::SyncPrefs sync_prefs(service()->profile()->GetPrefs());
309 sync_prefs.SetFirstSyncTime(base::Time::Now());
310 sync_prefs.SetSyncSetupCompleted();
311 sync_prefs.SetKeepEverythingSynced(true);
312 service_->Initialize();
315 void InitializeForFirstSync() {
316 service_->Initialize();
319 void TriggerPassphraseRequired() {
320 service_->OnPassphraseRequired(syncer::REASON_DECRYPTION,
321 sync_pb::EncryptedData());
324 void TriggerDataTypeStartRequest() {
325 service_->OnDataTypeRequestsSyncStartup(syncer::BOOKMARKS);
328 void OnConfigureCalled(syncer::ConfigureReason configure_reason) {
329 sync_driver::DataTypeManager::ConfigureResult result;
330 result.status = sync_driver::DataTypeManager::OK;
331 service()->OnConfigureDone(result);
334 FakeDataTypeManager::ConfigureCalled GetDefaultConfigureCalledCallback() {
335 return base::Bind(&ProfileSyncServiceTest::OnConfigureCalled,
336 base::Unretained(this));
339 void OnConfigureCalledRecordReason(syncer::ConfigureReason* reason_dest,
340 syncer::ConfigureReason reason) {
341 DCHECK(reason_dest);
342 *reason_dest = reason;
345 FakeDataTypeManager::ConfigureCalled GetRecordingConfigureCalledCallback(
346 syncer::ConfigureReason* reason) {
347 return base::Bind(&ProfileSyncServiceTest::OnConfigureCalledRecordReason,
348 base::Unretained(this), reason);
351 void ExpectDataTypeManagerCreation(
352 int times,
353 const FakeDataTypeManager::ConfigureCalled& callback) {
354 EXPECT_CALL(*components_factory_, CreateDataTypeManager(_, _, _, _, _))
355 .Times(times)
356 .WillRepeatedly(ReturnNewDataTypeManager(callback));
359 void ExpectSyncBackendHostCreation(int times) {
360 EXPECT_CALL(*components_factory_, CreateSyncBackendHost(_, _, _, _))
361 .Times(times)
362 .WillRepeatedly(ReturnNewSyncBackendHostMock());
365 void ExpectSyncBackendHostCreationCollectDeleteDir(
366 int times, std::vector<bool> *delete_dir_param) {
367 EXPECT_CALL(*components_factory_, CreateSyncBackendHost(_, _, _, _))
368 .Times(times)
369 .WillRepeatedly(ReturnNewMockHostCollectDeleteDirParam(
370 delete_dir_param));
373 void ExpectSyncBackendHostCreationCaptureClearServerData(
374 syncer::SyncManager::ClearServerDataCallback* captured_callback) {
375 EXPECT_CALL(*components_factory_, CreateSyncBackendHost(_, _, _, _))
376 .Times(1)
377 .WillOnce(ReturnNewMockHostCaptureClearServerData(captured_callback));
380 void PrepareDelayedInitSyncBackendHost() {
381 EXPECT_CALL(*components_factory_, CreateSyncBackendHost(_, _, _, _)).
382 WillOnce(ReturnNewSyncBackendHostNoReturn());
385 TestingProfile* profile() {
386 return profile_;
389 ProfileSyncService* service() {
390 return service_.get();
393 ProfileSyncComponentsFactoryMock* components_factory() {
394 return components_factory_;
397 void ClearBrowsingDataCallback(BrowsingDataRemover::Observer* observer,
398 Profile* profile,
399 base::Time start,
400 base::Time end) {
401 EXPECT_EQ(profile_, profile);
402 clear_browsing_date_start_ = start;
405 protected:
406 void PumpLoop() {
407 base::RunLoop run_loop;
408 base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE,
409 run_loop.QuitClosure());
410 run_loop.Run();
413 // The requested start time when ClearBrowsingDataCallback is called.
414 base::Time clear_browsing_date_start_;
416 private:
417 content::TestBrowserThreadBundle thread_bundle_;
418 TestingProfileManager profile_manager_;
419 TestingProfile* profile_;
420 scoped_ptr<ProfileSyncService> service_;
422 // Pointer to the components factory. Not owned. May be null.
423 ProfileSyncComponentsFactoryMock* components_factory_;
426 // Verify that the server URLs are sane.
427 TEST_F(ProfileSyncServiceTest, InitialState) {
428 CreateService(browser_sync::AUTO_START);
429 InitializeForNthSync();
430 const std::string& url = service()->sync_service_url().spec();
431 EXPECT_TRUE(url == internal::kSyncServerUrl ||
432 url == internal::kSyncDevServerUrl);
435 // Verify a successful initialization.
436 TEST_F(ProfileSyncServiceTest, SuccessfulInitialization) {
437 profile()->GetTestingPrefService()->SetManagedPref(
438 sync_driver::prefs::kSyncManaged, new base::FundamentalValue(false));
439 IssueTestTokens();
440 CreateService(browser_sync::AUTO_START);
441 ExpectDataTypeManagerCreation(1, GetDefaultConfigureCalledCallback());
442 ExpectSyncBackendHostCreation(1);
443 InitializeForNthSync();
444 EXPECT_FALSE(service()->IsManaged());
445 EXPECT_TRUE(service()->IsSyncActive());
446 EXPECT_EQ(ProfileSyncService::SYNC, service()->backend_mode());
450 // Verify that the SetSetupInProgress function call updates state
451 // and notifies observers.
452 TEST_F(ProfileSyncServiceTest, SetupInProgress) {
453 CreateService(browser_sync::AUTO_START);
454 InitializeForFirstSync();
456 TestSyncServiceObserver observer(service());
457 service()->AddObserver(&observer);
459 service()->SetSetupInProgress(true);
460 EXPECT_TRUE(observer.first_setup_in_progress());
461 service()->SetSetupInProgress(false);
462 EXPECT_FALSE(observer.first_setup_in_progress());
464 service()->RemoveObserver(&observer);
467 // Verify that disable by enterprise policy works.
468 TEST_F(ProfileSyncServiceTest, DisabledByPolicyBeforeInit) {
469 profile()->GetTestingPrefService()->SetManagedPref(
470 sync_driver::prefs::kSyncManaged, new base::FundamentalValue(true));
471 IssueTestTokens();
472 CreateService(browser_sync::AUTO_START);
473 InitializeForNthSync();
474 EXPECT_TRUE(service()->IsManaged());
475 EXPECT_FALSE(service()->IsSyncActive());
478 // Verify that disable by enterprise policy works even after the backend has
479 // been initialized.
480 TEST_F(ProfileSyncServiceTest, DisabledByPolicyAfterInit) {
481 IssueTestTokens();
482 CreateService(browser_sync::AUTO_START);
483 ExpectDataTypeManagerCreation(1, GetDefaultConfigureCalledCallback());
484 ExpectSyncBackendHostCreation(1);
485 InitializeForNthSync();
487 EXPECT_FALSE(service()->IsManaged());
488 EXPECT_TRUE(service()->IsSyncActive());
490 profile()->GetTestingPrefService()->SetManagedPref(
491 sync_driver::prefs::kSyncManaged, new base::FundamentalValue(true));
493 EXPECT_TRUE(service()->IsManaged());
494 EXPECT_FALSE(service()->IsSyncActive());
497 // Exercies the ProfileSyncService's code paths related to getting shut down
498 // before the backend initialize call returns.
499 TEST_F(ProfileSyncServiceTest, AbortedByShutdown) {
500 CreateService(browser_sync::AUTO_START);
501 PrepareDelayedInitSyncBackendHost();
503 IssueTestTokens();
504 InitializeForNthSync();
505 EXPECT_FALSE(service()->IsSyncActive());
507 ShutdownAndDeleteService();
510 // Test RequestStop() before we've initialized the backend.
511 TEST_F(ProfileSyncServiceTest, EarlyRequestStop) {
512 CreateService(browser_sync::AUTO_START);
513 IssueTestTokens();
515 service()->RequestStop(ProfileSyncService::KEEP_DATA);
516 EXPECT_TRUE(profile()->GetPrefs()->GetBoolean(
517 sync_driver::prefs::kSyncSuppressStart));
519 // Because of suppression, this should fail.
520 sync_driver::SyncPrefs sync_prefs(service()->profile()->GetPrefs());
521 sync_prefs.SetFirstSyncTime(base::Time::Now());
522 service()->Initialize();
523 EXPECT_FALSE(service()->IsSyncActive());
525 // Request start. This should be enough to allow init to happen.
526 ExpectDataTypeManagerCreation(1, GetDefaultConfigureCalledCallback());
527 ExpectSyncBackendHostCreation(1);
528 service()->RequestStart();
529 EXPECT_TRUE(service()->IsSyncActive());
530 EXPECT_FALSE(profile()->GetPrefs()->GetBoolean(
531 sync_driver::prefs::kSyncSuppressStart));
534 // Test RequestStop() after we've initialized the backend.
535 TEST_F(ProfileSyncServiceTest, DisableAndEnableSyncTemporarily) {
536 CreateService(browser_sync::AUTO_START);
537 IssueTestTokens();
538 ExpectDataTypeManagerCreation(1, GetDefaultConfigureCalledCallback());
539 ExpectSyncBackendHostCreation(1);
540 InitializeForNthSync();
542 EXPECT_TRUE(service()->IsSyncActive());
543 EXPECT_FALSE(profile()->GetPrefs()->GetBoolean(
544 sync_driver::prefs::kSyncSuppressStart));
546 testing::Mock::VerifyAndClearExpectations(components_factory());
548 service()->RequestStop(ProfileSyncService::KEEP_DATA);
549 EXPECT_FALSE(service()->IsSyncActive());
550 EXPECT_TRUE(profile()->GetPrefs()->GetBoolean(
551 sync_driver::prefs::kSyncSuppressStart));
553 ExpectDataTypeManagerCreation(1, GetDefaultConfigureCalledCallback());
554 ExpectSyncBackendHostCreation(1);
556 service()->RequestStart();
557 EXPECT_TRUE(service()->IsSyncActive());
558 EXPECT_FALSE(profile()->GetPrefs()->GetBoolean(
559 sync_driver::prefs::kSyncSuppressStart));
562 // Certain ProfileSyncService tests don't apply to Chrome OS, for example
563 // things that deal with concepts like "signing out" and policy.
564 #if !defined (OS_CHROMEOS)
565 TEST_F(ProfileSyncServiceTest, EnableSyncAndSignOut) {
566 CreateService(browser_sync::AUTO_START);
567 ExpectDataTypeManagerCreation(1, GetDefaultConfigureCalledCallback());
568 ExpectSyncBackendHostCreation(1);
569 IssueTestTokens();
570 InitializeForNthSync();
572 EXPECT_TRUE(service()->IsSyncActive());
573 EXPECT_FALSE(profile()->GetPrefs()->GetBoolean(
574 sync_driver::prefs::kSyncSuppressStart));
576 SigninManagerFactory::GetForProfile(profile())->SignOut(
577 signin_metrics::SIGNOUT_TEST);
578 EXPECT_FALSE(service()->IsSyncActive());
580 #endif // !defined(OS_CHROMEOS)
582 TEST_F(ProfileSyncServiceTest, GetSyncTokenStatus) {
583 CreateService(browser_sync::AUTO_START);
584 IssueTestTokens();
585 ExpectDataTypeManagerCreation(1, GetDefaultConfigureCalledCallback());
586 ExpectSyncBackendHostCreation(1);
587 InitializeForNthSync();
589 // Initial status.
590 ProfileSyncService::SyncTokenStatus token_status =
591 service()->GetSyncTokenStatus();
592 EXPECT_EQ(syncer::CONNECTION_NOT_ATTEMPTED, token_status.connection_status);
593 EXPECT_TRUE(token_status.connection_status_update_time.is_null());
594 EXPECT_TRUE(token_status.token_request_time.is_null());
595 EXPECT_TRUE(token_status.token_receive_time.is_null());
597 // Simulate an auth error.
598 service()->OnConnectionStatusChange(syncer::CONNECTION_AUTH_ERROR);
600 // The token request will take the form of a posted task. Run it.
601 base::RunLoop loop;
602 loop.RunUntilIdle();
604 token_status = service()->GetSyncTokenStatus();
605 EXPECT_EQ(syncer::CONNECTION_AUTH_ERROR, token_status.connection_status);
606 EXPECT_FALSE(token_status.connection_status_update_time.is_null());
607 EXPECT_FALSE(token_status.token_request_time.is_null());
608 EXPECT_FALSE(token_status.token_receive_time.is_null());
609 EXPECT_EQ(GoogleServiceAuthError::AuthErrorNone(),
610 token_status.last_get_token_error);
611 EXPECT_TRUE(token_status.next_token_request_time.is_null());
613 // Simulate successful connection.
614 service()->OnConnectionStatusChange(syncer::CONNECTION_OK);
615 token_status = service()->GetSyncTokenStatus();
616 EXPECT_EQ(syncer::CONNECTION_OK, token_status.connection_status);
619 #if defined(ENABLE_PRE_SYNC_BACKUP)
620 TEST_F(ProfileSyncServiceTest, DontStartBackupOnBrowserStart) {
621 CreateServiceWithoutSignIn();
622 InitializeForFirstSync();
623 PumpLoop();
624 EXPECT_EQ(ProfileSyncService::IDLE, service()->backend_mode());
627 TEST_F(ProfileSyncServiceTest, BackupBeforeFirstSync) {
628 CreateServiceWithoutSignIn();
629 ExpectDataTypeManagerCreation(2, GetDefaultConfigureCalledCallback());
630 std::vector<bool> delete_dir_param;
631 ExpectSyncBackendHostCreationCollectDeleteDir(2, &delete_dir_param);
632 InitializeForFirstSync();
634 SigninManagerFactory::GetForProfile(profile())
635 ->SetAuthenticatedAccountInfo(kGaiaId, kEmail);
636 IssueTestTokens();
637 PumpLoop();
639 // At this time, backup is finished. Task is posted to start sync again.
640 EXPECT_EQ(ProfileSyncService::BACKUP, service()->backend_mode());
641 EXPECT_FALSE(service()->IsSyncActive());
642 EXPECT_EQ(1u, delete_dir_param.size());
643 EXPECT_TRUE(delete_dir_param[0]);
645 // Pump loop to start sync.
646 PumpLoop();
647 EXPECT_EQ(ProfileSyncService::SYNC, service()->backend_mode());
648 EXPECT_TRUE(service()->IsSyncActive());
649 EXPECT_EQ(2u, delete_dir_param.size());
650 EXPECT_TRUE(delete_dir_param[0]);
653 // Test backup is done again on browser start if user signed in last session
654 // but backup didn't finish when last session was closed.
655 TEST_F(ProfileSyncServiceTest, ResumeBackupIfAborted) {
656 IssueTestTokens();
657 CreateService(AUTO_START);
658 ExpectDataTypeManagerCreation(2, GetDefaultConfigureCalledCallback());
659 std::vector<bool> delete_dir_param;
660 ExpectSyncBackendHostCreationCollectDeleteDir(2, &delete_dir_param);
661 InitializeForFirstSync();
662 PumpLoop();
664 // At this time, backup is finished. Task is posted to start sync again.
665 EXPECT_EQ(ProfileSyncService::BACKUP, service()->backend_mode());
666 EXPECT_FALSE(service()->IsSyncActive());
667 EXPECT_EQ(1u, delete_dir_param.size());
668 EXPECT_TRUE(delete_dir_param[0]);
670 // Pump loop to start sync.
671 PumpLoop();
672 EXPECT_EQ(ProfileSyncService::SYNC, service()->backend_mode());
673 EXPECT_TRUE(service()->IsSyncActive());
674 EXPECT_EQ(2u, delete_dir_param.size());
675 EXPECT_TRUE(delete_dir_param[0]);
678 TEST_F(ProfileSyncServiceTest, Rollback) {
679 CreateService(browser_sync::MANUAL_START);
680 service()->SetSyncSetupCompleted();
681 ExpectDataTypeManagerCreation(2, GetDefaultConfigureCalledCallback());
682 std::vector<bool> delete_dir_param;
683 ExpectSyncBackendHostCreationCollectDeleteDir(2, &delete_dir_param);
684 IssueTestTokens();
685 InitializeForNthSync();
686 EXPECT_TRUE(service()->IsSyncActive());
687 EXPECT_EQ(ProfileSyncService::SYNC, service()->backend_mode());
689 // First sync time should be recorded.
690 sync_driver::SyncPrefs sync_prefs(service()->profile()->GetPrefs());
691 base::Time first_sync_time = sync_prefs.GetFirstSyncTime();
692 EXPECT_FALSE(first_sync_time.is_null());
694 syncer::SyncProtocolError client_cmd;
695 client_cmd.action = syncer::DISABLE_SYNC_AND_ROLLBACK;
696 service()->OnActionableError(client_cmd);
697 EXPECT_EQ(ProfileSyncService::IDLE, service()->backend_mode());
699 // Pump loop to run rollback.
700 PumpLoop();
701 EXPECT_EQ(ProfileSyncService::ROLLBACK, service()->backend_mode());
703 // Browser data should be cleared during rollback.
704 EXPECT_EQ(first_sync_time, clear_browsing_date_start_);
706 client_cmd.action = syncer::ROLLBACK_DONE;
707 service()->OnActionableError(client_cmd);
708 EXPECT_EQ(ProfileSyncService::IDLE, service()->backend_mode());
710 // First sync time is erased after rollback is done.
711 EXPECT_TRUE(sync_prefs.GetFirstSyncTime().is_null());
713 EXPECT_EQ(2u, delete_dir_param.size());
714 EXPECT_FALSE(delete_dir_param[0]);
715 EXPECT_FALSE(delete_dir_param[1]);
718 #endif
720 // Verify that LastSyncedTime is cleared when the user signs out.
721 TEST_F(ProfileSyncServiceTest, ClearLastSyncedTimeOnSignOut) {
722 IssueTestTokens();
723 CreateService(AUTO_START);
724 ExpectDataTypeManagerCreation(1, GetDefaultConfigureCalledCallback());
725 ExpectSyncBackendHostCreation(1);
726 InitializeForNthSync();
727 EXPECT_TRUE(service()->IsSyncActive());
728 EXPECT_EQ(l10n_util::GetStringUTF16(IDS_SYNC_TIME_JUST_NOW),
729 service()->GetLastSyncedTimeString());
731 // Sign out.
732 service()->RequestStop(ProfileSyncService::CLEAR_DATA);
733 PumpLoop();
735 EXPECT_EQ(l10n_util::GetStringUTF16(IDS_SYNC_TIME_NEVER),
736 service()->GetLastSyncedTimeString());
739 // Verify that the disable sync flag disables sync.
740 TEST_F(ProfileSyncServiceTest, DisableSyncFlag) {
741 base::CommandLine::ForCurrentProcess()->AppendSwitch(switches::kDisableSync);
742 EXPECT_FALSE(ProfileSyncService::IsSyncAllowedByFlag());
745 // Verify that no disable sync flag enables sync.
746 TEST_F(ProfileSyncServiceTest, NoDisableSyncFlag) {
747 EXPECT_TRUE(ProfileSyncService::IsSyncAllowedByFlag());
750 // Test Sync will stop after receive memory pressure
751 TEST_F(ProfileSyncServiceTest, MemoryPressureRecording) {
752 CreateService(browser_sync::AUTO_START);
753 IssueTestTokens();
754 ExpectDataTypeManagerCreation(1, GetDefaultConfigureCalledCallback());
755 ExpectSyncBackendHostCreation(1);
756 InitializeForNthSync();
758 EXPECT_TRUE(service()->IsSyncActive());
759 EXPECT_FALSE(profile()->GetPrefs()->GetBoolean(
760 sync_driver::prefs::kSyncSuppressStart));
762 testing::Mock::VerifyAndClearExpectations(components_factory());
764 sync_driver::SyncPrefs sync_prefs(service()->profile()->GetPrefs());
766 EXPECT_EQ(profile()->GetPrefs()->GetInteger(
767 sync_driver::prefs::kSyncMemoryPressureWarningCount),
769 EXPECT_FALSE(sync_prefs.DidSyncShutdownCleanly());
771 // Simulate memory pressure notification.
772 base::MemoryPressureListener::NotifyMemoryPressure(
773 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL);
774 base::RunLoop().RunUntilIdle();
776 // Verify memory pressure recorded.
777 EXPECT_EQ(profile()->GetPrefs()->GetInteger(
778 sync_driver::prefs::kSyncMemoryPressureWarningCount),
780 EXPECT_FALSE(sync_prefs.DidSyncShutdownCleanly());
782 // Simulate memory pressure notification.
783 base::MemoryPressureListener::NotifyMemoryPressure(
784 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL);
785 base::RunLoop().RunUntilIdle();
786 ShutdownAndDeleteService();
788 // Verify memory pressure and shutdown recorded.
789 EXPECT_EQ(profile()->GetPrefs()->GetInteger(
790 sync_driver::prefs::kSyncMemoryPressureWarningCount),
792 EXPECT_TRUE(sync_prefs.DidSyncShutdownCleanly());
795 // Verify that OnLocalSetPassphraseEncryption triggers catch up configure sync
796 // cycle, calls ClearServerData, shuts down and restarts sync.
797 TEST_F(ProfileSyncServiceTest, OnLocalSetPassphraseEncryption) {
798 base::CommandLine::ForCurrentProcess()->AppendSwitch(
799 switches::kSyncEnableClearDataOnPassphraseEncryption);
800 IssueTestTokens();
801 CreateService(browser_sync::AUTO_START);
803 syncer::SyncManager::ClearServerDataCallback captured_callback;
804 syncer::ConfigureReason configure_reason = syncer::CONFIGURE_REASON_UNKNOWN;
806 // Initialize sync, ensure that both DataTypeManager and SyncBackendHost are
807 // initialized and DTM::Configure is called with
808 // CONFIGURE_REASON_NEWLY_ENABLED_DATA_TYPE.
809 ExpectSyncBackendHostCreationCaptureClearServerData(&captured_callback);
810 ExpectDataTypeManagerCreation(
811 1, GetRecordingConfigureCalledCallback(&configure_reason));
812 InitializeForNthSync();
813 EXPECT_TRUE(service()->IsSyncActive());
814 EXPECT_EQ(ProfileSyncService::SYNC, service()->backend_mode());
815 testing::Mock::VerifyAndClearExpectations(components_factory());
816 EXPECT_EQ(syncer::CONFIGURE_REASON_NEWLY_ENABLED_DATA_TYPE, configure_reason);
817 sync_driver::DataTypeManager::ConfigureResult result;
818 result.status = sync_driver::DataTypeManager::OK;
819 service()->OnConfigureDone(result);
821 // Simulate user entering encryption passphrase. Ensure that catch up
822 // configure cycle is started (DTM::Configure is called with
823 // CONFIGURE_REASON_CATCH_UP).
824 const syncer::SyncEncryptionHandler::NigoriState nigori_state;
825 service()->OnLocalSetPassphraseEncryption(nigori_state);
826 EXPECT_EQ(syncer::CONFIGURE_REASON_CATCH_UP, configure_reason);
827 EXPECT_TRUE(captured_callback.is_null());
829 // Simulate configure successful. Ensure that SBH::ClearServerData is called.
830 service()->OnConfigureDone(result);
831 EXPECT_FALSE(captured_callback.is_null());
833 // Once SBH::ClearServerData finishes successfully ensure that sync is
834 // restarted.
835 configure_reason = syncer::CONFIGURE_REASON_UNKNOWN;
836 ExpectSyncBackendHostCreation(1);
837 ExpectDataTypeManagerCreation(
838 1, GetRecordingConfigureCalledCallback(&configure_reason));
839 captured_callback.Run();
840 testing::Mock::VerifyAndClearExpectations(components_factory());
841 EXPECT_EQ(syncer::CONFIGURE_REASON_NEWLY_ENABLED_DATA_TYPE, configure_reason);
842 service()->OnConfigureDone(result);
845 // Verify that if after OnLocalSetPassphraseEncryption catch up configure sync
846 // cycle gets interrupted, it starts again after browser restart.
847 TEST_F(ProfileSyncServiceTest,
848 OnLocalSetPassphraseEncryption_RestartDuringCatchUp) {
849 syncer::ConfigureReason configure_reason = syncer::CONFIGURE_REASON_UNKNOWN;
850 base::CommandLine::ForCurrentProcess()->AppendSwitch(
851 switches::kSyncEnableClearDataOnPassphraseEncryption);
852 IssueTestTokens();
853 CreateService(browser_sync::AUTO_START);
854 ExpectSyncBackendHostCreation(1);
855 ExpectDataTypeManagerCreation(
856 1, GetRecordingConfigureCalledCallback(&configure_reason));
857 InitializeForNthSync();
858 EXPECT_EQ(ProfileSyncService::SYNC, service()->backend_mode());
859 testing::Mock::VerifyAndClearExpectations(components_factory());
860 EXPECT_EQ(syncer::CONFIGURE_REASON_NEWLY_ENABLED_DATA_TYPE, configure_reason);
861 sync_driver::DataTypeManager::ConfigureResult result;
862 result.status = sync_driver::DataTypeManager::OK;
863 service()->OnConfigureDone(result);
865 // Simulate user entering encryption passphrase. Ensure Configure was called
866 // but don't let it continue.
867 const syncer::SyncEncryptionHandler::NigoriState nigori_state;
868 service()->OnLocalSetPassphraseEncryption(nigori_state);
869 EXPECT_EQ(syncer::CONFIGURE_REASON_CATCH_UP, configure_reason);
871 // Simulate browser restart. First configuration is a regular one.
872 service()->Shutdown();
873 syncer::SyncManager::ClearServerDataCallback captured_callback;
874 ExpectSyncBackendHostCreationCaptureClearServerData(&captured_callback);
875 ExpectDataTypeManagerCreation(
876 1, GetRecordingConfigureCalledCallback(&configure_reason));
877 service()->RequestStart();
878 testing::Mock::VerifyAndClearExpectations(components_factory());
879 EXPECT_EQ(syncer::CONFIGURE_REASON_NEWLY_ENABLED_DATA_TYPE, configure_reason);
880 EXPECT_TRUE(captured_callback.is_null());
882 // Simulate configure successful. This time it should be catch up.
883 service()->OnConfigureDone(result);
884 EXPECT_EQ(syncer::CONFIGURE_REASON_CATCH_UP, configure_reason);
885 EXPECT_TRUE(captured_callback.is_null());
887 // Simulate catch up configure successful. Ensure that SBH::ClearServerData is
888 // called.
889 service()->OnConfigureDone(result);
890 EXPECT_FALSE(captured_callback.is_null());
892 ExpectSyncBackendHostCreation(1);
893 ExpectDataTypeManagerCreation(
894 1, GetRecordingConfigureCalledCallback(&configure_reason));
895 captured_callback.Run();
896 testing::Mock::VerifyAndClearExpectations(components_factory());
897 EXPECT_EQ(syncer::CONFIGURE_REASON_NEWLY_ENABLED_DATA_TYPE, configure_reason);
900 // Verify that if after OnLocalSetPassphraseEncryption ClearServerData gets
901 // interrupted, transition again from catch up sync cycle after browser restart.
902 TEST_F(ProfileSyncServiceTest,
903 OnLocalSetPassphraseEncryption_RestartDuringClearServerData) {
904 syncer::SyncManager::ClearServerDataCallback captured_callback;
905 syncer::ConfigureReason configure_reason = syncer::CONFIGURE_REASON_UNKNOWN;
906 base::CommandLine::ForCurrentProcess()->AppendSwitch(
907 switches::kSyncEnableClearDataOnPassphraseEncryption);
908 IssueTestTokens();
909 CreateService(browser_sync::AUTO_START);
910 ExpectSyncBackendHostCreationCaptureClearServerData(&captured_callback);
911 ExpectDataTypeManagerCreation(1, GetDefaultConfigureCalledCallback());
912 InitializeForNthSync();
913 EXPECT_EQ(ProfileSyncService::SYNC, service()->backend_mode());
914 testing::Mock::VerifyAndClearExpectations(components_factory());
916 // Simulate user entering encryption passphrase.
917 const syncer::SyncEncryptionHandler::NigoriState nigori_state;
918 service()->OnLocalSetPassphraseEncryption(nigori_state);
919 EXPECT_FALSE(captured_callback.is_null());
920 captured_callback.Reset();
922 // Simulate browser restart. First configuration is a regular one.
923 service()->Shutdown();
924 ExpectSyncBackendHostCreationCaptureClearServerData(&captured_callback);
925 ExpectDataTypeManagerCreation(
926 1, GetRecordingConfigureCalledCallback(&configure_reason));
927 service()->RequestStart();
928 testing::Mock::VerifyAndClearExpectations(components_factory());
929 EXPECT_EQ(syncer::CONFIGURE_REASON_NEWLY_ENABLED_DATA_TYPE, configure_reason);
930 EXPECT_TRUE(captured_callback.is_null());
932 // Simulate configure successful. This time it should be catch up.
933 sync_driver::DataTypeManager::ConfigureResult result;
934 result.status = sync_driver::DataTypeManager::OK;
935 service()->OnConfigureDone(result);
936 EXPECT_EQ(syncer::CONFIGURE_REASON_CATCH_UP, configure_reason);
937 EXPECT_TRUE(captured_callback.is_null());
939 // Simulate catch up configure successful. Ensure that SBH::ClearServerData is
940 // called.
941 service()->OnConfigureDone(result);
942 EXPECT_FALSE(captured_callback.is_null());
944 ExpectSyncBackendHostCreation(1);
945 ExpectDataTypeManagerCreation(
946 1, GetRecordingConfigureCalledCallback(&configure_reason));
947 captured_callback.Run();
948 testing::Mock::VerifyAndClearExpectations(components_factory());
949 EXPECT_EQ(syncer::CONFIGURE_REASON_NEWLY_ENABLED_DATA_TYPE, configure_reason);
952 // Test that the passphrase prompt due to version change logic gets triggered
953 // on a datatype type requesting startup, but only happens once.
954 TEST_F(ProfileSyncServiceTest, PassphrasePromptDueToVersion) {
955 IssueTestTokens();
956 CreateService(browser_sync::AUTO_START);
957 ExpectDataTypeManagerCreation(1, GetDefaultConfigureCalledCallback());
958 ExpectSyncBackendHostCreation(1);
959 InitializeForNthSync();
961 sync_driver::SyncPrefs sync_prefs(service()->profile()->GetPrefs());
962 EXPECT_EQ(PRODUCT_VERSION, sync_prefs.GetLastRunVersion());
964 sync_prefs.SetPassphrasePrompted(true);
966 // Until a datatype requests startup while a passphrase is required the
967 // passphrase prompt bit should remain set.
968 EXPECT_TRUE(sync_prefs.IsPassphrasePrompted());
969 TriggerPassphraseRequired();
970 EXPECT_TRUE(sync_prefs.IsPassphrasePrompted());
972 // Because the last version was unset, this run should be treated as a new
973 // version and force a prompt.
974 TriggerDataTypeStartRequest();
975 EXPECT_FALSE(sync_prefs.IsPassphrasePrompted());
977 // At this point further datatype startup request should have no effect.
978 sync_prefs.SetPassphrasePrompted(true);
979 TriggerDataTypeStartRequest();
980 EXPECT_TRUE(sync_prefs.IsPassphrasePrompted());
983 } // namespace
984 } // namespace browser_sync