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