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