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