autofill_dialog_controller_unittest.cc revision f8ee788a64d60abd8f2d742a5fdedde054ecd910
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/bind_helpers.h"
9#include "base/callback.h"
10#include "base/command_line.h"
11#include "base/guid.h"
12#include "base/memory/scoped_ptr.h"
13#include "base/message_loop/message_loop.h"
14#include "base/prefs/pref_service.h"
15#include "base/run_loop.h"
16#include "base/strings/string_number_conversions.h"
17#include "base/strings/string_piece.h"
18#include "base/strings/utf_string_conversions.h"
19#include "base/tuple.h"
20#include "chrome/browser/ui/autofill/autofill_dialog_controller_impl.h"
21#include "chrome/browser/ui/autofill/autofill_dialog_i18n_input.h"
22#include "chrome/browser/ui/autofill/autofill_dialog_view.h"
23#include "chrome/browser/ui/autofill/generated_credit_card_bubble_controller.h"
24#include "chrome/browser/ui/autofill/mock_address_validator.h"
25#include "chrome/browser/ui/autofill/mock_new_credit_card_bubble_controller.h"
26#include "chrome/browser/ui/autofill/test_generated_credit_card_bubble_controller.h"
27#include "chrome/browser/webdata/web_data_service_factory.h"
28#include "chrome/common/chrome_switches.h"
29#include "chrome/common/pref_names.h"
30#include "chrome/common/render_messages.h"
31#include "chrome/test/base/chrome_render_view_host_test_harness.h"
32#include "chrome/test/base/scoped_testing_local_state.h"
33#include "chrome/test/base/testing_browser_process.h"
34#include "chrome/test/base/testing_profile.h"
35#include "components/autofill/content/browser/risk/proto/fingerprint.pb.h"
36#include "components/autofill/content/browser/wallet/full_wallet.h"
37#include "components/autofill/content/browser/wallet/gaia_account.h"
38#include "components/autofill/content/browser/wallet/instrument.h"
39#include "components/autofill/content/browser/wallet/mock_wallet_client.h"
40#include "components/autofill/content/browser/wallet/wallet_address.h"
41#include "components/autofill/content/browser/wallet/wallet_service_url.h"
42#include "components/autofill/content/browser/wallet/wallet_test_util.h"
43#include "components/autofill/core/browser/autofill_metrics.h"
44#include "components/autofill/core/browser/autofill_test_utils.h"
45#include "components/autofill/core/browser/test_personal_data_manager.h"
46#include "components/autofill/core/browser/webdata/autofill_webdata_service.h"
47#include "components/autofill/core/common/autofill_switches.h"
48#include "components/autofill/core/common/form_data.h"
49#include "components/user_prefs/user_prefs.h"
50#include "content/public/browser/web_contents.h"
51#include "content/public/test/mock_render_process_host.h"
52#include "google_apis/gaia/google_service_auth_error.h"
53#include "grit/component_scaled_resources.h"
54#include "grit/generated_resources.h"
55#include "testing/gmock/include/gmock/gmock.h"
56#include "testing/gtest/include/gtest/gtest.h"
57#include "third_party/libaddressinput/chromium/cpp/include/libaddressinput/address_data.h"
58#include "third_party/libaddressinput/chromium/cpp/include/libaddressinput/address_validator.h"
59#include "ui/base/resource/resource_bundle.h"
60
61#if defined(OS_WIN)
62#include "ui/base/win/scoped_ole_initializer.h"
63#endif
64
65using base::ASCIIToUTF16;
66using base::UTF8ToUTF16;
67
68namespace autofill {
69
70namespace {
71
72using ::i18n::addressinput::AddressData;
73using ::i18n::addressinput::AddressProblemFilter;
74using ::i18n::addressinput::AddressProblem;
75using ::i18n::addressinput::AddressProblems;
76using ::i18n::addressinput::AddressValidator;
77using testing::AtLeast;
78using testing::DoAll;
79using testing::Return;
80using testing::SetArgPointee;
81using testing::_;
82
83const char kSourceUrl[] = "http://localbike.shop";
84const char kFakeEmail[] = "user@chromium.org";
85const char kFakeFingerprintEncoded[] = "CgVaAwiACA==";
86const char kEditedBillingAddress[] = "123 edited billing address";
87const char* kFieldsFromPage[] =
88    { "email",
89      "cc-name",
90      "cc-number",
91      "cc-exp-month",
92      "cc-exp-year",
93      "cc-csc",
94      "billing name",
95      "billing address-line1",
96      "billing address-level2",
97      "billing address-level1",
98      "billing postal-code",
99      "billing country",
100      "billing tel",
101      "shipping name",
102      "shipping address-line1",
103      "shipping address-level2",
104      "shipping address-level1",
105      "shipping postal-code",
106      "shipping country",
107      "shipping tel",
108    };
109const char kSettingsOrigin[] = "Chrome settings";
110const char kTestCCNumberAmex[] = "376200000000002";
111const char kTestCCNumberVisa[] = "4111111111111111";
112const char kTestCCNumberMaster[] = "5555555555554444";
113const char kTestCCNumberDiscover[] = "6011111111111117";
114const char kTestCCNumberIncomplete[] = "4111111111";
115// Credit card number fails Luhn check.
116const char kTestCCNumberInvalid[] = "4111111111111112";
117
118// Copies the initial values from |inputs| into |outputs|.
119void CopyInitialValues(const DetailInputs& inputs, FieldValueMap* outputs) {
120  for (size_t i = 0; i < inputs.size(); ++i) {
121    const DetailInput& input = inputs[i];
122    (*outputs)[input.type] = input.initial_value;
123  }
124}
125
126scoped_ptr<wallet::WalletItems> CompleteAndValidWalletItems() {
127  scoped_ptr<wallet::WalletItems> items =
128      wallet::GetTestWalletItems(wallet::AMEX_DISALLOWED);
129  items->AddAccount(wallet::GetTestGaiaAccount());
130  items->AddInstrument(wallet::GetTestMaskedInstrument());
131  items->AddAddress(wallet::GetTestShippingAddress());
132  return items.Pass();
133}
134
135scoped_ptr<risk::Fingerprint> GetFakeFingerprint() {
136  scoped_ptr<risk::Fingerprint> fingerprint(new risk::Fingerprint());
137  // Add some data to the proto, else the encoded content is empty.
138  fingerprint->mutable_machine_characteristics()->mutable_screen_size()->
139      set_width(1024);
140  return fingerprint.Pass();
141}
142
143bool HasAnyError(const ValidityMessages& messages, ServerFieldType field) {
144  return !messages.GetMessageOrDefault(field).text.empty();
145}
146
147bool HasUnsureError(const ValidityMessages& messages, ServerFieldType field) {
148  const ValidityMessage& message = messages.GetMessageOrDefault(field);
149  return !message.text.empty() && !message.sure;
150}
151
152class TestAutofillDialogView : public AutofillDialogView {
153 public:
154  TestAutofillDialogView()
155      : updates_started_(0), save_details_locally_checked_(true) {}
156  virtual ~TestAutofillDialogView() {}
157
158  virtual void Show() OVERRIDE {}
159  virtual void Hide() OVERRIDE {}
160
161  virtual void UpdatesStarted() OVERRIDE {
162    updates_started_++;
163  }
164
165  virtual void UpdatesFinished() OVERRIDE {
166    updates_started_--;
167    EXPECT_GE(updates_started_, 0);
168  }
169
170  virtual void UpdateNotificationArea() OVERRIDE {
171    EXPECT_GE(updates_started_, 1);
172  }
173
174  virtual void UpdateAccountChooser() OVERRIDE {
175    EXPECT_GE(updates_started_, 1);
176  }
177
178  virtual void UpdateButtonStrip() OVERRIDE {
179    EXPECT_GE(updates_started_, 1);
180  }
181
182  virtual void UpdateOverlay() OVERRIDE {
183    EXPECT_GE(updates_started_, 1);
184  }
185
186  virtual void UpdateDetailArea() OVERRIDE {
187    EXPECT_GE(updates_started_, 1);
188  }
189
190  virtual void UpdateSection(DialogSection section) OVERRIDE {
191    section_updates_[section]++;
192    EXPECT_GE(updates_started_, 1);
193  }
194
195  virtual void UpdateErrorBubble() OVERRIDE {
196    EXPECT_GE(updates_started_, 1);
197  }
198
199  virtual void FillSection(DialogSection section,
200                           ServerFieldType originating_type) OVERRIDE {}
201  virtual void GetUserInput(DialogSection section, FieldValueMap* output)
202      OVERRIDE {
203    *output = outputs_[section];
204  }
205
206  virtual base::string16 GetCvc() OVERRIDE { return base::string16(); }
207
208  virtual bool SaveDetailsLocally() OVERRIDE {
209    return save_details_locally_checked_;
210  }
211
212  virtual const content::NavigationController* ShowSignIn() OVERRIDE {
213    return NULL;
214  }
215  virtual void HideSignIn() OVERRIDE {}
216
217  MOCK_METHOD0(ModelChanged, void());
218  MOCK_METHOD0(UpdateForErrors, void());
219
220  virtual void OnSignInResize(const gfx::Size& pref_size) OVERRIDE {}
221  virtual void ValidateSection(DialogSection) OVERRIDE {}
222
223  void SetUserInput(DialogSection section, const FieldValueMap& map) {
224    outputs_[section] = map;
225  }
226
227  void CheckSaveDetailsLocallyCheckbox(bool checked) {
228    save_details_locally_checked_ = checked;
229  }
230
231  void ClearSectionUpdates() {
232    section_updates_.clear();
233  }
234
235  std::map<DialogSection, size_t> section_updates() const {
236    return section_updates_;
237  }
238
239 private:
240  std::map<DialogSection, FieldValueMap> outputs_;
241  std::map<DialogSection, size_t> section_updates_;
242
243  int updates_started_;
244  bool save_details_locally_checked_;
245
246  DISALLOW_COPY_AND_ASSIGN(TestAutofillDialogView);
247};
248
249class TestAutofillDialogController
250    : public AutofillDialogControllerImpl,
251      public base::SupportsWeakPtr<TestAutofillDialogController> {
252 public:
253  TestAutofillDialogController(
254      content::WebContents* contents,
255      const FormData& form_structure,
256      const GURL& source_url,
257      const AutofillMetrics& metric_logger,
258      const AutofillClient::ResultCallback& callback,
259      MockNewCreditCardBubbleController* mock_new_card_bubble_controller)
260      : AutofillDialogControllerImpl(contents,
261                                     form_structure,
262                                     source_url,
263                                     callback),
264        metric_logger_(metric_logger),
265        mock_wallet_client_(
266            Profile::FromBrowserContext(contents->GetBrowserContext())
267                ->GetRequestContext(),
268            this,
269            source_url),
270        mock_new_card_bubble_controller_(mock_new_card_bubble_controller),
271        submit_button_delay_count_(0) {}
272
273  virtual ~TestAutofillDialogController() {}
274
275  virtual AutofillDialogView* CreateView() OVERRIDE {
276    return new testing::NiceMock<TestAutofillDialogView>();
277  }
278
279  void Init(content::BrowserContext* browser_context) {
280    test_manager_.Init(
281        WebDataServiceFactory::GetAutofillWebDataForProfile(
282            Profile::FromBrowserContext(browser_context),
283            Profile::EXPLICIT_ACCESS),
284        user_prefs::UserPrefs::Get(browser_context),
285        browser_context->IsOffTheRecord());
286  }
287
288  TestAutofillDialogView* GetView() {
289    return static_cast<TestAutofillDialogView*>(view());
290  }
291
292  TestPersonalDataManager* GetTestingManager() {
293    return &test_manager_;
294  }
295
296  MockAddressValidator* GetMockValidator() {
297    return &mock_validator_;
298  }
299
300  wallet::MockWalletClient* GetTestingWalletClient() {
301    return &mock_wallet_client_;
302  }
303
304  const GURL& open_tab_url() { return open_tab_url_; }
305
306  void SimulateSigninError() {
307    OnWalletSigninError();
308  }
309
310  // Skips past the 2 second wait between FinishSubmit and DoFinishSubmit.
311  void ForceFinishSubmit() {
312    DoFinishSubmit();
313  }
314
315  void SimulateSubmitButtonDelayBegin() {
316    AutofillDialogControllerImpl::SubmitButtonDelayBegin();
317  }
318
319  void SimulateSubmitButtonDelayEnd() {
320    AutofillDialogControllerImpl::SubmitButtonDelayEndForTesting();
321  }
322
323  using AutofillDialogControllerImpl::
324      ClearLastWalletItemsFetchTimestampForTesting;
325
326  // Returns the number of times that the submit button was delayed.
327  int get_submit_button_delay_count() const {
328    return submit_button_delay_count_;
329  }
330
331  MOCK_METHOD0(LoadRiskFingerprintData, void());
332  using AutofillDialogControllerImpl::AccountChooserModelForTesting;
333  using AutofillDialogControllerImpl::OnDidLoadRiskFingerprintData;
334  using AutofillDialogControllerImpl::IsEditingExistingData;
335  using AutofillDialogControllerImpl::IsManuallyEditingSection;
336  using AutofillDialogControllerImpl::IsPayingWithWallet;
337  using AutofillDialogControllerImpl::IsSubmitPausedOn;
338  using AutofillDialogControllerImpl::NOT_CHECKED;
339  using AutofillDialogControllerImpl::popup_input_type;
340  using AutofillDialogControllerImpl::SignedInState;
341
342 protected:
343  virtual PersonalDataManager* GetManager() const OVERRIDE {
344    return const_cast<TestAutofillDialogController*>(this)->
345        GetTestingManager();
346  }
347
348  virtual AddressValidator* GetValidator() OVERRIDE {
349    return &mock_validator_;
350  }
351
352  virtual wallet::WalletClient* GetWalletClient() OVERRIDE {
353    return &mock_wallet_client_;
354  }
355
356  virtual void OpenTabWithUrl(const GURL& url) OVERRIDE {
357    open_tab_url_ = url;
358  }
359
360  virtual void ShowNewCreditCardBubble(
361      scoped_ptr<CreditCard> new_card,
362      scoped_ptr<AutofillProfile> billing_profile) OVERRIDE {
363    mock_new_card_bubble_controller_->Show(new_card.Pass(),
364                                           billing_profile.Pass());
365  }
366
367  // AutofillDialogControllerImpl calls this method before showing the dialog
368  // window.
369  virtual void SubmitButtonDelayBegin() OVERRIDE {
370    // Do not delay enabling the submit button in testing.
371    submit_button_delay_count_++;
372  }
373
374 private:
375  // To specify our own metric logger.
376  virtual const AutofillMetrics& GetMetricLogger() const OVERRIDE {
377    return metric_logger_;
378  }
379
380  const AutofillMetrics& metric_logger_;
381  TestPersonalDataManager test_manager_;
382  testing::NiceMock<wallet::MockWalletClient> mock_wallet_client_;
383
384  // A mock validator object to prevent network requests and track when
385  // validation rules are loaded or validation attempts occur.
386  testing::NiceMock<MockAddressValidator> mock_validator_;
387
388  GURL open_tab_url_;
389  MockNewCreditCardBubbleController* mock_new_card_bubble_controller_;
390
391  // The number of times that the submit button was delayed.
392  int submit_button_delay_count_;
393
394  DISALLOW_COPY_AND_ASSIGN(TestAutofillDialogController);
395};
396
397class AutofillDialogControllerTest : public ChromeRenderViewHostTestHarness {
398 protected:
399  AutofillDialogControllerTest(): form_structure_(NULL) {}
400
401  // testing::Test implementation:
402  virtual void SetUp() OVERRIDE {
403    ChromeRenderViewHostTestHarness::SetUp();
404    Reset();
405  }
406
407  virtual void TearDown() OVERRIDE {
408    if (controller_)
409      controller_->ViewClosed();
410    ChromeRenderViewHostTestHarness::TearDown();
411  }
412
413  void Reset() {
414    if (controller_)
415      controller_->ViewClosed();
416
417    test_generated_bubble_controller_ =
418        new testing::NiceMock<TestGeneratedCreditCardBubbleController>(
419            web_contents());
420    ASSERT_TRUE(test_generated_bubble_controller_->IsInstalled());
421
422    mock_new_card_bubble_controller_.reset(
423        new MockNewCreditCardBubbleController);
424
425    profile()->GetPrefs()->ClearPref(::prefs::kAutofillDialogSaveData);
426
427    // We have to clear the old local state before creating a new one.
428    scoped_local_state_.reset();
429    scoped_local_state_.reset(new ScopedTestingLocalState(
430        TestingBrowserProcess::GetGlobal()));
431
432    SetUpControllerWithFormData(DefaultFormData());
433  }
434
435  FormData DefaultFormData() {
436    FormData form_data;
437    for (size_t i = 0; i < arraysize(kFieldsFromPage); ++i) {
438      FormFieldData field;
439      field.autocomplete_attribute = kFieldsFromPage[i];
440      form_data.fields.push_back(field);
441    }
442    return form_data;
443  }
444
445  // Creates a new controller for |form_data|.
446  void ResetControllerWithFormData(const FormData& form_data) {
447    if (controller_)
448      controller_->ViewClosed();
449
450    AutofillClient::ResultCallback callback =
451        base::Bind(&AutofillDialogControllerTest::FinishedCallback,
452                   base::Unretained(this));
453    controller_ = (new testing::NiceMock<TestAutofillDialogController>(
454        web_contents(),
455        form_data,
456        GURL(kSourceUrl),
457        metric_logger_,
458        callback,
459        mock_new_card_bubble_controller_.get()))->AsWeakPtr();
460    controller_->Init(profile());
461  }
462
463  // Creates a new controller for |form_data| and sets up some initial wallet
464  // data for it.
465  void SetUpControllerWithFormData(const FormData& form_data) {
466    ResetControllerWithFormData(form_data);
467    controller()->Show();
468    if (controller() &&
469        !profile()->GetPrefs()->GetBoolean(
470            ::prefs::kAutofillDialogPayWithoutWallet)) {
471      EXPECT_CALL(*controller()->GetTestingWalletClient(), GetWalletItems());
472      controller()->OnDidFetchWalletCookieValue(std::string());
473      controller()->OnDidGetWalletItems(CompleteAndValidWalletItems());
474    }
475  }
476
477  // Fills the inputs in SECTION_CC with data.
478  void FillCreditCardInputs() {
479    FieldValueMap cc_outputs;
480    const DetailInputs& cc_inputs =
481        controller()->RequestedFieldsForSection(SECTION_CC);
482    for (size_t i = 0; i < cc_inputs.size(); ++i) {
483      cc_outputs[cc_inputs[i].type] = cc_inputs[i].type == CREDIT_CARD_NUMBER ?
484          ASCIIToUTF16(kTestCCNumberVisa) : ASCIIToUTF16("11");
485    }
486    controller()->GetView()->SetUserInput(SECTION_CC, cc_outputs);
487  }
488
489  // Fills the inputs in SECTION_CC_BILLING with valid data.
490  void FillCCBillingInputs() {
491    FieldValueMap outputs;
492    const DetailInputs& inputs =
493        controller()->RequestedFieldsForSection(SECTION_CC_BILLING);
494    AutofillProfile full_profile(test::GetVerifiedProfile());
495    CreditCard full_card(test::GetCreditCard());
496    for (size_t i = 0; i < inputs.size(); ++i) {
497      const ServerFieldType type = inputs[i].type;
498      outputs[type] = full_profile.GetInfo(AutofillType(type), "en-US");
499
500      if (outputs[type].empty())
501        outputs[type] = full_card.GetInfo(AutofillType(type), "en-US");
502    }
503    controller()->GetView()->SetUserInput(SECTION_CC_BILLING, outputs);
504  }
505
506  // Activates the 'Add new foo' option from the |section|'s suggestions
507  // dropdown and fills the |section|'s inputs with the data from the
508  // |data_model|.  If |section| is SECTION_CC, also fills in '123' for the CVC.
509  void FillInputs(DialogSection section, const AutofillDataModel& data_model) {
510    // Select the 'Add new foo' option.
511    ui::MenuModel* model = GetMenuModelForSection(section);
512    if (model)
513      model->ActivatedAt(model->GetItemCount() - 2);
514
515    // Fill the inputs.
516    FieldValueMap outputs;
517    const DetailInputs& inputs =
518        controller()->RequestedFieldsForSection(section);
519    for (size_t i = 0; i < inputs.size(); ++i) {
520      ServerFieldType type = inputs[i].type;
521      base::string16 output;
522      if (type == CREDIT_CARD_VERIFICATION_CODE)
523        output = ASCIIToUTF16("123");
524      else
525        output = data_model.GetInfo(AutofillType(type), "en-US");
526      outputs[inputs[i].type] = output;
527    }
528    controller()->GetView()->SetUserInput(section, outputs);
529  }
530
531  std::vector<DialogNotification> NotificationsOfType(
532      DialogNotification::Type type) {
533    std::vector<DialogNotification> right_type;
534    const std::vector<DialogNotification>& notifications =
535        controller()->CurrentNotifications();
536    for (size_t i = 0; i < notifications.size(); ++i) {
537      if (notifications[i].type() == type)
538        right_type.push_back(notifications[i]);
539    }
540    return right_type;
541  }
542
543  void SwitchToAutofill() {
544    ui::MenuModel* model = controller_->MenuModelForAccountChooser();
545    model->ActivatedAt(model->GetItemCount() - 1);
546  }
547
548  void SwitchToWallet() {
549    controller_->MenuModelForAccountChooser()->ActivatedAt(0);
550  }
551
552  void SimulateSigninError() {
553    controller_->SimulateSigninError();
554  }
555
556  void UseBillingForShipping() {
557    controller()->MenuModelForSection(SECTION_SHIPPING)->ActivatedAt(0);
558  }
559
560  void ValidateCCNumber(DialogSection section,
561                        const std::string& cc_number,
562                        bool should_pass) {
563    FieldValueMap outputs;
564    outputs[ADDRESS_BILLING_COUNTRY] = ASCIIToUTF16("United States");
565    outputs[CREDIT_CARD_NUMBER] = UTF8ToUTF16(cc_number);
566    ValidityMessages messages =
567        controller()->InputsAreValid(section, outputs);
568    EXPECT_EQ(should_pass, !messages.HasSureError(CREDIT_CARD_NUMBER));
569  }
570
571  void SubmitWithWalletItems(scoped_ptr<wallet::WalletItems> wallet_items) {
572    controller()->OnDidGetWalletItems(wallet_items.Pass());
573    AcceptAndLoadFakeFingerprint();
574  }
575
576  void AcceptAndLoadFakeFingerprint() {
577    controller()->OnAccept();
578    controller()->OnDidLoadRiskFingerprintData(GetFakeFingerprint().Pass());
579  }
580
581  // Returns true if the given |section| contains a field of the given |type|.
582  bool SectionContainsField(DialogSection section, ServerFieldType type) {
583    const DetailInputs& inputs =
584        controller()->RequestedFieldsForSection(section);
585    for (DetailInputs::const_iterator it = inputs.begin(); it != inputs.end();
586         ++it) {
587      if (it->type == type)
588        return true;
589    }
590    return false;
591  }
592
593  SuggestionsMenuModel* GetMenuModelForSection(DialogSection section) {
594    ui::MenuModel* model = controller()->MenuModelForSection(section);
595    return static_cast<SuggestionsMenuModel*>(model);
596  }
597
598  void SubmitAndVerifyShippingAndBillingResults() {
599    // Test after setting use billing for shipping.
600    UseBillingForShipping();
601
602    controller()->OnAccept();
603
604    ASSERT_EQ(20U, form_structure()->field_count());
605    EXPECT_EQ(ADDRESS_HOME_COUNTRY,
606              form_structure()->field(11)->Type().GetStorableType());
607    EXPECT_EQ(ADDRESS_BILLING, form_structure()->field(11)->Type().group());
608    EXPECT_EQ(ADDRESS_HOME_COUNTRY,
609              form_structure()->field(18)->Type().GetStorableType());
610    EXPECT_EQ(ADDRESS_HOME, form_structure()->field(18)->Type().group());
611    base::string16 billing_country = form_structure()->field(11)->value;
612    EXPECT_EQ(2U, billing_country.size());
613    base::string16 shipping_country = form_structure()->field(18)->value;
614    EXPECT_EQ(2U, shipping_country.size());
615    EXPECT_FALSE(billing_country.empty());
616    EXPECT_FALSE(shipping_country.empty());
617    EXPECT_EQ(billing_country, shipping_country);
618
619    EXPECT_EQ(CREDIT_CARD_NAME,
620              form_structure()->field(1)->Type().GetStorableType());
621    base::string16 cc_name = form_structure()->field(1)->value;
622    EXPECT_EQ(NAME_FULL, form_structure()->field(6)->Type().GetStorableType());
623    EXPECT_EQ(NAME_BILLING, form_structure()->field(6)->Type().group());
624    base::string16 billing_name = form_structure()->field(6)->value;
625    EXPECT_EQ(NAME_FULL, form_structure()->field(13)->Type().GetStorableType());
626    EXPECT_EQ(NAME, form_structure()->field(13)->Type().group());
627    base::string16 shipping_name = form_structure()->field(13)->value;
628
629    EXPECT_FALSE(cc_name.empty());
630    EXPECT_FALSE(billing_name.empty());
631    EXPECT_FALSE(shipping_name.empty());
632    EXPECT_EQ(cc_name, billing_name);
633    EXPECT_EQ(cc_name, shipping_name);
634  }
635
636  TestAutofillDialogController* controller() { return controller_.get(); }
637
638  const FormStructure* form_structure() { return form_structure_; }
639
640  TestGeneratedCreditCardBubbleController* test_generated_bubble_controller() {
641    return test_generated_bubble_controller_;
642  }
643
644  const MockNewCreditCardBubbleController* mock_new_card_bubble_controller() {
645    return mock_new_card_bubble_controller_.get();
646  }
647
648 private:
649  void FinishedCallback(AutofillClient::RequestAutocompleteResult result,
650                        const base::string16& debug_message,
651                        const FormStructure* form_structure) {
652    form_structure_ = form_structure;
653  }
654
655#if defined(OS_WIN)
656   // http://crbug.com/227221
657   ui::ScopedOleInitializer ole_initializer_;
658#endif
659
660  // The controller owns itself.
661  base::WeakPtr<TestAutofillDialogController> controller_;
662
663  // Must outlive the controller.
664  AutofillMetrics metric_logger_;
665
666  // Returned when the dialog closes successfully.
667  const FormStructure* form_structure_;
668
669  // Used to monitor if the Autofill credit card bubble is shown. Owned by
670  // |web_contents()|.
671  TestGeneratedCreditCardBubbleController* test_generated_bubble_controller_;
672
673  // Used to record when new card bubbles would show. Created in |Reset()|.
674  scoped_ptr<MockNewCreditCardBubbleController>
675      mock_new_card_bubble_controller_;
676
677  scoped_ptr<ScopedTestingLocalState> scoped_local_state_;
678};
679
680}  // namespace
681
682TEST_F(AutofillDialogControllerTest, RefuseToShowWithNoAutocompleteAttributes) {
683  FormFieldData email_field;
684  email_field.name = ASCIIToUTF16("email");
685  FormFieldData cc_field;
686  cc_field.name = ASCIIToUTF16("cc");
687  FormFieldData billing_field;
688  billing_field.name = ASCIIToUTF16("billing name");
689
690  FormData form_data;
691  form_data.fields.push_back(email_field);
692  form_data.fields.push_back(cc_field);
693  form_data.fields.push_back(billing_field);
694
695  SetUpControllerWithFormData(form_data);
696  EXPECT_FALSE(controller());
697}
698
699TEST_F(AutofillDialogControllerTest, RefuseToShowWithNoCcField) {
700  FormFieldData shipping_tel;
701  shipping_tel.autocomplete_attribute = "shipping tel";
702
703  FormData form_data;
704  form_data.fields.push_back(shipping_tel);
705
706  SetUpControllerWithFormData(form_data);
707  EXPECT_FALSE(controller());
708
709  // Any cc- field will do.
710  FormFieldData cc_field;
711  cc_field.autocomplete_attribute = "cc-csc";
712  form_data.fields.push_back(cc_field);
713
714  SetUpControllerWithFormData(form_data);
715  EXPECT_TRUE(controller());
716}
717
718// Ensure the default ValidityMessage has the expected values.
719TEST_F(AutofillDialogControllerTest, DefaultValidityMessage) {
720  ValidityMessages messages;
721  ValidityMessage message = messages.GetMessageOrDefault(UNKNOWN_TYPE);
722  EXPECT_FALSE(message.sure);
723  EXPECT_TRUE(message.text.empty());
724}
725
726// This test makes sure nothing falls over when fields are being validity-
727// checked.
728TEST_F(AutofillDialogControllerTest, ValidityCheck) {
729  for (size_t i = SECTION_MIN; i <= SECTION_MAX; ++i) {
730    DialogSection section = static_cast<DialogSection>(i);
731    const DetailInputs& shipping_inputs =
732        controller()->RequestedFieldsForSection(section);
733    for (DetailInputs::const_iterator iter = shipping_inputs.begin();
734         iter != shipping_inputs.end(); ++iter) {
735      controller()->InputValidityMessage(section, iter->type, base::string16());
736    }
737  }
738}
739
740// Test for phone number validation.
741TEST_F(AutofillDialogControllerTest, PhoneNumberValidation) {
742  // Construct FieldValueMap from existing data.
743  SwitchToAutofill();
744
745  for (size_t i = 0; i < 2; ++i) {
746    ServerFieldType phone = i == 0 ? PHONE_HOME_WHOLE_NUMBER :
747                                     PHONE_BILLING_WHOLE_NUMBER;
748    ServerFieldType address = i == 0 ? ADDRESS_HOME_COUNTRY :
749                                       ADDRESS_BILLING_COUNTRY;
750    DialogSection section = i == 0 ? SECTION_SHIPPING : SECTION_BILLING;
751
752    FieldValueMap outputs;
753    const DetailInputs& inputs =
754        controller()->RequestedFieldsForSection(section);
755    AutofillProfile full_profile(test::GetVerifiedProfile());
756    for (size_t i = 0; i < inputs.size(); ++i) {
757      const ServerFieldType type = inputs[i].type;
758      outputs[type] = full_profile.GetInfo(AutofillType(type), "en-US");
759    }
760
761    // Make sure country is United States.
762    outputs[address] = ASCIIToUTF16("United States");
763
764    // Existing data should have no errors.
765    ValidityMessages messages = controller()->InputsAreValid(section, outputs);
766    EXPECT_FALSE(HasAnyError(messages, phone));
767
768    // Input an empty phone number.
769    outputs[phone] = base::string16();
770    messages = controller()->InputsAreValid(section, outputs);
771    EXPECT_TRUE(HasUnsureError(messages, phone));
772
773    // Input an invalid phone number.
774    outputs[phone] = ASCIIToUTF16("ABC");
775    messages = controller()->InputsAreValid(section, outputs);
776    EXPECT_TRUE(messages.HasSureError(phone));
777
778    // Input a local phone number.
779    outputs[phone] = ASCIIToUTF16("2155546699");
780    messages = controller()->InputsAreValid(section, outputs);
781    EXPECT_FALSE(HasAnyError(messages, phone));
782
783    // Input an invalid local phone number.
784    outputs[phone] = ASCIIToUTF16("215554669");
785    messages = controller()->InputsAreValid(section, outputs);
786    EXPECT_TRUE(messages.HasSureError(phone));
787
788    // Input an international phone number.
789    outputs[phone] = ASCIIToUTF16("+33 892 70 12 39");
790    messages = controller()->InputsAreValid(section, outputs);
791    EXPECT_FALSE(HasAnyError(messages, phone));
792
793    // Input an invalid international phone number.
794    outputs[phone] = ASCIIToUTF16("+112333 892 70 12 39");
795    messages = controller()->InputsAreValid(section, outputs);
796    EXPECT_TRUE(messages.HasSureError(phone));
797
798    // Input a valid Canadian number.
799    outputs[phone] = ASCIIToUTF16("+1 506 887 1234");
800    messages = controller()->InputsAreValid(section, outputs);
801    EXPECT_FALSE(HasAnyError(messages, phone));
802
803    // Input a valid Canadian number without the country code.
804    outputs[phone] = ASCIIToUTF16("506 887 1234");
805    messages = controller()->InputsAreValid(section, outputs);
806    EXPECT_TRUE(HasAnyError(messages, phone));
807
808    // Input a valid Canadian toll-free number.
809    outputs[phone] = ASCIIToUTF16("310 1234");
810    messages = controller()->InputsAreValid(section, outputs);
811    EXPECT_TRUE(HasAnyError(messages, phone));
812  }
813}
814
815TEST_F(AutofillDialogControllerTest, ExpirationDateValidity) {
816  ui::ComboboxModel* exp_year_model =
817      controller()->ComboboxModelForAutofillType(CREDIT_CARD_EXP_4_DIGIT_YEAR);
818  ui::ComboboxModel* exp_month_model =
819      controller()->ComboboxModelForAutofillType(CREDIT_CARD_EXP_MONTH);
820
821  base::string16 default_year_value =
822      exp_year_model->GetItemAt(exp_year_model->GetDefaultIndex());
823  base::string16 default_month_value =
824      exp_month_model->GetItemAt(exp_month_model->GetDefaultIndex());
825
826  base::string16 other_year_value =
827      exp_year_model->GetItemAt(exp_year_model->GetItemCount() - 1);
828  base::string16 other_month_value =
829      exp_month_model->GetItemAt(exp_month_model->GetItemCount() - 1);
830
831  FieldValueMap outputs;
832  outputs[ADDRESS_BILLING_COUNTRY] = ASCIIToUTF16("United States");
833  outputs[CREDIT_CARD_EXP_MONTH] = default_month_value;
834  outputs[CREDIT_CARD_EXP_4_DIGIT_YEAR] = default_year_value;
835
836  // Expiration default values generate unsure validation errors (but not sure).
837  ValidityMessages messages = controller()->InputsAreValid(SECTION_CC_BILLING,
838                                                           outputs);
839  EXPECT_TRUE(HasUnsureError(messages, CREDIT_CARD_EXP_4_DIGIT_YEAR));
840  EXPECT_TRUE(HasUnsureError(messages, CREDIT_CARD_EXP_MONTH));
841
842  // Expiration date with default month fails.
843  outputs[CREDIT_CARD_EXP_4_DIGIT_YEAR] = other_year_value;
844  messages = controller()->InputsAreValid(SECTION_CC_BILLING, outputs);
845  EXPECT_FALSE(HasUnsureError(messages, CREDIT_CARD_EXP_4_DIGIT_YEAR));
846  EXPECT_TRUE(HasUnsureError(messages, CREDIT_CARD_EXP_MONTH));
847
848  // Expiration date with default year fails.
849  outputs[CREDIT_CARD_EXP_MONTH] = other_month_value;
850  outputs[CREDIT_CARD_EXP_4_DIGIT_YEAR] = default_year_value;
851  messages = controller()->InputsAreValid(SECTION_CC_BILLING, outputs);
852  EXPECT_TRUE(HasUnsureError(messages, CREDIT_CARD_EXP_4_DIGIT_YEAR));
853  EXPECT_FALSE(HasUnsureError(messages, CREDIT_CARD_EXP_MONTH));
854}
855
856TEST_F(AutofillDialogControllerTest, BillingNameValidation) {
857  // Construct FieldValueMap from AutofillProfile data.
858  SwitchToAutofill();
859
860  FieldValueMap outputs;
861  outputs[ADDRESS_BILLING_COUNTRY] = ASCIIToUTF16("United States");
862
863  // Input an empty billing name.
864  outputs[NAME_BILLING_FULL] = base::string16();
865  ValidityMessages messages = controller()->InputsAreValid(SECTION_BILLING,
866                                                           outputs);
867  EXPECT_TRUE(HasUnsureError(messages, NAME_BILLING_FULL));
868
869  // Input a non-empty billing name.
870  outputs[NAME_BILLING_FULL] = ASCIIToUTF16("Bob");
871  messages = controller()->InputsAreValid(SECTION_BILLING, outputs);
872  EXPECT_FALSE(HasAnyError(messages, NAME_BILLING_FULL));
873
874  // Switch to Wallet which only considers names with with at least two names to
875  // be valid.
876  SwitchToWallet();
877
878  // Setup some wallet state.
879  scoped_ptr<wallet::WalletItems> wallet_items =
880      wallet::GetTestWalletItems(wallet::AMEX_DISALLOWED);
881  controller()->OnDidGetWalletItems(wallet_items.Pass());
882
883  // Input an empty billing name. Data source should not change this behavior.
884  outputs[NAME_BILLING_FULL] = base::string16();
885  messages = controller()->InputsAreValid(SECTION_CC_BILLING, outputs);
886  EXPECT_TRUE(HasUnsureError(messages, NAME_BILLING_FULL));
887
888  // Input a one name billing name. Wallet does not currently support this.
889  outputs[NAME_BILLING_FULL] = ASCIIToUTF16("Bob");
890  messages = controller()->InputsAreValid(SECTION_CC_BILLING, outputs);
891  EXPECT_TRUE(messages.HasSureError(NAME_BILLING_FULL));
892
893  // Input a two name billing name.
894  outputs[NAME_BILLING_FULL] = ASCIIToUTF16("Bob Barker");
895  messages = controller()->InputsAreValid(SECTION_CC_BILLING, outputs);
896  EXPECT_FALSE(HasAnyError(messages, NAME_BILLING_FULL));
897
898  // Input a more than two name billing name.
899  outputs[NAME_BILLING_FULL] = ASCIIToUTF16("John Jacob Jingleheimer Schmidt"),
900  messages = controller()->InputsAreValid(SECTION_CC_BILLING, outputs);
901  EXPECT_FALSE(HasAnyError(messages, NAME_BILLING_FULL));
902
903  // Input a billing name with lots of crazy whitespace.
904  outputs[NAME_BILLING_FULL] =
905      ASCIIToUTF16("     \\n\\r John \\n  Jacob Jingleheimer \\t Schmidt  "),
906  messages = controller()->InputsAreValid(SECTION_CC_BILLING, outputs);
907  EXPECT_FALSE(HasAnyError(messages, NAME_BILLING_FULL));
908}
909
910TEST_F(AutofillDialogControllerTest, CreditCardNumberValidation) {
911  // Construct FieldValueMap from AutofillProfile data.
912  SwitchToAutofill();
913
914  // Should accept AMEX, Visa, Master and Discover.
915  ValidateCCNumber(SECTION_CC, kTestCCNumberVisa, true);
916  ValidateCCNumber(SECTION_CC, kTestCCNumberMaster, true);
917  ValidateCCNumber(SECTION_CC, kTestCCNumberDiscover, true);
918  ValidateCCNumber(SECTION_CC, kTestCCNumberAmex, true);
919  ValidateCCNumber(SECTION_CC, kTestCCNumberIncomplete, false);
920  ValidateCCNumber(SECTION_CC, kTestCCNumberInvalid, false);
921
922  // Switch to Wallet which will not accept AMEX.
923  SwitchToWallet();
924
925  // Setup some wallet state on a merchant for which Wallet doesn't
926  // support AMEX.
927  controller()->OnDidGetWalletItems(
928      wallet::GetTestWalletItems(wallet::AMEX_DISALLOWED));
929
930  // Should accept Visa, Master and Discover, but not AMEX.
931  ValidateCCNumber(SECTION_CC_BILLING, kTestCCNumberVisa, true);
932  ValidateCCNumber(SECTION_CC_BILLING, kTestCCNumberMaster, true);
933  ValidateCCNumber(SECTION_CC_BILLING, kTestCCNumberDiscover, true);
934  ValidateCCNumber(SECTION_CC_BILLING, kTestCCNumberAmex, false);
935  ValidateCCNumber(SECTION_CC_BILLING, kTestCCNumberIncomplete, false);
936  ValidateCCNumber(SECTION_CC_BILLING, kTestCCNumberInvalid, false);
937
938  // Setup some wallet state on a merchant for which Wallet supports AMEX.
939  controller()->OnDidGetWalletItems(
940      wallet::GetTestWalletItems(wallet::AMEX_ALLOWED));
941
942  // Should accept Visa, Master, Discover, and AMEX.
943  ValidateCCNumber(SECTION_CC_BILLING, kTestCCNumberVisa, true);
944  ValidateCCNumber(SECTION_CC_BILLING, kTestCCNumberMaster, true);
945  ValidateCCNumber(SECTION_CC_BILLING, kTestCCNumberDiscover, true);
946  ValidateCCNumber(SECTION_CC_BILLING, kTestCCNumberAmex, true);
947  ValidateCCNumber(SECTION_CC_BILLING, kTestCCNumberIncomplete, false);
948  ValidateCCNumber(SECTION_CC_BILLING, kTestCCNumberInvalid, false);
949}
950
951TEST_F(AutofillDialogControllerTest, AutofillProfiles) {
952  SwitchToAutofill();
953  ui::MenuModel* shipping_model =
954      controller()->MenuModelForSection(SECTION_SHIPPING);
955  // Since the PersonalDataManager is empty, this should only have the
956  // "use billing", "add new" and "manage" menu items.
957  ASSERT_TRUE(shipping_model);
958  EXPECT_EQ(3, shipping_model->GetItemCount());
959  // On the other hand, the other models should be NULL when there's no
960  // suggestion.
961  EXPECT_FALSE(controller()->MenuModelForSection(SECTION_CC));
962  EXPECT_FALSE(controller()->MenuModelForSection(SECTION_BILLING));
963
964  EXPECT_CALL(*controller()->GetView(), ModelChanged()).Times(3);
965
966  // Empty profiles are ignored.
967  AutofillProfile empty_profile(base::GenerateGUID(), kSettingsOrigin);
968  empty_profile.SetRawInfo(NAME_FULL, ASCIIToUTF16("John Doe"));
969  controller()->GetTestingManager()->AddTestingProfile(&empty_profile);
970  shipping_model = controller()->MenuModelForSection(SECTION_SHIPPING);
971  ASSERT_TRUE(shipping_model);
972  EXPECT_EQ(3, shipping_model->GetItemCount());
973
974  // An otherwise full but unverified profile should be ignored.
975  AutofillProfile full_profile(test::GetFullProfile());
976  full_profile.set_origin("https://www.example.com");
977  full_profile.SetRawInfo(ADDRESS_HOME_LINE2, base::string16());
978  controller()->GetTestingManager()->AddTestingProfile(&full_profile);
979  shipping_model = controller()->MenuModelForSection(SECTION_SHIPPING);
980  ASSERT_TRUE(shipping_model);
981  EXPECT_EQ(3, shipping_model->GetItemCount());
982
983  // A full, verified profile should be picked up.
984  AutofillProfile verified_profile(test::GetVerifiedProfile());
985  verified_profile.SetRawInfo(ADDRESS_HOME_LINE2, base::string16());
986  controller()->GetTestingManager()->AddTestingProfile(&verified_profile);
987  shipping_model = controller()->MenuModelForSection(SECTION_SHIPPING);
988  ASSERT_TRUE(shipping_model);
989  EXPECT_EQ(4, shipping_model->GetItemCount());
990}
991
992// Checks that a valid profile is selected by default, but if invalid is
993// popped into edit mode.
994TEST_F(AutofillDialogControllerTest, AutofillProfilesPopInvalidIntoEdit) {
995  SwitchToAutofill();
996  SuggestionsMenuModel* shipping_model =
997      GetMenuModelForSection(SECTION_SHIPPING);
998  EXPECT_EQ(3, shipping_model->GetItemCount());
999  // "Same as billing" is selected.
1000  EXPECT_FALSE(controller()->IsManuallyEditingSection(SECTION_SHIPPING));
1001  EXPECT_TRUE(controller()->IsManuallyEditingSection(SECTION_BILLING));
1002
1003  AutofillProfile verified_profile(test::GetVerifiedProfile());
1004  controller()->GetTestingManager()->AddTestingProfile(&verified_profile);
1005  EXPECT_EQ(4, shipping_model->GetItemCount());
1006  EXPECT_FALSE(controller()->IsManuallyEditingSection(SECTION_SHIPPING));
1007  EXPECT_FALSE(controller()->IsManuallyEditingSection(SECTION_BILLING));
1008
1009  // Now make up a problem and make sure the profile isn't in the list.
1010  Reset();
1011  SwitchToAutofill();
1012  AddressProblems problems;
1013  problems.push_back(
1014      AddressProblem(::i18n::addressinput::POSTAL_CODE,
1015                     AddressProblem::MISMATCHING_VALUE,
1016                     IDS_LEARN_MORE));
1017  EXPECT_CALL(*controller()->GetMockValidator(),
1018              ValidateAddress(CountryCodeMatcher("US"), _, _)).
1019      WillRepeatedly(DoAll(SetArgPointee<2>(problems),
1020                           Return(AddressValidator::SUCCESS)));
1021
1022  controller()->GetTestingManager()->AddTestingProfile(&verified_profile);
1023  shipping_model = GetMenuModelForSection(SECTION_SHIPPING);
1024  EXPECT_EQ(4, shipping_model->GetItemCount());
1025  EXPECT_TRUE(controller()->IsManuallyEditingSection(SECTION_SHIPPING));
1026  EXPECT_TRUE(controller()->IsManuallyEditingSection(SECTION_BILLING));
1027}
1028
1029// Makes sure suggestion profiles are re-validated when validation rules load.
1030TEST_F(AutofillDialogControllerTest, AutofillProfilesRevalidateAfterRulesLoad) {
1031  SwitchToAutofill();
1032  SuggestionsMenuModel* shipping_model =
1033      GetMenuModelForSection(SECTION_SHIPPING);
1034  EXPECT_EQ(3, shipping_model->GetItemCount());
1035  // "Same as billing" is selected.
1036  EXPECT_FALSE(controller()->IsManuallyEditingSection(SECTION_SHIPPING));
1037  EXPECT_TRUE(controller()->IsManuallyEditingSection(SECTION_BILLING));
1038  AutofillProfile verified_profile(test::GetVerifiedProfile());
1039  controller()->GetTestingManager()->AddTestingProfile(&verified_profile);
1040  EXPECT_EQ(4, shipping_model->GetItemCount());
1041  EXPECT_FALSE(controller()->IsManuallyEditingSection(SECTION_SHIPPING));
1042  EXPECT_FALSE(controller()->IsManuallyEditingSection(SECTION_BILLING));
1043
1044  AddressProblems problems;
1045  problems.push_back(
1046      AddressProblem(::i18n::addressinput::POSTAL_CODE,
1047                     AddressProblem::MISMATCHING_VALUE,
1048                     IDS_LEARN_MORE));
1049  EXPECT_CALL(*controller()->GetMockValidator(),
1050              ValidateAddress(CountryCodeMatcher("US"), _, _)).
1051      WillRepeatedly(DoAll(SetArgPointee<2>(problems),
1052                           Return(AddressValidator::SUCCESS)));
1053
1054  controller()->OnAddressValidationRulesLoaded("US", true);
1055  EXPECT_EQ(4, shipping_model->GetItemCount());
1056  EXPECT_TRUE(controller()->IsManuallyEditingSection(SECTION_SHIPPING));
1057  EXPECT_TRUE(controller()->IsManuallyEditingSection(SECTION_BILLING));
1058}
1059
1060// Makes sure that the choice of which Autofill profile to use for each section
1061// is sticky.
1062TEST_F(AutofillDialogControllerTest, AutofillProfileDefaults) {
1063  SwitchToAutofill();
1064  AutofillProfile profile(test::GetVerifiedProfile());
1065  AutofillProfile profile2(test::GetVerifiedProfile2());
1066  controller()->GetTestingManager()->AddTestingProfile(&profile);
1067  controller()->GetTestingManager()->AddTestingProfile(&profile2);
1068
1069  // Until a selection has been made, the default shipping suggestion is the
1070  // first one (after "use billing").
1071  SuggestionsMenuModel* shipping_model =
1072      GetMenuModelForSection(SECTION_SHIPPING);
1073  EXPECT_EQ(1, shipping_model->checked_item());
1074
1075  for (int i = 2; i >= 0; --i) {
1076    shipping_model = GetMenuModelForSection(SECTION_SHIPPING);
1077    shipping_model->ExecuteCommand(i, 0);
1078    FillCreditCardInputs();
1079    controller()->OnAccept();
1080
1081    Reset();
1082    controller()->GetTestingManager()->AddTestingProfile(&profile);
1083    controller()->GetTestingManager()->AddTestingProfile(&profile2);
1084    shipping_model = GetMenuModelForSection(SECTION_SHIPPING);
1085    EXPECT_EQ(i, shipping_model->checked_item());
1086  }
1087
1088  // Try again, but don't add the default profile to the PDM. The dialog
1089  // should fall back to the first profile.
1090  shipping_model->ExecuteCommand(2, 0);
1091  FillCreditCardInputs();
1092  controller()->OnAccept();
1093  Reset();
1094  controller()->GetTestingManager()->AddTestingProfile(&profile);
1095  shipping_model = GetMenuModelForSection(SECTION_SHIPPING);
1096  EXPECT_EQ(1, shipping_model->checked_item());
1097}
1098
1099// Makes sure that a newly added Autofill profile becomes set as the default
1100// choice for the next run.
1101TEST_F(AutofillDialogControllerTest, NewAutofillProfileIsDefault) {
1102  SwitchToAutofill();
1103
1104  AutofillProfile profile(test::GetVerifiedProfile());
1105  CreditCard credit_card(test::GetVerifiedCreditCard());
1106  controller()->GetTestingManager()->AddTestingProfile(&profile);
1107  controller()->GetTestingManager()->AddTestingCreditCard(&credit_card);
1108
1109  // Until a selection has been made, the default suggestion is the first one.
1110  // For the shipping section, this follows the "use billing" suggestion.
1111  EXPECT_EQ(0, GetMenuModelForSection(SECTION_CC)->checked_item());
1112  EXPECT_EQ(1, GetMenuModelForSection(SECTION_SHIPPING)->checked_item());
1113
1114  // Fill in the shipping and credit card sections with new data.
1115  AutofillProfile new_profile(test::GetVerifiedProfile2());
1116  CreditCard new_credit_card(test::GetVerifiedCreditCard2());
1117  FillInputs(SECTION_SHIPPING, new_profile);
1118  FillInputs(SECTION_CC, new_credit_card);
1119  controller()->GetView()->CheckSaveDetailsLocallyCheckbox(true);
1120  controller()->OnAccept();
1121
1122  // Update the |new_profile| and |new_credit_card|'s guids to the saved ones.
1123  new_profile.set_guid(
1124      controller()->GetTestingManager()->imported_profile().guid());
1125  new_credit_card.set_guid(
1126      controller()->GetTestingManager()->imported_credit_card().guid());
1127
1128  // Reload the dialog. The newly added address and credit card should now be
1129  // set as the defaults.
1130  Reset();
1131  controller()->GetTestingManager()->AddTestingProfile(&profile);
1132  controller()->GetTestingManager()->AddTestingProfile(&new_profile);
1133  controller()->GetTestingManager()->AddTestingCreditCard(&credit_card);
1134  controller()->GetTestingManager()->AddTestingCreditCard(&new_credit_card);
1135
1136  // Until a selection has been made, the default suggestion is the first one.
1137  // For the shipping section, this follows the "use billing" suggestion.
1138  EXPECT_EQ(1, GetMenuModelForSection(SECTION_CC)->checked_item());
1139  EXPECT_EQ(2, GetMenuModelForSection(SECTION_SHIPPING)->checked_item());
1140}
1141
1142TEST_F(AutofillDialogControllerTest, AutofillProfileVariants) {
1143  SwitchToAutofill();
1144  EXPECT_CALL(*controller()->GetView(), ModelChanged());
1145  ui::MenuModel* shipping_model =
1146      controller()->MenuModelForSection(SECTION_SHIPPING);
1147  ASSERT_TRUE(!!shipping_model);
1148  EXPECT_EQ(3, shipping_model->GetItemCount());
1149
1150  // Set up some variant data.
1151  AutofillProfile full_profile(test::GetVerifiedProfile());
1152  std::vector<base::string16> names;
1153  names.push_back(ASCIIToUTF16("John Doe"));
1154  names.push_back(ASCIIToUTF16("Jane Doe"));
1155  full_profile.SetRawMultiInfo(NAME_FULL, names);
1156  std::vector<base::string16> emails;
1157  emails.push_back(ASCIIToUTF16(kFakeEmail));
1158  emails.push_back(ASCIIToUTF16("admin@example.com"));
1159  full_profile.SetRawMultiInfo(EMAIL_ADDRESS, emails);
1160
1161  // Non-default variants are ignored by the dialog.
1162  controller()->GetTestingManager()->AddTestingProfile(&full_profile);
1163  EXPECT_EQ(4, shipping_model->GetItemCount());
1164}
1165
1166TEST_F(AutofillDialogControllerTest, SuggestValidEmail) {
1167  SwitchToAutofill();
1168  AutofillProfile profile(test::GetVerifiedProfile());
1169  const base::string16 kValidEmail = ASCIIToUTF16(kFakeEmail);
1170  profile.SetRawInfo(EMAIL_ADDRESS, kValidEmail);
1171  controller()->GetTestingManager()->AddTestingProfile(&profile);
1172
1173  // "add", "manage", and 1 suggestion.
1174  EXPECT_EQ(
1175      3, controller()->MenuModelForSection(SECTION_BILLING)->GetItemCount());
1176  // "add", "manage", 1 suggestion, and "same as billing".
1177  EXPECT_EQ(
1178      4, controller()->MenuModelForSection(SECTION_SHIPPING)->GetItemCount());
1179}
1180
1181TEST_F(AutofillDialogControllerTest, DoNotSuggestInvalidEmail) {
1182  SwitchToAutofill();
1183  AutofillProfile profile(test::GetVerifiedProfile());
1184  profile.SetRawInfo(EMAIL_ADDRESS, ASCIIToUTF16(".!#$%&'*+/=?^_`-@-.."));
1185  controller()->GetTestingManager()->AddTestingProfile(&profile);
1186
1187  EXPECT_FALSE(!!controller()->MenuModelForSection(SECTION_BILLING));
1188  // "add", "manage", 1 suggestion, and "same as billing".
1189  EXPECT_EQ(
1190      4, controller()->MenuModelForSection(SECTION_SHIPPING)->GetItemCount());
1191}
1192
1193TEST_F(AutofillDialogControllerTest, SuggestValidAddress) {
1194  SwitchToAutofill();
1195  AutofillProfile full_profile(test::GetVerifiedProfile());
1196  full_profile.set_origin(kSettingsOrigin);
1197  controller()->GetTestingManager()->AddTestingProfile(&full_profile);
1198  // "add", "manage", and 1 suggestion.
1199  EXPECT_EQ(
1200      3, controller()->MenuModelForSection(SECTION_BILLING)->GetItemCount());
1201}
1202
1203TEST_F(AutofillDialogControllerTest, DoNotSuggestInvalidAddress) {
1204  SwitchToAutofill();
1205  AutofillProfile full_profile(test::GetVerifiedProfile());
1206  full_profile.set_origin(kSettingsOrigin);
1207  full_profile.SetRawInfo(ADDRESS_HOME_STATE, ASCIIToUTF16("C"));
1208  controller()->GetTestingManager()->AddTestingProfile(&full_profile);
1209}
1210
1211TEST_F(AutofillDialogControllerTest, DoNotSuggestIncompleteAddress) {
1212  SwitchToAutofill();
1213  AutofillProfile profile(test::GetVerifiedProfile());
1214  profile.SetRawInfo(ADDRESS_HOME_STATE, base::string16());
1215  controller()->GetTestingManager()->AddTestingProfile(&profile);
1216
1217  // Same as shipping, manage, add new.
1218  EXPECT_EQ(3,
1219      controller()->MenuModelForSection(SECTION_SHIPPING)->GetItemCount());
1220  EXPECT_FALSE(!!controller()->MenuModelForSection(SECTION_BILLING));
1221}
1222
1223TEST_F(AutofillDialogControllerTest, DoSuggestShippingAddressWithoutEmail) {
1224  SwitchToAutofill();
1225  AutofillProfile profile(test::GetVerifiedProfile());
1226  profile.SetRawInfo(EMAIL_ADDRESS, base::string16());
1227  controller()->GetTestingManager()->AddTestingProfile(&profile);
1228
1229  // Same as shipping, manage, add new, profile with missing email.
1230  EXPECT_EQ(4,
1231      controller()->MenuModelForSection(SECTION_SHIPPING)->GetItemCount());
1232  // Billing addresses require email.
1233  EXPECT_FALSE(!!controller()->MenuModelForSection(SECTION_BILLING));
1234}
1235
1236TEST_F(AutofillDialogControllerTest, AutofillCreditCards) {
1237  SwitchToAutofill();
1238  // Since the PersonalDataManager is empty, this should only have the
1239  // default menu items.
1240  EXPECT_FALSE(controller()->MenuModelForSection(SECTION_CC));
1241
1242  EXPECT_CALL(*controller()->GetView(), ModelChanged()).Times(3);
1243
1244  // Empty cards are ignored.
1245  CreditCard empty_card(base::GenerateGUID(), kSettingsOrigin);
1246  empty_card.SetRawInfo(CREDIT_CARD_NAME, ASCIIToUTF16("John Doe"));
1247  controller()->GetTestingManager()->AddTestingCreditCard(&empty_card);
1248  EXPECT_FALSE(controller()->MenuModelForSection(SECTION_CC));
1249
1250  // An otherwise full but unverified card should be ignored.
1251  CreditCard full_card(test::GetCreditCard());
1252  full_card.set_origin("https://www.example.com");
1253  controller()->GetTestingManager()->AddTestingCreditCard(&full_card);
1254  EXPECT_FALSE(controller()->MenuModelForSection(SECTION_CC));
1255
1256  // A full, verified card should be picked up.
1257  CreditCard verified_card(test::GetCreditCard());
1258  verified_card.set_origin(kSettingsOrigin);
1259  controller()->GetTestingManager()->AddTestingCreditCard(&verified_card);
1260  ui::MenuModel* credit_card_model =
1261      controller()->MenuModelForSection(SECTION_CC);
1262  ASSERT_TRUE(credit_card_model);
1263  EXPECT_EQ(3, credit_card_model->GetItemCount());
1264}
1265
1266// Test selecting a shipping address different from billing as address.
1267TEST_F(AutofillDialogControllerTest, DontUseBillingAsShipping) {
1268  SwitchToAutofill();
1269  AutofillProfile full_profile(test::GetVerifiedProfile());
1270  AutofillProfile full_profile2(test::GetVerifiedProfile2());
1271  CreditCard credit_card(test::GetVerifiedCreditCard());
1272  controller()->GetTestingManager()->AddTestingProfile(&full_profile);
1273  controller()->GetTestingManager()->AddTestingProfile(&full_profile2);
1274  controller()->GetTestingManager()->AddTestingCreditCard(&credit_card);
1275  ui::MenuModel* shipping_model =
1276      controller()->MenuModelForSection(SECTION_SHIPPING);
1277  shipping_model->ActivatedAt(2);
1278
1279  controller()->OnAccept();
1280  ASSERT_EQ(20U, form_structure()->field_count());
1281  EXPECT_EQ(ADDRESS_HOME_STATE,
1282            form_structure()->field(9)->Type().GetStorableType());
1283  EXPECT_EQ(ADDRESS_BILLING, form_structure()->field(9)->Type().group());
1284  EXPECT_EQ(ADDRESS_HOME_STATE,
1285            form_structure()->field(16)->Type().GetStorableType());
1286  EXPECT_EQ(ADDRESS_HOME, form_structure()->field(16)->Type().group());
1287  base::string16 billing_state = form_structure()->field(9)->value;
1288  base::string16 shipping_state = form_structure()->field(16)->value;
1289  EXPECT_FALSE(billing_state.empty());
1290  EXPECT_FALSE(shipping_state.empty());
1291  EXPECT_NE(billing_state, shipping_state);
1292
1293  EXPECT_EQ(CREDIT_CARD_NAME,
1294            form_structure()->field(1)->Type().GetStorableType());
1295  base::string16 cc_name = form_structure()->field(1)->value;
1296  EXPECT_EQ(NAME_FULL, form_structure()->field(6)->Type().GetStorableType());
1297  EXPECT_EQ(NAME_BILLING, form_structure()->field(6)->Type().group());
1298  base::string16 billing_name = form_structure()->field(6)->value;
1299  EXPECT_EQ(NAME_FULL, form_structure()->field(13)->Type().GetStorableType());
1300  EXPECT_EQ(NAME, form_structure()->field(13)->Type().group());
1301  base::string16 shipping_name = form_structure()->field(13)->value;
1302
1303  EXPECT_FALSE(cc_name.empty());
1304  EXPECT_FALSE(billing_name.empty());
1305  EXPECT_FALSE(shipping_name.empty());
1306  // Billing name should always be the same as cardholder name.
1307  EXPECT_EQ(cc_name, billing_name);
1308  EXPECT_NE(cc_name, shipping_name);
1309}
1310
1311// Test selecting UseBillingForShipping.
1312TEST_F(AutofillDialogControllerTest, UseBillingAsShipping) {
1313  SwitchToAutofill();
1314
1315  AutofillProfile full_profile(test::GetVerifiedProfile());
1316  controller()->GetTestingManager()->AddTestingProfile(&full_profile);
1317
1318  AutofillProfile full_profile2(test::GetVerifiedProfile2());
1319  controller()->GetTestingManager()->AddTestingProfile(&full_profile2);
1320
1321  CreditCard credit_card(test::GetVerifiedCreditCard());
1322  controller()->GetTestingManager()->AddTestingCreditCard(&credit_card);
1323
1324  ASSERT_FALSE(controller()->IsManuallyEditingSection(SECTION_CC));
1325  ASSERT_FALSE(controller()->IsManuallyEditingSection(SECTION_BILLING));
1326
1327  SubmitAndVerifyShippingAndBillingResults();
1328}
1329
1330TEST_F(AutofillDialogControllerTest, UseBillingAsShippingManualInput) {
1331  SwitchToAutofill();
1332
1333  ASSERT_TRUE(controller()->IsManuallyEditingSection(SECTION_CC));
1334  ASSERT_TRUE(controller()->IsManuallyEditingSection(SECTION_BILLING));
1335
1336  CreditCard credit_card(test::GetVerifiedCreditCard());
1337  FillInputs(SECTION_CC, credit_card);
1338
1339  AutofillProfile full_profile(test::GetVerifiedProfile());
1340  FillInputs(SECTION_BILLING, full_profile);
1341
1342  SubmitAndVerifyShippingAndBillingResults();
1343}
1344
1345// Tests that shipping and billing telephone fields are supported, and filled
1346// in by their respective profiles. http://crbug.com/244515
1347TEST_F(AutofillDialogControllerTest, BillingVsShippingPhoneNumber) {
1348  FormFieldData shipping_tel;
1349  shipping_tel.autocomplete_attribute = "shipping tel";
1350  FormFieldData billing_tel;
1351  billing_tel.autocomplete_attribute = "billing tel";
1352  FormFieldData cc_field;
1353  cc_field.autocomplete_attribute = "cc-csc";
1354
1355  FormData form_data;
1356  form_data.fields.push_back(shipping_tel);
1357  form_data.fields.push_back(billing_tel);
1358  form_data.fields.push_back(cc_field);
1359  SetUpControllerWithFormData(form_data);
1360
1361  SwitchToAutofill();
1362
1363  // The profile that will be chosen for the shipping section.
1364  AutofillProfile shipping_profile(test::GetVerifiedProfile());
1365  // The profile that will be chosen for the billing section.
1366  AutofillProfile billing_profile(test::GetVerifiedProfile2());
1367  CreditCard credit_card(test::GetVerifiedCreditCard());
1368  controller()->GetTestingManager()->AddTestingProfile(&shipping_profile);
1369  controller()->GetTestingManager()->AddTestingProfile(&billing_profile);
1370  controller()->GetTestingManager()->AddTestingCreditCard(&credit_card);
1371  ui::MenuModel* billing_model =
1372      controller()->MenuModelForSection(SECTION_BILLING);
1373  billing_model->ActivatedAt(1);
1374
1375  controller()->OnAccept();
1376  ASSERT_EQ(3U, form_structure()->field_count());
1377  EXPECT_EQ(PHONE_HOME_WHOLE_NUMBER,
1378            form_structure()->field(0)->Type().GetStorableType());
1379  EXPECT_EQ(PHONE_HOME, form_structure()->field(0)->Type().group());
1380  EXPECT_EQ(PHONE_HOME_WHOLE_NUMBER,
1381            form_structure()->field(1)->Type().GetStorableType());
1382  EXPECT_EQ(PHONE_BILLING, form_structure()->field(1)->Type().group());
1383  EXPECT_EQ(shipping_profile.GetRawInfo(PHONE_HOME_WHOLE_NUMBER),
1384            form_structure()->field(0)->value);
1385  EXPECT_EQ(billing_profile.GetRawInfo(PHONE_HOME_WHOLE_NUMBER),
1386            form_structure()->field(1)->value);
1387  EXPECT_NE(form_structure()->field(1)->value,
1388            form_structure()->field(0)->value);
1389}
1390
1391// Similar to the above, but tests that street-address (i.e. all lines of the
1392// street address) is successfully filled for both shipping and billing
1393// sections.
1394TEST_F(AutofillDialogControllerTest, BillingVsShippingStreetAddress) {
1395  FormFieldData shipping_address;
1396  shipping_address.autocomplete_attribute = "shipping street-address";
1397  FormFieldData billing_address;
1398  billing_address.autocomplete_attribute = "billing street-address";
1399  FormFieldData shipping_address_textarea;
1400  shipping_address_textarea.autocomplete_attribute = "shipping street-address";
1401  shipping_address_textarea.form_control_type = "textarea";
1402  FormFieldData billing_address_textarea;
1403  billing_address_textarea.autocomplete_attribute = "billing street-address";
1404  billing_address_textarea.form_control_type = "textarea";
1405  FormFieldData cc_field;
1406  cc_field.autocomplete_attribute = "cc-csc";
1407
1408  FormData form_data;
1409  form_data.fields.push_back(shipping_address);
1410  form_data.fields.push_back(billing_address);
1411  form_data.fields.push_back(shipping_address_textarea);
1412  form_data.fields.push_back(billing_address_textarea);
1413  form_data.fields.push_back(cc_field);
1414  SetUpControllerWithFormData(form_data);
1415
1416  SwitchToAutofill();
1417
1418  // The profile that will be chosen for the shipping section.
1419  AutofillProfile shipping_profile(test::GetVerifiedProfile());
1420  // The profile that will be chosen for the billing section.
1421  AutofillProfile billing_profile(test::GetVerifiedProfile2());
1422  CreditCard credit_card(test::GetVerifiedCreditCard());
1423  controller()->GetTestingManager()->AddTestingProfile(&shipping_profile);
1424  controller()->GetTestingManager()->AddTestingProfile(&billing_profile);
1425  controller()->GetTestingManager()->AddTestingCreditCard(&credit_card);
1426  ui::MenuModel* billing_model =
1427      controller()->MenuModelForSection(SECTION_BILLING);
1428  billing_model->ActivatedAt(1);
1429
1430  controller()->OnAccept();
1431  ASSERT_EQ(5U, form_structure()->field_count());
1432  EXPECT_EQ(ADDRESS_HOME_STREET_ADDRESS,
1433            form_structure()->field(0)->Type().GetStorableType());
1434  EXPECT_EQ(ADDRESS_HOME, form_structure()->field(0)->Type().group());
1435  EXPECT_EQ(ADDRESS_HOME_STREET_ADDRESS,
1436            form_structure()->field(1)->Type().GetStorableType());
1437  EXPECT_EQ(ADDRESS_BILLING, form_structure()->field(1)->Type().group());
1438  // Inexact matching; single-line inputs get the address data concatenated but
1439  // separated by commas.
1440  EXPECT_TRUE(StartsWith(form_structure()->field(0)->value,
1441                         shipping_profile.GetRawInfo(ADDRESS_HOME_LINE1),
1442                         true));
1443  EXPECT_TRUE(EndsWith(form_structure()->field(0)->value,
1444                       shipping_profile.GetRawInfo(ADDRESS_HOME_LINE2),
1445                       true));
1446  EXPECT_TRUE(StartsWith(form_structure()->field(1)->value,
1447                         billing_profile.GetRawInfo(ADDRESS_HOME_LINE1),
1448                         true));
1449  EXPECT_TRUE(EndsWith(form_structure()->field(1)->value,
1450                       billing_profile.GetRawInfo(ADDRESS_HOME_LINE2),
1451                       true));
1452  // The textareas should be an exact match.
1453  EXPECT_EQ(shipping_profile.GetRawInfo(ADDRESS_HOME_STREET_ADDRESS),
1454            form_structure()->field(2)->value);
1455  EXPECT_EQ(billing_profile.GetRawInfo(ADDRESS_HOME_STREET_ADDRESS),
1456            form_structure()->field(3)->value);
1457
1458  EXPECT_NE(form_structure()->field(1)->value,
1459            form_structure()->field(0)->value);
1460  EXPECT_NE(form_structure()->field(3)->value,
1461            form_structure()->field(2)->value);
1462}
1463
1464TEST_F(AutofillDialogControllerTest, AcceptLegalDocuments) {
1465  for (size_t i = 0; i < 2; ++i) {
1466    SCOPED_TRACE(testing::Message() << "Case " << i);
1467
1468    EXPECT_CALL(*controller()->GetTestingWalletClient(),
1469                AcceptLegalDocuments(_, _));
1470    EXPECT_CALL(*controller()->GetTestingWalletClient(), GetFullWallet(_));
1471    EXPECT_CALL(*controller(), LoadRiskFingerprintData());
1472
1473    EXPECT_TRUE(controller()->LegalDocumentLinks().empty());
1474    controller()->OnDidGetWalletItems(CompleteAndValidWalletItems());
1475    EXPECT_TRUE(controller()->LegalDocumentLinks().empty());
1476
1477    scoped_ptr<wallet::WalletItems> wallet_items =
1478        CompleteAndValidWalletItems();
1479    wallet_items->AddLegalDocument(wallet::GetTestLegalDocument());
1480    wallet_items->AddLegalDocument(wallet::GetTestLegalDocument());
1481    controller()->OnDidGetWalletItems(wallet_items.Pass());
1482    EXPECT_FALSE(controller()->LegalDocumentLinks().empty());
1483
1484    controller()->OnAccept();
1485    controller()->OnDidAcceptLegalDocuments();
1486    controller()->OnDidLoadRiskFingerprintData(GetFakeFingerprint().Pass());
1487
1488    // Now try it all over again with the location disclosure already accepted.
1489    // Nothing should change.
1490    Reset();
1491    base::ListValue preexisting_list;
1492    preexisting_list.AppendString(kFakeEmail);
1493    g_browser_process->local_state()->Set(
1494        ::prefs::kAutofillDialogWalletLocationAcceptance,
1495        preexisting_list);
1496  }
1497}
1498
1499TEST_F(AutofillDialogControllerTest, RejectLegalDocuments) {
1500  for (size_t i = 0; i < 2; ++i) {
1501    SCOPED_TRACE(testing::Message() << "Case " << i);
1502
1503    EXPECT_CALL(*controller()->GetTestingWalletClient(),
1504                AcceptLegalDocuments(_, _)).Times(0);
1505
1506    scoped_ptr<wallet::WalletItems> wallet_items =
1507        CompleteAndValidWalletItems();
1508    wallet_items->AddLegalDocument(wallet::GetTestLegalDocument());
1509    wallet_items->AddLegalDocument(wallet::GetTestLegalDocument());
1510    controller()->OnDidGetWalletItems(wallet_items.Pass());
1511    EXPECT_FALSE(controller()->LegalDocumentLinks().empty());
1512
1513    controller()->OnCancel();
1514
1515    // Now try it all over again with the location disclosure already accepted.
1516    // Nothing should change.
1517    Reset();
1518    base::ListValue preexisting_list;
1519    preexisting_list.AppendString(kFakeEmail);
1520    g_browser_process->local_state()->Set(
1521        ::prefs::kAutofillDialogWalletLocationAcceptance,
1522        preexisting_list);
1523  }
1524}
1525
1526TEST_F(AutofillDialogControllerTest, AcceptLocationDisclosure) {
1527  // Check that accepting the dialog registers the user's name in the list
1528  // of users who have accepted the geolocation terms.
1529  EXPECT_TRUE(g_browser_process->local_state()->GetList(
1530      ::prefs::kAutofillDialogWalletLocationAcceptance)->empty());
1531
1532  controller()->OnDidGetWalletItems(CompleteAndValidWalletItems());
1533  EXPECT_FALSE(controller()->LegalDocumentsText().empty());
1534  EXPECT_TRUE(controller()->LegalDocumentLinks().empty());
1535  controller()->OnAccept();
1536
1537  const base::ListValue* list = g_browser_process->local_state()->GetList(
1538      ::prefs::kAutofillDialogWalletLocationAcceptance);
1539  ASSERT_EQ(1U, list->GetSize());
1540  std::string accepted_username;
1541  EXPECT_TRUE(list->GetString(0, &accepted_username));
1542  EXPECT_EQ(kFakeEmail, accepted_username);
1543
1544  // Now check it still works if that list starts off with some other username
1545  // in it.
1546  Reset();
1547  list = g_browser_process->local_state()->GetList(
1548      ::prefs::kAutofillDialogWalletLocationAcceptance);
1549  ASSERT_TRUE(list->empty());
1550
1551  std::string kOtherUsername("spouse@example.com");
1552  base::ListValue preexisting_list;
1553  preexisting_list.AppendString(kOtherUsername);
1554  g_browser_process->local_state()->Set(
1555      ::prefs::kAutofillDialogWalletLocationAcceptance,
1556      preexisting_list);
1557
1558  controller()->OnDidGetWalletItems(CompleteAndValidWalletItems());
1559  EXPECT_FALSE(controller()->LegalDocumentsText().empty());
1560  EXPECT_TRUE(controller()->LegalDocumentLinks().empty());
1561  controller()->OnAccept();
1562
1563  list = g_browser_process->local_state()->GetList(
1564      ::prefs::kAutofillDialogWalletLocationAcceptance);
1565  ASSERT_EQ(2U, list->GetSize());
1566  EXPECT_NE(list->end(), list->Find(base::StringValue(kFakeEmail)));
1567  EXPECT_NE(list->end(), list->Find(base::StringValue(kOtherUsername)));
1568
1569  // Now check the list doesn't change if the user cancels out of the dialog.
1570  Reset();
1571  list = g_browser_process->local_state()->GetList(
1572      ::prefs::kAutofillDialogWalletLocationAcceptance);
1573  ASSERT_TRUE(list->empty());
1574
1575  g_browser_process->local_state()->Set(
1576      ::prefs::kAutofillDialogWalletLocationAcceptance,
1577      preexisting_list);
1578
1579  controller()->OnDidGetWalletItems(CompleteAndValidWalletItems());
1580  EXPECT_FALSE(controller()->LegalDocumentsText().empty());
1581  EXPECT_TRUE(controller()->LegalDocumentLinks().empty());
1582  controller()->OnCancel();
1583
1584  list = g_browser_process->local_state()->GetList(
1585      ::prefs::kAutofillDialogWalletLocationAcceptance);
1586  ASSERT_EQ(1U, list->GetSize());
1587  EXPECT_NE(list->end(), list->Find(base::StringValue(kOtherUsername)));
1588  EXPECT_EQ(list->end(), list->Find(base::StringValue(kFakeEmail)));
1589}
1590
1591TEST_F(AutofillDialogControllerTest, LegalDocumentOverflow) {
1592  for (size_t number_of_docs = 2; number_of_docs < 11; ++number_of_docs) {
1593    scoped_ptr<wallet::WalletItems> wallet_items =
1594        CompleteAndValidWalletItems();
1595    for (size_t i = 0; i < number_of_docs; ++i)
1596      wallet_items->AddLegalDocument(wallet::GetTestLegalDocument());
1597
1598    Reset();
1599    controller()->OnDidGetWalletItems(wallet_items.Pass());
1600
1601    // The dialog is only equipped to handle 2-6 legal documents. More than
1602    // 6 errors out.
1603    if (number_of_docs <= 6U) {
1604      EXPECT_FALSE(controller()->LegalDocumentsText().empty());
1605    } else {
1606      EXPECT_TRUE(controller()->LegalDocumentsText().empty());
1607      EXPECT_EQ(1U, NotificationsOfType(
1608          DialogNotification::WALLET_ERROR).size());
1609    }
1610  }
1611
1612  controller()->OnCancel();
1613}
1614
1615// Makes sure the default object IDs are respected.
1616TEST_F(AutofillDialogControllerTest, WalletDefaultItems) {
1617  scoped_ptr<wallet::WalletItems> wallet_items =
1618      wallet::GetTestWalletItems(wallet::AMEX_DISALLOWED);
1619  wallet_items->AddInstrument(wallet::GetTestNonDefaultMaskedInstrument());
1620  wallet_items->AddInstrument(wallet::GetTestNonDefaultMaskedInstrument());
1621  wallet_items->AddInstrument(wallet::GetTestMaskedInstrument());
1622  wallet_items->AddInstrument(wallet::GetTestNonDefaultMaskedInstrument());
1623
1624  wallet_items->AddAddress(wallet::GetTestNonDefaultShippingAddress());
1625  wallet_items->AddAddress(wallet::GetTestNonDefaultShippingAddress());
1626  wallet_items->AddAddress(wallet::GetTestNonDefaultShippingAddress());
1627  wallet_items->AddAddress(wallet::GetTestShippingAddress());
1628  wallet_items->AddAddress(wallet::GetTestNonDefaultShippingAddress());
1629
1630  controller()->OnDidGetWalletItems(wallet_items.Pass());
1631  // "add", "manage", and 4 suggestions.
1632  EXPECT_EQ(6,
1633      controller()->MenuModelForSection(SECTION_CC_BILLING)->GetItemCount());
1634  EXPECT_TRUE(controller()->MenuModelForSection(SECTION_CC_BILLING)->
1635      IsItemCheckedAt(2));
1636  ASSERT_FALSE(controller()->IsEditingExistingData(SECTION_CC_BILLING));
1637  // "use billing", "add", "manage", and 5 suggestions.
1638  EXPECT_EQ(8,
1639      controller()->MenuModelForSection(SECTION_SHIPPING)->GetItemCount());
1640  EXPECT_TRUE(controller()->MenuModelForSection(SECTION_SHIPPING)->
1641      IsItemCheckedAt(4));
1642  ASSERT_FALSE(controller()->IsEditingExistingData(SECTION_SHIPPING));
1643}
1644
1645// Tests that invalid and AMEX default instruments are ignored.
1646TEST_F(AutofillDialogControllerTest, SelectInstrument) {
1647  scoped_ptr<wallet::WalletItems> wallet_items =
1648      wallet::GetTestWalletItems(wallet::AMEX_DISALLOWED);
1649  // Tests if default instrument is invalid, then, the first valid instrument is
1650  // selected instead of the default instrument.
1651  wallet_items->AddInstrument(wallet::GetTestNonDefaultMaskedInstrument());
1652  wallet_items->AddInstrument(wallet::GetTestNonDefaultMaskedInstrument());
1653  wallet_items->AddInstrument(wallet::GetTestMaskedInstrumentInvalid());
1654  wallet_items->AddInstrument(wallet::GetTestNonDefaultMaskedInstrument());
1655
1656  controller()->OnDidGetWalletItems(wallet_items.Pass());
1657  // 4 suggestions and "add", "manage".
1658  EXPECT_EQ(6,
1659      controller()->MenuModelForSection(SECTION_CC_BILLING)->GetItemCount());
1660  EXPECT_TRUE(controller()->MenuModelForSection(SECTION_CC_BILLING)->
1661      IsItemCheckedAt(0));
1662
1663  // Tests if default instrument is AMEX but Wallet doesn't support
1664  // AMEX on this merchant, then the first valid instrument is
1665  // selected instead of the default instrument.
1666  wallet_items = wallet::GetTestWalletItems(wallet::AMEX_DISALLOWED);
1667  wallet_items->AddInstrument(wallet::GetTestNonDefaultMaskedInstrument());
1668  wallet_items->AddInstrument(wallet::GetTestNonDefaultMaskedInstrument());
1669  wallet_items->AddInstrument(
1670      wallet::GetTestMaskedInstrumentAmex(wallet::AMEX_DISALLOWED));
1671  wallet_items->AddInstrument(wallet::GetTestNonDefaultMaskedInstrument());
1672
1673  controller()->OnDidGetWalletItems(wallet_items.Pass());
1674  // 4 suggestions and "add", "manage".
1675  EXPECT_EQ(6,
1676      controller()->MenuModelForSection(SECTION_CC_BILLING)->GetItemCount());
1677  EXPECT_TRUE(controller()->MenuModelForSection(SECTION_CC_BILLING)->
1678      IsItemCheckedAt(0));
1679
1680  // Tests if default instrument is AMEX and it is allowed on this merchant,
1681  // then it is selected.
1682  wallet_items = wallet::GetTestWalletItems(wallet::AMEX_ALLOWED);
1683  wallet_items->AddInstrument(wallet::GetTestNonDefaultMaskedInstrument());
1684  wallet_items->AddInstrument(wallet::GetTestNonDefaultMaskedInstrument());
1685  wallet_items->AddInstrument(
1686      wallet::GetTestMaskedInstrumentAmex(wallet::AMEX_ALLOWED));
1687  wallet_items->AddInstrument(wallet::GetTestNonDefaultMaskedInstrument());
1688
1689  controller()->OnDidGetWalletItems(wallet_items.Pass());
1690  // 4 suggestions and "add", "manage".
1691  EXPECT_EQ(6,
1692      controller()->MenuModelForSection(SECTION_CC_BILLING)->GetItemCount());
1693  EXPECT_TRUE(controller()->MenuModelForSection(SECTION_CC_BILLING)->
1694      IsItemCheckedAt(2));
1695
1696  // Tests if only have AMEX and invalid instrument, then "add" is selected.
1697  wallet_items = wallet::GetTestWalletItems(wallet::AMEX_DISALLOWED);
1698  wallet_items->AddInstrument(wallet::GetTestMaskedInstrumentInvalid());
1699  wallet_items->AddInstrument(
1700      wallet::GetTestMaskedInstrumentAmex(wallet::AMEX_DISALLOWED));
1701
1702  controller()->OnDidGetWalletItems(wallet_items.Pass());
1703  // 2 suggestions and "add", "manage".
1704  EXPECT_EQ(4,
1705      controller()->MenuModelForSection(SECTION_CC_BILLING)->GetItemCount());
1706  // "add"
1707  EXPECT_TRUE(controller()->MenuModelForSection(SECTION_CC_BILLING)->
1708      IsItemCheckedAt(2));
1709}
1710
1711TEST_F(AutofillDialogControllerTest, SaveAddress) {
1712  EXPECT_CALL(*controller()->GetView(), ModelChanged());
1713  EXPECT_CALL(*controller()->GetTestingWalletClient(),
1714              SaveToWalletMock(testing::IsNull(),
1715                               testing::NotNull(),
1716                               testing::IsNull(),
1717                               testing::IsNull()));
1718
1719  scoped_ptr<wallet::WalletItems> wallet_items =
1720      wallet::GetTestWalletItems(wallet::AMEX_DISALLOWED);
1721  wallet_items->AddInstrument(wallet::GetTestMaskedInstrument());
1722  controller()->OnDidGetWalletItems(wallet_items.Pass());
1723  // If there is no shipping address in wallet, it will default to
1724  // "same-as-billing" instead of "add-new-item". "same-as-billing" is covered
1725  // by the following tests. The penultimate item in the menu is "add-new-item".
1726  ui::MenuModel* shipping_model =
1727      controller()->MenuModelForSection(SECTION_SHIPPING);
1728  shipping_model->ActivatedAt(shipping_model->GetItemCount() - 2);
1729
1730  AutofillProfile test_profile(test::GetVerifiedProfile());
1731  FillInputs(SECTION_SHIPPING, test_profile);
1732
1733  AcceptAndLoadFakeFingerprint();
1734}
1735
1736TEST_F(AutofillDialogControllerTest, SaveInstrument) {
1737  EXPECT_CALL(*controller()->GetView(), ModelChanged());
1738  EXPECT_CALL(*controller()->GetTestingWalletClient(),
1739              SaveToWalletMock(testing::NotNull(),
1740                               testing::IsNull(),
1741                               testing::IsNull(),
1742                               testing::IsNull()));
1743
1744  FillCCBillingInputs();
1745  scoped_ptr<wallet::WalletItems> wallet_items =
1746      wallet::GetTestWalletItems(wallet::AMEX_DISALLOWED);
1747  wallet_items->AddAddress(wallet::GetTestShippingAddress());
1748  SubmitWithWalletItems(wallet_items.Pass());
1749}
1750
1751TEST_F(AutofillDialogControllerTest, SaveInstrumentWithInvalidInstruments) {
1752  EXPECT_CALL(*controller()->GetView(), ModelChanged());
1753  EXPECT_CALL(*controller()->GetTestingWalletClient(),
1754              SaveToWalletMock(testing::NotNull(),
1755                               testing::IsNull(),
1756                               testing::IsNull(),
1757                               testing::IsNull()));
1758
1759  FillCCBillingInputs();
1760  scoped_ptr<wallet::WalletItems> wallet_items =
1761      wallet::GetTestWalletItems(wallet::AMEX_DISALLOWED);
1762  wallet_items->AddAddress(wallet::GetTestShippingAddress());
1763  wallet_items->AddInstrument(wallet::GetTestMaskedInstrumentInvalid());
1764  SubmitWithWalletItems(wallet_items.Pass());
1765}
1766
1767TEST_F(AutofillDialogControllerTest, SaveInstrumentAndAddress) {
1768  EXPECT_CALL(*controller()->GetTestingWalletClient(),
1769              SaveToWalletMock(testing::NotNull(),
1770                               testing::NotNull(),
1771                               testing::IsNull(),
1772                               testing::IsNull()));
1773
1774  FillCCBillingInputs();
1775  scoped_ptr<wallet::WalletItems> wallet_items =
1776      wallet::GetTestWalletItems(wallet::AMEX_DISALLOWED);
1777  SubmitWithWalletItems(wallet_items.Pass());
1778}
1779
1780MATCHER(IsUpdatingExistingData, "updating existing Wallet data") {
1781  return !arg->object_id().empty();
1782}
1783
1784MATCHER(UsesLocalBillingAddress, "uses the local billing address") {
1785  return arg->street_address()[0] == ASCIIToUTF16(kEditedBillingAddress);
1786}
1787
1788// Tests that when using billing address for shipping, and there is no exact
1789// matched shipping address, then a shipping address should be added.
1790TEST_F(AutofillDialogControllerTest, BillingForShipping) {
1791  EXPECT_CALL(*controller()->GetTestingWalletClient(),
1792              SaveToWalletMock(testing::IsNull(),
1793                               testing::NotNull(),
1794                               testing::IsNull(),
1795                               testing::IsNull()));
1796
1797  controller()->OnDidGetWalletItems(CompleteAndValidWalletItems());
1798  // Select "Same as billing" in the address menu.
1799  UseBillingForShipping();
1800
1801  AcceptAndLoadFakeFingerprint();
1802}
1803
1804// Tests that when using billing address for shipping, and there is an exact
1805// matched shipping address, then a shipping address should not be added.
1806TEST_F(AutofillDialogControllerTest, BillingForShippingHasMatch) {
1807  EXPECT_CALL(*controller()->GetTestingWalletClient(),
1808              SaveToWalletMock(_, _, _, _)).Times(0);
1809
1810  scoped_ptr<wallet::WalletItems> wallet_items =
1811      wallet::GetTestWalletItems(wallet::AMEX_DISALLOWED);
1812  scoped_ptr<wallet::WalletItems::MaskedInstrument> instrument =
1813      wallet::GetTestMaskedInstrument();
1814  // Copy billing address as shipping address, and assign an id to it.
1815  scoped_ptr<wallet::Address> shipping_address(
1816      new wallet::Address(instrument->address()));
1817  shipping_address->set_object_id("shipping_address_id");
1818  wallet_items->AddAddress(shipping_address.Pass());
1819  wallet_items->AddInstrument(instrument.Pass());
1820  wallet_items->AddAddress(wallet::GetTestShippingAddress());
1821
1822  controller()->OnDidGetWalletItems(wallet_items.Pass());
1823  // Select "Same as billing" in the address menu.
1824  UseBillingForShipping();
1825
1826  AcceptAndLoadFakeFingerprint();
1827}
1828
1829// Test that the local view contents is used when saving a new instrument and
1830// the user has selected "Same as billing".
1831TEST_F(AutofillDialogControllerTest, SaveInstrumentSameAsBilling) {
1832  scoped_ptr<wallet::WalletItems> wallet_items =
1833      wallet::GetTestWalletItems(wallet::AMEX_DISALLOWED);
1834  wallet_items->AddInstrument(wallet::GetTestMaskedInstrument());
1835  controller()->OnDidGetWalletItems(wallet_items.Pass());
1836
1837  ui::MenuModel* model = controller()->MenuModelForSection(SECTION_CC_BILLING);
1838  model->ActivatedAt(model->GetItemCount() - 2);
1839
1840  FieldValueMap outputs;
1841  const DetailInputs& inputs =
1842      controller()->RequestedFieldsForSection(SECTION_CC_BILLING);
1843  AutofillProfile full_profile(test::GetVerifiedProfile());
1844  CreditCard full_card(test::GetCreditCard());
1845  for (size_t i = 0; i < inputs.size(); ++i) {
1846    const ServerFieldType type = inputs[i].type;
1847    if (type == ADDRESS_BILLING_STREET_ADDRESS)
1848      outputs[type] = ASCIIToUTF16(kEditedBillingAddress);
1849    else
1850      outputs[type] = full_profile.GetInfo(AutofillType(type), "en-US");
1851
1852    if (outputs[type].empty())
1853      outputs[type] = full_card.GetInfo(AutofillType(type), "en-US");
1854  }
1855  controller()->GetView()->SetUserInput(SECTION_CC_BILLING, outputs);
1856
1857  controller()->OnAccept();
1858
1859  EXPECT_CALL(*controller()->GetTestingWalletClient(),
1860              SaveToWalletMock(testing::NotNull(),
1861                               UsesLocalBillingAddress(),
1862                               testing::IsNull(),
1863                               testing::IsNull()));
1864  AcceptAndLoadFakeFingerprint();
1865}
1866
1867TEST_F(AutofillDialogControllerTest, CancelNoSave) {
1868  EXPECT_CALL(*controller()->GetTestingWalletClient(),
1869              SaveToWalletMock(_, _, _, _)).Times(0);
1870
1871  EXPECT_CALL(*controller()->GetView(), ModelChanged());
1872
1873  controller()->OnDidGetWalletItems(
1874      wallet::GetTestWalletItems(wallet::AMEX_DISALLOWED));
1875  controller()->OnCancel();
1876}
1877
1878// Checks that clicking the Manage menu item opens a new tab with a different
1879// URL for Wallet and Autofill.
1880TEST_F(AutofillDialogControllerTest, ManageItem) {
1881  AutofillProfile full_profile(test::GetVerifiedProfile());
1882  full_profile.set_origin(kSettingsOrigin);
1883  full_profile.SetRawInfo(ADDRESS_HOME_LINE2, base::string16());
1884  controller()->GetTestingManager()->AddTestingProfile(&full_profile);
1885  SwitchToAutofill();
1886
1887  SuggestionsMenuModel* shipping = GetMenuModelForSection(SECTION_SHIPPING);
1888  shipping->ExecuteCommand(shipping->GetItemCount() - 1, 0);
1889  GURL autofill_manage_url = controller()->open_tab_url();
1890  EXPECT_EQ("chrome", autofill_manage_url.scheme());
1891
1892  SwitchToWallet();
1893  scoped_ptr<wallet::WalletItems> wallet_items =
1894      wallet::GetTestWalletItems(wallet::AMEX_DISALLOWED);
1895  wallet_items->AddInstrument(wallet::GetTestMaskedInstrument());
1896  controller()->OnDidGetWalletItems(wallet_items.Pass());
1897
1898  controller()->SuggestionItemSelected(shipping, shipping->GetItemCount() - 1);
1899  GURL wallet_manage_addresses_url = controller()->open_tab_url();
1900  EXPECT_EQ("https", wallet_manage_addresses_url.scheme());
1901
1902  SuggestionsMenuModel* billing = GetMenuModelForSection(SECTION_CC_BILLING);
1903  controller()->SuggestionItemSelected(billing, billing->GetItemCount() - 1);
1904  GURL wallet_manage_instruments_url = controller()->open_tab_url();
1905  EXPECT_EQ("https", wallet_manage_instruments_url.scheme());
1906
1907  EXPECT_NE(autofill_manage_url, wallet_manage_instruments_url);
1908  EXPECT_NE(wallet_manage_instruments_url, wallet_manage_addresses_url);
1909}
1910
1911// Tests that adding an autofill profile and then submitting works.
1912TEST_F(AutofillDialogControllerTest, AddAutofillProfile) {
1913  SwitchToAutofill();
1914  EXPECT_CALL(*controller()->GetView(), ModelChanged()).Times(2);
1915
1916  AutofillProfile full_profile(test::GetVerifiedProfile());
1917  CreditCard credit_card(test::GetVerifiedCreditCard());
1918  controller()->GetTestingManager()->AddTestingProfile(&full_profile);
1919  controller()->GetTestingManager()->AddTestingCreditCard(&credit_card);
1920
1921  ui::MenuModel* model = controller()->MenuModelForSection(SECTION_BILLING);
1922  // Activate the "Add billing address" menu item.
1923  model->ActivatedAt(model->GetItemCount() - 2);
1924
1925  // Fill in the inputs from the profile.
1926  FieldValueMap outputs;
1927  const DetailInputs& inputs =
1928      controller()->RequestedFieldsForSection(SECTION_BILLING);
1929  AutofillProfile full_profile2(test::GetVerifiedProfile2());
1930  for (size_t i = 0; i < inputs.size(); ++i) {
1931    const ServerFieldType type = inputs[i].type;
1932    outputs[type] = full_profile2.GetInfo(AutofillType(type), "en-US");
1933  }
1934  controller()->GetView()->SetUserInput(SECTION_BILLING, outputs);
1935
1936  controller()->OnAccept();
1937  const AutofillProfile& added_profile =
1938      controller()->GetTestingManager()->imported_profile();
1939
1940  const DetailInputs& shipping_inputs =
1941      controller()->RequestedFieldsForSection(SECTION_SHIPPING);
1942  for (size_t i = 0; i < shipping_inputs.size(); ++i) {
1943    const ServerFieldType type = shipping_inputs[i].type;
1944    EXPECT_EQ(full_profile2.GetInfo(AutofillType(type), "en-US"),
1945              added_profile.GetInfo(AutofillType(type), "en-US"));
1946  }
1947}
1948
1949TEST_F(AutofillDialogControllerTest, VerifyCvv) {
1950  EXPECT_CALL(*controller()->GetTestingWalletClient(), GetFullWallet(_));
1951  EXPECT_CALL(*controller()->GetTestingWalletClient(),
1952              AuthenticateInstrument(_, _));
1953
1954  SubmitWithWalletItems(CompleteAndValidWalletItems());
1955
1956  EXPECT_TRUE(NotificationsOfType(DialogNotification::REQUIRED_ACTION).empty());
1957  EXPECT_TRUE(controller()->SectionIsActive(SECTION_SHIPPING));
1958  EXPECT_TRUE(controller()->SectionIsActive(SECTION_CC_BILLING));
1959  EXPECT_FALSE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_OK));
1960  EXPECT_FALSE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_CANCEL));
1961
1962  SuggestionState suggestion_state =
1963      controller()->SuggestionStateForSection(SECTION_CC_BILLING);
1964  EXPECT_TRUE(suggestion_state.extra_text.empty());
1965
1966  controller()->OnDidGetFullWallet(
1967      wallet::GetTestFullWalletWithRequiredActions(
1968          std::vector<wallet::RequiredAction>(1, wallet::VERIFY_CVV)));
1969  ASSERT_TRUE(controller()->IsSubmitPausedOn(wallet::VERIFY_CVV));
1970
1971  EXPECT_FALSE(
1972      NotificationsOfType(DialogNotification::REQUIRED_ACTION).empty());
1973  EXPECT_FALSE(controller()->SectionIsActive(SECTION_SHIPPING));
1974  EXPECT_TRUE(controller()->SectionIsActive(SECTION_CC_BILLING));
1975
1976  suggestion_state =
1977      controller()->SuggestionStateForSection(SECTION_CC_BILLING);
1978  EXPECT_FALSE(suggestion_state.extra_text.empty());
1979  EXPECT_FALSE(controller()->MenuModelForSection(SECTION_CC_BILLING));
1980
1981  EXPECT_TRUE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_OK));
1982  EXPECT_TRUE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_CANCEL));
1983
1984  controller()->OnAccept();
1985
1986  EXPECT_FALSE(controller()->GetDialogOverlay().image.IsEmpty());
1987}
1988
1989TEST_F(AutofillDialogControllerTest, ErrorDuringSubmit) {
1990  EXPECT_CALL(*controller()->GetTestingWalletClient(), GetFullWallet(_));
1991
1992  SubmitWithWalletItems(CompleteAndValidWalletItems());
1993
1994  EXPECT_FALSE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_OK));
1995  EXPECT_FALSE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_CANCEL));
1996
1997  controller()->OnWalletError(wallet::WalletClient::UNKNOWN_ERROR);
1998
1999  EXPECT_TRUE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_OK));
2000  EXPECT_TRUE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_CANCEL));
2001}
2002
2003TEST_F(AutofillDialogControllerTest, ErrorDuringVerifyCvv) {
2004  EXPECT_CALL(*controller()->GetTestingWalletClient(), GetFullWallet(_));
2005
2006  SubmitWithWalletItems(CompleteAndValidWalletItems());
2007  controller()->OnDidGetFullWallet(
2008      wallet::GetTestFullWalletWithRequiredActions(
2009          std::vector<wallet::RequiredAction>(1, wallet::VERIFY_CVV)));
2010
2011  ASSERT_TRUE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_OK));
2012  ASSERT_TRUE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_CANCEL));
2013
2014  controller()->OnWalletError(wallet::WalletClient::UNKNOWN_ERROR);
2015
2016  EXPECT_TRUE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_OK));
2017  EXPECT_TRUE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_CANCEL));
2018}
2019
2020// Simulates receiving an INVALID_FORM_FIELD required action while processing a
2021// |WalletClientDelegate::OnDid{Save,Update}*()| call. This can happen if Online
2022// Wallet's server validation differs from Chrome's local validation.
2023TEST_F(AutofillDialogControllerTest, WalletServerSideValidation) {
2024  scoped_ptr<wallet::WalletItems> wallet_items =
2025      wallet::GetTestWalletItems(wallet::AMEX_DISALLOWED);
2026  wallet_items->AddInstrument(wallet::GetTestMaskedInstrument());
2027  controller()->OnDidGetWalletItems(wallet_items.Pass());
2028  controller()->OnAccept();
2029
2030  std::vector<wallet::RequiredAction> required_actions;
2031  required_actions.push_back(wallet::INVALID_FORM_FIELD);
2032
2033  std::vector<wallet::FormFieldError> form_errors;
2034  form_errors.push_back(
2035      wallet::FormFieldError(wallet::FormFieldError::INVALID_POSTAL_CODE,
2036                             wallet::FormFieldError::SHIPPING_ADDRESS));
2037
2038  EXPECT_CALL(*controller()->GetView(), UpdateForErrors());
2039  controller()->OnDidSaveToWallet(std::string(),
2040                                  std::string(),
2041                                  required_actions,
2042                                  form_errors);
2043}
2044
2045// Simulates receiving unrecoverable Wallet server validation errors.
2046TEST_F(AutofillDialogControllerTest, WalletServerSideValidationUnrecoverable) {
2047  scoped_ptr<wallet::WalletItems> wallet_items =
2048      wallet::GetTestWalletItems(wallet::AMEX_DISALLOWED);
2049  wallet_items->AddInstrument(wallet::GetTestMaskedInstrument());
2050  controller()->OnDidGetWalletItems(wallet_items.Pass());
2051  controller()->OnAccept();
2052
2053  std::vector<wallet::RequiredAction> required_actions;
2054  required_actions.push_back(wallet::INVALID_FORM_FIELD);
2055
2056  std::vector<wallet::FormFieldError> form_errors;
2057  form_errors.push_back(
2058      wallet::FormFieldError(wallet::FormFieldError::UNKNOWN_ERROR,
2059                             wallet::FormFieldError::UNKNOWN_LOCATION));
2060
2061  controller()->OnDidSaveToWallet(std::string(),
2062                                  std::string(),
2063                                  required_actions,
2064                                  form_errors);
2065
2066  EXPECT_EQ(1U, NotificationsOfType(
2067      DialogNotification::REQUIRED_ACTION).size());
2068}
2069
2070// Test Wallet banners are show in the right situations. These banners promote
2071// saving details into Wallet (i.e. "[x] Save details to Wallet").
2072TEST_F(AutofillDialogControllerTest, WalletBanners) {
2073  // Simulate non-signed-in case.
2074  SetUpControllerWithFormData(DefaultFormData());
2075  GoogleServiceAuthError error(GoogleServiceAuthError::NONE);
2076  controller()->OnPassiveSigninFailure(error);
2077  EXPECT_EQ(0U, NotificationsOfType(
2078      DialogNotification::WALLET_USAGE_CONFIRMATION).size());
2079
2080  // Sign in a user with a completed account.
2081  SetUpControllerWithFormData(DefaultFormData());
2082  controller()->OnDidGetWalletItems(CompleteAndValidWalletItems());
2083
2084  // Full account; should show "Details from Wallet" message.
2085  EXPECT_EQ(1U, NotificationsOfType(
2086      DialogNotification::WALLET_USAGE_CONFIRMATION).size());
2087  SwitchToAutofill();
2088  EXPECT_EQ(1U, NotificationsOfType(
2089      DialogNotification::WALLET_USAGE_CONFIRMATION).size());
2090
2091  // Start over and sign in a user with an incomplete account.
2092  SetUpControllerWithFormData(DefaultFormData());
2093  scoped_ptr<wallet::WalletItems> wallet_items =
2094      wallet::GetTestWalletItems(wallet::AMEX_DISALLOWED);
2095  wallet_items->AddInstrument(wallet::GetTestMaskedInstrument());
2096  controller()->OnDidGetWalletItems(wallet_items.Pass());
2097
2098  // Partial account.
2099  EXPECT_EQ(1U, NotificationsOfType(
2100      DialogNotification::WALLET_USAGE_CONFIRMATION).size());
2101
2102  SwitchToAutofill();
2103  EXPECT_EQ(1U, NotificationsOfType(
2104      DialogNotification::WALLET_USAGE_CONFIRMATION).size());
2105
2106  // A Wallet error should kill any Wallet promos.
2107  controller()->OnWalletError(wallet::WalletClient::UNKNOWN_ERROR);
2108
2109  EXPECT_EQ(1U, NotificationsOfType(
2110      DialogNotification::WALLET_ERROR).size());
2111  EXPECT_EQ(0U, NotificationsOfType(
2112      DialogNotification::WALLET_USAGE_CONFIRMATION).size());
2113}
2114
2115TEST_F(AutofillDialogControllerTest, ViewCancelDoesntSetPref) {
2116  ASSERT_FALSE(profile()->GetPrefs()->HasPrefPath(
2117      ::prefs::kAutofillDialogPayWithoutWallet));
2118
2119  SwitchToAutofill();
2120
2121  controller()->OnCancel();
2122  controller()->ViewClosed();
2123
2124  EXPECT_FALSE(profile()->GetPrefs()->HasPrefPath(
2125      ::prefs::kAutofillDialogPayWithoutWallet));
2126}
2127
2128TEST_F(AutofillDialogControllerTest, SubmitWithSigninErrorDoesntSetPref) {
2129  ASSERT_FALSE(profile()->GetPrefs()->HasPrefPath(
2130      ::prefs::kAutofillDialogPayWithoutWallet));
2131
2132  SimulateSigninError();
2133  FillCreditCardInputs();
2134  controller()->OnAccept();
2135
2136  EXPECT_FALSE(profile()->GetPrefs()->HasPrefPath(
2137      ::prefs::kAutofillDialogPayWithoutWallet));
2138}
2139
2140// Tests that there's an overlay shown while waiting for full wallet items.
2141TEST_F(AutofillDialogControllerTest, WalletFirstRun) {
2142  EXPECT_TRUE(controller()->GetDialogOverlay().image.IsEmpty());
2143
2144  SubmitWithWalletItems(CompleteAndValidWalletItems());
2145  EXPECT_FALSE(controller()->GetDialogOverlay().image.IsEmpty());
2146
2147  controller()->OnDidGetFullWallet(wallet::GetTestFullWallet());
2148  EXPECT_FALSE(controller()->GetDialogOverlay().image.IsEmpty());
2149  EXPECT_FALSE(form_structure());
2150
2151  // Don't make the test wait for 2 seconds.
2152  controller()->ForceFinishSubmit();
2153  EXPECT_TRUE(form_structure());
2154}
2155
2156TEST_F(AutofillDialogControllerTest, ViewSubmitSetsPref) {
2157  ASSERT_FALSE(profile()->GetPrefs()->HasPrefPath(
2158      ::prefs::kAutofillDialogPayWithoutWallet));
2159
2160  SwitchToAutofill();
2161  FillCreditCardInputs();
2162  controller()->OnAccept();
2163
2164  EXPECT_TRUE(profile()->GetPrefs()->HasPrefPath(
2165      ::prefs::kAutofillDialogPayWithoutWallet));
2166  EXPECT_TRUE(profile()->GetPrefs()->GetBoolean(
2167      ::prefs::kAutofillDialogPayWithoutWallet));
2168
2169  // Try again with a signin error (just leaves the pref alone).
2170  SetUpControllerWithFormData(DefaultFormData());
2171
2172  // Setting up the controller again should not change the pref.
2173  EXPECT_TRUE(profile()->GetPrefs()->HasPrefPath(
2174      ::prefs::kAutofillDialogPayWithoutWallet));
2175  EXPECT_TRUE(profile()->GetPrefs()->GetBoolean(
2176      ::prefs::kAutofillDialogPayWithoutWallet));
2177
2178  SimulateSigninError();
2179  FillCreditCardInputs();
2180  controller()->OnAccept();
2181  EXPECT_TRUE(profile()->GetPrefs()->HasPrefPath(
2182      ::prefs::kAutofillDialogPayWithoutWallet));
2183  EXPECT_TRUE(profile()->GetPrefs()->GetBoolean(
2184      ::prefs::kAutofillDialogPayWithoutWallet));
2185
2186  // Successfully choosing wallet does set the pref.
2187  // Note that OnDidGetWalletItems sets the account chooser to wallet mode.
2188  SetUpControllerWithFormData(DefaultFormData());
2189
2190  controller()->OnDidFetchWalletCookieValue(std::string());
2191  scoped_ptr<wallet::WalletItems> wallet_items =
2192      wallet::GetTestWalletItems(wallet::AMEX_DISALLOWED);
2193  wallet_items->AddInstrument(wallet::GetTestMaskedInstrument());
2194  controller()->OnDidGetWalletItems(wallet_items.Pass());
2195  controller()->OnAccept();
2196  controller()->OnDidGetFullWallet(wallet::GetTestFullWallet());
2197  controller()->ForceFinishSubmit();
2198
2199  EXPECT_TRUE(profile()->GetPrefs()->HasPrefPath(
2200      ::prefs::kAutofillDialogPayWithoutWallet));
2201  EXPECT_FALSE(profile()->GetPrefs()->GetBoolean(
2202      ::prefs::kAutofillDialogPayWithoutWallet));
2203}
2204
2205TEST_F(AutofillDialogControllerTest, HideWalletEmail) {
2206  SwitchToAutofill();
2207
2208  // Email field should be showing when using Autofill.
2209  EXPECT_TRUE(controller()->SectionIsActive(SECTION_BILLING));
2210  EXPECT_FALSE(controller()->SectionIsActive(SECTION_CC_BILLING));
2211  EXPECT_TRUE(SectionContainsField(SECTION_BILLING, EMAIL_ADDRESS));
2212
2213  SwitchToWallet();
2214
2215  // Reset the wallet state.
2216  controller()->OnDidGetWalletItems(scoped_ptr<wallet::WalletItems>());
2217
2218  // Setup some wallet state, submit, and get a full wallet to end the flow.
2219  scoped_ptr<wallet::WalletItems> wallet_items = CompleteAndValidWalletItems();
2220
2221  // Filling |form_structure()| depends on the current username and wallet items
2222  // being fetched. Until both of these have occurred, the user should not be
2223  // able to click Submit if using Wallet. The username fetch happened earlier.
2224  EXPECT_FALSE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_OK));
2225  controller()->OnDidGetWalletItems(wallet_items.Pass());
2226  EXPECT_TRUE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_OK));
2227
2228  // Email field should be absent when using Wallet.
2229  EXPECT_FALSE(controller()->SectionIsActive(SECTION_BILLING));
2230  EXPECT_TRUE(controller()->SectionIsActive(SECTION_CC_BILLING));
2231  EXPECT_FALSE(SectionContainsField(SECTION_CC_BILLING, EMAIL_ADDRESS));
2232
2233  controller()->OnAccept();
2234  controller()->OnDidGetFullWallet(wallet::GetTestFullWallet());
2235  controller()->ForceFinishSubmit();
2236
2237  ASSERT_TRUE(form_structure());
2238  size_t i = 0;
2239  for (; i < form_structure()->field_count(); ++i) {
2240    if (form_structure()->field(i)->Type().GetStorableType() == EMAIL_ADDRESS) {
2241      EXPECT_EQ(ASCIIToUTF16(kFakeEmail), form_structure()->field(i)->value);
2242      break;
2243    }
2244  }
2245  EXPECT_LT(i, form_structure()->field_count());
2246}
2247
2248// Test if autofill types of returned form structure are correct for billing
2249// entries.
2250TEST_F(AutofillDialogControllerTest, AutofillTypes) {
2251  controller()->OnDidGetWalletItems(CompleteAndValidWalletItems());
2252  controller()->OnAccept();
2253  controller()->OnDidGetFullWallet(wallet::GetTestFullWallet());
2254  controller()->ForceFinishSubmit();
2255  ASSERT_TRUE(form_structure());
2256  ASSERT_EQ(20U, form_structure()->field_count());
2257  EXPECT_EQ(EMAIL_ADDRESS,
2258            form_structure()->field(0)->Type().GetStorableType());
2259  EXPECT_EQ(CREDIT_CARD_NUMBER,
2260            form_structure()->field(2)->Type().GetStorableType());
2261  EXPECT_EQ(ADDRESS_HOME_STATE,
2262            form_structure()->field(9)->Type().GetStorableType());
2263  EXPECT_EQ(ADDRESS_BILLING, form_structure()->field(9)->Type().group());
2264  EXPECT_EQ(ADDRESS_HOME_STATE,
2265            form_structure()->field(16)->Type().GetStorableType());
2266  EXPECT_EQ(ADDRESS_HOME, form_structure()->field(16)->Type().group());
2267}
2268
2269TEST_F(AutofillDialogControllerTest, SaveDetailsInChrome) {
2270  SwitchToAutofill();
2271  EXPECT_CALL(*controller()->GetView(), ModelChanged()).Times(4);
2272
2273  AutofillProfile full_profile(test::GetVerifiedProfile());
2274  controller()->GetTestingManager()->AddTestingProfile(&full_profile);
2275
2276  CreditCard card(test::GetVerifiedCreditCard());
2277  controller()->GetTestingManager()->AddTestingCreditCard(&card);
2278  EXPECT_FALSE(controller()->ShouldOfferToSaveInChrome());
2279
2280  controller()->MenuModelForSection(SECTION_BILLING)->ActivatedAt(0);
2281  EXPECT_FALSE(controller()->ShouldOfferToSaveInChrome());
2282
2283  controller()->MenuModelForSection(SECTION_BILLING)->ActivatedAt(1);
2284  EXPECT_TRUE(controller()->ShouldOfferToSaveInChrome());
2285
2286  profile()->GetPrefs()->SetBoolean(prefs::kAutofillEnabled, false);
2287  EXPECT_FALSE(controller()->ShouldOfferToSaveInChrome());
2288
2289  profile()->GetPrefs()->SetBoolean(prefs::kAutofillEnabled, true);
2290  controller()->MenuModelForSection(SECTION_BILLING)->ActivatedAt(1);
2291  EXPECT_TRUE(controller()->ShouldOfferToSaveInChrome());
2292
2293  profile()->ForceIncognito(true);
2294  EXPECT_FALSE(controller()->ShouldOfferToSaveInChrome());
2295}
2296
2297TEST_F(AutofillDialogControllerTest, DisabledAutofill) {
2298  SwitchToAutofill();
2299  ASSERT_TRUE(profile()->GetPrefs()->GetBoolean(prefs::kAutofillEnabled));
2300
2301  AutofillProfile verified_profile(test::GetVerifiedProfile());
2302  controller()->GetTestingManager()->AddTestingProfile(&verified_profile);
2303
2304  CreditCard credit_card(test::GetVerifiedCreditCard());
2305  controller()->GetTestingManager()->AddTestingCreditCard(&credit_card);
2306
2307  // Verify suggestions menus should be showing when Autofill is enabled.
2308  EXPECT_TRUE(controller()->MenuModelForSection(SECTION_CC));
2309  EXPECT_TRUE(controller()->MenuModelForSection(SECTION_BILLING));
2310  EXPECT_EQ(
2311      4, controller()->MenuModelForSection(SECTION_SHIPPING)->GetItemCount());
2312
2313  EXPECT_CALL(*controller()->GetView(), ModelChanged());
2314  profile()->GetPrefs()->SetBoolean(prefs::kAutofillEnabled, false);
2315
2316  // Verify billing and credit card suggestions menus are hidden when Autofill
2317  // is disabled.
2318  EXPECT_FALSE(controller()->MenuModelForSection(SECTION_CC));
2319  EXPECT_FALSE(controller()->MenuModelForSection(SECTION_BILLING));
2320  // And that the shipping suggestions menu has less selections.
2321  EXPECT_EQ(
2322      2, controller()->MenuModelForSection(SECTION_SHIPPING)->GetItemCount());
2323
2324  // Additionally, editing fields should not show Autofill popups.
2325  ASSERT_NO_FATAL_FAILURE(controller()->UserEditedOrActivatedInput(
2326      SECTION_BILLING,
2327      NAME_BILLING_FULL,
2328      gfx::NativeView(),
2329      gfx::Rect(),
2330      verified_profile.GetRawInfo(NAME_FULL).substr(0, 1),
2331      true));
2332  EXPECT_EQ(UNKNOWN_TYPE, controller()->popup_input_type());
2333}
2334
2335// Tests that user is prompted when using instrument with minimal address.
2336TEST_F(AutofillDialogControllerTest, UpgradeMinimalAddress) {
2337  // A minimal address being selected should trigger error validation in the
2338  // view. Called once for each incomplete suggestion.
2339  EXPECT_CALL(*controller()->GetView(), UpdateForErrors());
2340
2341  scoped_ptr<wallet::WalletItems> wallet_items =
2342      wallet::GetTestWalletItems(wallet::AMEX_DISALLOWED);
2343  wallet_items->AddInstrument(wallet::GetTestMaskedInstrumentWithIdAndAddress(
2344      "id", wallet::GetTestMinimalAddress()));
2345  scoped_ptr<wallet::Address> address(wallet::GetTestShippingAddress());
2346  address->set_is_complete_address(false);
2347  wallet_items->AddAddress(address.Pass());
2348  controller()->OnDidGetWalletItems(wallet_items.Pass());
2349
2350  // Assert that dialog's SECTION_CC_BILLING section is in edit mode.
2351  ASSERT_TRUE(controller()->IsEditingExistingData(SECTION_CC_BILLING));
2352  // Shipping section should be in edit mode because of
2353  // is_minimal_shipping_address.
2354  ASSERT_TRUE(controller()->IsEditingExistingData(SECTION_SHIPPING));
2355}
2356
2357TEST_F(AutofillDialogControllerTest, RiskNeverLoadsWithPendingLegalDocuments) {
2358  EXPECT_CALL(*controller(), LoadRiskFingerprintData()).Times(0);
2359
2360  scoped_ptr<wallet::WalletItems> wallet_items = CompleteAndValidWalletItems();
2361  wallet_items->AddLegalDocument(wallet::GetTestLegalDocument());
2362  wallet_items->AddLegalDocument(wallet::GetTestLegalDocument());
2363  controller()->OnDidGetWalletItems(wallet_items.Pass());
2364  controller()->OnAccept();
2365}
2366
2367TEST_F(AutofillDialogControllerTest, RiskLoadsAfterAcceptingLegalDocuments) {
2368  EXPECT_CALL(*controller(), LoadRiskFingerprintData()).Times(0);
2369
2370  scoped_ptr<wallet::WalletItems> wallet_items = CompleteAndValidWalletItems();
2371  wallet_items->AddLegalDocument(wallet::GetTestLegalDocument());
2372  wallet_items->AddLegalDocument(wallet::GetTestLegalDocument());
2373  controller()->OnDidGetWalletItems(wallet_items.Pass());
2374
2375  testing::Mock::VerifyAndClear(controller());
2376  EXPECT_CALL(*controller(), LoadRiskFingerprintData());
2377
2378  controller()->OnAccept();
2379
2380  // Simulate a risk load and verify |GetRiskData()| matches the encoded value.
2381  controller()->OnDidAcceptLegalDocuments();
2382  controller()->OnDidLoadRiskFingerprintData(GetFakeFingerprint().Pass());
2383  EXPECT_EQ(kFakeFingerprintEncoded, controller()->GetRiskData());
2384}
2385
2386TEST_F(AutofillDialogControllerTest, NoManageMenuItemForNewWalletUsers) {
2387  // Make sure the menu model item is created for a returning Wallet user.
2388  scoped_ptr<wallet::WalletItems> wallet_items =
2389      wallet::GetTestWalletItems(wallet::AMEX_DISALLOWED);
2390  wallet_items->AddInstrument(wallet::GetTestMaskedInstrument());
2391  wallet_items->AddAddress(wallet::GetTestShippingAddress());
2392  controller()->OnDidGetWalletItems(wallet_items.Pass());
2393
2394  EXPECT_TRUE(controller()->MenuModelForSection(SECTION_CC_BILLING));
2395  // "Same as billing", "123 address", "Add address...", and "Manage addresses".
2396  EXPECT_EQ(
2397      4, controller()->MenuModelForSection(SECTION_SHIPPING)->GetItemCount());
2398
2399  // Make sure the menu model item is not created for new Wallet users.
2400  base::DictionaryValue dict;
2401  scoped_ptr<base::ListValue> required_actions(new base::ListValue);
2402  required_actions->AppendString("setup_wallet");
2403  dict.Set("required_action", required_actions.release());
2404  controller()->OnDidGetWalletItems(
2405      wallet::WalletItems::CreateWalletItems(dict).Pass());
2406
2407  EXPECT_FALSE(controller()->MenuModelForSection(SECTION_CC_BILLING));
2408  // "Same as billing" and "Add address...".
2409  EXPECT_EQ(
2410      2, controller()->MenuModelForSection(SECTION_SHIPPING)->GetItemCount());
2411}
2412
2413TEST_F(AutofillDialogControllerTest, ShippingSectionCanBeHidden) {
2414  FormFieldData email_field;
2415  email_field.autocomplete_attribute = "email";
2416  FormFieldData cc_field;
2417  cc_field.autocomplete_attribute = "cc-number";
2418  FormFieldData billing_field;
2419  billing_field.autocomplete_attribute = "billing address-level1";
2420
2421  FormData form_data;
2422  form_data.fields.push_back(email_field);
2423  form_data.fields.push_back(cc_field);
2424  form_data.fields.push_back(billing_field);
2425
2426  AutofillProfile full_profile(test::GetVerifiedProfile());
2427  controller()->GetTestingManager()->AddTestingProfile(&full_profile);
2428  SetUpControllerWithFormData(form_data);
2429
2430  SwitchToAutofill();
2431
2432  EXPECT_FALSE(controller()->SectionIsActive(SECTION_SHIPPING));
2433
2434  FillCreditCardInputs();
2435  controller()->OnAccept();
2436  EXPECT_TRUE(form_structure());
2437}
2438
2439TEST_F(AutofillDialogControllerTest, ShippingSectionCanBeHiddenForWallet) {
2440  FormFieldData email_field;
2441  email_field.autocomplete_attribute = "email";
2442  FormFieldData cc_field;
2443  cc_field.autocomplete_attribute = "cc-number";
2444  FormFieldData billing_field;
2445  billing_field.autocomplete_attribute = "billing address-level1";
2446
2447  FormData form_data;
2448  form_data.fields.push_back(email_field);
2449  form_data.fields.push_back(cc_field);
2450  form_data.fields.push_back(billing_field);
2451
2452  SetUpControllerWithFormData(form_data);
2453  EXPECT_FALSE(controller()->SectionIsActive(SECTION_SHIPPING));
2454  EXPECT_FALSE(controller()->IsShippingAddressRequired());
2455
2456  EXPECT_CALL(*controller()->GetTestingWalletClient(), GetFullWallet(_));
2457  scoped_ptr<wallet::WalletItems> wallet_items =
2458      wallet::GetTestWalletItems(wallet::AMEX_DISALLOWED);
2459  wallet_items->AddInstrument(wallet::GetTestMaskedInstrument());
2460  SubmitWithWalletItems(wallet_items.Pass());
2461  controller()->OnDidGetFullWallet(wallet::GetTestFullWalletInstrumentOnly());
2462  controller()->ForceFinishSubmit();
2463  EXPECT_TRUE(form_structure());
2464}
2465
2466TEST_F(AutofillDialogControllerTest, NotProdNotification) {
2467  // To make IsPayingWithWallet() true.
2468  controller()->OnDidGetWalletItems(
2469      wallet::GetTestWalletItems(wallet::AMEX_DISALLOWED));
2470
2471  CommandLine* command_line = CommandLine::ForCurrentProcess();
2472  ASSERT_EQ(
2473      "",
2474      command_line->GetSwitchValueASCII(switches::kWalletServiceUseSandbox));
2475
2476  command_line->AppendSwitchASCII(switches::kWalletServiceUseSandbox, "1");
2477  EXPECT_EQ(1U,
2478            NotificationsOfType(DialogNotification::DEVELOPER_WARNING).size());
2479}
2480
2481TEST_F(AutofillDialogControllerTest, NoNotProdNotification) {
2482  // To make IsPayingWithWallet() true.
2483  controller()->OnDidGetWalletItems(
2484      wallet::GetTestWalletItems(wallet::AMEX_DISALLOWED));
2485
2486  CommandLine* command_line = CommandLine::ForCurrentProcess();
2487  ASSERT_EQ(
2488      "",
2489      command_line->GetSwitchValueASCII(switches::kWalletServiceUseSandbox));
2490
2491  command_line->AppendSwitchASCII(switches::kWalletServiceUseSandbox, "0");
2492  EXPECT_EQ(0U,
2493            NotificationsOfType(DialogNotification::DEVELOPER_WARNING).size());
2494}
2495
2496// Ensure Wallet instruments marked expired by the server are shown as invalid.
2497TEST_F(AutofillDialogControllerTest, WalletExpiredCard) {
2498  scoped_ptr<wallet::WalletItems> wallet_items =
2499      wallet::GetTestWalletItems(wallet::AMEX_DISALLOWED);
2500  wallet_items->AddInstrument(wallet::GetTestMaskedInstrumentExpired());
2501  controller()->OnDidGetWalletItems(wallet_items.Pass());
2502
2503  EXPECT_TRUE(controller()->IsEditingExistingData(SECTION_CC_BILLING));
2504
2505  const DetailInputs& inputs =
2506      controller()->RequestedFieldsForSection(SECTION_CC_BILLING);
2507  FieldValueMap outputs;
2508  CopyInitialValues(inputs, &outputs);
2509
2510  // The local inputs are invalid because the server said so. They'll
2511  // stay invalid until they differ from the remotely fetched model.
2512  ValidityMessages messages = controller()->InputsAreValid(SECTION_CC_BILLING,
2513                                                           outputs);
2514  EXPECT_TRUE(messages.HasSureError(CREDIT_CARD_EXP_MONTH));
2515  EXPECT_TRUE(messages.HasSureError(CREDIT_CARD_EXP_4_DIGIT_YEAR));
2516
2517  // Make the local input year differ from the instrument.
2518  CopyInitialValues(inputs, &outputs);
2519  outputs[CREDIT_CARD_EXP_4_DIGIT_YEAR] = ASCIIToUTF16("3002");
2520  messages = controller()->InputsAreValid(SECTION_CC_BILLING, outputs);
2521  EXPECT_FALSE(HasAnyError(messages, CREDIT_CARD_EXP_MONTH));
2522  EXPECT_FALSE(HasAnyError(messages, CREDIT_CARD_EXP_4_DIGIT_YEAR));
2523
2524  // Make the local input month differ from the instrument.
2525  CopyInitialValues(inputs, &outputs);
2526  outputs[CREDIT_CARD_EXP_MONTH] = ASCIIToUTF16("06");
2527  messages = controller()->InputsAreValid(SECTION_CC_BILLING, outputs);
2528  EXPECT_FALSE(HasAnyError(messages, CREDIT_CARD_EXP_MONTH));
2529  EXPECT_FALSE(HasAnyError(messages, CREDIT_CARD_EXP_4_DIGIT_YEAR));
2530}
2531
2532TEST_F(AutofillDialogControllerTest, ChooseAnotherInstrumentOrAddress) {
2533  SubmitWithWalletItems(CompleteAndValidWalletItems());
2534
2535  EXPECT_EQ(0U, NotificationsOfType(
2536      DialogNotification::REQUIRED_ACTION).size());
2537  EXPECT_CALL(*controller()->GetTestingWalletClient(), GetWalletItems());
2538  controller()->OnDidGetFullWallet(
2539      wallet::GetTestFullWalletWithRequiredActions(
2540          std::vector<wallet::RequiredAction>(
2541              1, wallet::CHOOSE_ANOTHER_INSTRUMENT_OR_ADDRESS)));
2542  EXPECT_EQ(1U, NotificationsOfType(
2543      DialogNotification::REQUIRED_ACTION).size());
2544  controller()->OnDidGetWalletItems(CompleteAndValidWalletItems());
2545
2546  controller()->OnAccept();
2547  EXPECT_EQ(0U, NotificationsOfType(
2548      DialogNotification::REQUIRED_ACTION).size());
2549}
2550
2551TEST_F(AutofillDialogControllerTest, NewCardBubbleShown) {
2552  SwitchToAutofill();
2553  FillCreditCardInputs();
2554  controller()->OnAccept();
2555  controller()->ViewClosed();
2556
2557  EXPECT_EQ(1, mock_new_card_bubble_controller()->bubbles_shown());
2558  EXPECT_EQ(0, test_generated_bubble_controller()->bubbles_shown());
2559}
2560
2561TEST_F(AutofillDialogControllerTest, GeneratedCardBubbleShown) {
2562  SubmitWithWalletItems(CompleteAndValidWalletItems());
2563  controller()->OnDidGetFullWallet(wallet::GetTestFullWallet());
2564  controller()->ForceFinishSubmit();
2565  controller()->ViewClosed();
2566
2567  EXPECT_EQ(0, mock_new_card_bubble_controller()->bubbles_shown());
2568  EXPECT_EQ(1, test_generated_bubble_controller()->bubbles_shown());
2569}
2570
2571// Verify that new Wallet data is fetched when the user switches away from the
2572// tab hosting the Autofill dialog and back. Also verify that the user's
2573// selection is preserved across this re-fetch.
2574TEST_F(AutofillDialogControllerTest, ReloadWalletItemsOnActivation) {
2575  // Initialize some Wallet data.
2576  scoped_ptr<wallet::WalletItems> wallet_items =
2577      wallet::GetTestWalletItems(wallet::AMEX_DISALLOWED);
2578  wallet_items->AddInstrument(wallet::GetTestMaskedInstrument());
2579  wallet_items->AddInstrument(wallet::GetTestNonDefaultMaskedInstrument());
2580  wallet_items->AddAddress(wallet::GetTestNonDefaultShippingAddress());
2581  wallet_items->AddAddress(wallet::GetTestShippingAddress());
2582  controller()->OnDidGetWalletItems(wallet_items.Pass());
2583
2584  // Initially, the default entries should be selected.
2585  ui::MenuModel* cc_billing_model =
2586      controller()->MenuModelForSection(SECTION_CC_BILLING);
2587  ui::MenuModel* shipping_model =
2588      controller()->MenuModelForSection(SECTION_SHIPPING);
2589  // "add", "manage", and 2 suggestions.
2590  ASSERT_EQ(4, cc_billing_model->GetItemCount());
2591  EXPECT_TRUE(cc_billing_model->IsItemCheckedAt(0));
2592  // "use billing", "add", "manage", and 2 suggestions.
2593  ASSERT_EQ(5, shipping_model->GetItemCount());
2594  EXPECT_TRUE(shipping_model->IsItemCheckedAt(2));
2595
2596  // Select entries other than the defaults.
2597  cc_billing_model->ActivatedAt(1);
2598  shipping_model->ActivatedAt(1);
2599  // 2 suggestions, "add", and "manage".
2600  ASSERT_EQ(4, cc_billing_model->GetItemCount());
2601  EXPECT_TRUE(cc_billing_model->IsItemCheckedAt(1));
2602  // "use billing", 2 suggestions, "add", "manage".
2603  ASSERT_EQ(5, shipping_model->GetItemCount());
2604  EXPECT_TRUE(shipping_model-> IsItemCheckedAt(1));
2605
2606  // Simulate switching away from the tab and back.  This should issue a request
2607  // for wallet items.
2608  controller()->ClearLastWalletItemsFetchTimestampForTesting();
2609  EXPECT_CALL(*controller()->GetTestingWalletClient(), GetWalletItems());
2610  controller()->TabActivated();
2611
2612  // Simulate a response that includes different items.
2613  wallet_items = wallet::GetTestWalletItems(wallet::AMEX_DISALLOWED);
2614  wallet_items->AddInstrument(wallet::GetTestMaskedInstrumentExpired());
2615  wallet_items->AddInstrument(wallet::GetTestMaskedInstrument());
2616  wallet_items->AddInstrument(wallet::GetTestNonDefaultMaskedInstrument());
2617  wallet_items->AddAddress(wallet::GetTestNonDefaultShippingAddress());
2618  controller()->OnDidGetWalletItems(wallet_items.Pass());
2619
2620  // The previously selected entries should still be selected.
2621  // 3 suggestions, "add", and "manage".
2622  ASSERT_EQ(5, cc_billing_model->GetItemCount());
2623  EXPECT_TRUE(cc_billing_model->IsItemCheckedAt(2));
2624  // "use billing", 1 suggestion, "add", and "manage".
2625  ASSERT_EQ(4, shipping_model->GetItemCount());
2626  EXPECT_TRUE(shipping_model->IsItemCheckedAt(1));
2627}
2628
2629// Verify that if the default values change when re-fetching Wallet data, these
2630// new default values are selected in the dialog.
2631TEST_F(AutofillDialogControllerTest,
2632       ReloadWalletItemsOnActivationWithNewDefaults) {
2633  // Initialize some Wallet data.
2634  scoped_ptr<wallet::WalletItems> wallet_items =
2635      wallet::GetTestWalletItems(wallet::AMEX_DISALLOWED);
2636  wallet_items->AddInstrument(wallet::GetTestMaskedInstrument());
2637  wallet_items->AddInstrument(wallet::GetTestNonDefaultMaskedInstrument());
2638  wallet_items->AddAddress(wallet::GetTestNonDefaultShippingAddress());
2639  wallet_items->AddAddress(wallet::GetTestShippingAddress());
2640  controller()->OnDidGetWalletItems(wallet_items.Pass());
2641
2642  // Initially, the default entries should be selected.
2643  ui::MenuModel* cc_billing_model =
2644      controller()->MenuModelForSection(SECTION_CC_BILLING);
2645  ui::MenuModel* shipping_model =
2646      controller()->MenuModelForSection(SECTION_SHIPPING);
2647  // 2 suggestions, "add", and "manage".
2648  ASSERT_EQ(4, cc_billing_model->GetItemCount());
2649  EXPECT_TRUE(cc_billing_model->IsItemCheckedAt(0));
2650  // "use billing", 2 suggestions, "add", and "manage".
2651  ASSERT_EQ(5, shipping_model->GetItemCount());
2652  EXPECT_TRUE(shipping_model->IsItemCheckedAt(2));
2653
2654  // Simulate switching away from the tab and back.  This should issue a request
2655  // for wallet items.
2656  controller()->ClearLastWalletItemsFetchTimestampForTesting();
2657  EXPECT_CALL(*controller()->GetTestingWalletClient(), GetWalletItems());
2658  controller()->TabActivated();
2659
2660  // Simulate a response that includes different default values.
2661  wallet_items =
2662      wallet::GetTestWalletItemsWithDefaultIds("new_default_instrument_id",
2663                                               "new_default_address_id",
2664                                               wallet::AMEX_DISALLOWED);
2665  scoped_ptr<wallet::Address> other_address = wallet::GetTestShippingAddress();
2666  other_address->set_object_id("other_address_id");
2667  scoped_ptr<wallet::Address> new_default_address =
2668      wallet::GetTestNonDefaultShippingAddress();
2669  new_default_address->set_object_id("new_default_address_id");
2670
2671  wallet_items->AddInstrument(
2672      wallet::GetTestMaskedInstrumentWithId("other_instrument_id"));
2673  wallet_items->AddInstrument(
2674      wallet::GetTestMaskedInstrumentWithId("new_default_instrument_id"));
2675  wallet_items->AddAddress(new_default_address.Pass());
2676  wallet_items->AddAddress(other_address.Pass());
2677  controller()->OnDidGetWalletItems(wallet_items.Pass());
2678
2679  // The new default entries should be selected.
2680  // 2 suggestions, "add", and "manage".
2681  ASSERT_EQ(4, cc_billing_model->GetItemCount());
2682  EXPECT_TRUE(cc_billing_model->IsItemCheckedAt(1));
2683  // "use billing", 2 suggestions, "add", and "manage".
2684  ASSERT_EQ(5, shipping_model->GetItemCount());
2685  EXPECT_TRUE(shipping_model->IsItemCheckedAt(1));
2686}
2687
2688TEST_F(AutofillDialogControllerTest, ReloadWithEmptyWalletItems) {
2689  controller()->OnDidGetWalletItems(CompleteAndValidWalletItems());
2690  controller()->MenuModelForSection(SECTION_CC_BILLING)->ActivatedAt(1);
2691  controller()->MenuModelForSection(SECTION_SHIPPING)->ActivatedAt(1);
2692
2693  controller()->ClearLastWalletItemsFetchTimestampForTesting();
2694  EXPECT_CALL(*controller()->GetTestingWalletClient(), GetWalletItems());
2695  controller()->TabActivated();
2696
2697  controller()->OnDidGetWalletItems(
2698      wallet::GetTestWalletItems(wallet::AMEX_DISALLOWED));
2699
2700  EXPECT_FALSE(controller()->MenuModelForSection(SECTION_CC_BILLING));
2701  EXPECT_EQ(
2702      3, controller()->MenuModelForSection(SECTION_SHIPPING)->GetItemCount());
2703}
2704
2705TEST_F(AutofillDialogControllerTest, SaveInChromeByDefault) {
2706  EXPECT_TRUE(controller()->ShouldSaveInChrome());
2707  SwitchToAutofill();
2708  FillCreditCardInputs();
2709  controller()->OnAccept();
2710  EXPECT_TRUE(controller()->ShouldSaveInChrome());
2711}
2712
2713TEST_F(AutofillDialogControllerTest,
2714       SaveInChromePreferenceNotRememberedOnCancel) {
2715  EXPECT_TRUE(controller()->ShouldSaveInChrome());
2716  SwitchToAutofill();
2717  controller()->GetView()->CheckSaveDetailsLocallyCheckbox(false);
2718  controller()->OnCancel();
2719  EXPECT_TRUE(controller()->ShouldSaveInChrome());
2720}
2721
2722TEST_F(AutofillDialogControllerTest,
2723       SaveInChromePreferenceRememberedOnSuccess) {
2724  EXPECT_TRUE(controller()->ShouldSaveInChrome());
2725  SwitchToAutofill();
2726  FillCreditCardInputs();
2727  controller()->GetView()->CheckSaveDetailsLocallyCheckbox(false);
2728  controller()->OnAccept();
2729  EXPECT_FALSE(controller()->ShouldSaveInChrome());
2730}
2731
2732TEST_F(AutofillDialogControllerTest,
2733       SubmitButtonIsDisabled_SpinnerFinishesBeforeDelay) {
2734  // Reset Wallet state.
2735  controller()->OnDidGetWalletItems(scoped_ptr<wallet::WalletItems>());
2736
2737  EXPECT_EQ(1, controller()->get_submit_button_delay_count());
2738
2739  // Begin the submit button delay.
2740  controller()->SimulateSubmitButtonDelayBegin();
2741
2742  EXPECT_TRUE(controller()->ShouldShowSpinner());
2743  EXPECT_FALSE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_OK));
2744
2745  // Stop the spinner.
2746  controller()->OnDidGetWalletItems(CompleteAndValidWalletItems());
2747
2748  EXPECT_FALSE(controller()->ShouldShowSpinner());
2749  EXPECT_FALSE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_OK));
2750
2751  // End the submit button delay.
2752  controller()->SimulateSubmitButtonDelayEnd();
2753
2754  EXPECT_FALSE(controller()->ShouldShowSpinner());
2755  EXPECT_TRUE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_OK));
2756}
2757
2758TEST_F(AutofillDialogControllerTest,
2759       SubmitButtonIsDisabled_SpinnerFinishesAfterDelay) {
2760  // Reset Wallet state.
2761  controller()->OnDidGetWalletItems(scoped_ptr<wallet::WalletItems>());
2762
2763  EXPECT_EQ(1, controller()->get_submit_button_delay_count());
2764
2765  // Begin the submit button delay.
2766  controller()->SimulateSubmitButtonDelayBegin();
2767
2768  EXPECT_TRUE(controller()->ShouldShowSpinner());
2769  EXPECT_FALSE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_OK));
2770
2771  // End the submit button delay.
2772  controller()->SimulateSubmitButtonDelayEnd();
2773
2774  EXPECT_TRUE(controller()->ShouldShowSpinner());
2775  EXPECT_FALSE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_OK));
2776
2777  // Stop the spinner.
2778  controller()->OnDidGetWalletItems(CompleteAndValidWalletItems());
2779
2780  EXPECT_FALSE(controller()->ShouldShowSpinner());
2781  EXPECT_TRUE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_OK));
2782}
2783
2784TEST_F(AutofillDialogControllerTest, SubmitButtonIsDisabled_NoSpinner) {
2785  SwitchToAutofill();
2786
2787  EXPECT_EQ(1, controller()->get_submit_button_delay_count());
2788
2789  // Begin the submit button delay.
2790  controller()->SimulateSubmitButtonDelayBegin();
2791
2792  EXPECT_FALSE(controller()->ShouldShowSpinner());
2793  EXPECT_FALSE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_OK));
2794
2795  // End the submit button delay.
2796  controller()->SimulateSubmitButtonDelayEnd();
2797
2798  EXPECT_FALSE(controller()->ShouldShowSpinner());
2799  EXPECT_TRUE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_OK));
2800}
2801
2802TEST_F(AutofillDialogControllerTest, IconsForFields_NoCreditCard) {
2803  FieldValueMap values;
2804  values[EMAIL_ADDRESS] = ASCIIToUTF16(kFakeEmail);
2805  FieldIconMap icons = controller()->IconsForFields(values);
2806  EXPECT_TRUE(icons.empty());
2807}
2808
2809TEST_F(AutofillDialogControllerTest, IconsForFields_CreditCardNumberOnly) {
2810  FieldValueMap values;
2811  values[EMAIL_ADDRESS] = ASCIIToUTF16(kFakeEmail);
2812  values[CREDIT_CARD_NUMBER] = ASCIIToUTF16(kTestCCNumberVisa);
2813  FieldIconMap icons = controller()->IconsForFields(values);
2814  EXPECT_EQ(1UL, icons.size());
2815  EXPECT_EQ(1UL, icons.count(CREDIT_CARD_NUMBER));
2816}
2817
2818TEST_F(AutofillDialogControllerTest, IconsForFields_CvcOnly) {
2819  FieldValueMap values;
2820  values[EMAIL_ADDRESS] = ASCIIToUTF16(kFakeEmail);
2821  values[CREDIT_CARD_VERIFICATION_CODE] = ASCIIToUTF16("123");
2822  FieldIconMap icons = controller()->IconsForFields(values);
2823  EXPECT_EQ(1UL, icons.size());
2824  EXPECT_EQ(1UL, icons.count(CREDIT_CARD_VERIFICATION_CODE));
2825}
2826
2827TEST_F(AutofillDialogControllerTest, IconsForFields_BothCreditCardAndCvc) {
2828  FieldValueMap values;
2829  values[EMAIL_ADDRESS] = ASCIIToUTF16(kFakeEmail);
2830  values[CREDIT_CARD_NUMBER] = ASCIIToUTF16(kTestCCNumberVisa);
2831  values[CREDIT_CARD_VERIFICATION_CODE] = ASCIIToUTF16("123");
2832  FieldIconMap icons = controller()->IconsForFields(values);
2833  EXPECT_EQ(2UL, icons.size());
2834  EXPECT_EQ(1UL, icons.count(CREDIT_CARD_VERIFICATION_CODE));
2835  EXPECT_EQ(1UL, icons.count(CREDIT_CARD_NUMBER));
2836}
2837
2838TEST_F(AutofillDialogControllerTest, FieldControlsIcons) {
2839  EXPECT_TRUE(controller()->FieldControlsIcons(CREDIT_CARD_NUMBER));
2840  EXPECT_FALSE(controller()->FieldControlsIcons(CREDIT_CARD_VERIFICATION_CODE));
2841  EXPECT_FALSE(controller()->FieldControlsIcons(EMAIL_ADDRESS));
2842}
2843
2844TEST_F(AutofillDialogControllerTest, SaveCreditCardIncludesName_NoBilling) {
2845  SwitchToAutofill();
2846
2847  CreditCard test_credit_card(test::GetVerifiedCreditCard());
2848  FillInputs(SECTION_CC, test_credit_card);
2849
2850  AutofillProfile test_profile(test::GetVerifiedProfile());
2851  FillInputs(SECTION_BILLING, test_profile);
2852
2853  UseBillingForShipping();
2854
2855  controller()->GetView()->CheckSaveDetailsLocallyCheckbox(true);
2856  controller()->OnAccept();
2857
2858  TestPersonalDataManager* test_pdm = controller()->GetTestingManager();
2859  const CreditCard& imported_card = test_pdm->imported_credit_card();
2860  EXPECT_EQ(test_profile.GetRawInfo(NAME_FULL),
2861            imported_card.GetRawInfo(CREDIT_CARD_NAME));
2862}
2863
2864TEST_F(AutofillDialogControllerTest, SaveCreditCardIncludesName_WithBilling) {
2865  SwitchToAutofill();
2866
2867  TestPersonalDataManager* test_pdm = controller()->GetTestingManager();
2868  AutofillProfile test_profile(test::GetVerifiedProfile());
2869
2870  EXPECT_CALL(*controller()->GetView(), ModelChanged());
2871  test_pdm->AddTestingProfile(&test_profile);
2872  ASSERT_TRUE(controller()->MenuModelForSection(SECTION_BILLING));
2873
2874  CreditCard test_credit_card(test::GetVerifiedCreditCard());
2875  FillInputs(SECTION_CC, test_credit_card);
2876
2877  controller()->GetView()->CheckSaveDetailsLocallyCheckbox(true);
2878  controller()->OnAccept();
2879
2880  const CreditCard& imported_card = test_pdm->imported_credit_card();
2881  EXPECT_EQ(test_profile.GetRawInfo(NAME_FULL),
2882            imported_card.GetRawInfo(CREDIT_CARD_NAME));
2883
2884  controller()->ViewClosed();
2885}
2886
2887TEST_F(AutofillDialogControllerTest, InputEditability) {
2888  // Empty wallet items: all fields are editable.
2889  scoped_ptr<wallet::WalletItems> items =
2890      wallet::GetTestWalletItems(wallet::AMEX_DISALLOWED);
2891  controller()->OnDidGetWalletItems(items.Pass());
2892
2893  DialogSection sections[] = { SECTION_CC_BILLING, SECTION_SHIPPING };
2894  for (size_t i = 0; i < arraysize(sections); ++i) {
2895    const DetailInputs& inputs =
2896        controller()->RequestedFieldsForSection(sections[i]);
2897    for (size_t j = 0; j < inputs.size(); ++j) {
2898      EXPECT_TRUE(controller()->InputIsEditable(inputs[j], sections[i]));
2899    }
2900  }
2901
2902  // Expired instrument: CC number + CVV are not editable.
2903  items = wallet::GetTestWalletItems(wallet::AMEX_DISALLOWED);
2904  scoped_ptr<wallet::WalletItems::MaskedInstrument> expired_instrument =
2905      wallet::GetTestMaskedInstrumentExpired();
2906  items->AddInstrument(expired_instrument.Pass());
2907  controller()->OnDidGetWalletItems(items.Pass());
2908  EXPECT_TRUE(controller()->IsEditingExistingData(SECTION_CC_BILLING));
2909
2910  const DetailInputs& inputs =
2911      controller()->RequestedFieldsForSection(SECTION_CC_BILLING);
2912  FieldValueMap outputs;
2913  CopyInitialValues(inputs, &outputs);
2914  controller()->GetView()->SetUserInput(SECTION_CC_BILLING, outputs);
2915
2916  for (size_t i = 0; i < arraysize(sections); ++i) {
2917    const DetailInputs& inputs =
2918        controller()->RequestedFieldsForSection(sections[i]);
2919    for (size_t j = 0; j < inputs.size(); ++j) {
2920      if (inputs[j].type == CREDIT_CARD_NUMBER ||
2921          inputs[j].type == CREDIT_CARD_VERIFICATION_CODE) {
2922        EXPECT_FALSE(controller()->InputIsEditable(inputs[j], sections[i]));
2923      } else {
2924        EXPECT_TRUE(controller()->InputIsEditable(inputs[j], sections[i]));
2925      }
2926    }
2927  }
2928
2929  // User changes the billing address; same story.
2930  outputs[ADDRESS_BILLING_ZIP] = ASCIIToUTF16("77025");
2931  controller()->GetView()->SetUserInput(SECTION_CC_BILLING, outputs);
2932  for (size_t i = 0; i < arraysize(sections); ++i) {
2933    const DetailInputs& inputs =
2934        controller()->RequestedFieldsForSection(sections[i]);
2935    for (size_t j = 0; j < inputs.size(); ++j) {
2936      if (inputs[j].type == CREDIT_CARD_NUMBER ||
2937          inputs[j].type == CREDIT_CARD_VERIFICATION_CODE) {
2938        EXPECT_FALSE(controller()->InputIsEditable(inputs[j], sections[i]));
2939      } else {
2940        EXPECT_TRUE(controller()->InputIsEditable(inputs[j], sections[i]));
2941      }
2942    }
2943  }
2944
2945  // User changes a detail of the CC itself (expiration date), CVV is now
2946  // editable (and mandatory).
2947  outputs[CREDIT_CARD_EXP_MONTH] = ASCIIToUTF16("06");
2948  controller()->GetView()->SetUserInput(SECTION_CC_BILLING, outputs);
2949  for (size_t i = 0; i < arraysize(sections); ++i) {
2950    const DetailInputs& inputs =
2951        controller()->RequestedFieldsForSection(sections[i]);
2952    for (size_t j = 0; j < inputs.size(); ++j) {
2953      if (inputs[j].type == CREDIT_CARD_NUMBER)
2954        EXPECT_FALSE(controller()->InputIsEditable(inputs[j], sections[i]));
2955      else
2956        EXPECT_TRUE(controller()->InputIsEditable(inputs[j], sections[i]));
2957    }
2958  }
2959}
2960
2961// When the default country is something besides US, wallet is not selected
2962// and the account chooser shouldn't be visible.
2963TEST_F(AutofillDialogControllerTest, HideWalletInOtherCountries) {
2964  // Addresses from different countries.
2965  AutofillProfile us_profile(base::GenerateGUID(), kSettingsOrigin),
2966      es_profile(base::GenerateGUID(), kSettingsOrigin),
2967      es_profile2(base::GenerateGUID(), kSettingsOrigin);
2968  us_profile.SetRawInfo(ADDRESS_HOME_COUNTRY, ASCIIToUTF16("US"));
2969  es_profile.SetRawInfo(ADDRESS_HOME_COUNTRY, ASCIIToUTF16("ES"));
2970  es_profile2.SetRawInfo(ADDRESS_HOME_COUNTRY, ASCIIToUTF16("ES"));
2971
2972  // If US is indicated (via timezone), show Wallet.
2973  ResetControllerWithFormData(DefaultFormData());
2974  controller()->GetTestingManager()->set_timezone_country_code("US");
2975  controller()->Show();
2976  EXPECT_TRUE(
2977      controller()->AccountChooserModelForTesting()->WalletIsSelected());
2978  controller()->OnDidFetchWalletCookieValue(std::string());
2979  controller()->OnDidGetWalletItems(CompleteAndValidWalletItems());
2980  EXPECT_TRUE(controller()->ShouldShowAccountChooser());
2981  EXPECT_TRUE(
2982      controller()->AccountChooserModelForTesting()->WalletIsSelected());
2983
2984  // If US is not indicated, don't show Wallet.
2985  ResetControllerWithFormData(DefaultFormData());
2986  controller()->GetTestingManager()->set_timezone_country_code("ES");
2987  controller()->Show();
2988  controller()->OnDidFetchWalletCookieValue(std::string());
2989  controller()->OnDidGetWalletItems(CompleteAndValidWalletItems());
2990  EXPECT_FALSE(controller()->ShouldShowAccountChooser());
2991
2992  // If US is indicated (via a profile), show Wallet.
2993  ResetControllerWithFormData(DefaultFormData());
2994  controller()->GetTestingManager()->set_timezone_country_code("ES");
2995  controller()->GetTestingManager()->AddTestingProfile(&us_profile);
2996  controller()->Show();
2997  controller()->OnDidFetchWalletCookieValue(std::string());
2998  controller()->OnDidGetWalletItems(CompleteAndValidWalletItems());
2999  EXPECT_TRUE(controller()->ShouldShowAccountChooser());
3000  EXPECT_TRUE(
3001      controller()->AccountChooserModelForTesting()->WalletIsSelected());
3002
3003  // Make sure the profile doesn't just override the timezone.
3004  ResetControllerWithFormData(DefaultFormData());
3005  controller()->GetTestingManager()->set_timezone_country_code("US");
3006  controller()->GetTestingManager()->AddTestingProfile(&es_profile);
3007  controller()->Show();
3008  controller()->OnDidFetchWalletCookieValue(std::string());
3009  controller()->OnDidGetWalletItems(CompleteAndValidWalletItems());
3010  EXPECT_TRUE(controller()->ShouldShowAccountChooser());
3011  EXPECT_TRUE(
3012      controller()->AccountChooserModelForTesting()->WalletIsSelected());
3013
3014  // Only takes one US address to enable Wallet.
3015  ResetControllerWithFormData(DefaultFormData());
3016  controller()->GetTestingManager()->set_timezone_country_code("FR");
3017  controller()->GetTestingManager()->AddTestingProfile(&es_profile);
3018  controller()->GetTestingManager()->AddTestingProfile(&es_profile2);
3019  controller()->GetTestingManager()->AddTestingProfile(&us_profile);
3020  controller()->Show();
3021  controller()->OnDidFetchWalletCookieValue(std::string());
3022  controller()->OnDidGetWalletItems(CompleteAndValidWalletItems());
3023  EXPECT_TRUE(controller()->ShouldShowAccountChooser());
3024  EXPECT_TRUE(
3025      controller()->AccountChooserModelForTesting()->WalletIsSelected());
3026}
3027
3028TEST_F(AutofillDialogControllerTest, DontGetWalletTillNecessary) {
3029  // When starting on local data mode, the dialog will provide a "Use Google
3030  // Wallet" link.
3031  profile()->GetPrefs()->SetBoolean(
3032      ::prefs::kAutofillDialogPayWithoutWallet, true);
3033  ResetControllerWithFormData(DefaultFormData());
3034  controller()->Show();
3035  base::string16 use_wallet_text = controller()->SignInLinkText();
3036  EXPECT_EQ(TestAutofillDialogController::NOT_CHECKED,
3037            controller()->SignedInState());
3038
3039  // When clicked, this link will ask for wallet items. If there's a signin
3040  // failure, the link will switch to "Sign in to use Google Wallet".
3041  EXPECT_CALL(*controller()->GetTestingWalletClient(), GetWalletItems());
3042  controller()->SignInLinkClicked();
3043  EXPECT_NE(TestAutofillDialogController::NOT_CHECKED,
3044            controller()->SignedInState());
3045  controller()->OnDidFetchWalletCookieValue(std::string());
3046  controller()->OnDidGetWalletItems(CompleteAndValidWalletItems());
3047  controller()->OnPassiveSigninFailure(GoogleServiceAuthError(
3048      GoogleServiceAuthError::CONNECTION_FAILED));
3049  EXPECT_NE(use_wallet_text, controller()->SignInLinkText());
3050}
3051
3052TEST_F(AutofillDialogControllerTest, MultiAccountSwitch) {
3053  std::vector<std::string> users;
3054  users.push_back("user_1@example.com");
3055  users.push_back("user_2@example.com");
3056  controller()->OnDidGetWalletItems(
3057      wallet::GetTestWalletItemsWithUsers(users, 0));
3058
3059  // Items should be: Account 1, account 2, add account, disable wallet.
3060  EXPECT_EQ(4, controller()->MenuModelForAccountChooser()->GetItemCount());
3061  EXPECT_EQ(0U, controller()->GetTestingWalletClient()->user_index());
3062
3063  // GetWalletItems should be called when the user switches accounts.
3064  EXPECT_CALL(*controller()->GetTestingWalletClient(), GetWalletItems());
3065  controller()->MenuModelForAccountChooser()->ActivatedAt(1);
3066  // The wallet client should be updated to the new user index.
3067  EXPECT_EQ(1U, controller()->GetTestingWalletClient()->user_index());
3068}
3069
3070TEST_F(AutofillDialogControllerTest, PassiveAuthFailure) {
3071  controller()->OnDidGetWalletItems(
3072      wallet::GetTestWalletItemsWithRequiredAction(
3073           wallet::PASSIVE_GAIA_AUTH));
3074  EXPECT_TRUE(controller()->ShouldShowSpinner());
3075  controller()->OnPassiveSigninFailure(GoogleServiceAuthError(
3076      GoogleServiceAuthError::NONE));
3077  EXPECT_FALSE(controller()->ShouldShowSpinner());
3078}
3079
3080TEST_F(AutofillDialogControllerTest, WalletShippingSameAsBilling) {
3081  // Assert initial state.
3082  ASSERT_FALSE(profile()->GetPrefs()->HasPrefPath(
3083      ::prefs::kAutofillDialogWalletShippingSameAsBilling));
3084
3085  // Verify that false pref defaults to wallet defaults.
3086  scoped_ptr<wallet::WalletItems> wallet_items =
3087      wallet::GetTestWalletItems(wallet::AMEX_DISALLOWED);
3088  wallet_items->AddAddress(wallet::GetTestNonDefaultShippingAddress());
3089  wallet_items->AddAddress(wallet::GetTestShippingAddress());
3090  controller()->OnDidGetWalletItems(wallet_items.Pass());
3091  ASSERT_FALSE(profile()->GetPrefs()->GetBoolean(
3092      ::prefs::kAutofillDialogWalletShippingSameAsBilling));
3093  EXPECT_EQ(2, GetMenuModelForSection(SECTION_SHIPPING)->checked_item());
3094
3095  // Set "Same as Billing" for the shipping address and verify it sets the pref
3096  // and selects the appropriate menu item.
3097  UseBillingForShipping();
3098  ASSERT_EQ(0, GetMenuModelForSection(SECTION_SHIPPING)->checked_item());
3099  controller()->ForceFinishSubmit();
3100  ASSERT_TRUE(profile()->GetPrefs()->GetBoolean(
3101      ::prefs::kAutofillDialogWalletShippingSameAsBilling));
3102
3103  // Getting new wallet info shouldn't disrupt the preference and menu should be
3104  // set accordingly.
3105  Reset();
3106  wallet_items = wallet::GetTestWalletItems(wallet::AMEX_DISALLOWED);
3107  wallet_items->AddAddress(wallet::GetTestNonDefaultShippingAddress());
3108  wallet_items->AddAddress(wallet::GetTestShippingAddress());
3109  controller()->OnDidGetWalletItems(wallet_items.Pass());
3110  EXPECT_TRUE(profile()->GetPrefs()->GetBoolean(
3111      ::prefs::kAutofillDialogWalletShippingSameAsBilling));
3112  EXPECT_EQ(0, GetMenuModelForSection(SECTION_SHIPPING)->checked_item());
3113
3114  // Choose a different address and ensure pref gets set to false.
3115  controller()->MenuModelForSection(SECTION_SHIPPING)->ActivatedAt(1);
3116  controller()->ForceFinishSubmit();
3117  EXPECT_FALSE(profile()->GetPrefs()->GetBoolean(
3118      ::prefs::kAutofillDialogWalletShippingSameAsBilling));
3119}
3120
3121// Verifies that a call to the IconsForFields() method before the card type is
3122// known returns a placeholder image that is at least as large as the icons for
3123// all of the supported major credit card issuers.
3124TEST_F(AutofillDialogControllerTest, IconReservedForCreditCardField) {
3125  FieldValueMap inputs;
3126  inputs[CREDIT_CARD_NUMBER] = base::string16();
3127
3128  FieldIconMap icons = controller()->IconsForFields(inputs);
3129  EXPECT_EQ(1U, icons.size());
3130
3131  ASSERT_EQ(1U, icons.count(CREDIT_CARD_NUMBER));
3132  gfx::Image placeholder_icon = icons[CREDIT_CARD_NUMBER];
3133
3134  // Verify that the placeholder icon is at least as large as the icons for the
3135  // supported credit card issuers.
3136  const int kSupportedCardIdrs[] = {
3137    IDR_AUTOFILL_CC_AMEX,
3138    IDR_AUTOFILL_CC_DINERS,
3139    IDR_AUTOFILL_CC_DISCOVER,
3140    IDR_AUTOFILL_CC_GENERIC,
3141    IDR_AUTOFILL_CC_JCB,
3142    IDR_AUTOFILL_CC_MASTERCARD,
3143    IDR_AUTOFILL_CC_VISA,
3144  };
3145  ui::ResourceBundle& rb = ui::ResourceBundle::GetSharedInstance();
3146  for (size_t i = 0; i < arraysize(kSupportedCardIdrs); ++i) {
3147    SCOPED_TRACE(base::IntToString(i));
3148    gfx::Image supported_card_icon = rb.GetImageNamed(kSupportedCardIdrs[i]);
3149    EXPECT_GE(placeholder_icon.Width(), supported_card_icon.Width());
3150    EXPECT_GE(placeholder_icon.Height(), supported_card_icon.Height());
3151  }
3152}
3153
3154TEST_F(AutofillDialogControllerTest, CountryChangeUpdatesSection) {
3155  TestAutofillDialogView* view = controller()->GetView();
3156  view->ClearSectionUpdates();
3157
3158  controller()->UserEditedOrActivatedInput(SECTION_SHIPPING,
3159                                           ADDRESS_HOME_COUNTRY,
3160                                           gfx::NativeView(),
3161                                           gfx::Rect(),
3162                                           ASCIIToUTF16("Belarus"),
3163                                           true);
3164  std::map<DialogSection, size_t> updates = view->section_updates();
3165  EXPECT_EQ(1U, updates[SECTION_SHIPPING]);
3166  EXPECT_EQ(1U, updates.size());
3167
3168  view->ClearSectionUpdates();
3169
3170  controller()->UserEditedOrActivatedInput(SECTION_CC_BILLING,
3171                                           ADDRESS_BILLING_COUNTRY,
3172                                           gfx::NativeView(),
3173                                           gfx::Rect(),
3174                                           ASCIIToUTF16("France"),
3175                                           true);
3176  updates = view->section_updates();
3177  EXPECT_EQ(1U, updates[SECTION_CC_BILLING]);
3178  EXPECT_EQ(1U, updates.size());
3179
3180  SwitchToAutofill();
3181  view->ClearSectionUpdates();
3182
3183  controller()->UserEditedOrActivatedInput(SECTION_BILLING,
3184                                           ADDRESS_BILLING_COUNTRY,
3185                                           gfx::NativeView(),
3186                                           gfx::Rect(),
3187                                           ASCIIToUTF16("Italy"),
3188                                           true);
3189  updates = view->section_updates();
3190  EXPECT_EQ(1U, updates[SECTION_BILLING]);
3191  EXPECT_EQ(1U, updates.size());
3192}
3193
3194TEST_F(AutofillDialogControllerTest, CorrectCountryFromInputs) {
3195  EXPECT_CALL(*controller()->GetMockValidator(),
3196              ValidateAddress(CountryCodeMatcher("DE"), _, _));
3197
3198  FieldValueMap billing_inputs;
3199  billing_inputs[ADDRESS_BILLING_COUNTRY] = ASCIIToUTF16("Germany");
3200  controller()->InputsAreValid(SECTION_BILLING, billing_inputs);
3201
3202  EXPECT_CALL(*controller()->GetMockValidator(),
3203              ValidateAddress(CountryCodeMatcher("FR"), _, _));
3204
3205  FieldValueMap shipping_inputs;
3206  shipping_inputs[ADDRESS_HOME_COUNTRY] = ASCIIToUTF16("France");
3207  controller()->InputsAreValid(SECTION_SHIPPING, shipping_inputs);
3208}
3209
3210TEST_F(AutofillDialogControllerTest, ValidationRulesLoadedOnCountryChange) {
3211  ResetControllerWithFormData(DefaultFormData());
3212  EXPECT_CALL(*controller()->GetMockValidator(),
3213              LoadRules("US")).Times(AtLeast(1));
3214  controller()->Show();
3215
3216  EXPECT_CALL(*controller()->GetMockValidator(), LoadRules("FR"));
3217  controller()->UserEditedOrActivatedInput(SECTION_BILLING,
3218                                           ADDRESS_BILLING_COUNTRY,
3219                                           gfx::NativeView(),
3220                                           gfx::Rect(),
3221                                           ASCIIToUTF16("France"),
3222                                           true);
3223}
3224
3225TEST_F(AutofillDialogControllerTest, UsValidationRulesLoadedForJpOnlyProfile) {
3226  ResetControllerWithFormData(DefaultFormData());
3227  AutofillProfile jp_profile(base::GenerateGUID(), kSettingsOrigin);
3228  jp_profile.SetRawInfo(ADDRESS_HOME_COUNTRY, ASCIIToUTF16("JP"));
3229  controller()->GetTestingManager()->AddTestingProfile(&jp_profile);
3230  EXPECT_CALL(*controller()->GetMockValidator(), LoadRules("US"));
3231  EXPECT_CALL(*controller()->GetMockValidator(),
3232              LoadRules("JP")).Times(AtLeast(1));
3233  controller()->Show();
3234}
3235
3236TEST_F(AutofillDialogControllerTest, InvalidWhenRulesNotReady) {
3237  // Select "Add new shipping address...".
3238  controller()->MenuModelForSection(SECTION_SHIPPING)->ActivatedAt(1);
3239
3240  // If the rules haven't loaded yet, validation errors should show on submit.
3241  EXPECT_CALL(*controller()->GetMockValidator(),
3242              ValidateAddress(CountryCodeMatcher("US"), _, _)).
3243              WillRepeatedly(Return(AddressValidator::RULES_NOT_READY));
3244
3245  FieldValueMap inputs;
3246  inputs[ADDRESS_HOME_ZIP] = ASCIIToUTF16("1234");
3247  inputs[ADDRESS_HOME_COUNTRY] = ASCIIToUTF16("United States");
3248
3249  ValidityMessages messages =
3250      controller()->InputsAreValid(SECTION_SHIPPING, inputs);
3251  EXPECT_FALSE(messages.GetMessageOrDefault(ADDRESS_HOME_ZIP).text.empty());
3252  EXPECT_FALSE(messages.HasSureError(ADDRESS_HOME_ZIP));
3253  // Country should never show an error message as it's always valid.
3254  EXPECT_TRUE(messages.GetMessageOrDefault(ADDRESS_HOME_COUNTRY).text.empty());
3255}
3256
3257TEST_F(AutofillDialogControllerTest, ValidButUnverifiedWhenRulesFail) {
3258  SwitchToAutofill();
3259
3260  // Add suggestions so the credit card and billing sections aren't showing
3261  // their manual inputs (to isolate to just shipping).
3262  AutofillProfile verified_profile(test::GetVerifiedProfile());
3263  controller()->GetTestingManager()->AddTestingProfile(&verified_profile);
3264  CreditCard verified_card(test::GetVerifiedCreditCard());
3265  controller()->GetTestingManager()->AddTestingCreditCard(&verified_card);
3266
3267  // Select "Add new shipping address...".
3268  controller()->MenuModelForSection(SECTION_SHIPPING)->ActivatedAt(2);
3269
3270  // If the rules are unavailable, validation errors should not show.
3271  EXPECT_CALL(*controller()->GetMockValidator(),
3272              ValidateAddress(CountryCodeMatcher("US"), _, _)).
3273              WillRepeatedly(Return(AddressValidator::RULES_UNAVAILABLE));
3274
3275  FieldValueMap outputs;
3276  AutofillProfile full_profile(test::GetFullProfile());
3277  const DetailInputs& inputs =
3278      controller()->RequestedFieldsForSection(SECTION_SHIPPING);
3279  for (size_t i = 0; i < inputs.size(); ++i) {
3280    const ServerFieldType type = inputs[i].type;
3281    outputs[type] = full_profile.GetInfo(AutofillType(type), "en-US");
3282  }
3283  controller()->GetView()->SetUserInput(SECTION_SHIPPING, outputs);
3284  controller()->GetView()->CheckSaveDetailsLocallyCheckbox(true);
3285  controller()->OnAccept();
3286
3287  // Profiles saved while rules are unavailable shouldn't be verified.
3288  const AutofillProfile& imported_profile =
3289      controller()->GetTestingManager()->imported_profile();
3290  ASSERT_EQ(imported_profile.GetRawInfo(NAME_FULL),
3291            full_profile.GetRawInfo(NAME_FULL));
3292  EXPECT_EQ(imported_profile.origin(), GURL(kSourceUrl).GetOrigin().spec());
3293  EXPECT_FALSE(imported_profile.IsVerified());
3294}
3295
3296TEST_F(AutofillDialogControllerTest, LimitedCountryChoices) {
3297  ui::ComboboxModel* shipping_country_model =
3298      controller()->ComboboxModelForAutofillType(ADDRESS_HOME_COUNTRY);
3299  const int default_number_of_countries =
3300      shipping_country_model->GetItemCount();
3301  // We show a lot of countries by default, but the exact number doesn't matter.
3302  EXPECT_GT(default_number_of_countries, 50);
3303
3304  // Create a form data that simulates:
3305  //   <select autocomplete="billing country">
3306  //     <option value="AU">Down Under</option>
3307  //     <option value="">fR</option>  <!-- Case doesn't matter -->
3308  //     <option value="GRMNY">Germany</option>
3309  //   </select>
3310  // Only country codes are respected, whether they're in value or the option's
3311  // text content. Thus the first two options should be recognized.
3312  FormData form_data;
3313  FormFieldData field;
3314  field.autocomplete_attribute = "billing country";
3315  field.option_contents.push_back(ASCIIToUTF16("Down Under"));
3316  field.option_values.push_back(ASCIIToUTF16("AU"));
3317  field.option_contents.push_back(ASCIIToUTF16("Fr"));
3318  field.option_values.push_back(ASCIIToUTF16(""));
3319  field.option_contents.push_back(ASCIIToUTF16("Germany"));
3320  field.option_values.push_back(ASCIIToUTF16("GRMNY"));
3321
3322  FormFieldData cc_field;
3323  cc_field.autocomplete_attribute = "cc-csc";
3324
3325  form_data.fields.push_back(field);
3326  form_data.fields.push_back(cc_field);
3327  ResetControllerWithFormData(form_data);
3328  controller()->Show();
3329
3330  // Shipping model shouldn't have changed.
3331  shipping_country_model =
3332      controller()->ComboboxModelForAutofillType(ADDRESS_HOME_COUNTRY);
3333  EXPECT_EQ(default_number_of_countries,
3334            shipping_country_model->GetItemCount());
3335  // Billing model now only has two items.
3336  ui::ComboboxModel* billing_country_model =
3337      controller()->ComboboxModelForAutofillType(ADDRESS_BILLING_COUNTRY);
3338  ASSERT_EQ(2, billing_country_model->GetItemCount());
3339  EXPECT_EQ(billing_country_model->GetItemAt(0), ASCIIToUTF16("Australia"));
3340  EXPECT_EQ(billing_country_model->GetItemAt(1), ASCIIToUTF16("France"));
3341
3342  // Make sure it also applies to profile suggestions.
3343  AutofillProfile us_profile(test::GetVerifiedProfile());
3344  us_profile.SetRawInfo(ADDRESS_HOME_COUNTRY, ASCIIToUTF16("US"));
3345  controller()->GetTestingManager()->AddTestingProfile(&us_profile);
3346  // Don't show a suggestion if the only one that exists is disabled.
3347  EXPECT_FALSE(
3348      controller()->SuggestionStateForSection(SECTION_BILLING).visible);
3349
3350  // Add a profile with an acceptable country; suggestion should be shown.
3351  ResetControllerWithFormData(form_data);
3352  controller()->Show();
3353  AutofillProfile au_profile(test::GetVerifiedProfile2());
3354  au_profile.SetRawInfo(ADDRESS_HOME_COUNTRY, ASCIIToUTF16("AU"));
3355  controller()->GetTestingManager()->AddTestingProfile(&us_profile);
3356  controller()->GetTestingManager()->AddTestingProfile(&au_profile);
3357  ui::MenuModel* model = controller()->MenuModelForSection(SECTION_BILLING);
3358  ASSERT_TRUE(model);
3359  EXPECT_EQ(4, model->GetItemCount());
3360  EXPECT_FALSE(model->IsEnabledAt(0));
3361  EXPECT_TRUE(model->IsEnabledAt(1));
3362
3363  // Add <input type="text" autocomplete="billing country"></input>
3364  // This should open up selection of all countries again.
3365  FormFieldData field2;
3366  field2.autocomplete_attribute = "billing country";
3367  form_data.fields.push_back(field2);
3368  ResetControllerWithFormData(form_data);
3369  controller()->Show();
3370
3371  billing_country_model =
3372      controller()->ComboboxModelForAutofillType(ADDRESS_BILLING_COUNTRY);
3373  EXPECT_EQ(default_number_of_countries,
3374            billing_country_model->GetItemCount());
3375}
3376
3377TEST_F(AutofillDialogControllerTest, LimitedCcChoices) {
3378  SwitchToAutofill();
3379  // Typically, MC and Visa are both valid.
3380  ValidateCCNumber(SECTION_CC, kTestCCNumberMaster, true);
3381  ValidateCCNumber(SECTION_CC, kTestCCNumberVisa, true);
3382
3383  FormData form_data;
3384  FormFieldData field;
3385  field.autocomplete_attribute = "billing cc-type";
3386  field.option_contents.push_back(ASCIIToUTF16("Visa"));
3387  field.option_values.push_back(ASCIIToUTF16("V"));
3388  field.option_contents.push_back(ASCIIToUTF16("American Express"));
3389  field.option_values.push_back(ASCIIToUTF16("AX"));
3390  form_data.fields.push_back(field);
3391  ResetControllerWithFormData(form_data);
3392  controller()->Show();
3393
3394  // MC is not valid because it's missing from FormData.
3395  ValidateCCNumber(SECTION_CC, kTestCCNumberMaster, false);
3396  ValidateCCNumber(SECTION_CC, kTestCCNumberVisa, true);
3397
3398  CreditCard visa_card(test::GetVerifiedCreditCard());
3399  CreditCard amex_card(test::GetVerifiedCreditCard2());
3400
3401  CreditCard master_card(base::GenerateGUID(), "chrome settings");
3402  test::SetCreditCardInfo(
3403      &master_card, "Mr Foo", "5105105105105100", "07", "2099");
3404
3405  controller()->GetTestingManager()->AddTestingCreditCard(&visa_card);
3406  controller()->GetTestingManager()->AddTestingCreditCard(&amex_card);
3407  controller()->GetTestingManager()->AddTestingCreditCard(&master_card);
3408
3409  // The stored MC is disabled in the dropdown.
3410  ui::MenuModel* model = controller()->MenuModelForSection(SECTION_CC);
3411  ASSERT_TRUE(model);
3412  ASSERT_EQ(5, model->GetItemCount());
3413  EXPECT_TRUE(model->IsEnabledAt(0));
3414  EXPECT_TRUE(model->IsEnabledAt(1));
3415  EXPECT_FALSE(model->IsEnabledAt(2));
3416  EXPECT_TRUE(model->IsEnabledAt(3));
3417  EXPECT_TRUE(model->IsEnabledAt(4));
3418
3419  // No MC; Wallet is disabled.
3420  SetUpControllerWithFormData(form_data);
3421  EXPECT_FALSE(controller()->IsPayingWithWallet());
3422
3423  // In Autofill mode, Discover is disallowed because it's not in FormData.
3424  ValidateCCNumber(SECTION_CC, kTestCCNumberDiscover, false);
3425
3426  field.option_contents.push_back(ASCIIToUTF16("Mastercard"));
3427  field.option_values.push_back(ASCIIToUTF16("Mastercard"));
3428  form_data.fields[0] = field;
3429
3430  // Add MC to FormData; Wallet is enabled.
3431  SetUpControllerWithFormData(form_data);
3432  EXPECT_TRUE(controller()->IsPayingWithWallet());
3433  // Even though Discover isn't in FormData, it's allowed because Wallet always
3434  // generates a MC Virtual card.
3435  ValidateCCNumber(SECTION_CC_BILLING, kTestCCNumberDiscover, true);
3436}
3437
3438TEST_F(AutofillDialogControllerTest, SuggestCountrylessProfiles) {
3439  SwitchToAutofill();
3440
3441  FieldValueMap outputs;
3442  outputs[ADDRESS_HOME_COUNTRY] = ASCIIToUTF16("US");
3443  controller()->GetView()->SetUserInput(SECTION_SHIPPING, outputs);
3444
3445  AutofillProfile profile(test::GetVerifiedProfile());
3446  profile.SetRawInfo(NAME_FULL, ASCIIToUTF16("The Man Without a Country"));
3447  profile.SetRawInfo(ADDRESS_HOME_COUNTRY, base::string16());
3448  controller()->GetTestingManager()->AddTestingProfile(&profile);
3449
3450  controller()->UserEditedOrActivatedInput(
3451      SECTION_SHIPPING,
3452      NAME_FULL,
3453      gfx::NativeView(),
3454      gfx::Rect(),
3455      profile.GetRawInfo(NAME_FULL).substr(0, 1),
3456      true);
3457  EXPECT_EQ(NAME_FULL, controller()->popup_input_type());
3458}
3459
3460TEST_F(AutofillDialogControllerTest, SwitchFromWalletWithFirstName) {
3461  controller()->MenuModelForSection(SECTION_CC_BILLING)->ActivatedAt(2);
3462
3463  FieldValueMap outputs;
3464  outputs[NAME_FULL] = ASCIIToUTF16("madonna");
3465  controller()->GetView()->SetUserInput(SECTION_CC_BILLING, outputs);
3466
3467  ASSERT_NO_FATAL_FAILURE(SwitchToAutofill());
3468}
3469
3470// Regression test for http://crbug.com/382777
3471TEST_F(AutofillDialogControllerTest, WalletBillingCountry) {
3472  FormFieldData cc_field;
3473  cc_field.autocomplete_attribute = "cc-number";
3474  FormFieldData billing_country, billing_country_name, shipping_country,
3475      shipping_country_name;
3476  billing_country.autocomplete_attribute = "billing country";
3477  billing_country_name.autocomplete_attribute = "billing country-name";
3478  shipping_country.autocomplete_attribute = "shipping country";
3479  shipping_country_name.autocomplete_attribute = "shipping country-name";
3480
3481  FormData form_data;
3482  form_data.fields.push_back(cc_field);
3483  form_data.fields.push_back(billing_country);
3484  form_data.fields.push_back(billing_country_name);
3485  form_data.fields.push_back(shipping_country);
3486  form_data.fields.push_back(shipping_country_name);
3487
3488  SetUpControllerWithFormData(form_data);
3489  AcceptAndLoadFakeFingerprint();
3490  controller()->OnDidGetFullWallet(wallet::GetTestFullWallet());
3491  controller()->ForceFinishSubmit();
3492
3493  ASSERT_EQ(5U, form_structure()->field_count());
3494  EXPECT_EQ(ADDRESS_HOME_COUNTRY,
3495            form_structure()->field(1)->Type().GetStorableType());
3496  EXPECT_EQ(ASCIIToUTF16("US"), form_structure()->field(1)->value);
3497  EXPECT_EQ(ADDRESS_HOME_COUNTRY,
3498            form_structure()->field(2)->Type().GetStorableType());
3499  EXPECT_EQ(ASCIIToUTF16("United States"), form_structure()->field(2)->value);
3500  EXPECT_EQ(ADDRESS_HOME_COUNTRY,
3501            form_structure()->field(3)->Type().GetStorableType());
3502  EXPECT_EQ(ASCIIToUTF16("US"), form_structure()->field(3)->value);
3503  EXPECT_EQ(ADDRESS_HOME_COUNTRY,
3504            form_structure()->field(4)->Type().GetStorableType());
3505  EXPECT_EQ(ASCIIToUTF16("United States"), form_structure()->field(4)->value);
3506}
3507
3508}  // namespace autofill
3509