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