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