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 "chrome/browser/ui/webui/sync_setup_handler.h"
9 #include "base/command_line.h"
10 #include "base/json/json_writer.h"
11 #include "base/memory/scoped_ptr.h"
12 #include "base/prefs/pref_service.h"
13 #include "base/stl_util.h"
14 #include "base/values.h"
15 #include "chrome/browser/signin/fake_auth_status_provider.h"
16 #include "chrome/browser/signin/fake_signin_manager.h"
17 #include "chrome/browser/signin/profile_oauth2_token_service.h"
18 #include "chrome/browser/signin/profile_oauth2_token_service_factory.h"
19 #include "chrome/browser/signin/signin_manager.h"
20 #include "chrome/browser/signin/signin_manager_factory.h"
21 #include "chrome/browser/sync/profile_sync_service_factory.h"
22 #include "chrome/browser/sync/profile_sync_service_mock.h"
23 #include "chrome/browser/ui/webui/signin/login_ui_service.h"
24 #include "chrome/browser/ui/webui/signin/login_ui_service_factory.h"
25 #include "chrome/common/chrome_switches.h"
26 #include "chrome/common/pref_names.h"
27 #include "chrome/test/base/testing_profile.h"
28 #include "chrome/test/base/testing_browser_process.h"
29 #include "chrome/test/base/scoped_testing_local_state.h"
30 #include "content/public/browser/web_ui.h"
31 #include "content/public/test/test_browser_thread.h"
32 #include "content/public/test/test_browser_thread_bundle.h"
33 #include "grit/generated_resources.h"
34 #include "testing/gtest/include/gtest/gtest.h"
35 #include "ui/base/l10n/l10n_util.h"
36 #include "ui/base/layout.h"
39 using ::testing::Mock;
40 using ::testing::Return;
41 using ::testing::ReturnRef;
42 using ::testing::Values;
44 typedef GoogleServiceAuthError AuthError;
48 MATCHER_P(ModelTypeSetMatches, value, "") { return arg.Equals(value); }
50 const char kTestUser[] = "chrome.p13n.test@gmail.com";
52 // Returns a ModelTypeSet with all user selectable types set.
53 syncer::ModelTypeSet GetAllTypes() {
54 return syncer::UserSelectableTypes();
57 enum SyncAllDataConfig {
63 enum EncryptAllConfig {
68 // Create a json-format string with the key/value pairs appropriate for a call
69 // to HandleConfigure(). If |extra_values| is non-null, then the values from
70 // the passed dictionary are added to the json.
71 std::string GetConfiguration(const DictionaryValue* extra_values,
72 SyncAllDataConfig sync_all,
73 syncer::ModelTypeSet types,
74 const std::string& passphrase,
75 EncryptAllConfig encrypt_all) {
76 DictionaryValue result;
78 result.MergeDictionary(extra_values);
79 result.SetBoolean("syncAllDataTypes", sync_all == SYNC_ALL_DATA);
80 result.SetBoolean("syncNothing", sync_all == SYNC_NOTHING);
81 result.SetBoolean("encryptAllData", encrypt_all == ENCRYPT_ALL_DATA);
82 result.SetBoolean("usePassphrase", !passphrase.empty());
83 if (!passphrase.empty())
84 result.SetString("passphrase", passphrase);
85 // Add all of our data types.
86 result.SetBoolean("appsSynced", types.Has(syncer::APPS));
87 result.SetBoolean("autofillSynced", types.Has(syncer::AUTOFILL));
88 result.SetBoolean("bookmarksSynced", types.Has(syncer::BOOKMARKS));
89 result.SetBoolean("extensionsSynced", types.Has(syncer::EXTENSIONS));
90 result.SetBoolean("passwordsSynced", types.Has(syncer::PASSWORDS));
91 result.SetBoolean("preferencesSynced", types.Has(syncer::PREFERENCES));
92 result.SetBoolean("tabsSynced", types.Has(syncer::PROXY_TABS));
93 result.SetBoolean("themesSynced", types.Has(syncer::THEMES));
94 result.SetBoolean("typedUrlsSynced", types.Has(syncer::TYPED_URLS));
96 base::JSONWriter::Write(&result, &args);
100 void CheckInt(const DictionaryValue* dictionary,
101 const std::string& key,
102 int expected_value) {
104 EXPECT_TRUE(dictionary->GetInteger(key, &actual_value)) <<
105 "Did not expect to find value for " << key;
106 EXPECT_EQ(actual_value, expected_value) <<
107 "Mismatch found for " << key;
110 // Checks whether the passed |dictionary| contains a |key| with the given
111 // |expected_value|. If |omit_if_false| is true, then the value should only
112 // be present if |expected_value| is true.
113 void CheckBool(const DictionaryValue* dictionary,
114 const std::string& key,
116 bool omit_if_false) {
117 if (omit_if_false && !expected_value) {
118 EXPECT_FALSE(dictionary->HasKey(key)) <<
119 "Did not expect to find value for " << key;
122 EXPECT_TRUE(dictionary->GetBoolean(key, &actual_value)) <<
123 "No value found for " << key;
124 EXPECT_EQ(actual_value, expected_value) <<
125 "Mismatch found for " << key;
129 void CheckBool(const DictionaryValue* dictionary,
130 const std::string& key,
131 bool expected_value) {
132 return CheckBool(dictionary, key, expected_value, false);
135 void CheckString(const DictionaryValue* dictionary,
136 const std::string& key,
137 const std::string& expected_value,
138 bool omit_if_empty) {
139 if (omit_if_empty && expected_value.empty()) {
140 EXPECT_FALSE(dictionary->HasKey(key)) <<
141 "Did not expect to find value for " << key;
143 std::string actual_value;
144 EXPECT_TRUE(dictionary->GetString(key, &actual_value)) <<
145 "No value found for " << key;
146 EXPECT_EQ(actual_value, expected_value) <<
147 "Mismatch found for " << key;
151 // Checks to make sure that the values stored in |dictionary| match the values
152 // expected by the showSyncSetupPage() JS function for a given set of data
154 void CheckConfigDataTypeArguments(DictionaryValue* dictionary,
155 SyncAllDataConfig config,
156 syncer::ModelTypeSet types) {
157 CheckBool(dictionary, "syncAllDataTypes", config == SYNC_ALL_DATA);
158 CheckBool(dictionary, "syncNothing", config == SYNC_NOTHING);
159 CheckBool(dictionary, "appsSynced", types.Has(syncer::APPS));
160 CheckBool(dictionary, "autofillSynced", types.Has(syncer::AUTOFILL));
161 CheckBool(dictionary, "bookmarksSynced", types.Has(syncer::BOOKMARKS));
162 CheckBool(dictionary, "extensionsSynced", types.Has(syncer::EXTENSIONS));
163 CheckBool(dictionary, "passwordsSynced", types.Has(syncer::PASSWORDS));
164 CheckBool(dictionary, "preferencesSynced", types.Has(syncer::PREFERENCES));
165 CheckBool(dictionary, "tabsSynced", types.Has(syncer::PROXY_TABS));
166 CheckBool(dictionary, "themesSynced", types.Has(syncer::THEMES));
167 CheckBool(dictionary, "typedUrlsSynced", types.Has(syncer::TYPED_URLS));
173 // Test instance of WebUI that tracks the data passed to
174 // CallJavascriptFunction().
175 class TestWebUI : public content::WebUI {
177 virtual ~TestWebUI() {
181 void ClearTrackedCalls() {
182 // Manually free the arguments stored in CallData, since there's no good
183 // way to use a self-freeing reference like scoped_ptr in a std::vector.
184 for (std::vector<CallData>::iterator i = call_data_.begin();
185 i != call_data_.end();
193 virtual void CallJavascriptFunction(const std::string& function_name)
195 call_data_.push_back(CallData());
196 call_data_.back().function_name = function_name;
199 virtual void CallJavascriptFunction(const std::string& function_name,
200 const base::Value& arg1) OVERRIDE {
201 call_data_.push_back(CallData());
202 call_data_.back().function_name = function_name;
203 call_data_.back().arg1 = arg1.DeepCopy();
206 virtual void CallJavascriptFunction(const std::string& function_name,
207 const base::Value& arg1,
208 const base::Value& arg2) OVERRIDE {
209 call_data_.push_back(CallData());
210 call_data_.back().function_name = function_name;
211 call_data_.back().arg1 = arg1.DeepCopy();
212 call_data_.back().arg2 = arg2.DeepCopy();
215 virtual content::WebContents* GetWebContents() const OVERRIDE {
218 virtual content::WebUIController* GetController() const OVERRIDE {
221 virtual void SetController(content::WebUIController* controller) OVERRIDE {}
222 virtual ui::ScaleFactor GetDeviceScaleFactor() const OVERRIDE {
223 return ui::SCALE_FACTOR_100P;
225 virtual const string16& GetOverriddenTitle() const OVERRIDE {
228 virtual void OverrideTitle(const string16& title) OVERRIDE {}
229 virtual content::PageTransition GetLinkTransitionType() const OVERRIDE {
230 return content::PAGE_TRANSITION_LINK;
232 virtual void SetLinkTransitionType(content::PageTransition type) OVERRIDE {}
233 virtual int GetBindings() const OVERRIDE {
236 virtual void SetBindings(int bindings) OVERRIDE {}
237 virtual void SetFrameXPath(const std::string& xpath) OVERRIDE {}
238 virtual void AddMessageHandler(
239 content::WebUIMessageHandler* handler) OVERRIDE {}
240 virtual void RegisterMessageCallback(
241 const std::string& message,
242 const MessageCallback& callback) OVERRIDE {}
243 virtual void ProcessWebUIMessage(const GURL& source_url,
244 const std::string& message,
245 const base::ListValue& args) OVERRIDE {}
246 virtual void CallJavascriptFunction(const std::string& function_name,
247 const base::Value& arg1,
248 const base::Value& arg2,
249 const base::Value& arg3) OVERRIDE {}
250 virtual void CallJavascriptFunction(const std::string& function_name,
251 const base::Value& arg1,
252 const base::Value& arg2,
253 const base::Value& arg3,
254 const base::Value& arg4) OVERRIDE {}
255 virtual void CallJavascriptFunction(
256 const std::string& function_name,
257 const std::vector<const base::Value*>& args) OVERRIDE {}
261 CallData() : arg1(NULL), arg2(NULL) {}
262 std::string function_name;
266 const std::vector<CallData>& call_data() { return call_data_; }
268 std::vector<CallData> call_data_;
269 string16 temp_string_;
272 class TestingSyncSetupHandler : public SyncSetupHandler {
274 TestingSyncSetupHandler(content::WebUI* web_ui, Profile* profile)
275 : SyncSetupHandler(NULL),
279 virtual ~TestingSyncSetupHandler() {
283 virtual void FocusUI() OVERRIDE {}
285 virtual Profile* GetProfile() const OVERRIDE { return profile_; }
287 using SyncSetupHandler::is_configuring_sync;
290 #if !defined(OS_CHROMEOS)
291 virtual void DisplayGaiaLoginInNewTabOrWindow() OVERRIDE {}
294 // Weak pointer to parent profile.
296 DISALLOW_COPY_AND_ASSIGN(TestingSyncSetupHandler);
299 // The boolean parameter indicates whether the test is run with ClientOAuth
300 // or not. The test parameter is a bool: whether or not to test with/
301 // /ClientLogin enabled or not.
302 class SyncSetupHandlerTest : public testing::Test {
304 SyncSetupHandlerTest() : error_(GoogleServiceAuthError::NONE) {}
305 virtual void SetUp() OVERRIDE {
306 error_ = GoogleServiceAuthError::AuthErrorNone();
307 profile_.reset(ProfileSyncServiceMock::MakeSignedInTestingProfile());
309 mock_pss_ = static_cast<ProfileSyncServiceMock*>(
310 ProfileSyncServiceFactory::GetInstance()->SetTestingFactoryAndUse(
312 ProfileSyncServiceMock::BuildMockProfileSyncService));
313 EXPECT_CALL(*mock_pss_, GetAuthError()).WillRepeatedly(ReturnRef(error_));
314 ON_CALL(*mock_pss_, GetPassphraseType()).WillByDefault(
315 Return(syncer::IMPLICIT_PASSPHRASE));
316 ON_CALL(*mock_pss_, GetPassphraseTime()).WillByDefault(
317 Return(base::Time()));
318 ON_CALL(*mock_pss_, GetExplicitPassphraseTime()).WillByDefault(
319 Return(base::Time()));
321 mock_pss_->Initialize();
323 #if defined(OS_CHROMEOS)
324 mock_signin_ = static_cast<SigninManagerBase*>(
325 SigninManagerFactory::GetInstance()->SetTestingFactoryAndUse(
326 profile_.get(), FakeSigninManagerBase::Build));
328 mock_signin_ = static_cast<SigninManagerBase*>(
329 SigninManagerFactory::GetInstance()->SetTestingFactoryAndUse(
330 profile_.get(), FakeSigninManager::Build));
332 handler_.reset(new TestingSyncSetupHandler(&web_ui_, profile_.get()));
335 // Setup the expectations for calls made when displaying the config page.
336 void SetDefaultExpectationsForConfigPage() {
337 EXPECT_CALL(*mock_pss_, IsSyncEnabledAndLoggedIn()).
338 WillRepeatedly(Return(true));
339 EXPECT_CALL(*mock_pss_, GetRegisteredDataTypes()).
340 WillRepeatedly(Return(GetAllTypes()));
341 EXPECT_CALL(*mock_pss_, GetPreferredDataTypes()).
342 WillRepeatedly(Return(GetAllTypes()));
343 EXPECT_CALL(*mock_pss_, GetActiveDataTypes()).
344 WillRepeatedly(Return(GetAllTypes()));
345 EXPECT_CALL(*mock_pss_, EncryptEverythingEnabled()).
346 WillRepeatedly(Return(false));
349 void SetupInitializedProfileSyncService() {
350 // An initialized ProfileSyncService will have already completed sync setup
351 // and will have an initialized sync backend.
352 if (!mock_signin_->IsInitialized()) {
353 profile_->GetPrefs()->SetString(
354 prefs::kGoogleServicesUsername, kTestUser);
355 mock_signin_->Initialize(profile_.get(), NULL);
357 EXPECT_CALL(*mock_pss_, IsSyncEnabledAndLoggedIn())
358 .WillRepeatedly(Return(true));
359 EXPECT_CALL(*mock_pss_, IsOAuthRefreshTokenAvailable())
360 .WillRepeatedly(Return(true));
361 EXPECT_CALL(*mock_pss_, HasSyncSetupCompleted())
362 .WillRepeatedly(Return(true));
363 EXPECT_CALL(*mock_pss_, sync_initialized()).WillRepeatedly(Return(true));
366 void ExpectConfig() {
367 ASSERT_EQ(1U, web_ui_.call_data().size());
368 const TestWebUI::CallData& data = web_ui_.call_data()[0];
369 EXPECT_EQ("SyncSetupOverlay.showSyncSetupPage", data.function_name);
371 ASSERT_TRUE(data.arg1->GetAsString(&page));
372 EXPECT_EQ(page, "configure");
376 ASSERT_EQ(1U, web_ui_.call_data().size());
377 const TestWebUI::CallData& data = web_ui_.call_data()[0];
378 EXPECT_EQ("SyncSetupOverlay.showSyncSetupPage", data.function_name);
380 ASSERT_TRUE(data.arg1->GetAsString(&page));
381 EXPECT_EQ(page, "done");
384 void ExpectSpinnerAndClose() {
385 // We expect a call to SyncSetupOverlay.showSyncSetupPage.
386 EXPECT_EQ(1U, web_ui_.call_data().size());
387 const TestWebUI::CallData& data = web_ui_.call_data()[0];
388 EXPECT_EQ("SyncSetupOverlay.showSyncSetupPage", data.function_name);
391 ASSERT_TRUE(data.arg1->GetAsString(&page));
392 EXPECT_EQ(page, "spinner");
393 // Cancelling the spinner dialog will cause CloseSyncSetup().
394 handler_->CloseSyncSetup();
396 LoginUIServiceFactory::GetForProfile(
397 profile_.get())->current_login_ui());
400 // It's difficult to notify sync listeners when using a ProfileSyncServiceMock
401 // so this helper routine dispatches an OnStateChanged() notification to the
402 // SyncStartupTracker.
403 void NotifySyncListeners() {
404 if (handler_->sync_startup_tracker_)
405 handler_->sync_startup_tracker_->OnStateChanged();
408 content::TestBrowserThreadBundle thread_bundle_;
409 scoped_ptr<Profile> profile_;
410 ProfileSyncServiceMock* mock_pss_;
411 GoogleServiceAuthError error_;
412 SigninManagerBase* mock_signin_;
414 scoped_ptr<TestingSyncSetupHandler> handler_;
417 TEST_F(SyncSetupHandlerTest, Basic) {
420 #if !defined(OS_CHROMEOS)
421 TEST_F(SyncSetupHandlerTest, DisplayBasicLogin) {
422 EXPECT_CALL(*mock_pss_, IsSyncEnabledAndLoggedIn())
423 .WillRepeatedly(Return(false));
424 EXPECT_CALL(*mock_pss_, IsOAuthRefreshTokenAvailable())
425 .WillRepeatedly(Return(false));
426 EXPECT_CALL(*mock_pss_, HasSyncSetupCompleted())
427 .WillRepeatedly(Return(false));
428 handler_->HandleStartSignin(NULL);
430 // Sync setup hands off control to the gaia login tab.
432 LoginUIServiceFactory::GetForProfile(
433 profile_.get())->current_login_ui());
435 ASSERT_FALSE(handler_->is_configuring_sync());
437 handler_->CloseSyncSetup();
439 LoginUIServiceFactory::GetForProfile(
440 profile_.get())->current_login_ui());
443 TEST_F(SyncSetupHandlerTest, ShowSyncSetupWhenNotSignedIn) {
444 EXPECT_CALL(*mock_pss_, IsSyncEnabledAndLoggedIn())
445 .WillRepeatedly(Return(false));
446 EXPECT_CALL(*mock_pss_, IsOAuthRefreshTokenAvailable())
447 .WillRepeatedly(Return(false));
448 EXPECT_CALL(*mock_pss_, HasSyncSetupCompleted())
449 .WillRepeatedly(Return(false));
450 handler_->HandleShowSetupUI(NULL);
452 // We expect a call to SyncSetupOverlay.showSyncSetupPage.
453 ASSERT_EQ(1U, web_ui_.call_data().size());
454 const TestWebUI::CallData& data = web_ui_.call_data()[0];
455 EXPECT_EQ("SyncSetupOverlay.showSyncSetupPage", data.function_name);
457 ASSERT_FALSE(handler_->is_configuring_sync());
459 LoginUIServiceFactory::GetForProfile(
460 profile_.get())->current_login_ui());
464 // Verifies that the handler correctly handles a cancellation when
465 // it is displaying the spinner to the user.
466 TEST_F(SyncSetupHandlerTest, DisplayConfigureWithBackendDisabledAndCancel) {
467 EXPECT_CALL(*mock_pss_, IsSyncEnabledAndLoggedIn())
468 .WillRepeatedly(Return(true));
469 profile_->GetPrefs()->SetString(prefs::kGoogleServicesUsername, kTestUser);
470 mock_signin_->Initialize(profile_.get(), NULL);
471 EXPECT_CALL(*mock_pss_, IsOAuthRefreshTokenAvailable())
472 .WillRepeatedly(Return(true));
473 EXPECT_CALL(*mock_pss_, HasSyncSetupCompleted())
474 .WillRepeatedly(Return(false));
475 error_ = GoogleServiceAuthError::AuthErrorNone();
476 EXPECT_CALL(*mock_pss_, sync_initialized()).WillRepeatedly(Return(false));
478 // We're simulating a user setting up sync, which would cause the backend to
479 // kick off initialization, but not download user data types. The sync
480 // backend will try to download control data types (e.g encryption info), but
481 // that won't finish for this test as we're simulating cancelling while the
482 // spinner is showing.
483 handler_->HandleShowSetupUI(NULL);
485 EXPECT_EQ(handler_.get(),
486 LoginUIServiceFactory::GetForProfile(
487 profile_.get())->current_login_ui());
489 ExpectSpinnerAndClose();
492 // Verifies that the handler correctly transitions from showing the spinner
493 // to showing a configuration page when sync setup completes successfully.
494 TEST_F(SyncSetupHandlerTest,
495 DisplayConfigureWithBackendDisabledAndSyncStartupCompleted) {
496 EXPECT_CALL(*mock_pss_, IsSyncEnabledAndLoggedIn())
497 .WillRepeatedly(Return(true));
498 profile_->GetPrefs()->SetString(prefs::kGoogleServicesUsername, kTestUser);
499 mock_signin_->Initialize(profile_.get(), NULL);
500 EXPECT_CALL(*mock_pss_, IsOAuthRefreshTokenAvailable())
501 .WillRepeatedly(Return(true));
502 EXPECT_CALL(*mock_pss_, HasSyncSetupCompleted())
503 .WillRepeatedly(Return(false));
504 error_ = GoogleServiceAuthError::AuthErrorNone();
505 // Sync backend is stopped initially, and will start up.
506 EXPECT_CALL(*mock_pss_, sync_initialized())
507 .WillRepeatedly(Return(false));
508 SetDefaultExpectationsForConfigPage();
510 handler_->OpenSyncSetup();
512 // We expect a call to SyncSetupOverlay.showSyncSetupPage.
513 EXPECT_EQ(1U, web_ui_.call_data().size());
515 const TestWebUI::CallData& data0 = web_ui_.call_data()[0];
516 EXPECT_EQ("SyncSetupOverlay.showSyncSetupPage", data0.function_name);
518 ASSERT_TRUE(data0.arg1->GetAsString(&page));
519 EXPECT_EQ(page, "spinner");
521 Mock::VerifyAndClearExpectations(mock_pss_);
522 // Now, act as if the ProfileSyncService has started up.
523 SetDefaultExpectationsForConfigPage();
524 EXPECT_CALL(*mock_pss_, sync_initialized())
525 .WillRepeatedly(Return(true));
526 error_ = GoogleServiceAuthError::AuthErrorNone();
527 EXPECT_CALL(*mock_pss_, GetAuthError()).WillRepeatedly(ReturnRef(error_));
528 NotifySyncListeners();
530 // We expect a second call to SyncSetupOverlay.showSyncSetupPage.
531 EXPECT_EQ(2U, web_ui_.call_data().size());
532 const TestWebUI::CallData& data1 = web_ui_.call_data().back();
533 EXPECT_EQ("SyncSetupOverlay.showSyncSetupPage", data1.function_name);
534 ASSERT_TRUE(data1.arg1->GetAsString(&page));
535 EXPECT_EQ(page, "configure");
536 DictionaryValue* dictionary;
537 ASSERT_TRUE(data1.arg2->GetAsDictionary(&dictionary));
538 CheckBool(dictionary, "passphraseFailed", false);
539 CheckBool(dictionary, "showSyncEverythingPage", false);
540 CheckBool(dictionary, "syncAllDataTypes", true);
541 CheckBool(dictionary, "encryptAllData", false);
542 CheckBool(dictionary, "usePassphrase", false);
545 // Verifies the case where the user cancels after the sync backend has
546 // initialized (meaning it already transitioned from the spinner to a proper
547 // configuration page, tested by
548 // DisplayConfigureWithBackendDisabledAndSigninSuccess), but before the user
549 // before the user has continued on.
550 TEST_F(SyncSetupHandlerTest,
551 DisplayConfigureWithBackendDisabledAndCancelAfterSigninSuccess) {
552 EXPECT_CALL(*mock_pss_, IsSyncEnabledAndLoggedIn())
553 .WillRepeatedly(Return(true));
554 profile_->GetPrefs()->SetString(prefs::kGoogleServicesUsername, kTestUser);
555 mock_signin_->Initialize(profile_.get(), NULL);
556 EXPECT_CALL(*mock_pss_, IsOAuthRefreshTokenAvailable())
557 .WillRepeatedly(Return(true));
558 EXPECT_CALL(*mock_pss_, HasSyncSetupCompleted())
559 .WillRepeatedly(Return(false));
560 error_ = GoogleServiceAuthError::AuthErrorNone();
561 EXPECT_CALL(*mock_pss_, sync_initialized())
562 .WillOnce(Return(false))
563 .WillRepeatedly(Return(true));
564 SetDefaultExpectationsForConfigPage();
565 handler_->OpenSyncSetup();
567 // It's important to tell sync the user cancelled the setup flow before we
568 // tell it we're through with the setup progress.
569 testing::InSequence seq;
570 EXPECT_CALL(*mock_pss_, DisableForUser());
571 EXPECT_CALL(*mock_pss_, SetSetupInProgress(false));
573 handler_->CloseSyncSetup();
575 LoginUIServiceFactory::GetForProfile(
576 profile_.get())->current_login_ui());
579 TEST_F(SyncSetupHandlerTest,
580 DisplayConfigureWithBackendDisabledAndSigninFailed) {
581 EXPECT_CALL(*mock_pss_, IsSyncEnabledAndLoggedIn())
582 .WillRepeatedly(Return(true));
583 profile_->GetPrefs()->SetString(prefs::kGoogleServicesUsername, kTestUser);
584 mock_signin_->Initialize(profile_.get(), NULL);
585 EXPECT_CALL(*mock_pss_, IsOAuthRefreshTokenAvailable())
586 .WillRepeatedly(Return(true));
587 EXPECT_CALL(*mock_pss_, HasSyncSetupCompleted())
588 .WillRepeatedly(Return(false));
589 error_ = GoogleServiceAuthError::AuthErrorNone();
590 EXPECT_CALL(*mock_pss_, sync_initialized()).WillRepeatedly(Return(false));
592 handler_->OpenSyncSetup();
593 const TestWebUI::CallData& data = web_ui_.call_data()[0];
594 EXPECT_EQ("SyncSetupOverlay.showSyncSetupPage", data.function_name);
596 ASSERT_TRUE(data.arg1->GetAsString(&page));
597 EXPECT_EQ(page, "spinner");
598 Mock::VerifyAndClearExpectations(mock_pss_);
599 error_ = GoogleServiceAuthError(
600 GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS);
601 EXPECT_CALL(*mock_pss_, GetAuthError()).WillRepeatedly(ReturnRef(error_));
602 NotifySyncListeners();
604 // On failure, the dialog will be closed.
606 LoginUIServiceFactory::GetForProfile(
607 profile_.get())->current_login_ui());
610 #if !defined(OS_CHROMEOS)
612 class SyncSetupHandlerNonCrosTest : public SyncSetupHandlerTest {
614 SyncSetupHandlerNonCrosTest() {}
615 virtual void SetUp() OVERRIDE {
616 SyncSetupHandlerTest::SetUp();
617 mock_signin_ = static_cast<SigninManagerBase*>(
618 SigninManagerFactory::GetInstance()->SetTestingFactoryAndUse(
619 profile_.get(), FakeSigninManager::Build));
623 TEST_F(SyncSetupHandlerNonCrosTest, HandleGaiaAuthFailure) {
624 EXPECT_CALL(*mock_pss_, IsSyncEnabledAndLoggedIn())
625 .WillRepeatedly(Return(false));
626 EXPECT_CALL(*mock_pss_, IsOAuthRefreshTokenAvailable())
627 .WillRepeatedly(Return(false));
628 EXPECT_CALL(*mock_pss_, HasUnrecoverableError())
629 .WillRepeatedly(Return(false));
630 EXPECT_CALL(*mock_pss_, HasSyncSetupCompleted())
631 .WillRepeatedly(Return(false));
633 handler_->OpenSyncSetup();
635 ASSERT_FALSE(handler_->is_configuring_sync());
638 // TODO(kochi): We need equivalent tests for ChromeOS.
639 TEST_F(SyncSetupHandlerNonCrosTest, UnrecoverableErrorInitializingSync) {
640 EXPECT_CALL(*mock_pss_, IsSyncEnabledAndLoggedIn())
641 .WillRepeatedly(Return(false));
642 EXPECT_CALL(*mock_pss_, IsOAuthRefreshTokenAvailable())
643 .WillRepeatedly(Return(false));
644 EXPECT_CALL(*mock_pss_, HasSyncSetupCompleted())
645 .WillRepeatedly(Return(false));
647 handler_->OpenSyncSetup();
649 ASSERT_FALSE(handler_->is_configuring_sync());
652 TEST_F(SyncSetupHandlerNonCrosTest, GaiaErrorInitializingSync) {
653 EXPECT_CALL(*mock_pss_, IsSyncEnabledAndLoggedIn())
654 .WillRepeatedly(Return(false));
655 EXPECT_CALL(*mock_pss_, IsOAuthRefreshTokenAvailable())
656 .WillRepeatedly(Return(false));
657 EXPECT_CALL(*mock_pss_, HasSyncSetupCompleted())
658 .WillRepeatedly(Return(false));
660 handler_->OpenSyncSetup();
662 ASSERT_FALSE(handler_->is_configuring_sync());
665 #endif // #if !defined(OS_CHROMEOS)
667 TEST_F(SyncSetupHandlerTest, TestSyncEverything) {
668 std::string args = GetConfiguration(
669 NULL, SYNC_ALL_DATA, GetAllTypes(), std::string(), ENCRYPT_PASSWORDS);
671 list_args.Append(new StringValue(args));
672 EXPECT_CALL(*mock_pss_, IsPassphraseRequiredForDecryption())
673 .WillRepeatedly(Return(false));
674 EXPECT_CALL(*mock_pss_, IsPassphraseRequired())
675 .WillRepeatedly(Return(false));
676 SetupInitializedProfileSyncService();
677 EXPECT_CALL(*mock_pss_, OnUserChoseDatatypes(true, _));
678 handler_->HandleConfigure(&list_args);
680 // Ensure that we navigated to the "done" state since we don't need a
685 TEST_F(SyncSetupHandlerTest, TestSyncNothing) {
686 std::string args = GetConfiguration(
687 NULL, SYNC_NOTHING, GetAllTypes(), std::string(), ENCRYPT_PASSWORDS);
689 list_args.Append(new StringValue(args));
690 EXPECT_CALL(*mock_pss_, DisableForUser());
691 SetupInitializedProfileSyncService();
692 handler_->HandleConfigure(&list_args);
694 // We expect a call to SyncSetupOverlay.showSyncSetupPage.
695 ASSERT_EQ(1U, web_ui_.call_data().size());
696 const TestWebUI::CallData& data = web_ui_.call_data()[0];
697 EXPECT_EQ("SyncSetupOverlay.showSyncSetupPage", data.function_name);
700 TEST_F(SyncSetupHandlerTest, TurnOnEncryptAll) {
701 std::string args = GetConfiguration(
702 NULL, SYNC_ALL_DATA, GetAllTypes(), std::string(), ENCRYPT_ALL_DATA);
704 list_args.Append(new StringValue(args));
705 EXPECT_CALL(*mock_pss_, IsPassphraseRequiredForDecryption())
706 .WillRepeatedly(Return(false));
707 EXPECT_CALL(*mock_pss_, IsPassphraseRequired())
708 .WillRepeatedly(Return(false));
709 SetupInitializedProfileSyncService();
710 EXPECT_CALL(*mock_pss_, EnableEncryptEverything());
711 EXPECT_CALL(*mock_pss_, OnUserChoseDatatypes(true, _));
712 handler_->HandleConfigure(&list_args);
714 // Ensure that we navigated to the "done" state since we don't need a
719 TEST_F(SyncSetupHandlerTest, TestPassphraseStillRequired) {
720 std::string args = GetConfiguration(
721 NULL, SYNC_ALL_DATA, GetAllTypes(), std::string(), ENCRYPT_PASSWORDS);
723 list_args.Append(new StringValue(args));
724 EXPECT_CALL(*mock_pss_, IsPassphraseRequiredForDecryption())
725 .WillRepeatedly(Return(true));
726 EXPECT_CALL(*mock_pss_, IsPassphraseRequired())
727 .WillRepeatedly(Return(true));
728 EXPECT_CALL(*mock_pss_, IsUsingSecondaryPassphrase())
729 .WillRepeatedly(Return(false));
730 SetupInitializedProfileSyncService();
731 EXPECT_CALL(*mock_pss_, OnUserChoseDatatypes(_, _));
732 SetDefaultExpectationsForConfigPage();
734 // We should navigate back to the configure page since we need a passphrase.
735 handler_->HandleConfigure(&list_args);
740 TEST_F(SyncSetupHandlerTest, SuccessfullySetPassphrase) {
741 DictionaryValue dict;
742 dict.SetBoolean("isGooglePassphrase", true);
743 std::string args = GetConfiguration(&dict,
749 list_args.Append(new StringValue(args));
750 // Act as if an encryption passphrase is required the first time, then never
752 EXPECT_CALL(*mock_pss_, IsPassphraseRequired()).WillOnce(Return(true));
753 EXPECT_CALL(*mock_pss_, IsPassphraseRequiredForDecryption())
754 .WillRepeatedly(Return(false));
755 EXPECT_CALL(*mock_pss_, IsUsingSecondaryPassphrase())
756 .WillRepeatedly(Return(false));
757 SetupInitializedProfileSyncService();
758 EXPECT_CALL(*mock_pss_, OnUserChoseDatatypes(_, _));
759 EXPECT_CALL(*mock_pss_, SetDecryptionPassphrase("gaiaPassphrase")).
760 WillOnce(Return(true));
762 handler_->HandleConfigure(&list_args);
763 // We should navigate to "done" page since we finished configuring.
767 TEST_F(SyncSetupHandlerTest, SelectCustomEncryption) {
768 DictionaryValue dict;
769 dict.SetBoolean("isGooglePassphrase", false);
770 std::string args = GetConfiguration(&dict,
776 list_args.Append(new StringValue(args));
777 EXPECT_CALL(*mock_pss_, IsPassphraseRequiredForDecryption())
778 .WillRepeatedly(Return(false));
779 EXPECT_CALL(*mock_pss_, IsPassphraseRequired())
780 .WillRepeatedly(Return(false));
781 EXPECT_CALL(*mock_pss_, IsUsingSecondaryPassphrase())
782 .WillRepeatedly(Return(false));
783 SetupInitializedProfileSyncService();
784 EXPECT_CALL(*mock_pss_, OnUserChoseDatatypes(_, _));
785 EXPECT_CALL(*mock_pss_,
786 SetEncryptionPassphrase("custom_passphrase",
787 ProfileSyncService::EXPLICIT));
789 handler_->HandleConfigure(&list_args);
790 // We should navigate to "done" page since we finished configuring.
794 TEST_F(SyncSetupHandlerTest, UnsuccessfullySetPassphrase) {
795 DictionaryValue dict;
796 dict.SetBoolean("isGooglePassphrase", true);
797 std::string args = GetConfiguration(&dict,
800 "invalid_passphrase",
803 list_args.Append(new StringValue(args));
804 EXPECT_CALL(*mock_pss_, IsPassphraseRequiredForDecryption())
805 .WillRepeatedly(Return(true));
806 EXPECT_CALL(*mock_pss_, IsPassphraseRequired())
807 .WillRepeatedly(Return(true));
808 EXPECT_CALL(*mock_pss_, IsUsingSecondaryPassphrase())
809 .WillRepeatedly(Return(false));
810 SetupInitializedProfileSyncService();
811 EXPECT_CALL(*mock_pss_, OnUserChoseDatatypes(_, _));
812 EXPECT_CALL(*mock_pss_, SetDecryptionPassphrase("invalid_passphrase")).
813 WillOnce(Return(false));
815 SetDefaultExpectationsForConfigPage();
816 // We should navigate back to the configure page since we need a passphrase.
817 handler_->HandleConfigure(&list_args);
821 // Make sure we display an error message to the user due to the failed
823 const TestWebUI::CallData& data = web_ui_.call_data()[0];
824 DictionaryValue* dictionary;
825 ASSERT_TRUE(data.arg2->GetAsDictionary(&dictionary));
826 CheckBool(dictionary, "passphraseFailed", true);
829 // Walks through each user selectable type, and tries to sync just that single
831 TEST_F(SyncSetupHandlerTest, TestSyncIndividualTypes) {
832 syncer::ModelTypeSet user_selectable_types = GetAllTypes();
833 syncer::ModelTypeSet::Iterator it;
834 for (it = user_selectable_types.First(); it.Good(); it.Inc()) {
835 syncer::ModelTypeSet type_to_set;
836 type_to_set.Put(it.Get());
837 std::string args = GetConfiguration(NULL,
843 list_args.Append(new StringValue(args));
844 EXPECT_CALL(*mock_pss_, IsPassphraseRequiredForDecryption())
845 .WillRepeatedly(Return(false));
846 EXPECT_CALL(*mock_pss_, IsPassphraseRequired())
847 .WillRepeatedly(Return(false));
848 SetupInitializedProfileSyncService();
849 EXPECT_CALL(*mock_pss_,
850 OnUserChoseDatatypes(false, ModelTypeSetMatches(type_to_set)));
851 handler_->HandleConfigure(&list_args);
854 Mock::VerifyAndClearExpectations(mock_pss_);
855 web_ui_.ClearTrackedCalls();
859 TEST_F(SyncSetupHandlerTest, TestSyncAllManually) {
860 std::string args = GetConfiguration(NULL,
866 list_args.Append(new StringValue(args));
867 EXPECT_CALL(*mock_pss_, IsPassphraseRequiredForDecryption())
868 .WillRepeatedly(Return(false));
869 EXPECT_CALL(*mock_pss_, IsPassphraseRequired())
870 .WillRepeatedly(Return(false));
871 SetupInitializedProfileSyncService();
872 EXPECT_CALL(*mock_pss_,
873 OnUserChoseDatatypes(false, ModelTypeSetMatches(GetAllTypes())));
874 handler_->HandleConfigure(&list_args);
879 TEST_F(SyncSetupHandlerTest, ShowSyncSetup) {
880 EXPECT_CALL(*mock_pss_, IsPassphraseRequired())
881 .WillRepeatedly(Return(false));
882 EXPECT_CALL(*mock_pss_, IsUsingSecondaryPassphrase())
883 .WillRepeatedly(Return(false));
884 SetupInitializedProfileSyncService();
885 // This should display the sync setup dialog (not login).
886 SetDefaultExpectationsForConfigPage();
887 handler_->OpenSyncSetup();
892 // We do not display signin on chromeos in the case of auth error.
893 TEST_F(SyncSetupHandlerTest, ShowSigninOnAuthError) {
894 // Initialize the system to a signed in state, but with an auth error.
895 error_ = GoogleServiceAuthError(
896 GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS);
898 SetupInitializedProfileSyncService();
899 mock_signin_->SetAuthenticatedUsername(kTestUser);
900 FakeAuthStatusProvider provider(
901 SigninGlobalError::GetForProfile(profile_.get()));
902 provider.SetAuthError(kTestUser, error_);
903 EXPECT_CALL(*mock_pss_, IsSyncEnabledAndLoggedIn())
904 .WillRepeatedly(Return(true));
905 EXPECT_CALL(*mock_pss_, IsOAuthRefreshTokenAvailable())
906 .WillRepeatedly(Return(true));
907 EXPECT_CALL(*mock_pss_, IsPassphraseRequired())
908 .WillRepeatedly(Return(false));
909 EXPECT_CALL(*mock_pss_, IsUsingSecondaryPassphrase())
910 .WillRepeatedly(Return(false));
911 EXPECT_CALL(*mock_pss_, sync_initialized()).WillRepeatedly(Return(false));
913 #if defined(OS_CHROMEOS)
914 // On ChromeOS, auth errors are ignored - instead we just try to start the
915 // sync backend (which will fail due to the auth error). This should only
916 // happen if the user manually navigates to chrome://settings/syncSetup -
917 // clicking on the button in the UI will sign the user out rather than
918 // displaying a spinner. Should be no visible UI on ChromeOS in this case.
919 EXPECT_EQ(NULL, LoginUIServiceFactory::GetForProfile(
920 profile_.get())->current_login_ui());
923 // On ChromeOS, this should display the spinner while we try to startup the
924 // sync backend, and on desktop this displays the login dialog.
925 handler_->OpenSyncSetup();
927 // Sync setup is closed when re-auth is in progress.
929 LoginUIServiceFactory::GetForProfile(
930 profile_.get())->current_login_ui());
932 ASSERT_FALSE(handler_->is_configuring_sync());
936 TEST_F(SyncSetupHandlerTest, ShowSetupSyncEverything) {
937 EXPECT_CALL(*mock_pss_, IsPassphraseRequired())
938 .WillRepeatedly(Return(false));
939 EXPECT_CALL(*mock_pss_, IsUsingSecondaryPassphrase())
940 .WillRepeatedly(Return(false));
941 SetupInitializedProfileSyncService();
942 SetDefaultExpectationsForConfigPage();
943 // This should display the sync setup dialog (not login).
944 handler_->OpenSyncSetup();
947 const TestWebUI::CallData& data = web_ui_.call_data()[0];
948 DictionaryValue* dictionary;
949 ASSERT_TRUE(data.arg2->GetAsDictionary(&dictionary));
950 CheckBool(dictionary, "showSyncEverythingPage", false);
951 CheckBool(dictionary, "syncAllDataTypes", true);
952 CheckBool(dictionary, "appsRegistered", true);
953 CheckBool(dictionary, "autofillRegistered", true);
954 CheckBool(dictionary, "bookmarksRegistered", true);
955 CheckBool(dictionary, "extensionsRegistered", true);
956 CheckBool(dictionary, "passwordsRegistered", true);
957 CheckBool(dictionary, "preferencesRegistered", true);
958 CheckBool(dictionary, "tabsRegistered", true);
959 CheckBool(dictionary, "themesRegistered", true);
960 CheckBool(dictionary, "typedUrlsRegistered", true);
961 CheckBool(dictionary, "showPassphrase", false);
962 CheckBool(dictionary, "usePassphrase", false);
963 CheckBool(dictionary, "passphraseFailed", false);
964 CheckBool(dictionary, "encryptAllData", false);
965 CheckConfigDataTypeArguments(dictionary, SYNC_ALL_DATA, GetAllTypes());
968 TEST_F(SyncSetupHandlerTest, ShowSetupManuallySyncAll) {
969 EXPECT_CALL(*mock_pss_, IsPassphraseRequired())
970 .WillRepeatedly(Return(false));
971 EXPECT_CALL(*mock_pss_, IsUsingSecondaryPassphrase())
972 .WillRepeatedly(Return(false));
973 SetupInitializedProfileSyncService();
974 browser_sync::SyncPrefs sync_prefs(profile_->GetPrefs());
975 sync_prefs.SetKeepEverythingSynced(false);
976 SetDefaultExpectationsForConfigPage();
977 // This should display the sync setup dialog (not login).
978 handler_->OpenSyncSetup();
981 const TestWebUI::CallData& data = web_ui_.call_data()[0];
982 DictionaryValue* dictionary;
983 ASSERT_TRUE(data.arg2->GetAsDictionary(&dictionary));
984 CheckConfigDataTypeArguments(dictionary, CHOOSE_WHAT_TO_SYNC, GetAllTypes());
987 TEST_F(SyncSetupHandlerTest, ShowSetupSyncForAllTypesIndividually) {
988 syncer::ModelTypeSet user_selectable_types = GetAllTypes();
989 syncer::ModelTypeSet::Iterator it;
990 for (it = user_selectable_types.First(); it.Good(); it.Inc()) {
991 EXPECT_CALL(*mock_pss_, IsPassphraseRequired())
992 .WillRepeatedly(Return(false));
993 EXPECT_CALL(*mock_pss_, IsUsingSecondaryPassphrase())
994 .WillRepeatedly(Return(false));
995 SetupInitializedProfileSyncService();
996 browser_sync::SyncPrefs sync_prefs(profile_->GetPrefs());
997 sync_prefs.SetKeepEverythingSynced(false);
998 SetDefaultExpectationsForConfigPage();
999 syncer::ModelTypeSet types;
1000 types.Put(it.Get());
1001 EXPECT_CALL(*mock_pss_, GetPreferredDataTypes()).
1002 WillRepeatedly(Return(types));
1004 // This should display the sync setup dialog (not login).
1005 handler_->OpenSyncSetup();
1008 // Close the config overlay.
1009 LoginUIServiceFactory::GetForProfile(profile_.get())->LoginUIClosed(
1011 const TestWebUI::CallData& data = web_ui_.call_data()[0];
1012 DictionaryValue* dictionary;
1013 ASSERT_TRUE(data.arg2->GetAsDictionary(&dictionary));
1014 CheckConfigDataTypeArguments(dictionary, CHOOSE_WHAT_TO_SYNC, types);
1015 Mock::VerifyAndClearExpectations(mock_pss_);
1016 // Clean up so we can loop back to display the dialog again.
1017 web_ui_.ClearTrackedCalls();
1021 TEST_F(SyncSetupHandlerTest, ShowSetupGaiaPassphraseRequired) {
1022 EXPECT_CALL(*mock_pss_, IsPassphraseRequired())
1023 .WillRepeatedly(Return(true));
1024 EXPECT_CALL(*mock_pss_, IsUsingSecondaryPassphrase())
1025 .WillRepeatedly(Return(false));
1026 SetupInitializedProfileSyncService();
1027 SetDefaultExpectationsForConfigPage();
1029 // This should display the sync setup dialog (not login).
1030 handler_->OpenSyncSetup();
1033 const TestWebUI::CallData& data = web_ui_.call_data()[0];
1034 DictionaryValue* dictionary;
1035 ASSERT_TRUE(data.arg2->GetAsDictionary(&dictionary));
1036 CheckBool(dictionary, "showPassphrase", true);
1037 CheckBool(dictionary, "usePassphrase", false);
1038 CheckBool(dictionary, "passphraseFailed", false);
1041 TEST_F(SyncSetupHandlerTest, ShowSetupCustomPassphraseRequired) {
1042 EXPECT_CALL(*mock_pss_, IsPassphraseRequired())
1043 .WillRepeatedly(Return(true));
1044 EXPECT_CALL(*mock_pss_, IsUsingSecondaryPassphrase())
1045 .WillRepeatedly(Return(true));
1046 EXPECT_CALL(*mock_pss_, GetPassphraseType())
1047 .WillRepeatedly(Return(syncer::CUSTOM_PASSPHRASE));
1048 SetupInitializedProfileSyncService();
1049 SetDefaultExpectationsForConfigPage();
1051 // This should display the sync setup dialog (not login).
1052 handler_->OpenSyncSetup();
1055 const TestWebUI::CallData& data = web_ui_.call_data()[0];
1056 DictionaryValue* dictionary;
1057 ASSERT_TRUE(data.arg2->GetAsDictionary(&dictionary));
1058 CheckBool(dictionary, "showPassphrase", true);
1059 CheckBool(dictionary, "usePassphrase", true);
1060 CheckBool(dictionary, "passphraseFailed", false);
1063 TEST_F(SyncSetupHandlerTest, ShowSetupEncryptAll) {
1064 EXPECT_CALL(*mock_pss_, IsPassphraseRequired())
1065 .WillRepeatedly(Return(false));
1066 EXPECT_CALL(*mock_pss_, IsUsingSecondaryPassphrase())
1067 .WillRepeatedly(Return(false));
1068 SetupInitializedProfileSyncService();
1069 SetDefaultExpectationsForConfigPage();
1070 EXPECT_CALL(*mock_pss_, EncryptEverythingEnabled()).
1071 WillRepeatedly(Return(true));
1073 // This should display the sync setup dialog (not login).
1074 handler_->OpenSyncSetup();
1077 const TestWebUI::CallData& data = web_ui_.call_data()[0];
1078 DictionaryValue* dictionary;
1079 ASSERT_TRUE(data.arg2->GetAsDictionary(&dictionary));
1080 CheckBool(dictionary, "encryptAllData", true);