1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964
|
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "components/browser_sync/profile_sync_service.h"
#include <utility>
#include "base/callback.h"
#include "base/command_line.h"
#include "base/feature_list.h"
#include "base/memory/ptr_util.h"
#include "base/run_loop.h"
#include "base/single_thread_task_runner.h"
#include "base/strings/string_number_conversions.h"
#include "base/strings/utf_string_conversions.h"
#include "base/test/scoped_feature_list.h"
#include "base/test/sequenced_worker_pool_owner.h"
#include "base/threading/thread_task_runner_handle.h"
#include "base/values.h"
#include "components/browser_sync/browser_sync_switches.h"
#include "components/browser_sync/profile_sync_test_util.h"
#include "components/invalidation/impl/profile_invalidation_provider.h"
#include "components/invalidation/public/invalidation_service.h"
#include "components/signin/core/browser/account_tracker_service.h"
#include "components/signin/core/browser/fake_signin_manager.h"
#include "components/strings/grit/components_strings.h"
#include "components/sync/base/pref_names.h"
#include "components/sync/driver/fake_data_type_controller.h"
#include "components/sync/driver/sync_api_component_factory_mock.h"
#include "components/sync/driver/sync_driver_switches.h"
#include "components/sync/driver/sync_service_observer.h"
#include "components/sync/driver/sync_util.h"
#include "components/sync/engine/fake_sync_engine.h"
#include "components/sync_preferences/testing_pref_service_syncable.h"
#include "components/version_info/version_info_values.h"
#include "google_apis/gaia/gaia_constants.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#include "ui/base/l10n/l10n_util.h"
using syncer::DataTypeController;
using syncer::FakeSyncEngine;
using syncer::SyncMergeResult;
using testing::Return;
namespace browser_sync {
namespace {
const char kGaiaId[] = "12345";
const char kEmail[] = "test_user@gmail.com";
class FakeDataTypeManager : public syncer::DataTypeManager {
public:
typedef base::Callback<void(syncer::ConfigureReason)> ConfigureCalled;
explicit FakeDataTypeManager(const ConfigureCalled& configure_called)
: configure_called_(configure_called) {}
~FakeDataTypeManager() override{};
void Configure(syncer::ModelTypeSet desired_types,
syncer::ConfigureReason reason) override {
DCHECK(!configure_called_.is_null());
configure_called_.Run(reason);
}
void ReenableType(syncer::ModelType type) override {}
void ResetDataTypeErrors() override {}
void PurgeForMigration(syncer::ModelTypeSet undesired_types,
syncer::ConfigureReason reason) override {}
void Stop() override{};
State state() const override { return syncer::DataTypeManager::CONFIGURED; };
private:
ConfigureCalled configure_called_;
};
ACTION_P(ReturnNewDataTypeManager, configure_called) {
return new FakeDataTypeManager(configure_called);
}
using testing::Return;
using testing::StrictMock;
using testing::_;
class TestSyncServiceObserver : public syncer::SyncServiceObserver {
public:
explicit TestSyncServiceObserver(ProfileSyncService* service)
: service_(service), setup_in_progress_(false) {}
void OnStateChanged() override {
setup_in_progress_ = service_->IsSetupInProgress();
}
bool setup_in_progress() const { return setup_in_progress_; }
private:
ProfileSyncService* service_;
bool setup_in_progress_;
};
// A variant of the FakeSyncEngine that won't automatically call back when asked
// to initialized. Allows us to test things that could happen while backend init
// is in progress.
class SyncEngineNoReturn : public FakeSyncEngine {
void Initialize(InitParams params) override {}
};
class FakeSyncEngineCollectDeleteDirParam : public FakeSyncEngine {
public:
explicit FakeSyncEngineCollectDeleteDirParam(
std::vector<bool>* delete_dir_param)
: delete_dir_param_(delete_dir_param) {}
void Initialize(InitParams params) override {
delete_dir_param_->push_back(params.delete_sync_data_folder);
FakeSyncEngine::Initialize(std::move(params));
}
private:
std::vector<bool>* delete_dir_param_;
};
// FakeSyncEngine that calls an external callback when ClearServerData is
// called.
class SyncEngineCaptureClearServerData : public FakeSyncEngine {
public:
typedef base::Callback<void(
const syncer::SyncManager::ClearServerDataCallback&)>
ClearServerDataCalled;
explicit SyncEngineCaptureClearServerData(
const ClearServerDataCalled& clear_server_data_called)
: clear_server_data_called_(clear_server_data_called) {}
void ClearServerData(
const syncer::SyncManager::ClearServerDataCallback& callback) override {
clear_server_data_called_.Run(callback);
}
private:
ClearServerDataCalled clear_server_data_called_;
};
ACTION(ReturnNewFakeSyncEngine) {
return new FakeSyncEngine();
}
ACTION(ReturnNewSyncEngineNoReturn) {
return new SyncEngineNoReturn();
}
ACTION_P(ReturnNewMockHostCollectDeleteDirParam, delete_dir_param) {
return new FakeSyncEngineCollectDeleteDirParam(delete_dir_param);
}
void OnClearServerDataCalled(
syncer::SyncManager::ClearServerDataCallback* captured_callback,
const syncer::SyncManager::ClearServerDataCallback& callback) {
*captured_callback = callback;
}
ACTION_P(ReturnNewMockHostCaptureClearServerData, captured_callback) {
return new SyncEngineCaptureClearServerData(base::Bind(
&OnClearServerDataCalled, base::Unretained(captured_callback)));
}
void DoNothing(DataTypeController::ConfigureResult ignored1,
const SyncMergeResult& ignored2,
const SyncMergeResult& ignored3) {}
// A test harness that uses a real ProfileSyncService and in most cases a
// MockSyncEngine.
//
// This is useful if we want to test the ProfileSyncService and don't care about
// testing the SyncEngine.
class ProfileSyncServiceTest : public ::testing::Test {
protected:
ProfileSyncServiceTest() : component_factory_(nullptr) {}
~ProfileSyncServiceTest() override {}
void SetUp() override {
base::CommandLine::ForCurrentProcess()->AppendSwitchASCII(
switches::kSyncDeferredStartupTimeoutSeconds, "0");
}
void TearDown() override {
// Kill the service before the profile.
if (service_)
service_->Shutdown();
service_.reset();
}
void IssueTestTokens() {
std::string account_id =
account_tracker()->SeedAccountInfo(kGaiaId, kEmail);
auth_service()->UpdateCredentials(account_id, "oauth2_login_token");
}
void CreateService(ProfileSyncService::StartBehavior behavior) {
signin_manager()->SetAuthenticatedAccountInfo(kGaiaId, kEmail);
component_factory_ = profile_sync_service_bundle_.component_factory();
ProfileSyncServiceBundle::SyncClientBuilder builder(
&profile_sync_service_bundle_);
ProfileSyncService::InitParams init_params =
profile_sync_service_bundle_.CreateBasicInitParams(behavior,
builder.Build());
service_ = base::MakeUnique<ProfileSyncService>(std::move(init_params));
service_->RegisterDataTypeController(
base::MakeUnique<syncer::FakeDataTypeController>(syncer::BOOKMARKS));
}
void CreateServiceWithLocalSyncBackend() {
component_factory_ = profile_sync_service_bundle_.component_factory();
ProfileSyncServiceBundle::SyncClientBuilder builder(
&profile_sync_service_bundle_);
ProfileSyncService::InitParams init_params =
profile_sync_service_bundle_.CreateBasicInitParams(
ProfileSyncService::AUTO_START, builder.Build());
prefs()->SetBoolean(syncer::prefs::kEnableLocalSyncBackend, true);
init_params.local_sync_backend_folder =
base::FilePath(FILE_PATH_LITERAL("dummyPath"));
init_params.oauth2_token_service = nullptr;
init_params.gaia_cookie_manager_service = nullptr;
service_ = base::MakeUnique<ProfileSyncService>(std::move(init_params));
service_->RegisterDataTypeController(
base::MakeUnique<syncer::FakeDataTypeController>(syncer::BOOKMARKS));
}
void ShutdownAndDeleteService() {
if (service_)
service_->Shutdown();
service_.reset();
}
void InitializeForNthSync() {
// Set first sync time before initialize to simulate a complete sync setup.
syncer::SyncPrefs sync_prefs(prefs());
sync_prefs.SetFirstSyncTime(base::Time::Now());
sync_prefs.SetFirstSetupComplete();
sync_prefs.SetKeepEverythingSynced(true);
service_->Initialize();
}
void InitializeForFirstSync() { service_->Initialize(); }
void TriggerPassphraseRequired() {
service_->OnPassphraseRequired(syncer::REASON_DECRYPTION,
sync_pb::EncryptedData());
}
void TriggerDataTypeStartRequest() {
service_->OnDataTypeRequestsSyncStartup(syncer::BOOKMARKS);
}
void OnConfigureCalled(syncer::ConfigureReason configure_reason) {
syncer::DataTypeManager::ConfigureResult result;
result.status = syncer::DataTypeManager::OK;
service()->OnConfigureDone(result);
}
FakeDataTypeManager::ConfigureCalled GetDefaultConfigureCalledCallback() {
return base::Bind(&ProfileSyncServiceTest::OnConfigureCalled,
base::Unretained(this));
}
void OnConfigureCalledRecordReason(syncer::ConfigureReason* reason_dest,
syncer::ConfigureReason reason) {
DCHECK(reason_dest);
*reason_dest = reason;
}
FakeDataTypeManager::ConfigureCalled GetRecordingConfigureCalledCallback(
syncer::ConfigureReason* reason) {
return base::Bind(&ProfileSyncServiceTest::OnConfigureCalledRecordReason,
base::Unretained(this), reason);
}
void ExpectDataTypeManagerCreation(
int times,
const FakeDataTypeManager::ConfigureCalled& callback) {
EXPECT_CALL(*component_factory_, CreateDataTypeManager(_, _, _, _, _, _))
.Times(times)
.WillRepeatedly(ReturnNewDataTypeManager(callback));
}
void ExpectSyncEngineCreation(int times) {
EXPECT_CALL(*component_factory_, CreateSyncEngine(_, _, _, _))
.Times(times)
.WillRepeatedly(ReturnNewFakeSyncEngine());
}
void ExpectSyncEngineCreationCollectDeleteDir(
int times,
std::vector<bool>* delete_dir_param) {
EXPECT_CALL(*component_factory_, CreateSyncEngine(_, _, _, _))
.Times(times)
.WillRepeatedly(
ReturnNewMockHostCollectDeleteDirParam(delete_dir_param));
}
void ExpectSyncEngineCreationCaptureClearServerData(
syncer::SyncManager::ClearServerDataCallback* captured_callback) {
EXPECT_CALL(*component_factory_, CreateSyncEngine(_, _, _, _))
.Times(1)
.WillOnce(ReturnNewMockHostCaptureClearServerData(captured_callback));
}
void PrepareDelayedInitSyncEngine() {
EXPECT_CALL(*component_factory_, CreateSyncEngine(_, _, _, _))
.WillOnce(ReturnNewSyncEngineNoReturn());
}
AccountTrackerService* account_tracker() {
return profile_sync_service_bundle_.account_tracker();
}
#if defined(OS_CHROMEOS)
SigninManagerBase* signin_manager()
#else
SigninManager* signin_manager()
#endif
// Opening brace is outside of macro to avoid confusing lint.
{
return profile_sync_service_bundle_.signin_manager();
}
ProfileOAuth2TokenService* auth_service() {
return profile_sync_service_bundle_.auth_service();
}
ProfileSyncService* service() { return service_.get(); }
sync_preferences::TestingPrefServiceSyncable* prefs() {
return profile_sync_service_bundle_.pref_service();
}
syncer::SyncApiComponentFactoryMock* component_factory() {
return component_factory_;
}
protected:
void PumpLoop() {
base::RunLoop run_loop;
base::ThreadTaskRunnerHandle::Get()->PostTask(FROM_HERE,
run_loop.QuitClosure());
run_loop.Run();
}
private:
base::MessageLoop message_loop_;
ProfileSyncServiceBundle profile_sync_service_bundle_;
std::unique_ptr<ProfileSyncService> service_;
// The current component factory used by sync. May be null if the server
// hasn't been created yet.
syncer::SyncApiComponentFactoryMock* component_factory_;
};
// Verify that the server URLs are sane.
TEST_F(ProfileSyncServiceTest, InitialState) {
CreateService(ProfileSyncService::AUTO_START);
InitializeForNthSync();
const std::string& url = service()->sync_service_url().spec();
EXPECT_TRUE(url == syncer::internal::kSyncServerUrl ||
url == syncer::internal::kSyncDevServerUrl);
}
// Verify a successful initialization.
TEST_F(ProfileSyncServiceTest, SuccessfulInitialization) {
prefs()->SetManagedPref(syncer::prefs::kSyncManaged,
new base::FundamentalValue(false));
IssueTestTokens();
CreateService(ProfileSyncService::AUTO_START);
ExpectDataTypeManagerCreation(1, GetDefaultConfigureCalledCallback());
ExpectSyncEngineCreation(1);
InitializeForNthSync();
EXPECT_FALSE(service()->IsManaged());
EXPECT_TRUE(service()->IsSyncActive());
}
// Verify a successful initialization.
TEST_F(ProfileSyncServiceTest, SuccessfulLocalBackendInitialization) {
prefs()->SetManagedPref(syncer::prefs::kSyncManaged,
new base::FundamentalValue(false));
IssueTestTokens();
CreateServiceWithLocalSyncBackend();
ExpectDataTypeManagerCreation(1, GetDefaultConfigureCalledCallback());
ExpectSyncEngineCreation(1);
InitializeForNthSync();
EXPECT_FALSE(service()->IsManaged());
EXPECT_TRUE(service()->IsSyncActive());
}
// Verify that an initialization where first setup is not complete does not
// start up the backend.
TEST_F(ProfileSyncServiceTest, NeedsConfirmation) {
prefs()->SetManagedPref(syncer::prefs::kSyncManaged,
new base::FundamentalValue(false));
IssueTestTokens();
CreateService(ProfileSyncService::MANUAL_START);
syncer::SyncPrefs sync_prefs(prefs());
base::Time now = base::Time::Now();
sync_prefs.SetLastSyncedTime(now);
sync_prefs.SetKeepEverythingSynced(true);
service()->Initialize();
EXPECT_FALSE(service()->IsSyncActive());
// The last sync time shouldn't be cleared.
// TODO(zea): figure out a way to check that the directory itself wasn't
// cleared.
EXPECT_EQ(now, sync_prefs.GetLastSyncedTime());
}
// Verify that the SetSetupInProgress function call updates state
// and notifies observers.
TEST_F(ProfileSyncServiceTest, SetupInProgress) {
CreateService(ProfileSyncService::AUTO_START);
InitializeForFirstSync();
TestSyncServiceObserver observer(service());
service()->AddObserver(&observer);
auto sync_blocker = service()->GetSetupInProgressHandle();
EXPECT_TRUE(observer.setup_in_progress());
sync_blocker.reset();
EXPECT_FALSE(observer.setup_in_progress());
service()->RemoveObserver(&observer);
}
// Verify that disable by enterprise policy works.
TEST_F(ProfileSyncServiceTest, DisabledByPolicyBeforeInit) {
prefs()->SetManagedPref(syncer::prefs::kSyncManaged,
new base::FundamentalValue(true));
IssueTestTokens();
CreateService(ProfileSyncService::AUTO_START);
InitializeForNthSync();
EXPECT_TRUE(service()->IsManaged());
EXPECT_FALSE(service()->IsSyncActive());
}
// Verify that disable by enterprise policy works even after the backend has
// been initialized.
TEST_F(ProfileSyncServiceTest, DisabledByPolicyAfterInit) {
IssueTestTokens();
CreateService(ProfileSyncService::AUTO_START);
ExpectDataTypeManagerCreation(1, GetDefaultConfigureCalledCallback());
ExpectSyncEngineCreation(1);
InitializeForNthSync();
EXPECT_FALSE(service()->IsManaged());
EXPECT_TRUE(service()->IsSyncActive());
prefs()->SetManagedPref(syncer::prefs::kSyncManaged,
new base::FundamentalValue(true));
EXPECT_TRUE(service()->IsManaged());
EXPECT_FALSE(service()->IsSyncActive());
}
// Exercies the ProfileSyncService's code paths related to getting shut down
// before the backend initialize call returns.
TEST_F(ProfileSyncServiceTest, AbortedByShutdown) {
CreateService(ProfileSyncService::AUTO_START);
PrepareDelayedInitSyncEngine();
IssueTestTokens();
InitializeForNthSync();
EXPECT_FALSE(service()->IsSyncActive());
ShutdownAndDeleteService();
}
// Test RequestStop() before we've initialized the backend.
TEST_F(ProfileSyncServiceTest, EarlyRequestStop) {
CreateService(ProfileSyncService::AUTO_START);
IssueTestTokens();
ExpectDataTypeManagerCreation(1, GetDefaultConfigureCalledCallback());
ExpectSyncEngineCreation(1);
service()->RequestStop(ProfileSyncService::KEEP_DATA);
EXPECT_FALSE(service()->IsSyncRequested());
// Because sync is not requested, this should fail.
InitializeForNthSync();
EXPECT_FALSE(service()->IsSyncRequested());
EXPECT_FALSE(service()->IsSyncActive());
// Request start. This should be enough to allow init to happen.
service()->RequestStart();
EXPECT_TRUE(service()->IsSyncRequested());
EXPECT_TRUE(service()->IsSyncActive());
}
// Test RequestStop() after we've initialized the backend.
TEST_F(ProfileSyncServiceTest, DisableAndEnableSyncTemporarily) {
CreateService(ProfileSyncService::AUTO_START);
IssueTestTokens();
ExpectDataTypeManagerCreation(1, GetDefaultConfigureCalledCallback());
ExpectSyncEngineCreation(1);
InitializeForNthSync();
EXPECT_TRUE(service()->IsSyncActive());
EXPECT_FALSE(prefs()->GetBoolean(syncer::prefs::kSyncSuppressStart));
testing::Mock::VerifyAndClearExpectations(component_factory());
service()->RequestStop(ProfileSyncService::KEEP_DATA);
EXPECT_FALSE(service()->IsSyncActive());
EXPECT_TRUE(prefs()->GetBoolean(syncer::prefs::kSyncSuppressStart));
ExpectDataTypeManagerCreation(1, GetDefaultConfigureCalledCallback());
ExpectSyncEngineCreation(1);
service()->RequestStart();
EXPECT_TRUE(service()->IsSyncActive());
EXPECT_FALSE(prefs()->GetBoolean(syncer::prefs::kSyncSuppressStart));
}
// Certain ProfileSyncService tests don't apply to Chrome OS, for example
// things that deal with concepts like "signing out" and policy.
#if !defined(OS_CHROMEOS)
TEST_F(ProfileSyncServiceTest, EnableSyncAndSignOut) {
CreateService(ProfileSyncService::AUTO_START);
ExpectDataTypeManagerCreation(1, GetDefaultConfigureCalledCallback());
ExpectSyncEngineCreation(1);
IssueTestTokens();
InitializeForNthSync();
EXPECT_TRUE(service()->IsSyncActive());
EXPECT_FALSE(prefs()->GetBoolean(syncer::prefs::kSyncSuppressStart));
signin_manager()->SignOut(signin_metrics::SIGNOUT_TEST,
signin_metrics::SignoutDelete::IGNORE_METRIC);
EXPECT_FALSE(service()->IsSyncActive());
}
#endif // !defined(OS_CHROMEOS)
TEST_F(ProfileSyncServiceTest, GetSyncTokenStatus) {
CreateService(ProfileSyncService::AUTO_START);
IssueTestTokens();
ExpectDataTypeManagerCreation(1, GetDefaultConfigureCalledCallback());
ExpectSyncEngineCreation(1);
InitializeForNthSync();
// Initial status.
ProfileSyncService::SyncTokenStatus token_status =
service()->GetSyncTokenStatus();
EXPECT_EQ(syncer::CONNECTION_NOT_ATTEMPTED, token_status.connection_status);
EXPECT_TRUE(token_status.connection_status_update_time.is_null());
EXPECT_TRUE(token_status.token_request_time.is_null());
EXPECT_TRUE(token_status.token_receive_time.is_null());
// Simulate an auth error.
service()->OnConnectionStatusChange(syncer::CONNECTION_AUTH_ERROR);
// The token request will take the form of a posted task. Run it.
base::RunLoop loop;
loop.RunUntilIdle();
token_status = service()->GetSyncTokenStatus();
EXPECT_EQ(syncer::CONNECTION_AUTH_ERROR, token_status.connection_status);
EXPECT_FALSE(token_status.connection_status_update_time.is_null());
EXPECT_FALSE(token_status.token_request_time.is_null());
EXPECT_FALSE(token_status.token_receive_time.is_null());
EXPECT_EQ(GoogleServiceAuthError::AuthErrorNone(),
token_status.last_get_token_error);
EXPECT_TRUE(token_status.next_token_request_time.is_null());
// Simulate successful connection.
service()->OnConnectionStatusChange(syncer::CONNECTION_OK);
token_status = service()->GetSyncTokenStatus();
EXPECT_EQ(syncer::CONNECTION_OK, token_status.connection_status);
}
TEST_F(ProfileSyncServiceTest, RevokeAccessTokenFromTokenService) {
CreateService(ProfileSyncService::AUTO_START);
IssueTestTokens();
ExpectDataTypeManagerCreation(1, GetDefaultConfigureCalledCallback());
ExpectSyncEngineCreation(1);
InitializeForNthSync();
EXPECT_TRUE(service()->IsSyncActive());
std::string primary_account_id =
signin_manager()->GetAuthenticatedAccountId();
auth_service()->LoadCredentials(primary_account_id);
base::RunLoop().RunUntilIdle();
EXPECT_FALSE(service()->GetAccessTokenForTest().empty());
std::string secondary_account_gaiaid = "1234567";
std::string secondary_account_name = "test_user2@gmail.com";
std::string secondary_account_id = account_tracker()->SeedAccountInfo(
secondary_account_gaiaid, secondary_account_name);
auth_service()->UpdateCredentials(secondary_account_id,
"second_account_refresh_token");
auth_service()->RevokeCredentials(secondary_account_id);
EXPECT_FALSE(service()->GetAccessTokenForTest().empty());
auth_service()->RevokeCredentials(primary_account_id);
EXPECT_TRUE(service()->GetAccessTokenForTest().empty());
}
// CrOS does not support signout.
#if !defined(OS_CHROMEOS)
TEST_F(ProfileSyncServiceTest, SignOutRevokeAccessToken) {
CreateService(ProfileSyncService::AUTO_START);
IssueTestTokens();
ExpectDataTypeManagerCreation(1, GetDefaultConfigureCalledCallback());
ExpectSyncEngineCreation(1);
InitializeForNthSync();
EXPECT_TRUE(service()->IsSyncActive());
std::string primary_account_id =
signin_manager()->GetAuthenticatedAccountId();
auth_service()->LoadCredentials(primary_account_id);
base::RunLoop().RunUntilIdle();
EXPECT_FALSE(service()->GetAccessTokenForTest().empty());
signin_manager()->SignOut(signin_metrics::SIGNOUT_TEST,
signin_metrics::SignoutDelete::IGNORE_METRIC);
EXPECT_TRUE(service()->GetAccessTokenForTest().empty());
}
#endif
// Verify that LastSyncedTime and local DeviceInfo is cleared on sign out.
TEST_F(ProfileSyncServiceTest, ClearDataOnSignOut) {
IssueTestTokens();
CreateService(ProfileSyncService::AUTO_START);
ExpectDataTypeManagerCreation(1, GetDefaultConfigureCalledCallback());
ExpectSyncEngineCreation(1);
InitializeForNthSync();
EXPECT_TRUE(service()->IsSyncActive());
EXPECT_EQ(l10n_util::GetStringUTF16(IDS_SYNC_TIME_JUST_NOW),
service()->GetLastSyncedTimeString());
EXPECT_TRUE(service()->GetLocalDeviceInfoProvider()->GetLocalDeviceInfo());
// Sign out.
service()->RequestStop(ProfileSyncService::CLEAR_DATA);
PumpLoop();
EXPECT_EQ(l10n_util::GetStringUTF16(IDS_SYNC_TIME_NEVER),
service()->GetLastSyncedTimeString());
EXPECT_FALSE(service()->GetLocalDeviceInfoProvider()->GetLocalDeviceInfo());
}
// Verify that the disable sync flag disables sync.
TEST_F(ProfileSyncServiceTest, DisableSyncFlag) {
base::CommandLine::ForCurrentProcess()->AppendSwitch(switches::kDisableSync);
EXPECT_FALSE(ProfileSyncService::IsSyncAllowedByFlag());
}
// Verify that no disable sync flag enables sync.
TEST_F(ProfileSyncServiceTest, NoDisableSyncFlag) {
EXPECT_TRUE(ProfileSyncService::IsSyncAllowedByFlag());
}
// Test Sync will stop after receive memory pressure
TEST_F(ProfileSyncServiceTest, MemoryPressureRecording) {
CreateService(ProfileSyncService::AUTO_START);
IssueTestTokens();
ExpectDataTypeManagerCreation(1, GetDefaultConfigureCalledCallback());
ExpectSyncEngineCreation(1);
InitializeForNthSync();
EXPECT_TRUE(service()->IsSyncActive());
EXPECT_FALSE(prefs()->GetBoolean(syncer::prefs::kSyncSuppressStart));
testing::Mock::VerifyAndClearExpectations(component_factory());
syncer::SyncPrefs sync_prefs(service()->GetSyncClient()->GetPrefService());
EXPECT_EQ(prefs()->GetInteger(syncer::prefs::kSyncMemoryPressureWarningCount),
0);
EXPECT_FALSE(sync_prefs.DidSyncShutdownCleanly());
// Simulate memory pressure notification.
base::MemoryPressureListener::NotifyMemoryPressure(
base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL);
base::RunLoop().RunUntilIdle();
// Verify memory pressure recorded.
EXPECT_EQ(prefs()->GetInteger(syncer::prefs::kSyncMemoryPressureWarningCount),
1);
EXPECT_FALSE(sync_prefs.DidSyncShutdownCleanly());
// Simulate memory pressure notification.
base::MemoryPressureListener::NotifyMemoryPressure(
base::MemoryPressureListener::MEMORY_PRESSURE_LEVEL_CRITICAL);
base::RunLoop().RunUntilIdle();
ShutdownAndDeleteService();
// Verify memory pressure and shutdown recorded.
EXPECT_EQ(prefs()->GetInteger(syncer::prefs::kSyncMemoryPressureWarningCount),
2);
EXPECT_TRUE(sync_prefs.DidSyncShutdownCleanly());
}
// Verify that OnLocalSetPassphraseEncryption triggers catch up configure sync
// cycle, calls ClearServerData, shuts down and restarts sync.
TEST_F(ProfileSyncServiceTest, OnLocalSetPassphraseEncryption) {
base::test::ScopedFeatureList scoped_feature_list;
scoped_feature_list.InitAndEnableFeature(
switches::kSyncClearDataOnPassphraseEncryption);
IssueTestTokens();
CreateService(ProfileSyncService::AUTO_START);
syncer::SyncManager::ClearServerDataCallback captured_callback;
syncer::ConfigureReason configure_reason = syncer::CONFIGURE_REASON_UNKNOWN;
// Initialize sync, ensure that both DataTypeManager and SyncEngine are
// initialized and DTM::Configure is called with
// CONFIGURE_REASON_NEWLY_ENABLED_DATA_TYPE.
ExpectSyncEngineCreationCaptureClearServerData(&captured_callback);
ExpectDataTypeManagerCreation(
1, GetRecordingConfigureCalledCallback(&configure_reason));
InitializeForNthSync();
EXPECT_TRUE(service()->IsSyncActive());
testing::Mock::VerifyAndClearExpectations(component_factory());
EXPECT_EQ(syncer::CONFIGURE_REASON_NEWLY_ENABLED_DATA_TYPE, configure_reason);
syncer::DataTypeManager::ConfigureResult result;
result.status = syncer::DataTypeManager::OK;
service()->OnConfigureDone(result);
// Simulate user entering encryption passphrase. Ensure that catch up
// configure cycle is started (DTM::Configure is called with
// CONFIGURE_REASON_CATCH_UP).
const syncer::SyncEncryptionHandler::NigoriState nigori_state;
service()->OnLocalSetPassphraseEncryption(nigori_state);
EXPECT_EQ(syncer::CONFIGURE_REASON_CATCH_UP, configure_reason);
EXPECT_TRUE(captured_callback.is_null());
// Simulate configure successful. Ensure that SBH::ClearServerData is called.
service()->OnConfigureDone(result);
EXPECT_FALSE(captured_callback.is_null());
// Once SBH::ClearServerData finishes successfully ensure that sync is
// restarted.
configure_reason = syncer::CONFIGURE_REASON_UNKNOWN;
ExpectSyncEngineCreation(1);
ExpectDataTypeManagerCreation(
1, GetRecordingConfigureCalledCallback(&configure_reason));
captured_callback.Run();
testing::Mock::VerifyAndClearExpectations(component_factory());
EXPECT_EQ(syncer::CONFIGURE_REASON_NEWLY_ENABLED_DATA_TYPE, configure_reason);
service()->OnConfigureDone(result);
}
// Verify that if after OnLocalSetPassphraseEncryption catch up configure sync
// cycle gets interrupted, it starts again after browser restart.
TEST_F(ProfileSyncServiceTest,
OnLocalSetPassphraseEncryption_RestartDuringCatchUp) {
syncer::ConfigureReason configure_reason = syncer::CONFIGURE_REASON_UNKNOWN;
base::test::ScopedFeatureList scoped_feature_list;
scoped_feature_list.InitAndEnableFeature(
switches::kSyncClearDataOnPassphraseEncryption);
IssueTestTokens();
CreateService(ProfileSyncService::AUTO_START);
ExpectSyncEngineCreation(1);
ExpectDataTypeManagerCreation(
1, GetRecordingConfigureCalledCallback(&configure_reason));
InitializeForNthSync();
testing::Mock::VerifyAndClearExpectations(component_factory());
EXPECT_EQ(syncer::CONFIGURE_REASON_NEWLY_ENABLED_DATA_TYPE, configure_reason);
syncer::DataTypeManager::ConfigureResult result;
result.status = syncer::DataTypeManager::OK;
service()->OnConfigureDone(result);
// Simulate user entering encryption passphrase. Ensure Configure was called
// but don't let it continue.
const syncer::SyncEncryptionHandler::NigoriState nigori_state;
service()->OnLocalSetPassphraseEncryption(nigori_state);
EXPECT_EQ(syncer::CONFIGURE_REASON_CATCH_UP, configure_reason);
// Simulate browser restart. First configuration is a regular one.
service()->Shutdown();
syncer::SyncManager::ClearServerDataCallback captured_callback;
ExpectSyncEngineCreationCaptureClearServerData(&captured_callback);
ExpectDataTypeManagerCreation(
1, GetRecordingConfigureCalledCallback(&configure_reason));
service()->RequestStart();
testing::Mock::VerifyAndClearExpectations(component_factory());
EXPECT_EQ(syncer::CONFIGURE_REASON_NEWLY_ENABLED_DATA_TYPE, configure_reason);
EXPECT_TRUE(captured_callback.is_null());
// Simulate configure successful. This time it should be catch up.
service()->OnConfigureDone(result);
EXPECT_EQ(syncer::CONFIGURE_REASON_CATCH_UP, configure_reason);
EXPECT_TRUE(captured_callback.is_null());
// Simulate catch up configure successful. Ensure that SBH::ClearServerData is
// called.
service()->OnConfigureDone(result);
EXPECT_FALSE(captured_callback.is_null());
ExpectSyncEngineCreation(1);
ExpectDataTypeManagerCreation(
1, GetRecordingConfigureCalledCallback(&configure_reason));
captured_callback.Run();
testing::Mock::VerifyAndClearExpectations(component_factory());
EXPECT_EQ(syncer::CONFIGURE_REASON_NEWLY_ENABLED_DATA_TYPE, configure_reason);
}
// Verify that if after OnLocalSetPassphraseEncryption ClearServerData gets
// interrupted, transition again from catch up sync cycle after browser restart.
TEST_F(ProfileSyncServiceTest,
OnLocalSetPassphraseEncryption_RestartDuringClearServerData) {
syncer::SyncManager::ClearServerDataCallback captured_callback;
syncer::ConfigureReason configure_reason = syncer::CONFIGURE_REASON_UNKNOWN;
base::test::ScopedFeatureList scoped_feature_list;
scoped_feature_list.InitAndEnableFeature(
switches::kSyncClearDataOnPassphraseEncryption);
IssueTestTokens();
CreateService(ProfileSyncService::AUTO_START);
ExpectSyncEngineCreationCaptureClearServerData(&captured_callback);
ExpectDataTypeManagerCreation(1, GetDefaultConfigureCalledCallback());
InitializeForNthSync();
testing::Mock::VerifyAndClearExpectations(component_factory());
// Simulate user entering encryption passphrase.
const syncer::SyncEncryptionHandler::NigoriState nigori_state;
service()->OnLocalSetPassphraseEncryption(nigori_state);
EXPECT_FALSE(captured_callback.is_null());
captured_callback.Reset();
// Simulate browser restart. First configuration is a regular one.
service()->Shutdown();
ExpectSyncEngineCreationCaptureClearServerData(&captured_callback);
ExpectDataTypeManagerCreation(
1, GetRecordingConfigureCalledCallback(&configure_reason));
service()->RequestStart();
testing::Mock::VerifyAndClearExpectations(component_factory());
EXPECT_EQ(syncer::CONFIGURE_REASON_NEWLY_ENABLED_DATA_TYPE, configure_reason);
EXPECT_TRUE(captured_callback.is_null());
// Simulate configure successful. This time it should be catch up.
syncer::DataTypeManager::ConfigureResult result;
result.status = syncer::DataTypeManager::OK;
service()->OnConfigureDone(result);
EXPECT_EQ(syncer::CONFIGURE_REASON_CATCH_UP, configure_reason);
EXPECT_TRUE(captured_callback.is_null());
// Simulate catch up configure successful. Ensure that SBH::ClearServerData is
// called.
service()->OnConfigureDone(result);
EXPECT_FALSE(captured_callback.is_null());
ExpectSyncEngineCreation(1);
ExpectDataTypeManagerCreation(
1, GetRecordingConfigureCalledCallback(&configure_reason));
captured_callback.Run();
testing::Mock::VerifyAndClearExpectations(component_factory());
EXPECT_EQ(syncer::CONFIGURE_REASON_NEWLY_ENABLED_DATA_TYPE, configure_reason);
}
// Test that the passphrase prompt due to version change logic gets triggered
// on a datatype type requesting startup, but only happens once.
TEST_F(ProfileSyncServiceTest, PassphrasePromptDueToVersion) {
IssueTestTokens();
CreateService(ProfileSyncService::AUTO_START);
ExpectDataTypeManagerCreation(1, GetDefaultConfigureCalledCallback());
ExpectSyncEngineCreation(1);
InitializeForNthSync();
syncer::SyncPrefs sync_prefs(service()->GetSyncClient()->GetPrefService());
EXPECT_EQ(PRODUCT_VERSION, sync_prefs.GetLastRunVersion());
sync_prefs.SetPassphrasePrompted(true);
// Until a datatype requests startup while a passphrase is required the
// passphrase prompt bit should remain set.
EXPECT_TRUE(sync_prefs.IsPassphrasePrompted());
TriggerPassphraseRequired();
EXPECT_TRUE(sync_prefs.IsPassphrasePrompted());
// Because the last version was unset, this run should be treated as a new
// version and force a prompt.
TriggerDataTypeStartRequest();
EXPECT_FALSE(sync_prefs.IsPassphrasePrompted());
// At this point further datatype startup request should have no effect.
sync_prefs.SetPassphrasePrompted(true);
TriggerDataTypeStartRequest();
EXPECT_TRUE(sync_prefs.IsPassphrasePrompted());
}
// Test that when ProfileSyncService receives actionable error
// RESET_LOCAL_SYNC_DATA it restarts sync.
TEST_F(ProfileSyncServiceTest, ResetSyncData) {
IssueTestTokens();
CreateService(ProfileSyncService::AUTO_START);
// Backend should get initialized two times: once during initialization and
// once when handling actionable error.
ExpectDataTypeManagerCreation(2, GetDefaultConfigureCalledCallback());
ExpectSyncEngineCreation(2);
InitializeForNthSync();
syncer::SyncProtocolError client_cmd;
client_cmd.action = syncer::RESET_LOCAL_SYNC_DATA;
service()->OnActionableError(client_cmd);
}
// Test that when ProfileSyncService receives actionable error
// DISABLE_SYNC_ON_CLIENT it disables sync and signs out.
TEST_F(ProfileSyncServiceTest, DisableSyncOnClient) {
IssueTestTokens();
CreateService(ProfileSyncService::AUTO_START);
ExpectDataTypeManagerCreation(1, GetDefaultConfigureCalledCallback());
ExpectSyncEngineCreation(1);
InitializeForNthSync();
EXPECT_TRUE(service()->IsSyncActive());
EXPECT_EQ(l10n_util::GetStringUTF16(IDS_SYNC_TIME_JUST_NOW),
service()->GetLastSyncedTimeString());
EXPECT_TRUE(service()->GetLocalDeviceInfoProvider()->GetLocalDeviceInfo());
syncer::SyncProtocolError client_cmd;
client_cmd.action = syncer::DISABLE_SYNC_ON_CLIENT;
service()->OnActionableError(client_cmd);
// CrOS does not support signout.
#if !defined(OS_CHROMEOS)
EXPECT_TRUE(signin_manager()->GetAuthenticatedAccountId().empty());
#else
EXPECT_FALSE(signin_manager()->GetAuthenticatedAccountId().empty());
#endif
EXPECT_FALSE(service()->IsSyncActive());
EXPECT_EQ(l10n_util::GetStringUTF16(IDS_SYNC_TIME_NEVER),
service()->GetLastSyncedTimeString());
EXPECT_FALSE(service()->GetLocalDeviceInfoProvider()->GetLocalDeviceInfo());
}
// Regression test for crbug/555434. The issue is that check for sessions DTC in
// OnSessionRestoreComplete was creating map entry with nullptr which later was
// dereferenced in OnSyncCycleCompleted. The fix is to use find() to check if
// entry for sessions exists in map.
TEST_F(ProfileSyncServiceTest, ValidPointersInDTCMap) {
CreateService(ProfileSyncService::AUTO_START);
service()->OnSessionRestoreComplete();
service()->OnSyncCycleCompleted(syncer::SyncCycleSnapshot());
}
// The OpenTabsUIDelegate should only be accessable when PROXY_TABS is enabled.
TEST_F(ProfileSyncServiceTest, GetOpenTabsUIDelegate) {
CreateService(ProfileSyncService::AUTO_START);
InitializeForNthSync();
EXPECT_EQ(nullptr, service()->GetOpenTabsUIDelegate());
auto controller =
base::MakeUnique<syncer::FakeDataTypeController>(syncer::PROXY_TABS);
// Progress the controller to RUNNING first, which is how the service
// determines whether a type is enabled.
controller->StartAssociating(base::Bind(&DoNothing));
controller->FinishStart(DataTypeController::OK_FIRST_RUN);
service()->RegisterDataTypeController(std::move(controller));
EXPECT_NE(nullptr, service()->GetOpenTabsUIDelegate());
}
} // namespace
} // namespace browser_sync
|