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