[Sync] Rename PSS::IsSyncEnabled to PSS::IsSyncAllowedByFlag.
[chromium-blink-merge.git] / chrome / browser / sync / profile_sync_service_unittest.cc
blobd760297ba79eaa5c9c2c0df68059fa90db461eeb
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 syncer::ReportUnrecoverableErrorFunction
116 report_unrecoverable_error_function,
117 syncer::NetworkResources* network_resources) override {}
120 class SyncBackendHostMockCollectDeleteDirParam : public SyncBackendHostMock {
121 public:
122 explicit SyncBackendHostMockCollectDeleteDirParam(
123 std::vector<bool>* delete_dir_param)
124 : delete_dir_param_(delete_dir_param) {}
126 void Initialize(
127 sync_driver::SyncFrontend* frontend,
128 scoped_ptr<base::Thread> sync_thread,
129 const syncer::WeakHandle<syncer::JsEventHandler>& event_handler,
130 const GURL& service_url,
131 const syncer::SyncCredentials& credentials,
132 bool delete_sync_data_folder,
133 scoped_ptr<syncer::SyncManagerFactory> sync_manager_factory,
134 scoped_ptr<syncer::UnrecoverableErrorHandler> unrecoverable_error_handler,
135 syncer::ReportUnrecoverableErrorFunction
136 report_unrecoverable_error_function,
137 syncer::NetworkResources* network_resources) override {
138 delete_dir_param_->push_back(delete_sync_data_folder);
139 SyncBackendHostMock::Initialize(frontend, sync_thread.Pass(),
140 event_handler, service_url, credentials,
141 delete_sync_data_folder,
142 sync_manager_factory.Pass(),
143 unrecoverable_error_handler.Pass(),
144 report_unrecoverable_error_function,
145 network_resources);
148 private:
149 std::vector<bool>* delete_dir_param_;
152 ACTION(ReturnNewSyncBackendHostMock) {
153 return new browser_sync::SyncBackendHostMock();
156 ACTION(ReturnNewSyncBackendHostNoReturn) {
157 return new browser_sync::SyncBackendHostNoReturn();
160 ACTION_P(ReturnNewMockHostCollectDeleteDirParam, delete_dir_param) {
161 return new browser_sync::SyncBackendHostMockCollectDeleteDirParam(
162 delete_dir_param);
165 KeyedService* BuildFakeProfileInvalidationProvider(
166 content::BrowserContext* context) {
167 return new invalidation::ProfileInvalidationProvider(
168 scoped_ptr<invalidation::InvalidationService>(
169 new invalidation::FakeInvalidationService));
172 // A test harness that uses a real ProfileSyncService and in most cases a
173 // MockSyncBackendHost.
175 // This is useful if we want to test the ProfileSyncService and don't care about
176 // testing the SyncBackendHost.
177 class ProfileSyncServiceTest : public ::testing::Test {
178 protected:
179 ProfileSyncServiceTest()
180 : thread_bundle_(content::TestBrowserThreadBundle::IO_MAINLOOP),
181 profile_manager_(TestingBrowserProcess::GetGlobal()) {}
182 ~ProfileSyncServiceTest() override {}
184 void SetUp() override {
185 base::CommandLine::ForCurrentProcess()->AppendSwitchASCII(
186 switches::kSyncDeferredStartupTimeoutSeconds, "0");
188 CHECK(profile_manager_.SetUp());
190 TestingProfile::TestingFactories testing_facotries;
191 testing_facotries.push_back(
192 std::make_pair(ProfileOAuth2TokenServiceFactory::GetInstance(),
193 BuildAutoIssuingFakeProfileOAuth2TokenService));
194 testing_facotries.push_back(
195 std::make_pair(
196 invalidation::ProfileInvalidationProviderFactory::GetInstance(),
197 BuildFakeProfileInvalidationProvider));
199 profile_ = profile_manager_.CreateTestingProfile(
200 "sync-service-test", scoped_ptr<PrefServiceSyncable>(),
201 base::UTF8ToUTF16("sync-service-test"), 0, std::string(),
202 testing_facotries);
205 void TearDown() override {
206 // Kill the service before the profile.
207 if (service_)
208 service_->Shutdown();
210 service_.reset();
213 void IssueTestTokens() {
214 std::string account_id =
215 AccountTrackerServiceFactory::GetForProfile(profile_)
216 ->SeedAccountInfo(kGaiaId, kEmail);
217 ProfileOAuth2TokenServiceFactory::GetForProfile(profile_)
218 ->UpdateCredentials(account_id, "oauth2_login_token");
221 void CreateService(ProfileSyncServiceStartBehavior behavior) {
222 SigninManagerBase* signin =
223 SigninManagerFactory::GetForProfile(profile_);
224 signin->SetAuthenticatedAccountInfo(kGaiaId, kEmail);
225 ProfileOAuth2TokenService* oauth2_token_service =
226 ProfileOAuth2TokenServiceFactory::GetForProfile(profile_);
227 components_factory_ = new ProfileSyncComponentsFactoryMock();
228 service_.reset(new ProfileSyncService(
229 scoped_ptr<ProfileSyncComponentsFactory>(components_factory_),
230 profile_,
231 make_scoped_ptr(new SupervisedUserSigninManagerWrapper(profile_,
232 signin)),
233 oauth2_token_service,
234 behavior));
235 service_->SetClearingBrowseringDataForTesting(
236 base::Bind(&ProfileSyncServiceTest::ClearBrowsingDataCallback,
237 base::Unretained(this)));
240 #if defined(OS_WIN) || defined(OS_MACOSX) || (defined(OS_LINUX) && !defined(OS_CHROMEOS))
241 void CreateServiceWithoutSignIn() {
242 CreateService(browser_sync::AUTO_START);
243 SigninManagerFactory::GetForProfile(profile())->SignOut(
244 signin_metrics::SIGNOUT_TEST);
246 #endif
248 void ShutdownAndDeleteService() {
249 if (service_)
250 service_->Shutdown();
251 service_.reset();
254 void InitializeForNthSync() {
255 // Set first sync time before initialize to disable backup.
256 sync_driver::SyncPrefs sync_prefs(service()->profile()->GetPrefs());
257 sync_prefs.SetFirstSyncTime(base::Time::Now());
258 service_->Initialize();
261 void InitializeForFirstSync() {
262 service_->Initialize();
265 void ExpectDataTypeManagerCreation(int times) {
266 EXPECT_CALL(*components_factory_, CreateDataTypeManager(_, _, _, _, _))
267 .Times(times)
268 .WillRepeatedly(ReturnNewDataTypeManager());
271 void ExpectSyncBackendHostCreation(int times) {
272 EXPECT_CALL(*components_factory_, CreateSyncBackendHost(_, _, _, _, _))
273 .Times(times)
274 .WillRepeatedly(ReturnNewSyncBackendHostMock());
277 void ExpectSyncBackendHostCreationCollectDeleteDir(
278 int times, std::vector<bool> *delete_dir_param) {
279 EXPECT_CALL(*components_factory_, CreateSyncBackendHost(_, _, _, _, _))
280 .Times(times)
281 .WillRepeatedly(ReturnNewMockHostCollectDeleteDirParam(
282 delete_dir_param));
285 void PrepareDelayedInitSyncBackendHost() {
286 EXPECT_CALL(*components_factory_, CreateSyncBackendHost(_, _, _, _, _)).
287 WillOnce(ReturnNewSyncBackendHostNoReturn());
290 TestingProfile* profile() {
291 return profile_;
294 ProfileSyncService* service() {
295 return service_.get();
298 ProfileSyncComponentsFactoryMock* components_factory() {
299 return components_factory_;
302 void ClearBrowsingDataCallback(BrowsingDataRemover::Observer* observer,
303 Profile* profile,
304 base::Time start,
305 base::Time end) {
306 EXPECT_EQ(profile_, profile);
307 clear_browsing_date_start_ = start;
310 protected:
311 void PumpLoop() {
312 base::RunLoop run_loop;
313 base::MessageLoop::current()->PostTask(
314 FROM_HERE, run_loop.QuitClosure());
315 run_loop.Run();
318 // The requested start time when ClearBrowsingDataCallback is called.
319 base::Time clear_browsing_date_start_;
321 private:
322 content::TestBrowserThreadBundle thread_bundle_;
323 TestingProfileManager profile_manager_;
324 TestingProfile* profile_;
325 scoped_ptr<ProfileSyncService> service_;
327 // Pointer to the components factory. Not owned. May be null.
328 ProfileSyncComponentsFactoryMock* components_factory_;
331 // Verify that the server URLs are sane.
332 TEST_F(ProfileSyncServiceTest, InitialState) {
333 CreateService(browser_sync::AUTO_START);
334 InitializeForNthSync();
335 const std::string& url = service()->sync_service_url().spec();
336 EXPECT_TRUE(url == ProfileSyncService::kSyncServerUrl ||
337 url == ProfileSyncService::kDevServerUrl);
340 // Verify a successful initialization.
341 TEST_F(ProfileSyncServiceTest, SuccessfulInitialization) {
342 profile()->GetTestingPrefService()->SetManagedPref(
343 sync_driver::prefs::kSyncManaged, new base::FundamentalValue(false));
344 IssueTestTokens();
345 CreateService(browser_sync::AUTO_START);
346 ExpectDataTypeManagerCreation(1);
347 ExpectSyncBackendHostCreation(1);
348 InitializeForNthSync();
349 EXPECT_FALSE(service()->IsManaged());
350 EXPECT_TRUE(service()->SyncActive());
351 EXPECT_EQ(ProfileSyncService::SYNC, service()->backend_mode());
355 // Verify that the SetSetupInProgress function call updates state
356 // and notifies observers.
357 TEST_F(ProfileSyncServiceTest, SetupInProgress) {
358 CreateService(browser_sync::AUTO_START);
359 InitializeForNthSync();
361 TestSyncServiceObserver observer(service());
362 service()->AddObserver(&observer);
364 service()->SetSetupInProgress(true);
365 EXPECT_TRUE(observer.first_setup_in_progress());
366 service()->SetSetupInProgress(false);
367 EXPECT_FALSE(observer.first_setup_in_progress());
369 service()->RemoveObserver(&observer);
372 // Verify that disable by enterprise policy works.
373 TEST_F(ProfileSyncServiceTest, DisabledByPolicyBeforeInit) {
374 profile()->GetTestingPrefService()->SetManagedPref(
375 sync_driver::prefs::kSyncManaged, new base::FundamentalValue(true));
376 IssueTestTokens();
377 CreateService(browser_sync::AUTO_START);
378 InitializeForNthSync();
379 EXPECT_TRUE(service()->IsManaged());
380 EXPECT_FALSE(service()->SyncActive());
383 // Verify that disable by enterprise policy works even after the backend has
384 // been initialized.
385 TEST_F(ProfileSyncServiceTest, DisabledByPolicyAfterInit) {
386 IssueTestTokens();
387 CreateService(browser_sync::AUTO_START);
388 ExpectDataTypeManagerCreation(1);
389 ExpectSyncBackendHostCreation(1);
390 InitializeForNthSync();
392 EXPECT_FALSE(service()->IsManaged());
393 EXPECT_TRUE(service()->SyncActive());
395 profile()->GetTestingPrefService()->SetManagedPref(
396 sync_driver::prefs::kSyncManaged, new base::FundamentalValue(true));
398 EXPECT_TRUE(service()->IsManaged());
399 EXPECT_FALSE(service()->SyncActive());
402 // Exercies the ProfileSyncService's code paths related to getting shut down
403 // before the backend initialize call returns.
404 TEST_F(ProfileSyncServiceTest, AbortedByShutdown) {
405 CreateService(browser_sync::AUTO_START);
406 PrepareDelayedInitSyncBackendHost();
408 IssueTestTokens();
409 InitializeForNthSync();
410 EXPECT_FALSE(service()->SyncActive());
412 ShutdownAndDeleteService();
415 // Test StopAndSuppress() before we've initialized the backend.
416 TEST_F(ProfileSyncServiceTest, EarlyStopAndSuppress) {
417 CreateService(browser_sync::AUTO_START);
418 IssueTestTokens();
420 service()->StopAndSuppress();
421 EXPECT_TRUE(profile()->GetPrefs()->GetBoolean(
422 sync_driver::prefs::kSyncSuppressStart));
424 // Because of supression, this should fail.
425 InitializeForNthSync();
426 EXPECT_FALSE(service()->SyncActive());
428 // Remove suppression. This should be enough to allow init to happen.
429 ExpectDataTypeManagerCreation(1);
430 ExpectSyncBackendHostCreation(1);
431 service()->UnsuppressAndStart();
432 EXPECT_TRUE(service()->SyncActive());
433 EXPECT_FALSE(profile()->GetPrefs()->GetBoolean(
434 sync_driver::prefs::kSyncSuppressStart));
437 // Test StopAndSuppress() after we've initialized the backend.
438 TEST_F(ProfileSyncServiceTest, DisableAndEnableSyncTemporarily) {
439 CreateService(browser_sync::AUTO_START);
440 IssueTestTokens();
441 ExpectDataTypeManagerCreation(1);
442 ExpectSyncBackendHostCreation(1);
443 InitializeForNthSync();
445 EXPECT_TRUE(service()->SyncActive());
446 EXPECT_FALSE(profile()->GetPrefs()->GetBoolean(
447 sync_driver::prefs::kSyncSuppressStart));
449 testing::Mock::VerifyAndClearExpectations(components_factory());
451 service()->StopAndSuppress();
452 EXPECT_FALSE(service()->SyncActive());
453 EXPECT_TRUE(profile()->GetPrefs()->GetBoolean(
454 sync_driver::prefs::kSyncSuppressStart));
456 ExpectDataTypeManagerCreation(1);
457 ExpectSyncBackendHostCreation(1);
459 service()->UnsuppressAndStart();
460 EXPECT_TRUE(service()->SyncActive());
461 EXPECT_FALSE(profile()->GetPrefs()->GetBoolean(
462 sync_driver::prefs::kSyncSuppressStart));
465 // Certain ProfileSyncService tests don't apply to Chrome OS, for example
466 // things that deal with concepts like "signing out" and policy.
467 #if !defined (OS_CHROMEOS)
468 TEST_F(ProfileSyncServiceTest, EnableSyncAndSignOut) {
469 CreateService(browser_sync::AUTO_START);
470 ExpectDataTypeManagerCreation(1);
471 ExpectSyncBackendHostCreation(1);
472 IssueTestTokens();
473 InitializeForNthSync();
475 EXPECT_TRUE(service()->SyncActive());
476 EXPECT_FALSE(profile()->GetPrefs()->GetBoolean(
477 sync_driver::prefs::kSyncSuppressStart));
479 SigninManagerFactory::GetForProfile(profile())->SignOut(
480 signin_metrics::SIGNOUT_TEST);
481 EXPECT_FALSE(service()->SyncActive());
483 #endif // !defined(OS_CHROMEOS)
485 TEST_F(ProfileSyncServiceTest, GetSyncTokenStatus) {
486 CreateService(browser_sync::AUTO_START);
487 IssueTestTokens();
488 ExpectDataTypeManagerCreation(1);
489 ExpectSyncBackendHostCreation(1);
490 InitializeForNthSync();
492 // Initial status.
493 ProfileSyncService::SyncTokenStatus token_status =
494 service()->GetSyncTokenStatus();
495 EXPECT_EQ(syncer::CONNECTION_NOT_ATTEMPTED, token_status.connection_status);
496 EXPECT_TRUE(token_status.connection_status_update_time.is_null());
497 EXPECT_TRUE(token_status.token_request_time.is_null());
498 EXPECT_TRUE(token_status.token_receive_time.is_null());
500 // Simulate an auth error.
501 service()->OnConnectionStatusChange(syncer::CONNECTION_AUTH_ERROR);
503 // The token request will take the form of a posted task. Run it.
504 base::RunLoop loop;
505 loop.RunUntilIdle();
507 token_status = service()->GetSyncTokenStatus();
508 EXPECT_EQ(syncer::CONNECTION_AUTH_ERROR, token_status.connection_status);
509 EXPECT_FALSE(token_status.connection_status_update_time.is_null());
510 EXPECT_FALSE(token_status.token_request_time.is_null());
511 EXPECT_FALSE(token_status.token_receive_time.is_null());
512 EXPECT_EQ(GoogleServiceAuthError::AuthErrorNone(),
513 token_status.last_get_token_error);
514 EXPECT_TRUE(token_status.next_token_request_time.is_null());
516 // Simulate successful connection.
517 service()->OnConnectionStatusChange(syncer::CONNECTION_OK);
518 token_status = service()->GetSyncTokenStatus();
519 EXPECT_EQ(syncer::CONNECTION_OK, token_status.connection_status);
522 #if defined(ENABLE_PRE_SYNC_BACKUP)
523 TEST_F(ProfileSyncServiceTest, DontStartBackupOnBrowserStart) {
524 CreateServiceWithoutSignIn();
525 InitializeForFirstSync();
526 PumpLoop();
527 EXPECT_EQ(ProfileSyncService::IDLE, service()->backend_mode());
530 TEST_F(ProfileSyncServiceTest, BackupBeforeFirstSync) {
531 CreateServiceWithoutSignIn();
532 ExpectDataTypeManagerCreation(2);
533 std::vector<bool> delete_dir_param;
534 ExpectSyncBackendHostCreationCollectDeleteDir(2, &delete_dir_param);
535 InitializeForFirstSync();
537 SigninManagerFactory::GetForProfile(profile())
538 ->SetAuthenticatedAccountInfo(kGaiaId, kEmail);
539 IssueTestTokens();
540 PumpLoop();
542 // At this time, backup is finished. Task is posted to start sync again.
543 EXPECT_EQ(ProfileSyncService::BACKUP, service()->backend_mode());
544 EXPECT_FALSE(service()->SyncActive());
545 EXPECT_EQ(1u, delete_dir_param.size());
546 EXPECT_TRUE(delete_dir_param[0]);
548 // Pump loop to start sync.
549 PumpLoop();
550 EXPECT_EQ(ProfileSyncService::SYNC, service()->backend_mode());
551 EXPECT_TRUE(service()->SyncActive());
552 EXPECT_EQ(2u, delete_dir_param.size());
553 EXPECT_TRUE(delete_dir_param[0]);
556 // Test backup is done again on browser start if user signed in last session
557 // but backup didn't finish when last session was closed.
558 TEST_F(ProfileSyncServiceTest, ResumeBackupIfAborted) {
559 IssueTestTokens();
560 CreateService(AUTO_START);
561 ExpectDataTypeManagerCreation(2);
562 std::vector<bool> delete_dir_param;
563 ExpectSyncBackendHostCreationCollectDeleteDir(2, &delete_dir_param);
564 InitializeForFirstSync();
565 PumpLoop();
567 // At this time, backup is finished. Task is posted to start sync again.
568 EXPECT_EQ(ProfileSyncService::BACKUP, service()->backend_mode());
569 EXPECT_FALSE(service()->SyncActive());
570 EXPECT_EQ(1u, delete_dir_param.size());
571 EXPECT_TRUE(delete_dir_param[0]);
573 // Pump loop to start sync.
574 PumpLoop();
575 EXPECT_EQ(ProfileSyncService::SYNC, service()->backend_mode());
576 EXPECT_TRUE(service()->SyncActive());
577 EXPECT_EQ(2u, delete_dir_param.size());
578 EXPECT_TRUE(delete_dir_param[0]);
581 TEST_F(ProfileSyncServiceTest, Rollback) {
582 CreateService(browser_sync::MANUAL_START);
583 service()->SetSyncSetupCompleted();
584 ExpectDataTypeManagerCreation(2);
585 std::vector<bool> delete_dir_param;
586 ExpectSyncBackendHostCreationCollectDeleteDir(2, &delete_dir_param);
587 IssueTestTokens();
588 InitializeForNthSync();
589 EXPECT_TRUE(service()->SyncActive());
590 EXPECT_EQ(ProfileSyncService::SYNC, service()->backend_mode());
592 // First sync time should be recorded.
593 sync_driver::SyncPrefs sync_prefs(service()->profile()->GetPrefs());
594 base::Time first_sync_time = sync_prefs.GetFirstSyncTime();
595 EXPECT_FALSE(first_sync_time.is_null());
597 syncer::SyncProtocolError client_cmd;
598 client_cmd.action = syncer::DISABLE_SYNC_AND_ROLLBACK;
599 service()->OnActionableError(client_cmd);
600 EXPECT_EQ(ProfileSyncService::IDLE, service()->backend_mode());
602 // Pump loop to run rollback.
603 PumpLoop();
604 EXPECT_EQ(ProfileSyncService::ROLLBACK, service()->backend_mode());
606 // Browser data should be cleared during rollback.
607 EXPECT_EQ(first_sync_time, clear_browsing_date_start_);
609 client_cmd.action = syncer::ROLLBACK_DONE;
610 service()->OnActionableError(client_cmd);
611 EXPECT_EQ(ProfileSyncService::IDLE, service()->backend_mode());
613 // First sync time is erased after rollback is done.
614 EXPECT_TRUE(sync_prefs.GetFirstSyncTime().is_null());
616 EXPECT_EQ(2u, delete_dir_param.size());
617 EXPECT_FALSE(delete_dir_param[0]);
618 EXPECT_FALSE(delete_dir_param[1]);
621 #endif
623 TEST_F(ProfileSyncServiceTest, GetSyncServiceURL) {
624 // See that we can override the URL with a flag.
625 base::CommandLine command_line(
626 base::FilePath(base::FilePath(FILE_PATH_LITERAL("chrome.exe"))));
627 command_line.AppendSwitchASCII(switches::kSyncServiceURL, "https://foo/bar");
628 EXPECT_EQ("https://foo/bar",
629 ProfileSyncService::GetSyncServiceURL(command_line).spec());
632 // Verify that LastSyncedTime is cleared when the user signs out.
633 TEST_F(ProfileSyncServiceTest, ClearLastSyncedTimeOnSignOut) {
634 IssueTestTokens();
635 CreateService(AUTO_START);
636 ExpectDataTypeManagerCreation(1);
637 ExpectSyncBackendHostCreation(1);
638 InitializeForNthSync();
639 EXPECT_TRUE(service()->SyncActive());
640 EXPECT_EQ(l10n_util::GetStringUTF16(IDS_SYNC_TIME_JUST_NOW),
641 service()->GetLastSyncedTimeString());
643 // Sign out.
644 service()->DisableForUser();
645 PumpLoop();
647 EXPECT_EQ(l10n_util::GetStringUTF16(IDS_SYNC_TIME_NEVER),
648 service()->GetLastSyncedTimeString());
651 // Verify that the disable sync flag disables sync.
652 TEST_F(ProfileSyncServiceTest, DisableSyncFlag) {
653 base::CommandLine::ForCurrentProcess()->AppendSwitch(switches::kDisableSync);
654 EXPECT_FALSE(ProfileSyncService::IsSyncAllowedByFlag());
657 // Verify that no disable sync flag enables sync.
658 TEST_F(ProfileSyncServiceTest, NoDisableSyncFlag) {
659 EXPECT_TRUE(ProfileSyncService::IsSyncAllowedByFlag());
662 // Test Sync will stop after receive memory pressure
663 TEST_F(ProfileSyncServiceTest, MemoryPressureRecording) {
664 CreateService(browser_sync::AUTO_START);
665 IssueTestTokens();
666 ExpectDataTypeManagerCreation(1);
667 ExpectSyncBackendHostCreation(1);
668 InitializeForNthSync();
670 EXPECT_TRUE(service()->SyncActive());
671 EXPECT_FALSE(profile()->GetPrefs()->GetBoolean(
672 sync_driver::prefs::kSyncSuppressStart));
674 testing::Mock::VerifyAndClearExpectations(components_factory());
676 sync_driver::SyncPrefs sync_prefs(service()->profile()->GetPrefs());
678 EXPECT_EQ(profile()->GetPrefs()->GetInteger(
679 sync_driver::prefs::kSyncMemoryPressureWarningCount),
681 EXPECT_FALSE(sync_prefs.DidSyncShutdownCleanly());
683 // Simulate memory pressure notification.
684 base::MemoryPressureListener::NotifyMemoryPressure(
685 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL);
686 base::RunLoop().RunUntilIdle();
688 // Verify memory pressure recorded.
689 EXPECT_EQ(profile()->GetPrefs()->GetInteger(
690 sync_driver::prefs::kSyncMemoryPressureWarningCount),
692 EXPECT_FALSE(sync_prefs.DidSyncShutdownCleanly());
694 // Simulate memory pressure notification.
695 base::MemoryPressureListener::NotifyMemoryPressure(
696 base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL);
697 base::RunLoop().RunUntilIdle();
698 ShutdownAndDeleteService();
700 // Verify memory pressure and shutdown recorded.
701 EXPECT_EQ(profile()->GetPrefs()->GetInteger(
702 sync_driver::prefs::kSyncMemoryPressureWarningCount),
704 EXPECT_TRUE(sync_prefs.DidSyncShutdownCleanly());
707 } // namespace
708 } // namespace browser_sync