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_signin_manager.h"
16 #include "chrome/browser/signin/profile_oauth2_token_service_factory.h"
17 #include "chrome/browser/signin/signin_manager_factory.h"
18 #include "chrome/browser/sync/profile_sync_service_factory.h"
19 #include "chrome/browser/sync/profile_sync_service_mock.h"
20 #include "chrome/browser/ui/webui/signin/login_ui_service.h"
21 #include "chrome/browser/ui/webui/signin/login_ui_service_factory.h"
22 #include "chrome/common/chrome_switches.h"
23 #include "chrome/common/pref_names.h"
24 #include "chrome/test/base/scoped_testing_local_state.h"
25 #include "chrome/test/base/testing_browser_process.h"
26 #include "chrome/test/base/testing_profile.h"
27 #include "components/signin/core/browser/fake_auth_status_provider.h"
28 #include "components/signin/core/browser/profile_oauth2_token_service.h"
29 #include "components/signin/core/browser/signin_manager.h"
30 #include "components/sync_driver/sync_prefs.h"
31 #include "content/public/browser/web_ui.h"
32 #include "content/public/test/test_browser_thread.h"
33 #include "content/public/test/test_browser_thread_bundle.h"
34 #include "grit/generated_resources.h"
35 #include "testing/gtest/include/gtest/gtest.h"
36 #include "ui/base/l10n/l10n_util.h"
37 #include "ui/base/layout.h"
40 using ::testing::Mock;
41 using ::testing::Return;
42 using ::testing::ReturnRef;
43 using ::testing::Values;
45 typedef GoogleServiceAuthError AuthError;
49 MATCHER_P(ModelTypeSetMatches, value, "") { return arg.Equals(value); }
51 const char kTestUser[] = "chrome.p13n.test@gmail.com";
53 // Returns a ModelTypeSet with all user selectable types set.
54 syncer::ModelTypeSet GetAllTypes() {
55 return syncer::UserSelectableTypes();
58 enum SyncAllDataConfig {
64 enum EncryptAllConfig {
69 // Create a json-format string with the key/value pairs appropriate for a call
70 // to HandleConfigure(). If |extra_values| is non-null, then the values from
71 // the passed dictionary are added to the json.
72 std::string GetConfiguration(const base::DictionaryValue* extra_values,
73 SyncAllDataConfig sync_all,
74 syncer::ModelTypeSet types,
75 const std::string& passphrase,
76 EncryptAllConfig encrypt_all) {
77 base::DictionaryValue result;
79 result.MergeDictionary(extra_values);
80 result.SetBoolean("syncAllDataTypes", sync_all == SYNC_ALL_DATA);
81 result.SetBoolean("syncNothing", sync_all == SYNC_NOTHING);
82 result.SetBoolean("encryptAllData", encrypt_all == ENCRYPT_ALL_DATA);
83 result.SetBoolean("usePassphrase", !passphrase.empty());
84 if (!passphrase.empty())
85 result.SetString("passphrase", passphrase);
86 // Add all of our data types.
87 result.SetBoolean("appsSynced", types.Has(syncer::APPS));
88 result.SetBoolean("autofillSynced", types.Has(syncer::AUTOFILL));
89 result.SetBoolean("bookmarksSynced", types.Has(syncer::BOOKMARKS));
90 result.SetBoolean("extensionsSynced", types.Has(syncer::EXTENSIONS));
91 result.SetBoolean("passwordsSynced", types.Has(syncer::PASSWORDS));
92 result.SetBoolean("preferencesSynced", types.Has(syncer::PREFERENCES));
93 result.SetBoolean("tabsSynced", types.Has(syncer::PROXY_TABS));
94 result.SetBoolean("themesSynced", types.Has(syncer::THEMES));
95 result.SetBoolean("typedUrlsSynced", types.Has(syncer::TYPED_URLS));
97 base::JSONWriter::Write(&result, &args);
101 // Checks whether the passed |dictionary| contains a |key| with the given
102 // |expected_value|. If |omit_if_false| is true, then the value should only
103 // be present if |expected_value| is true.
104 void CheckBool(const base::DictionaryValue* dictionary,
105 const std::string& key,
107 bool omit_if_false) {
108 if (omit_if_false && !expected_value) {
109 EXPECT_FALSE(dictionary->HasKey(key)) <<
110 "Did not expect to find value for " << key;
113 EXPECT_TRUE(dictionary->GetBoolean(key, &actual_value)) <<
114 "No value found for " << key;
115 EXPECT_EQ(actual_value, expected_value) <<
116 "Mismatch found for " << key;
120 void CheckBool(const base::DictionaryValue* dictionary,
121 const std::string& key,
122 bool expected_value) {
123 return CheckBool(dictionary, key, expected_value, false);
126 // Checks to make sure that the values stored in |dictionary| match the values
127 // expected by the showSyncSetupPage() JS function for a given set of data
129 void CheckConfigDataTypeArguments(base::DictionaryValue* dictionary,
130 SyncAllDataConfig config,
131 syncer::ModelTypeSet types) {
132 CheckBool(dictionary, "syncAllDataTypes", config == SYNC_ALL_DATA);
133 CheckBool(dictionary, "syncNothing", config == SYNC_NOTHING);
134 CheckBool(dictionary, "appsSynced", types.Has(syncer::APPS));
135 CheckBool(dictionary, "autofillSynced", types.Has(syncer::AUTOFILL));
136 CheckBool(dictionary, "bookmarksSynced", types.Has(syncer::BOOKMARKS));
137 CheckBool(dictionary, "extensionsSynced", types.Has(syncer::EXTENSIONS));
138 CheckBool(dictionary, "passwordsSynced", types.Has(syncer::PASSWORDS));
139 CheckBool(dictionary, "preferencesSynced", types.Has(syncer::PREFERENCES));
140 CheckBool(dictionary, "tabsSynced", types.Has(syncer::PROXY_TABS));
141 CheckBool(dictionary, "themesSynced", types.Has(syncer::THEMES));
142 CheckBool(dictionary, "typedUrlsSynced", types.Has(syncer::TYPED_URLS));
148 // Test instance of WebUI that tracks the data passed to
149 // CallJavascriptFunction().
150 class TestWebUI : public content::WebUI {
152 virtual ~TestWebUI() {
156 void ClearTrackedCalls() {
157 // Manually free the arguments stored in CallData, since there's no good
158 // way to use a self-freeing reference like scoped_ptr in a std::vector.
159 for (std::vector<CallData>::iterator i = call_data_.begin();
160 i != call_data_.end();
168 virtual void CallJavascriptFunction(const std::string& function_name)
170 call_data_.push_back(CallData());
171 call_data_.back().function_name = function_name;
174 virtual void CallJavascriptFunction(const std::string& function_name,
175 const base::Value& arg1) OVERRIDE {
176 call_data_.push_back(CallData());
177 call_data_.back().function_name = function_name;
178 call_data_.back().arg1 = arg1.DeepCopy();
181 virtual void CallJavascriptFunction(const std::string& function_name,
182 const base::Value& arg1,
183 const base::Value& arg2) OVERRIDE {
184 call_data_.push_back(CallData());
185 call_data_.back().function_name = function_name;
186 call_data_.back().arg1 = arg1.DeepCopy();
187 call_data_.back().arg2 = arg2.DeepCopy();
190 virtual content::WebContents* GetWebContents() const OVERRIDE {
193 virtual content::WebUIController* GetController() const OVERRIDE {
196 virtual void SetController(content::WebUIController* controller) OVERRIDE {}
197 virtual float GetDeviceScaleFactor() const OVERRIDE {
200 virtual const base::string16& GetOverriddenTitle() const OVERRIDE {
203 virtual void OverrideTitle(const base::string16& title) OVERRIDE {}
204 virtual content::PageTransition GetLinkTransitionType() const OVERRIDE {
205 return content::PAGE_TRANSITION_LINK;
207 virtual void SetLinkTransitionType(content::PageTransition type) OVERRIDE {}
208 virtual int GetBindings() const OVERRIDE {
211 virtual void SetBindings(int bindings) OVERRIDE {}
212 virtual void OverrideJavaScriptFrame(
213 const std::string& frame_name) OVERRIDE {}
214 virtual void AddMessageHandler(
215 content::WebUIMessageHandler* handler) OVERRIDE {}
216 virtual void RegisterMessageCallback(
217 const std::string& message,
218 const MessageCallback& callback) OVERRIDE {}
219 virtual void ProcessWebUIMessage(const GURL& source_url,
220 const std::string& message,
221 const base::ListValue& args) OVERRIDE {}
222 virtual void CallJavascriptFunction(const std::string& function_name,
223 const base::Value& arg1,
224 const base::Value& arg2,
225 const base::Value& arg3) OVERRIDE {}
226 virtual void CallJavascriptFunction(const std::string& function_name,
227 const base::Value& arg1,
228 const base::Value& arg2,
229 const base::Value& arg3,
230 const base::Value& arg4) OVERRIDE {}
231 virtual void CallJavascriptFunction(
232 const std::string& function_name,
233 const std::vector<const base::Value*>& args) OVERRIDE {}
237 CallData() : arg1(NULL), arg2(NULL) {}
238 std::string function_name;
242 const std::vector<CallData>& call_data() { return call_data_; }
244 std::vector<CallData> call_data_;
245 base::string16 temp_string_;
248 class TestingSyncSetupHandler : public SyncSetupHandler {
250 TestingSyncSetupHandler(content::WebUI* web_ui, Profile* profile)
251 : SyncSetupHandler(NULL),
255 virtual ~TestingSyncSetupHandler() {
259 virtual void FocusUI() OVERRIDE {}
261 virtual Profile* GetProfile() const OVERRIDE { return profile_; }
263 using SyncSetupHandler::is_configuring_sync;
266 #if !defined(OS_CHROMEOS)
267 virtual void DisplayGaiaLoginInNewTabOrWindow() OVERRIDE {}
270 // Weak pointer to parent profile.
272 DISALLOW_COPY_AND_ASSIGN(TestingSyncSetupHandler);
275 // The boolean parameter indicates whether the test is run with ClientOAuth
276 // or not. The test parameter is a bool: whether or not to test with/
277 // /ClientLogin enabled or not.
278 class SyncSetupHandlerTest : public testing::Test {
280 SyncSetupHandlerTest() : error_(GoogleServiceAuthError::NONE) {}
281 virtual void SetUp() OVERRIDE {
282 error_ = GoogleServiceAuthError::AuthErrorNone();
284 TestingProfile::Builder builder;
285 builder.AddTestingFactory(SigninManagerFactory::GetInstance(),
286 FakeSigninManagerBase::Build);
287 profile_ = builder.Build();
290 mock_signin_ = static_cast<SigninManagerBase*>(
291 SigninManagerFactory::GetForProfile(profile_.get()));
292 mock_signin_->SetAuthenticatedUsername(GetTestUser());
293 profile_->GetPrefs()->SetString(prefs::kGoogleServicesUsername,
296 mock_pss_ = static_cast<ProfileSyncServiceMock*>(
297 ProfileSyncServiceFactory::GetInstance()->SetTestingFactoryAndUse(
299 ProfileSyncServiceMock::BuildMockProfileSyncService));
300 EXPECT_CALL(*mock_pss_, GetAuthError()).WillRepeatedly(ReturnRef(error_));
301 ON_CALL(*mock_pss_, GetPassphraseType()).WillByDefault(
302 Return(syncer::IMPLICIT_PASSPHRASE));
303 ON_CALL(*mock_pss_, GetPassphraseTime()).WillByDefault(
304 Return(base::Time()));
305 ON_CALL(*mock_pss_, GetExplicitPassphraseTime()).WillByDefault(
306 Return(base::Time()));
307 ON_CALL(*mock_pss_, GetRegisteredDataTypes())
308 .WillByDefault(Return(syncer::ModelTypeSet()));
310 mock_pss_->Initialize();
312 handler_.reset(new TestingSyncSetupHandler(&web_ui_, profile_.get()));
315 // Setup the expectations for calls made when displaying the config page.
316 void SetDefaultExpectationsForConfigPage() {
317 EXPECT_CALL(*mock_pss_, IsSyncEnabledAndLoggedIn()).
318 WillRepeatedly(Return(true));
319 EXPECT_CALL(*mock_pss_, GetRegisteredDataTypes()).
320 WillRepeatedly(Return(GetAllTypes()));
321 EXPECT_CALL(*mock_pss_, GetPreferredDataTypes()).
322 WillRepeatedly(Return(GetAllTypes()));
323 EXPECT_CALL(*mock_pss_, GetActiveDataTypes()).
324 WillRepeatedly(Return(GetAllTypes()));
325 EXPECT_CALL(*mock_pss_, EncryptEverythingEnabled()).
326 WillRepeatedly(Return(false));
329 void SetupInitializedProfileSyncService() {
330 // An initialized ProfileSyncService will have already completed sync setup
331 // and will have an initialized sync backend.
332 ASSERT_TRUE(mock_signin_->IsInitialized());
333 EXPECT_CALL(*mock_pss_, sync_initialized()).WillRepeatedly(Return(true));
336 void ExpectConfig() {
337 ASSERT_EQ(1U, web_ui_.call_data().size());
338 const TestWebUI::CallData& data = web_ui_.call_data()[0];
339 EXPECT_EQ("SyncSetupOverlay.showSyncSetupPage", data.function_name);
341 ASSERT_TRUE(data.arg1->GetAsString(&page));
342 EXPECT_EQ(page, "configure");
346 ASSERT_EQ(1U, web_ui_.call_data().size());
347 const TestWebUI::CallData& data = web_ui_.call_data()[0];
348 EXPECT_EQ("SyncSetupOverlay.showSyncSetupPage", data.function_name);
350 ASSERT_TRUE(data.arg1->GetAsString(&page));
351 EXPECT_EQ(page, "done");
354 void ExpectSpinnerAndClose() {
355 // We expect a call to SyncSetupOverlay.showSyncSetupPage.
356 EXPECT_EQ(1U, web_ui_.call_data().size());
357 const TestWebUI::CallData& data = web_ui_.call_data()[0];
358 EXPECT_EQ("SyncSetupOverlay.showSyncSetupPage", data.function_name);
361 ASSERT_TRUE(data.arg1->GetAsString(&page));
362 EXPECT_EQ(page, "spinner");
363 // Cancelling the spinner dialog will cause CloseSyncSetup().
364 handler_->CloseSyncSetup();
366 LoginUIServiceFactory::GetForProfile(
367 profile_.get())->current_login_ui());
370 // It's difficult to notify sync listeners when using a ProfileSyncServiceMock
371 // so this helper routine dispatches an OnStateChanged() notification to the
372 // SyncStartupTracker.
373 void NotifySyncListeners() {
374 if (handler_->sync_startup_tracker_)
375 handler_->sync_startup_tracker_->OnStateChanged();
378 virtual std::string GetTestUser() {
379 return std::string(kTestUser);
382 content::TestBrowserThreadBundle thread_bundle_;
383 scoped_ptr<Profile> profile_;
384 ProfileSyncServiceMock* mock_pss_;
385 GoogleServiceAuthError error_;
386 SigninManagerBase* mock_signin_;
388 scoped_ptr<TestingSyncSetupHandler> handler_;
391 class SyncSetupHandlerFirstSigninTest : public SyncSetupHandlerTest {
392 virtual std::string GetTestUser() OVERRIDE { return std::string(); }
395 TEST_F(SyncSetupHandlerTest, Basic) {
398 #if !defined(OS_CHROMEOS)
399 TEST_F(SyncSetupHandlerFirstSigninTest, DisplayBasicLogin) {
400 EXPECT_CALL(*mock_pss_, IsSyncEnabledAndLoggedIn())
401 .WillRepeatedly(Return(false));
402 EXPECT_CALL(*mock_pss_, IsOAuthRefreshTokenAvailable())
403 .WillRepeatedly(Return(false));
404 EXPECT_CALL(*mock_pss_, HasSyncSetupCompleted())
405 .WillRepeatedly(Return(false));
406 // Ensure that the user is not signed in before calling |HandleStartSignin()|.
407 SigninManager* manager = static_cast<SigninManager*>(mock_signin_);
409 handler_->HandleStartSignin(NULL);
411 // Sync setup hands off control to the gaia login tab.
413 LoginUIServiceFactory::GetForProfile(
414 profile_.get())->current_login_ui());
416 ASSERT_FALSE(handler_->is_configuring_sync());
418 handler_->CloseSyncSetup();
420 LoginUIServiceFactory::GetForProfile(
421 profile_.get())->current_login_ui());
424 TEST_F(SyncSetupHandlerTest, ShowSyncSetupWhenNotSignedIn) {
425 EXPECT_CALL(*mock_pss_, IsSyncEnabledAndLoggedIn())
426 .WillRepeatedly(Return(false));
427 EXPECT_CALL(*mock_pss_, IsOAuthRefreshTokenAvailable())
428 .WillRepeatedly(Return(false));
429 EXPECT_CALL(*mock_pss_, HasSyncSetupCompleted())
430 .WillRepeatedly(Return(false));
431 handler_->HandleShowSetupUI(NULL);
433 // We expect a call to SyncSetupOverlay.showSyncSetupPage.
434 ASSERT_EQ(1U, web_ui_.call_data().size());
435 const TestWebUI::CallData& data = web_ui_.call_data()[0];
436 EXPECT_EQ("SyncSetupOverlay.showSyncSetupPage", data.function_name);
438 ASSERT_FALSE(handler_->is_configuring_sync());
440 LoginUIServiceFactory::GetForProfile(
441 profile_.get())->current_login_ui());
443 #endif // !defined(OS_CHROMEOS)
445 // Verifies that the sync setup is terminated correctly when the
447 TEST_F(SyncSetupHandlerTest, HandleSetupUIWhenSyncDisabled) {
448 EXPECT_CALL(*mock_pss_, IsManaged()).WillRepeatedly(Return(true));
449 handler_->HandleShowSetupUI(NULL);
451 // Sync setup is closed when sync is disabled.
453 LoginUIServiceFactory::GetForProfile(
454 profile_.get())->current_login_ui());
455 ASSERT_FALSE(handler_->is_configuring_sync());
458 // Verifies that the handler correctly handles a cancellation when
459 // it is displaying the spinner to the user.
460 TEST_F(SyncSetupHandlerTest, DisplayConfigureWithBackendDisabledAndCancel) {
461 EXPECT_CALL(*mock_pss_, IsSyncEnabledAndLoggedIn())
462 .WillRepeatedly(Return(true));
463 EXPECT_CALL(*mock_pss_, IsOAuthRefreshTokenAvailable())
464 .WillRepeatedly(Return(true));
465 EXPECT_CALL(*mock_pss_, HasSyncSetupCompleted())
466 .WillRepeatedly(Return(false));
467 error_ = GoogleServiceAuthError::AuthErrorNone();
468 EXPECT_CALL(*mock_pss_, sync_initialized()).WillRepeatedly(Return(false));
470 // We're simulating a user setting up sync, which would cause the backend to
471 // kick off initialization, but not download user data types. The sync
472 // backend will try to download control data types (e.g encryption info), but
473 // that won't finish for this test as we're simulating cancelling while the
474 // spinner is showing.
475 handler_->HandleShowSetupUI(NULL);
477 EXPECT_EQ(handler_.get(),
478 LoginUIServiceFactory::GetForProfile(
479 profile_.get())->current_login_ui());
481 ExpectSpinnerAndClose();
484 // Verifies that the handler correctly transitions from showing the spinner
485 // to showing a configuration page when sync setup completes successfully.
486 TEST_F(SyncSetupHandlerTest,
487 DisplayConfigureWithBackendDisabledAndSyncStartupCompleted) {
488 EXPECT_CALL(*mock_pss_, IsSyncEnabledAndLoggedIn())
489 .WillRepeatedly(Return(true));
490 EXPECT_CALL(*mock_pss_, IsOAuthRefreshTokenAvailable())
491 .WillRepeatedly(Return(true));
492 EXPECT_CALL(*mock_pss_, HasSyncSetupCompleted())
493 .WillRepeatedly(Return(false));
494 error_ = GoogleServiceAuthError::AuthErrorNone();
495 // Sync backend is stopped initially, and will start up.
496 EXPECT_CALL(*mock_pss_, sync_initialized())
497 .WillRepeatedly(Return(false));
498 SetDefaultExpectationsForConfigPage();
500 handler_->OpenSyncSetup();
502 // We expect a call to SyncSetupOverlay.showSyncSetupPage.
503 EXPECT_EQ(1U, web_ui_.call_data().size());
505 const TestWebUI::CallData& data0 = web_ui_.call_data()[0];
506 EXPECT_EQ("SyncSetupOverlay.showSyncSetupPage", data0.function_name);
508 ASSERT_TRUE(data0.arg1->GetAsString(&page));
509 EXPECT_EQ(page, "spinner");
511 Mock::VerifyAndClearExpectations(mock_pss_);
512 // Now, act as if the ProfileSyncService has started up.
513 SetDefaultExpectationsForConfigPage();
514 EXPECT_CALL(*mock_pss_, sync_initialized())
515 .WillRepeatedly(Return(true));
516 error_ = GoogleServiceAuthError::AuthErrorNone();
517 EXPECT_CALL(*mock_pss_, GetAuthError()).WillRepeatedly(ReturnRef(error_));
518 NotifySyncListeners();
520 // We expect a second call to SyncSetupOverlay.showSyncSetupPage.
521 EXPECT_EQ(2U, web_ui_.call_data().size());
522 const TestWebUI::CallData& data1 = web_ui_.call_data().back();
523 EXPECT_EQ("SyncSetupOverlay.showSyncSetupPage", data1.function_name);
524 ASSERT_TRUE(data1.arg1->GetAsString(&page));
525 EXPECT_EQ(page, "configure");
526 base::DictionaryValue* dictionary;
527 ASSERT_TRUE(data1.arg2->GetAsDictionary(&dictionary));
528 CheckBool(dictionary, "passphraseFailed", false);
529 CheckBool(dictionary, "showSyncEverythingPage", false);
530 CheckBool(dictionary, "syncAllDataTypes", true);
531 CheckBool(dictionary, "encryptAllData", false);
532 CheckBool(dictionary, "usePassphrase", false);
535 // Verifies the case where the user cancels after the sync backend has
536 // initialized (meaning it already transitioned from the spinner to a proper
537 // configuration page, tested by
538 // DisplayConfigureWithBackendDisabledAndSigninSuccess), but before the user
539 // before the user has continued on.
540 TEST_F(SyncSetupHandlerTest,
541 DisplayConfigureWithBackendDisabledAndCancelAfterSigninSuccess) {
542 EXPECT_CALL(*mock_pss_, IsSyncEnabledAndLoggedIn())
543 .WillRepeatedly(Return(true));
544 EXPECT_CALL(*mock_pss_, IsOAuthRefreshTokenAvailable())
545 .WillRepeatedly(Return(true));
546 EXPECT_CALL(*mock_pss_, HasSyncSetupCompleted())
547 .WillRepeatedly(Return(false));
548 error_ = GoogleServiceAuthError::AuthErrorNone();
549 EXPECT_CALL(*mock_pss_, sync_initialized())
550 .WillOnce(Return(false))
551 .WillRepeatedly(Return(true));
552 SetDefaultExpectationsForConfigPage();
553 handler_->OpenSyncSetup();
555 // It's important to tell sync the user cancelled the setup flow before we
556 // tell it we're through with the setup progress.
557 testing::InSequence seq;
558 EXPECT_CALL(*mock_pss_, DisableForUser());
559 EXPECT_CALL(*mock_pss_, SetSetupInProgress(false));
561 handler_->CloseSyncSetup();
563 LoginUIServiceFactory::GetForProfile(
564 profile_.get())->current_login_ui());
567 TEST_F(SyncSetupHandlerTest,
568 DisplayConfigureWithBackendDisabledAndSigninFailed) {
569 EXPECT_CALL(*mock_pss_, IsSyncEnabledAndLoggedIn())
570 .WillRepeatedly(Return(true));
571 EXPECT_CALL(*mock_pss_, IsOAuthRefreshTokenAvailable())
572 .WillRepeatedly(Return(true));
573 EXPECT_CALL(*mock_pss_, HasSyncSetupCompleted())
574 .WillRepeatedly(Return(false));
575 error_ = GoogleServiceAuthError::AuthErrorNone();
576 EXPECT_CALL(*mock_pss_, sync_initialized()).WillRepeatedly(Return(false));
578 handler_->OpenSyncSetup();
579 const TestWebUI::CallData& data = web_ui_.call_data()[0];
580 EXPECT_EQ("SyncSetupOverlay.showSyncSetupPage", data.function_name);
582 ASSERT_TRUE(data.arg1->GetAsString(&page));
583 EXPECT_EQ(page, "spinner");
584 Mock::VerifyAndClearExpectations(mock_pss_);
585 error_ = GoogleServiceAuthError(
586 GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS);
587 EXPECT_CALL(*mock_pss_, GetAuthError()).WillRepeatedly(ReturnRef(error_));
588 NotifySyncListeners();
590 // On failure, the dialog will be closed.
592 LoginUIServiceFactory::GetForProfile(
593 profile_.get())->current_login_ui());
596 #if !defined(OS_CHROMEOS)
598 class SyncSetupHandlerNonCrosTest : public SyncSetupHandlerTest {
600 SyncSetupHandlerNonCrosTest() {}
603 TEST_F(SyncSetupHandlerNonCrosTest, HandleGaiaAuthFailure) {
604 EXPECT_CALL(*mock_pss_, IsSyncEnabledAndLoggedIn())
605 .WillRepeatedly(Return(false));
606 EXPECT_CALL(*mock_pss_, IsOAuthRefreshTokenAvailable())
607 .WillRepeatedly(Return(false));
608 EXPECT_CALL(*mock_pss_, HasUnrecoverableError())
609 .WillRepeatedly(Return(false));
610 EXPECT_CALL(*mock_pss_, HasSyncSetupCompleted())
611 .WillRepeatedly(Return(false));
613 handler_->OpenSyncSetup();
615 ASSERT_FALSE(handler_->is_configuring_sync());
618 // TODO(kochi): We need equivalent tests for ChromeOS.
619 TEST_F(SyncSetupHandlerNonCrosTest, UnrecoverableErrorInitializingSync) {
620 EXPECT_CALL(*mock_pss_, IsSyncEnabledAndLoggedIn())
621 .WillRepeatedly(Return(false));
622 EXPECT_CALL(*mock_pss_, IsOAuthRefreshTokenAvailable())
623 .WillRepeatedly(Return(false));
624 EXPECT_CALL(*mock_pss_, HasSyncSetupCompleted())
625 .WillRepeatedly(Return(false));
627 handler_->OpenSyncSetup();
629 ASSERT_FALSE(handler_->is_configuring_sync());
632 TEST_F(SyncSetupHandlerNonCrosTest, GaiaErrorInitializingSync) {
633 EXPECT_CALL(*mock_pss_, IsSyncEnabledAndLoggedIn())
634 .WillRepeatedly(Return(false));
635 EXPECT_CALL(*mock_pss_, IsOAuthRefreshTokenAvailable())
636 .WillRepeatedly(Return(false));
637 EXPECT_CALL(*mock_pss_, HasSyncSetupCompleted())
638 .WillRepeatedly(Return(false));
640 handler_->OpenSyncSetup();
642 ASSERT_FALSE(handler_->is_configuring_sync());
645 #endif // #if !defined(OS_CHROMEOS)
647 TEST_F(SyncSetupHandlerTest, TestSyncEverything) {
648 std::string args = GetConfiguration(
649 NULL, SYNC_ALL_DATA, GetAllTypes(), std::string(), ENCRYPT_PASSWORDS);
650 base::ListValue list_args;
651 list_args.Append(new base::StringValue(args));
652 EXPECT_CALL(*mock_pss_, IsPassphraseRequiredForDecryption())
653 .WillRepeatedly(Return(false));
654 EXPECT_CALL(*mock_pss_, IsPassphraseRequired())
655 .WillRepeatedly(Return(false));
656 SetupInitializedProfileSyncService();
657 EXPECT_CALL(*mock_pss_, OnUserChoseDatatypes(true, _));
658 handler_->HandleConfigure(&list_args);
660 // Ensure that we navigated to the "done" state since we don't need a
665 TEST_F(SyncSetupHandlerTest, TestSyncNothing) {
666 std::string args = GetConfiguration(
667 NULL, SYNC_NOTHING, GetAllTypes(), std::string(), ENCRYPT_PASSWORDS);
668 base::ListValue list_args;
669 list_args.Append(new base::StringValue(args));
670 EXPECT_CALL(*mock_pss_, DisableForUser());
671 SetupInitializedProfileSyncService();
672 handler_->HandleConfigure(&list_args);
674 // We expect a call to SyncSetupOverlay.showSyncSetupPage.
675 ASSERT_EQ(1U, web_ui_.call_data().size());
676 const TestWebUI::CallData& data = web_ui_.call_data()[0];
677 EXPECT_EQ("SyncSetupOverlay.showSyncSetupPage", data.function_name);
680 TEST_F(SyncSetupHandlerTest, TurnOnEncryptAll) {
681 std::string args = GetConfiguration(
682 NULL, SYNC_ALL_DATA, GetAllTypes(), std::string(), ENCRYPT_ALL_DATA);
683 base::ListValue list_args;
684 list_args.Append(new base::StringValue(args));
685 EXPECT_CALL(*mock_pss_, IsPassphraseRequiredForDecryption())
686 .WillRepeatedly(Return(false));
687 EXPECT_CALL(*mock_pss_, IsPassphraseRequired())
688 .WillRepeatedly(Return(false));
689 SetupInitializedProfileSyncService();
690 EXPECT_CALL(*mock_pss_, EnableEncryptEverything());
691 EXPECT_CALL(*mock_pss_, OnUserChoseDatatypes(true, _));
692 handler_->HandleConfigure(&list_args);
694 // Ensure that we navigated to the "done" state since we don't need a
699 TEST_F(SyncSetupHandlerTest, TestPassphraseStillRequired) {
700 std::string args = GetConfiguration(
701 NULL, SYNC_ALL_DATA, GetAllTypes(), std::string(), ENCRYPT_PASSWORDS);
702 base::ListValue list_args;
703 list_args.Append(new base::StringValue(args));
704 EXPECT_CALL(*mock_pss_, IsPassphraseRequiredForDecryption())
705 .WillRepeatedly(Return(true));
706 EXPECT_CALL(*mock_pss_, IsPassphraseRequired())
707 .WillRepeatedly(Return(true));
708 EXPECT_CALL(*mock_pss_, IsUsingSecondaryPassphrase())
709 .WillRepeatedly(Return(false));
710 SetupInitializedProfileSyncService();
711 EXPECT_CALL(*mock_pss_, OnUserChoseDatatypes(_, _));
712 SetDefaultExpectationsForConfigPage();
714 // We should navigate back to the configure page since we need a passphrase.
715 handler_->HandleConfigure(&list_args);
720 TEST_F(SyncSetupHandlerTest, SuccessfullySetPassphrase) {
721 base::DictionaryValue dict;
722 dict.SetBoolean("isGooglePassphrase", true);
723 std::string args = GetConfiguration(&dict,
728 base::ListValue list_args;
729 list_args.Append(new base::StringValue(args));
730 // Act as if an encryption passphrase is required the first time, then never
732 EXPECT_CALL(*mock_pss_, IsPassphraseRequired()).WillOnce(Return(true));
733 EXPECT_CALL(*mock_pss_, IsPassphraseRequiredForDecryption())
734 .WillRepeatedly(Return(false));
735 EXPECT_CALL(*mock_pss_, IsUsingSecondaryPassphrase())
736 .WillRepeatedly(Return(false));
737 SetupInitializedProfileSyncService();
738 EXPECT_CALL(*mock_pss_, OnUserChoseDatatypes(_, _));
739 EXPECT_CALL(*mock_pss_, SetDecryptionPassphrase("gaiaPassphrase")).
740 WillOnce(Return(true));
742 handler_->HandleConfigure(&list_args);
743 // We should navigate to "done" page since we finished configuring.
747 TEST_F(SyncSetupHandlerTest, SelectCustomEncryption) {
748 base::DictionaryValue dict;
749 dict.SetBoolean("isGooglePassphrase", false);
750 std::string args = GetConfiguration(&dict,
755 base::ListValue list_args;
756 list_args.Append(new base::StringValue(args));
757 EXPECT_CALL(*mock_pss_, IsPassphraseRequiredForDecryption())
758 .WillRepeatedly(Return(false));
759 EXPECT_CALL(*mock_pss_, IsPassphraseRequired())
760 .WillRepeatedly(Return(false));
761 EXPECT_CALL(*mock_pss_, IsUsingSecondaryPassphrase())
762 .WillRepeatedly(Return(false));
763 SetupInitializedProfileSyncService();
764 EXPECT_CALL(*mock_pss_, OnUserChoseDatatypes(_, _));
765 EXPECT_CALL(*mock_pss_,
766 SetEncryptionPassphrase("custom_passphrase",
767 ProfileSyncService::EXPLICIT));
769 handler_->HandleConfigure(&list_args);
770 // We should navigate to "done" page since we finished configuring.
774 TEST_F(SyncSetupHandlerTest, UnsuccessfullySetPassphrase) {
775 base::DictionaryValue dict;
776 dict.SetBoolean("isGooglePassphrase", true);
777 std::string args = GetConfiguration(&dict,
780 "invalid_passphrase",
782 base::ListValue list_args;
783 list_args.Append(new base::StringValue(args));
784 EXPECT_CALL(*mock_pss_, IsPassphraseRequiredForDecryption())
785 .WillRepeatedly(Return(true));
786 EXPECT_CALL(*mock_pss_, IsPassphraseRequired())
787 .WillRepeatedly(Return(true));
788 EXPECT_CALL(*mock_pss_, IsUsingSecondaryPassphrase())
789 .WillRepeatedly(Return(false));
790 SetupInitializedProfileSyncService();
791 EXPECT_CALL(*mock_pss_, OnUserChoseDatatypes(_, _));
792 EXPECT_CALL(*mock_pss_, SetDecryptionPassphrase("invalid_passphrase")).
793 WillOnce(Return(false));
795 SetDefaultExpectationsForConfigPage();
796 // We should navigate back to the configure page since we need a passphrase.
797 handler_->HandleConfigure(&list_args);
801 // Make sure we display an error message to the user due to the failed
803 const TestWebUI::CallData& data = web_ui_.call_data()[0];
804 base::DictionaryValue* dictionary;
805 ASSERT_TRUE(data.arg2->GetAsDictionary(&dictionary));
806 CheckBool(dictionary, "passphraseFailed", true);
809 // Walks through each user selectable type, and tries to sync just that single
811 TEST_F(SyncSetupHandlerTest, TestSyncIndividualTypes) {
812 syncer::ModelTypeSet user_selectable_types = GetAllTypes();
813 syncer::ModelTypeSet::Iterator it;
814 for (it = user_selectable_types.First(); it.Good(); it.Inc()) {
815 syncer::ModelTypeSet type_to_set;
816 type_to_set.Put(it.Get());
817 std::string args = GetConfiguration(NULL,
822 base::ListValue list_args;
823 list_args.Append(new base::StringValue(args));
824 EXPECT_CALL(*mock_pss_, IsPassphraseRequiredForDecryption())
825 .WillRepeatedly(Return(false));
826 EXPECT_CALL(*mock_pss_, IsPassphraseRequired())
827 .WillRepeatedly(Return(false));
828 SetupInitializedProfileSyncService();
829 EXPECT_CALL(*mock_pss_,
830 OnUserChoseDatatypes(false, ModelTypeSetMatches(type_to_set)));
831 handler_->HandleConfigure(&list_args);
834 Mock::VerifyAndClearExpectations(mock_pss_);
835 web_ui_.ClearTrackedCalls();
839 TEST_F(SyncSetupHandlerTest, TestSyncAllManually) {
840 std::string args = GetConfiguration(NULL,
845 base::ListValue list_args;
846 list_args.Append(new base::StringValue(args));
847 EXPECT_CALL(*mock_pss_, IsPassphraseRequiredForDecryption())
848 .WillRepeatedly(Return(false));
849 EXPECT_CALL(*mock_pss_, IsPassphraseRequired())
850 .WillRepeatedly(Return(false));
851 SetupInitializedProfileSyncService();
852 EXPECT_CALL(*mock_pss_,
853 OnUserChoseDatatypes(false, ModelTypeSetMatches(GetAllTypes())));
854 handler_->HandleConfigure(&list_args);
859 TEST_F(SyncSetupHandlerTest, ShowSyncSetup) {
860 EXPECT_CALL(*mock_pss_, IsPassphraseRequired())
861 .WillRepeatedly(Return(false));
862 EXPECT_CALL(*mock_pss_, IsUsingSecondaryPassphrase())
863 .WillRepeatedly(Return(false));
864 SetupInitializedProfileSyncService();
865 // This should display the sync setup dialog (not login).
866 SetDefaultExpectationsForConfigPage();
867 handler_->OpenSyncSetup();
872 // We do not display signin on chromeos in the case of auth error.
873 TEST_F(SyncSetupHandlerTest, ShowSigninOnAuthError) {
874 // Initialize the system to a signed in state, but with an auth error.
875 error_ = GoogleServiceAuthError(
876 GoogleServiceAuthError::INVALID_GAIA_CREDENTIALS);
878 SetupInitializedProfileSyncService();
879 mock_signin_->SetAuthenticatedUsername(kTestUser);
880 FakeAuthStatusProvider provider(
881 ProfileOAuth2TokenServiceFactory::GetForProfile(profile_.get())->
882 signin_error_controller());
883 provider.SetAuthError(kTestUser, kTestUser, error_);
884 EXPECT_CALL(*mock_pss_, IsSyncEnabledAndLoggedIn())
885 .WillRepeatedly(Return(true));
886 EXPECT_CALL(*mock_pss_, IsOAuthRefreshTokenAvailable())
887 .WillRepeatedly(Return(true));
888 EXPECT_CALL(*mock_pss_, IsPassphraseRequired())
889 .WillRepeatedly(Return(false));
890 EXPECT_CALL(*mock_pss_, IsUsingSecondaryPassphrase())
891 .WillRepeatedly(Return(false));
892 EXPECT_CALL(*mock_pss_, sync_initialized()).WillRepeatedly(Return(false));
894 #if defined(OS_CHROMEOS)
895 // On ChromeOS, auth errors are ignored - instead we just try to start the
896 // sync backend (which will fail due to the auth error). This should only
897 // happen if the user manually navigates to chrome://settings/syncSetup -
898 // clicking on the button in the UI will sign the user out rather than
899 // displaying a spinner. Should be no visible UI on ChromeOS in this case.
900 EXPECT_EQ(NULL, LoginUIServiceFactory::GetForProfile(
901 profile_.get())->current_login_ui());
904 // On ChromeOS, this should display the spinner while we try to startup the
905 // sync backend, and on desktop this displays the login dialog.
906 handler_->OpenSyncSetup();
908 // Sync setup is closed when re-auth is in progress.
910 LoginUIServiceFactory::GetForProfile(
911 profile_.get())->current_login_ui());
913 ASSERT_FALSE(handler_->is_configuring_sync());
917 TEST_F(SyncSetupHandlerTest, ShowSetupSyncEverything) {
918 EXPECT_CALL(*mock_pss_, IsPassphraseRequired())
919 .WillRepeatedly(Return(false));
920 EXPECT_CALL(*mock_pss_, IsUsingSecondaryPassphrase())
921 .WillRepeatedly(Return(false));
922 SetupInitializedProfileSyncService();
923 SetDefaultExpectationsForConfigPage();
924 // This should display the sync setup dialog (not login).
925 handler_->OpenSyncSetup();
928 const TestWebUI::CallData& data = web_ui_.call_data()[0];
929 base::DictionaryValue* dictionary;
930 ASSERT_TRUE(data.arg2->GetAsDictionary(&dictionary));
931 CheckBool(dictionary, "showSyncEverythingPage", false);
932 CheckBool(dictionary, "syncAllDataTypes", true);
933 CheckBool(dictionary, "appsRegistered", true);
934 CheckBool(dictionary, "autofillRegistered", true);
935 CheckBool(dictionary, "bookmarksRegistered", true);
936 CheckBool(dictionary, "extensionsRegistered", true);
937 CheckBool(dictionary, "passwordsRegistered", true);
938 CheckBool(dictionary, "preferencesRegistered", true);
939 CheckBool(dictionary, "tabsRegistered", true);
940 CheckBool(dictionary, "themesRegistered", true);
941 CheckBool(dictionary, "typedUrlsRegistered", true);
942 CheckBool(dictionary, "showPassphrase", false);
943 CheckBool(dictionary, "usePassphrase", false);
944 CheckBool(dictionary, "passphraseFailed", false);
945 CheckBool(dictionary, "encryptAllData", false);
946 CheckConfigDataTypeArguments(dictionary, SYNC_ALL_DATA, GetAllTypes());
949 TEST_F(SyncSetupHandlerTest, ShowSetupManuallySyncAll) {
950 EXPECT_CALL(*mock_pss_, IsPassphraseRequired())
951 .WillRepeatedly(Return(false));
952 EXPECT_CALL(*mock_pss_, IsUsingSecondaryPassphrase())
953 .WillRepeatedly(Return(false));
954 SetupInitializedProfileSyncService();
955 sync_driver::SyncPrefs sync_prefs(profile_->GetPrefs());
956 sync_prefs.SetKeepEverythingSynced(false);
957 SetDefaultExpectationsForConfigPage();
958 // This should display the sync setup dialog (not login).
959 handler_->OpenSyncSetup();
962 const TestWebUI::CallData& data = web_ui_.call_data()[0];
963 base::DictionaryValue* dictionary;
964 ASSERT_TRUE(data.arg2->GetAsDictionary(&dictionary));
965 CheckConfigDataTypeArguments(dictionary, CHOOSE_WHAT_TO_SYNC, GetAllTypes());
968 TEST_F(SyncSetupHandlerTest, ShowSetupSyncForAllTypesIndividually) {
969 syncer::ModelTypeSet user_selectable_types = GetAllTypes();
970 syncer::ModelTypeSet::Iterator it;
971 for (it = user_selectable_types.First(); it.Good(); it.Inc()) {
972 EXPECT_CALL(*mock_pss_, IsPassphraseRequired())
973 .WillRepeatedly(Return(false));
974 EXPECT_CALL(*mock_pss_, IsUsingSecondaryPassphrase())
975 .WillRepeatedly(Return(false));
976 SetupInitializedProfileSyncService();
977 sync_driver::SyncPrefs sync_prefs(profile_->GetPrefs());
978 sync_prefs.SetKeepEverythingSynced(false);
979 SetDefaultExpectationsForConfigPage();
980 syncer::ModelTypeSet types;
982 EXPECT_CALL(*mock_pss_, GetPreferredDataTypes()).
983 WillRepeatedly(Return(types));
985 // This should display the sync setup dialog (not login).
986 handler_->OpenSyncSetup();
989 // Close the config overlay.
990 LoginUIServiceFactory::GetForProfile(profile_.get())->LoginUIClosed(
992 const TestWebUI::CallData& data = web_ui_.call_data()[0];
993 base::DictionaryValue* dictionary;
994 ASSERT_TRUE(data.arg2->GetAsDictionary(&dictionary));
995 CheckConfigDataTypeArguments(dictionary, CHOOSE_WHAT_TO_SYNC, types);
996 Mock::VerifyAndClearExpectations(mock_pss_);
997 // Clean up so we can loop back to display the dialog again.
998 web_ui_.ClearTrackedCalls();
1002 TEST_F(SyncSetupHandlerTest, ShowSetupGaiaPassphraseRequired) {
1003 EXPECT_CALL(*mock_pss_, IsPassphraseRequired())
1004 .WillRepeatedly(Return(true));
1005 EXPECT_CALL(*mock_pss_, IsUsingSecondaryPassphrase())
1006 .WillRepeatedly(Return(false));
1007 SetupInitializedProfileSyncService();
1008 SetDefaultExpectationsForConfigPage();
1010 // This should display the sync setup dialog (not login).
1011 handler_->OpenSyncSetup();
1014 const TestWebUI::CallData& data = web_ui_.call_data()[0];
1015 base::DictionaryValue* dictionary;
1016 ASSERT_TRUE(data.arg2->GetAsDictionary(&dictionary));
1017 CheckBool(dictionary, "showPassphrase", true);
1018 CheckBool(dictionary, "usePassphrase", false);
1019 CheckBool(dictionary, "passphraseFailed", false);
1022 TEST_F(SyncSetupHandlerTest, ShowSetupCustomPassphraseRequired) {
1023 EXPECT_CALL(*mock_pss_, IsPassphraseRequired())
1024 .WillRepeatedly(Return(true));
1025 EXPECT_CALL(*mock_pss_, IsUsingSecondaryPassphrase())
1026 .WillRepeatedly(Return(true));
1027 EXPECT_CALL(*mock_pss_, GetPassphraseType())
1028 .WillRepeatedly(Return(syncer::CUSTOM_PASSPHRASE));
1029 SetupInitializedProfileSyncService();
1030 SetDefaultExpectationsForConfigPage();
1032 // This should display the sync setup dialog (not login).
1033 handler_->OpenSyncSetup();
1036 const TestWebUI::CallData& data = web_ui_.call_data()[0];
1037 base::DictionaryValue* dictionary;
1038 ASSERT_TRUE(data.arg2->GetAsDictionary(&dictionary));
1039 CheckBool(dictionary, "showPassphrase", true);
1040 CheckBool(dictionary, "usePassphrase", true);
1041 CheckBool(dictionary, "passphraseFailed", false);
1044 TEST_F(SyncSetupHandlerTest, ShowSetupEncryptAll) {
1045 EXPECT_CALL(*mock_pss_, IsPassphraseRequired())
1046 .WillRepeatedly(Return(false));
1047 EXPECT_CALL(*mock_pss_, IsUsingSecondaryPassphrase())
1048 .WillRepeatedly(Return(false));
1049 SetupInitializedProfileSyncService();
1050 SetDefaultExpectationsForConfigPage();
1051 EXPECT_CALL(*mock_pss_, EncryptEverythingEnabled()).
1052 WillRepeatedly(Return(true));
1054 // This should display the sync setup dialog (not login).
1055 handler_->OpenSyncSetup();
1058 const TestWebUI::CallData& data = web_ui_.call_data()[0];
1059 base::DictionaryValue* dictionary;
1060 ASSERT_TRUE(data.arg2->GetAsDictionary(&dictionary));
1061 CheckBool(dictionary, "encryptAllData", true);