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