- add sources.
[platform/framework/web/crosswalk.git] / src / chrome / browser / ui / webui / sync_setup_handler_unittest.cc
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.
4
5 #include "chrome/browser/ui/webui/sync_setup_handler.h"
6
7 #include <vector>
8
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"
37
38 using ::testing::_;
39 using ::testing::Mock;
40 using ::testing::Return;
41 using ::testing::ReturnRef;
42 using ::testing::Values;
43
44 typedef GoogleServiceAuthError AuthError;
45
46 namespace {
47
48 MATCHER_P(ModelTypeSetMatches, value, "") { return arg.Equals(value); }
49
50 const char kTestUser[] = "chrome.p13n.test@gmail.com";
51
52 // Returns a ModelTypeSet with all user selectable types set.
53 syncer::ModelTypeSet GetAllTypes() {
54   return syncer::UserSelectableTypes();
55 }
56
57 enum SyncAllDataConfig {
58   SYNC_ALL_DATA,
59   CHOOSE_WHAT_TO_SYNC,
60   SYNC_NOTHING
61 };
62
63 enum EncryptAllConfig {
64   ENCRYPT_ALL_DATA,
65   ENCRYPT_PASSWORDS
66 };
67
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;
77   if (extra_values)
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));
95   std::string args;
96   base::JSONWriter::Write(&result, &args);
97   return args;
98 }
99
100 void CheckInt(const DictionaryValue* dictionary,
101               const std::string& key,
102               int expected_value) {
103   int actual_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;
108 }
109
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,
115                bool expected_value,
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;
120   } else {
121     bool actual_value;
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;
126   }
127 }
128
129 void CheckBool(const DictionaryValue* dictionary,
130                const std::string& key,
131                bool expected_value) {
132   return CheckBool(dictionary, key, expected_value, false);
133 }
134
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;
142   } else {
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;
148   }
149 }
150
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
153 // types.
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));
168 }
169
170
171 }  // namespace
172
173 // Test instance of WebUI that tracks the data passed to
174 // CallJavascriptFunction().
175 class TestWebUI : public content::WebUI {
176  public:
177   virtual ~TestWebUI() {
178     ClearTrackedCalls();
179   }
180
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();
186          ++i) {
187       delete i->arg1;
188       delete i->arg2;
189     }
190     call_data_.clear();
191   }
192
193   virtual void CallJavascriptFunction(const std::string& function_name)
194       OVERRIDE {
195     call_data_.push_back(CallData());
196     call_data_.back().function_name = function_name;
197   }
198
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();
204   }
205
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();
213   }
214
215   virtual content::WebContents* GetWebContents() const OVERRIDE {
216     return NULL;
217   }
218   virtual content::WebUIController* GetController() const OVERRIDE {
219     return NULL;
220   }
221   virtual void SetController(content::WebUIController* controller) OVERRIDE {}
222   virtual ui::ScaleFactor GetDeviceScaleFactor() const OVERRIDE {
223     return ui::SCALE_FACTOR_100P;
224   }
225   virtual const string16& GetOverriddenTitle() const OVERRIDE {
226     return temp_string_;
227   }
228   virtual void OverrideTitle(const string16& title) OVERRIDE {}
229   virtual content::PageTransition GetLinkTransitionType() const OVERRIDE {
230     return content::PAGE_TRANSITION_LINK;
231   }
232   virtual void SetLinkTransitionType(content::PageTransition type) OVERRIDE {}
233   virtual int GetBindings() const OVERRIDE {
234     return 0;
235   }
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 {}
258
259   class CallData {
260    public:
261     CallData() : arg1(NULL), arg2(NULL) {}
262     std::string function_name;
263     Value* arg1;
264     Value* arg2;
265   };
266   const std::vector<CallData>& call_data() { return call_data_; }
267  private:
268   std::vector<CallData> call_data_;
269   string16 temp_string_;
270 };
271
272 class TestingSyncSetupHandler : public SyncSetupHandler {
273  public:
274   TestingSyncSetupHandler(content::WebUI* web_ui, Profile* profile)
275       : SyncSetupHandler(NULL),
276         profile_(profile) {
277     set_web_ui(web_ui);
278   }
279   virtual ~TestingSyncSetupHandler() {
280     set_web_ui(NULL);
281   }
282
283   virtual void FocusUI() OVERRIDE {}
284
285   virtual Profile* GetProfile() const OVERRIDE { return profile_; }
286
287   using SyncSetupHandler::is_configuring_sync;
288
289  private:
290 #if !defined(OS_CHROMEOS)
291   virtual void DisplayGaiaLoginInNewTabOrWindow() OVERRIDE {}
292 #endif
293
294   // Weak pointer to parent profile.
295   Profile* profile_;
296   DISALLOW_COPY_AND_ASSIGN(TestingSyncSetupHandler);
297 };
298
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 {
303  public:
304   SyncSetupHandlerTest() : error_(GoogleServiceAuthError::NONE) {}
305   virtual void SetUp() OVERRIDE {
306     error_ = GoogleServiceAuthError::AuthErrorNone();
307     profile_.reset(ProfileSyncServiceMock::MakeSignedInTestingProfile());
308
309     mock_pss_ = static_cast<ProfileSyncServiceMock*>(
310         ProfileSyncServiceFactory::GetInstance()->SetTestingFactoryAndUse(
311             profile_.get(),
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()));
320
321     mock_pss_->Initialize();
322
323 #if defined(OS_CHROMEOS)
324     mock_signin_ = static_cast<SigninManagerBase*>(
325         SigninManagerFactory::GetInstance()->SetTestingFactoryAndUse(
326             profile_.get(), FakeSigninManagerBase::Build));
327 #else
328     mock_signin_ = static_cast<SigninManagerBase*>(
329         SigninManagerFactory::GetInstance()->SetTestingFactoryAndUse(
330             profile_.get(), FakeSigninManager::Build));
331 #endif
332     handler_.reset(new TestingSyncSetupHandler(&web_ui_, profile_.get()));
333   }
334
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));
347   }
348
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);
356     }
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));
364   }
365
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);
370     std::string page;
371     ASSERT_TRUE(data.arg1->GetAsString(&page));
372     EXPECT_EQ(page, "configure");
373   }
374
375   void ExpectDone() {
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);
379     std::string page;
380     ASSERT_TRUE(data.arg1->GetAsString(&page));
381     EXPECT_EQ(page, "done");
382   }
383
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);
389
390     std::string page;
391     ASSERT_TRUE(data.arg1->GetAsString(&page));
392     EXPECT_EQ(page, "spinner");
393     // Cancelling the spinner dialog will cause CloseSyncSetup().
394     handler_->CloseSyncSetup();
395     EXPECT_EQ(NULL,
396               LoginUIServiceFactory::GetForProfile(
397                   profile_.get())->current_login_ui());
398   }
399
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();
406   }
407
408   content::TestBrowserThreadBundle thread_bundle_;
409   scoped_ptr<Profile> profile_;
410   ProfileSyncServiceMock* mock_pss_;
411   GoogleServiceAuthError error_;
412   SigninManagerBase* mock_signin_;
413   TestWebUI web_ui_;
414   scoped_ptr<TestingSyncSetupHandler> handler_;
415 };
416
417 TEST_F(SyncSetupHandlerTest, Basic) {
418 }
419
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);
429
430   // Sync setup hands off control to the gaia login tab.
431   EXPECT_EQ(NULL,
432             LoginUIServiceFactory::GetForProfile(
433                 profile_.get())->current_login_ui());
434
435   ASSERT_FALSE(handler_->is_configuring_sync());
436
437   handler_->CloseSyncSetup();
438   EXPECT_EQ(NULL,
439             LoginUIServiceFactory::GetForProfile(
440                 profile_.get())->current_login_ui());
441 }
442
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);
451
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);
456
457   ASSERT_FALSE(handler_->is_configuring_sync());
458   EXPECT_EQ(NULL,
459             LoginUIServiceFactory::GetForProfile(
460                 profile_.get())->current_login_ui());
461 }
462 #endif
463
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));
477
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);
484
485   EXPECT_EQ(handler_.get(),
486             LoginUIServiceFactory::GetForProfile(
487                 profile_.get())->current_login_ui());
488
489   ExpectSpinnerAndClose();
490 }
491
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();
509
510   handler_->OpenSyncSetup();
511
512   // We expect a call to SyncSetupOverlay.showSyncSetupPage.
513   EXPECT_EQ(1U, web_ui_.call_data().size());
514
515   const TestWebUI::CallData& data0 = web_ui_.call_data()[0];
516   EXPECT_EQ("SyncSetupOverlay.showSyncSetupPage", data0.function_name);
517   std::string page;
518   ASSERT_TRUE(data0.arg1->GetAsString(&page));
519   EXPECT_EQ(page, "spinner");
520
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();
529
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);
543 }
544
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();
566
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));
572
573   handler_->CloseSyncSetup();
574   EXPECT_EQ(NULL,
575             LoginUIServiceFactory::GetForProfile(
576                 profile_.get())->current_login_ui());
577 }
578
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));
591
592   handler_->OpenSyncSetup();
593   const TestWebUI::CallData& data = web_ui_.call_data()[0];
594   EXPECT_EQ("SyncSetupOverlay.showSyncSetupPage", data.function_name);
595   std::string page;
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();
603
604   // On failure, the dialog will be closed.
605   EXPECT_EQ(NULL,
606             LoginUIServiceFactory::GetForProfile(
607                 profile_.get())->current_login_ui());
608 }
609
610 #if !defined(OS_CHROMEOS)
611
612 class SyncSetupHandlerNonCrosTest : public SyncSetupHandlerTest {
613  public:
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));
620   }
621 };
622
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));
632   // Open the web UI.
633   handler_->OpenSyncSetup();
634
635   ASSERT_FALSE(handler_->is_configuring_sync());
636 }
637
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));
646   // Open the web UI.
647   handler_->OpenSyncSetup();
648
649   ASSERT_FALSE(handler_->is_configuring_sync());
650 }
651
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));
659   // Open the web UI.
660   handler_->OpenSyncSetup();
661
662   ASSERT_FALSE(handler_->is_configuring_sync());
663 }
664
665 #endif  // #if !defined(OS_CHROMEOS)
666
667 TEST_F(SyncSetupHandlerTest, TestSyncEverything) {
668   std::string args = GetConfiguration(
669       NULL, SYNC_ALL_DATA, GetAllTypes(), std::string(), ENCRYPT_PASSWORDS);
670   ListValue list_args;
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);
679
680   // Ensure that we navigated to the "done" state since we don't need a
681   // passphrase.
682   ExpectDone();
683 }
684
685 TEST_F(SyncSetupHandlerTest, TestSyncNothing) {
686   std::string args = GetConfiguration(
687       NULL, SYNC_NOTHING, GetAllTypes(), std::string(), ENCRYPT_PASSWORDS);
688   ListValue list_args;
689   list_args.Append(new StringValue(args));
690   EXPECT_CALL(*mock_pss_, DisableForUser());
691   SetupInitializedProfileSyncService();
692   handler_->HandleConfigure(&list_args);
693
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);
698 }
699
700 TEST_F(SyncSetupHandlerTest, TurnOnEncryptAll) {
701   std::string args = GetConfiguration(
702       NULL, SYNC_ALL_DATA, GetAllTypes(), std::string(), ENCRYPT_ALL_DATA);
703   ListValue list_args;
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);
713
714   // Ensure that we navigated to the "done" state since we don't need a
715   // passphrase.
716   ExpectDone();
717 }
718
719 TEST_F(SyncSetupHandlerTest, TestPassphraseStillRequired) {
720   std::string args = GetConfiguration(
721       NULL, SYNC_ALL_DATA, GetAllTypes(), std::string(), ENCRYPT_PASSWORDS);
722   ListValue list_args;
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();
733
734   // We should navigate back to the configure page since we need a passphrase.
735   handler_->HandleConfigure(&list_args);
736
737   ExpectConfig();
738 }
739
740 TEST_F(SyncSetupHandlerTest, SuccessfullySetPassphrase) {
741   DictionaryValue dict;
742   dict.SetBoolean("isGooglePassphrase", true);
743   std::string args = GetConfiguration(&dict,
744                                       SYNC_ALL_DATA,
745                                       GetAllTypes(),
746                                       "gaiaPassphrase",
747                                       ENCRYPT_PASSWORDS);
748   ListValue list_args;
749   list_args.Append(new StringValue(args));
750   // Act as if an encryption passphrase is required the first time, then never
751   // again after that.
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));
761
762   handler_->HandleConfigure(&list_args);
763   // We should navigate to "done" page since we finished configuring.
764   ExpectDone();
765 }
766
767 TEST_F(SyncSetupHandlerTest, SelectCustomEncryption) {
768   DictionaryValue dict;
769   dict.SetBoolean("isGooglePassphrase", false);
770   std::string args = GetConfiguration(&dict,
771                                       SYNC_ALL_DATA,
772                                       GetAllTypes(),
773                                       "custom_passphrase",
774                                       ENCRYPT_PASSWORDS);
775   ListValue list_args;
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));
788
789   handler_->HandleConfigure(&list_args);
790   // We should navigate to "done" page since we finished configuring.
791   ExpectDone();
792 }
793
794 TEST_F(SyncSetupHandlerTest, UnsuccessfullySetPassphrase) {
795   DictionaryValue dict;
796   dict.SetBoolean("isGooglePassphrase", true);
797   std::string args = GetConfiguration(&dict,
798                                       SYNC_ALL_DATA,
799                                       GetAllTypes(),
800                                       "invalid_passphrase",
801                                       ENCRYPT_PASSWORDS);
802   ListValue list_args;
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));
814
815   SetDefaultExpectationsForConfigPage();
816   // We should navigate back to the configure page since we need a passphrase.
817   handler_->HandleConfigure(&list_args);
818
819   ExpectConfig();
820
821   // Make sure we display an error message to the user due to the failed
822   // passphrase.
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);
827 }
828
829 // Walks through each user selectable type, and tries to sync just that single
830 // data type.
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,
838                                         CHOOSE_WHAT_TO_SYNC,
839                                         type_to_set,
840                                         std::string(),
841                                         ENCRYPT_PASSWORDS);
842     ListValue list_args;
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);
852
853     ExpectDone();
854     Mock::VerifyAndClearExpectations(mock_pss_);
855     web_ui_.ClearTrackedCalls();
856   }
857 }
858
859 TEST_F(SyncSetupHandlerTest, TestSyncAllManually) {
860   std::string args = GetConfiguration(NULL,
861                                       CHOOSE_WHAT_TO_SYNC,
862                                       GetAllTypes(),
863                                       std::string(),
864                                       ENCRYPT_PASSWORDS);
865   ListValue list_args;
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);
875
876   ExpectDone();
877 }
878
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();
888
889   ExpectConfig();
890 }
891
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);
897
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));
912
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());
921 #else
922
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();
926
927   // Sync setup is closed when re-auth is in progress.
928   EXPECT_EQ(NULL,
929             LoginUIServiceFactory::GetForProfile(
930                 profile_.get())->current_login_ui());
931
932   ASSERT_FALSE(handler_->is_configuring_sync());
933 #endif
934 }
935
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();
945
946   ExpectConfig();
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());
966 }
967
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();
979
980   ExpectConfig();
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());
985 }
986
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));
1003
1004     // This should display the sync setup dialog (not login).
1005     handler_->OpenSyncSetup();
1006
1007     ExpectConfig();
1008     // Close the config overlay.
1009     LoginUIServiceFactory::GetForProfile(profile_.get())->LoginUIClosed(
1010         handler_.get());
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();
1018   }
1019 }
1020
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();
1028
1029   // This should display the sync setup dialog (not login).
1030   handler_->OpenSyncSetup();
1031
1032   ExpectConfig();
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);
1039 }
1040
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();
1050
1051   // This should display the sync setup dialog (not login).
1052   handler_->OpenSyncSetup();
1053
1054   ExpectConfig();
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);
1061 }
1062
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));
1072
1073   // This should display the sync setup dialog (not login).
1074   handler_->OpenSyncSetup();
1075
1076   ExpectConfig();
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);
1081 }