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