autofill_dialog_controller_unittest.cc revision 424c4d7b64af9d0d8fd9624f381f469654d5e3d2
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 <map>
6
7#include "base/bind.h"
8#include "base/command_line.h"
9#include "base/guid.h"
10#include "base/memory/scoped_ptr.h"
11#include "base/message_loop/message_loop.h"
12#include "base/prefs/pref_service.h"
13#include "base/run_loop.h"
14#include "base/strings/string_number_conversions.h"
15#include "base/strings/utf_string_conversions.h"
16#include "base/tuple.h"
17#include "chrome/browser/ui/autofill/autofill_dialog_controller_impl.h"
18#include "chrome/browser/ui/autofill/autofill_dialog_view.h"
19#include "chrome/browser/ui/autofill/generated_credit_card_bubble_controller.h"
20#include "chrome/browser/ui/autofill/mock_new_credit_card_bubble_controller.h"
21#include "chrome/browser/ui/autofill/test_generated_credit_card_bubble_view.h"
22#include "chrome/common/pref_names.h"
23#include "chrome/common/render_messages.h"
24#include "chrome/test/base/chrome_render_view_host_test_harness.h"
25#include "chrome/test/base/testing_profile.h"
26#include "components/autofill/content/browser/risk/proto/fingerprint.pb.h"
27#include "components/autofill/content/browser/wallet/full_wallet.h"
28#include "components/autofill/content/browser/wallet/instrument.h"
29#include "components/autofill/content/browser/wallet/mock_wallet_client.h"
30#include "components/autofill/content/browser/wallet/wallet_address.h"
31#include "components/autofill/content/browser/wallet/wallet_service_url.h"
32#include "components/autofill/content/browser/wallet/wallet_test_util.h"
33#include "components/autofill/core/browser/autofill_common_test.h"
34#include "components/autofill/core/browser/autofill_metrics.h"
35#include "components/autofill/core/browser/test_personal_data_manager.h"
36#include "components/autofill/core/common/autofill_switches.h"
37#include "components/autofill/core/common/form_data.h"
38#include "content/public/browser/web_contents.h"
39#include "content/public/test/mock_render_process_host.h"
40#include "testing/gmock/include/gmock/gmock.h"
41#include "testing/gtest/include/gtest/gtest.h"
42
43#if defined(OS_WIN)
44#include "ui/base/win/scoped_ole_initializer.h"
45#endif
46
47using testing::_;
48
49namespace autofill {
50
51namespace {
52
53const char kFakeEmail[] = "user@example.com";
54const char kFakeFingerprintEncoded[] = "CgVaAwiACA==";
55const char kEditedBillingAddress[] = "123 edited billing address";
56const char* kFieldsFromPage[] =
57    { "email",
58      "cc-name",
59      "cc-number",
60      "cc-exp-month",
61      "cc-exp-year",
62      "cc-csc",
63      "billing name",
64      "billing address-line1",
65      "billing locality",
66      "billing region",
67      "billing postal-code",
68      "billing country",
69      "billing tel",
70      "shipping name",
71      "shipping address-line1",
72      "shipping locality",
73      "shipping region",
74      "shipping postal-code",
75      "shipping country",
76      "shipping tel",
77    };
78const char kSettingsOrigin[] = "Chrome settings";
79const char kTestCCNumberAmex[] = "376200000000002";
80const char kTestCCNumberVisa[] = "4111111111111111";
81const char kTestCCNumberMaster[] = "5555555555554444";
82const char kTestCCNumberDiscover[] = "6011111111111117";
83const char kTestCCNumberIncomplete[] = "4111111111";
84// Credit card number fails Luhn check.
85const char kTestCCNumberInvalid[] = "4111111111111112";
86
87
88void SetOutputValue(const DetailInputs& inputs,
89                    DetailOutputMap* outputs,
90                    ServerFieldType type,
91                    const base::string16& value) {
92  for (size_t i = 0; i < inputs.size(); ++i) {
93    const DetailInput& input = inputs[i];
94    (*outputs)[&input] = input.type == type ?
95        value :
96        input.initial_value;
97  }
98}
99
100scoped_ptr<wallet::WalletItems> CompleteAndValidWalletItems() {
101  scoped_ptr<wallet::WalletItems> items = wallet::GetTestWalletItems();
102  items->AddInstrument(wallet::GetTestMaskedInstrument());
103  items->AddAddress(wallet::GetTestShippingAddress());
104  return items.Pass();
105}
106
107scoped_ptr<wallet::FullWallet> CreateFullWallet(const char* required_action) {
108  base::DictionaryValue dict;
109  scoped_ptr<base::ListValue> list(new base::ListValue());
110  list->AppendString(required_action);
111  dict.Set("required_action", list.release());
112  return wallet::FullWallet::CreateFullWallet(dict);
113}
114
115scoped_ptr<risk::Fingerprint> GetFakeFingerprint() {
116  scoped_ptr<risk::Fingerprint> fingerprint(new risk::Fingerprint());
117  // Add some data to the proto, else the encoded content is empty.
118  fingerprint->mutable_machine_characteristics()->mutable_screen_size()->
119      set_width(1024);
120  return fingerprint.Pass();
121}
122
123class TestAutofillDialogView : public AutofillDialogView {
124 public:
125  TestAutofillDialogView() : updates_started_(0) {}
126  virtual ~TestAutofillDialogView() {}
127
128  virtual void Show() OVERRIDE {}
129  virtual void Hide() OVERRIDE {}
130
131  virtual void UpdatesStarted() OVERRIDE {
132    updates_started_++;
133  }
134
135  virtual void UpdatesFinished() OVERRIDE {
136    updates_started_--;
137    EXPECT_GE(updates_started_, 0);
138  }
139
140  virtual void UpdateNotificationArea() OVERRIDE {
141    EXPECT_GE(updates_started_, 1);
142  }
143
144  virtual void UpdateAccountChooser() OVERRIDE {
145    EXPECT_GE(updates_started_, 1);
146  }
147
148  virtual void UpdateButtonStrip() OVERRIDE {
149    EXPECT_GE(updates_started_, 1);
150  }
151
152  virtual void UpdateDetailArea() OVERRIDE {
153    EXPECT_GE(updates_started_, 1);
154  }
155
156  virtual void UpdateAutocheckoutStepsArea() OVERRIDE {
157    EXPECT_GE(updates_started_, 1);
158  }
159
160  virtual void UpdateSection(DialogSection section) OVERRIDE {
161    EXPECT_GE(updates_started_, 1);
162  }
163
164  virtual void FillSection(DialogSection section,
165                           const DetailInput& originating_input) OVERRIDE {};
166  virtual void GetUserInput(DialogSection section, DetailOutputMap* output)
167      OVERRIDE {
168    *output = outputs_[section];
169  }
170  virtual TestableAutofillDialogView* GetTestableView() OVERRIDE {
171    return NULL;
172  }
173
174  virtual string16 GetCvc() OVERRIDE { return string16(); }
175  virtual bool HitTestInput(const DetailInput& input,
176                            const gfx::Point& screen_point) OVERRIDE {
177    return false;
178  }
179  virtual bool SaveDetailsLocally() OVERRIDE { return true; }
180  virtual const content::NavigationController* ShowSignIn() OVERRIDE {
181    return NULL;
182  }
183  virtual void HideSignIn() OVERRIDE {}
184  virtual void UpdateProgressBar(double value) OVERRIDE {}
185
186  MOCK_METHOD0(ModelChanged, void());
187  MOCK_METHOD0(UpdateForErrors, void());
188
189  virtual void OnSignInResize(const gfx::Size& pref_size) OVERRIDE {}
190
191  void SetUserInput(DialogSection section, const DetailOutputMap& map) {
192    outputs_[section] = map;
193  }
194
195 private:
196  std::map<DialogSection, DetailOutputMap> outputs_;
197
198  int updates_started_;
199
200  DISALLOW_COPY_AND_ASSIGN(TestAutofillDialogView);
201};
202
203// Bring over command-ids from AccountChooserModel.
204class TestAccountChooserModel : public AccountChooserModel {
205 public:
206  TestAccountChooserModel(AccountChooserModelDelegate* delegate,
207                          PrefService* prefs,
208                          const AutofillMetrics& metric_logger)
209      : AccountChooserModel(delegate, prefs, metric_logger,
210                            DIALOG_TYPE_REQUEST_AUTOCOMPLETE) {}
211  virtual ~TestAccountChooserModel() {}
212
213  using AccountChooserModel::kActiveWalletItemId;
214  using AccountChooserModel::kAutofillItemId;
215
216 private:
217  DISALLOW_COPY_AND_ASSIGN(TestAccountChooserModel);
218};
219
220class TestAutofillDialogController
221    : public AutofillDialogControllerImpl,
222      public base::SupportsWeakPtr<TestAutofillDialogController> {
223 public:
224  TestAutofillDialogController(
225      content::WebContents* contents,
226      const FormData& form_structure,
227      const GURL& source_url,
228      const AutofillMetrics& metric_logger,
229      const DialogType dialog_type,
230      const base::Callback<void(const FormStructure*,
231                                const std::string&)>& callback,
232      MockNewCreditCardBubbleController* mock_new_card_bubble_controller)
233      : AutofillDialogControllerImpl(contents,
234                                     form_structure,
235                                     source_url,
236                                     dialog_type,
237                                     callback),
238        metric_logger_(metric_logger),
239        mock_wallet_client_(
240            Profile::FromBrowserContext(contents->GetBrowserContext())->
241                GetRequestContext(), this),
242        dialog_type_(dialog_type),
243        mock_new_card_bubble_controller_(mock_new_card_bubble_controller) {}
244
245  virtual ~TestAutofillDialogController() {}
246
247  virtual AutofillDialogView* CreateView() OVERRIDE {
248    return new testing::NiceMock<TestAutofillDialogView>();
249  }
250
251  void Init(content::BrowserContext* browser_context) {
252    test_manager_.Init(browser_context);
253  }
254
255  TestAutofillDialogView* GetView() {
256    return static_cast<TestAutofillDialogView*>(view());
257  }
258
259  TestPersonalDataManager* GetTestingManager() {
260    return &test_manager_;
261  }
262
263  wallet::MockWalletClient* GetTestingWalletClient() {
264    return &mock_wallet_client_;
265  }
266
267  const GURL& open_tab_url() { return open_tab_url_; }
268
269  virtual DialogType GetDialogType() const OVERRIDE {
270    return dialog_type_;
271  }
272
273  void set_dialog_type(DialogType dialog_type) { dialog_type_ = dialog_type; }
274
275  void SimulateSigninError() {
276    OnWalletSigninError();
277  }
278
279  bool AutocheckoutIsRunning() const {
280    return AUTOCHECKOUT_IN_PROGRESS == autocheckout_state();
281  }
282
283  MOCK_METHOD0(LoadRiskFingerprintData, void());
284  using AutofillDialogControllerImpl::OnDidLoadRiskFingerprintData;
285  using AutofillDialogControllerImpl::IsEditingExistingData;
286
287 protected:
288  virtual PersonalDataManager* GetManager() OVERRIDE {
289    return &test_manager_;
290  }
291
292  virtual wallet::WalletClient* GetWalletClient() OVERRIDE {
293    return &mock_wallet_client_;
294  }
295
296  virtual void OpenTabWithUrl(const GURL& url) OVERRIDE {
297    open_tab_url_ = url;
298  }
299
300  // Whether the information input in this dialog will be securely transmitted
301  // to the requesting site.
302  virtual bool TransmissionWillBeSecure() const OVERRIDE {
303    return true;
304  }
305
306  virtual void ShowNewCreditCardBubble(
307      scoped_ptr<CreditCard> new_card,
308      scoped_ptr<AutofillProfile> billing_profile) OVERRIDE {
309    mock_new_card_bubble_controller_->Show(new_card.Pass(),
310                                           billing_profile.Pass());
311  }
312
313 private:
314  // To specify our own metric logger.
315  virtual const AutofillMetrics& GetMetricLogger() const OVERRIDE {
316    return metric_logger_;
317  }
318
319  const AutofillMetrics& metric_logger_;
320  TestPersonalDataManager test_manager_;
321  testing::NiceMock<wallet::MockWalletClient> mock_wallet_client_;
322  GURL open_tab_url_;
323  DialogType dialog_type_;
324  MockNewCreditCardBubbleController* mock_new_card_bubble_controller_;
325
326  DISALLOW_COPY_AND_ASSIGN(TestAutofillDialogController);
327};
328
329class TestGeneratedCreditCardBubbleController :
330    public GeneratedCreditCardBubbleController {
331 public:
332  explicit TestGeneratedCreditCardBubbleController(
333      content::WebContents* contents)
334      : GeneratedCreditCardBubbleController(contents) {
335    contents->SetUserData(UserDataKey(), this);
336    CHECK_EQ(contents->GetUserData(UserDataKey()), this);
337  }
338
339  virtual ~TestGeneratedCreditCardBubbleController() {}
340
341  MOCK_METHOD2(SetupAndShow, void(const base::string16& backing_card_name,
342                                  const base::string16& fronting_card_name));
343
344 protected:
345  virtual base::WeakPtr<GeneratedCreditCardBubbleView> CreateBubble() OVERRIDE {
346    return TestGeneratedCreditCardBubbleView::Create(GetWeakPtr());
347  }
348
349  virtual bool CanShow() const OVERRIDE {
350    return true;
351  }
352
353 private:
354  DISALLOW_COPY_AND_ASSIGN(TestGeneratedCreditCardBubbleController);
355};
356
357class AutofillDialogControllerTest : public ChromeRenderViewHostTestHarness {
358 protected:
359  AutofillDialogControllerTest(): form_structure_(NULL) {}
360
361  // testing::Test implementation:
362  virtual void SetUp() OVERRIDE {
363    ChromeRenderViewHostTestHarness::SetUp();
364    Reset();
365  }
366
367  virtual void TearDown() OVERRIDE {
368    if (controller_)
369      controller_->ViewClosed();
370    ChromeRenderViewHostTestHarness::TearDown();
371  }
372
373  void Reset() {
374    if (controller_)
375      controller_->ViewClosed();
376
377    test_generated_bubble_controller_ =
378        new testing::NiceMock<TestGeneratedCreditCardBubbleController>(
379            web_contents());
380    mock_new_card_bubble_controller_.reset(
381        new MockNewCreditCardBubbleController);
382
383    // Don't get stuck on the first run wallet interstitial.
384    profile()->GetPrefs()->SetBoolean(::prefs::kAutofillDialogHasPaidWithWallet,
385                                      true);
386
387    SetUpControllerWithFormData(DefaultFormData());
388  }
389
390  FormData DefaultFormData() {
391    FormData form_data;
392    for (size_t i = 0; i < arraysize(kFieldsFromPage); ++i) {
393      FormFieldData field;
394      field.autocomplete_attribute = kFieldsFromPage[i];
395      form_data.fields.push_back(field);
396    }
397    return form_data;
398  }
399
400  void SetUpControllerWithFormData(const FormData& form_data) {
401    if (controller_)
402      controller_->ViewClosed();
403
404    base::Callback<void(const FormStructure*, const std::string&)> callback =
405        base::Bind(&AutofillDialogControllerTest::FinishedCallback,
406                   base::Unretained(this));
407    controller_ = (new testing::NiceMock<TestAutofillDialogController>(
408        web_contents(),
409        form_data,
410        GURL(),
411        metric_logger_,
412        DIALOG_TYPE_REQUEST_AUTOCOMPLETE,
413        callback,
414        mock_new_card_bubble_controller_.get()))->AsWeakPtr();
415    controller_->Init(profile());
416    controller_->Show();
417    controller_->OnUserNameFetchSuccess(kFakeEmail);
418  }
419
420  void FillCreditCardInputs() {
421    DetailOutputMap cc_outputs;
422    const DetailInputs& cc_inputs =
423        controller()->RequestedFieldsForSection(SECTION_CC);
424    for (size_t i = 0; i < cc_inputs.size(); ++i) {
425      cc_outputs[&cc_inputs[i]] = cc_inputs[i].type == CREDIT_CARD_NUMBER ?
426          ASCIIToUTF16(kTestCCNumberVisa) : ASCIIToUTF16("11");
427    }
428    controller()->GetView()->SetUserInput(SECTION_CC, cc_outputs);
429  }
430
431  std::vector<DialogNotification> NotificationsOfType(
432      DialogNotification::Type type) {
433    std::vector<DialogNotification> right_type;
434    const std::vector<DialogNotification>& notifications =
435        controller()->CurrentNotifications();
436    for (size_t i = 0; i < notifications.size(); ++i) {
437      if (notifications[i].type() == type)
438        right_type.push_back(notifications[i]);
439    }
440    return right_type;
441  }
442
443  void SwitchToAutofill() {
444    controller_->MenuModelForAccountChooser()->ActivatedAt(
445        TestAccountChooserModel::kAutofillItemId);
446  }
447
448  void SwitchToWallet() {
449    controller_->MenuModelForAccountChooser()->ActivatedAt(
450        TestAccountChooserModel::kActiveWalletItemId);
451  }
452
453  void SimulateSigninError() {
454    controller_->SimulateSigninError();
455  }
456
457  void UseBillingForShipping() {
458    controller()->MenuModelForSection(SECTION_SHIPPING)->ActivatedAt(0);
459  }
460
461  void ValidateCCNumber(DialogSection section,
462                        const std::string& cc_number,
463                        bool should_pass) {
464    DetailOutputMap outputs;
465    const DetailInputs& inputs =
466        controller()->RequestedFieldsForSection(section);
467
468    SetOutputValue(inputs, &outputs, CREDIT_CARD_NUMBER,
469                   ASCIIToUTF16(cc_number));
470    ValidityData validity_data =
471        controller()->InputsAreValid(section, outputs, VALIDATE_FINAL);
472    EXPECT_EQ(should_pass ? 0U : 1U, validity_data.count(CREDIT_CARD_NUMBER));
473  }
474
475  void SubmitWithWalletItems(scoped_ptr<wallet::WalletItems> wallet_items) {
476    controller()->OnDidGetWalletItems(wallet_items.Pass());
477    AcceptAndLoadFakeFingerprint();
478  }
479
480  void AcceptAndLoadFakeFingerprint() {
481    controller()->OnAccept();
482    controller()->OnDidLoadRiskFingerprintData(GetFakeFingerprint().Pass());
483  }
484
485  bool ReadSetVisuallyDeemphasizedIpc() {
486    EXPECT_EQ(1U, process()->sink().message_count());
487    uint32 kMsgID = ChromeViewMsg_SetVisuallyDeemphasized::ID;
488    const IPC::Message* message =
489        process()->sink().GetFirstMessageMatching(kMsgID);
490    EXPECT_TRUE(message);
491    Tuple1<bool> payload;
492    ChromeViewMsg_SetVisuallyDeemphasized::Read(message, &payload);
493    process()->sink().ClearMessages();
494    return payload.a;
495  }
496
497  TestAutofillDialogController* controller() { return controller_.get(); }
498
499  const FormStructure* form_structure() { return form_structure_; }
500
501  TestGeneratedCreditCardBubbleController* test_generated_bubble_controller() {
502    return test_generated_bubble_controller_;
503  }
504
505  const MockNewCreditCardBubbleController* mock_new_card_bubble_controller() {
506    return mock_new_card_bubble_controller_.get();
507  }
508
509 private:
510  void FinishedCallback(const FormStructure* form_structure,
511                        const std::string& google_transaction_id) {
512    form_structure_ = form_structure;
513    if (controller()->GetDialogType() == DIALOG_TYPE_AUTOCHECKOUT)
514      EXPECT_TRUE(controller()->AutocheckoutIsRunning());
515  }
516
517#if defined(OS_WIN)
518   // http://crbug.com/227221
519   ui::ScopedOleInitializer ole_initializer_;
520#endif
521
522  // The controller owns itself.
523  base::WeakPtr<TestAutofillDialogController> controller_;
524
525  // Must outlive the controller.
526  AutofillMetrics metric_logger_;
527
528  // Returned when the dialog closes successfully.
529  const FormStructure* form_structure_;
530
531  // Used to monitor if the Autofill credit card bubble is shown. Owned by
532  // |web_contents()|.
533  TestGeneratedCreditCardBubbleController* test_generated_bubble_controller_;
534
535  // Used to record when new card bubbles would show. Created in |Reset()|.
536  scoped_ptr<MockNewCreditCardBubbleController>
537      mock_new_card_bubble_controller_;
538};
539
540}  // namespace
541
542// This test makes sure nothing falls over when fields are being validity-
543// checked.
544TEST_F(AutofillDialogControllerTest, ValidityCheck) {
545  for (size_t i = SECTION_MIN; i <= SECTION_MAX; ++i) {
546    DialogSection section = static_cast<DialogSection>(i);
547    const DetailInputs& shipping_inputs =
548        controller()->RequestedFieldsForSection(section);
549    for (DetailInputs::const_iterator iter = shipping_inputs.begin();
550         iter != shipping_inputs.end(); ++iter) {
551      controller()->InputValidityMessage(section, iter->type, string16());
552    }
553  }
554}
555
556// Test for phone number validation.
557TEST_F(AutofillDialogControllerTest, PhoneNumberValidation) {
558  // Construct DetailOutputMap from existing data.
559  SwitchToAutofill();
560
561  AutofillProfile full_profile(test::GetVerifiedProfile());
562  controller()->GetTestingManager()->AddTestingProfile(&full_profile);
563
564  for (size_t i = 0; i < 2; ++i) {
565    ServerFieldType phone = i == 0 ? PHONE_HOME_WHOLE_NUMBER :
566                                     PHONE_BILLING_WHOLE_NUMBER;
567    ServerFieldType address = i == 0 ? ADDRESS_HOME_COUNTRY :
568                                       ADDRESS_BILLING_COUNTRY;
569    DialogSection section = i == 0 ? SECTION_SHIPPING : SECTION_BILLING;
570
571    controller()->EditClickedForSection(section);
572
573    DetailOutputMap outputs;
574    const DetailInputs& inputs =
575        controller()->RequestedFieldsForSection(section);
576    // Make sure country is United States.
577    SetOutputValue(inputs, &outputs, address, ASCIIToUTF16("United States"));
578
579    // Existing data should have no errors.
580    ValidityData validity_data =
581        controller()->InputsAreValid(section, outputs, VALIDATE_FINAL);
582    EXPECT_EQ(0U, validity_data.count(phone));
583
584    // Input an empty phone number with VALIDATE_FINAL.
585    SetOutputValue( inputs, &outputs, phone, base::string16());
586    validity_data =
587        controller()->InputsAreValid(section, outputs, VALIDATE_FINAL);
588    EXPECT_EQ(1U, validity_data.count(phone));
589
590    // Input an empty phone number with VALIDATE_EDIT.
591    validity_data =
592        controller()->InputsAreValid(section, outputs, VALIDATE_EDIT);
593    EXPECT_EQ(0U, validity_data.count(phone));
594
595    // Input an invalid phone number.
596    SetOutputValue(inputs, &outputs, phone, ASCIIToUTF16("ABC"));
597    validity_data =
598        controller()->InputsAreValid(section, outputs, VALIDATE_EDIT);
599    EXPECT_EQ(1U, validity_data.count(phone));
600
601    // Input a local phone number.
602    SetOutputValue(inputs, &outputs, phone, ASCIIToUTF16("2155546699"));
603    validity_data =
604        controller()->InputsAreValid(section, outputs, VALIDATE_EDIT);
605    EXPECT_EQ(0U, validity_data.count(phone));
606
607    // Input an invalid local phone number.
608    SetOutputValue(inputs, &outputs, phone, ASCIIToUTF16("215554669"));
609    validity_data =
610        controller()->InputsAreValid(section, outputs, VALIDATE_EDIT);
611    EXPECT_EQ(1U, validity_data.count(phone));
612
613    // Input an international phone number.
614    SetOutputValue(inputs, &outputs, phone, ASCIIToUTF16("+33 892 70 12 39"));
615    validity_data =
616        controller()->InputsAreValid(section, outputs, VALIDATE_EDIT);
617    EXPECT_EQ(0U, validity_data.count(phone));
618
619    // Input an invalid international phone number.
620    SetOutputValue(inputs, &outputs, phone,
621                   ASCIIToUTF16("+112333 892 70 12 39"));
622    validity_data =
623        controller()->InputsAreValid(section, outputs, VALIDATE_EDIT);
624    EXPECT_EQ(1U, validity_data.count(phone));
625  }
626}
627
628TEST_F(AutofillDialogControllerTest, ExpirationDateValidity) {
629  DetailOutputMap outputs;
630  const DetailInputs& inputs =
631      controller()->RequestedFieldsForSection(SECTION_CC_BILLING);
632
633  ui::ComboboxModel* exp_year_model =
634      controller()->ComboboxModelForAutofillType(CREDIT_CARD_EXP_4_DIGIT_YEAR);
635  ui::ComboboxModel* exp_month_model =
636      controller()->ComboboxModelForAutofillType(CREDIT_CARD_EXP_MONTH);
637
638  base::string16 default_year_value =
639      exp_year_model->GetItemAt(exp_year_model->GetDefaultIndex());
640
641  base::string16 other_year_value =
642      exp_year_model->GetItemAt(exp_year_model->GetItemCount() - 1);
643  base::string16 other_month_value =
644      exp_month_model->GetItemAt(exp_month_model->GetItemCount() - 1);
645
646  SetOutputValue(inputs, &outputs, CREDIT_CARD_EXP_4_DIGIT_YEAR,
647                 default_year_value);
648
649  // Expiration default values "validate" with VALIDATE_EDIT.
650  ValidityData validity_data =
651      controller()->InputsAreValid(SECTION_CC_BILLING, outputs, VALIDATE_EDIT);
652  EXPECT_EQ(0U, validity_data.count(CREDIT_CARD_EXP_4_DIGIT_YEAR));
653  EXPECT_EQ(0U, validity_data.count(CREDIT_CARD_EXP_MONTH));
654
655  // Expiration date with default month "validates" with VALIDATE_EDIT.
656  SetOutputValue(inputs, &outputs, CREDIT_CARD_EXP_4_DIGIT_YEAR,
657                 other_year_value);
658
659  validity_data =
660      controller()->InputsAreValid(SECTION_CC_BILLING, outputs, VALIDATE_EDIT);
661  EXPECT_EQ(0U, validity_data.count(CREDIT_CARD_EXP_4_DIGIT_YEAR));
662  EXPECT_EQ(0U, validity_data.count(CREDIT_CARD_EXP_MONTH));
663
664  // Expiration date with default year "validates" with VALIDATE_EDIT.
665  SetOutputValue(inputs, &outputs, CREDIT_CARD_EXP_MONTH, other_month_value);
666
667  validity_data =
668      controller()->InputsAreValid(SECTION_CC_BILLING, outputs, VALIDATE_EDIT);
669  EXPECT_EQ(0U, validity_data.count(CREDIT_CARD_EXP_4_DIGIT_YEAR));
670  EXPECT_EQ(0U, validity_data.count(CREDIT_CARD_EXP_MONTH));
671
672  // Expiration default values fail with VALIDATE_FINAL.
673  SetOutputValue(inputs, &outputs, CREDIT_CARD_EXP_4_DIGIT_YEAR,
674                 default_year_value);
675
676  validity_data =
677      controller()->InputsAreValid(SECTION_CC_BILLING, outputs, VALIDATE_FINAL);
678  EXPECT_EQ(1U, validity_data.count(CREDIT_CARD_EXP_4_DIGIT_YEAR));
679  EXPECT_EQ(1U, validity_data.count(CREDIT_CARD_EXP_MONTH));
680
681  // Expiration date with default month fails with VALIDATE_FINAL.
682  SetOutputValue(inputs,
683                 &outputs,
684                 CREDIT_CARD_EXP_4_DIGIT_YEAR,
685                 other_year_value);
686
687  validity_data =
688      controller()->InputsAreValid(SECTION_CC_BILLING, outputs, VALIDATE_FINAL);
689  EXPECT_EQ(0U, validity_data.count(CREDIT_CARD_EXP_4_DIGIT_YEAR));
690  EXPECT_EQ(1U, validity_data.count(CREDIT_CARD_EXP_MONTH));
691
692  // Expiration date with default year fails with VALIDATE_FINAL.
693  SetOutputValue(inputs, &outputs, CREDIT_CARD_EXP_MONTH, other_month_value);
694
695  validity_data =
696      controller()->InputsAreValid(SECTION_CC_BILLING, outputs, VALIDATE_FINAL);
697  EXPECT_EQ(1U, validity_data.count(CREDIT_CARD_EXP_4_DIGIT_YEAR));
698  EXPECT_EQ(0U, validity_data.count(CREDIT_CARD_EXP_MONTH));
699}
700
701TEST_F(AutofillDialogControllerTest, BillingNameValidation) {
702  // Construct DetailOutputMap from AutofillProfile data.
703  SwitchToAutofill();
704
705  DetailOutputMap outputs;
706  const DetailInputs& inputs =
707      controller()->RequestedFieldsForSection(SECTION_BILLING);
708
709  // Input an empty billing name with VALIDATE_FINAL.
710  SetOutputValue(inputs, &outputs, NAME_BILLING_FULL, base::string16());
711  ValidityData validity_data =
712      controller()->InputsAreValid(SECTION_BILLING, outputs, VALIDATE_FINAL);
713  EXPECT_EQ(1U, validity_data.count(NAME_BILLING_FULL));
714
715  // Input an empty billing name with VALIDATE_EDIT.
716  validity_data =
717      controller()->InputsAreValid(SECTION_BILLING, outputs, VALIDATE_EDIT);
718  EXPECT_EQ(0U, validity_data.count(NAME_BILLING_FULL));
719
720  // Input a non-empty billing name.
721  SetOutputValue(inputs, &outputs, NAME_BILLING_FULL, ASCIIToUTF16("Bob"));
722  validity_data =
723      controller()->InputsAreValid(SECTION_BILLING, outputs, VALIDATE_FINAL);
724  EXPECT_EQ(0U, validity_data.count(NAME_BILLING_FULL));
725
726  // Switch to Wallet which only considers names with with at least two names to
727  // be valid.
728  SwitchToWallet();
729
730  // Setup some wallet state.
731  scoped_ptr<wallet::WalletItems> wallet_items = wallet::GetTestWalletItems();
732  controller()->OnDidGetWalletItems(wallet_items.Pass());
733
734  DetailOutputMap wallet_outputs;
735  const DetailInputs& wallet_inputs =
736      controller()->RequestedFieldsForSection(SECTION_CC_BILLING);
737
738  // Input an empty billing name with VALIDATE_FINAL. Data source should not
739  // change this behavior.
740  SetOutputValue(wallet_inputs, &wallet_outputs, NAME_BILLING_FULL,
741                 base::string16());
742  validity_data =
743      controller()->InputsAreValid(
744          SECTION_CC_BILLING, wallet_outputs, VALIDATE_FINAL);
745  EXPECT_EQ(1U, validity_data.count(NAME_BILLING_FULL));
746
747  // Input an empty billing name with VALIDATE_EDIT. Data source should not
748  // change this behavior.
749  validity_data =
750      controller()->InputsAreValid(
751          SECTION_CC_BILLING, wallet_outputs, VALIDATE_EDIT);
752  EXPECT_EQ(0U, validity_data.count(NAME_BILLING_FULL));
753
754  // Input a one name billing name. Wallet does not currently support this.
755  SetOutputValue(wallet_inputs, &wallet_outputs, NAME_BILLING_FULL,
756                 ASCIIToUTF16("Bob"));
757  validity_data =
758      controller()->InputsAreValid(
759          SECTION_CC_BILLING, wallet_outputs, VALIDATE_FINAL);
760  EXPECT_EQ(1U, validity_data.count(NAME_BILLING_FULL));
761
762  // Input a two name billing name.
763  SetOutputValue(wallet_inputs, &wallet_outputs, NAME_BILLING_FULL,
764                 ASCIIToUTF16("Bob Barker"));
765  validity_data =
766      controller()->InputsAreValid(
767          SECTION_CC_BILLING, wallet_outputs, VALIDATE_FINAL);
768  EXPECT_EQ(0U, validity_data.count(NAME_BILLING_FULL));
769
770  // Input a more than two name billing name.
771  SetOutputValue(wallet_inputs, &wallet_outputs, NAME_BILLING_FULL,
772                 ASCIIToUTF16("John Jacob Jingleheimer Schmidt"));
773  validity_data =
774      controller()->InputsAreValid(
775          SECTION_CC_BILLING, wallet_outputs, VALIDATE_FINAL);
776  EXPECT_EQ(0U, validity_data.count(NAME_BILLING_FULL));
777
778  // Input a billing name with lots of crazy whitespace.
779  SetOutputValue(
780      wallet_inputs, &wallet_outputs, NAME_BILLING_FULL,
781      ASCIIToUTF16("     \\n\\r John \\n  Jacob Jingleheimer \\t Schmidt  "));
782  validity_data =
783      controller()->InputsAreValid(
784          SECTION_CC_BILLING, wallet_outputs, VALIDATE_FINAL);
785  EXPECT_EQ(0U, validity_data.count(NAME_BILLING_FULL));
786}
787
788TEST_F(AutofillDialogControllerTest, CreditCardNumberValidation) {
789  // Construct DetailOutputMap from AutofillProfile data.
790  SwitchToAutofill();
791
792  // Should accept AMEX, Visa, Master and Discover.
793  ValidateCCNumber(SECTION_CC, kTestCCNumberVisa, true);
794  ValidateCCNumber(SECTION_CC, kTestCCNumberMaster, true);
795  ValidateCCNumber(SECTION_CC, kTestCCNumberDiscover, true);
796  ValidateCCNumber(SECTION_CC, kTestCCNumberAmex, true);
797
798  ValidateCCNumber(SECTION_CC, kTestCCNumberIncomplete, false);
799  ValidateCCNumber(SECTION_CC, kTestCCNumberInvalid, false);
800
801  // Switch to Wallet which will not accept AMEX.
802  SwitchToWallet();
803
804  // Setup some wallet state.
805  controller()->OnDidGetWalletItems(wallet::GetTestWalletItems());
806
807  // Should accept Visa, Master and Discover, but not AMEX.
808  ValidateCCNumber(SECTION_CC_BILLING, kTestCCNumberVisa, true);
809  ValidateCCNumber(SECTION_CC_BILLING, kTestCCNumberMaster, true);
810  ValidateCCNumber(SECTION_CC_BILLING, kTestCCNumberDiscover, true);
811
812  ValidateCCNumber(SECTION_CC_BILLING, kTestCCNumberAmex, false);
813  ValidateCCNumber(SECTION_CC_BILLING, kTestCCNumberIncomplete, false);
814  ValidateCCNumber(SECTION_CC_BILLING, kTestCCNumberInvalid, false);
815}
816
817TEST_F(AutofillDialogControllerTest, AutofillProfiles) {
818  ui::MenuModel* shipping_model =
819      controller()->MenuModelForSection(SECTION_SHIPPING);
820  // Since the PersonalDataManager is empty, this should only have the
821  // "use billing", "add new" and "manage" menu items.
822  ASSERT_TRUE(shipping_model);
823  EXPECT_EQ(3, shipping_model->GetItemCount());
824  // On the other hand, the other models should be NULL when there's no
825  // suggestion.
826  EXPECT_FALSE(controller()->MenuModelForSection(SECTION_CC));
827  EXPECT_FALSE(controller()->MenuModelForSection(SECTION_BILLING));
828  EXPECT_FALSE(controller()->MenuModelForSection(SECTION_EMAIL));
829
830  EXPECT_CALL(*controller()->GetView(), ModelChanged()).Times(3);
831
832  // Empty profiles are ignored.
833  AutofillProfile empty_profile(base::GenerateGUID(), kSettingsOrigin);
834  empty_profile.SetRawInfo(NAME_FULL, ASCIIToUTF16("John Doe"));
835  controller()->GetTestingManager()->AddTestingProfile(&empty_profile);
836  shipping_model = controller()->MenuModelForSection(SECTION_SHIPPING);
837  ASSERT_TRUE(shipping_model);
838  EXPECT_EQ(3, shipping_model->GetItemCount());
839  EXPECT_FALSE(controller()->MenuModelForSection(SECTION_EMAIL));
840
841  // An otherwise full but unverified profile should be ignored.
842  AutofillProfile full_profile(test::GetFullProfile());
843  full_profile.set_origin("https://www.example.com");
844  full_profile.SetRawInfo(ADDRESS_HOME_LINE2, string16());
845  controller()->GetTestingManager()->AddTestingProfile(&full_profile);
846  shipping_model = controller()->MenuModelForSection(SECTION_SHIPPING);
847  ASSERT_TRUE(shipping_model);
848  EXPECT_EQ(3, shipping_model->GetItemCount());
849  EXPECT_FALSE(controller()->MenuModelForSection(SECTION_EMAIL));
850
851  // A full, verified profile should be picked up.
852  AutofillProfile verified_profile(test::GetVerifiedProfile());
853  verified_profile.SetRawInfo(ADDRESS_HOME_LINE2, string16());
854  controller()->GetTestingManager()->AddTestingProfile(&verified_profile);
855  shipping_model = controller()->MenuModelForSection(SECTION_SHIPPING);
856  ASSERT_TRUE(shipping_model);
857  EXPECT_EQ(4, shipping_model->GetItemCount());
858  EXPECT_TRUE(!!controller()->MenuModelForSection(SECTION_EMAIL));
859}
860
861// Makes sure that the choice of which Autofill profile to use for each section
862// is sticky.
863TEST_F(AutofillDialogControllerTest, AutofillProfileDefaults) {
864  AutofillProfile full_profile(test::GetFullProfile());
865  full_profile.set_origin(kSettingsOrigin);
866  controller()->GetTestingManager()->AddTestingProfile(&full_profile);
867  AutofillProfile full_profile2(test::GetFullProfile2());
868  full_profile2.set_origin(kSettingsOrigin);
869  controller()->GetTestingManager()->AddTestingProfile(&full_profile2);
870
871  // Until a selection has been made, the default shipping suggestion is the
872  // first one (after "use billing").
873  SuggestionsMenuModel* shipping_model = static_cast<SuggestionsMenuModel*>(
874      controller()->MenuModelForSection(SECTION_SHIPPING));
875  EXPECT_EQ(1, shipping_model->checked_item());
876
877  for (int i = 2; i >= 0; --i) {
878    shipping_model = static_cast<SuggestionsMenuModel*>(
879        controller()->MenuModelForSection(SECTION_SHIPPING));
880    shipping_model->ExecuteCommand(i, 0);
881    FillCreditCardInputs();
882    controller()->OnAccept();
883
884    Reset();
885    controller()->GetTestingManager()->AddTestingProfile(&full_profile);
886    controller()->GetTestingManager()->AddTestingProfile(&full_profile2);
887    shipping_model = static_cast<SuggestionsMenuModel*>(
888        controller()->MenuModelForSection(SECTION_SHIPPING));
889    EXPECT_EQ(i, shipping_model->checked_item());
890  }
891
892  // Try again, but don't add the default profile to the PDM. The dialog
893  // should fall back to the first profile.
894  shipping_model->ExecuteCommand(2, 0);
895  FillCreditCardInputs();
896  controller()->OnAccept();
897  Reset();
898  controller()->GetTestingManager()->AddTestingProfile(&full_profile);
899  shipping_model = static_cast<SuggestionsMenuModel*>(
900      controller()->MenuModelForSection(SECTION_SHIPPING));
901  EXPECT_EQ(1, shipping_model->checked_item());
902}
903
904TEST_F(AutofillDialogControllerTest, AutofillProfileVariants) {
905  EXPECT_CALL(*controller()->GetView(), ModelChanged()).Times(1);
906  ui::MenuModel* email_model =
907      controller()->MenuModelForSection(SECTION_EMAIL);
908  EXPECT_FALSE(email_model);
909
910  // Set up some variant data.
911  AutofillProfile full_profile(test::GetVerifiedProfile());
912  std::vector<string16> names;
913  names.push_back(ASCIIToUTF16("John Doe"));
914  names.push_back(ASCIIToUTF16("Jane Doe"));
915  full_profile.SetRawMultiInfo(EMAIL_ADDRESS, names);
916  const string16 kEmail1 = ASCIIToUTF16(kFakeEmail);
917  const string16 kEmail2 = ASCIIToUTF16("admin@example.com");
918  std::vector<string16> emails;
919  emails.push_back(kEmail1);
920  emails.push_back(kEmail2);
921  full_profile.SetRawMultiInfo(EMAIL_ADDRESS, emails);
922
923  // Respect variants for the email address field only.
924  controller()->GetTestingManager()->AddTestingProfile(&full_profile);
925  ui::MenuModel* shipping_model =
926      controller()->MenuModelForSection(SECTION_SHIPPING);
927  EXPECT_EQ(4, shipping_model->GetItemCount());
928  email_model = controller()->MenuModelForSection(SECTION_EMAIL);
929  ASSERT_TRUE(!!email_model);
930  EXPECT_EQ(4, email_model->GetItemCount());
931
932  // The first one is the default.
933  SuggestionsMenuModel* email_suggestions = static_cast<SuggestionsMenuModel*>(
934      controller()->MenuModelForSection(SECTION_EMAIL));
935  EXPECT_EQ(0, email_suggestions->checked_item());
936
937  email_model->ActivatedAt(0);
938  EXPECT_EQ(kEmail1,
939            controller()->SuggestionStateForSection(SECTION_EMAIL).
940                vertically_compact_text);
941  email_model->ActivatedAt(1);
942  EXPECT_EQ(kEmail2,
943            controller()->SuggestionStateForSection(SECTION_EMAIL).
944                vertically_compact_text);
945
946  controller()->EditClickedForSection(SECTION_EMAIL);
947  const DetailInputs& inputs =
948      controller()->RequestedFieldsForSection(SECTION_EMAIL);
949  EXPECT_EQ(kEmail2, inputs[0].initial_value);
950
951  // The choice of variant is persisted across runs of the dialog.
952  email_model->ActivatedAt(0);
953  email_model->ActivatedAt(1);
954  FillCreditCardInputs();
955  controller()->OnAccept();
956
957  Reset();
958  controller()->GetTestingManager()->AddTestingProfile(&full_profile);
959  email_suggestions = static_cast<SuggestionsMenuModel*>(
960      controller()->MenuModelForSection(SECTION_EMAIL));
961  EXPECT_EQ(1, email_suggestions->checked_item());
962}
963
964TEST_F(AutofillDialogControllerTest, SuggestValidEmail) {
965  AutofillProfile profile(test::GetVerifiedProfile());
966  const string16 kValidEmail = ASCIIToUTF16(kFakeEmail);
967  profile.SetRawInfo(EMAIL_ADDRESS, kValidEmail);
968  controller()->GetTestingManager()->AddTestingProfile(&profile);
969
970  controller()->MenuModelForSection(SECTION_EMAIL)->ActivatedAt(0);
971  EXPECT_EQ(kValidEmail,
972            controller()->SuggestionStateForSection(SECTION_EMAIL).
973                vertically_compact_text);
974}
975
976TEST_F(AutofillDialogControllerTest, DoNotSuggestInvalidEmail) {
977  AutofillProfile profile(test::GetVerifiedProfile());
978  profile.SetRawInfo(EMAIL_ADDRESS, ASCIIToUTF16(".!#$%&'*+/=?^_`-@-.."));
979  controller()->GetTestingManager()->AddTestingProfile(&profile);
980  EXPECT_EQ(static_cast<ui::MenuModel*>(NULL),
981            controller()->MenuModelForSection(SECTION_EMAIL));
982}
983
984TEST_F(AutofillDialogControllerTest, DoNotSuggestEmailFromIncompleteProfile) {
985  AutofillProfile profile(test::GetVerifiedProfile());
986  profile.SetRawInfo(EMAIL_ADDRESS, ASCIIToUTF16(kFakeEmail));
987  profile.SetRawInfo(ADDRESS_HOME_STATE, base::string16());
988  controller()->GetTestingManager()->AddTestingProfile(&profile);
989  EXPECT_EQ(static_cast<ui::MenuModel*>(NULL),
990            controller()->MenuModelForSection(SECTION_EMAIL));
991}
992
993TEST_F(AutofillDialogControllerTest, DoNotSuggestEmailFromInvalidProfile) {
994  AutofillProfile profile(test::GetVerifiedProfile());
995  profile.SetRawInfo(EMAIL_ADDRESS, ASCIIToUTF16(kFakeEmail));
996  profile.SetRawInfo(ADDRESS_HOME_STATE, ASCIIToUTF16("C"));
997  controller()->GetTestingManager()->AddTestingProfile(&profile);
998  EXPECT_EQ(static_cast<ui::MenuModel*>(NULL),
999            controller()->MenuModelForSection(SECTION_EMAIL));
1000}
1001
1002TEST_F(AutofillDialogControllerTest, SuggestValidAddress) {
1003  AutofillProfile full_profile(test::GetVerifiedProfile());
1004  full_profile.set_origin(kSettingsOrigin);
1005  controller()->GetTestingManager()->AddTestingProfile(&full_profile);
1006  EXPECT_EQ(
1007      4, controller()->MenuModelForSection(SECTION_SHIPPING)->GetItemCount());
1008}
1009
1010TEST_F(AutofillDialogControllerTest, DoNotSuggestInvalidAddress) {
1011  AutofillProfile full_profile(test::GetVerifiedProfile());
1012  full_profile.set_origin(kSettingsOrigin);
1013  full_profile.SetRawInfo(ADDRESS_HOME_STATE, ASCIIToUTF16("C"));
1014  controller()->GetTestingManager()->AddTestingProfile(&full_profile);
1015  EXPECT_EQ(
1016      3, controller()->MenuModelForSection(SECTION_SHIPPING)->GetItemCount());
1017}
1018
1019TEST_F(AutofillDialogControllerTest, AutofillCreditCards) {
1020  // Since the PersonalDataManager is empty, this should only have the
1021  // default menu items.
1022  EXPECT_FALSE(controller()->MenuModelForSection(SECTION_CC));
1023
1024  EXPECT_CALL(*controller()->GetView(), ModelChanged()).Times(3);
1025
1026  // Empty cards are ignored.
1027  CreditCard empty_card(base::GenerateGUID(), kSettingsOrigin);
1028  empty_card.SetRawInfo(CREDIT_CARD_NAME, ASCIIToUTF16("John Doe"));
1029  controller()->GetTestingManager()->AddTestingCreditCard(&empty_card);
1030  EXPECT_FALSE(controller()->MenuModelForSection(SECTION_CC));
1031
1032  // An otherwise full but unverified card should be ignored.
1033  CreditCard full_card(test::GetCreditCard());
1034  full_card.set_origin("https://www.example.com");
1035  controller()->GetTestingManager()->AddTestingCreditCard(&full_card);
1036  EXPECT_FALSE(controller()->MenuModelForSection(SECTION_CC));
1037
1038  // A full, verified card should be picked up.
1039  CreditCard verified_card(test::GetCreditCard());
1040  verified_card.set_origin(kSettingsOrigin);
1041  controller()->GetTestingManager()->AddTestingCreditCard(&verified_card);
1042  ui::MenuModel* credit_card_model =
1043      controller()->MenuModelForSection(SECTION_CC);
1044  ASSERT_TRUE(credit_card_model);
1045  EXPECT_EQ(3, credit_card_model->GetItemCount());
1046}
1047
1048// Test selecting a shipping address different from billing as address.
1049TEST_F(AutofillDialogControllerTest, DontUseBillingAsShipping) {
1050  AutofillProfile full_profile(test::GetVerifiedProfile());
1051  AutofillProfile full_profile2(test::GetVerifiedProfile2());
1052  CreditCard credit_card(test::GetVerifiedCreditCard());
1053  controller()->GetTestingManager()->AddTestingProfile(&full_profile);
1054  controller()->GetTestingManager()->AddTestingProfile(&full_profile2);
1055  controller()->GetTestingManager()->AddTestingCreditCard(&credit_card);
1056  ui::MenuModel* shipping_model =
1057      controller()->MenuModelForSection(SECTION_SHIPPING);
1058  shipping_model->ActivatedAt(2);
1059
1060  controller()->OnAccept();
1061  ASSERT_EQ(20U, form_structure()->field_count());
1062  EXPECT_EQ(ADDRESS_HOME_STATE,
1063            form_structure()->field(9)->Type().GetStorableType());
1064  EXPECT_EQ(ADDRESS_BILLING, form_structure()->field(9)->Type().group());
1065  EXPECT_EQ(ADDRESS_HOME_STATE,
1066            form_structure()->field(16)->Type().GetStorableType());
1067  EXPECT_EQ(ADDRESS_HOME, form_structure()->field(16)->Type().group());
1068  string16 billing_state = form_structure()->field(9)->value;
1069  string16 shipping_state = form_structure()->field(16)->value;
1070  EXPECT_FALSE(billing_state.empty());
1071  EXPECT_FALSE(shipping_state.empty());
1072  EXPECT_NE(billing_state, shipping_state);
1073
1074  EXPECT_EQ(CREDIT_CARD_NAME,
1075            form_structure()->field(1)->Type().GetStorableType());
1076  string16 cc_name = form_structure()->field(1)->value;
1077  EXPECT_EQ(NAME_FULL, form_structure()->field(6)->Type().GetStorableType());
1078  EXPECT_EQ(NAME_BILLING, form_structure()->field(6)->Type().group());
1079  string16 billing_name = form_structure()->field(6)->value;
1080  EXPECT_EQ(NAME_FULL, form_structure()->field(13)->Type().GetStorableType());
1081  EXPECT_EQ(NAME, form_structure()->field(13)->Type().group());
1082  string16 shipping_name = form_structure()->field(13)->value;
1083
1084  EXPECT_FALSE(cc_name.empty());
1085  EXPECT_FALSE(billing_name.empty());
1086  EXPECT_FALSE(shipping_name.empty());
1087  // Billing name should always be the same as cardholder name.
1088  EXPECT_EQ(cc_name, billing_name);
1089  EXPECT_NE(cc_name, shipping_name);
1090}
1091
1092// Test selecting UseBillingForShipping.
1093TEST_F(AutofillDialogControllerTest, UseBillingAsShipping) {
1094  AutofillProfile full_profile(test::GetVerifiedProfile());
1095  AutofillProfile full_profile2(test::GetVerifiedProfile2());
1096  CreditCard credit_card(test::GetVerifiedCreditCard());
1097  controller()->GetTestingManager()->AddTestingProfile(&full_profile);
1098  controller()->GetTestingManager()->AddTestingProfile(&full_profile2);
1099  controller()->GetTestingManager()->AddTestingCreditCard(&credit_card);
1100
1101  // Test after setting use billing for shipping.
1102  UseBillingForShipping();
1103
1104  controller()->OnAccept();
1105  ASSERT_EQ(20U, form_structure()->field_count());
1106  EXPECT_EQ(ADDRESS_HOME_STATE,
1107            form_structure()->field(9)->Type().GetStorableType());
1108  EXPECT_EQ(ADDRESS_BILLING, form_structure()->field(9)->Type().group());
1109  EXPECT_EQ(ADDRESS_HOME_STATE,
1110            form_structure()->field(16)->Type().GetStorableType());
1111  EXPECT_EQ(ADDRESS_HOME, form_structure()->field(16)->Type().group());
1112  string16 billing_state = form_structure()->field(9)->value;
1113  string16 shipping_state = form_structure()->field(16)->value;
1114  EXPECT_FALSE(billing_state.empty());
1115  EXPECT_FALSE(shipping_state.empty());
1116  EXPECT_EQ(billing_state, shipping_state);
1117
1118  EXPECT_EQ(CREDIT_CARD_NAME,
1119            form_structure()->field(1)->Type().GetStorableType());
1120  string16 cc_name = form_structure()->field(1)->value;
1121  EXPECT_EQ(NAME_FULL, form_structure()->field(6)->Type().GetStorableType());
1122  EXPECT_EQ(NAME_BILLING, form_structure()->field(6)->Type().group());
1123  string16 billing_name = form_structure()->field(6)->value;
1124  EXPECT_EQ(NAME_FULL, form_structure()->field(13)->Type().GetStorableType());
1125  EXPECT_EQ(NAME, form_structure()->field(13)->Type().group());
1126  string16 shipping_name = form_structure()->field(13)->value;
1127
1128  EXPECT_FALSE(cc_name.empty());
1129  EXPECT_FALSE(billing_name.empty());
1130  EXPECT_FALSE(shipping_name.empty());
1131  EXPECT_EQ(cc_name, billing_name);
1132  EXPECT_EQ(cc_name, shipping_name);
1133}
1134
1135// Tests that shipping and billing telephone fields are supported, and filled
1136// in by their respective profiles. http://crbug.com/244515
1137TEST_F(AutofillDialogControllerTest, BillingVsShippingPhoneNumber) {
1138  FormFieldData shipping_tel;
1139  shipping_tel.autocomplete_attribute = "shipping tel";
1140  FormFieldData billing_tel;
1141  billing_tel.autocomplete_attribute = "billing tel";
1142
1143  FormData form_data;
1144  form_data.fields.push_back(shipping_tel);
1145  form_data.fields.push_back(billing_tel);
1146  SetUpControllerWithFormData(form_data);
1147
1148  // The profile that will be chosen for the shipping section.
1149  AutofillProfile shipping_profile(test::GetVerifiedProfile());
1150  // The profile that will be chosen for the billing section.
1151  AutofillProfile billing_profile(test::GetVerifiedProfile2());
1152  CreditCard credit_card(test::GetVerifiedCreditCard());
1153  controller()->GetTestingManager()->AddTestingProfile(&shipping_profile);
1154  controller()->GetTestingManager()->AddTestingProfile(&billing_profile);
1155  controller()->GetTestingManager()->AddTestingCreditCard(&credit_card);
1156  ui::MenuModel* billing_model =
1157      controller()->MenuModelForSection(SECTION_BILLING);
1158  billing_model->ActivatedAt(1);
1159
1160  controller()->OnAccept();
1161  ASSERT_EQ(2U, form_structure()->field_count());
1162  EXPECT_EQ(PHONE_HOME_WHOLE_NUMBER,
1163            form_structure()->field(0)->Type().GetStorableType());
1164  EXPECT_EQ(PHONE_HOME, form_structure()->field(0)->Type().group());
1165  EXPECT_EQ(PHONE_HOME_WHOLE_NUMBER,
1166            form_structure()->field(1)->Type().GetStorableType());
1167  EXPECT_EQ(PHONE_BILLING, form_structure()->field(1)->Type().group());
1168  EXPECT_EQ(shipping_profile.GetRawInfo(PHONE_HOME_WHOLE_NUMBER),
1169            form_structure()->field(0)->value);
1170  EXPECT_EQ(billing_profile.GetRawInfo(PHONE_HOME_WHOLE_NUMBER),
1171            form_structure()->field(1)->value);
1172  EXPECT_NE(form_structure()->field(1)->value,
1173            form_structure()->field(0)->value);
1174}
1175
1176TEST_F(AutofillDialogControllerTest, AcceptLegalDocuments) {
1177  EXPECT_CALL(*controller()->GetTestingWalletClient(),
1178              AcceptLegalDocuments(_, _, _)).Times(1);
1179  EXPECT_CALL(*controller()->GetTestingWalletClient(),
1180              GetFullWallet(_)).Times(1);
1181  EXPECT_CALL(*controller(), LoadRiskFingerprintData()).Times(1);
1182
1183  scoped_ptr<wallet::WalletItems> wallet_items = CompleteAndValidWalletItems();
1184  wallet_items->AddLegalDocument(wallet::GetTestLegalDocument());
1185  controller()->OnDidGetWalletItems(wallet_items.Pass());
1186  controller()->OnAccept();
1187  controller()->OnDidAcceptLegalDocuments();
1188  controller()->OnDidLoadRiskFingerprintData(GetFakeFingerprint().Pass());
1189}
1190
1191// Makes sure the default object IDs are respected.
1192TEST_F(AutofillDialogControllerTest, WalletDefaultItems) {
1193  scoped_ptr<wallet::WalletItems> wallet_items = wallet::GetTestWalletItems();
1194  wallet_items->AddInstrument(wallet::GetTestNonDefaultMaskedInstrument());
1195  wallet_items->AddInstrument(wallet::GetTestNonDefaultMaskedInstrument());
1196  wallet_items->AddInstrument(wallet::GetTestMaskedInstrument());
1197  wallet_items->AddInstrument(wallet::GetTestNonDefaultMaskedInstrument());
1198
1199  wallet_items->AddAddress(wallet::GetTestNonDefaultShippingAddress());
1200  wallet_items->AddAddress(wallet::GetTestNonDefaultShippingAddress());
1201  wallet_items->AddAddress(wallet::GetTestNonDefaultShippingAddress());
1202  wallet_items->AddAddress(wallet::GetTestShippingAddress());
1203  wallet_items->AddAddress(wallet::GetTestNonDefaultShippingAddress());
1204
1205  controller()->OnDidGetWalletItems(wallet_items.Pass());
1206  // "add", "manage", and 4 suggestions.
1207  EXPECT_EQ(6,
1208      controller()->MenuModelForSection(SECTION_CC_BILLING)->GetItemCount());
1209  EXPECT_TRUE(controller()->MenuModelForSection(SECTION_CC_BILLING)->
1210      IsItemCheckedAt(2));
1211  ASSERT_FALSE(controller()->IsEditingExistingData(SECTION_CC_BILLING));
1212  // "use billing", "add", "manage", and 5 suggestions.
1213  EXPECT_EQ(8,
1214      controller()->MenuModelForSection(SECTION_SHIPPING)->GetItemCount());
1215  EXPECT_TRUE(controller()->MenuModelForSection(SECTION_SHIPPING)->
1216      IsItemCheckedAt(4));
1217  ASSERT_FALSE(controller()->IsEditingExistingData(SECTION_SHIPPING));
1218}
1219
1220// Tests that invalid and AMEX default instruments are ignored.
1221TEST_F(AutofillDialogControllerTest, SelectInstrument) {
1222  scoped_ptr<wallet::WalletItems> wallet_items = wallet::GetTestWalletItems();
1223  // Tests if default instrument is invalid, then, the first valid instrument is
1224  // selected instead of the default instrument.
1225  wallet_items->AddInstrument(wallet::GetTestNonDefaultMaskedInstrument());
1226  wallet_items->AddInstrument(wallet::GetTestNonDefaultMaskedInstrument());
1227  wallet_items->AddInstrument(wallet::GetTestMaskedInstrumentInvalid());
1228  wallet_items->AddInstrument(wallet::GetTestNonDefaultMaskedInstrument());
1229
1230  controller()->OnDidGetWalletItems(wallet_items.Pass());
1231  // 4 suggestions and "add", "manage".
1232  EXPECT_EQ(6,
1233      controller()->MenuModelForSection(SECTION_CC_BILLING)->GetItemCount());
1234  EXPECT_TRUE(controller()->MenuModelForSection(SECTION_CC_BILLING)->
1235      IsItemCheckedAt(0));
1236
1237  // Tests if default instrument is AMEX, then, the first valid instrument is
1238  // selected instead of the default instrument.
1239  wallet_items = wallet::GetTestWalletItems();
1240  wallet_items->AddInstrument(wallet::GetTestNonDefaultMaskedInstrument());
1241  wallet_items->AddInstrument(wallet::GetTestNonDefaultMaskedInstrument());
1242  wallet_items->AddInstrument(wallet::GetTestMaskedInstrumentAmex());
1243  wallet_items->AddInstrument(wallet::GetTestNonDefaultMaskedInstrument());
1244
1245  controller()->OnDidGetWalletItems(wallet_items.Pass());
1246  // 4 suggestions and "add", "manage".
1247  EXPECT_EQ(6,
1248      controller()->MenuModelForSection(SECTION_CC_BILLING)->GetItemCount());
1249  EXPECT_TRUE(controller()->MenuModelForSection(SECTION_CC_BILLING)->
1250      IsItemCheckedAt(0));
1251
1252  // Tests if only have AMEX and invalid instrument, then "add" is selected.
1253  wallet_items = wallet::GetTestWalletItems();
1254  wallet_items->AddInstrument(wallet::GetTestMaskedInstrumentInvalid());
1255  wallet_items->AddInstrument(wallet::GetTestMaskedInstrumentAmex());
1256
1257  controller()->OnDidGetWalletItems(wallet_items.Pass());
1258  // 2 suggestions and "add", "manage".
1259  EXPECT_EQ(4,
1260      controller()->MenuModelForSection(SECTION_CC_BILLING)->GetItemCount());
1261  // "add"
1262  EXPECT_TRUE(controller()->MenuModelForSection(SECTION_CC_BILLING)->
1263      IsItemCheckedAt(2));
1264}
1265
1266TEST_F(AutofillDialogControllerTest, SaveAddress) {
1267  EXPECT_CALL(*controller()->GetView(), ModelChanged()).Times(1);
1268  EXPECT_CALL(*controller()->GetTestingWalletClient(),
1269              SaveToWalletMock(testing::IsNull(),
1270                               testing::NotNull(),
1271                               _)).Times(1);
1272
1273  scoped_ptr<wallet::WalletItems> wallet_items = wallet::GetTestWalletItems();
1274  wallet_items->AddInstrument(wallet::GetTestMaskedInstrument());
1275  controller()->OnDidGetWalletItems(wallet_items.Pass());
1276  // If there is no shipping address in wallet, it will default to
1277  // "same-as-billing" instead of "add-new-item". "same-as-billing" is covered
1278  // by the following tests. The last item in the menu is "add-new-item".
1279  ui::MenuModel* shipping_model =
1280      controller()->MenuModelForSection(SECTION_SHIPPING);
1281  shipping_model->ActivatedAt(shipping_model->GetItemCount() - 1);
1282  AcceptAndLoadFakeFingerprint();
1283}
1284
1285TEST_F(AutofillDialogControllerTest, SaveInstrument) {
1286  EXPECT_CALL(*controller()->GetView(), ModelChanged()).Times(1);
1287  EXPECT_CALL(*controller()->GetTestingWalletClient(),
1288              SaveToWalletMock(testing::NotNull(),
1289                               testing::IsNull(),
1290                               _)).Times(1);
1291
1292  scoped_ptr<wallet::WalletItems> wallet_items = wallet::GetTestWalletItems();
1293  wallet_items->AddAddress(wallet::GetTestShippingAddress());
1294  SubmitWithWalletItems(wallet_items.Pass());
1295}
1296
1297TEST_F(AutofillDialogControllerTest, SaveInstrumentWithInvalidInstruments) {
1298  EXPECT_CALL(*controller()->GetView(), ModelChanged()).Times(1);
1299  EXPECT_CALL(*controller()->GetTestingWalletClient(),
1300              SaveToWalletMock(testing::NotNull(),
1301                               testing::IsNull(),
1302                               _)).Times(1);
1303
1304  scoped_ptr<wallet::WalletItems> wallet_items = wallet::GetTestWalletItems();
1305  wallet_items->AddAddress(wallet::GetTestShippingAddress());
1306  wallet_items->AddInstrument(wallet::GetTestMaskedInstrumentInvalid());
1307  SubmitWithWalletItems(wallet_items.Pass());
1308}
1309
1310TEST_F(AutofillDialogControllerTest, SaveInstrumentAndAddress) {
1311  EXPECT_CALL(*controller()->GetTestingWalletClient(),
1312              SaveToWalletMock(testing::NotNull(),
1313                               testing::NotNull(),
1314                               _)).Times(1);
1315
1316  controller()->OnDidGetWalletItems(wallet::GetTestWalletItems());
1317  AcceptAndLoadFakeFingerprint();
1318}
1319
1320MATCHER(IsUpdatingExistingData, "updating existing Wallet data") {
1321  return !arg->object_id().empty();
1322}
1323
1324// Tests that editing an address (in wallet mode0 and submitting the dialog
1325// should update the existing address on the server via WalletClient.
1326TEST_F(AutofillDialogControllerTest, UpdateAddress) {
1327  EXPECT_CALL(*controller()->GetTestingWalletClient(),
1328              SaveToWalletMock(testing::IsNull(),
1329                               IsUpdatingExistingData(),
1330                               _)).Times(1);
1331
1332  controller()->OnDidGetWalletItems(CompleteAndValidWalletItems());
1333
1334  controller()->EditClickedForSection(SECTION_SHIPPING);
1335  AcceptAndLoadFakeFingerprint();
1336}
1337
1338// Tests that editing an instrument (CC + address) in wallet mode updates an
1339// existing instrument on the server via WalletClient.
1340TEST_F(AutofillDialogControllerTest, UpdateInstrument) {
1341  EXPECT_CALL(*controller()->GetTestingWalletClient(),
1342              SaveToWalletMock(IsUpdatingExistingData(),
1343                               testing::IsNull(),
1344                               _)).Times(1);
1345
1346  controller()->OnDidGetWalletItems(CompleteAndValidWalletItems());
1347
1348  controller()->EditClickedForSection(SECTION_CC_BILLING);
1349  AcceptAndLoadFakeFingerprint();
1350}
1351
1352// Test that a user is able to edit their instrument and add a new address in
1353// the same submission.
1354TEST_F(AutofillDialogControllerTest, UpdateInstrumentSaveAddress) {
1355  EXPECT_CALL(*controller()->GetTestingWalletClient(),
1356              SaveToWalletMock(IsUpdatingExistingData(),
1357                               testing::NotNull(),
1358                               _)).Times(1);
1359
1360  scoped_ptr<wallet::WalletItems> wallet_items = wallet::GetTestWalletItems();
1361  wallet_items->AddInstrument(wallet::GetTestMaskedInstrument());
1362  controller()->OnDidGetWalletItems(wallet_items.Pass());
1363
1364  controller()->EditClickedForSection(SECTION_CC_BILLING);
1365  AcceptAndLoadFakeFingerprint();
1366}
1367
1368// Test that saving a new instrument and editing an address works.
1369TEST_F(AutofillDialogControllerTest, SaveInstrumentUpdateAddress) {
1370  EXPECT_CALL(*controller()->GetTestingWalletClient(),
1371              SaveToWalletMock(testing::NotNull(),
1372                               IsUpdatingExistingData(),
1373                               _)).Times(1);
1374
1375  scoped_ptr<wallet::WalletItems> wallet_items = wallet::GetTestWalletItems();
1376  wallet_items->AddAddress(wallet::GetTestShippingAddress());
1377
1378  controller()->OnDidGetWalletItems(wallet_items.Pass());
1379
1380  controller()->EditClickedForSection(SECTION_SHIPPING);
1381  AcceptAndLoadFakeFingerprint();
1382}
1383
1384MATCHER(UsesLocalBillingAddress, "uses the local billing address") {
1385  return arg->address_line_1() == ASCIIToUTF16(kEditedBillingAddress);
1386}
1387
1388// Tests that when using billing address for shipping, and there is no exact
1389// matched shipping address, then a shipping address should be added.
1390TEST_F(AutofillDialogControllerTest, BillingForShipping) {
1391  EXPECT_CALL(*controller()->GetTestingWalletClient(),
1392              SaveToWalletMock(testing::IsNull(),
1393                               testing::NotNull(),
1394                               _)).Times(1);
1395
1396  controller()->OnDidGetWalletItems(CompleteAndValidWalletItems());
1397  // Select "Same as billing" in the address menu.
1398  UseBillingForShipping();
1399
1400  AcceptAndLoadFakeFingerprint();
1401}
1402
1403// Tests that when using billing address for shipping, and there is an exact
1404// matched shipping address, then a shipping address should not be added.
1405TEST_F(AutofillDialogControllerTest, BillingForShippingHasMatch) {
1406  EXPECT_CALL(*controller()->GetTestingWalletClient(),
1407              SaveToWalletMock(_, _, _)).Times(0);
1408
1409  scoped_ptr<wallet::WalletItems> wallet_items = wallet::GetTestWalletItems();
1410  scoped_ptr<wallet::WalletItems::MaskedInstrument> instrument =
1411      wallet::GetTestMaskedInstrument();
1412  // Copy billing address as shipping address, and assign an id to it.
1413  scoped_ptr<wallet::Address> shipping_address(
1414      new wallet::Address(instrument->address()));
1415  shipping_address->set_object_id("shipping_address_id");
1416  wallet_items->AddAddress(shipping_address.Pass());
1417  wallet_items->AddInstrument(instrument.Pass());
1418  wallet_items->AddAddress(wallet::GetTestShippingAddress());
1419
1420  controller()->OnDidGetWalletItems(wallet_items.Pass());
1421  // Select "Same as billing" in the address menu.
1422  UseBillingForShipping();
1423
1424  AcceptAndLoadFakeFingerprint();
1425}
1426
1427// Test that the local view contents is used when saving a new instrument and
1428// the user has selected "Same as billing".
1429TEST_F(AutofillDialogControllerTest, SaveInstrumentSameAsBilling) {
1430  scoped_ptr<wallet::WalletItems> wallet_items = wallet::GetTestWalletItems();
1431  wallet_items->AddInstrument(wallet::GetTestMaskedInstrument());
1432  controller()->OnDidGetWalletItems(wallet_items.Pass());
1433
1434  controller()->EditClickedForSection(SECTION_CC_BILLING);
1435  controller()->OnAccept();
1436
1437  DetailOutputMap outputs;
1438  const DetailInputs& inputs =
1439      controller()->RequestedFieldsForSection(SECTION_CC_BILLING);
1440  for (size_t i = 0; i < inputs.size(); ++i) {
1441    const DetailInput& input = inputs[i];
1442    outputs[&input] = input.type == ADDRESS_BILLING_LINE1 ?
1443        ASCIIToUTF16(kEditedBillingAddress) : input.initial_value;
1444  }
1445  controller()->GetView()->SetUserInput(SECTION_CC_BILLING, outputs);
1446
1447  EXPECT_CALL(*controller()->GetTestingWalletClient(),
1448              SaveToWalletMock(testing::NotNull(),
1449                               UsesLocalBillingAddress(),
1450                               _)).Times(1);
1451  AcceptAndLoadFakeFingerprint();
1452}
1453
1454TEST_F(AutofillDialogControllerTest, CancelNoSave) {
1455  EXPECT_CALL(*controller()->GetTestingWalletClient(),
1456              SaveToWalletMock(_, _, _)).Times(0);
1457
1458  EXPECT_CALL(*controller()->GetView(), ModelChanged()).Times(1);
1459
1460  controller()->OnDidGetWalletItems(wallet::GetTestWalletItems());
1461  controller()->OnCancel();
1462}
1463
1464// Checks that clicking the Manage menu item opens a new tab with a different
1465// URL for Wallet and Autofill.
1466TEST_F(AutofillDialogControllerTest, ManageItem) {
1467  AutofillProfile full_profile(test::GetVerifiedProfile());
1468  full_profile.set_origin(kSettingsOrigin);
1469  full_profile.SetRawInfo(ADDRESS_HOME_LINE2, string16());
1470  controller()->GetTestingManager()->AddTestingProfile(&full_profile);
1471  SwitchToAutofill();
1472
1473  SuggestionsMenuModel* shipping = static_cast<SuggestionsMenuModel*>(
1474      controller()->MenuModelForSection(SECTION_SHIPPING));
1475  shipping->ExecuteCommand(shipping->GetItemCount() - 1, 0);
1476  GURL autofill_manage_url = controller()->open_tab_url();
1477  EXPECT_EQ("chrome", autofill_manage_url.scheme());
1478
1479  SwitchToWallet();
1480  scoped_ptr<wallet::WalletItems> wallet_items = wallet::GetTestWalletItems();
1481  wallet_items->AddInstrument(wallet::GetTestMaskedInstrument());
1482  controller()->OnDidGetWalletItems(wallet_items.Pass());
1483
1484  controller()->SuggestionItemSelected(shipping, shipping->GetItemCount() - 1);
1485  GURL wallet_manage_addresses_url = controller()->open_tab_url();
1486  EXPECT_EQ("https", wallet_manage_addresses_url.scheme());
1487
1488  SuggestionsMenuModel* billing = static_cast<SuggestionsMenuModel*>(
1489      controller()->MenuModelForSection(SECTION_CC_BILLING));
1490  controller()->SuggestionItemSelected(billing, billing->GetItemCount() - 1);
1491  GURL wallet_manage_instruments_url = controller()->open_tab_url();
1492  EXPECT_EQ("https", wallet_manage_instruments_url.scheme());
1493
1494  EXPECT_NE(autofill_manage_url, wallet_manage_instruments_url);
1495  EXPECT_NE(wallet_manage_instruments_url, wallet_manage_addresses_url);
1496}
1497
1498TEST_F(AutofillDialogControllerTest, EditClicked) {
1499  EXPECT_CALL(*controller()->GetView(), ModelChanged()).Times(1);
1500
1501  AutofillProfile full_profile(test::GetVerifiedProfile());
1502  const string16 kEmail = ASCIIToUTF16("first@johndoe.com");
1503  full_profile.SetRawInfo(EMAIL_ADDRESS, kEmail);
1504  controller()->GetTestingManager()->AddTestingProfile(&full_profile);
1505
1506  ui::MenuModel* email_model =
1507      controller()->MenuModelForSection(SECTION_EMAIL);
1508  EXPECT_EQ(3, email_model->GetItemCount());
1509
1510  // When unedited, the initial_value should be empty.
1511  email_model->ActivatedAt(0);
1512  const DetailInputs& inputs0 =
1513      controller()->RequestedFieldsForSection(SECTION_EMAIL);
1514  EXPECT_EQ(string16(), inputs0[0].initial_value);
1515  EXPECT_EQ(kEmail,
1516            controller()->SuggestionStateForSection(SECTION_EMAIL).
1517                vertically_compact_text);
1518
1519  // When edited, the initial_value should contain the value.
1520  controller()->EditClickedForSection(SECTION_EMAIL);
1521  const DetailInputs& inputs1 =
1522      controller()->RequestedFieldsForSection(SECTION_EMAIL);
1523  EXPECT_EQ(kEmail, inputs1[0].initial_value);
1524  EXPECT_FALSE(controller()->SuggestionStateForSection(SECTION_EMAIL).visible);
1525}
1526
1527// Tests that editing an autofill profile and then submitting works.
1528TEST_F(AutofillDialogControllerTest, EditAutofillProfile) {
1529  SwitchToAutofill();
1530
1531  EXPECT_CALL(*controller()->GetView(), ModelChanged()).Times(2);
1532
1533  AutofillProfile full_profile(test::GetVerifiedProfile());
1534  CreditCard credit_card(test::GetVerifiedCreditCard());
1535  controller()->GetTestingManager()->AddTestingProfile(&full_profile);
1536  controller()->GetTestingManager()->AddTestingCreditCard(&credit_card);
1537  controller()->EditClickedForSection(SECTION_SHIPPING);
1538
1539  DetailOutputMap outputs;
1540  const DetailInputs& inputs =
1541      controller()->RequestedFieldsForSection(SECTION_SHIPPING);
1542  for (size_t i = 0; i < inputs.size(); ++i) {
1543    const DetailInput& input = inputs[i];
1544    outputs[&input] = input.type == NAME_FULL ? ASCIIToUTF16("Edited Name") :
1545                                                input.initial_value;
1546  }
1547  controller()->GetView()->SetUserInput(SECTION_SHIPPING, outputs);
1548
1549  // We also have to simulate CC inputs to keep the controller happy.
1550  FillCreditCardInputs();
1551
1552  controller()->OnAccept();
1553  const AutofillProfile& edited_profile =
1554      controller()->GetTestingManager()->imported_profile();
1555
1556  for (size_t i = 0; i < inputs.size(); ++i) {
1557    const DetailInput& input = inputs[i];
1558    EXPECT_EQ(input.type == NAME_FULL ? ASCIIToUTF16("Edited Name") :
1559                                        input.initial_value,
1560              edited_profile.GetInfo(AutofillType(input.type), "en-US"));
1561  }
1562}
1563
1564// Tests that adding an autofill profile and then submitting works.
1565TEST_F(AutofillDialogControllerTest, AddAutofillProfile) {
1566  SwitchToAutofill();
1567  EXPECT_CALL(*controller()->GetView(), ModelChanged()).Times(2);
1568
1569  AutofillProfile full_profile(test::GetVerifiedProfile());
1570  CreditCard credit_card(test::GetVerifiedCreditCard());
1571  controller()->GetTestingManager()->AddTestingProfile(&full_profile);
1572  controller()->GetTestingManager()->AddTestingCreditCard(&credit_card);
1573
1574  ui::MenuModel* model = controller()->MenuModelForSection(SECTION_BILLING);
1575  // Activate the "Add billing address" menu item.
1576  model->ActivatedAt(model->GetItemCount() - 2);
1577
1578  // Fill in the inputs from the profile.
1579  DetailOutputMap outputs;
1580  const DetailInputs& inputs =
1581      controller()->RequestedFieldsForSection(SECTION_BILLING);
1582  AutofillProfile full_profile2(test::GetVerifiedProfile2());
1583  for (size_t i = 0; i < inputs.size(); ++i) {
1584    const DetailInput& input = inputs[i];
1585    outputs[&input] = full_profile2.GetInfo(AutofillType(input.type), "en-US");
1586  }
1587  controller()->GetView()->SetUserInput(SECTION_BILLING, outputs);
1588
1589  controller()->OnAccept();
1590  const AutofillProfile& added_profile =
1591      controller()->GetTestingManager()->imported_profile();
1592
1593  const DetailInputs& shipping_inputs =
1594      controller()->RequestedFieldsForSection(SECTION_SHIPPING);
1595  for (size_t i = 0; i < shipping_inputs.size(); ++i) {
1596    const DetailInput& input = shipping_inputs[i];
1597    EXPECT_EQ(full_profile2.GetInfo(AutofillType(input.type), "en-US"),
1598              added_profile.GetInfo(AutofillType(input.type), "en-US"));
1599  }
1600
1601  // Also, the currently selected email address should get added to the new
1602  // profile.
1603  string16 original_email =
1604      full_profile.GetInfo(AutofillType(EMAIL_ADDRESS), "en-US");
1605  EXPECT_FALSE(original_email.empty());
1606  EXPECT_EQ(original_email,
1607            added_profile.GetInfo(AutofillType(EMAIL_ADDRESS), "en-US"));
1608}
1609
1610// Makes sure that a newly added email address gets added to an existing profile
1611// (as opposed to creating its own profile). http://crbug.com/240926
1612TEST_F(AutofillDialogControllerTest, AddEmail) {
1613  SwitchToAutofill();
1614  EXPECT_CALL(*controller()->GetView(), ModelChanged()).Times(2);
1615
1616  AutofillProfile full_profile(test::GetVerifiedProfile());
1617  CreditCard credit_card(test::GetVerifiedCreditCard());
1618  controller()->GetTestingManager()->AddTestingProfile(&full_profile);
1619  controller()->GetTestingManager()->AddTestingCreditCard(&credit_card);
1620
1621  ui::MenuModel* model = controller()->MenuModelForSection(SECTION_EMAIL);
1622  ASSERT_TRUE(model);
1623  // Activate the "Add email address" menu item.
1624  model->ActivatedAt(model->GetItemCount() - 2);
1625
1626  // Fill in the inputs from the profile.
1627  DetailOutputMap outputs;
1628  const DetailInputs& inputs =
1629      controller()->RequestedFieldsForSection(SECTION_EMAIL);
1630  const DetailInput& input = inputs[0];
1631  string16 new_email = ASCIIToUTF16("addemailtest@example.com");
1632  outputs[&input] = new_email;
1633  controller()->GetView()->SetUserInput(SECTION_EMAIL, outputs);
1634
1635  FillCreditCardInputs();
1636  controller()->OnAccept();
1637  std::vector<base::string16> email_values;
1638  full_profile.GetMultiInfo(
1639      AutofillType(EMAIL_ADDRESS), "en-US", &email_values);
1640  ASSERT_EQ(2U, email_values.size());
1641  EXPECT_EQ(new_email, email_values[1]);
1642}
1643
1644TEST_F(AutofillDialogControllerTest, VerifyCvv) {
1645  EXPECT_CALL(*controller()->GetTestingWalletClient(),
1646              GetFullWallet(_)).Times(1);
1647  EXPECT_CALL(*controller()->GetTestingWalletClient(),
1648              AuthenticateInstrument(_, _)).Times(1);
1649
1650  SubmitWithWalletItems(CompleteAndValidWalletItems());
1651
1652  EXPECT_TRUE(NotificationsOfType(DialogNotification::REQUIRED_ACTION).empty());
1653  EXPECT_TRUE(controller()->SectionIsActive(SECTION_SHIPPING));
1654  EXPECT_TRUE(controller()->SectionIsActive(SECTION_CC_BILLING));
1655  EXPECT_FALSE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_OK));
1656  EXPECT_FALSE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_CANCEL));
1657
1658  SuggestionState suggestion_state =
1659      controller()->SuggestionStateForSection(SECTION_CC_BILLING);
1660  EXPECT_TRUE(suggestion_state.extra_text.empty());
1661
1662  controller()->OnDidGetFullWallet(CreateFullWallet("verify_cvv"));
1663
1664  EXPECT_FALSE(
1665      NotificationsOfType(DialogNotification::REQUIRED_ACTION).empty());
1666  EXPECT_FALSE(controller()->SectionIsActive(SECTION_SHIPPING));
1667  EXPECT_TRUE(controller()->SectionIsActive(SECTION_CC_BILLING));
1668
1669  suggestion_state =
1670      controller()->SuggestionStateForSection(SECTION_CC_BILLING);
1671  EXPECT_FALSE(suggestion_state.extra_text.empty());
1672  EXPECT_FALSE(controller()->MenuModelForSection(SECTION_CC_BILLING));
1673
1674  EXPECT_TRUE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_OK));
1675  EXPECT_TRUE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_CANCEL));
1676
1677  controller()->OnAccept();
1678}
1679
1680TEST_F(AutofillDialogControllerTest, ErrorDuringSubmit) {
1681  EXPECT_CALL(*controller()->GetTestingWalletClient(),
1682              GetFullWallet(_)).Times(1);
1683
1684  SubmitWithWalletItems(CompleteAndValidWalletItems());
1685
1686  EXPECT_FALSE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_OK));
1687  EXPECT_FALSE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_CANCEL));
1688
1689  controller()->OnWalletError(wallet::WalletClient::UNKNOWN_ERROR);
1690
1691  EXPECT_TRUE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_OK));
1692  EXPECT_TRUE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_CANCEL));
1693}
1694
1695// TODO(dbeam): disallow changing accounts instead and remove this test.
1696TEST_F(AutofillDialogControllerTest, ChangeAccountDuringSubmit) {
1697  EXPECT_CALL(*controller()->GetTestingWalletClient(),
1698              GetFullWallet(_)).Times(1);
1699
1700  SubmitWithWalletItems(CompleteAndValidWalletItems());
1701
1702  EXPECT_FALSE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_OK));
1703  EXPECT_FALSE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_CANCEL));
1704
1705  SwitchToWallet();
1706  SwitchToAutofill();
1707
1708  EXPECT_TRUE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_OK));
1709  EXPECT_TRUE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_CANCEL));
1710}
1711
1712TEST_F(AutofillDialogControllerTest, ErrorDuringVerifyCvv) {
1713  EXPECT_CALL(*controller()->GetTestingWalletClient(),
1714              GetFullWallet(_)).Times(1);
1715
1716  SubmitWithWalletItems(CompleteAndValidWalletItems());
1717  controller()->OnDidGetFullWallet(CreateFullWallet("verify_cvv"));
1718
1719  ASSERT_TRUE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_OK));
1720  ASSERT_TRUE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_CANCEL));
1721
1722  controller()->OnWalletError(wallet::WalletClient::UNKNOWN_ERROR);
1723
1724  EXPECT_TRUE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_OK));
1725  EXPECT_TRUE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_CANCEL));
1726}
1727
1728// TODO(dbeam): disallow changing accounts instead and remove this test.
1729TEST_F(AutofillDialogControllerTest, ChangeAccountDuringVerifyCvv) {
1730  EXPECT_CALL(*controller()->GetTestingWalletClient(),
1731              GetFullWallet(_)).Times(1);
1732
1733  SubmitWithWalletItems(CompleteAndValidWalletItems());
1734  controller()->OnDidGetFullWallet(CreateFullWallet("verify_cvv"));
1735
1736  ASSERT_TRUE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_OK));
1737  ASSERT_TRUE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_CANCEL));
1738
1739  SwitchToWallet();
1740  SwitchToAutofill();
1741
1742  EXPECT_TRUE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_OK));
1743  EXPECT_TRUE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_CANCEL));
1744}
1745
1746// Simulates receiving an INVALID_FORM_FIELD required action while processing a
1747// |WalletClientDelegate::OnDid{Save,Update}*()| call. This can happen if Online
1748// Wallet's server validation differs from Chrome's local validation.
1749TEST_F(AutofillDialogControllerTest, WalletServerSideValidation) {
1750  scoped_ptr<wallet::WalletItems> wallet_items = wallet::GetTestWalletItems();
1751  wallet_items->AddInstrument(wallet::GetTestMaskedInstrument());
1752  controller()->OnDidGetWalletItems(wallet_items.Pass());
1753  controller()->OnAccept();
1754
1755  std::vector<wallet::RequiredAction> required_actions;
1756  required_actions.push_back(wallet::INVALID_FORM_FIELD);
1757
1758  std::vector<wallet::FormFieldError> form_errors;
1759  form_errors.push_back(
1760      wallet::FormFieldError(wallet::FormFieldError::INVALID_POSTAL_CODE,
1761                             wallet::FormFieldError::SHIPPING_ADDRESS));
1762
1763  EXPECT_CALL(*controller()->GetView(), UpdateForErrors()).Times(1);
1764  controller()->OnDidSaveToWallet(std::string(),
1765                                  std::string(),
1766                                  required_actions,
1767                                  form_errors);
1768}
1769
1770// Simulates receiving unrecoverable Wallet server validation errors.
1771TEST_F(AutofillDialogControllerTest, WalletServerSideValidationUnrecoverable) {
1772  scoped_ptr<wallet::WalletItems> wallet_items = wallet::GetTestWalletItems();
1773  wallet_items->AddInstrument(wallet::GetTestMaskedInstrument());
1774  controller()->OnDidGetWalletItems(wallet_items.Pass());
1775  controller()->OnAccept();
1776
1777  std::vector<wallet::RequiredAction> required_actions;
1778  required_actions.push_back(wallet::INVALID_FORM_FIELD);
1779
1780  std::vector<wallet::FormFieldError> form_errors;
1781  form_errors.push_back(
1782      wallet::FormFieldError(wallet::FormFieldError::UNKNOWN_ERROR,
1783                             wallet::FormFieldError::UNKNOWN_LOCATION));
1784
1785  controller()->OnDidSaveToWallet(std::string(),
1786                                  std::string(),
1787                                  required_actions,
1788                                  form_errors);
1789
1790  EXPECT_EQ(1U, NotificationsOfType(
1791      DialogNotification::REQUIRED_ACTION).size());
1792}
1793
1794// Test Wallet banners are show in the right situations. These banners explain
1795// where Chrome got the user's data (i.e. "Got details from Wallet") or promote
1796// saving details into Wallet (i.e. "[x] Save details to Wallet").
1797TEST_F(AutofillDialogControllerTest, WalletBanners) {
1798  CommandLine* command_line = CommandLine::ForCurrentProcess();
1799  command_line->AppendSwitch(switches::kWalletServiceUseProd);
1800  PrefService* prefs = profile()->GetPrefs();
1801
1802  // Simulate first run.
1803  prefs->SetBoolean(::prefs::kAutofillDialogHasPaidWithWallet, false);
1804  SetUpControllerWithFormData(DefaultFormData());
1805
1806  EXPECT_EQ(0U, NotificationsOfType(
1807      DialogNotification::EXPLANATORY_MESSAGE).size());
1808  EXPECT_EQ(0U, NotificationsOfType(
1809      DialogNotification::WALLET_USAGE_CONFIRMATION).size());
1810
1811  // Sign in a user with a completed account.
1812  controller()->OnDidGetWalletItems(CompleteAndValidWalletItems());
1813
1814  // Full account; should show "Details from Wallet" message.
1815  EXPECT_EQ(1U, NotificationsOfType(
1816      DialogNotification::EXPLANATORY_MESSAGE).size());
1817  EXPECT_EQ(0U, NotificationsOfType(
1818      DialogNotification::WALLET_USAGE_CONFIRMATION).size());
1819
1820  // Full account; no "[x] Save details in Wallet" option should show.
1821  SwitchToAutofill();
1822  EXPECT_EQ(0U, NotificationsOfType(
1823      DialogNotification::EXPLANATORY_MESSAGE).size());
1824  EXPECT_EQ(0U, NotificationsOfType(
1825      DialogNotification::WALLET_USAGE_CONFIRMATION).size());
1826
1827  SetUpControllerWithFormData(DefaultFormData());
1828  // |controller()| has already been initialized. Test that should not take
1829  // effect until the next call of |SetUpControllerWithFormData()|.
1830  prefs->SetBoolean(::prefs::kAutofillDialogHasPaidWithWallet, true);
1831
1832  // Sign in a user with a incomplete account.
1833  scoped_ptr<wallet::WalletItems> wallet_items = wallet::GetTestWalletItems();
1834  wallet_items->AddInstrument(wallet::GetTestMaskedInstrument());
1835  controller()->OnDidGetWalletItems(wallet_items.Pass());
1836
1837  // Partial account; no "Details from Wallet" message should show, but a
1838  // "[x] Save details in Wallet" should.
1839  EXPECT_EQ(0U, NotificationsOfType(
1840      DialogNotification::EXPLANATORY_MESSAGE).size());
1841  EXPECT_EQ(1U, NotificationsOfType(
1842      DialogNotification::WALLET_USAGE_CONFIRMATION).size());
1843
1844  // Once the usage confirmation banner is shown once, it keeps showing even if
1845  // the user switches to Autofill data.
1846  SwitchToAutofill();
1847  EXPECT_EQ(0U, NotificationsOfType(
1848      DialogNotification::EXPLANATORY_MESSAGE).size());
1849  EXPECT_EQ(1U, NotificationsOfType(
1850      DialogNotification::WALLET_USAGE_CONFIRMATION).size());
1851
1852  // A Wallet error should kill any Wallet promos.
1853  controller()->OnWalletError(wallet::WalletClient::UNKNOWN_ERROR);
1854
1855  EXPECT_EQ(1U, NotificationsOfType(
1856      DialogNotification::WALLET_ERROR).size());
1857  EXPECT_EQ(0U, NotificationsOfType(
1858      DialogNotification::EXPLANATORY_MESSAGE).size());
1859  EXPECT_EQ(0U, NotificationsOfType(
1860      DialogNotification::WALLET_USAGE_CONFIRMATION).size());
1861
1862  SetUpControllerWithFormData(DefaultFormData());
1863  // |controller()| is error free and thinks the user has already paid w/Wallet.
1864
1865  // User has already paid with wallet. Don't show promos.
1866  EXPECT_EQ(0U, NotificationsOfType(
1867      DialogNotification::EXPLANATORY_MESSAGE).size());
1868  EXPECT_EQ(0U, NotificationsOfType(
1869      DialogNotification::WALLET_USAGE_CONFIRMATION).size());
1870
1871  controller()->OnDidGetWalletItems(CompleteAndValidWalletItems());
1872
1873  EXPECT_EQ(0U, NotificationsOfType(
1874      DialogNotification::EXPLANATORY_MESSAGE).size());
1875  EXPECT_EQ(0U, NotificationsOfType(
1876      DialogNotification::WALLET_USAGE_CONFIRMATION).size());
1877
1878  wallet_items = wallet::GetTestWalletItems();
1879  wallet_items->AddInstrument(wallet::GetTestMaskedInstrument());
1880  controller()->OnDidGetWalletItems(wallet_items.Pass());
1881
1882  SwitchToAutofill();
1883  EXPECT_EQ(0U, NotificationsOfType(
1884      DialogNotification::EXPLANATORY_MESSAGE).size());
1885  EXPECT_EQ(0U, NotificationsOfType(
1886      DialogNotification::WALLET_USAGE_CONFIRMATION).size());
1887}
1888
1889TEST_F(AutofillDialogControllerTest, OnAutocheckoutError) {
1890  SwitchToAutofill();
1891  controller()->set_dialog_type(DIALOG_TYPE_AUTOCHECKOUT);
1892
1893  // We also have to simulate CC inputs to keep the controller happy.
1894  FillCreditCardInputs();
1895
1896  controller()->OnAccept();
1897  EXPECT_TRUE(ReadSetVisuallyDeemphasizedIpc());
1898  controller()->OnAutocheckoutError();
1899
1900  EXPECT_FALSE(controller()->GetDialogButtons() & ui::DIALOG_BUTTON_CANCEL);
1901  EXPECT_TRUE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_OK));
1902  EXPECT_EQ(0U, NotificationsOfType(
1903      DialogNotification::AUTOCHECKOUT_SUCCESS).size());
1904  EXPECT_EQ(1U, NotificationsOfType(
1905      DialogNotification::AUTOCHECKOUT_ERROR).size());
1906
1907  controller()->ViewClosed();
1908  EXPECT_FALSE(ReadSetVisuallyDeemphasizedIpc());
1909}
1910
1911TEST_F(AutofillDialogControllerTest, OnAutocheckoutSuccess) {
1912  CommandLine* command_line = CommandLine::ForCurrentProcess();
1913  command_line->AppendSwitch(switches::kWalletServiceUseProd);
1914  controller()->set_dialog_type(DIALOG_TYPE_AUTOCHECKOUT);
1915
1916  // Simulate first run.
1917  profile()->GetPrefs()->SetBoolean(::prefs::kAutofillDialogHasPaidWithWallet,
1918                                    false);
1919  SetUpControllerWithFormData(DefaultFormData());
1920  controller()->set_dialog_type(DIALOG_TYPE_AUTOCHECKOUT);
1921
1922  // Sign in a user with a completed account.
1923  controller()->OnDidGetWalletItems(CompleteAndValidWalletItems());
1924
1925  // Full account; should show "Details from Wallet" message.
1926  EXPECT_EQ(1U, NotificationsOfType(
1927      DialogNotification::EXPLANATORY_MESSAGE).size());
1928  EXPECT_EQ(0U, NotificationsOfType(
1929      DialogNotification::WALLET_USAGE_CONFIRMATION).size());
1930
1931  AcceptAndLoadFakeFingerprint();
1932  EXPECT_TRUE(ReadSetVisuallyDeemphasizedIpc());
1933  controller()->OnDidGetFullWallet(wallet::GetTestFullWallet());
1934  EXPECT_TRUE(controller()->GetDialogOverlay().image.IsEmpty());
1935
1936  EXPECT_EQ(0U, NotificationsOfType(
1937      DialogNotification::EXPLANATORY_MESSAGE).size());
1938
1939  controller()->OnAutocheckoutSuccess();
1940  EXPECT_TRUE(controller()->GetDialogOverlay().image.IsEmpty());
1941
1942  EXPECT_FALSE(controller()->GetDialogButtons() & ui::DIALOG_BUTTON_CANCEL);
1943  EXPECT_TRUE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_OK));
1944  EXPECT_EQ(1U, NotificationsOfType(
1945      DialogNotification::AUTOCHECKOUT_SUCCESS).size());
1946  EXPECT_EQ(0U, NotificationsOfType(
1947      DialogNotification::AUTOCHECKOUT_ERROR).size());
1948  EXPECT_EQ(0U, NotificationsOfType(
1949      DialogNotification::EXPLANATORY_MESSAGE).size());
1950  EXPECT_TRUE(profile()->GetPrefs()->GetBoolean(
1951      ::prefs::kAutofillDialogHasPaidWithWallet));
1952
1953  controller()->ViewClosed();
1954  EXPECT_FALSE(ReadSetVisuallyDeemphasizedIpc());
1955}
1956
1957TEST_F(AutofillDialogControllerTest, ViewCancelDoesntSetPref) {
1958  ASSERT_FALSE(profile()->GetPrefs()->HasPrefPath(
1959      ::prefs::kAutofillDialogPayWithoutWallet));
1960
1961  SwitchToAutofill();
1962
1963  controller()->OnCancel();
1964  controller()->ViewClosed();
1965
1966  EXPECT_FALSE(profile()->GetPrefs()->HasPrefPath(
1967      ::prefs::kAutofillDialogPayWithoutWallet));
1968}
1969
1970TEST_F(AutofillDialogControllerTest, SubmitWithSigninErrorDoesntSetPref) {
1971  ASSERT_FALSE(profile()->GetPrefs()->HasPrefPath(
1972      ::prefs::kAutofillDialogPayWithoutWallet));
1973
1974  SimulateSigninError();
1975  FillCreditCardInputs();
1976  controller()->OnAccept();
1977
1978  EXPECT_FALSE(profile()->GetPrefs()->HasPrefPath(
1979      ::prefs::kAutofillDialogPayWithoutWallet));
1980}
1981
1982// Tests that there's an overlay shown while waiting for full wallet items,
1983// and on first run an additional expository wallet overlay shown after full
1984// wallet items are returned.
1985// TODO(estade): enable on other platforms when overlays are supported there.
1986#if defined(TOOLKIT_VIEWS)
1987TEST_F(AutofillDialogControllerTest, WalletFirstRun) {
1988  // Simulate first run.
1989  PrefService* prefs = profile()->GetPrefs();
1990  prefs->SetBoolean(::prefs::kAutofillDialogHasPaidWithWallet, false);
1991  SetUpControllerWithFormData(DefaultFormData());
1992
1993  SwitchToWallet();
1994  EXPECT_TRUE(controller()->GetDialogOverlay().image.IsEmpty());
1995
1996  SubmitWithWalletItems(CompleteAndValidWalletItems());
1997  EXPECT_FALSE(controller()->GetDialogOverlay().image.IsEmpty());
1998
1999  EXPECT_FALSE(prefs->GetBoolean(::prefs::kAutofillDialogHasPaidWithWallet));
2000  controller()->OnDidGetFullWallet(wallet::GetTestFullWallet());
2001  EXPECT_FALSE(prefs->GetBoolean(::prefs::kAutofillDialogHasPaidWithWallet));
2002  EXPECT_FALSE(controller()->GetDialogOverlay().image.IsEmpty());
2003  EXPECT_FALSE(form_structure());
2004
2005  controller()->OverlayButtonPressed();
2006  EXPECT_TRUE(prefs->GetBoolean(::prefs::kAutofillDialogHasPaidWithWallet));
2007  EXPECT_TRUE(form_structure());
2008}
2009#endif
2010
2011// On second run, the second overlay doesn't show.
2012TEST_F(AutofillDialogControllerTest, WalletSecondRun) {
2013  SwitchToWallet();
2014  EXPECT_TRUE(controller()->GetDialogOverlay().image.IsEmpty());
2015
2016  SubmitWithWalletItems(CompleteAndValidWalletItems());
2017  EXPECT_FALSE(controller()->GetDialogOverlay().image.IsEmpty());
2018
2019  EXPECT_TRUE(profile()->GetPrefs()->GetBoolean(
2020      ::prefs::kAutofillDialogHasPaidWithWallet));
2021  controller()->OnDidGetFullWallet(wallet::GetTestFullWallet());
2022  EXPECT_TRUE(profile()->GetPrefs()->GetBoolean(
2023      ::prefs::kAutofillDialogHasPaidWithWallet));
2024  EXPECT_TRUE(form_structure());
2025}
2026
2027TEST_F(AutofillDialogControllerTest, ViewSubmitSetsPref) {
2028  ASSERT_FALSE(profile()->GetPrefs()->HasPrefPath(
2029      ::prefs::kAutofillDialogPayWithoutWallet));
2030
2031  SwitchToAutofill();
2032  FillCreditCardInputs();
2033  controller()->OnAccept();
2034
2035  EXPECT_TRUE(profile()->GetPrefs()->HasPrefPath(
2036      ::prefs::kAutofillDialogPayWithoutWallet));
2037  EXPECT_TRUE(profile()->GetPrefs()->GetBoolean(
2038      ::prefs::kAutofillDialogPayWithoutWallet));
2039
2040  // Try again with a signin error (just leaves the pref alone).
2041  SetUpControllerWithFormData(DefaultFormData());
2042
2043  // Setting up the controller again should not change the pref.
2044  EXPECT_TRUE(profile()->GetPrefs()->HasPrefPath(
2045      ::prefs::kAutofillDialogPayWithoutWallet));
2046  EXPECT_TRUE(profile()->GetPrefs()->GetBoolean(
2047      ::prefs::kAutofillDialogPayWithoutWallet));
2048
2049  SimulateSigninError();
2050  FillCreditCardInputs();
2051  controller()->OnAccept();
2052  EXPECT_TRUE(profile()->GetPrefs()->HasPrefPath(
2053      ::prefs::kAutofillDialogPayWithoutWallet));
2054  EXPECT_TRUE(profile()->GetPrefs()->GetBoolean(
2055      ::prefs::kAutofillDialogPayWithoutWallet));
2056
2057  // Succesfully choosing wallet does set the pref.
2058  SetUpControllerWithFormData(DefaultFormData());
2059
2060  SwitchToWallet();
2061  scoped_ptr<wallet::WalletItems> wallet_items = wallet::GetTestWalletItems();
2062  wallet_items->AddInstrument(wallet::GetTestMaskedInstrument());
2063  controller()->OnDidGetWalletItems(wallet_items.Pass());
2064  controller()->OnAccept();
2065  controller()->OnDidGetFullWallet(wallet::GetTestFullWallet());
2066
2067  EXPECT_TRUE(profile()->GetPrefs()->HasPrefPath(
2068      ::prefs::kAutofillDialogPayWithoutWallet));
2069  EXPECT_FALSE(profile()->GetPrefs()->GetBoolean(
2070      ::prefs::kAutofillDialogPayWithoutWallet));
2071}
2072
2073TEST_F(AutofillDialogControllerTest, HideWalletEmail) {
2074  SwitchToAutofill();
2075
2076  // Email section should be showing when using Autofill.
2077  EXPECT_TRUE(controller()->SectionIsActive(SECTION_EMAIL));
2078
2079  SwitchToWallet();
2080
2081  // Setup some wallet state, submit, and get a full wallet to end the flow.
2082  scoped_ptr<wallet::WalletItems> wallet_items = CompleteAndValidWalletItems();
2083
2084  // Filling |form_structure()| depends on the current username and wallet items
2085  // being fetched. Until both of these have occurred, the user should not be
2086  // able to click Submit if using Wallet. The username fetch happened earlier.
2087  EXPECT_FALSE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_OK));
2088  controller()->OnDidGetWalletItems(wallet_items.Pass());
2089  EXPECT_TRUE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_OK));
2090
2091  // Email section should be hidden when using Wallet.
2092  EXPECT_FALSE(controller()->SectionIsActive(SECTION_EMAIL));
2093
2094  controller()->OnAccept();
2095  controller()->OnDidGetFullWallet(wallet::GetTestFullWallet());
2096
2097  size_t i = 0;
2098  for (; i < form_structure()->field_count(); ++i) {
2099    if (form_structure()->field(i)->Type().GetStorableType() == EMAIL_ADDRESS) {
2100      EXPECT_EQ(ASCIIToUTF16(kFakeEmail), form_structure()->field(i)->value);
2101      break;
2102    }
2103  }
2104  ASSERT_LT(i, form_structure()->field_count());
2105}
2106
2107// Test if autofill types of returned form structure are correct for billing
2108// entries.
2109TEST_F(AutofillDialogControllerTest, AutofillTypes) {
2110  controller()->OnDidGetWalletItems(CompleteAndValidWalletItems());
2111  controller()->OnAccept();
2112  controller()->OnDidGetFullWallet(wallet::GetTestFullWallet());
2113  ASSERT_EQ(20U, form_structure()->field_count());
2114  EXPECT_EQ(EMAIL_ADDRESS,
2115            form_structure()->field(0)->Type().GetStorableType());
2116  EXPECT_EQ(CREDIT_CARD_NUMBER,
2117            form_structure()->field(2)->Type().GetStorableType());
2118  EXPECT_EQ(ADDRESS_HOME_STATE,
2119            form_structure()->field(9)->Type().GetStorableType());
2120  EXPECT_EQ(ADDRESS_BILLING, form_structure()->field(9)->Type().group());
2121  EXPECT_EQ(ADDRESS_HOME_STATE,
2122            form_structure()->field(16)->Type().GetStorableType());
2123  EXPECT_EQ(ADDRESS_HOME, form_structure()->field(16)->Type().group());
2124}
2125
2126TEST_F(AutofillDialogControllerTest, SaveDetailsInChrome) {
2127  SwitchToAutofill();
2128  EXPECT_CALL(*controller()->GetView(), ModelChanged()).Times(2);
2129
2130  AutofillProfile full_profile(test::GetVerifiedProfile());
2131  controller()->GetTestingManager()->AddTestingProfile(&full_profile);
2132
2133  CreditCard card(test::GetVerifiedCreditCard());
2134  controller()->GetTestingManager()->AddTestingCreditCard(&card);
2135  EXPECT_FALSE(controller()->ShouldOfferToSaveInChrome());
2136
2137  controller()->EditClickedForSection(SECTION_EMAIL);
2138  EXPECT_TRUE(controller()->ShouldOfferToSaveInChrome());
2139
2140  controller()->MenuModelForSection(SECTION_EMAIL)->ActivatedAt(0);
2141  EXPECT_FALSE(controller()->ShouldOfferToSaveInChrome());
2142
2143  controller()->MenuModelForSection(SECTION_EMAIL)->ActivatedAt(1);
2144  EXPECT_TRUE(controller()->ShouldOfferToSaveInChrome());
2145
2146  profile()->ForceIncognito(true);
2147  EXPECT_FALSE(controller()->ShouldOfferToSaveInChrome());
2148}
2149
2150// Tests that user is prompted when using instrument with minimal address.
2151TEST_F(AutofillDialogControllerTest, UpgradeMinimalAddress) {
2152  // A minimal address being selected should trigger error validation in the
2153  // view. Called once for each incomplete suggestion.
2154  EXPECT_CALL(*controller()->GetView(), UpdateForErrors()).Times(1);
2155
2156  scoped_ptr<wallet::WalletItems> wallet_items = wallet::GetTestWalletItems();
2157  wallet_items->AddInstrument(wallet::GetTestMaskedInstrumentWithIdAndAddress(
2158      "id", wallet::GetTestMinimalAddress()));
2159  scoped_ptr<wallet::Address> address(wallet::GetTestShippingAddress());
2160  address->set_is_complete_address(false);
2161  wallet_items->AddAddress(address.Pass());
2162  controller()->OnDidGetWalletItems(wallet_items.Pass());
2163
2164  // Assert that dialog's SECTION_CC_BILLING section is in edit mode.
2165  ASSERT_TRUE(controller()->IsEditingExistingData(SECTION_CC_BILLING));
2166  // Shipping section should be in edit mode because of
2167  // is_minimal_shipping_address.
2168  ASSERT_TRUE(controller()->IsEditingExistingData(SECTION_SHIPPING));
2169}
2170
2171TEST_F(AutofillDialogControllerTest, RiskNeverLoadsWithPendingLegalDocuments) {
2172  EXPECT_CALL(*controller(), LoadRiskFingerprintData()).Times(0);
2173
2174  scoped_ptr<wallet::WalletItems> wallet_items = wallet::GetTestWalletItems();
2175  wallet_items->AddLegalDocument(wallet::GetTestLegalDocument());
2176  controller()->OnDidGetWalletItems(wallet_items.Pass());
2177  controller()->OnAccept();
2178}
2179
2180TEST_F(AutofillDialogControllerTest, RiskLoadsAfterAcceptingLegalDocuments) {
2181  EXPECT_CALL(*controller(), LoadRiskFingerprintData()).Times(0);
2182
2183  scoped_ptr<wallet::WalletItems> wallet_items = wallet::GetTestWalletItems();
2184  wallet_items->AddLegalDocument(wallet::GetTestLegalDocument());
2185  controller()->OnDidGetWalletItems(wallet_items.Pass());
2186
2187  testing::Mock::VerifyAndClear(controller());
2188  EXPECT_CALL(*controller(), LoadRiskFingerprintData()).Times(1);
2189
2190  controller()->OnAccept();
2191
2192  // Simulate a risk load and verify |GetRiskData()| matches the encoded value.
2193  controller()->OnDidAcceptLegalDocuments();
2194  controller()->OnDidLoadRiskFingerprintData(GetFakeFingerprint().Pass());
2195  EXPECT_EQ(kFakeFingerprintEncoded, controller()->GetRiskData());
2196}
2197
2198TEST_F(AutofillDialogControllerTest, NoManageMenuItemForNewWalletUsers) {
2199  // Make sure the menu model item is created for a returning Wallet user.
2200  scoped_ptr<wallet::WalletItems> wallet_items = wallet::GetTestWalletItems();
2201  wallet_items->AddInstrument(wallet::GetTestMaskedInstrument());
2202  wallet_items->AddAddress(wallet::GetTestShippingAddress());
2203  controller()->OnDidGetWalletItems(wallet_items.Pass());
2204
2205  EXPECT_TRUE(controller()->MenuModelForSection(SECTION_CC_BILLING));
2206  // "Same as billing", "123 address", "Add address...", and "Manage addresses".
2207  EXPECT_EQ(
2208      4, controller()->MenuModelForSection(SECTION_SHIPPING)->GetItemCount());
2209
2210  // Make sure the menu model item is not created for new Wallet users.
2211  base::DictionaryValue dict;
2212  scoped_ptr<base::ListValue> required_actions(new base::ListValue);
2213  required_actions->AppendString("setup_wallet");
2214  dict.Set("required_action", required_actions.release());
2215  controller()->OnDidGetWalletItems(
2216      wallet::WalletItems::CreateWalletItems(dict).Pass());
2217
2218  EXPECT_FALSE(controller()->MenuModelForSection(SECTION_CC_BILLING));
2219  // "Same as billing" and "Add address...".
2220  EXPECT_EQ(
2221      2, controller()->MenuModelForSection(SECTION_SHIPPING)->GetItemCount());
2222}
2223
2224TEST_F(AutofillDialogControllerTest, ShippingSectionCanBeHidden) {
2225  SwitchToAutofill();
2226
2227  FormFieldData email_field;
2228  email_field.autocomplete_attribute = "email";
2229  FormFieldData cc_field;
2230  cc_field.autocomplete_attribute = "cc-number";
2231  FormFieldData billing_field;
2232  billing_field.autocomplete_attribute = "billing region";
2233
2234  FormData form_data;
2235  form_data.fields.push_back(email_field);
2236  form_data.fields.push_back(cc_field);
2237  form_data.fields.push_back(billing_field);
2238
2239  AutofillProfile full_profile(test::GetVerifiedProfile());
2240  controller()->GetTestingManager()->AddTestingProfile(&full_profile);
2241  SetUpControllerWithFormData(form_data);
2242  EXPECT_FALSE(controller()->SectionIsActive(SECTION_SHIPPING));
2243
2244  FillCreditCardInputs();
2245  controller()->OnAccept();
2246  EXPECT_TRUE(form_structure());
2247}
2248
2249TEST_F(AutofillDialogControllerTest, ShippingSectionCanBeHiddenForWallet) {
2250  SwitchToWallet();
2251
2252  FormFieldData email_field;
2253  email_field.autocomplete_attribute = "email";
2254  FormFieldData cc_field;
2255  cc_field.autocomplete_attribute = "cc-number";
2256  FormFieldData billing_field;
2257  billing_field.autocomplete_attribute = "billing region";
2258
2259  FormData form_data;
2260  form_data.fields.push_back(email_field);
2261  form_data.fields.push_back(cc_field);
2262  form_data.fields.push_back(billing_field);
2263
2264  SetUpControllerWithFormData(form_data);
2265  EXPECT_FALSE(controller()->SectionIsActive(SECTION_SHIPPING));
2266  EXPECT_FALSE(controller()->IsShippingAddressRequired());
2267
2268  EXPECT_CALL(*controller()->GetTestingWalletClient(),
2269              GetFullWallet(_)).Times(1);
2270  scoped_ptr<wallet::WalletItems> wallet_items = wallet::GetTestWalletItems();
2271  wallet_items->AddInstrument(wallet::GetTestMaskedInstrument());
2272  SubmitWithWalletItems(wallet_items.Pass());
2273  controller()->OnDidGetFullWallet(wallet::GetTestFullWalletInstrumentOnly());
2274  EXPECT_TRUE(form_structure());
2275}
2276
2277TEST_F(AutofillDialogControllerTest, NotProdNotification) {
2278  // To make IsPayingWithWallet() true.
2279  controller()->OnDidGetWalletItems(wallet::GetTestWalletItems());
2280
2281  CommandLine* command_line = CommandLine::ForCurrentProcess();
2282  ASSERT_FALSE(command_line->HasSwitch(switches::kWalletServiceUseProd));
2283  EXPECT_FALSE(
2284      NotificationsOfType(DialogNotification::DEVELOPER_WARNING).empty());
2285
2286  command_line->AppendSwitch(switches::kWalletServiceUseProd);
2287  EXPECT_TRUE(
2288      NotificationsOfType(DialogNotification::DEVELOPER_WARNING).empty());
2289}
2290
2291// Ensure Wallet instruments marked expired by the server are shown as invalid.
2292TEST_F(AutofillDialogControllerTest, WalletExpiredCard) {
2293  scoped_ptr<wallet::WalletItems> wallet_items = wallet::GetTestWalletItems();
2294  wallet_items->AddInstrument(wallet::GetTestMaskedInstrumentExpired());
2295  controller()->OnDidGetWalletItems(wallet_items.Pass());
2296
2297  EXPECT_TRUE(controller()->IsEditingExistingData(SECTION_CC_BILLING));
2298
2299  // Use |SetOutputValue()| to put the right ServerFieldTypes into the map.
2300  const DetailInputs& inputs =
2301      controller()->RequestedFieldsForSection(SECTION_CC_BILLING);
2302  DetailOutputMap outputs;
2303  SetOutputValue(inputs, &outputs, COMPANY_NAME, ASCIIToUTF16("Bluth Company"));
2304
2305  ValidityData validity_data =
2306      controller()->InputsAreValid(SECTION_CC_BILLING, outputs, VALIDATE_EDIT);
2307  EXPECT_EQ(1U, validity_data.count(CREDIT_CARD_EXP_MONTH));
2308  EXPECT_EQ(1U, validity_data.count(CREDIT_CARD_EXP_4_DIGIT_YEAR));
2309
2310  // Make the local input year differ from the instrument.
2311  SetOutputValue(inputs, &outputs, CREDIT_CARD_EXP_4_DIGIT_YEAR,
2312                 ASCIIToUTF16("3002"));
2313
2314  validity_data =
2315      controller()->InputsAreValid(SECTION_CC_BILLING, outputs, VALIDATE_EDIT);
2316  EXPECT_EQ(0U, validity_data.count(CREDIT_CARD_EXP_MONTH));
2317  EXPECT_EQ(0U, validity_data.count(CREDIT_CARD_EXP_4_DIGIT_YEAR));
2318
2319  // Make the local input month differ from the instrument.
2320  SetOutputValue(inputs, &outputs, CREDIT_CARD_EXP_MONTH, ASCIIToUTF16("06"));
2321
2322  validity_data =
2323      controller()->InputsAreValid(SECTION_CC_BILLING, outputs, VALIDATE_EDIT);
2324  EXPECT_EQ(0U, validity_data.count(CREDIT_CARD_EXP_MONTH));
2325  EXPECT_EQ(0U, validity_data.count(CREDIT_CARD_EXP_4_DIGIT_YEAR));
2326}
2327
2328TEST_F(AutofillDialogControllerTest, ChooseAnotherInstrumentOrAddress) {
2329  SubmitWithWalletItems(CompleteAndValidWalletItems());
2330
2331  EXPECT_EQ(0U, NotificationsOfType(
2332      DialogNotification::REQUIRED_ACTION).size());
2333  EXPECT_CALL(*controller()->GetTestingWalletClient(),
2334              GetWalletItems(_)).Times(1);
2335  controller()->OnDidGetFullWallet(
2336      CreateFullWallet("choose_another_instrument_or_address"));
2337  EXPECT_EQ(1U, NotificationsOfType(
2338      DialogNotification::REQUIRED_ACTION).size());
2339  controller()->OnDidGetWalletItems(CompleteAndValidWalletItems());
2340
2341  controller()->OnAccept();
2342  EXPECT_EQ(0U, NotificationsOfType(
2343      DialogNotification::REQUIRED_ACTION).size());
2344}
2345
2346// Make sure detailed steps for Autocheckout are added
2347// and updated correctly.
2348TEST_F(AutofillDialogControllerTest, DetailedSteps) {
2349  EXPECT_CALL(*controller()->GetTestingWalletClient(),
2350              GetFullWallet(_)).Times(1);
2351
2352  controller()->set_dialog_type(DIALOG_TYPE_AUTOCHECKOUT);
2353
2354  // Add steps as would normally be done by the AutocheckoutManager.
2355  controller()->AddAutocheckoutStep(AUTOCHECKOUT_STEP_SHIPPING);
2356  controller()->AddAutocheckoutStep(AUTOCHECKOUT_STEP_DELIVERY);
2357  controller()->AddAutocheckoutStep(AUTOCHECKOUT_STEP_BILLING);
2358
2359  scoped_ptr<wallet::WalletItems> wallet_items = wallet::GetTestWalletItems();
2360  wallet_items->AddInstrument(wallet::GetTestMaskedInstrument());
2361  wallet_items->AddAddress(wallet::GetTestShippingAddress());
2362  controller()->OnDidGetWalletItems(wallet_items.Pass());
2363  // Initiate flow - should add proxy card step since the user is using wallet
2364  // data.
2365  controller()->OnAccept();
2366  EXPECT_TRUE(ReadSetVisuallyDeemphasizedIpc());
2367  controller()->OnDidLoadRiskFingerprintData(GetFakeFingerprint().Pass());
2368
2369  SuggestionState suggestion_state =
2370      controller()->SuggestionStateForSection(SECTION_CC_BILLING);
2371  EXPECT_TRUE(suggestion_state.extra_text.empty());
2372
2373  // There should be four steps total, with the first being the card generation
2374  // step added by the dialog controller.
2375  EXPECT_EQ(4U, controller()->CurrentAutocheckoutSteps().size());
2376  EXPECT_EQ(AUTOCHECKOUT_STEP_PROXY_CARD,
2377            controller()->CurrentAutocheckoutSteps()[0].type());
2378  EXPECT_EQ(AUTOCHECKOUT_STEP_STARTED,
2379            controller()->CurrentAutocheckoutSteps()[0].status());
2380
2381  // Simulate a wallet error. This should remove the card generation step from
2382  // the flow, as we will have to proceed with local data.
2383  controller()->OnWalletError(wallet::WalletClient::UNKNOWN_ERROR);
2384
2385  AutofillProfile shipping_profile(test::GetVerifiedProfile());
2386  AutofillProfile billing_profile(test::GetVerifiedProfile2());
2387  CreditCard credit_card(test::GetVerifiedCreditCard());
2388  controller()->GetTestingManager()->AddTestingProfile(&shipping_profile);
2389  controller()->GetTestingManager()->AddTestingProfile(&billing_profile);
2390  controller()->GetTestingManager()->AddTestingCreditCard(&credit_card);
2391  ui::MenuModel* billing_model =
2392      controller()->MenuModelForSection(SECTION_BILLING);
2393  billing_model->ActivatedAt(1);
2394
2395  // Re-initiate flow.
2396  controller()->OnAccept();
2397  EXPECT_TRUE(ReadSetVisuallyDeemphasizedIpc());
2398
2399  // All steps should be initially unstarted.
2400  EXPECT_EQ(3U, controller()->CurrentAutocheckoutSteps().size());
2401  EXPECT_EQ(AUTOCHECKOUT_STEP_SHIPPING,
2402            controller()->CurrentAutocheckoutSteps()[0].type());
2403  EXPECT_EQ(AUTOCHECKOUT_STEP_UNSTARTED,
2404            controller()->CurrentAutocheckoutSteps()[0].status());
2405  EXPECT_EQ(AUTOCHECKOUT_STEP_DELIVERY,
2406            controller()->CurrentAutocheckoutSteps()[1].type());
2407  EXPECT_EQ(AUTOCHECKOUT_STEP_UNSTARTED,
2408            controller()->CurrentAutocheckoutSteps()[1].status());
2409  EXPECT_EQ(AUTOCHECKOUT_STEP_BILLING,
2410            controller()->CurrentAutocheckoutSteps()[2].type());
2411  EXPECT_EQ(AUTOCHECKOUT_STEP_UNSTARTED,
2412            controller()->CurrentAutocheckoutSteps()[2].status());
2413
2414  // Update steps in the same manner that we would expect to see from the
2415  // AutocheckoutManager while progressing through a flow.
2416  controller()->UpdateAutocheckoutStep(AUTOCHECKOUT_STEP_SHIPPING,
2417                                       AUTOCHECKOUT_STEP_STARTED);
2418  controller()->UpdateAutocheckoutStep(AUTOCHECKOUT_STEP_SHIPPING,
2419                                       AUTOCHECKOUT_STEP_COMPLETED);
2420  controller()->UpdateAutocheckoutStep(AUTOCHECKOUT_STEP_DELIVERY,
2421                                       AUTOCHECKOUT_STEP_STARTED);
2422
2423  // Verify that the steps were appropriately updated.
2424  EXPECT_EQ(3U, controller()->CurrentAutocheckoutSteps().size());
2425  EXPECT_EQ(AUTOCHECKOUT_STEP_SHIPPING,
2426            controller()->CurrentAutocheckoutSteps()[0].type());
2427  EXPECT_EQ(AUTOCHECKOUT_STEP_COMPLETED,
2428            controller()->CurrentAutocheckoutSteps()[0].status());
2429  EXPECT_EQ(AUTOCHECKOUT_STEP_DELIVERY,
2430            controller()->CurrentAutocheckoutSteps()[1].type());
2431  EXPECT_EQ(AUTOCHECKOUT_STEP_STARTED,
2432            controller()->CurrentAutocheckoutSteps()[1].status());
2433  EXPECT_EQ(AUTOCHECKOUT_STEP_BILLING,
2434            controller()->CurrentAutocheckoutSteps()[2].type());
2435  EXPECT_EQ(AUTOCHECKOUT_STEP_UNSTARTED,
2436            controller()->CurrentAutocheckoutSteps()[2].status());
2437
2438  controller()->ViewClosed();
2439  EXPECT_FALSE(ReadSetVisuallyDeemphasizedIpc());
2440}
2441
2442TEST_F(AutofillDialogControllerTest, NewCardBubbleShown) {
2443  EXPECT_CALL(*test_generated_bubble_controller(), SetupAndShow(_, _)).Times(0);
2444
2445  SwitchToAutofill();
2446  FillCreditCardInputs();
2447  controller()->OnAccept();
2448  controller()->ViewClosed();
2449
2450  EXPECT_EQ(1, mock_new_card_bubble_controller()->bubbles_shown());
2451}
2452
2453TEST_F(AutofillDialogControllerTest, GeneratedCardBubbleShown) {
2454  EXPECT_CALL(*test_generated_bubble_controller(), SetupAndShow(_, _)).Times(1);
2455
2456  SubmitWithWalletItems(CompleteAndValidWalletItems());
2457  controller()->OnDidGetFullWallet(wallet::GetTestFullWallet());
2458  controller()->ViewClosed();
2459
2460  EXPECT_EQ(0, mock_new_card_bubble_controller()->bubbles_shown());
2461}
2462
2463TEST_F(AutofillDialogControllerTest, ReloadWalletItemsOnActivation) {
2464  // Switch into Wallet mode and initialize some Wallet data.
2465  SwitchToWallet();
2466
2467  scoped_ptr<wallet::WalletItems> wallet_items = wallet::GetTestWalletItems();
2468  wallet_items->AddInstrument(wallet::GetTestMaskedInstrument());
2469  wallet_items->AddInstrument(wallet::GetTestNonDefaultMaskedInstrument());
2470  wallet_items->AddAddress(wallet::GetTestNonDefaultShippingAddress());
2471  wallet_items->AddAddress(wallet::GetTestShippingAddress());
2472  controller()->OnDidGetWalletItems(wallet_items.Pass());
2473
2474  // Initially, the default entries should be selected.
2475  ui::MenuModel* cc_billing_model =
2476      controller()->MenuModelForSection(SECTION_CC_BILLING);
2477  ui::MenuModel* shipping_model =
2478      controller()->MenuModelForSection(SECTION_SHIPPING);
2479  // "add", "manage", and 2 suggestions.
2480  ASSERT_EQ(4, cc_billing_model->GetItemCount());
2481  EXPECT_TRUE(cc_billing_model->IsItemCheckedAt(0));
2482  // "use billing", "add", "manage", and 2 suggestions.
2483  ASSERT_EQ(5, shipping_model->GetItemCount());
2484  EXPECT_TRUE(shipping_model->IsItemCheckedAt(2));
2485
2486  // Select entries other than the defaults.
2487  cc_billing_model->ActivatedAt(1);
2488  shipping_model->ActivatedAt(1);
2489  // "add", "manage", and 2 suggestions.
2490  ASSERT_EQ(4, cc_billing_model->GetItemCount());
2491  EXPECT_TRUE(cc_billing_model->IsItemCheckedAt(1));
2492  // "use billing", "add", "manage", and 2 suggestions.
2493  ASSERT_EQ(5, shipping_model->GetItemCount());
2494  EXPECT_TRUE(shipping_model-> IsItemCheckedAt(1));
2495
2496  // Simulate switching away from the tab and back.  This should issue a request
2497  // for wallet items.
2498  EXPECT_CALL(*controller()->GetTestingWalletClient(), GetWalletItems(_));
2499  controller()->TabActivated();
2500
2501  // Simulate a response that includes different items.
2502  wallet_items = wallet::GetTestWalletItems();
2503  wallet_items->AddInstrument(wallet::GetTestMaskedInstrumentExpired());
2504  wallet_items->AddInstrument(wallet::GetTestMaskedInstrument());
2505  wallet_items->AddInstrument(wallet::GetTestNonDefaultMaskedInstrument());
2506  wallet_items->AddAddress(wallet::GetTestNonDefaultShippingAddress());
2507  controller()->OnDidGetWalletItems(wallet_items.Pass());
2508
2509  // The previously selected entries should still be selected.
2510  // "add", "manage", and 3 suggestions.
2511  ASSERT_EQ(5, cc_billing_model->GetItemCount());
2512  EXPECT_TRUE(cc_billing_model->IsItemCheckedAt(2));
2513  // "use billing", "add", "manage", and 1 suggestion.
2514  ASSERT_EQ(4, shipping_model->GetItemCount());
2515  EXPECT_TRUE(shipping_model->IsItemCheckedAt(1));
2516}
2517
2518TEST_F(AutofillDialogControllerTest, ReloadWithEmptyWalletItems) {
2519  SwitchToWallet();
2520
2521  controller()->OnDidGetWalletItems(CompleteAndValidWalletItems());
2522  controller()->MenuModelForSection(SECTION_CC_BILLING)->ActivatedAt(1);
2523  controller()->MenuModelForSection(SECTION_SHIPPING)->ActivatedAt(1);
2524
2525  EXPECT_CALL(*controller()->GetTestingWalletClient(), GetWalletItems(_));
2526  controller()->TabActivated();
2527
2528  controller()->OnDidGetWalletItems(wallet::GetTestWalletItems());
2529
2530  EXPECT_FALSE(controller()->MenuModelForSection(SECTION_CC_BILLING));
2531  EXPECT_EQ(
2532      3, controller()->MenuModelForSection(SECTION_SHIPPING)->GetItemCount());
2533}
2534
2535TEST_F(AutofillDialogControllerTest, GeneratedCardBubbleNotShown) {
2536  EXPECT_CALL(*test_generated_bubble_controller(), SetupAndShow(_, _)).Times(0);
2537
2538  SubmitWithWalletItems(CompleteAndValidWalletItems());
2539  controller()->set_dialog_type(DIALOG_TYPE_AUTOCHECKOUT);
2540  controller()->OnDidGetFullWallet(wallet::GetTestFullWallet());
2541  controller()->OnAutocheckoutError();
2542  controller()->ViewClosed();
2543
2544  EXPECT_EQ(0, mock_new_card_bubble_controller()->bubbles_shown());
2545}
2546
2547}  // namespace autofill
2548