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