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