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