[Cleanup] Used scoped pointers in KeyedServiceFactory's SetTestingFactory functions.
[chromium-blink-merge.git] / chrome / browser / sync / profile_sync_service_unittest.cc
blobd738304aad4834d2d2fcd4c66aff9ce94bc2f8f0
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/command_line.h"
7 #include "base/compiler_specific.h"
8 #include "base/memory/scoped_ptr.h"
9 #include "base/run_loop.h"
10 #include "base/strings/string_number_conversions.h"
11 #include "base/strings/utf_string_conversions.h"
12 #include "base/values.h"
13 #include "chrome/browser/invalidation/fake_invalidation_service.h"
14 #include "chrome/browser/invalidation/profile_invalidation_provider_factory.h"
15 #include "chrome/browser/signin/account_tracker_service_factory.h"
16 #include "chrome/browser/signin/fake_profile_oauth2_token_service.h"
17 #include "chrome/browser/signin/fake_profile_oauth2_token_service_builder.h"
18 #include "chrome/browser/signin/profile_oauth2_token_service_factory.h"
19 #include "chrome/browser/signin/signin_manager_factory.h"
20 #include "chrome/browser/sync/glue/sync_backend_host_mock.h"
21 #include "chrome/browser/sync/profile_sync_components_factory_mock.h"
22 #include "chrome/browser/sync/supervised_user_signin_manager_wrapper.h"
23 #include "chrome/common/chrome_switches.h"
24 #include "chrome/common/pref_names.h"
25 #include "chrome/grit/generated_resources.h"
26 #include "chrome/test/base/testing_browser_process.h"
27 #include "chrome/test/base/testing_pref_service_syncable.h"
28 #include "chrome/test/base/testing_profile.h"
29 #include "chrome/test/base/testing_profile_manager.h"
30 #include "components/invalidation/invalidation_service.h"
31 #include "components/invalidation/profile_invalidation_provider.h"
32 #include "components/signin/core/browser/account_tracker_service.h"
33 #include "components/signin/core/browser/signin_manager.h"
34 #include "components/signin/core/browser/signin_manager.h"
35 #include "components/sync_driver/data_type_manager.h"
36 #include "components/sync_driver/pref_names.h"
37 #include "components/sync_driver/sync_prefs.h"
38 #include "content/public/test/test_browser_thread_bundle.h"
39 #include "google_apis/gaia/gaia_constants.h"
40 #include "testing/gmock/include/gmock/gmock.h"
41 #include "testing/gtest/include/gtest/gtest.h"
42 #include "ui/base/l10n/l10n_util.h"
44 namespace content {
45 class BrowserContext;
48 namespace browser_sync {
50 namespace {
52 const char kGaiaId[] = "12345";
53 const char kEmail[] = "test_user@gmail.com";
55 class FakeDataTypeManager : public sync_driver::DataTypeManager {
56 public:
57 explicit FakeDataTypeManager(sync_driver::DataTypeManagerObserver* observer)
58 : observer_(observer) {}
59 ~FakeDataTypeManager() override{};
61 void Configure(syncer::ModelTypeSet desired_types,
62 syncer::ConfigureReason reason) override {
63 sync_driver::DataTypeManager::ConfigureResult result;
64 result.status = sync_driver::DataTypeManager::OK;
65 observer_->OnConfigureDone(result);
68 void ReenableType(syncer::ModelType type) override {}
69 void ResetDataTypeErrors() override {}
70 void PurgeForMigration(syncer::ModelTypeSet undesired_types,
71 syncer::ConfigureReason reason) override {}
72 void Stop() override{};
73 State state() const override {
74 return sync_driver::DataTypeManager::CONFIGURED;
77 private:
78 sync_driver::DataTypeManagerObserver* observer_;
81 ACTION(ReturnNewDataTypeManager) {
82 return new FakeDataTypeManager(arg4);
85 using testing::Return;
86 using testing::StrictMock;
87 using testing::_;
89 class TestSyncServiceObserver : public sync_driver::SyncServiceObserver {
90 public:
91 explicit TestSyncServiceObserver(ProfileSyncService* service)
92 : service_(service), first_setup_in_progress_(false) {}
93 void OnStateChanged() override {
94 first_setup_in_progress_ = service_->FirstSetupInProgress();
96 bool first_setup_in_progress() const { return first_setup_in_progress_; }
97 private:
98 ProfileSyncService* service_;
99 bool first_setup_in_progress_;
102 // A variant of the SyncBackendHostMock that won't automatically
103 // call back when asked to initialized. Allows us to test things
104 // that could happen while backend init is in progress.
105 class SyncBackendHostNoReturn : public SyncBackendHostMock {
106 void Initialize(
107 sync_driver::SyncFrontend* frontend,
108 scoped_ptr<base::Thread> sync_thread,
109 const syncer::WeakHandle<syncer::JsEventHandler>& event_handler,
110 const GURL& service_url,
111 const syncer::SyncCredentials& credentials,
112 bool delete_sync_data_folder,
113 scoped_ptr<syncer::SyncManagerFactory> sync_manager_factory,
114 scoped_ptr<syncer::UnrecoverableErrorHandler> unrecoverable_error_handler,
115 const base::Closure& report_unrecoverable_error_function,
116 syncer::NetworkResources* network_resources) override {}
119 class SyncBackendHostMockCollectDeleteDirParam : public SyncBackendHostMock {
120 public:
121 explicit SyncBackendHostMockCollectDeleteDirParam(
122 std::vector<bool>* delete_dir_param)
123 : delete_dir_param_(delete_dir_param) {}
125 void Initialize(
126 sync_driver::SyncFrontend* frontend,
127 scoped_ptr<base::Thread> sync_thread,
128 const syncer::WeakHandle<syncer::JsEventHandler>& event_handler,
129 const GURL& service_url,
130 const syncer::SyncCredentials& credentials,
131 bool delete_sync_data_folder,
132 scoped_ptr<syncer::SyncManagerFactory> sync_manager_factory,
133 scoped_ptr<syncer::UnrecoverableErrorHandler> unrecoverable_error_handler,
134 const base::Closure& report_unrecoverable_error_function,
135 syncer::NetworkResources* network_resources) override {
136 delete_dir_param_->push_back(delete_sync_data_folder);
137 SyncBackendHostMock::Initialize(frontend, sync_thread.Pass(),
138 event_handler, service_url, credentials,
139 delete_sync_data_folder,
140 sync_manager_factory.Pass(),
141 unrecoverable_error_handler.Pass(),
142 report_unrecoverable_error_function,
143 network_resources);
146 private:
147 std::vector<bool>* delete_dir_param_;
150 ACTION(ReturnNewSyncBackendHostMock) {
151 return new browser_sync::SyncBackendHostMock();
154 ACTION(ReturnNewSyncBackendHostNoReturn) {
155 return new browser_sync::SyncBackendHostNoReturn();
158 ACTION_P(ReturnNewMockHostCollectDeleteDirParam, delete_dir_param) {
159 return new browser_sync::SyncBackendHostMockCollectDeleteDirParam(
160 delete_dir_param);
163 scoped_ptr<KeyedService> BuildFakeProfileInvalidationProvider(
164 content::BrowserContext* context) {
165 return make_scoped_ptr(new invalidation::ProfileInvalidationProvider(
166 scoped_ptr<invalidation::InvalidationService>(
167 new invalidation::FakeInvalidationService)));
170 // A test harness that uses a real ProfileSyncService and in most cases a
171 // MockSyncBackendHost.
173 // This is useful if we want to test the ProfileSyncService and don't care about
174 // testing the SyncBackendHost.
175 class ProfileSyncServiceTest : public ::testing::Test {
176 protected:
177 ProfileSyncServiceTest()
178 : thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP),
179 profile_manager_(TestingBrowserProcess::GetGlobal()) {}
180 ~ProfileSyncServiceTest() override {}
182 void SetUp() override {
183 base::CommandLine::ForCurrentProcess()->AppendSwitchASCII(
184 switches::kSyncDeferredStartupTimeoutSeconds, "0");
186 CHECK(profile_manager_.SetUp());
188 TestingProfile::TestingFactories testing_facotries;
189 testing_facotries.push_back(
190 std::make_pair(ProfileOAuth2TokenServiceFactory::GetInstance(),
191 BuildAutoIssuingFakeProfileOAuth2TokenService));
192 testing_facotries.push_back(
193 std::make_pair(
194 invalidation::ProfileInvalidationProviderFactory::GetInstance(),
195 BuildFakeProfileInvalidationProvider));
197 profile_ = profile_manager_.CreateTestingProfile(
198 "sync-service-test", scoped_ptr<PrefServiceSyncable>(),
199 base::UTF8ToUTF16("sync-service-test"), 0, std::string(),
200 testing_facotries);
203 void TearDown() override {
204 // Kill the service before the profile.
205 if (service_)
206 service_->Shutdown();
208 service_.reset();
211 void IssueTestTokens() {
212 std::string account_id =
213 AccountTrackerServiceFactory::GetForProfile(profile_)
214 ->SeedAccountInfo(kGaiaId, kEmail);
215 ProfileOAuth2TokenServiceFactory::GetForProfile(profile_)
216 ->UpdateCredentials(account_id, "oauth2_login_token");
219 void CreateService(ProfileSyncServiceStartBehavior behavior) {
220 SigninManagerBase* signin =
221 SigninManagerFactory::GetForProfile(profile_);
222 signin->SetAuthenticatedAccountInfo(kGaiaId, kEmail);
223 ProfileOAuth2TokenService* oauth2_token_service =
224 ProfileOAuth2TokenServiceFactory::GetForProfile(profile_);
225 components_factory_ = new ProfileSyncComponentsFactoryMock();
226 service_.reset(new ProfileSyncService(
227 scoped_ptr<ProfileSyncComponentsFactory>(components_factory_),
228 profile_,
229 make_scoped_ptr(new SupervisedUserSigninManagerWrapper(profile_,
230 signin)),
231 oauth2_token_service,
232 behavior));
233 service_->SetClearingBrowseringDataForTesting(
234 base::Bind(&ProfileSyncServiceTest::ClearBrowsingDataCallback,
235 base::Unretained(this)));
238 #if defined(OS_WIN) || defined(OS_MACOSX) || (defined(OS_LINUX) && !defined(OS_CHROMEOS))
239 void CreateServiceWithoutSignIn() {
240 CreateService(browser_sync::AUTO_START);
241 SigninManagerFactory::GetForProfile(profile())->SignOut(
242 signin_metrics::SIGNOUT_TEST);
244 #endif
246 void ShutdownAndDeleteService() {
247 if (service_)
248 service_->Shutdown();
249 service_.reset();
252 void InitializeForNthSync() {
253 // Set first sync time before initialize to disable backup.
254 sync_driver::SyncPrefs sync_prefs(service()->profile()->GetPrefs());
255 sync_prefs.SetFirstSyncTime(base::Time::Now());
256 service_->Initialize();
259 void InitializeForFirstSync() {
260 service_->Initialize();
263 void ExpectDataTypeManagerCreation(int times) {
264 EXPECT_CALL(*components_factory_, CreateDataTypeManager(_, _, _, _, _))
265 .Times(times)
266 .WillRepeatedly(ReturnNewDataTypeManager());
269 void ExpectSyncBackendHostCreation(int times) {
270 EXPECT_CALL(*components_factory_, CreateSyncBackendHost(_, _, _, _, _))
271 .Times(times)
272 .WillRepeatedly(ReturnNewSyncBackendHostMock());
275 void ExpectSyncBackendHostCreationCollectDeleteDir(
276 int times, std::vector<bool> *delete_dir_param) {
277 EXPECT_CALL(*components_factory_, CreateSyncBackendHost(_, _, _, _, _))
278 .Times(times)
279 .WillRepeatedly(ReturnNewMockHostCollectDeleteDirParam(
280 delete_dir_param));
283 void PrepareDelayedInitSyncBackendHost() {
284 EXPECT_CALL(*components_factory_, CreateSyncBackendHost(_, _, _, _, _)).
285 WillOnce(ReturnNewSyncBackendHostNoReturn());
288 TestingProfile* profile() {
289 return profile_;
292 ProfileSyncService* service() {
293 return service_.get();
296 ProfileSyncComponentsFactoryMock* components_factory() {
297 return components_factory_;
300 void ClearBrowsingDataCallback(BrowsingDataRemover::Observer* observer,
301 Profile* profile,
302 base::Time start,
303 base::Time end) {
304 EXPECT_EQ(profile_, profile);
305 clear_browsing_date_start_ = start;
308 protected:
309 void PumpLoop() {
310 base::RunLoop run_loop;
311 base::MessageLoop::current()->PostTask(
312 FROM_HERE, run_loop.QuitClosure());
313 run_loop.Run();
316 // The requested start time when ClearBrowsingDataCallback is called.
317 base::Time clear_browsing_date_start_;
319 private:
320 content::TestBrowserThreadBundle thread_bundle_;
321 TestingProfileManager profile_manager_;
322 TestingProfile* profile_;
323 scoped_ptr<ProfileSyncService> service_;
325 // Pointer to the components factory. Not owned. May be null.
326 ProfileSyncComponentsFactoryMock* components_factory_;
329 // Verify that the server URLs are sane.
330 TEST_F(ProfileSyncServiceTest, InitialState) {
331 CreateService(browser_sync::AUTO_START);
332 InitializeForNthSync();
333 const std::string& url = service()->sync_service_url().spec();
334 EXPECT_TRUE(url == ProfileSyncService::kSyncServerUrl ||
335 url == ProfileSyncService::kDevServerUrl);
338 // Verify a successful initialization.
339 TEST_F(ProfileSyncServiceTest, SuccessfulInitialization) {
340 profile()->GetTestingPrefService()->SetManagedPref(
341 sync_driver::prefs::kSyncManaged, new base::FundamentalValue(false));
342 IssueTestTokens();
343 CreateService(browser_sync::AUTO_START);
344 ExpectDataTypeManagerCreation(1);
345 ExpectSyncBackendHostCreation(1);
346 InitializeForNthSync();
347 EXPECT_FALSE(service()->IsManaged());
348 EXPECT_TRUE(service()->IsSyncActive());
349 EXPECT_EQ(ProfileSyncService::SYNC, service()->backend_mode());
353 // Verify that the SetSetupInProgress function call updates state
354 // and notifies observers.
355 TEST_F(ProfileSyncServiceTest, SetupInProgress) {
356 CreateService(browser_sync::AUTO_START);
357 InitializeForNthSync();
359 TestSyncServiceObserver observer(service());
360 service()->AddObserver(&observer);
362 service()->SetSetupInProgress(true);
363 EXPECT_TRUE(observer.first_setup_in_progress());
364 service()->SetSetupInProgress(false);
365 EXPECT_FALSE(observer.first_setup_in_progress());
367 service()->RemoveObserver(&observer);
370 // Verify that disable by enterprise policy works.
371 TEST_F(ProfileSyncServiceTest, DisabledByPolicyBeforeInit) {
372 profile()->GetTestingPrefService()->SetManagedPref(
373 sync_driver::prefs::kSyncManaged, new base::FundamentalValue(true));
374 IssueTestTokens();
375 CreateService(browser_sync::AUTO_START);
376 InitializeForNthSync();
377 EXPECT_TRUE(service()->IsManaged());
378 EXPECT_FALSE(service()->IsSyncActive());
381 // Verify that disable by enterprise policy works even after the backend has
382 // been initialized.
383 TEST_F(ProfileSyncServiceTest, DisabledByPolicyAfterInit) {
384 IssueTestTokens();
385 CreateService(browser_sync::AUTO_START);
386 ExpectDataTypeManagerCreation(1);
387 ExpectSyncBackendHostCreation(1);
388 InitializeForNthSync();
390 EXPECT_FALSE(service()->IsManaged());
391 EXPECT_TRUE(service()->IsSyncActive());
393 profile()->GetTestingPrefService()->SetManagedPref(
394 sync_driver::prefs::kSyncManaged, new base::FundamentalValue(true));
396 EXPECT_TRUE(service()->IsManaged());
397 EXPECT_FALSE(service()->IsSyncActive());
400 // Exercies the ProfileSyncService's code paths related to getting shut down
401 // before the backend initialize call returns.
402 TEST_F(ProfileSyncServiceTest, AbortedByShutdown) {
403 CreateService(browser_sync::AUTO_START);
404 PrepareDelayedInitSyncBackendHost();
406 IssueTestTokens();
407 InitializeForNthSync();
408 EXPECT_FALSE(service()->IsSyncActive());
410 ShutdownAndDeleteService();
413 // Test RequestStop() before we've initialized the backend.
414 TEST_F(ProfileSyncServiceTest, EarlyRequestStop) {
415 CreateService(browser_sync::AUTO_START);
416 IssueTestTokens();
418 service()->RequestStop();
419 EXPECT_TRUE(profile()->GetPrefs()->GetBoolean(
420 sync_driver::prefs::kSyncSuppressStart));
422 // Because of supression, this should fail.
423 InitializeForNthSync();
424 EXPECT_FALSE(service()->IsSyncActive());
426 // Remove suppression. This should be enough to allow init to happen.
427 ExpectDataTypeManagerCreation(1);
428 ExpectSyncBackendHostCreation(1);
429 service()->RequestStart();
430 EXPECT_TRUE(service()->IsSyncActive());
431 EXPECT_FALSE(profile()->GetPrefs()->GetBoolean(
432 sync_driver::prefs::kSyncSuppressStart));
435 // Test RequestStop() after we've initialized the backend.
436 TEST_F(ProfileSyncServiceTest, DisableAndEnableSyncTemporarily) {
437 CreateService(browser_sync::AUTO_START);
438 IssueTestTokens();
439 ExpectDataTypeManagerCreation(1);
440 ExpectSyncBackendHostCreation(1);
441 InitializeForNthSync();
443 EXPECT_TRUE(service()->IsSyncActive());
444 EXPECT_FALSE(profile()->GetPrefs()->GetBoolean(
445 sync_driver::prefs::kSyncSuppressStart));
447 testing::Mock::VerifyAndClearExpectations(components_factory());
449 service()->RequestStop();
450 EXPECT_FALSE(service()->IsSyncActive());
451 EXPECT_TRUE(profile()->GetPrefs()->GetBoolean(
452 sync_driver::prefs::kSyncSuppressStart));
454 ExpectDataTypeManagerCreation(1);
455 ExpectSyncBackendHostCreation(1);
457 service()->RequestStart();
458 EXPECT_TRUE(service()->IsSyncActive());
459 EXPECT_FALSE(profile()->GetPrefs()->GetBoolean(
460 sync_driver::prefs::kSyncSuppressStart));
463 // Certain ProfileSyncService tests don't apply to Chrome OS, for example
464 // things that deal with concepts like "signing out" and policy.
465 #if !defined (OS_CHROMEOS)
466 TEST_F(ProfileSyncServiceTest, EnableSyncAndSignOut) {
467 CreateService(browser_sync::AUTO_START);
468 ExpectDataTypeManagerCreation(1);
469 ExpectSyncBackendHostCreation(1);
470 IssueTestTokens();
471 InitializeForNthSync();
473 EXPECT_TRUE(service()->IsSyncActive());
474 EXPECT_FALSE(profile()->GetPrefs()->GetBoolean(
475 sync_driver::prefs::kSyncSuppressStart));
477 SigninManagerFactory::GetForProfile(profile())->SignOut(
478 signin_metrics::SIGNOUT_TEST);
479 EXPECT_FALSE(service()->IsSyncActive());
481 #endif // !defined(OS_CHROMEOS)
483 TEST_F(ProfileSyncServiceTest, GetSyncTokenStatus) {
484 CreateService(browser_sync::AUTO_START);
485 IssueTestTokens();
486 ExpectDataTypeManagerCreation(1);
487 ExpectSyncBackendHostCreation(1);
488 InitializeForNthSync();
490 // Initial status.
491 ProfileSyncService::SyncTokenStatus token_status =
492 service()->GetSyncTokenStatus();
493 EXPECT_EQ(syncer::CONNECTION_NOT_ATTEMPTED, token_status.connection_status);
494 EXPECT_TRUE(token_status.connection_status_update_time.is_null());
495 EXPECT_TRUE(token_status.token_request_time.is_null());
496 EXPECT_TRUE(token_status.token_receive_time.is_null());
498 // Simulate an auth error.
499 service()->OnConnectionStatusChange(syncer::CONNECTION_AUTH_ERROR);
501 // The token request will take the form of a posted task. Run it.
502 base::RunLoop loop;
503 loop.RunUntilIdle();
505 token_status = service()->GetSyncTokenStatus();
506 EXPECT_EQ(syncer::CONNECTION_AUTH_ERROR, token_status.connection_status);
507 EXPECT_FALSE(token_status.connection_status_update_time.is_null());
508 EXPECT_FALSE(token_status.token_request_time.is_null());
509 EXPECT_FALSE(token_status.token_receive_time.is_null());
510 EXPECT_EQ(GoogleServiceAuthError::AuthErrorNone(),
511 token_status.last_get_token_error);
512 EXPECT_TRUE(token_status.next_token_request_time.is_null());
514 // Simulate successful connection.
515 service()->OnConnectionStatusChange(syncer::CONNECTION_OK);
516 token_status = service()->GetSyncTokenStatus();
517 EXPECT_EQ(syncer::CONNECTION_OK, token_status.connection_status);
520 #if defined(ENABLE_PRE_SYNC_BACKUP)
521 TEST_F(ProfileSyncServiceTest, DontStartBackupOnBrowserStart) {
522 CreateServiceWithoutSignIn();
523 InitializeForFirstSync();
524 PumpLoop();
525 EXPECT_EQ(ProfileSyncService::IDLE, service()->backend_mode());
528 TEST_F(ProfileSyncServiceTest, BackupBeforeFirstSync) {
529 CreateServiceWithoutSignIn();
530 ExpectDataTypeManagerCreation(2);
531 std::vector<bool> delete_dir_param;
532 ExpectSyncBackendHostCreationCollectDeleteDir(2, &delete_dir_param);
533 InitializeForFirstSync();
535 SigninManagerFactory::GetForProfile(profile())
536 ->SetAuthenticatedAccountInfo(kGaiaId, kEmail);
537 IssueTestTokens();
538 PumpLoop();
540 // At this time, backup is finished. Task is posted to start sync again.
541 EXPECT_EQ(ProfileSyncService::BACKUP, service()->backend_mode());
542 EXPECT_FALSE(service()->IsSyncActive());
543 EXPECT_EQ(1u, delete_dir_param.size());
544 EXPECT_TRUE(delete_dir_param[0]);
546 // Pump loop to start sync.
547 PumpLoop();
548 EXPECT_EQ(ProfileSyncService::SYNC, service()->backend_mode());
549 EXPECT_TRUE(service()->IsSyncActive());
550 EXPECT_EQ(2u, delete_dir_param.size());
551 EXPECT_TRUE(delete_dir_param[0]);
554 // Test backup is done again on browser start if user signed in last session
555 // but backup didn't finish when last session was closed.
556 TEST_F(ProfileSyncServiceTest, ResumeBackupIfAborted) {
557 IssueTestTokens();
558 CreateService(AUTO_START);
559 ExpectDataTypeManagerCreation(2);
560 std::vector<bool> delete_dir_param;
561 ExpectSyncBackendHostCreationCollectDeleteDir(2, &delete_dir_param);
562 InitializeForFirstSync();
563 PumpLoop();
565 // At this time, backup is finished. Task is posted to start sync again.
566 EXPECT_EQ(ProfileSyncService::BACKUP, service()->backend_mode());
567 EXPECT_FALSE(service()->IsSyncActive());
568 EXPECT_EQ(1u, delete_dir_param.size());
569 EXPECT_TRUE(delete_dir_param[0]);
571 // Pump loop to start sync.
572 PumpLoop();
573 EXPECT_EQ(ProfileSyncService::SYNC, service()->backend_mode());
574 EXPECT_TRUE(service()->IsSyncActive());
575 EXPECT_EQ(2u, delete_dir_param.size());
576 EXPECT_TRUE(delete_dir_param[0]);
579 TEST_F(ProfileSyncServiceTest, Rollback) {
580 CreateService(browser_sync::MANUAL_START);
581 service()->SetSyncSetupCompleted();
582 ExpectDataTypeManagerCreation(2);
583 std::vector<bool> delete_dir_param;
584 ExpectSyncBackendHostCreationCollectDeleteDir(2, &delete_dir_param);
585 IssueTestTokens();
586 InitializeForNthSync();
587 EXPECT_TRUE(service()->IsSyncActive());
588 EXPECT_EQ(ProfileSyncService::SYNC, service()->backend_mode());
590 // First sync time should be recorded.
591 sync_driver::SyncPrefs sync_prefs(service()->profile()->GetPrefs());
592 base::Time first_sync_time = sync_prefs.GetFirstSyncTime();
593 EXPECT_FALSE(first_sync_time.is_null());
595 syncer::SyncProtocolError client_cmd;
596 client_cmd.action = syncer::DISABLE_SYNC_AND_ROLLBACK;
597 service()->OnActionableError(client_cmd);
598 EXPECT_EQ(ProfileSyncService::IDLE, service()->backend_mode());
600 // Pump loop to run rollback.
601 PumpLoop();
602 EXPECT_EQ(ProfileSyncService::ROLLBACK, service()->backend_mode());
604 // Browser data should be cleared during rollback.
605 EXPECT_EQ(first_sync_time, clear_browsing_date_start_);
607 client_cmd.action = syncer::ROLLBACK_DONE;
608 service()->OnActionableError(client_cmd);
609 EXPECT_EQ(ProfileSyncService::IDLE, service()->backend_mode());
611 // First sync time is erased after rollback is done.
612 EXPECT_TRUE(sync_prefs.GetFirstSyncTime().is_null());
614 EXPECT_EQ(2u, delete_dir_param.size());
615 EXPECT_FALSE(delete_dir_param[0]);
616 EXPECT_FALSE(delete_dir_param[1]);
619 #endif
621 TEST_F(ProfileSyncServiceTest, GetSyncServiceURL) {
622 // See that we can override the URL with a flag.
623 base::CommandLine command_line(
624 base::FilePath(base::FilePath(FILE_PATH_LITERAL("chrome.exe"))));
625 command_line.AppendSwitchASCII(switches::kSyncServiceURL, "https://foo/bar");
626 EXPECT_EQ("https://foo/bar",
627 ProfileSyncService::GetSyncServiceURL(command_line).spec());
630 // Verify that LastSyncedTime is cleared when the user signs out.
631 TEST_F(ProfileSyncServiceTest, ClearLastSyncedTimeOnSignOut) {
632 IssueTestTokens();
633 CreateService(AUTO_START);
634 ExpectDataTypeManagerCreation(1);
635 ExpectSyncBackendHostCreation(1);
636 InitializeForNthSync();
637 EXPECT_TRUE(service()->IsSyncActive());
638 EXPECT_EQ(l10n_util::GetStringUTF16(IDS_SYNC_TIME_JUST_NOW),
639 service()->GetLastSyncedTimeString());
641 // Sign out.
642 service()->DisableForUser();
643 PumpLoop();
645 EXPECT_EQ(l10n_util::GetStringUTF16(IDS_SYNC_TIME_NEVER),
646 service()->GetLastSyncedTimeString());
649 // Verify that the disable sync flag disables sync.
650 TEST_F(ProfileSyncServiceTest, DisableSyncFlag) {
651 base::CommandLine::ForCurrentProcess()->AppendSwitch(switches::kDisableSync);
652 EXPECT_FALSE(ProfileSyncService::IsSyncAllowedByFlag());
655 // Verify that no disable sync flag enables sync.
656 TEST_F(ProfileSyncServiceTest, NoDisableSyncFlag) {
657 EXPECT_TRUE(ProfileSyncService::IsSyncAllowedByFlag());
660 // Test Sync will stop after receive memory pressure
661 TEST_F(ProfileSyncServiceTest, MemoryPressureRecording) {
662 CreateService(browser_sync::AUTO_START);
663 IssueTestTokens();
664 ExpectDataTypeManagerCreation(1);
665 ExpectSyncBackendHostCreation(1);
666 InitializeForNthSync();
668 EXPECT_TRUE(service()->IsSyncActive());
669 EXPECT_FALSE(profile()->GetPrefs()->GetBoolean(
670 sync_driver::prefs::kSyncSuppressStart));
672 testing::Mock::VerifyAndClearExpectations(components_factory());
674 sync_driver::SyncPrefs sync_prefs(service()->profile()->GetPrefs());
676 EXPECT_EQ(profile()->GetPrefs()->GetInteger(
677 sync_driver::prefs::kSyncMemoryPressureWarningCount),
679 EXPECT_FALSE(sync_prefs.DidSyncShutdownCleanly());
681 // Simulate memory pressure notification.
682 base::MemoryPressureListener::NotifyMemoryPressure(
683 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL);
684 base::RunLoop().RunUntilIdle();
686 // Verify memory pressure recorded.
687 EXPECT_EQ(profile()->GetPrefs()->GetInteger(
688 sync_driver::prefs::kSyncMemoryPressureWarningCount),
690 EXPECT_FALSE(sync_prefs.DidSyncShutdownCleanly());
692 // Simulate memory pressure notification.
693 base::MemoryPressureListener::NotifyMemoryPressure(
694 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL);
695 base::RunLoop().RunUntilIdle();
696 ShutdownAndDeleteService();
698 // Verify memory pressure and shutdown recorded.
699 EXPECT_EQ(profile()->GetPrefs()->GetInteger(
700 sync_driver::prefs::kSyncMemoryPressureWarningCount),
702 EXPECT_TRUE(sync_prefs.DidSyncShutdownCleanly());
705 } // namespace
706 } // namespace browser_sync