autofill_dialog_controller_unittest.cc revision 23730a6e56a168d1879203e4b3819bb36e3d8f1f
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  virtual bool HitTestInput(ServerFieldType type,
208                            const gfx::Point& screen_point) OVERRIDE {
209    return false;
210  }
211
212  virtual bool SaveDetailsLocally() OVERRIDE {
213    return save_details_locally_checked_;
214  }
215
216  virtual const content::NavigationController* ShowSignIn() OVERRIDE {
217    return NULL;
218  }
219  virtual void HideSignIn() OVERRIDE {}
220
221  MOCK_METHOD0(ModelChanged, void());
222  MOCK_METHOD0(UpdateForErrors, void());
223
224  virtual void OnSignInResize(const gfx::Size& pref_size) OVERRIDE {}
225  virtual void ValidateSection(DialogSection) OVERRIDE {}
226
227  void SetUserInput(DialogSection section, const FieldValueMap& map) {
228    outputs_[section] = map;
229  }
230
231  void CheckSaveDetailsLocallyCheckbox(bool checked) {
232    save_details_locally_checked_ = checked;
233  }
234
235  void ClearSectionUpdates() {
236    section_updates_.clear();
237  }
238
239  std::map<DialogSection, size_t> section_updates() const {
240    return section_updates_;
241  }
242
243 private:
244  std::map<DialogSection, FieldValueMap> outputs_;
245  std::map<DialogSection, size_t> section_updates_;
246
247  int updates_started_;
248  bool save_details_locally_checked_;
249
250  DISALLOW_COPY_AND_ASSIGN(TestAutofillDialogView);
251};
252
253class TestAutofillDialogController
254    : public AutofillDialogControllerImpl,
255      public base::SupportsWeakPtr<TestAutofillDialogController> {
256 public:
257  TestAutofillDialogController(
258      content::WebContents* contents,
259      const FormData& form_structure,
260      const GURL& source_url,
261      const AutofillMetrics& metric_logger,
262      const base::Callback<void(const FormStructure*)>& callback,
263      MockNewCreditCardBubbleController* mock_new_card_bubble_controller)
264      : AutofillDialogControllerImpl(contents,
265                                     form_structure,
266                                     source_url,
267                                     callback),
268        metric_logger_(metric_logger),
269        mock_wallet_client_(
270            Profile::FromBrowserContext(contents->GetBrowserContext())->
271                GetRequestContext(), this, source_url),
272        mock_new_card_bubble_controller_(mock_new_card_bubble_controller),
273        submit_button_delay_count_(0) {}
274
275  virtual ~TestAutofillDialogController() {}
276
277  virtual AutofillDialogView* CreateView() OVERRIDE {
278    return new testing::NiceMock<TestAutofillDialogView>();
279  }
280
281  void Init(content::BrowserContext* browser_context) {
282    test_manager_.Init(
283        WebDataServiceFactory::GetAutofillWebDataForProfile(
284            Profile::FromBrowserContext(browser_context),
285            Profile::EXPLICIT_ACCESS),
286        user_prefs::UserPrefs::Get(browser_context),
287        browser_context->IsOffTheRecord());
288  }
289
290  TestAutofillDialogView* GetView() {
291    return static_cast<TestAutofillDialogView*>(view());
292  }
293
294  TestPersonalDataManager* GetTestingManager() {
295    return &test_manager_;
296  }
297
298  MockAddressValidator* GetMockValidator() {
299    return &mock_validator_;
300  }
301
302  wallet::MockWalletClient* GetTestingWalletClient() {
303    return &mock_wallet_client_;
304  }
305
306  const GURL& open_tab_url() { return open_tab_url_; }
307
308  void SimulateSigninError() {
309    OnWalletSigninError();
310  }
311
312  // Skips past the 2 second wait between FinishSubmit and DoFinishSubmit.
313  void ForceFinishSubmit() {
314    DoFinishSubmit();
315  }
316
317  void SimulateSubmitButtonDelayBegin() {
318    AutofillDialogControllerImpl::SubmitButtonDelayBegin();
319  }
320
321  void SimulateSubmitButtonDelayEnd() {
322    AutofillDialogControllerImpl::SubmitButtonDelayEndForTesting();
323  }
324
325  using AutofillDialogControllerImpl::
326      ClearLastWalletItemsFetchTimestampForTesting;
327
328  // Returns the number of times that the submit button was delayed.
329  int get_submit_button_delay_count() const {
330    return submit_button_delay_count_;
331  }
332
333  MOCK_METHOD0(LoadRiskFingerprintData, void());
334  using AutofillDialogControllerImpl::AccountChooserModelForTesting;
335  using AutofillDialogControllerImpl::OnDidLoadRiskFingerprintData;
336  using AutofillDialogControllerImpl::IsEditingExistingData;
337  using AutofillDialogControllerImpl::IsManuallyEditingSection;
338  using AutofillDialogControllerImpl::IsPayingWithWallet;
339  using AutofillDialogControllerImpl::IsSubmitPausedOn;
340  using AutofillDialogControllerImpl::NOT_CHECKED;
341  using AutofillDialogControllerImpl::popup_input_type;
342  using AutofillDialogControllerImpl::SignedInState;
343
344 protected:
345  virtual PersonalDataManager* GetManager() const OVERRIDE {
346    return const_cast<TestAutofillDialogController*>(this)->
347        GetTestingManager();
348  }
349
350  virtual AddressValidator* GetValidator() OVERRIDE {
351    return &mock_validator_;
352  }
353
354  virtual wallet::WalletClient* GetWalletClient() OVERRIDE {
355    return &mock_wallet_client_;
356  }
357
358  virtual void OpenTabWithUrl(const GURL& url) OVERRIDE {
359    open_tab_url_ = url;
360  }
361
362  virtual void ShowNewCreditCardBubble(
363      scoped_ptr<CreditCard> new_card,
364      scoped_ptr<AutofillProfile> billing_profile) OVERRIDE {
365    mock_new_card_bubble_controller_->Show(new_card.Pass(),
366                                           billing_profile.Pass());
367  }
368
369  // AutofillDialogControllerImpl calls this method before showing the dialog
370  // window.
371  virtual void SubmitButtonDelayBegin() OVERRIDE {
372    // Do not delay enabling the submit button in testing.
373    submit_button_delay_count_++;
374  }
375
376 private:
377  // To specify our own metric logger.
378  virtual const AutofillMetrics& GetMetricLogger() const OVERRIDE {
379    return metric_logger_;
380  }
381
382  const AutofillMetrics& metric_logger_;
383  TestPersonalDataManager test_manager_;
384  testing::NiceMock<wallet::MockWalletClient> mock_wallet_client_;
385
386  // A mock validator object to prevent network requests and track when
387  // validation rules are loaded or validation attempts occur.
388  testing::NiceMock<MockAddressValidator> mock_validator_;
389
390  GURL open_tab_url_;
391  MockNewCreditCardBubbleController* mock_new_card_bubble_controller_;
392
393  // The number of times that the submit button was delayed.
394  int submit_button_delay_count_;
395
396  DISALLOW_COPY_AND_ASSIGN(TestAutofillDialogController);
397};
398
399class AutofillDialogControllerTest : public ChromeRenderViewHostTestHarness {
400 protected:
401  AutofillDialogControllerTest(): form_structure_(NULL) {}
402
403  // testing::Test implementation:
404  virtual void SetUp() OVERRIDE {
405    ChromeRenderViewHostTestHarness::SetUp();
406    Reset();
407  }
408
409  virtual void TearDown() OVERRIDE {
410    if (controller_)
411      controller_->ViewClosed();
412    ChromeRenderViewHostTestHarness::TearDown();
413  }
414
415  void Reset() {
416    if (controller_)
417      controller_->ViewClosed();
418
419    test_generated_bubble_controller_ =
420        new testing::NiceMock<TestGeneratedCreditCardBubbleController>(
421            web_contents());
422    ASSERT_TRUE(test_generated_bubble_controller_->IsInstalled());
423
424    mock_new_card_bubble_controller_.reset(
425        new MockNewCreditCardBubbleController);
426
427    profile()->GetPrefs()->ClearPref(::prefs::kAutofillDialogSaveData);
428
429    // We have to clear the old local state before creating a new one.
430    scoped_local_state_.reset();
431    scoped_local_state_.reset(new ScopedTestingLocalState(
432        TestingBrowserProcess::GetGlobal()));
433
434    SetUpControllerWithFormData(DefaultFormData());
435  }
436
437  FormData DefaultFormData() {
438    FormData form_data;
439    for (size_t i = 0; i < arraysize(kFieldsFromPage); ++i) {
440      FormFieldData field;
441      field.autocomplete_attribute = kFieldsFromPage[i];
442      form_data.fields.push_back(field);
443    }
444    return form_data;
445  }
446
447  // Creates a new controller for |form_data|.
448  void ResetControllerWithFormData(const FormData& form_data) {
449    if (controller_)
450      controller_->ViewClosed();
451
452    base::Callback<void(const FormStructure*)> callback =
453        base::Bind(&AutofillDialogControllerTest::FinishedCallback,
454                   base::Unretained(this));
455    controller_ = (new testing::NiceMock<TestAutofillDialogController>(
456        web_contents(),
457        form_data,
458        GURL(kSourceUrl),
459        metric_logger_,
460        callback,
461        mock_new_card_bubble_controller_.get()))->AsWeakPtr();
462    controller_->Init(profile());
463  }
464
465  // Creates a new controller for |form_data| and sets up some initial wallet
466  // data for it.
467  void SetUpControllerWithFormData(const FormData& form_data) {
468    ResetControllerWithFormData(form_data);
469    controller()->Show();
470    if (!profile()->GetPrefs()->GetBoolean(
471            ::prefs::kAutofillDialogPayWithoutWallet)) {
472      EXPECT_CALL(*controller()->GetTestingWalletClient(), GetWalletItems());
473      controller()->OnDidFetchWalletCookieValue(std::string());
474      controller()->OnDidGetWalletItems(CompleteAndValidWalletItems());
475    }
476  }
477
478  // Fills the inputs in SECTION_CC with data.
479  void FillCreditCardInputs() {
480    FieldValueMap cc_outputs;
481    const DetailInputs& cc_inputs =
482        controller()->RequestedFieldsForSection(SECTION_CC);
483    for (size_t i = 0; i < cc_inputs.size(); ++i) {
484      cc_outputs[cc_inputs[i].type] = cc_inputs[i].type == CREDIT_CARD_NUMBER ?
485          ASCIIToUTF16(kTestCCNumberVisa) : ASCIIToUTF16("11");
486    }
487    controller()->GetView()->SetUserInput(SECTION_CC, cc_outputs);
488  }
489
490  // Fills the inputs in SECTION_CC_BILLING with valid data.
491  void FillCCBillingInputs() {
492    FieldValueMap outputs;
493    const DetailInputs& inputs =
494        controller()->RequestedFieldsForSection(SECTION_CC_BILLING);
495    AutofillProfile full_profile(test::GetVerifiedProfile());
496    CreditCard full_card(test::GetCreditCard());
497    for (size_t i = 0; i < inputs.size(); ++i) {
498      const ServerFieldType type = inputs[i].type;
499      outputs[type] = full_profile.GetInfo(AutofillType(type), "en-US");
500
501      if (outputs[type].empty())
502        outputs[type] = full_card.GetInfo(AutofillType(type), "en-US");
503    }
504    controller()->GetView()->SetUserInput(SECTION_CC_BILLING, outputs);
505  }
506
507  // Activates the 'Add new foo' option from the |section|'s suggestions
508  // dropdown and fills the |section|'s inputs with the data from the
509  // |data_model|.  If |section| is SECTION_CC, also fills in '123' for the CVC.
510  void FillInputs(DialogSection section, const AutofillDataModel& data_model) {
511    // Select the 'Add new foo' option.
512    ui::MenuModel* model = GetMenuModelForSection(section);
513    if (model)
514      model->ActivatedAt(model->GetItemCount() - 2);
515
516    // Fill the inputs.
517    FieldValueMap outputs;
518    const DetailInputs& inputs =
519        controller()->RequestedFieldsForSection(section);
520    for (size_t i = 0; i < inputs.size(); ++i) {
521      ServerFieldType type = inputs[i].type;
522      base::string16 output;
523      if (type == CREDIT_CARD_VERIFICATION_CODE)
524        output = ASCIIToUTF16("123");
525      else
526        output = data_model.GetInfo(AutofillType(type), "en-US");
527      outputs[inputs[i].type] = output;
528    }
529    controller()->GetView()->SetUserInput(section, outputs);
530  }
531
532  std::vector<DialogNotification> NotificationsOfType(
533      DialogNotification::Type type) {
534    std::vector<DialogNotification> right_type;
535    const std::vector<DialogNotification>& notifications =
536        controller()->CurrentNotifications();
537    for (size_t i = 0; i < notifications.size(); ++i) {
538      if (notifications[i].type() == type)
539        right_type.push_back(notifications[i]);
540    }
541    return right_type;
542  }
543
544  void SwitchToAutofill() {
545    ui::MenuModel* model = controller_->MenuModelForAccountChooser();
546    model->ActivatedAt(model->GetItemCount() - 1);
547  }
548
549  void SwitchToWallet() {
550    controller_->MenuModelForAccountChooser()->ActivatedAt(0);
551  }
552
553  void SimulateSigninError() {
554    controller_->SimulateSigninError();
555  }
556
557  void UseBillingForShipping() {
558    controller()->MenuModelForSection(SECTION_SHIPPING)->ActivatedAt(0);
559  }
560
561  void ValidateCCNumber(DialogSection section,
562                        const std::string& cc_number,
563                        bool should_pass) {
564    FieldValueMap outputs;
565    outputs[ADDRESS_BILLING_COUNTRY] = ASCIIToUTF16("United States");
566    outputs[CREDIT_CARD_NUMBER] = UTF8ToUTF16(cc_number);
567    ValidityMessages messages =
568        controller()->InputsAreValid(section, outputs);
569    EXPECT_EQ(should_pass, !messages.HasSureError(CREDIT_CARD_NUMBER));
570  }
571
572  void SubmitWithWalletItems(scoped_ptr<wallet::WalletItems> wallet_items) {
573    controller()->OnDidGetWalletItems(wallet_items.Pass());
574    AcceptAndLoadFakeFingerprint();
575  }
576
577  void AcceptAndLoadFakeFingerprint() {
578    controller()->OnAccept();
579    controller()->OnDidLoadRiskFingerprintData(GetFakeFingerprint().Pass());
580  }
581
582  // Returns true if the given |section| contains a field of the given |type|.
583  bool SectionContainsField(DialogSection section, ServerFieldType type) {
584    const DetailInputs& inputs =
585        controller()->RequestedFieldsForSection(section);
586    for (DetailInputs::const_iterator it = inputs.begin(); it != inputs.end();
587         ++it) {
588      if (it->type == type)
589        return true;
590    }
591    return false;
592  }
593
594  SuggestionsMenuModel* GetMenuModelForSection(DialogSection section) {
595    ui::MenuModel* model = controller()->MenuModelForSection(section);
596    return static_cast<SuggestionsMenuModel*>(model);
597  }
598
599  void SubmitAndVerifyShippingAndBillingResults() {
600    // Test after setting use billing for shipping.
601    UseBillingForShipping();
602
603    controller()->OnAccept();
604
605    ASSERT_EQ(20U, form_structure()->field_count());
606    EXPECT_EQ(ADDRESS_HOME_COUNTRY,
607              form_structure()->field(11)->Type().GetStorableType());
608    EXPECT_EQ(ADDRESS_BILLING, form_structure()->field(11)->Type().group());
609    EXPECT_EQ(ADDRESS_HOME_COUNTRY,
610              form_structure()->field(18)->Type().GetStorableType());
611    EXPECT_EQ(ADDRESS_HOME, form_structure()->field(18)->Type().group());
612    base::string16 billing_country = form_structure()->field(11)->value;
613    EXPECT_EQ(2U, billing_country.size());
614    base::string16 shipping_country = form_structure()->field(18)->value;
615    EXPECT_EQ(2U, shipping_country.size());
616    EXPECT_FALSE(billing_country.empty());
617    EXPECT_FALSE(shipping_country.empty());
618    EXPECT_EQ(billing_country, shipping_country);
619
620    EXPECT_EQ(CREDIT_CARD_NAME,
621              form_structure()->field(1)->Type().GetStorableType());
622    base::string16 cc_name = form_structure()->field(1)->value;
623    EXPECT_EQ(NAME_FULL, form_structure()->field(6)->Type().GetStorableType());
624    EXPECT_EQ(NAME_BILLING, form_structure()->field(6)->Type().group());
625    base::string16 billing_name = form_structure()->field(6)->value;
626    EXPECT_EQ(NAME_FULL, form_structure()->field(13)->Type().GetStorableType());
627    EXPECT_EQ(NAME, form_structure()->field(13)->Type().group());
628    base::string16 shipping_name = form_structure()->field(13)->value;
629
630    EXPECT_FALSE(cc_name.empty());
631    EXPECT_FALSE(billing_name.empty());
632    EXPECT_FALSE(shipping_name.empty());
633    EXPECT_EQ(cc_name, billing_name);
634    EXPECT_EQ(cc_name, shipping_name);
635  }
636
637  TestAutofillDialogController* controller() { return controller_.get(); }
638
639  const FormStructure* form_structure() { return form_structure_; }
640
641  TestGeneratedCreditCardBubbleController* test_generated_bubble_controller() {
642    return test_generated_bubble_controller_;
643  }
644
645  const MockNewCreditCardBubbleController* mock_new_card_bubble_controller() {
646    return mock_new_card_bubble_controller_.get();
647  }
648
649 private:
650  void FinishedCallback(const FormStructure* form_structure) {
651    form_structure_ = form_structure;
652  }
653
654#if defined(OS_WIN)
655   // http://crbug.com/227221
656   ui::ScopedOleInitializer ole_initializer_;
657#endif
658
659  // The controller owns itself.
660  base::WeakPtr<TestAutofillDialogController> controller_;
661
662  // Must outlive the controller.
663  AutofillMetrics metric_logger_;
664
665  // Returned when the dialog closes successfully.
666  const FormStructure* form_structure_;
667
668  // Used to monitor if the Autofill credit card bubble is shown. Owned by
669  // |web_contents()|.
670  TestGeneratedCreditCardBubbleController* test_generated_bubble_controller_;
671
672  // Used to record when new card bubbles would show. Created in |Reset()|.
673  scoped_ptr<MockNewCreditCardBubbleController>
674      mock_new_card_bubble_controller_;
675
676  scoped_ptr<ScopedTestingLocalState> scoped_local_state_;
677};
678
679}  // namespace
680
681// Ensure the default ValidityMessage has the expected values.
682TEST_F(AutofillDialogControllerTest, DefaultValidityMessage) {
683  ValidityMessages messages;
684  ValidityMessage message = messages.GetMessageOrDefault(UNKNOWN_TYPE);
685  EXPECT_FALSE(message.sure);
686  EXPECT_TRUE(message.text.empty());
687}
688
689// This test makes sure nothing falls over when fields are being validity-
690// checked.
691TEST_F(AutofillDialogControllerTest, ValidityCheck) {
692  for (size_t i = SECTION_MIN; i <= SECTION_MAX; ++i) {
693    DialogSection section = static_cast<DialogSection>(i);
694    const DetailInputs& shipping_inputs =
695        controller()->RequestedFieldsForSection(section);
696    for (DetailInputs::const_iterator iter = shipping_inputs.begin();
697         iter != shipping_inputs.end(); ++iter) {
698      controller()->InputValidityMessage(section, iter->type, base::string16());
699    }
700  }
701}
702
703// Test for phone number validation.
704TEST_F(AutofillDialogControllerTest, PhoneNumberValidation) {
705  // Construct FieldValueMap from existing data.
706  SwitchToAutofill();
707
708  for (size_t i = 0; i < 2; ++i) {
709    ServerFieldType phone = i == 0 ? PHONE_HOME_WHOLE_NUMBER :
710                                     PHONE_BILLING_WHOLE_NUMBER;
711    ServerFieldType address = i == 0 ? ADDRESS_HOME_COUNTRY :
712                                       ADDRESS_BILLING_COUNTRY;
713    DialogSection section = i == 0 ? SECTION_SHIPPING : SECTION_BILLING;
714
715    FieldValueMap outputs;
716    const DetailInputs& inputs =
717        controller()->RequestedFieldsForSection(section);
718    AutofillProfile full_profile(test::GetVerifiedProfile());
719    for (size_t i = 0; i < inputs.size(); ++i) {
720      const ServerFieldType type = inputs[i].type;
721      outputs[type] = full_profile.GetInfo(AutofillType(type), "en-US");
722    }
723
724    // Make sure country is United States.
725    outputs[address] = ASCIIToUTF16("United States");
726
727    // Existing data should have no errors.
728    ValidityMessages messages = controller()->InputsAreValid(section, outputs);
729    EXPECT_FALSE(HasAnyError(messages, phone));
730
731    // Input an empty phone number.
732    outputs[phone] = base::string16();
733    messages = controller()->InputsAreValid(section, outputs);
734    EXPECT_TRUE(HasUnsureError(messages, phone));
735
736    // Input an invalid phone number.
737    outputs[phone] = ASCIIToUTF16("ABC");
738    messages = controller()->InputsAreValid(section, outputs);
739    EXPECT_TRUE(messages.HasSureError(phone));
740
741    // Input a local phone number.
742    outputs[phone] = ASCIIToUTF16("2155546699");
743    messages = controller()->InputsAreValid(section, outputs);
744    EXPECT_FALSE(HasAnyError(messages, phone));
745
746    // Input an invalid local phone number.
747    outputs[phone] = ASCIIToUTF16("215554669");
748    messages = controller()->InputsAreValid(section, outputs);
749    EXPECT_TRUE(messages.HasSureError(phone));
750
751    // Input an international phone number.
752    outputs[phone] = ASCIIToUTF16("+33 892 70 12 39");
753    messages = controller()->InputsAreValid(section, outputs);
754    EXPECT_FALSE(HasAnyError(messages, phone));
755
756    // Input an invalid international phone number.
757    outputs[phone] = ASCIIToUTF16("+112333 892 70 12 39");
758    messages = controller()->InputsAreValid(section, outputs);
759    EXPECT_TRUE(messages.HasSureError(phone));
760
761    // Input a valid Canadian number.
762    outputs[phone] = ASCIIToUTF16("+1 506 887 1234");
763    messages = controller()->InputsAreValid(section, outputs);
764    EXPECT_FALSE(HasAnyError(messages, phone));
765
766    // Input a valid Canadian number without the country code.
767    outputs[phone] = ASCIIToUTF16("506 887 1234");
768    messages = controller()->InputsAreValid(section, outputs);
769    EXPECT_TRUE(HasAnyError(messages, phone));
770
771    // Input a valid Canadian toll-free number.
772    outputs[phone] = ASCIIToUTF16("310 1234");
773    messages = controller()->InputsAreValid(section, outputs);
774    EXPECT_TRUE(HasAnyError(messages, phone));
775  }
776}
777
778TEST_F(AutofillDialogControllerTest, ExpirationDateValidity) {
779  ui::ComboboxModel* exp_year_model =
780      controller()->ComboboxModelForAutofillType(CREDIT_CARD_EXP_4_DIGIT_YEAR);
781  ui::ComboboxModel* exp_month_model =
782      controller()->ComboboxModelForAutofillType(CREDIT_CARD_EXP_MONTH);
783
784  base::string16 default_year_value =
785      exp_year_model->GetItemAt(exp_year_model->GetDefaultIndex());
786  base::string16 default_month_value =
787      exp_month_model->GetItemAt(exp_month_model->GetDefaultIndex());
788
789  base::string16 other_year_value =
790      exp_year_model->GetItemAt(exp_year_model->GetItemCount() - 1);
791  base::string16 other_month_value =
792      exp_month_model->GetItemAt(exp_month_model->GetItemCount() - 1);
793
794  FieldValueMap outputs;
795  outputs[ADDRESS_BILLING_COUNTRY] = ASCIIToUTF16("United States");
796  outputs[CREDIT_CARD_EXP_MONTH] = default_month_value;
797  outputs[CREDIT_CARD_EXP_4_DIGIT_YEAR] = default_year_value;
798
799  // Expiration default values generate unsure validation errors (but not sure).
800  ValidityMessages messages = controller()->InputsAreValid(SECTION_CC_BILLING,
801                                                           outputs);
802  EXPECT_TRUE(HasUnsureError(messages, CREDIT_CARD_EXP_4_DIGIT_YEAR));
803  EXPECT_TRUE(HasUnsureError(messages, CREDIT_CARD_EXP_MONTH));
804
805  // Expiration date with default month fails.
806  outputs[CREDIT_CARD_EXP_4_DIGIT_YEAR] = other_year_value;
807  messages = controller()->InputsAreValid(SECTION_CC_BILLING, outputs);
808  EXPECT_FALSE(HasUnsureError(messages, CREDIT_CARD_EXP_4_DIGIT_YEAR));
809  EXPECT_TRUE(HasUnsureError(messages, CREDIT_CARD_EXP_MONTH));
810
811  // Expiration date with default year fails.
812  outputs[CREDIT_CARD_EXP_MONTH] = other_month_value;
813  outputs[CREDIT_CARD_EXP_4_DIGIT_YEAR] = default_year_value;
814  messages = controller()->InputsAreValid(SECTION_CC_BILLING, outputs);
815  EXPECT_TRUE(HasUnsureError(messages, CREDIT_CARD_EXP_4_DIGIT_YEAR));
816  EXPECT_FALSE(HasUnsureError(messages, CREDIT_CARD_EXP_MONTH));
817}
818
819TEST_F(AutofillDialogControllerTest, BillingNameValidation) {
820  // Construct FieldValueMap from AutofillProfile data.
821  SwitchToAutofill();
822
823  FieldValueMap outputs;
824  outputs[ADDRESS_BILLING_COUNTRY] = ASCIIToUTF16("United States");
825
826  // Input an empty billing name.
827  outputs[NAME_BILLING_FULL] = base::string16();
828  ValidityMessages messages = controller()->InputsAreValid(SECTION_BILLING,
829                                                           outputs);
830  EXPECT_TRUE(HasUnsureError(messages, NAME_BILLING_FULL));
831
832  // Input a non-empty billing name.
833  outputs[NAME_BILLING_FULL] = ASCIIToUTF16("Bob");
834  messages = controller()->InputsAreValid(SECTION_BILLING, outputs);
835  EXPECT_FALSE(HasAnyError(messages, NAME_BILLING_FULL));
836
837  // Switch to Wallet which only considers names with with at least two names to
838  // be valid.
839  SwitchToWallet();
840
841  // Setup some wallet state.
842  scoped_ptr<wallet::WalletItems> wallet_items =
843      wallet::GetTestWalletItems(wallet::AMEX_DISALLOWED);
844  controller()->OnDidGetWalletItems(wallet_items.Pass());
845
846  // Input an empty billing name. Data source should not change this behavior.
847  outputs[NAME_BILLING_FULL] = base::string16();
848  messages = controller()->InputsAreValid(SECTION_CC_BILLING, outputs);
849  EXPECT_TRUE(HasUnsureError(messages, NAME_BILLING_FULL));
850
851  // Input a one name billing name. Wallet does not currently support this.
852  outputs[NAME_BILLING_FULL] = ASCIIToUTF16("Bob");
853  messages = controller()->InputsAreValid(SECTION_CC_BILLING, outputs);
854  EXPECT_TRUE(messages.HasSureError(NAME_BILLING_FULL));
855
856  // Input a two name billing name.
857  outputs[NAME_BILLING_FULL] = ASCIIToUTF16("Bob Barker");
858  messages = controller()->InputsAreValid(SECTION_CC_BILLING, outputs);
859  EXPECT_FALSE(HasAnyError(messages, NAME_BILLING_FULL));
860
861  // Input a more than two name billing name.
862  outputs[NAME_BILLING_FULL] = ASCIIToUTF16("John Jacob Jingleheimer Schmidt"),
863  messages = controller()->InputsAreValid(SECTION_CC_BILLING, outputs);
864  EXPECT_FALSE(HasAnyError(messages, NAME_BILLING_FULL));
865
866  // Input a billing name with lots of crazy whitespace.
867  outputs[NAME_BILLING_FULL] =
868      ASCIIToUTF16("     \\n\\r John \\n  Jacob Jingleheimer \\t Schmidt  "),
869  messages = controller()->InputsAreValid(SECTION_CC_BILLING, outputs);
870  EXPECT_FALSE(HasAnyError(messages, NAME_BILLING_FULL));
871}
872
873TEST_F(AutofillDialogControllerTest, CreditCardNumberValidation) {
874  // Construct FieldValueMap from AutofillProfile data.
875  SwitchToAutofill();
876
877  // Should accept AMEX, Visa, Master and Discover.
878  ValidateCCNumber(SECTION_CC, kTestCCNumberVisa, true);
879  ValidateCCNumber(SECTION_CC, kTestCCNumberMaster, true);
880  ValidateCCNumber(SECTION_CC, kTestCCNumberDiscover, true);
881  ValidateCCNumber(SECTION_CC, kTestCCNumberAmex, true);
882  ValidateCCNumber(SECTION_CC, kTestCCNumberIncomplete, false);
883  ValidateCCNumber(SECTION_CC, kTestCCNumberInvalid, false);
884
885  // Switch to Wallet which will not accept AMEX.
886  SwitchToWallet();
887
888  // Setup some wallet state on a merchant for which Wallet doesn't
889  // support AMEX.
890  controller()->OnDidGetWalletItems(
891      wallet::GetTestWalletItems(wallet::AMEX_DISALLOWED));
892
893  // Should accept Visa, Master and Discover, but not AMEX.
894  ValidateCCNumber(SECTION_CC_BILLING, kTestCCNumberVisa, true);
895  ValidateCCNumber(SECTION_CC_BILLING, kTestCCNumberMaster, true);
896  ValidateCCNumber(SECTION_CC_BILLING, kTestCCNumberDiscover, true);
897  ValidateCCNumber(SECTION_CC_BILLING, kTestCCNumberAmex, false);
898  ValidateCCNumber(SECTION_CC_BILLING, kTestCCNumberIncomplete, false);
899  ValidateCCNumber(SECTION_CC_BILLING, kTestCCNumberInvalid, false);
900
901  // Setup some wallet state on a merchant for which Wallet supports AMEX.
902  controller()->OnDidGetWalletItems(
903      wallet::GetTestWalletItems(wallet::AMEX_ALLOWED));
904
905  // Should accept Visa, Master, Discover, and AMEX.
906  ValidateCCNumber(SECTION_CC_BILLING, kTestCCNumberVisa, true);
907  ValidateCCNumber(SECTION_CC_BILLING, kTestCCNumberMaster, true);
908  ValidateCCNumber(SECTION_CC_BILLING, kTestCCNumberDiscover, true);
909  ValidateCCNumber(SECTION_CC_BILLING, kTestCCNumberAmex, true);
910  ValidateCCNumber(SECTION_CC_BILLING, kTestCCNumberIncomplete, false);
911  ValidateCCNumber(SECTION_CC_BILLING, kTestCCNumberInvalid, false);
912}
913
914TEST_F(AutofillDialogControllerTest, AutofillProfiles) {
915  SwitchToAutofill();
916  ui::MenuModel* shipping_model =
917      controller()->MenuModelForSection(SECTION_SHIPPING);
918  // Since the PersonalDataManager is empty, this should only have the
919  // "use billing", "add new" and "manage" menu items.
920  ASSERT_TRUE(shipping_model);
921  EXPECT_EQ(3, shipping_model->GetItemCount());
922  // On the other hand, the other models should be NULL when there's no
923  // suggestion.
924  EXPECT_FALSE(controller()->MenuModelForSection(SECTION_CC));
925  EXPECT_FALSE(controller()->MenuModelForSection(SECTION_BILLING));
926
927  EXPECT_CALL(*controller()->GetView(), ModelChanged()).Times(3);
928
929  // Empty profiles are ignored.
930  AutofillProfile empty_profile(base::GenerateGUID(), kSettingsOrigin);
931  empty_profile.SetRawInfo(NAME_FULL, ASCIIToUTF16("John Doe"));
932  controller()->GetTestingManager()->AddTestingProfile(&empty_profile);
933  shipping_model = controller()->MenuModelForSection(SECTION_SHIPPING);
934  ASSERT_TRUE(shipping_model);
935  EXPECT_EQ(3, shipping_model->GetItemCount());
936
937  // An otherwise full but unverified profile should be ignored.
938  AutofillProfile full_profile(test::GetFullProfile());
939  full_profile.set_origin("https://www.example.com");
940  full_profile.SetRawInfo(ADDRESS_HOME_LINE2, base::string16());
941  controller()->GetTestingManager()->AddTestingProfile(&full_profile);
942  shipping_model = controller()->MenuModelForSection(SECTION_SHIPPING);
943  ASSERT_TRUE(shipping_model);
944  EXPECT_EQ(3, shipping_model->GetItemCount());
945
946  // A full, verified profile should be picked up.
947  AutofillProfile verified_profile(test::GetVerifiedProfile());
948  verified_profile.SetRawInfo(ADDRESS_HOME_LINE2, base::string16());
949  controller()->GetTestingManager()->AddTestingProfile(&verified_profile);
950  shipping_model = controller()->MenuModelForSection(SECTION_SHIPPING);
951  ASSERT_TRUE(shipping_model);
952  EXPECT_EQ(4, shipping_model->GetItemCount());
953}
954
955// Checks that a valid profile is selected by default, but if invalid is
956// popped into edit mode.
957TEST_F(AutofillDialogControllerTest, AutofillProfilesPopInvalidIntoEdit) {
958  SwitchToAutofill();
959  SuggestionsMenuModel* shipping_model =
960      GetMenuModelForSection(SECTION_SHIPPING);
961  EXPECT_EQ(3, shipping_model->GetItemCount());
962  // "Same as billing" is selected.
963  EXPECT_FALSE(controller()->IsManuallyEditingSection(SECTION_SHIPPING));
964  EXPECT_TRUE(controller()->IsManuallyEditingSection(SECTION_BILLING));
965
966  AutofillProfile verified_profile(test::GetVerifiedProfile());
967  controller()->GetTestingManager()->AddTestingProfile(&verified_profile);
968  EXPECT_EQ(4, shipping_model->GetItemCount());
969  EXPECT_FALSE(controller()->IsManuallyEditingSection(SECTION_SHIPPING));
970  EXPECT_FALSE(controller()->IsManuallyEditingSection(SECTION_BILLING));
971
972  // Now make up a problem and make sure the profile isn't in the list.
973  Reset();
974  SwitchToAutofill();
975  AddressProblems problems;
976  problems.push_back(
977      AddressProblem(::i18n::addressinput::POSTAL_CODE,
978                     AddressProblem::MISMATCHING_VALUE,
979                     IDS_LEARN_MORE));
980  EXPECT_CALL(*controller()->GetMockValidator(),
981              ValidateAddress(CountryCodeMatcher("US"), _, _)).
982      WillRepeatedly(DoAll(SetArgPointee<2>(problems),
983                           Return(AddressValidator::SUCCESS)));
984
985  controller()->GetTestingManager()->AddTestingProfile(&verified_profile);
986  shipping_model = GetMenuModelForSection(SECTION_SHIPPING);
987  EXPECT_EQ(4, shipping_model->GetItemCount());
988  EXPECT_TRUE(controller()->IsManuallyEditingSection(SECTION_SHIPPING));
989  EXPECT_TRUE(controller()->IsManuallyEditingSection(SECTION_BILLING));
990}
991
992// Makes sure suggestion profiles are re-validated when validation rules load.
993TEST_F(AutofillDialogControllerTest, AutofillProfilesRevalidateAfterRulesLoad) {
994  SwitchToAutofill();
995  SuggestionsMenuModel* shipping_model =
996      GetMenuModelForSection(SECTION_SHIPPING);
997  EXPECT_EQ(3, shipping_model->GetItemCount());
998  // "Same as billing" is selected.
999  EXPECT_FALSE(controller()->IsManuallyEditingSection(SECTION_SHIPPING));
1000  EXPECT_TRUE(controller()->IsManuallyEditingSection(SECTION_BILLING));
1001  AutofillProfile verified_profile(test::GetVerifiedProfile());
1002  controller()->GetTestingManager()->AddTestingProfile(&verified_profile);
1003  EXPECT_EQ(4, shipping_model->GetItemCount());
1004  EXPECT_FALSE(controller()->IsManuallyEditingSection(SECTION_SHIPPING));
1005  EXPECT_FALSE(controller()->IsManuallyEditingSection(SECTION_BILLING));
1006
1007  AddressProblems problems;
1008  problems.push_back(
1009      AddressProblem(::i18n::addressinput::POSTAL_CODE,
1010                     AddressProblem::MISMATCHING_VALUE,
1011                     IDS_LEARN_MORE));
1012  EXPECT_CALL(*controller()->GetMockValidator(),
1013              ValidateAddress(CountryCodeMatcher("US"), _, _)).
1014      WillRepeatedly(DoAll(SetArgPointee<2>(problems),
1015                           Return(AddressValidator::SUCCESS)));
1016
1017  controller()->OnAddressValidationRulesLoaded("US", true);
1018  EXPECT_EQ(4, shipping_model->GetItemCount());
1019  EXPECT_TRUE(controller()->IsManuallyEditingSection(SECTION_SHIPPING));
1020  EXPECT_TRUE(controller()->IsManuallyEditingSection(SECTION_BILLING));
1021}
1022
1023// Makes sure that the choice of which Autofill profile to use for each section
1024// is sticky.
1025TEST_F(AutofillDialogControllerTest, AutofillProfileDefaults) {
1026  SwitchToAutofill();
1027  AutofillProfile profile(test::GetVerifiedProfile());
1028  AutofillProfile profile2(test::GetVerifiedProfile2());
1029  controller()->GetTestingManager()->AddTestingProfile(&profile);
1030  controller()->GetTestingManager()->AddTestingProfile(&profile2);
1031
1032  // Until a selection has been made, the default shipping suggestion is the
1033  // first one (after "use billing").
1034  SuggestionsMenuModel* shipping_model =
1035      GetMenuModelForSection(SECTION_SHIPPING);
1036  EXPECT_EQ(1, shipping_model->checked_item());
1037
1038  for (int i = 2; i >= 0; --i) {
1039    shipping_model = GetMenuModelForSection(SECTION_SHIPPING);
1040    shipping_model->ExecuteCommand(i, 0);
1041    FillCreditCardInputs();
1042    controller()->OnAccept();
1043
1044    Reset();
1045    controller()->GetTestingManager()->AddTestingProfile(&profile);
1046    controller()->GetTestingManager()->AddTestingProfile(&profile2);
1047    shipping_model = GetMenuModelForSection(SECTION_SHIPPING);
1048    EXPECT_EQ(i, shipping_model->checked_item());
1049  }
1050
1051  // Try again, but don't add the default profile to the PDM. The dialog
1052  // should fall back to the first profile.
1053  shipping_model->ExecuteCommand(2, 0);
1054  FillCreditCardInputs();
1055  controller()->OnAccept();
1056  Reset();
1057  controller()->GetTestingManager()->AddTestingProfile(&profile);
1058  shipping_model = GetMenuModelForSection(SECTION_SHIPPING);
1059  EXPECT_EQ(1, shipping_model->checked_item());
1060}
1061
1062// Makes sure that a newly added Autofill profile becomes set as the default
1063// choice for the next run.
1064TEST_F(AutofillDialogControllerTest, NewAutofillProfileIsDefault) {
1065  SwitchToAutofill();
1066
1067  AutofillProfile profile(test::GetVerifiedProfile());
1068  CreditCard credit_card(test::GetVerifiedCreditCard());
1069  controller()->GetTestingManager()->AddTestingProfile(&profile);
1070  controller()->GetTestingManager()->AddTestingCreditCard(&credit_card);
1071
1072  // Until a selection has been made, the default suggestion is the first one.
1073  // For the shipping section, this follows the "use billing" suggestion.
1074  EXPECT_EQ(0, GetMenuModelForSection(SECTION_CC)->checked_item());
1075  EXPECT_EQ(1, GetMenuModelForSection(SECTION_SHIPPING)->checked_item());
1076
1077  // Fill in the shipping and credit card sections with new data.
1078  AutofillProfile new_profile(test::GetVerifiedProfile2());
1079  CreditCard new_credit_card(test::GetVerifiedCreditCard2());
1080  FillInputs(SECTION_SHIPPING, new_profile);
1081  FillInputs(SECTION_CC, new_credit_card);
1082  controller()->GetView()->CheckSaveDetailsLocallyCheckbox(true);
1083  controller()->OnAccept();
1084
1085  // Update the |new_profile| and |new_credit_card|'s guids to the saved ones.
1086  new_profile.set_guid(
1087      controller()->GetTestingManager()->imported_profile().guid());
1088  new_credit_card.set_guid(
1089      controller()->GetTestingManager()->imported_credit_card().guid());
1090
1091  // Reload the dialog. The newly added address and credit card should now be
1092  // set as the defaults.
1093  Reset();
1094  controller()->GetTestingManager()->AddTestingProfile(&profile);
1095  controller()->GetTestingManager()->AddTestingProfile(&new_profile);
1096  controller()->GetTestingManager()->AddTestingCreditCard(&credit_card);
1097  controller()->GetTestingManager()->AddTestingCreditCard(&new_credit_card);
1098
1099  // Until a selection has been made, the default suggestion is the first one.
1100  // For the shipping section, this follows the "use billing" suggestion.
1101  EXPECT_EQ(1, GetMenuModelForSection(SECTION_CC)->checked_item());
1102  EXPECT_EQ(2, GetMenuModelForSection(SECTION_SHIPPING)->checked_item());
1103}
1104
1105TEST_F(AutofillDialogControllerTest, AutofillProfileVariants) {
1106  SwitchToAutofill();
1107  EXPECT_CALL(*controller()->GetView(), ModelChanged());
1108  ui::MenuModel* shipping_model =
1109      controller()->MenuModelForSection(SECTION_SHIPPING);
1110  ASSERT_TRUE(!!shipping_model);
1111  EXPECT_EQ(3, shipping_model->GetItemCount());
1112
1113  // Set up some variant data.
1114  AutofillProfile full_profile(test::GetVerifiedProfile());
1115  std::vector<base::string16> names;
1116  names.push_back(ASCIIToUTF16("John Doe"));
1117  names.push_back(ASCIIToUTF16("Jane Doe"));
1118  full_profile.SetRawMultiInfo(NAME_FULL, names);
1119  std::vector<base::string16> emails;
1120  emails.push_back(ASCIIToUTF16(kFakeEmail));
1121  emails.push_back(ASCIIToUTF16("admin@example.com"));
1122  full_profile.SetRawMultiInfo(EMAIL_ADDRESS, emails);
1123
1124  // Non-default variants are ignored by the dialog.
1125  controller()->GetTestingManager()->AddTestingProfile(&full_profile);
1126  EXPECT_EQ(4, shipping_model->GetItemCount());
1127}
1128
1129TEST_F(AutofillDialogControllerTest, SuggestValidEmail) {
1130  SwitchToAutofill();
1131  AutofillProfile profile(test::GetVerifiedProfile());
1132  const base::string16 kValidEmail = ASCIIToUTF16(kFakeEmail);
1133  profile.SetRawInfo(EMAIL_ADDRESS, kValidEmail);
1134  controller()->GetTestingManager()->AddTestingProfile(&profile);
1135
1136  // "add", "manage", and 1 suggestion.
1137  EXPECT_EQ(
1138      3, controller()->MenuModelForSection(SECTION_BILLING)->GetItemCount());
1139  // "add", "manage", 1 suggestion, and "same as billing".
1140  EXPECT_EQ(
1141      4, controller()->MenuModelForSection(SECTION_SHIPPING)->GetItemCount());
1142}
1143
1144TEST_F(AutofillDialogControllerTest, DoNotSuggestInvalidEmail) {
1145  SwitchToAutofill();
1146  AutofillProfile profile(test::GetVerifiedProfile());
1147  profile.SetRawInfo(EMAIL_ADDRESS, ASCIIToUTF16(".!#$%&'*+/=?^_`-@-.."));
1148  controller()->GetTestingManager()->AddTestingProfile(&profile);
1149
1150  EXPECT_FALSE(!!controller()->MenuModelForSection(SECTION_BILLING));
1151  // "add", "manage", 1 suggestion, and "same as billing".
1152  EXPECT_EQ(
1153      4, controller()->MenuModelForSection(SECTION_SHIPPING)->GetItemCount());
1154}
1155
1156TEST_F(AutofillDialogControllerTest, SuggestValidAddress) {
1157  SwitchToAutofill();
1158  AutofillProfile full_profile(test::GetVerifiedProfile());
1159  full_profile.set_origin(kSettingsOrigin);
1160  controller()->GetTestingManager()->AddTestingProfile(&full_profile);
1161  // "add", "manage", and 1 suggestion.
1162  EXPECT_EQ(
1163      3, controller()->MenuModelForSection(SECTION_BILLING)->GetItemCount());
1164}
1165
1166TEST_F(AutofillDialogControllerTest, DoNotSuggestInvalidAddress) {
1167  SwitchToAutofill();
1168  AutofillProfile full_profile(test::GetVerifiedProfile());
1169  full_profile.set_origin(kSettingsOrigin);
1170  full_profile.SetRawInfo(ADDRESS_HOME_STATE, ASCIIToUTF16("C"));
1171  controller()->GetTestingManager()->AddTestingProfile(&full_profile);
1172}
1173
1174TEST_F(AutofillDialogControllerTest, DoNotSuggestIncompleteAddress) {
1175  SwitchToAutofill();
1176  AutofillProfile profile(test::GetVerifiedProfile());
1177  profile.SetRawInfo(ADDRESS_HOME_STATE, base::string16());
1178  controller()->GetTestingManager()->AddTestingProfile(&profile);
1179
1180  // Same as shipping, manage, add new.
1181  EXPECT_EQ(3,
1182      controller()->MenuModelForSection(SECTION_SHIPPING)->GetItemCount());
1183  EXPECT_FALSE(!!controller()->MenuModelForSection(SECTION_BILLING));
1184}
1185
1186TEST_F(AutofillDialogControllerTest, DoSuggestShippingAddressWithoutEmail) {
1187  SwitchToAutofill();
1188  AutofillProfile profile(test::GetVerifiedProfile());
1189  profile.SetRawInfo(EMAIL_ADDRESS, base::string16());
1190  controller()->GetTestingManager()->AddTestingProfile(&profile);
1191
1192  // Same as shipping, manage, add new, profile with missing email.
1193  EXPECT_EQ(4,
1194      controller()->MenuModelForSection(SECTION_SHIPPING)->GetItemCount());
1195  // Billing addresses require email.
1196  EXPECT_FALSE(!!controller()->MenuModelForSection(SECTION_BILLING));
1197}
1198
1199TEST_F(AutofillDialogControllerTest, AutofillCreditCards) {
1200  SwitchToAutofill();
1201  // Since the PersonalDataManager is empty, this should only have the
1202  // default menu items.
1203  EXPECT_FALSE(controller()->MenuModelForSection(SECTION_CC));
1204
1205  EXPECT_CALL(*controller()->GetView(), ModelChanged()).Times(3);
1206
1207  // Empty cards are ignored.
1208  CreditCard empty_card(base::GenerateGUID(), kSettingsOrigin);
1209  empty_card.SetRawInfo(CREDIT_CARD_NAME, ASCIIToUTF16("John Doe"));
1210  controller()->GetTestingManager()->AddTestingCreditCard(&empty_card);
1211  EXPECT_FALSE(controller()->MenuModelForSection(SECTION_CC));
1212
1213  // An otherwise full but unverified card should be ignored.
1214  CreditCard full_card(test::GetCreditCard());
1215  full_card.set_origin("https://www.example.com");
1216  controller()->GetTestingManager()->AddTestingCreditCard(&full_card);
1217  EXPECT_FALSE(controller()->MenuModelForSection(SECTION_CC));
1218
1219  // A full, verified card should be picked up.
1220  CreditCard verified_card(test::GetCreditCard());
1221  verified_card.set_origin(kSettingsOrigin);
1222  controller()->GetTestingManager()->AddTestingCreditCard(&verified_card);
1223  ui::MenuModel* credit_card_model =
1224      controller()->MenuModelForSection(SECTION_CC);
1225  ASSERT_TRUE(credit_card_model);
1226  EXPECT_EQ(3, credit_card_model->GetItemCount());
1227}
1228
1229// Test selecting a shipping address different from billing as address.
1230TEST_F(AutofillDialogControllerTest, DontUseBillingAsShipping) {
1231  SwitchToAutofill();
1232  AutofillProfile full_profile(test::GetVerifiedProfile());
1233  AutofillProfile full_profile2(test::GetVerifiedProfile2());
1234  CreditCard credit_card(test::GetVerifiedCreditCard());
1235  controller()->GetTestingManager()->AddTestingProfile(&full_profile);
1236  controller()->GetTestingManager()->AddTestingProfile(&full_profile2);
1237  controller()->GetTestingManager()->AddTestingCreditCard(&credit_card);
1238  ui::MenuModel* shipping_model =
1239      controller()->MenuModelForSection(SECTION_SHIPPING);
1240  shipping_model->ActivatedAt(2);
1241
1242  controller()->OnAccept();
1243  ASSERT_EQ(20U, form_structure()->field_count());
1244  EXPECT_EQ(ADDRESS_HOME_STATE,
1245            form_structure()->field(9)->Type().GetStorableType());
1246  EXPECT_EQ(ADDRESS_BILLING, form_structure()->field(9)->Type().group());
1247  EXPECT_EQ(ADDRESS_HOME_STATE,
1248            form_structure()->field(16)->Type().GetStorableType());
1249  EXPECT_EQ(ADDRESS_HOME, form_structure()->field(16)->Type().group());
1250  base::string16 billing_state = form_structure()->field(9)->value;
1251  base::string16 shipping_state = form_structure()->field(16)->value;
1252  EXPECT_FALSE(billing_state.empty());
1253  EXPECT_FALSE(shipping_state.empty());
1254  EXPECT_NE(billing_state, shipping_state);
1255
1256  EXPECT_EQ(CREDIT_CARD_NAME,
1257            form_structure()->field(1)->Type().GetStorableType());
1258  base::string16 cc_name = form_structure()->field(1)->value;
1259  EXPECT_EQ(NAME_FULL, form_structure()->field(6)->Type().GetStorableType());
1260  EXPECT_EQ(NAME_BILLING, form_structure()->field(6)->Type().group());
1261  base::string16 billing_name = form_structure()->field(6)->value;
1262  EXPECT_EQ(NAME_FULL, form_structure()->field(13)->Type().GetStorableType());
1263  EXPECT_EQ(NAME, form_structure()->field(13)->Type().group());
1264  base::string16 shipping_name = form_structure()->field(13)->value;
1265
1266  EXPECT_FALSE(cc_name.empty());
1267  EXPECT_FALSE(billing_name.empty());
1268  EXPECT_FALSE(shipping_name.empty());
1269  // Billing name should always be the same as cardholder name.
1270  EXPECT_EQ(cc_name, billing_name);
1271  EXPECT_NE(cc_name, shipping_name);
1272}
1273
1274// Test selecting UseBillingForShipping.
1275TEST_F(AutofillDialogControllerTest, UseBillingAsShipping) {
1276  SwitchToAutofill();
1277
1278  AutofillProfile full_profile(test::GetVerifiedProfile());
1279  controller()->GetTestingManager()->AddTestingProfile(&full_profile);
1280
1281  AutofillProfile full_profile2(test::GetVerifiedProfile2());
1282  controller()->GetTestingManager()->AddTestingProfile(&full_profile2);
1283
1284  CreditCard credit_card(test::GetVerifiedCreditCard());
1285  controller()->GetTestingManager()->AddTestingCreditCard(&credit_card);
1286
1287  ASSERT_FALSE(controller()->IsManuallyEditingSection(SECTION_CC));
1288  ASSERT_FALSE(controller()->IsManuallyEditingSection(SECTION_BILLING));
1289
1290  SubmitAndVerifyShippingAndBillingResults();
1291}
1292
1293TEST_F(AutofillDialogControllerTest, UseBillingAsShippingManualInput) {
1294  SwitchToAutofill();
1295
1296  ASSERT_TRUE(controller()->IsManuallyEditingSection(SECTION_CC));
1297  ASSERT_TRUE(controller()->IsManuallyEditingSection(SECTION_BILLING));
1298
1299  CreditCard credit_card(test::GetVerifiedCreditCard());
1300  FillInputs(SECTION_CC, credit_card);
1301
1302  AutofillProfile full_profile(test::GetVerifiedProfile());
1303  FillInputs(SECTION_BILLING, full_profile);
1304
1305  SubmitAndVerifyShippingAndBillingResults();
1306}
1307
1308// Tests that shipping and billing telephone fields are supported, and filled
1309// in by their respective profiles. http://crbug.com/244515
1310TEST_F(AutofillDialogControllerTest, BillingVsShippingPhoneNumber) {
1311  FormFieldData shipping_tel;
1312  shipping_tel.autocomplete_attribute = "shipping tel";
1313  FormFieldData billing_tel;
1314  billing_tel.autocomplete_attribute = "billing tel";
1315
1316  FormData form_data;
1317  form_data.fields.push_back(shipping_tel);
1318  form_data.fields.push_back(billing_tel);
1319  SetUpControllerWithFormData(form_data);
1320
1321  SwitchToAutofill();
1322
1323  // The profile that will be chosen for the shipping section.
1324  AutofillProfile shipping_profile(test::GetVerifiedProfile());
1325  // The profile that will be chosen for the billing section.
1326  AutofillProfile billing_profile(test::GetVerifiedProfile2());
1327  CreditCard credit_card(test::GetVerifiedCreditCard());
1328  controller()->GetTestingManager()->AddTestingProfile(&shipping_profile);
1329  controller()->GetTestingManager()->AddTestingProfile(&billing_profile);
1330  controller()->GetTestingManager()->AddTestingCreditCard(&credit_card);
1331  ui::MenuModel* billing_model =
1332      controller()->MenuModelForSection(SECTION_BILLING);
1333  billing_model->ActivatedAt(1);
1334
1335  controller()->OnAccept();
1336  ASSERT_EQ(2U, form_structure()->field_count());
1337  EXPECT_EQ(PHONE_HOME_WHOLE_NUMBER,
1338            form_structure()->field(0)->Type().GetStorableType());
1339  EXPECT_EQ(PHONE_HOME, form_structure()->field(0)->Type().group());
1340  EXPECT_EQ(PHONE_HOME_WHOLE_NUMBER,
1341            form_structure()->field(1)->Type().GetStorableType());
1342  EXPECT_EQ(PHONE_BILLING, form_structure()->field(1)->Type().group());
1343  EXPECT_EQ(shipping_profile.GetRawInfo(PHONE_HOME_WHOLE_NUMBER),
1344            form_structure()->field(0)->value);
1345  EXPECT_EQ(billing_profile.GetRawInfo(PHONE_HOME_WHOLE_NUMBER),
1346            form_structure()->field(1)->value);
1347  EXPECT_NE(form_structure()->field(1)->value,
1348            form_structure()->field(0)->value);
1349}
1350
1351// Similar to the above, but tests that street-address (i.e. all lines of the
1352// street address) is successfully filled for both shipping and billing
1353// sections.
1354TEST_F(AutofillDialogControllerTest, BillingVsShippingStreetAddress) {
1355  FormFieldData shipping_address;
1356  shipping_address.autocomplete_attribute = "shipping street-address";
1357  FormFieldData billing_address;
1358  billing_address.autocomplete_attribute = "billing street-address";
1359  FormFieldData shipping_address_textarea;
1360  shipping_address_textarea.autocomplete_attribute = "shipping street-address";
1361  shipping_address_textarea.form_control_type = "textarea";
1362  FormFieldData billing_address_textarea;
1363  billing_address_textarea.autocomplete_attribute = "billing street-address";
1364  billing_address_textarea.form_control_type = "textarea";
1365
1366  FormData form_data;
1367  form_data.fields.push_back(shipping_address);
1368  form_data.fields.push_back(billing_address);
1369  form_data.fields.push_back(shipping_address_textarea);
1370  form_data.fields.push_back(billing_address_textarea);
1371  SetUpControllerWithFormData(form_data);
1372
1373  SwitchToAutofill();
1374
1375  // The profile that will be chosen for the shipping section.
1376  AutofillProfile shipping_profile(test::GetVerifiedProfile());
1377  // The profile that will be chosen for the billing section.
1378  AutofillProfile billing_profile(test::GetVerifiedProfile2());
1379  CreditCard credit_card(test::GetVerifiedCreditCard());
1380  controller()->GetTestingManager()->AddTestingProfile(&shipping_profile);
1381  controller()->GetTestingManager()->AddTestingProfile(&billing_profile);
1382  controller()->GetTestingManager()->AddTestingCreditCard(&credit_card);
1383  ui::MenuModel* billing_model =
1384      controller()->MenuModelForSection(SECTION_BILLING);
1385  billing_model->ActivatedAt(1);
1386
1387  controller()->OnAccept();
1388  ASSERT_EQ(4U, form_structure()->field_count());
1389  EXPECT_EQ(ADDRESS_HOME_STREET_ADDRESS,
1390            form_structure()->field(0)->Type().GetStorableType());
1391  EXPECT_EQ(ADDRESS_HOME, form_structure()->field(0)->Type().group());
1392  EXPECT_EQ(ADDRESS_HOME_STREET_ADDRESS,
1393            form_structure()->field(1)->Type().GetStorableType());
1394  EXPECT_EQ(ADDRESS_BILLING, form_structure()->field(1)->Type().group());
1395  // Inexact matching; single-line inputs get the address data concatenated but
1396  // separated by commas.
1397  EXPECT_TRUE(StartsWith(form_structure()->field(0)->value,
1398                         shipping_profile.GetRawInfo(ADDRESS_HOME_LINE1),
1399                         true));
1400  EXPECT_TRUE(EndsWith(form_structure()->field(0)->value,
1401                       shipping_profile.GetRawInfo(ADDRESS_HOME_LINE2),
1402                       true));
1403  EXPECT_TRUE(StartsWith(form_structure()->field(1)->value,
1404                         billing_profile.GetRawInfo(ADDRESS_HOME_LINE1),
1405                         true));
1406  EXPECT_TRUE(EndsWith(form_structure()->field(1)->value,
1407                       billing_profile.GetRawInfo(ADDRESS_HOME_LINE2),
1408                       true));
1409  // The textareas should be an exact match.
1410  EXPECT_EQ(shipping_profile.GetRawInfo(ADDRESS_HOME_STREET_ADDRESS),
1411            form_structure()->field(2)->value);
1412  EXPECT_EQ(billing_profile.GetRawInfo(ADDRESS_HOME_STREET_ADDRESS),
1413            form_structure()->field(3)->value);
1414
1415  EXPECT_NE(form_structure()->field(1)->value,
1416            form_structure()->field(0)->value);
1417  EXPECT_NE(form_structure()->field(3)->value,
1418            form_structure()->field(2)->value);
1419}
1420
1421TEST_F(AutofillDialogControllerTest, AcceptLegalDocuments) {
1422  for (size_t i = 0; i < 2; ++i) {
1423    SCOPED_TRACE(testing::Message() << "Case " << i);
1424
1425    EXPECT_CALL(*controller()->GetTestingWalletClient(),
1426                AcceptLegalDocuments(_, _));
1427    EXPECT_CALL(*controller()->GetTestingWalletClient(), GetFullWallet(_));
1428    EXPECT_CALL(*controller(), LoadRiskFingerprintData());
1429
1430    EXPECT_TRUE(controller()->LegalDocumentLinks().empty());
1431    controller()->OnDidGetWalletItems(CompleteAndValidWalletItems());
1432    EXPECT_TRUE(controller()->LegalDocumentLinks().empty());
1433
1434    scoped_ptr<wallet::WalletItems> wallet_items =
1435        CompleteAndValidWalletItems();
1436    wallet_items->AddLegalDocument(wallet::GetTestLegalDocument());
1437    wallet_items->AddLegalDocument(wallet::GetTestLegalDocument());
1438    controller()->OnDidGetWalletItems(wallet_items.Pass());
1439    EXPECT_FALSE(controller()->LegalDocumentLinks().empty());
1440
1441    controller()->OnAccept();
1442    controller()->OnDidAcceptLegalDocuments();
1443    controller()->OnDidLoadRiskFingerprintData(GetFakeFingerprint().Pass());
1444
1445    // Now try it all over again with the location disclosure already accepted.
1446    // Nothing should change.
1447    Reset();
1448    base::ListValue preexisting_list;
1449    preexisting_list.AppendString(kFakeEmail);
1450    g_browser_process->local_state()->Set(
1451        ::prefs::kAutofillDialogWalletLocationAcceptance,
1452        preexisting_list);
1453  }
1454}
1455
1456TEST_F(AutofillDialogControllerTest, RejectLegalDocuments) {
1457  for (size_t i = 0; i < 2; ++i) {
1458    SCOPED_TRACE(testing::Message() << "Case " << i);
1459
1460    EXPECT_CALL(*controller()->GetTestingWalletClient(),
1461                AcceptLegalDocuments(_, _)).Times(0);
1462
1463    scoped_ptr<wallet::WalletItems> wallet_items =
1464        CompleteAndValidWalletItems();
1465    wallet_items->AddLegalDocument(wallet::GetTestLegalDocument());
1466    wallet_items->AddLegalDocument(wallet::GetTestLegalDocument());
1467    controller()->OnDidGetWalletItems(wallet_items.Pass());
1468    EXPECT_FALSE(controller()->LegalDocumentLinks().empty());
1469
1470    controller()->OnCancel();
1471
1472    // Now try it all over again with the location disclosure already accepted.
1473    // Nothing should change.
1474    Reset();
1475    base::ListValue preexisting_list;
1476    preexisting_list.AppendString(kFakeEmail);
1477    g_browser_process->local_state()->Set(
1478        ::prefs::kAutofillDialogWalletLocationAcceptance,
1479        preexisting_list);
1480  }
1481}
1482
1483TEST_F(AutofillDialogControllerTest, AcceptLocationDisclosure) {
1484  // Check that accepting the dialog registers the user's name in the list
1485  // of users who have accepted the geolocation terms.
1486  EXPECT_TRUE(g_browser_process->local_state()->GetList(
1487      ::prefs::kAutofillDialogWalletLocationAcceptance)->empty());
1488
1489  controller()->OnDidGetWalletItems(CompleteAndValidWalletItems());
1490  EXPECT_FALSE(controller()->LegalDocumentsText().empty());
1491  EXPECT_TRUE(controller()->LegalDocumentLinks().empty());
1492  controller()->OnAccept();
1493
1494  const base::ListValue* list = g_browser_process->local_state()->GetList(
1495      ::prefs::kAutofillDialogWalletLocationAcceptance);
1496  ASSERT_EQ(1U, list->GetSize());
1497  std::string accepted_username;
1498  EXPECT_TRUE(list->GetString(0, &accepted_username));
1499  EXPECT_EQ(kFakeEmail, accepted_username);
1500
1501  // Now check it still works if that list starts off with some other username
1502  // in it.
1503  Reset();
1504  list = g_browser_process->local_state()->GetList(
1505      ::prefs::kAutofillDialogWalletLocationAcceptance);
1506  ASSERT_TRUE(list->empty());
1507
1508  std::string kOtherUsername("spouse@example.com");
1509  base::ListValue preexisting_list;
1510  preexisting_list.AppendString(kOtherUsername);
1511  g_browser_process->local_state()->Set(
1512      ::prefs::kAutofillDialogWalletLocationAcceptance,
1513      preexisting_list);
1514
1515  controller()->OnDidGetWalletItems(CompleteAndValidWalletItems());
1516  EXPECT_FALSE(controller()->LegalDocumentsText().empty());
1517  EXPECT_TRUE(controller()->LegalDocumentLinks().empty());
1518  controller()->OnAccept();
1519
1520  list = g_browser_process->local_state()->GetList(
1521      ::prefs::kAutofillDialogWalletLocationAcceptance);
1522  ASSERT_EQ(2U, list->GetSize());
1523  EXPECT_NE(list->end(), list->Find(base::StringValue(kFakeEmail)));
1524  EXPECT_NE(list->end(), list->Find(base::StringValue(kOtherUsername)));
1525
1526  // Now check the list doesn't change if the user cancels out of the dialog.
1527  Reset();
1528  list = g_browser_process->local_state()->GetList(
1529      ::prefs::kAutofillDialogWalletLocationAcceptance);
1530  ASSERT_TRUE(list->empty());
1531
1532  g_browser_process->local_state()->Set(
1533      ::prefs::kAutofillDialogWalletLocationAcceptance,
1534      preexisting_list);
1535
1536  controller()->OnDidGetWalletItems(CompleteAndValidWalletItems());
1537  EXPECT_FALSE(controller()->LegalDocumentsText().empty());
1538  EXPECT_TRUE(controller()->LegalDocumentLinks().empty());
1539  controller()->OnCancel();
1540
1541  list = g_browser_process->local_state()->GetList(
1542      ::prefs::kAutofillDialogWalletLocationAcceptance);
1543  ASSERT_EQ(1U, list->GetSize());
1544  EXPECT_NE(list->end(), list->Find(base::StringValue(kOtherUsername)));
1545  EXPECT_EQ(list->end(), list->Find(base::StringValue(kFakeEmail)));
1546}
1547
1548TEST_F(AutofillDialogControllerTest, LegalDocumentOverflow) {
1549  for (size_t number_of_docs = 2; number_of_docs < 11; ++number_of_docs) {
1550    scoped_ptr<wallet::WalletItems> wallet_items =
1551        CompleteAndValidWalletItems();
1552    for (size_t i = 0; i < number_of_docs; ++i)
1553      wallet_items->AddLegalDocument(wallet::GetTestLegalDocument());
1554
1555    Reset();
1556    controller()->OnDidGetWalletItems(wallet_items.Pass());
1557
1558    // The dialog is only equipped to handle 2-6 legal documents. More than
1559    // 6 errors out.
1560    if (number_of_docs <= 6U) {
1561      EXPECT_FALSE(controller()->LegalDocumentsText().empty());
1562    } else {
1563      EXPECT_TRUE(controller()->LegalDocumentsText().empty());
1564      EXPECT_EQ(1U, NotificationsOfType(
1565          DialogNotification::WALLET_ERROR).size());
1566    }
1567  }
1568
1569  controller()->OnCancel();
1570}
1571
1572// Makes sure the default object IDs are respected.
1573TEST_F(AutofillDialogControllerTest, WalletDefaultItems) {
1574  scoped_ptr<wallet::WalletItems> wallet_items =
1575      wallet::GetTestWalletItems(wallet::AMEX_DISALLOWED);
1576  wallet_items->AddInstrument(wallet::GetTestNonDefaultMaskedInstrument());
1577  wallet_items->AddInstrument(wallet::GetTestNonDefaultMaskedInstrument());
1578  wallet_items->AddInstrument(wallet::GetTestMaskedInstrument());
1579  wallet_items->AddInstrument(wallet::GetTestNonDefaultMaskedInstrument());
1580
1581  wallet_items->AddAddress(wallet::GetTestNonDefaultShippingAddress());
1582  wallet_items->AddAddress(wallet::GetTestNonDefaultShippingAddress());
1583  wallet_items->AddAddress(wallet::GetTestNonDefaultShippingAddress());
1584  wallet_items->AddAddress(wallet::GetTestShippingAddress());
1585  wallet_items->AddAddress(wallet::GetTestNonDefaultShippingAddress());
1586
1587  controller()->OnDidGetWalletItems(wallet_items.Pass());
1588  // "add", "manage", and 4 suggestions.
1589  EXPECT_EQ(6,
1590      controller()->MenuModelForSection(SECTION_CC_BILLING)->GetItemCount());
1591  EXPECT_TRUE(controller()->MenuModelForSection(SECTION_CC_BILLING)->
1592      IsItemCheckedAt(2));
1593  ASSERT_FALSE(controller()->IsEditingExistingData(SECTION_CC_BILLING));
1594  // "use billing", "add", "manage", and 5 suggestions.
1595  EXPECT_EQ(8,
1596      controller()->MenuModelForSection(SECTION_SHIPPING)->GetItemCount());
1597  EXPECT_TRUE(controller()->MenuModelForSection(SECTION_SHIPPING)->
1598      IsItemCheckedAt(4));
1599  ASSERT_FALSE(controller()->IsEditingExistingData(SECTION_SHIPPING));
1600}
1601
1602// Tests that invalid and AMEX default instruments are ignored.
1603TEST_F(AutofillDialogControllerTest, SelectInstrument) {
1604  scoped_ptr<wallet::WalletItems> wallet_items =
1605      wallet::GetTestWalletItems(wallet::AMEX_DISALLOWED);
1606  // Tests if default instrument is invalid, then, the first valid instrument is
1607  // selected instead of the default instrument.
1608  wallet_items->AddInstrument(wallet::GetTestNonDefaultMaskedInstrument());
1609  wallet_items->AddInstrument(wallet::GetTestNonDefaultMaskedInstrument());
1610  wallet_items->AddInstrument(wallet::GetTestMaskedInstrumentInvalid());
1611  wallet_items->AddInstrument(wallet::GetTestNonDefaultMaskedInstrument());
1612
1613  controller()->OnDidGetWalletItems(wallet_items.Pass());
1614  // 4 suggestions and "add", "manage".
1615  EXPECT_EQ(6,
1616      controller()->MenuModelForSection(SECTION_CC_BILLING)->GetItemCount());
1617  EXPECT_TRUE(controller()->MenuModelForSection(SECTION_CC_BILLING)->
1618      IsItemCheckedAt(0));
1619
1620  // Tests if default instrument is AMEX but Wallet doesn't support
1621  // AMEX on this merchant, then the first valid instrument is
1622  // selected instead of the default instrument.
1623  wallet_items = wallet::GetTestWalletItems(wallet::AMEX_DISALLOWED);
1624  wallet_items->AddInstrument(wallet::GetTestNonDefaultMaskedInstrument());
1625  wallet_items->AddInstrument(wallet::GetTestNonDefaultMaskedInstrument());
1626  wallet_items->AddInstrument(
1627      wallet::GetTestMaskedInstrumentAmex(wallet::AMEX_DISALLOWED));
1628  wallet_items->AddInstrument(wallet::GetTestNonDefaultMaskedInstrument());
1629
1630  controller()->OnDidGetWalletItems(wallet_items.Pass());
1631  // 4 suggestions and "add", "manage".
1632  EXPECT_EQ(6,
1633      controller()->MenuModelForSection(SECTION_CC_BILLING)->GetItemCount());
1634  EXPECT_TRUE(controller()->MenuModelForSection(SECTION_CC_BILLING)->
1635      IsItemCheckedAt(0));
1636
1637  // Tests if default instrument is AMEX and it is allowed on this merchant,
1638  // then it is selected.
1639  wallet_items = wallet::GetTestWalletItems(wallet::AMEX_ALLOWED);
1640  wallet_items->AddInstrument(wallet::GetTestNonDefaultMaskedInstrument());
1641  wallet_items->AddInstrument(wallet::GetTestNonDefaultMaskedInstrument());
1642  wallet_items->AddInstrument(
1643      wallet::GetTestMaskedInstrumentAmex(wallet::AMEX_ALLOWED));
1644  wallet_items->AddInstrument(wallet::GetTestNonDefaultMaskedInstrument());
1645
1646  controller()->OnDidGetWalletItems(wallet_items.Pass());
1647  // 4 suggestions and "add", "manage".
1648  EXPECT_EQ(6,
1649      controller()->MenuModelForSection(SECTION_CC_BILLING)->GetItemCount());
1650  EXPECT_TRUE(controller()->MenuModelForSection(SECTION_CC_BILLING)->
1651      IsItemCheckedAt(2));
1652
1653  // Tests if only have AMEX and invalid instrument, then "add" is selected.
1654  wallet_items = wallet::GetTestWalletItems(wallet::AMEX_DISALLOWED);
1655  wallet_items->AddInstrument(wallet::GetTestMaskedInstrumentInvalid());
1656  wallet_items->AddInstrument(
1657      wallet::GetTestMaskedInstrumentAmex(wallet::AMEX_DISALLOWED));
1658
1659  controller()->OnDidGetWalletItems(wallet_items.Pass());
1660  // 2 suggestions and "add", "manage".
1661  EXPECT_EQ(4,
1662      controller()->MenuModelForSection(SECTION_CC_BILLING)->GetItemCount());
1663  // "add"
1664  EXPECT_TRUE(controller()->MenuModelForSection(SECTION_CC_BILLING)->
1665      IsItemCheckedAt(2));
1666}
1667
1668TEST_F(AutofillDialogControllerTest, SaveAddress) {
1669  EXPECT_CALL(*controller()->GetView(), ModelChanged());
1670  EXPECT_CALL(*controller()->GetTestingWalletClient(),
1671              SaveToWalletMock(testing::IsNull(),
1672                               testing::NotNull(),
1673                               testing::IsNull(),
1674                               testing::IsNull()));
1675
1676  scoped_ptr<wallet::WalletItems> wallet_items =
1677      wallet::GetTestWalletItems(wallet::AMEX_DISALLOWED);
1678  wallet_items->AddInstrument(wallet::GetTestMaskedInstrument());
1679  controller()->OnDidGetWalletItems(wallet_items.Pass());
1680  // If there is no shipping address in wallet, it will default to
1681  // "same-as-billing" instead of "add-new-item". "same-as-billing" is covered
1682  // by the following tests. The penultimate item in the menu is "add-new-item".
1683  ui::MenuModel* shipping_model =
1684      controller()->MenuModelForSection(SECTION_SHIPPING);
1685  shipping_model->ActivatedAt(shipping_model->GetItemCount() - 2);
1686
1687  AutofillProfile test_profile(test::GetVerifiedProfile());
1688  FillInputs(SECTION_SHIPPING, test_profile);
1689
1690  AcceptAndLoadFakeFingerprint();
1691}
1692
1693TEST_F(AutofillDialogControllerTest, SaveInstrument) {
1694  EXPECT_CALL(*controller()->GetView(), ModelChanged());
1695  EXPECT_CALL(*controller()->GetTestingWalletClient(),
1696              SaveToWalletMock(testing::NotNull(),
1697                               testing::IsNull(),
1698                               testing::IsNull(),
1699                               testing::IsNull()));
1700
1701  FillCCBillingInputs();
1702  scoped_ptr<wallet::WalletItems> wallet_items =
1703      wallet::GetTestWalletItems(wallet::AMEX_DISALLOWED);
1704  wallet_items->AddAddress(wallet::GetTestShippingAddress());
1705  SubmitWithWalletItems(wallet_items.Pass());
1706}
1707
1708TEST_F(AutofillDialogControllerTest, SaveInstrumentWithInvalidInstruments) {
1709  EXPECT_CALL(*controller()->GetView(), ModelChanged());
1710  EXPECT_CALL(*controller()->GetTestingWalletClient(),
1711              SaveToWalletMock(testing::NotNull(),
1712                               testing::IsNull(),
1713                               testing::IsNull(),
1714                               testing::IsNull()));
1715
1716  FillCCBillingInputs();
1717  scoped_ptr<wallet::WalletItems> wallet_items =
1718      wallet::GetTestWalletItems(wallet::AMEX_DISALLOWED);
1719  wallet_items->AddAddress(wallet::GetTestShippingAddress());
1720  wallet_items->AddInstrument(wallet::GetTestMaskedInstrumentInvalid());
1721  SubmitWithWalletItems(wallet_items.Pass());
1722}
1723
1724TEST_F(AutofillDialogControllerTest, SaveInstrumentAndAddress) {
1725  EXPECT_CALL(*controller()->GetTestingWalletClient(),
1726              SaveToWalletMock(testing::NotNull(),
1727                               testing::NotNull(),
1728                               testing::IsNull(),
1729                               testing::IsNull()));
1730
1731  FillCCBillingInputs();
1732  scoped_ptr<wallet::WalletItems> wallet_items =
1733      wallet::GetTestWalletItems(wallet::AMEX_DISALLOWED);
1734  SubmitWithWalletItems(wallet_items.Pass());
1735}
1736
1737MATCHER(IsUpdatingExistingData, "updating existing Wallet data") {
1738  return !arg->object_id().empty();
1739}
1740
1741MATCHER(UsesLocalBillingAddress, "uses the local billing address") {
1742  return arg->street_address()[0] == ASCIIToUTF16(kEditedBillingAddress);
1743}
1744
1745// Tests that when using billing address for shipping, and there is no exact
1746// matched shipping address, then a shipping address should be added.
1747TEST_F(AutofillDialogControllerTest, BillingForShipping) {
1748  EXPECT_CALL(*controller()->GetTestingWalletClient(),
1749              SaveToWalletMock(testing::IsNull(),
1750                               testing::NotNull(),
1751                               testing::IsNull(),
1752                               testing::IsNull()));
1753
1754  controller()->OnDidGetWalletItems(CompleteAndValidWalletItems());
1755  // Select "Same as billing" in the address menu.
1756  UseBillingForShipping();
1757
1758  AcceptAndLoadFakeFingerprint();
1759}
1760
1761// Tests that when using billing address for shipping, and there is an exact
1762// matched shipping address, then a shipping address should not be added.
1763TEST_F(AutofillDialogControllerTest, BillingForShippingHasMatch) {
1764  EXPECT_CALL(*controller()->GetTestingWalletClient(),
1765              SaveToWalletMock(_, _, _, _)).Times(0);
1766
1767  scoped_ptr<wallet::WalletItems> wallet_items =
1768      wallet::GetTestWalletItems(wallet::AMEX_DISALLOWED);
1769  scoped_ptr<wallet::WalletItems::MaskedInstrument> instrument =
1770      wallet::GetTestMaskedInstrument();
1771  // Copy billing address as shipping address, and assign an id to it.
1772  scoped_ptr<wallet::Address> shipping_address(
1773      new wallet::Address(instrument->address()));
1774  shipping_address->set_object_id("shipping_address_id");
1775  wallet_items->AddAddress(shipping_address.Pass());
1776  wallet_items->AddInstrument(instrument.Pass());
1777  wallet_items->AddAddress(wallet::GetTestShippingAddress());
1778
1779  controller()->OnDidGetWalletItems(wallet_items.Pass());
1780  // Select "Same as billing" in the address menu.
1781  UseBillingForShipping();
1782
1783  AcceptAndLoadFakeFingerprint();
1784}
1785
1786// Test that the local view contents is used when saving a new instrument and
1787// the user has selected "Same as billing".
1788TEST_F(AutofillDialogControllerTest, SaveInstrumentSameAsBilling) {
1789  scoped_ptr<wallet::WalletItems> wallet_items =
1790      wallet::GetTestWalletItems(wallet::AMEX_DISALLOWED);
1791  wallet_items->AddInstrument(wallet::GetTestMaskedInstrument());
1792  controller()->OnDidGetWalletItems(wallet_items.Pass());
1793
1794  ui::MenuModel* model = controller()->MenuModelForSection(SECTION_CC_BILLING);
1795  model->ActivatedAt(model->GetItemCount() - 2);
1796
1797  FieldValueMap outputs;
1798  const DetailInputs& inputs =
1799      controller()->RequestedFieldsForSection(SECTION_CC_BILLING);
1800  AutofillProfile full_profile(test::GetVerifiedProfile());
1801  CreditCard full_card(test::GetCreditCard());
1802  for (size_t i = 0; i < inputs.size(); ++i) {
1803    const ServerFieldType type = inputs[i].type;
1804    if (type == ADDRESS_BILLING_LINE1)
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  AutofillProfile cn_profile(test::GetVerifiedProfile());
3352  cn_profile.SetRawInfo(NAME_FULL, ASCIIToUTF16("Chinese User"));
3353  cn_profile.SetRawInfo(ADDRESS_HOME_COUNTRY, ASCIIToUTF16("CN"));
3354  controller()->GetTestingManager()->AddTestingProfile(&cn_profile);
3355
3356  controller()->UserEditedOrActivatedInput(
3357      SECTION_SHIPPING,
3358      NAME_FULL,
3359      gfx::NativeView(),
3360      gfx::Rect(),
3361      cn_profile.GetRawInfo(NAME_FULL).substr(0, 1),
3362      true);
3363  EXPECT_EQ(UNKNOWN_TYPE, controller()->popup_input_type());
3364
3365  AutofillProfile us_profile(test::GetVerifiedProfile());
3366  us_profile.SetRawInfo(NAME_FULL, ASCIIToUTF16("American User"));
3367  ASSERT_NE(cn_profile.GetRawInfo(NAME_FULL)[0],
3368            us_profile.GetRawInfo(NAME_FULL)[0]);
3369  controller()->GetTestingManager()->AddTestingProfile(&us_profile);
3370
3371  controller()->UserEditedOrActivatedInput(
3372      SECTION_SHIPPING,
3373      NAME_FULL,
3374      gfx::NativeView(),
3375      gfx::Rect(),
3376      us_profile.GetRawInfo(NAME_FULL).substr(0, 1),
3377      true);
3378  EXPECT_EQ(NAME_FULL, controller()->popup_input_type());
3379}
3380
3381TEST_F(AutofillDialogControllerTest, SuggestCountrylessProfiles) {
3382  SwitchToAutofill();
3383
3384  AutofillProfile profile(test::GetVerifiedProfile());
3385  profile.SetRawInfo(NAME_FULL, ASCIIToUTF16("The Man Without a Country"));
3386  profile.SetRawInfo(ADDRESS_HOME_COUNTRY, base::string16());
3387  controller()->GetTestingManager()->AddTestingProfile(&profile);
3388
3389  controller()->UserEditedOrActivatedInput(
3390      SECTION_SHIPPING,
3391      NAME_FULL,
3392      gfx::NativeView(),
3393      gfx::Rect(),
3394      profile.GetRawInfo(NAME_FULL).substr(0, 1),
3395      true);
3396  EXPECT_EQ(NAME_FULL, controller()->popup_input_type());
3397}
3398
3399}  // namespace autofill
3400