autofill_dialog_controller_unittest.cc revision 3240926e260ce088908e02ac07a6cf7b0c0cbf44
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_BILLING_STATE,
1015            form_structure()->field(9)->Type().server_type());
1016  EXPECT_EQ(ADDRESS_HOME_STATE,
1017            form_structure()->field(16)->Type().server_type());
1018  string16 billing_state = form_structure()->field(9)->value;
1019  string16 shipping_state = form_structure()->field(16)->value;
1020  EXPECT_FALSE(billing_state.empty());
1021  EXPECT_FALSE(shipping_state.empty());
1022  EXPECT_NE(billing_state, shipping_state);
1023
1024  EXPECT_EQ(CREDIT_CARD_NAME, form_structure()->field(1)->Type().server_type());
1025  string16 cc_name = form_structure()->field(1)->value;
1026  EXPECT_EQ(NAME_BILLING_FULL,
1027            form_structure()->field(6)->Type().server_type());
1028  string16 billing_name = form_structure()->field(6)->value;
1029  EXPECT_EQ(NAME_FULL, form_structure()->field(13)->Type().server_type());
1030  string16 shipping_name = form_structure()->field(13)->value;
1031
1032  EXPECT_FALSE(cc_name.empty());
1033  EXPECT_FALSE(billing_name.empty());
1034  EXPECT_FALSE(shipping_name.empty());
1035  // Billing name should always be the same as cardholder name.
1036  EXPECT_EQ(cc_name, billing_name);
1037  EXPECT_NE(cc_name, shipping_name);
1038}
1039
1040// Test selecting UseBillingForShipping.
1041TEST_F(AutofillDialogControllerTest, UseBillingAsShipping) {
1042  AutofillProfile full_profile(test::GetVerifiedProfile());
1043  AutofillProfile full_profile2(test::GetVerifiedProfile2());
1044  CreditCard credit_card(test::GetVerifiedCreditCard());
1045  controller()->GetTestingManager()->AddTestingProfile(&full_profile);
1046  controller()->GetTestingManager()->AddTestingProfile(&full_profile2);
1047  controller()->GetTestingManager()->AddTestingCreditCard(&credit_card);
1048
1049  // Test after setting use billing for shipping.
1050  UseBillingForShipping();
1051
1052  controller()->OnAccept();
1053  ASSERT_EQ(20U, form_structure()->field_count());
1054  EXPECT_EQ(ADDRESS_BILLING_STATE,
1055            form_structure()->field(9)->Type().server_type());
1056  EXPECT_EQ(ADDRESS_HOME_STATE,
1057            form_structure()->field(16)->Type().server_type());
1058  string16 billing_state = form_structure()->field(9)->value;
1059  string16 shipping_state = form_structure()->field(16)->value;
1060  EXPECT_FALSE(billing_state.empty());
1061  EXPECT_FALSE(shipping_state.empty());
1062  EXPECT_EQ(billing_state, shipping_state);
1063
1064  EXPECT_EQ(CREDIT_CARD_NAME,
1065            form_structure()->field(1)->Type().server_type());
1066  string16 cc_name = form_structure()->field(1)->value;
1067  EXPECT_EQ(NAME_BILLING_FULL,
1068            form_structure()->field(6)->Type().server_type());
1069  string16 billing_name = form_structure()->field(6)->value;
1070  EXPECT_EQ(NAME_FULL, form_structure()->field(13)->Type().server_type());
1071  string16 shipping_name = form_structure()->field(13)->value;
1072
1073  EXPECT_FALSE(cc_name.empty());
1074  EXPECT_FALSE(billing_name.empty());
1075  EXPECT_FALSE(shipping_name.empty());
1076  EXPECT_EQ(cc_name, billing_name);
1077  EXPECT_EQ(cc_name, shipping_name);
1078}
1079
1080// Tests that shipping and billing telephone fields are supported, and filled
1081// in by their respective profiles. http://crbug.com/244515
1082TEST_F(AutofillDialogControllerTest, BillingVsShippingPhoneNumber) {
1083  FormFieldData shipping_tel;
1084  shipping_tel.autocomplete_attribute = "shipping tel";
1085  FormFieldData billing_tel;
1086  billing_tel.autocomplete_attribute = "billing tel";
1087
1088  FormData form_data;
1089  form_data.fields.push_back(shipping_tel);
1090  form_data.fields.push_back(billing_tel);
1091  SetUpControllerWithFormData(form_data);
1092
1093  // The profile that will be chosen for the shipping section.
1094  AutofillProfile shipping_profile(test::GetVerifiedProfile());
1095  // The profile that will be chosen for the billing section.
1096  AutofillProfile billing_profile(test::GetVerifiedProfile2());
1097  CreditCard credit_card(test::GetVerifiedCreditCard());
1098  controller()->GetTestingManager()->AddTestingProfile(&shipping_profile);
1099  controller()->GetTestingManager()->AddTestingProfile(&billing_profile);
1100  controller()->GetTestingManager()->AddTestingCreditCard(&credit_card);
1101  ui::MenuModel* billing_model =
1102      controller()->MenuModelForSection(SECTION_BILLING);
1103  billing_model->ActivatedAt(1);
1104
1105  controller()->OnAccept();
1106  ASSERT_EQ(2U, form_structure()->field_count());
1107  EXPECT_EQ(PHONE_HOME_WHOLE_NUMBER,
1108            form_structure()->field(0)->Type().server_type());
1109  EXPECT_EQ(PHONE_BILLING_WHOLE_NUMBER,
1110            form_structure()->field(1)->Type().server_type());
1111  EXPECT_EQ(shipping_profile.GetRawInfo(PHONE_HOME_WHOLE_NUMBER),
1112            form_structure()->field(0)->value);
1113  EXPECT_EQ(billing_profile.GetRawInfo(PHONE_BILLING_WHOLE_NUMBER),
1114            form_structure()->field(1)->value);
1115  EXPECT_NE(form_structure()->field(1)->value,
1116            form_structure()->field(0)->value);
1117}
1118
1119TEST_F(AutofillDialogControllerTest, AcceptLegalDocuments) {
1120  EXPECT_CALL(*controller()->GetTestingWalletClient(),
1121              AcceptLegalDocuments(_, _, _)).Times(1);
1122  EXPECT_CALL(*controller()->GetTestingWalletClient(),
1123              GetFullWallet(_)).Times(1);
1124  EXPECT_CALL(*controller(), LoadRiskFingerprintData()).Times(1);
1125
1126  scoped_ptr<wallet::WalletItems> wallet_items = CompleteAndValidWalletItems();
1127  wallet_items->AddLegalDocument(wallet::GetTestLegalDocument());
1128  controller()->OnDidGetWalletItems(wallet_items.Pass());
1129  controller()->OnAccept();
1130  controller()->OnDidAcceptLegalDocuments();
1131  controller()->OnDidLoadRiskFingerprintData(GetFakeFingerprint().Pass());
1132}
1133
1134// Makes sure the default object IDs are respected.
1135TEST_F(AutofillDialogControllerTest, WalletDefaultItems) {
1136  scoped_ptr<wallet::WalletItems> wallet_items = wallet::GetTestWalletItems();
1137  wallet_items->AddInstrument(wallet::GetTestNonDefaultMaskedInstrument());
1138  wallet_items->AddInstrument(wallet::GetTestNonDefaultMaskedInstrument());
1139  wallet_items->AddInstrument(wallet::GetTestMaskedInstrument());
1140  wallet_items->AddInstrument(wallet::GetTestNonDefaultMaskedInstrument());
1141
1142  wallet_items->AddAddress(wallet::GetTestNonDefaultShippingAddress());
1143  wallet_items->AddAddress(wallet::GetTestNonDefaultShippingAddress());
1144  wallet_items->AddAddress(wallet::GetTestNonDefaultShippingAddress());
1145  wallet_items->AddAddress(wallet::GetTestShippingAddress());
1146  wallet_items->AddAddress(wallet::GetTestNonDefaultShippingAddress());
1147
1148  controller()->OnDidGetWalletItems(wallet_items.Pass());
1149  // "add", "manage", and 4 suggestions.
1150  EXPECT_EQ(6,
1151      controller()->MenuModelForSection(SECTION_CC_BILLING)->GetItemCount());
1152  EXPECT_TRUE(controller()->MenuModelForSection(SECTION_CC_BILLING)->
1153      IsItemCheckedAt(2));
1154  ASSERT_FALSE(controller()->IsEditingExistingData(SECTION_CC_BILLING));
1155  // "use billing", "add", "manage", and 5 suggestions.
1156  EXPECT_EQ(8,
1157      controller()->MenuModelForSection(SECTION_SHIPPING)->GetItemCount());
1158  EXPECT_TRUE(controller()->MenuModelForSection(SECTION_SHIPPING)->
1159      IsItemCheckedAt(4));
1160  ASSERT_FALSE(controller()->IsEditingExistingData(SECTION_SHIPPING));
1161}
1162
1163// Tests that invalid and AMEX default instruments are ignored.
1164TEST_F(AutofillDialogControllerTest, SelectInstrument) {
1165  scoped_ptr<wallet::WalletItems> wallet_items = wallet::GetTestWalletItems();
1166  // Tests if default instrument is invalid, then, the first valid instrument is
1167  // selected instead of the default instrument.
1168  wallet_items->AddInstrument(wallet::GetTestNonDefaultMaskedInstrument());
1169  wallet_items->AddInstrument(wallet::GetTestNonDefaultMaskedInstrument());
1170  wallet_items->AddInstrument(wallet::GetTestMaskedInstrumentInvalid());
1171  wallet_items->AddInstrument(wallet::GetTestNonDefaultMaskedInstrument());
1172
1173  controller()->OnDidGetWalletItems(wallet_items.Pass());
1174  // 4 suggestions and "add", "manage".
1175  EXPECT_EQ(6,
1176      controller()->MenuModelForSection(SECTION_CC_BILLING)->GetItemCount());
1177  EXPECT_TRUE(controller()->MenuModelForSection(SECTION_CC_BILLING)->
1178      IsItemCheckedAt(0));
1179
1180  // Tests if default instrument is AMEX, then, the first valid instrument is
1181  // selected instead of the default instrument.
1182  wallet_items = wallet::GetTestWalletItems();
1183  wallet_items->AddInstrument(wallet::GetTestNonDefaultMaskedInstrument());
1184  wallet_items->AddInstrument(wallet::GetTestNonDefaultMaskedInstrument());
1185  wallet_items->AddInstrument(wallet::GetTestMaskedInstrumentAmex());
1186  wallet_items->AddInstrument(wallet::GetTestNonDefaultMaskedInstrument());
1187
1188  controller()->OnDidGetWalletItems(wallet_items.Pass());
1189  // 4 suggestions and "add", "manage".
1190  EXPECT_EQ(6,
1191      controller()->MenuModelForSection(SECTION_CC_BILLING)->GetItemCount());
1192  EXPECT_TRUE(controller()->MenuModelForSection(SECTION_CC_BILLING)->
1193      IsItemCheckedAt(0));
1194
1195  // Tests if only have AMEX and invalid instrument, then "add" is selected.
1196  wallet_items = wallet::GetTestWalletItems();
1197  wallet_items->AddInstrument(wallet::GetTestMaskedInstrumentInvalid());
1198  wallet_items->AddInstrument(wallet::GetTestMaskedInstrumentAmex());
1199
1200  controller()->OnDidGetWalletItems(wallet_items.Pass());
1201  // 2 suggestions and "add", "manage".
1202  EXPECT_EQ(4,
1203      controller()->MenuModelForSection(SECTION_CC_BILLING)->GetItemCount());
1204  // "add"
1205  EXPECT_TRUE(controller()->MenuModelForSection(SECTION_CC_BILLING)->
1206      IsItemCheckedAt(2));
1207}
1208
1209TEST_F(AutofillDialogControllerTest, SaveAddress) {
1210  EXPECT_CALL(*controller()->GetView(), ModelChanged()).Times(1);
1211  EXPECT_CALL(*controller()->GetTestingWalletClient(),
1212              SaveToWalletMock(testing::IsNull(),
1213                               testing::NotNull(),
1214                               _)).Times(1);
1215
1216  scoped_ptr<wallet::WalletItems> wallet_items = wallet::GetTestWalletItems();
1217  wallet_items->AddInstrument(wallet::GetTestMaskedInstrument());
1218  controller()->OnDidGetWalletItems(wallet_items.Pass());
1219  // If there is no shipping address in wallet, it will default to
1220  // "same-as-billing" instead of "add-new-item". "same-as-billing" is covered
1221  // by the following tests. The last item in the menu is "add-new-item".
1222  ui::MenuModel* shipping_model =
1223      controller()->MenuModelForSection(SECTION_SHIPPING);
1224  shipping_model->ActivatedAt(shipping_model->GetItemCount() - 1);
1225  AcceptAndLoadFakeFingerprint();
1226}
1227
1228TEST_F(AutofillDialogControllerTest, SaveInstrument) {
1229  EXPECT_CALL(*controller()->GetView(), ModelChanged()).Times(1);
1230  EXPECT_CALL(*controller()->GetTestingWalletClient(),
1231              SaveToWalletMock(testing::NotNull(),
1232                               testing::IsNull(),
1233                               _)).Times(1);
1234
1235  scoped_ptr<wallet::WalletItems> wallet_items = wallet::GetTestWalletItems();
1236  wallet_items->AddAddress(wallet::GetTestShippingAddress());
1237  SubmitWithWalletItems(wallet_items.Pass());
1238}
1239
1240TEST_F(AutofillDialogControllerTest, SaveInstrumentWithInvalidInstruments) {
1241  EXPECT_CALL(*controller()->GetView(), ModelChanged()).Times(1);
1242  EXPECT_CALL(*controller()->GetTestingWalletClient(),
1243              SaveToWalletMock(testing::NotNull(),
1244                               testing::IsNull(),
1245                               _)).Times(1);
1246
1247  scoped_ptr<wallet::WalletItems> wallet_items = wallet::GetTestWalletItems();
1248  wallet_items->AddAddress(wallet::GetTestShippingAddress());
1249  wallet_items->AddInstrument(wallet::GetTestMaskedInstrumentInvalid());
1250  SubmitWithWalletItems(wallet_items.Pass());
1251}
1252
1253TEST_F(AutofillDialogControllerTest, SaveInstrumentAndAddress) {
1254  EXPECT_CALL(*controller()->GetTestingWalletClient(),
1255              SaveToWalletMock(testing::NotNull(),
1256                               testing::NotNull(),
1257                               _)).Times(1);
1258
1259  controller()->OnDidGetWalletItems(wallet::GetTestWalletItems());
1260  AcceptAndLoadFakeFingerprint();
1261}
1262
1263MATCHER(IsUpdatingExistingData, "updating existing Wallet data") {
1264  return !arg->object_id().empty();
1265}
1266
1267// Tests that editing an address (in wallet mode0 and submitting the dialog
1268// should update the existing address on the server via WalletClient.
1269TEST_F(AutofillDialogControllerTest, UpdateAddress) {
1270  EXPECT_CALL(*controller()->GetTestingWalletClient(),
1271              SaveToWalletMock(testing::IsNull(),
1272                               IsUpdatingExistingData(),
1273                               _)).Times(1);
1274
1275  controller()->OnDidGetWalletItems(CompleteAndValidWalletItems());
1276
1277  controller()->EditClickedForSection(SECTION_SHIPPING);
1278  AcceptAndLoadFakeFingerprint();
1279}
1280
1281// Tests that editing an instrument (CC + address) in wallet mode updates an
1282// existing instrument on the server via WalletClient.
1283TEST_F(AutofillDialogControllerTest, UpdateInstrument) {
1284  EXPECT_CALL(*controller()->GetTestingWalletClient(),
1285              SaveToWalletMock(IsUpdatingExistingData(),
1286                               testing::IsNull(),
1287                               _)).Times(1);
1288
1289  controller()->OnDidGetWalletItems(CompleteAndValidWalletItems());
1290
1291  controller()->EditClickedForSection(SECTION_CC_BILLING);
1292  AcceptAndLoadFakeFingerprint();
1293}
1294
1295// Test that a user is able to edit their instrument and add a new address in
1296// the same submission.
1297TEST_F(AutofillDialogControllerTest, UpdateInstrumentSaveAddress) {
1298  EXPECT_CALL(*controller()->GetTestingWalletClient(),
1299              SaveToWalletMock(IsUpdatingExistingData(),
1300                               testing::NotNull(),
1301                               _)).Times(1);
1302
1303  scoped_ptr<wallet::WalletItems> wallet_items = wallet::GetTestWalletItems();
1304  wallet_items->AddInstrument(wallet::GetTestMaskedInstrument());
1305  controller()->OnDidGetWalletItems(wallet_items.Pass());
1306
1307  controller()->EditClickedForSection(SECTION_CC_BILLING);
1308  AcceptAndLoadFakeFingerprint();
1309}
1310
1311// Test that saving a new instrument and editing an address works.
1312TEST_F(AutofillDialogControllerTest, SaveInstrumentUpdateAddress) {
1313  EXPECT_CALL(*controller()->GetTestingWalletClient(),
1314              SaveToWalletMock(testing::NotNull(),
1315                               IsUpdatingExistingData(),
1316                               _)).Times(1);
1317
1318  scoped_ptr<wallet::WalletItems> wallet_items = wallet::GetTestWalletItems();
1319  wallet_items->AddAddress(wallet::GetTestShippingAddress());
1320
1321  controller()->OnDidGetWalletItems(wallet_items.Pass());
1322
1323  controller()->EditClickedForSection(SECTION_SHIPPING);
1324  AcceptAndLoadFakeFingerprint();
1325}
1326
1327MATCHER(UsesLocalBillingAddress, "uses the local billing address") {
1328  return arg->address_line_1() == ASCIIToUTF16(kEditedBillingAddress);
1329}
1330
1331// Tests that when using billing address for shipping, and there is no exact
1332// matched shipping address, then a shipping address should be added.
1333TEST_F(AutofillDialogControllerTest, BillingForShipping) {
1334  EXPECT_CALL(*controller()->GetTestingWalletClient(),
1335              SaveToWalletMock(testing::IsNull(),
1336                               testing::NotNull(),
1337                               _)).Times(1);
1338
1339  controller()->OnDidGetWalletItems(CompleteAndValidWalletItems());
1340  // Select "Same as billing" in the address menu.
1341  UseBillingForShipping();
1342
1343  AcceptAndLoadFakeFingerprint();
1344}
1345
1346// Tests that when using billing address for shipping, and there is an exact
1347// matched shipping address, then a shipping address should not be added.
1348TEST_F(AutofillDialogControllerTest, BillingForShippingHasMatch) {
1349  EXPECT_CALL(*controller()->GetTestingWalletClient(),
1350              SaveToWalletMock(_, _, _)).Times(0);
1351
1352  scoped_ptr<wallet::WalletItems> wallet_items = wallet::GetTestWalletItems();
1353  scoped_ptr<wallet::WalletItems::MaskedInstrument> instrument =
1354      wallet::GetTestMaskedInstrument();
1355  // Copy billing address as shipping address, and assign an id to it.
1356  scoped_ptr<wallet::Address> shipping_address(
1357      new wallet::Address(instrument->address()));
1358  shipping_address->set_object_id("shipping_address_id");
1359  wallet_items->AddAddress(shipping_address.Pass());
1360  wallet_items->AddInstrument(instrument.Pass());
1361  wallet_items->AddAddress(wallet::GetTestShippingAddress());
1362
1363  controller()->OnDidGetWalletItems(wallet_items.Pass());
1364  // Select "Same as billing" in the address menu.
1365  UseBillingForShipping();
1366
1367  AcceptAndLoadFakeFingerprint();
1368}
1369
1370// Test that the local view contents is used when saving a new instrument and
1371// the user has selected "Same as billing".
1372TEST_F(AutofillDialogControllerTest, SaveInstrumentSameAsBilling) {
1373  scoped_ptr<wallet::WalletItems> wallet_items = wallet::GetTestWalletItems();
1374  wallet_items->AddInstrument(wallet::GetTestMaskedInstrument());
1375  controller()->OnDidGetWalletItems(wallet_items.Pass());
1376
1377  controller()->EditClickedForSection(SECTION_CC_BILLING);
1378  controller()->OnAccept();
1379
1380  DetailOutputMap outputs;
1381  const DetailInputs& inputs =
1382      controller()->RequestedFieldsForSection(SECTION_CC_BILLING);
1383  for (size_t i = 0; i < inputs.size(); ++i) {
1384    const DetailInput& input = inputs[i];
1385    outputs[&input] = input.type == ADDRESS_BILLING_LINE1 ?
1386        ASCIIToUTF16(kEditedBillingAddress) : input.initial_value;
1387  }
1388  controller()->GetView()->SetUserInput(SECTION_CC_BILLING, outputs);
1389
1390  EXPECT_CALL(*controller()->GetTestingWalletClient(),
1391              SaveToWalletMock(testing::NotNull(),
1392                               UsesLocalBillingAddress(),
1393                               _)).Times(1);
1394  AcceptAndLoadFakeFingerprint();
1395}
1396
1397TEST_F(AutofillDialogControllerTest, CancelNoSave) {
1398  EXPECT_CALL(*controller()->GetTestingWalletClient(),
1399              SaveToWalletMock(_, _, _)).Times(0);
1400
1401  EXPECT_CALL(*controller()->GetView(), ModelChanged()).Times(1);
1402
1403  controller()->OnDidGetWalletItems(wallet::GetTestWalletItems());
1404  controller()->OnCancel();
1405}
1406
1407// Checks that clicking the Manage menu item opens a new tab with a different
1408// URL for Wallet and Autofill.
1409TEST_F(AutofillDialogControllerTest, ManageItem) {
1410  AutofillProfile full_profile(test::GetVerifiedProfile());
1411  full_profile.set_origin(kSettingsOrigin);
1412  full_profile.SetRawInfo(ADDRESS_HOME_LINE2, string16());
1413  controller()->GetTestingManager()->AddTestingProfile(&full_profile);
1414  SwitchToAutofill();
1415
1416  SuggestionsMenuModel* shipping = static_cast<SuggestionsMenuModel*>(
1417      controller()->MenuModelForSection(SECTION_SHIPPING));
1418  shipping->ExecuteCommand(shipping->GetItemCount() - 1, 0);
1419  GURL autofill_manage_url = controller()->open_tab_url();
1420  EXPECT_EQ("chrome", autofill_manage_url.scheme());
1421
1422  SwitchToWallet();
1423  scoped_ptr<wallet::WalletItems> wallet_items = wallet::GetTestWalletItems();
1424  wallet_items->AddInstrument(wallet::GetTestMaskedInstrument());
1425  controller()->OnDidGetWalletItems(wallet_items.Pass());
1426
1427  controller()->SuggestionItemSelected(shipping, shipping->GetItemCount() - 1);
1428  GURL wallet_manage_addresses_url = controller()->open_tab_url();
1429  EXPECT_EQ("https", wallet_manage_addresses_url.scheme());
1430
1431  SuggestionsMenuModel* billing = static_cast<SuggestionsMenuModel*>(
1432      controller()->MenuModelForSection(SECTION_CC_BILLING));
1433  controller()->SuggestionItemSelected(billing, billing->GetItemCount() - 1);
1434  GURL wallet_manage_instruments_url = controller()->open_tab_url();
1435  EXPECT_EQ("https", wallet_manage_instruments_url.scheme());
1436
1437  EXPECT_NE(autofill_manage_url, wallet_manage_instruments_url);
1438  EXPECT_NE(wallet_manage_instruments_url, wallet_manage_addresses_url);
1439}
1440
1441TEST_F(AutofillDialogControllerTest, EditClickedCancelled) {
1442  EXPECT_CALL(*controller()->GetView(), ModelChanged()).Times(1);
1443
1444  AutofillProfile full_profile(test::GetVerifiedProfile());
1445  const string16 kEmail = ASCIIToUTF16("first@johndoe.com");
1446  full_profile.SetRawInfo(EMAIL_ADDRESS, kEmail);
1447  controller()->GetTestingManager()->AddTestingProfile(&full_profile);
1448
1449  ui::MenuModel* email_model =
1450      controller()->MenuModelForSection(SECTION_EMAIL);
1451  EXPECT_EQ(3, email_model->GetItemCount());
1452
1453  // When unedited, the initial_value should be empty.
1454  email_model->ActivatedAt(0);
1455  const DetailInputs& inputs0 =
1456      controller()->RequestedFieldsForSection(SECTION_EMAIL);
1457  EXPECT_EQ(string16(), inputs0[0].initial_value);
1458  EXPECT_EQ(kEmail,
1459            controller()->SuggestionStateForSection(SECTION_EMAIL).text);
1460
1461  // When edited, the initial_value should contain the value.
1462  controller()->EditClickedForSection(SECTION_EMAIL);
1463  const DetailInputs& inputs1 =
1464      controller()->RequestedFieldsForSection(SECTION_EMAIL);
1465  EXPECT_EQ(kEmail, inputs1[0].initial_value);
1466  EXPECT_EQ(string16(),
1467            controller()->SuggestionStateForSection(SECTION_EMAIL).text);
1468
1469  // When edit is cancelled, the initial_value should be empty.
1470  controller()->EditCancelledForSection(SECTION_EMAIL);
1471  const DetailInputs& inputs2 =
1472      controller()->RequestedFieldsForSection(SECTION_EMAIL);
1473  EXPECT_EQ(kEmail,
1474            controller()->SuggestionStateForSection(SECTION_EMAIL).text);
1475  EXPECT_EQ(string16(), inputs2[0].initial_value);
1476}
1477
1478// Tests that editing an autofill profile and then submitting works.
1479TEST_F(AutofillDialogControllerTest, EditAutofillProfile) {
1480  SwitchToAutofill();
1481
1482  EXPECT_CALL(*controller()->GetView(), ModelChanged()).Times(1);
1483
1484  AutofillProfile full_profile(test::GetVerifiedProfile());
1485  controller()->GetTestingManager()->AddTestingProfile(&full_profile);
1486  controller()->EditClickedForSection(SECTION_SHIPPING);
1487
1488  DetailOutputMap outputs;
1489  const DetailInputs& inputs =
1490      controller()->RequestedFieldsForSection(SECTION_SHIPPING);
1491  for (size_t i = 0; i < inputs.size(); ++i) {
1492    const DetailInput& input = inputs[i];
1493    outputs[&input] = input.type == NAME_FULL ? ASCIIToUTF16("Edited Name") :
1494                                                input.initial_value;
1495  }
1496  controller()->GetView()->SetUserInput(SECTION_SHIPPING, outputs);
1497
1498  // We also have to simulate CC inputs to keep the controller happy.
1499  FillCreditCardInputs();
1500
1501  controller()->OnAccept();
1502  const AutofillProfile& edited_profile =
1503      controller()->GetTestingManager()->imported_profile();
1504
1505  for (size_t i = 0; i < inputs.size(); ++i) {
1506    const DetailInput& input = inputs[i];
1507    EXPECT_EQ(input.type == NAME_FULL ? ASCIIToUTF16("Edited Name") :
1508                                        input.initial_value,
1509              edited_profile.GetInfo(AutofillType(input.type), "en-US"));
1510  }
1511}
1512
1513// Tests that adding an autofill profile and then submitting works.
1514TEST_F(AutofillDialogControllerTest, AddAutofillProfile) {
1515  EXPECT_CALL(*controller()->GetView(), ModelChanged()).Times(2);
1516
1517  AutofillProfile full_profile(test::GetVerifiedProfile());
1518  CreditCard credit_card(test::GetVerifiedCreditCard());
1519  controller()->GetTestingManager()->AddTestingProfile(&full_profile);
1520  controller()->GetTestingManager()->AddTestingCreditCard(&credit_card);
1521
1522  ui::MenuModel* model = controller()->MenuModelForSection(SECTION_BILLING);
1523  // Activate the "Add billing address" menu item.
1524  model->ActivatedAt(model->GetItemCount() - 2);
1525
1526  // Fill in the inputs from the profile.
1527  DetailOutputMap outputs;
1528  const DetailInputs& inputs =
1529      controller()->RequestedFieldsForSection(SECTION_BILLING);
1530  AutofillProfile full_profile2(test::GetVerifiedProfile2());
1531  for (size_t i = 0; i < inputs.size(); ++i) {
1532    const DetailInput& input = inputs[i];
1533    outputs[&input] = full_profile2.GetInfo(AutofillType(input.type), "en-US");
1534  }
1535  controller()->GetView()->SetUserInput(SECTION_BILLING, outputs);
1536
1537  controller()->OnAccept();
1538  const AutofillProfile& added_profile =
1539      controller()->GetTestingManager()->imported_profile();
1540
1541  const DetailInputs& shipping_inputs =
1542      controller()->RequestedFieldsForSection(SECTION_SHIPPING);
1543  for (size_t i = 0; i < shipping_inputs.size(); ++i) {
1544    const DetailInput& input = shipping_inputs[i];
1545    EXPECT_EQ(full_profile2.GetInfo(AutofillType(input.type), "en-US"),
1546              added_profile.GetInfo(AutofillType(input.type), "en-US"));
1547  }
1548
1549  // Also, the currently selected email address should get added to the new
1550  // profile.
1551  string16 original_email =
1552      full_profile.GetInfo(AutofillType(EMAIL_ADDRESS), "en-US");
1553  EXPECT_FALSE(original_email.empty());
1554  EXPECT_EQ(original_email,
1555            added_profile.GetInfo(AutofillType(EMAIL_ADDRESS), "en-US"));
1556}
1557
1558// Makes sure that a newly added email address gets added to an existing profile
1559// (as opposed to creating its own profile). http://crbug.com/240926
1560TEST_F(AutofillDialogControllerTest, AddEmail) {
1561  EXPECT_CALL(*controller()->GetView(), ModelChanged()).Times(1);
1562
1563  AutofillProfile full_profile(test::GetVerifiedProfile());
1564  controller()->GetTestingManager()->AddTestingProfile(&full_profile);
1565
1566  ui::MenuModel* model = controller()->MenuModelForSection(SECTION_EMAIL);
1567  ASSERT_TRUE(model);
1568  // Activate the "Add email address" menu item.
1569  model->ActivatedAt(model->GetItemCount() - 2);
1570
1571  // Fill in the inputs from the profile.
1572  DetailOutputMap outputs;
1573  const DetailInputs& inputs =
1574      controller()->RequestedFieldsForSection(SECTION_EMAIL);
1575  const DetailInput& input = inputs[0];
1576  string16 new_email = ASCIIToUTF16("addemailtest@example.com");
1577  outputs[&input] = new_email;
1578  controller()->GetView()->SetUserInput(SECTION_EMAIL, outputs);
1579
1580  FillCreditCardInputs();
1581  controller()->OnAccept();
1582  std::vector<base::string16> email_values;
1583  full_profile.GetMultiInfo(
1584      AutofillType(EMAIL_ADDRESS), "en-US", &email_values);
1585  ASSERT_EQ(2U, email_values.size());
1586  EXPECT_EQ(new_email, email_values[1]);
1587}
1588
1589TEST_F(AutofillDialogControllerTest, VerifyCvv) {
1590  EXPECT_CALL(*controller()->GetTestingWalletClient(),
1591              GetFullWallet(_)).Times(1);
1592  EXPECT_CALL(*controller()->GetTestingWalletClient(),
1593              AuthenticateInstrument(_, _)).Times(1);
1594
1595  SubmitWithWalletItems(CompleteAndValidWalletItems());
1596
1597  EXPECT_TRUE(NotificationsOfType(DialogNotification::REQUIRED_ACTION).empty());
1598  EXPECT_TRUE(controller()->SectionIsActive(SECTION_SHIPPING));
1599  EXPECT_TRUE(controller()->SectionIsActive(SECTION_CC_BILLING));
1600  EXPECT_FALSE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_OK));
1601  EXPECT_FALSE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_CANCEL));
1602
1603  SuggestionState suggestion_state =
1604      controller()->SuggestionStateForSection(SECTION_CC_BILLING);
1605  EXPECT_TRUE(suggestion_state.extra_text.empty());
1606
1607  controller()->OnDidGetFullWallet(CreateFullWallet("verify_cvv"));
1608
1609  EXPECT_FALSE(
1610      NotificationsOfType(DialogNotification::REQUIRED_ACTION).empty());
1611  EXPECT_FALSE(controller()->SectionIsActive(SECTION_SHIPPING));
1612  EXPECT_TRUE(controller()->SectionIsActive(SECTION_CC_BILLING));
1613
1614  suggestion_state =
1615      controller()->SuggestionStateForSection(SECTION_CC_BILLING);
1616  EXPECT_FALSE(suggestion_state.extra_text.empty());
1617  EXPECT_FALSE(controller()->MenuModelForSection(SECTION_CC_BILLING));
1618
1619  EXPECT_TRUE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_OK));
1620  EXPECT_TRUE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_CANCEL));
1621
1622  controller()->OnAccept();
1623}
1624
1625TEST_F(AutofillDialogControllerTest, ErrorDuringSubmit) {
1626  EXPECT_CALL(*controller()->GetTestingWalletClient(),
1627              GetFullWallet(_)).Times(1);
1628
1629  SubmitWithWalletItems(CompleteAndValidWalletItems());
1630
1631  EXPECT_FALSE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_OK));
1632  EXPECT_FALSE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_CANCEL));
1633
1634  controller()->OnWalletError(wallet::WalletClient::UNKNOWN_ERROR);
1635
1636  EXPECT_TRUE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_OK));
1637  EXPECT_TRUE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_CANCEL));
1638}
1639
1640// TODO(dbeam): disallow changing accounts instead and remove this test.
1641TEST_F(AutofillDialogControllerTest, ChangeAccountDuringSubmit) {
1642  EXPECT_CALL(*controller()->GetTestingWalletClient(),
1643              GetFullWallet(_)).Times(1);
1644
1645  SubmitWithWalletItems(CompleteAndValidWalletItems());
1646
1647  EXPECT_FALSE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_OK));
1648  EXPECT_FALSE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_CANCEL));
1649
1650  SwitchToWallet();
1651  SwitchToAutofill();
1652
1653  EXPECT_TRUE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_OK));
1654  EXPECT_TRUE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_CANCEL));
1655}
1656
1657TEST_F(AutofillDialogControllerTest, ErrorDuringVerifyCvv) {
1658  EXPECT_CALL(*controller()->GetTestingWalletClient(),
1659              GetFullWallet(_)).Times(1);
1660
1661  SubmitWithWalletItems(CompleteAndValidWalletItems());
1662  controller()->OnDidGetFullWallet(CreateFullWallet("verify_cvv"));
1663
1664  ASSERT_TRUE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_OK));
1665  ASSERT_TRUE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_CANCEL));
1666
1667  controller()->OnWalletError(wallet::WalletClient::UNKNOWN_ERROR);
1668
1669  EXPECT_TRUE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_OK));
1670  EXPECT_TRUE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_CANCEL));
1671}
1672
1673// TODO(dbeam): disallow changing accounts instead and remove this test.
1674TEST_F(AutofillDialogControllerTest, ChangeAccountDuringVerifyCvv) {
1675  EXPECT_CALL(*controller()->GetTestingWalletClient(),
1676              GetFullWallet(_)).Times(1);
1677
1678  SubmitWithWalletItems(CompleteAndValidWalletItems());
1679  controller()->OnDidGetFullWallet(CreateFullWallet("verify_cvv"));
1680
1681  ASSERT_TRUE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_OK));
1682  ASSERT_TRUE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_CANCEL));
1683
1684  SwitchToWallet();
1685  SwitchToAutofill();
1686
1687  EXPECT_TRUE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_OK));
1688  EXPECT_TRUE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_CANCEL));
1689}
1690
1691// Simulates receiving an INVALID_FORM_FIELD required action while processing a
1692// |WalletClientDelegate::OnDid{Save,Update}*()| call. This can happen if Online
1693// Wallet's server validation differs from Chrome's local validation.
1694TEST_F(AutofillDialogControllerTest, WalletServerSideValidation) {
1695  scoped_ptr<wallet::WalletItems> wallet_items = wallet::GetTestWalletItems();
1696  wallet_items->AddInstrument(wallet::GetTestMaskedInstrument());
1697  controller()->OnDidGetWalletItems(wallet_items.Pass());
1698  controller()->OnAccept();
1699
1700  std::vector<wallet::RequiredAction> required_actions;
1701  required_actions.push_back(wallet::INVALID_FORM_FIELD);
1702
1703  std::vector<wallet::FormFieldError> form_errors;
1704  form_errors.push_back(
1705      wallet::FormFieldError(wallet::FormFieldError::INVALID_POSTAL_CODE,
1706                             wallet::FormFieldError::SHIPPING_ADDRESS));
1707
1708  EXPECT_CALL(*controller()->GetView(), UpdateForErrors()).Times(1);
1709  controller()->OnDidSaveToWallet(std::string(),
1710                                  std::string(),
1711                                  required_actions,
1712                                  form_errors);
1713}
1714
1715// Simulates receiving unrecoverable Wallet server validation errors.
1716TEST_F(AutofillDialogControllerTest, WalletServerSideValidationUnrecoverable) {
1717  scoped_ptr<wallet::WalletItems> wallet_items = wallet::GetTestWalletItems();
1718  wallet_items->AddInstrument(wallet::GetTestMaskedInstrument());
1719  controller()->OnDidGetWalletItems(wallet_items.Pass());
1720  controller()->OnAccept();
1721
1722  std::vector<wallet::RequiredAction> required_actions;
1723  required_actions.push_back(wallet::INVALID_FORM_FIELD);
1724
1725  std::vector<wallet::FormFieldError> form_errors;
1726  form_errors.push_back(
1727      wallet::FormFieldError(wallet::FormFieldError::UNKNOWN_ERROR,
1728                             wallet::FormFieldError::UNKNOWN_LOCATION));
1729
1730  controller()->OnDidSaveToWallet(std::string(),
1731                                  std::string(),
1732                                  required_actions,
1733                                  form_errors);
1734
1735  EXPECT_EQ(1U, NotificationsOfType(
1736      DialogNotification::REQUIRED_ACTION).size());
1737}
1738
1739// Test Wallet banners are show in the right situations. These banners explain
1740// where Chrome got the user's data (i.e. "Got details from Wallet") or promote
1741// saving details into Wallet (i.e. "[x] Save details to Wallet").
1742TEST_F(AutofillDialogControllerTest, WalletBanners) {
1743  CommandLine* command_line = CommandLine::ForCurrentProcess();
1744  command_line->AppendSwitch(switches::kWalletServiceUseProd);
1745  PrefService* prefs = profile()->GetPrefs();
1746
1747  // Simulate first run.
1748  prefs->SetBoolean(::prefs::kAutofillDialogHasPaidWithWallet, false);
1749  SetUpControllerWithFormData(DefaultFormData());
1750
1751  EXPECT_EQ(0U, NotificationsOfType(
1752      DialogNotification::EXPLANATORY_MESSAGE).size());
1753  EXPECT_EQ(0U, NotificationsOfType(
1754      DialogNotification::WALLET_USAGE_CONFIRMATION).size());
1755
1756  // Sign in a user with a completed account.
1757  controller()->OnDidGetWalletItems(CompleteAndValidWalletItems());
1758
1759  // Full account; should show "Details from Wallet" message.
1760  EXPECT_EQ(1U, NotificationsOfType(
1761      DialogNotification::EXPLANATORY_MESSAGE).size());
1762  EXPECT_EQ(0U, NotificationsOfType(
1763      DialogNotification::WALLET_USAGE_CONFIRMATION).size());
1764
1765  // Full account; no "[x] Save details in Wallet" option should show.
1766  SwitchToAutofill();
1767  EXPECT_EQ(0U, NotificationsOfType(
1768      DialogNotification::EXPLANATORY_MESSAGE).size());
1769  EXPECT_EQ(0U, NotificationsOfType(
1770      DialogNotification::WALLET_USAGE_CONFIRMATION).size());
1771
1772  SetUpControllerWithFormData(DefaultFormData());
1773  // |controller()| has already been initialized. Test that should not take
1774  // effect until the next call of |SetUpControllerWithFormData()|.
1775  prefs->SetBoolean(::prefs::kAutofillDialogHasPaidWithWallet, true);
1776
1777  // Sign in a user with a incomplete account.
1778  scoped_ptr<wallet::WalletItems> wallet_items = wallet::GetTestWalletItems();
1779  wallet_items->AddInstrument(wallet::GetTestMaskedInstrument());
1780  controller()->OnDidGetWalletItems(wallet_items.Pass());
1781
1782  // Partial account; no "Details from Wallet" message should show, but a
1783  // "[x] Save details in Wallet" should.
1784  EXPECT_EQ(0U, NotificationsOfType(
1785      DialogNotification::EXPLANATORY_MESSAGE).size());
1786  EXPECT_EQ(1U, NotificationsOfType(
1787      DialogNotification::WALLET_USAGE_CONFIRMATION).size());
1788
1789  // Once the usage confirmation banner is shown once, it keeps showing even if
1790  // the user switches to Autofill data.
1791  SwitchToAutofill();
1792  EXPECT_EQ(0U, NotificationsOfType(
1793      DialogNotification::EXPLANATORY_MESSAGE).size());
1794  EXPECT_EQ(1U, NotificationsOfType(
1795      DialogNotification::WALLET_USAGE_CONFIRMATION).size());
1796
1797  // A Wallet error should kill any Wallet promos.
1798  controller()->OnWalletError(wallet::WalletClient::UNKNOWN_ERROR);
1799
1800  EXPECT_EQ(1U, NotificationsOfType(
1801      DialogNotification::WALLET_ERROR).size());
1802  EXPECT_EQ(0U, NotificationsOfType(
1803      DialogNotification::EXPLANATORY_MESSAGE).size());
1804  EXPECT_EQ(0U, NotificationsOfType(
1805      DialogNotification::WALLET_USAGE_CONFIRMATION).size());
1806
1807  SetUpControllerWithFormData(DefaultFormData());
1808  // |controller()| is error free and thinks the user has already paid w/Wallet.
1809
1810  // User has already paid with wallet. Don't show promos.
1811  EXPECT_EQ(0U, NotificationsOfType(
1812      DialogNotification::EXPLANATORY_MESSAGE).size());
1813  EXPECT_EQ(0U, NotificationsOfType(
1814      DialogNotification::WALLET_USAGE_CONFIRMATION).size());
1815
1816  controller()->OnDidGetWalletItems(CompleteAndValidWalletItems());
1817
1818  EXPECT_EQ(0U, NotificationsOfType(
1819      DialogNotification::EXPLANATORY_MESSAGE).size());
1820  EXPECT_EQ(0U, NotificationsOfType(
1821      DialogNotification::WALLET_USAGE_CONFIRMATION).size());
1822
1823  wallet_items = wallet::GetTestWalletItems();
1824  wallet_items->AddInstrument(wallet::GetTestMaskedInstrument());
1825  controller()->OnDidGetWalletItems(wallet_items.Pass());
1826
1827  SwitchToAutofill();
1828  EXPECT_EQ(0U, NotificationsOfType(
1829      DialogNotification::EXPLANATORY_MESSAGE).size());
1830  EXPECT_EQ(0U, NotificationsOfType(
1831      DialogNotification::WALLET_USAGE_CONFIRMATION).size());
1832}
1833
1834TEST_F(AutofillDialogControllerTest, OnAutocheckoutError) {
1835  SwitchToAutofill();
1836  controller()->set_dialog_type(DIALOG_TYPE_AUTOCHECKOUT);
1837
1838  // We also have to simulate CC inputs to keep the controller happy.
1839  FillCreditCardInputs();
1840
1841  controller()->OnAccept();
1842  EXPECT_TRUE(ReadSetVisuallyDeemphasizedIpc());
1843  controller()->OnAutocheckoutError();
1844
1845  EXPECT_FALSE(controller()->GetDialogButtons() & ui::DIALOG_BUTTON_CANCEL);
1846  EXPECT_TRUE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_OK));
1847  EXPECT_EQ(0U, NotificationsOfType(
1848      DialogNotification::AUTOCHECKOUT_SUCCESS).size());
1849  EXPECT_EQ(1U, NotificationsOfType(
1850      DialogNotification::AUTOCHECKOUT_ERROR).size());
1851
1852  controller()->ViewClosed();
1853  EXPECT_FALSE(ReadSetVisuallyDeemphasizedIpc());
1854}
1855
1856TEST_F(AutofillDialogControllerTest, OnAutocheckoutSuccess) {
1857  CommandLine* command_line = CommandLine::ForCurrentProcess();
1858  command_line->AppendSwitch(switches::kWalletServiceUseProd);
1859  controller()->set_dialog_type(DIALOG_TYPE_AUTOCHECKOUT);
1860
1861  // Simulate first run.
1862  profile()->GetPrefs()->SetBoolean(::prefs::kAutofillDialogHasPaidWithWallet,
1863                                    false);
1864  SetUpControllerWithFormData(DefaultFormData());
1865  controller()->set_dialog_type(DIALOG_TYPE_AUTOCHECKOUT);
1866
1867  // Sign in a user with a completed account.
1868  controller()->OnDidGetWalletItems(CompleteAndValidWalletItems());
1869
1870  // Full account; should show "Details from Wallet" message.
1871  EXPECT_EQ(1U, NotificationsOfType(
1872      DialogNotification::EXPLANATORY_MESSAGE).size());
1873  EXPECT_EQ(0U, NotificationsOfType(
1874      DialogNotification::WALLET_USAGE_CONFIRMATION).size());
1875
1876  AcceptAndLoadFakeFingerprint();
1877  EXPECT_TRUE(ReadSetVisuallyDeemphasizedIpc());
1878  controller()->OnDidGetFullWallet(wallet::GetTestFullWallet());
1879  EXPECT_TRUE(controller()->GetDialogOverlay().image.IsEmpty());
1880
1881  EXPECT_EQ(0U, NotificationsOfType(
1882      DialogNotification::EXPLANATORY_MESSAGE).size());
1883
1884  controller()->OnAutocheckoutSuccess();
1885  EXPECT_TRUE(controller()->GetDialogOverlay().image.IsEmpty());
1886
1887  EXPECT_FALSE(controller()->GetDialogButtons() & ui::DIALOG_BUTTON_CANCEL);
1888  EXPECT_TRUE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_OK));
1889  EXPECT_EQ(1U, NotificationsOfType(
1890      DialogNotification::AUTOCHECKOUT_SUCCESS).size());
1891  EXPECT_EQ(0U, NotificationsOfType(
1892      DialogNotification::AUTOCHECKOUT_ERROR).size());
1893  EXPECT_EQ(0U, NotificationsOfType(
1894      DialogNotification::EXPLANATORY_MESSAGE).size());
1895  EXPECT_TRUE(profile()->GetPrefs()->GetBoolean(
1896      ::prefs::kAutofillDialogHasPaidWithWallet));
1897
1898  controller()->ViewClosed();
1899  EXPECT_FALSE(ReadSetVisuallyDeemphasizedIpc());
1900}
1901
1902TEST_F(AutofillDialogControllerTest, ViewCancelDoesntSetPref) {
1903  ASSERT_FALSE(profile()->GetPrefs()->HasPrefPath(
1904      ::prefs::kAutofillDialogPayWithoutWallet));
1905
1906  SwitchToAutofill();
1907
1908  controller()->OnCancel();
1909  controller()->ViewClosed();
1910
1911  EXPECT_FALSE(profile()->GetPrefs()->HasPrefPath(
1912      ::prefs::kAutofillDialogPayWithoutWallet));
1913}
1914
1915TEST_F(AutofillDialogControllerTest, SubmitWithSigninErrorDoesntSetPref) {
1916  ASSERT_FALSE(profile()->GetPrefs()->HasPrefPath(
1917      ::prefs::kAutofillDialogPayWithoutWallet));
1918
1919  SimulateSigninError();
1920  FillCreditCardInputs();
1921  controller()->OnAccept();
1922
1923  EXPECT_FALSE(profile()->GetPrefs()->HasPrefPath(
1924      ::prefs::kAutofillDialogPayWithoutWallet));
1925}
1926
1927// Tests that there's an overlay shown while waiting for full wallet items,
1928// and on first run an additional expository wallet overlay shown after full
1929// wallet items are returned.
1930// TODO(estade): enable on other platforms when overlays are supported there.
1931#if defined(TOOLKIT_VIEWS)
1932TEST_F(AutofillDialogControllerTest, WalletFirstRun) {
1933  // Simulate first run.
1934  PrefService* prefs = profile()->GetPrefs();
1935  prefs->SetBoolean(::prefs::kAutofillDialogHasPaidWithWallet, false);
1936  SetUpControllerWithFormData(DefaultFormData());
1937
1938  SwitchToWallet();
1939  EXPECT_TRUE(controller()->GetDialogOverlay().image.IsEmpty());
1940
1941  SubmitWithWalletItems(CompleteAndValidWalletItems());
1942  EXPECT_FALSE(controller()->GetDialogOverlay().image.IsEmpty());
1943
1944  EXPECT_FALSE(prefs->GetBoolean(::prefs::kAutofillDialogHasPaidWithWallet));
1945  controller()->OnDidGetFullWallet(wallet::GetTestFullWallet());
1946  EXPECT_FALSE(prefs->GetBoolean(::prefs::kAutofillDialogHasPaidWithWallet));
1947  EXPECT_FALSE(controller()->GetDialogOverlay().image.IsEmpty());
1948  EXPECT_FALSE(form_structure());
1949
1950  controller()->OverlayButtonPressed();
1951  EXPECT_TRUE(prefs->GetBoolean(::prefs::kAutofillDialogHasPaidWithWallet));
1952  EXPECT_TRUE(form_structure());
1953}
1954#endif
1955
1956// On second run, the second overlay doesn't show.
1957TEST_F(AutofillDialogControllerTest, WalletSecondRun) {
1958  SwitchToWallet();
1959  EXPECT_TRUE(controller()->GetDialogOverlay().image.IsEmpty());
1960
1961  SubmitWithWalletItems(CompleteAndValidWalletItems());
1962  EXPECT_FALSE(controller()->GetDialogOverlay().image.IsEmpty());
1963
1964  EXPECT_TRUE(profile()->GetPrefs()->GetBoolean(
1965      ::prefs::kAutofillDialogHasPaidWithWallet));
1966  controller()->OnDidGetFullWallet(wallet::GetTestFullWallet());
1967  EXPECT_TRUE(profile()->GetPrefs()->GetBoolean(
1968      ::prefs::kAutofillDialogHasPaidWithWallet));
1969  EXPECT_TRUE(form_structure());
1970}
1971
1972TEST_F(AutofillDialogControllerTest, ViewSubmitSetsPref) {
1973  ASSERT_FALSE(profile()->GetPrefs()->HasPrefPath(
1974      ::prefs::kAutofillDialogPayWithoutWallet));
1975
1976  SwitchToAutofill();
1977  FillCreditCardInputs();
1978  controller()->OnAccept();
1979
1980  EXPECT_TRUE(profile()->GetPrefs()->HasPrefPath(
1981      ::prefs::kAutofillDialogPayWithoutWallet));
1982  EXPECT_TRUE(profile()->GetPrefs()->GetBoolean(
1983      ::prefs::kAutofillDialogPayWithoutWallet));
1984
1985  // Try again with a signin error (just leaves the pref alone).
1986  SetUpControllerWithFormData(DefaultFormData());
1987
1988  // Setting up the controller again should not change the pref.
1989  EXPECT_TRUE(profile()->GetPrefs()->HasPrefPath(
1990      ::prefs::kAutofillDialogPayWithoutWallet));
1991  EXPECT_TRUE(profile()->GetPrefs()->GetBoolean(
1992      ::prefs::kAutofillDialogPayWithoutWallet));
1993
1994  SimulateSigninError();
1995  FillCreditCardInputs();
1996  controller()->OnAccept();
1997  EXPECT_TRUE(profile()->GetPrefs()->HasPrefPath(
1998      ::prefs::kAutofillDialogPayWithoutWallet));
1999  EXPECT_TRUE(profile()->GetPrefs()->GetBoolean(
2000      ::prefs::kAutofillDialogPayWithoutWallet));
2001
2002  // Succesfully choosing wallet does set the pref.
2003  SetUpControllerWithFormData(DefaultFormData());
2004
2005  SwitchToWallet();
2006  scoped_ptr<wallet::WalletItems> wallet_items = wallet::GetTestWalletItems();
2007  wallet_items->AddInstrument(wallet::GetTestMaskedInstrument());
2008  controller()->OnDidGetWalletItems(wallet_items.Pass());
2009  controller()->OnAccept();
2010  controller()->OnDidGetFullWallet(wallet::GetTestFullWallet());
2011
2012  EXPECT_TRUE(profile()->GetPrefs()->HasPrefPath(
2013      ::prefs::kAutofillDialogPayWithoutWallet));
2014  EXPECT_FALSE(profile()->GetPrefs()->GetBoolean(
2015      ::prefs::kAutofillDialogPayWithoutWallet));
2016}
2017
2018TEST_F(AutofillDialogControllerTest, HideWalletEmail) {
2019  SwitchToAutofill();
2020
2021  // Email section should be showing when using Autofill.
2022  EXPECT_TRUE(controller()->SectionIsActive(SECTION_EMAIL));
2023
2024  SwitchToWallet();
2025
2026  // Setup some wallet state, submit, and get a full wallet to end the flow.
2027  scoped_ptr<wallet::WalletItems> wallet_items = CompleteAndValidWalletItems();
2028
2029  // Filling |form_structure()| depends on the current username and wallet items
2030  // being fetched. Until both of these have occurred, the user should not be
2031  // able to click Submit if using Wallet. The username fetch happened earlier.
2032  EXPECT_FALSE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_OK));
2033  controller()->OnDidGetWalletItems(wallet_items.Pass());
2034  EXPECT_TRUE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_OK));
2035
2036  // Email section should be hidden when using Wallet.
2037  EXPECT_FALSE(controller()->SectionIsActive(SECTION_EMAIL));
2038
2039  controller()->OnAccept();
2040  controller()->OnDidGetFullWallet(wallet::GetTestFullWallet());
2041
2042  size_t i = 0;
2043  for (; i < form_structure()->field_count(); ++i) {
2044    if (form_structure()->field(i)->Type().server_type() == EMAIL_ADDRESS) {
2045      EXPECT_EQ(ASCIIToUTF16(kFakeEmail), form_structure()->field(i)->value);
2046      break;
2047    }
2048  }
2049  ASSERT_LT(i, form_structure()->field_count());
2050}
2051
2052// Test if autofill types of returned form structure are correct for billing
2053// entries.
2054TEST_F(AutofillDialogControllerTest, AutofillTypes) {
2055  controller()->OnDidGetWalletItems(CompleteAndValidWalletItems());
2056  controller()->OnAccept();
2057  controller()->OnDidGetFullWallet(wallet::GetTestFullWallet());
2058  ASSERT_EQ(20U, form_structure()->field_count());
2059  EXPECT_EQ(EMAIL_ADDRESS, form_structure()->field(0)->Type().server_type());
2060  EXPECT_EQ(CREDIT_CARD_NUMBER,
2061            form_structure()->field(2)->Type().server_type());
2062  EXPECT_EQ(ADDRESS_BILLING_STATE,
2063            form_structure()->field(9)->Type().server_type());
2064  EXPECT_EQ(ADDRESS_HOME_STATE,
2065            form_structure()->field(16)->Type().server_type());
2066}
2067
2068TEST_F(AutofillDialogControllerTest, SaveDetailsInChrome) {
2069  EXPECT_CALL(*controller()->GetView(), ModelChanged()).Times(2);
2070
2071  AutofillProfile full_profile(test::GetVerifiedProfile());
2072  controller()->GetTestingManager()->AddTestingProfile(&full_profile);
2073
2074  CreditCard card(test::GetVerifiedCreditCard());
2075  controller()->GetTestingManager()->AddTestingCreditCard(&card);
2076  EXPECT_FALSE(controller()->ShouldOfferToSaveInChrome());
2077
2078  controller()->EditClickedForSection(SECTION_EMAIL);
2079  EXPECT_TRUE(controller()->ShouldOfferToSaveInChrome());
2080
2081  controller()->EditCancelledForSection(SECTION_EMAIL);
2082  EXPECT_FALSE(controller()->ShouldOfferToSaveInChrome());
2083
2084  controller()->MenuModelForSection(SECTION_EMAIL)->ActivatedAt(1);
2085  EXPECT_TRUE(controller()->ShouldOfferToSaveInChrome());
2086
2087  profile()->set_incognito(true);
2088  EXPECT_FALSE(controller()->ShouldOfferToSaveInChrome());
2089}
2090
2091// Tests that user is prompted when using instrument with minimal address.
2092TEST_F(AutofillDialogControllerTest, UpgradeMinimalAddress) {
2093  // A minimal address being selected should trigger error validation in the
2094  // view. Called once for each incomplete suggestion.
2095  EXPECT_CALL(*controller()->GetView(), UpdateForErrors()).Times(1);
2096
2097  scoped_ptr<wallet::WalletItems> wallet_items = wallet::GetTestWalletItems();
2098  wallet_items->AddInstrument(wallet::GetTestMaskedInstrumentWithIdAndAddress(
2099      "id", wallet::GetTestMinimalAddress()));
2100  scoped_ptr<wallet::Address> address(wallet::GetTestShippingAddress());
2101  address->set_is_complete_address(false);
2102  wallet_items->AddAddress(address.Pass());
2103  controller()->OnDidGetWalletItems(wallet_items.Pass());
2104
2105  // Assert that dialog's SECTION_CC_BILLING section is in edit mode.
2106  ASSERT_TRUE(controller()->IsEditingExistingData(SECTION_CC_BILLING));
2107  // Shipping section should be in edit mode because of
2108  // is_minimal_shipping_address.
2109  ASSERT_TRUE(controller()->IsEditingExistingData(SECTION_SHIPPING));
2110}
2111
2112TEST_F(AutofillDialogControllerTest, RiskNeverLoadsWithPendingLegalDocuments) {
2113  EXPECT_CALL(*controller(), LoadRiskFingerprintData()).Times(0);
2114
2115  scoped_ptr<wallet::WalletItems> wallet_items = wallet::GetTestWalletItems();
2116  wallet_items->AddLegalDocument(wallet::GetTestLegalDocument());
2117  controller()->OnDidGetWalletItems(wallet_items.Pass());
2118  controller()->OnAccept();
2119}
2120
2121TEST_F(AutofillDialogControllerTest, RiskLoadsAfterAcceptingLegalDocuments) {
2122  EXPECT_CALL(*controller(), LoadRiskFingerprintData()).Times(0);
2123
2124  scoped_ptr<wallet::WalletItems> wallet_items = wallet::GetTestWalletItems();
2125  wallet_items->AddLegalDocument(wallet::GetTestLegalDocument());
2126  controller()->OnDidGetWalletItems(wallet_items.Pass());
2127
2128  testing::Mock::VerifyAndClear(controller());
2129  EXPECT_CALL(*controller(), LoadRiskFingerprintData()).Times(1);
2130
2131  controller()->OnAccept();
2132
2133  // Simulate a risk load and verify |GetRiskData()| matches the encoded value.
2134  controller()->OnDidAcceptLegalDocuments();
2135  controller()->OnDidLoadRiskFingerprintData(GetFakeFingerprint().Pass());
2136  EXPECT_EQ(kFakeFingerprintEncoded, controller()->GetRiskData());
2137}
2138
2139TEST_F(AutofillDialogControllerTest, NoManageMenuItemForNewWalletUsers) {
2140  // Make sure the menu model item is created for a returning Wallet user.
2141  scoped_ptr<wallet::WalletItems> wallet_items = wallet::GetTestWalletItems();
2142  wallet_items->AddInstrument(wallet::GetTestMaskedInstrument());
2143  wallet_items->AddAddress(wallet::GetTestShippingAddress());
2144  controller()->OnDidGetWalletItems(wallet_items.Pass());
2145
2146  EXPECT_TRUE(controller()->MenuModelForSection(SECTION_CC_BILLING));
2147  // "Same as billing", "123 address", "Add address...", and "Manage addresses".
2148  EXPECT_EQ(
2149      4, controller()->MenuModelForSection(SECTION_SHIPPING)->GetItemCount());
2150
2151  // Make sure the menu model item is not created for new Wallet users.
2152  base::DictionaryValue dict;
2153  scoped_ptr<base::ListValue> required_actions(new base::ListValue);
2154  required_actions->AppendString("setup_wallet");
2155  dict.Set("required_action", required_actions.release());
2156  controller()->OnDidGetWalletItems(
2157      wallet::WalletItems::CreateWalletItems(dict).Pass());
2158
2159  EXPECT_FALSE(controller()->MenuModelForSection(SECTION_CC_BILLING));
2160  // "Same as billing" and "Add address...".
2161  EXPECT_EQ(
2162      2, controller()->MenuModelForSection(SECTION_SHIPPING)->GetItemCount());
2163}
2164
2165TEST_F(AutofillDialogControllerTest, ShippingSectionCanBeHidden) {
2166  SwitchToAutofill();
2167
2168  FormFieldData email_field;
2169  email_field.autocomplete_attribute = "email";
2170  FormFieldData cc_field;
2171  cc_field.autocomplete_attribute = "cc-number";
2172  FormFieldData billing_field;
2173  billing_field.autocomplete_attribute = "billing region";
2174
2175  FormData form_data;
2176  form_data.fields.push_back(email_field);
2177  form_data.fields.push_back(cc_field);
2178  form_data.fields.push_back(billing_field);
2179
2180  AutofillProfile full_profile(test::GetVerifiedProfile());
2181  controller()->GetTestingManager()->AddTestingProfile(&full_profile);
2182  SetUpControllerWithFormData(form_data);
2183  EXPECT_FALSE(controller()->SectionIsActive(SECTION_SHIPPING));
2184
2185  FillCreditCardInputs();
2186  controller()->OnAccept();
2187  EXPECT_TRUE(form_structure());
2188}
2189
2190TEST_F(AutofillDialogControllerTest, ShippingSectionCanBeHiddenForWallet) {
2191  SwitchToWallet();
2192
2193  FormFieldData email_field;
2194  email_field.autocomplete_attribute = "email";
2195  FormFieldData cc_field;
2196  cc_field.autocomplete_attribute = "cc-number";
2197  FormFieldData billing_field;
2198  billing_field.autocomplete_attribute = "billing region";
2199
2200  FormData form_data;
2201  form_data.fields.push_back(email_field);
2202  form_data.fields.push_back(cc_field);
2203  form_data.fields.push_back(billing_field);
2204
2205  SetUpControllerWithFormData(form_data);
2206  EXPECT_FALSE(controller()->SectionIsActive(SECTION_SHIPPING));
2207  EXPECT_FALSE(controller()->IsShippingAddressRequired());
2208
2209  EXPECT_CALL(*controller()->GetTestingWalletClient(),
2210              GetFullWallet(_)).Times(1);
2211  scoped_ptr<wallet::WalletItems> wallet_items = wallet::GetTestWalletItems();
2212  wallet_items->AddInstrument(wallet::GetTestMaskedInstrument());
2213  SubmitWithWalletItems(wallet_items.Pass());
2214  controller()->OnDidGetFullWallet(wallet::GetTestFullWalletInstrumentOnly());
2215  EXPECT_TRUE(form_structure());
2216}
2217
2218TEST_F(AutofillDialogControllerTest, NotProdNotification) {
2219  // To make IsPayingWithWallet() true.
2220  controller()->OnDidGetWalletItems(wallet::GetTestWalletItems());
2221
2222  CommandLine* command_line = CommandLine::ForCurrentProcess();
2223  ASSERT_FALSE(command_line->HasSwitch(switches::kWalletServiceUseProd));
2224  EXPECT_FALSE(
2225      NotificationsOfType(DialogNotification::DEVELOPER_WARNING).empty());
2226
2227  command_line->AppendSwitch(switches::kWalletServiceUseProd);
2228  EXPECT_TRUE(
2229      NotificationsOfType(DialogNotification::DEVELOPER_WARNING).empty());
2230}
2231
2232// Ensure Wallet instruments marked expired by the server are shown as invalid.
2233TEST_F(AutofillDialogControllerTest, WalletExpiredCard) {
2234  scoped_ptr<wallet::WalletItems> wallet_items = wallet::GetTestWalletItems();
2235  wallet_items->AddInstrument(wallet::GetTestMaskedInstrumentExpired());
2236  controller()->OnDidGetWalletItems(wallet_items.Pass());
2237
2238  EXPECT_TRUE(controller()->IsEditingExistingData(SECTION_CC_BILLING));
2239
2240  // Use |SetOutputValue()| to put the right ServerFieldTypes into the map.
2241  const DetailInputs& inputs =
2242      controller()->RequestedFieldsForSection(SECTION_CC_BILLING);
2243  DetailOutputMap outputs;
2244  SetOutputValue(inputs, &outputs, COMPANY_NAME, ASCIIToUTF16("Bluth Company"));
2245
2246  ValidityData validity_data =
2247      controller()->InputsAreValid(SECTION_CC_BILLING, outputs, VALIDATE_EDIT);
2248  EXPECT_EQ(1U, validity_data.count(CREDIT_CARD_EXP_MONTH));
2249  EXPECT_EQ(1U, validity_data.count(CREDIT_CARD_EXP_4_DIGIT_YEAR));
2250
2251  // Make the local input year differ from the instrument.
2252  SetOutputValue(inputs, &outputs, CREDIT_CARD_EXP_4_DIGIT_YEAR,
2253                 ASCIIToUTF16("3002"));
2254
2255  validity_data =
2256      controller()->InputsAreValid(SECTION_CC_BILLING, outputs, VALIDATE_EDIT);
2257  EXPECT_EQ(0U, validity_data.count(CREDIT_CARD_EXP_MONTH));
2258  EXPECT_EQ(0U, validity_data.count(CREDIT_CARD_EXP_4_DIGIT_YEAR));
2259
2260  // Make the local input month differ from the instrument.
2261  SetOutputValue(inputs, &outputs, CREDIT_CARD_EXP_MONTH, ASCIIToUTF16("06"));
2262
2263  validity_data =
2264      controller()->InputsAreValid(SECTION_CC_BILLING, outputs, VALIDATE_EDIT);
2265  EXPECT_EQ(0U, validity_data.count(CREDIT_CARD_EXP_MONTH));
2266  EXPECT_EQ(0U, validity_data.count(CREDIT_CARD_EXP_4_DIGIT_YEAR));
2267}
2268
2269TEST_F(AutofillDialogControllerTest, ChooseAnotherInstrumentOrAddress) {
2270  SubmitWithWalletItems(CompleteAndValidWalletItems());
2271
2272  EXPECT_EQ(0U, NotificationsOfType(
2273      DialogNotification::REQUIRED_ACTION).size());
2274  EXPECT_CALL(*controller()->GetTestingWalletClient(),
2275              GetWalletItems(_)).Times(1);
2276  controller()->OnDidGetFullWallet(
2277      CreateFullWallet("choose_another_instrument_or_address"));
2278  EXPECT_EQ(1U, NotificationsOfType(
2279      DialogNotification::REQUIRED_ACTION).size());
2280  controller()->OnDidGetWalletItems(CompleteAndValidWalletItems());
2281
2282  controller()->OnAccept();
2283  EXPECT_EQ(0U, NotificationsOfType(
2284      DialogNotification::REQUIRED_ACTION).size());
2285}
2286
2287// Make sure detailed steps for Autocheckout are added
2288// and updated correctly.
2289TEST_F(AutofillDialogControllerTest, DetailedSteps) {
2290  EXPECT_CALL(*controller()->GetTestingWalletClient(),
2291              GetFullWallet(_)).Times(1);
2292
2293  controller()->set_dialog_type(DIALOG_TYPE_AUTOCHECKOUT);
2294
2295  // Add steps as would normally be done by the AutocheckoutManager.
2296  controller()->AddAutocheckoutStep(AUTOCHECKOUT_STEP_SHIPPING);
2297  controller()->AddAutocheckoutStep(AUTOCHECKOUT_STEP_DELIVERY);
2298  controller()->AddAutocheckoutStep(AUTOCHECKOUT_STEP_BILLING);
2299
2300  scoped_ptr<wallet::WalletItems> wallet_items = wallet::GetTestWalletItems();
2301  wallet_items->AddInstrument(wallet::GetTestMaskedInstrument());
2302  wallet_items->AddAddress(wallet::GetTestShippingAddress());
2303  controller()->OnDidGetWalletItems(wallet_items.Pass());
2304  // Initiate flow - should add proxy card step since the user is using wallet
2305  // data.
2306  controller()->OnAccept();
2307  EXPECT_TRUE(ReadSetVisuallyDeemphasizedIpc());
2308  controller()->OnDidLoadRiskFingerprintData(GetFakeFingerprint().Pass());
2309
2310  SuggestionState suggestion_state =
2311      controller()->SuggestionStateForSection(SECTION_CC_BILLING);
2312  EXPECT_TRUE(suggestion_state.extra_text.empty());
2313
2314  // There should be four steps total, with the first being the card generation
2315  // step added by the dialog controller.
2316  EXPECT_EQ(4U, controller()->CurrentAutocheckoutSteps().size());
2317  EXPECT_EQ(AUTOCHECKOUT_STEP_PROXY_CARD,
2318            controller()->CurrentAutocheckoutSteps()[0].type());
2319  EXPECT_EQ(AUTOCHECKOUT_STEP_STARTED,
2320            controller()->CurrentAutocheckoutSteps()[0].status());
2321
2322  // Simulate a wallet error. This should remove the card generation step from
2323  // the flow, as we will have to proceed with local data.
2324  controller()->OnWalletError(wallet::WalletClient::UNKNOWN_ERROR);
2325
2326  AutofillProfile shipping_profile(test::GetVerifiedProfile());
2327  AutofillProfile billing_profile(test::GetVerifiedProfile2());
2328  CreditCard credit_card(test::GetVerifiedCreditCard());
2329  controller()->GetTestingManager()->AddTestingProfile(&shipping_profile);
2330  controller()->GetTestingManager()->AddTestingProfile(&billing_profile);
2331  controller()->GetTestingManager()->AddTestingCreditCard(&credit_card);
2332  ui::MenuModel* billing_model =
2333      controller()->MenuModelForSection(SECTION_BILLING);
2334  billing_model->ActivatedAt(1);
2335
2336  // Re-initiate flow.
2337  controller()->OnAccept();
2338  EXPECT_TRUE(ReadSetVisuallyDeemphasizedIpc());
2339
2340  // All steps should be initially unstarted.
2341  EXPECT_EQ(3U, controller()->CurrentAutocheckoutSteps().size());
2342  EXPECT_EQ(AUTOCHECKOUT_STEP_SHIPPING,
2343            controller()->CurrentAutocheckoutSteps()[0].type());
2344  EXPECT_EQ(AUTOCHECKOUT_STEP_UNSTARTED,
2345            controller()->CurrentAutocheckoutSteps()[0].status());
2346  EXPECT_EQ(AUTOCHECKOUT_STEP_DELIVERY,
2347            controller()->CurrentAutocheckoutSteps()[1].type());
2348  EXPECT_EQ(AUTOCHECKOUT_STEP_UNSTARTED,
2349            controller()->CurrentAutocheckoutSteps()[1].status());
2350  EXPECT_EQ(AUTOCHECKOUT_STEP_BILLING,
2351            controller()->CurrentAutocheckoutSteps()[2].type());
2352  EXPECT_EQ(AUTOCHECKOUT_STEP_UNSTARTED,
2353            controller()->CurrentAutocheckoutSteps()[2].status());
2354
2355  // Update steps in the same manner that we would expect to see from the
2356  // AutocheckoutManager while progressing through a flow.
2357  controller()->UpdateAutocheckoutStep(AUTOCHECKOUT_STEP_SHIPPING,
2358                                       AUTOCHECKOUT_STEP_STARTED);
2359  controller()->UpdateAutocheckoutStep(AUTOCHECKOUT_STEP_SHIPPING,
2360                                       AUTOCHECKOUT_STEP_COMPLETED);
2361  controller()->UpdateAutocheckoutStep(AUTOCHECKOUT_STEP_DELIVERY,
2362                                       AUTOCHECKOUT_STEP_STARTED);
2363
2364  // Verify that the steps were appropriately updated.
2365  EXPECT_EQ(3U, controller()->CurrentAutocheckoutSteps().size());
2366  EXPECT_EQ(AUTOCHECKOUT_STEP_SHIPPING,
2367            controller()->CurrentAutocheckoutSteps()[0].type());
2368  EXPECT_EQ(AUTOCHECKOUT_STEP_COMPLETED,
2369            controller()->CurrentAutocheckoutSteps()[0].status());
2370  EXPECT_EQ(AUTOCHECKOUT_STEP_DELIVERY,
2371            controller()->CurrentAutocheckoutSteps()[1].type());
2372  EXPECT_EQ(AUTOCHECKOUT_STEP_STARTED,
2373            controller()->CurrentAutocheckoutSteps()[1].status());
2374  EXPECT_EQ(AUTOCHECKOUT_STEP_BILLING,
2375            controller()->CurrentAutocheckoutSteps()[2].type());
2376  EXPECT_EQ(AUTOCHECKOUT_STEP_UNSTARTED,
2377            controller()->CurrentAutocheckoutSteps()[2].status());
2378
2379  controller()->ViewClosed();
2380  EXPECT_FALSE(ReadSetVisuallyDeemphasizedIpc());
2381}
2382
2383
2384TEST_F(AutofillDialogControllerTest, NewCardBubbleShown) {
2385  EXPECT_CALL(*test_bubble_controller(),
2386              ShowAsNewCardSavedBubble(ASCIIToUTF16("Visa - 1111"))).Times(1);
2387  EXPECT_CALL(*test_bubble_controller(),
2388              ShowAsGeneratedCardBubble(_, _)).Times(0);
2389
2390  SwitchToAutofill();
2391  FillCreditCardInputs();
2392  controller()->OnAccept();
2393  controller()->ViewClosed();
2394}
2395
2396TEST_F(AutofillDialogControllerTest, GeneratedCardBubbleShown) {
2397  EXPECT_CALL(*test_bubble_controller(),
2398              ShowAsGeneratedCardBubble(_, _)).Times(1);
2399  EXPECT_CALL(*test_bubble_controller(), ShowAsNewCardSavedBubble(_)).Times(0);
2400
2401  SubmitWithWalletItems(CompleteAndValidWalletItems());
2402  controller()->OnDidGetFullWallet(wallet::GetTestFullWallet());
2403  controller()->ViewClosed();
2404}
2405
2406TEST_F(AutofillDialogControllerTest, ReloadWalletItemsOnActivation) {
2407  // Switch into Wallet mode and initialize some Wallet data.
2408  SwitchToWallet();
2409
2410  scoped_ptr<wallet::WalletItems> wallet_items = wallet::GetTestWalletItems();
2411  wallet_items->AddInstrument(wallet::GetTestMaskedInstrument());
2412  wallet_items->AddInstrument(wallet::GetTestNonDefaultMaskedInstrument());
2413  wallet_items->AddAddress(wallet::GetTestNonDefaultShippingAddress());
2414  wallet_items->AddAddress(wallet::GetTestShippingAddress());
2415  controller()->OnDidGetWalletItems(wallet_items.Pass());
2416
2417  // Initially, the default entries should be selected.
2418  ui::MenuModel* cc_billing_model =
2419      controller()->MenuModelForSection(SECTION_CC_BILLING);
2420  ui::MenuModel* shipping_model =
2421      controller()->MenuModelForSection(SECTION_SHIPPING);
2422  // "add", "manage", and 2 suggestions.
2423  ASSERT_EQ(4, cc_billing_model->GetItemCount());
2424  EXPECT_TRUE(cc_billing_model->IsItemCheckedAt(0));
2425  // "use billing", "add", "manage", and 2 suggestions.
2426  ASSERT_EQ(5, shipping_model->GetItemCount());
2427  EXPECT_TRUE(shipping_model->IsItemCheckedAt(2));
2428
2429  // Select entries other than the defaults.
2430  cc_billing_model->ActivatedAt(1);
2431  shipping_model->ActivatedAt(1);
2432  // "add", "manage", and 2 suggestions.
2433  ASSERT_EQ(4, cc_billing_model->GetItemCount());
2434  EXPECT_TRUE(cc_billing_model->IsItemCheckedAt(1));
2435  // "use billing", "add", "manage", and 2 suggestions.
2436  ASSERT_EQ(5, shipping_model->GetItemCount());
2437  EXPECT_TRUE(shipping_model-> IsItemCheckedAt(1));
2438
2439  // Simulate switching away from the tab and back.  This should issue a request
2440  // for wallet items.
2441  EXPECT_CALL(*controller()->GetTestingWalletClient(), GetWalletItems(_));
2442  controller()->TabActivated();
2443
2444  // Simulate a response that includes different items.
2445  wallet_items = wallet::GetTestWalletItems();
2446  wallet_items->AddInstrument(wallet::GetTestMaskedInstrumentExpired());
2447  wallet_items->AddInstrument(wallet::GetTestMaskedInstrument());
2448  wallet_items->AddInstrument(wallet::GetTestNonDefaultMaskedInstrument());
2449  wallet_items->AddAddress(wallet::GetTestNonDefaultShippingAddress());
2450  controller()->OnDidGetWalletItems(wallet_items.Pass());
2451
2452  // The previously selected entries should still be selected.
2453  // "add", "manage", and 3 suggestions.
2454  ASSERT_EQ(5, cc_billing_model->GetItemCount());
2455  EXPECT_TRUE(cc_billing_model->IsItemCheckedAt(2));
2456  // "use billing", "add", "manage", and 1 suggestion.
2457  ASSERT_EQ(4, shipping_model->GetItemCount());
2458  EXPECT_TRUE(shipping_model->IsItemCheckedAt(1));
2459}
2460
2461TEST_F(AutofillDialogControllerTest, ReloadWithEmptyWalletItems) {
2462  SwitchToWallet();
2463
2464  controller()->OnDidGetWalletItems(CompleteAndValidWalletItems());
2465  controller()->MenuModelForSection(SECTION_CC_BILLING)->ActivatedAt(1);
2466  controller()->MenuModelForSection(SECTION_SHIPPING)->ActivatedAt(1);
2467
2468  EXPECT_CALL(*controller()->GetTestingWalletClient(), GetWalletItems(_));
2469  controller()->TabActivated();
2470
2471  controller()->OnDidGetWalletItems(wallet::GetTestWalletItems());
2472
2473  EXPECT_FALSE(controller()->MenuModelForSection(SECTION_CC_BILLING));
2474  EXPECT_EQ(
2475      3, controller()->MenuModelForSection(SECTION_SHIPPING)->GetItemCount());
2476}
2477
2478TEST_F(AutofillDialogControllerTest, GeneratedCardBubbleNotShown) {
2479  EXPECT_CALL(*test_bubble_controller(),
2480              ShowAsGeneratedCardBubble(_, _)).Times(0);
2481  EXPECT_CALL(*test_bubble_controller(), ShowAsNewCardSavedBubble(_)).Times(0);
2482
2483  SubmitWithWalletItems(CompleteAndValidWalletItems());
2484  controller()->set_dialog_type(DIALOG_TYPE_AUTOCHECKOUT);
2485  controller()->OnDidGetFullWallet(wallet::GetTestFullWallet());
2486  controller()->OnAutocheckoutError();
2487  controller()->ViewClosed();
2488}
2489
2490}  // namespace autofill
2491