Home | History | Annotate | Download | only in autofill
      1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
      2 // Use of this source code is governed by a BSD-style license that can be
      3 // found in the LICENSE file.
      4 
      5 #include <map>
      6 
      7 #include "base/bind.h"
      8 #include "base/command_line.h"
      9 #include "base/guid.h"
     10 #include "base/memory/scoped_ptr.h"
     11 #include "base/message_loop/message_loop.h"
     12 #include "base/prefs/pref_service.h"
     13 #include "base/run_loop.h"
     14 #include "base/strings/string_number_conversions.h"
     15 #include "base/strings/utf_string_conversions.h"
     16 #include "base/tuple.h"
     17 #include "chrome/browser/ui/autofill/autofill_dialog_controller_impl.h"
     18 #include "chrome/browser/ui/autofill/autofill_dialog_view.h"
     19 #include "chrome/browser/ui/autofill/generated_credit_card_bubble_controller.h"
     20 #include "chrome/browser/ui/autofill/mock_new_credit_card_bubble_controller.h"
     21 #include "chrome/browser/ui/autofill/test_generated_credit_card_bubble_view.h"
     22 #include "chrome/common/pref_names.h"
     23 #include "chrome/common/render_messages.h"
     24 #include "chrome/test/base/chrome_render_view_host_test_harness.h"
     25 #include "chrome/test/base/testing_profile.h"
     26 #include "components/autofill/content/browser/risk/proto/fingerprint.pb.h"
     27 #include "components/autofill/content/browser/wallet/full_wallet.h"
     28 #include "components/autofill/content/browser/wallet/instrument.h"
     29 #include "components/autofill/content/browser/wallet/mock_wallet_client.h"
     30 #include "components/autofill/content/browser/wallet/wallet_address.h"
     31 #include "components/autofill/content/browser/wallet/wallet_service_url.h"
     32 #include "components/autofill/content/browser/wallet/wallet_test_util.h"
     33 #include "components/autofill/core/browser/autofill_common_test.h"
     34 #include "components/autofill/core/browser/autofill_metrics.h"
     35 #include "components/autofill/core/browser/test_personal_data_manager.h"
     36 #include "components/autofill/core/common/autofill_switches.h"
     37 #include "components/autofill/core/common/form_data.h"
     38 #include "content/public/browser/web_contents.h"
     39 #include "content/public/test/mock_render_process_host.h"
     40 #include "testing/gmock/include/gmock/gmock.h"
     41 #include "testing/gtest/include/gtest/gtest.h"
     42 
     43 #if defined(OS_WIN)
     44 #include "ui/base/win/scoped_ole_initializer.h"
     45 #endif
     46 
     47 using testing::_;
     48 
     49 namespace autofill {
     50 
     51 namespace {
     52 
     53 const char kFakeEmail[] = "user (at) example.com";
     54 const char kFakeFingerprintEncoded[] = "CgVaAwiACA==";
     55 const char kEditedBillingAddress[] = "123 edited billing address";
     56 const char* kFieldsFromPage[] =
     57     { "email",
     58       "cc-name",
     59       "cc-number",
     60       "cc-exp-month",
     61       "cc-exp-year",
     62       "cc-csc",
     63       "billing name",
     64       "billing address-line1",
     65       "billing locality",
     66       "billing region",
     67       "billing postal-code",
     68       "billing country",
     69       "billing tel",
     70       "shipping name",
     71       "shipping address-line1",
     72       "shipping locality",
     73       "shipping region",
     74       "shipping postal-code",
     75       "shipping country",
     76       "shipping tel",
     77     };
     78 const char kSettingsOrigin[] = "Chrome settings";
     79 const char kTestCCNumberAmex[] = "376200000000002";
     80 const char kTestCCNumberVisa[] = "4111111111111111";
     81 const char kTestCCNumberMaster[] = "5555555555554444";
     82 const char kTestCCNumberDiscover[] = "6011111111111117";
     83 const char kTestCCNumberIncomplete[] = "4111111111";
     84 // Credit card number fails Luhn check.
     85 const char kTestCCNumberInvalid[] = "4111111111111112";
     86 
     87 
     88 void SetOutputValue(const DetailInputs& inputs,
     89                     DetailOutputMap* outputs,
     90                     ServerFieldType type,
     91                     const base::string16& value) {
     92   for (size_t i = 0; i < inputs.size(); ++i) {
     93     const DetailInput& input = inputs[i];
     94     (*outputs)[&input] = input.type == type ?
     95         value :
     96         input.initial_value;
     97   }
     98 }
     99 
    100 scoped_ptr<wallet::WalletItems> CompleteAndValidWalletItems() {
    101   scoped_ptr<wallet::WalletItems> items = wallet::GetTestWalletItems();
    102   items->AddInstrument(wallet::GetTestMaskedInstrument());
    103   items->AddAddress(wallet::GetTestShippingAddress());
    104   return items.Pass();
    105 }
    106 
    107 scoped_ptr<wallet::FullWallet> CreateFullWallet(const char* required_action) {
    108   base::DictionaryValue dict;
    109   scoped_ptr<base::ListValue> list(new base::ListValue());
    110   list->AppendString(required_action);
    111   dict.Set("required_action", list.release());
    112   return wallet::FullWallet::CreateFullWallet(dict);
    113 }
    114 
    115 scoped_ptr<risk::Fingerprint> GetFakeFingerprint() {
    116   scoped_ptr<risk::Fingerprint> fingerprint(new risk::Fingerprint());
    117   // Add some data to the proto, else the encoded content is empty.
    118   fingerprint->mutable_machine_characteristics()->mutable_screen_size()->
    119       set_width(1024);
    120   return fingerprint.Pass();
    121 }
    122 
    123 class TestAutofillDialogView : public AutofillDialogView {
    124  public:
    125   TestAutofillDialogView() {}
    126   virtual ~TestAutofillDialogView() {}
    127 
    128   virtual void Show() OVERRIDE {}
    129   virtual void Hide() OVERRIDE {}
    130   virtual void UpdateNotificationArea() OVERRIDE {}
    131   virtual void UpdateAccountChooser() OVERRIDE {}
    132   virtual void UpdateButtonStrip() OVERRIDE {}
    133   virtual void UpdateDetailArea() OVERRIDE {}
    134   virtual void UpdateAutocheckoutStepsArea() OVERRIDE {}
    135   virtual void UpdateSection(DialogSection section) OVERRIDE {}
    136   virtual void FillSection(DialogSection section,
    137                            const DetailInput& originating_input) OVERRIDE {};
    138   virtual void GetUserInput(DialogSection section, DetailOutputMap* output)
    139       OVERRIDE {
    140     *output = outputs_[section];
    141   }
    142   virtual TestableAutofillDialogView* GetTestableView() OVERRIDE {
    143     return NULL;
    144   }
    145 
    146   virtual string16 GetCvc() OVERRIDE { return string16(); }
    147   virtual bool SaveDetailsLocally() OVERRIDE { return true; }
    148   virtual const content::NavigationController* ShowSignIn() OVERRIDE {
    149     return NULL;
    150   }
    151   virtual void HideSignIn() OVERRIDE {}
    152   virtual void UpdateProgressBar(double value) OVERRIDE {}
    153 
    154   MOCK_METHOD0(ModelChanged, void());
    155   MOCK_METHOD0(UpdateForErrors, void());
    156 
    157   virtual void OnSignInResize(const gfx::Size& pref_size) OVERRIDE {}
    158 
    159   void SetUserInput(DialogSection section, const DetailOutputMap& map) {
    160     outputs_[section] = map;
    161   }
    162 
    163  private:
    164   std::map<DialogSection, DetailOutputMap> outputs_;
    165 
    166   DISALLOW_COPY_AND_ASSIGN(TestAutofillDialogView);
    167 };
    168 
    169 // Bring over command-ids from AccountChooserModel.
    170 class TestAccountChooserModel : public AccountChooserModel {
    171  public:
    172   TestAccountChooserModel(AccountChooserModelDelegate* delegate,
    173                           PrefService* prefs,
    174                           const AutofillMetrics& metric_logger)
    175       : AccountChooserModel(delegate, prefs, metric_logger,
    176                             DIALOG_TYPE_REQUEST_AUTOCOMPLETE) {}
    177   virtual ~TestAccountChooserModel() {}
    178 
    179   using AccountChooserModel::kActiveWalletItemId;
    180   using AccountChooserModel::kAutofillItemId;
    181 
    182  private:
    183   DISALLOW_COPY_AND_ASSIGN(TestAccountChooserModel);
    184 };
    185 
    186 class TestAutofillDialogController
    187     : public AutofillDialogControllerImpl,
    188       public base::SupportsWeakPtr<TestAutofillDialogController> {
    189  public:
    190   TestAutofillDialogController(
    191       content::WebContents* contents,
    192       const FormData& form_structure,
    193       const GURL& source_url,
    194       const AutofillMetrics& metric_logger,
    195       const DialogType dialog_type,
    196       const base::Callback<void(const FormStructure*,
    197                                 const std::string&)>& callback,
    198       MockNewCreditCardBubbleController* mock_new_card_bubble_controller)
    199       : AutofillDialogControllerImpl(contents,
    200                                      form_structure,
    201                                      source_url,
    202                                      dialog_type,
    203                                      callback),
    204         metric_logger_(metric_logger),
    205         mock_wallet_client_(
    206             Profile::FromBrowserContext(contents->GetBrowserContext())->
    207                 GetRequestContext(), this),
    208         dialog_type_(dialog_type),
    209         mock_new_card_bubble_controller_(mock_new_card_bubble_controller) {}
    210 
    211   virtual ~TestAutofillDialogController() {}
    212 
    213   virtual AutofillDialogView* CreateView() OVERRIDE {
    214     return new testing::NiceMock<TestAutofillDialogView>();
    215   }
    216 
    217   void Init(content::BrowserContext* browser_context) {
    218     test_manager_.Init(browser_context);
    219   }
    220 
    221   TestAutofillDialogView* GetView() {
    222     return static_cast<TestAutofillDialogView*>(view());
    223   }
    224 
    225   TestPersonalDataManager* GetTestingManager() {
    226     return &test_manager_;
    227   }
    228 
    229   wallet::MockWalletClient* GetTestingWalletClient() {
    230     return &mock_wallet_client_;
    231   }
    232 
    233   const GURL& open_tab_url() { return open_tab_url_; }
    234 
    235   virtual DialogType GetDialogType() const OVERRIDE {
    236     return dialog_type_;
    237   }
    238 
    239   void set_dialog_type(DialogType dialog_type) { dialog_type_ = dialog_type; }
    240 
    241   void SimulateSigninError() {
    242     OnWalletSigninError();
    243   }
    244 
    245   bool AutocheckoutIsRunning() const {
    246     return AUTOCHECKOUT_IN_PROGRESS == autocheckout_state();
    247   }
    248 
    249   MOCK_METHOD0(LoadRiskFingerprintData, void());
    250   using AutofillDialogControllerImpl::OnDidLoadRiskFingerprintData;
    251   using AutofillDialogControllerImpl::IsEditingExistingData;
    252 
    253  protected:
    254   virtual PersonalDataManager* GetManager() OVERRIDE {
    255     return &test_manager_;
    256   }
    257 
    258   virtual wallet::WalletClient* GetWalletClient() OVERRIDE {
    259     return &mock_wallet_client_;
    260   }
    261 
    262   virtual void OpenTabWithUrl(const GURL& url) OVERRIDE {
    263     open_tab_url_ = url;
    264   }
    265 
    266   // Whether the information input in this dialog will be securely transmitted
    267   // to the requesting site.
    268   virtual bool TransmissionWillBeSecure() const OVERRIDE {
    269     return true;
    270   }
    271 
    272   virtual void ShowNewCreditCardBubble(
    273       scoped_ptr<CreditCard> new_card,
    274       scoped_ptr<AutofillProfile> billing_profile) OVERRIDE {
    275     mock_new_card_bubble_controller_->Show(new_card.Pass(),
    276                                            billing_profile.Pass());
    277   }
    278 
    279  private:
    280   // To specify our own metric logger.
    281   virtual const AutofillMetrics& GetMetricLogger() const OVERRIDE {
    282     return metric_logger_;
    283   }
    284 
    285   const AutofillMetrics& metric_logger_;
    286   TestPersonalDataManager test_manager_;
    287   testing::NiceMock<wallet::MockWalletClient> mock_wallet_client_;
    288   GURL open_tab_url_;
    289   DialogType dialog_type_;
    290   MockNewCreditCardBubbleController* mock_new_card_bubble_controller_;
    291 
    292   DISALLOW_COPY_AND_ASSIGN(TestAutofillDialogController);
    293 };
    294 
    295 class TestGeneratedCreditCardBubbleController :
    296     public GeneratedCreditCardBubbleController {
    297  public:
    298   explicit TestGeneratedCreditCardBubbleController(
    299       content::WebContents* contents)
    300       : GeneratedCreditCardBubbleController(contents) {
    301     contents->SetUserData(UserDataKey(), this);
    302     CHECK_EQ(contents->GetUserData(UserDataKey()), this);
    303   }
    304 
    305   virtual ~TestGeneratedCreditCardBubbleController() {}
    306 
    307   MOCK_METHOD2(SetupAndShow, void(const base::string16& backing_card_name,
    308                                   const base::string16& fronting_card_name));
    309 
    310  protected:
    311   virtual base::WeakPtr<GeneratedCreditCardBubbleView> CreateBubble() OVERRIDE {
    312     return TestGeneratedCreditCardBubbleView::Create(GetWeakPtr());
    313   }
    314 
    315   virtual bool CanShow() const OVERRIDE {
    316     return true;
    317   }
    318 
    319  private:
    320   DISALLOW_COPY_AND_ASSIGN(TestGeneratedCreditCardBubbleController);
    321 };
    322 
    323 class AutofillDialogControllerTest : public ChromeRenderViewHostTestHarness {
    324  protected:
    325   AutofillDialogControllerTest(): form_structure_(NULL) {}
    326 
    327   // testing::Test implementation:
    328   virtual void SetUp() OVERRIDE {
    329     ChromeRenderViewHostTestHarness::SetUp();
    330     Reset();
    331   }
    332 
    333   virtual void TearDown() OVERRIDE {
    334     if (controller_)
    335       controller_->ViewClosed();
    336     ChromeRenderViewHostTestHarness::TearDown();
    337   }
    338 
    339   void Reset() {
    340     if (controller_)
    341       controller_->ViewClosed();
    342 
    343     test_generated_bubble_controller_ =
    344         new testing::NiceMock<TestGeneratedCreditCardBubbleController>(
    345             web_contents());
    346     mock_new_card_bubble_controller_.reset(
    347         new MockNewCreditCardBubbleController);
    348 
    349     // Don't get stuck on the first run wallet interstitial.
    350     profile()->GetPrefs()->SetBoolean(::prefs::kAutofillDialogHasPaidWithWallet,
    351                                       true);
    352 
    353     SetUpControllerWithFormData(DefaultFormData());
    354   }
    355 
    356   FormData DefaultFormData() {
    357     FormData form_data;
    358     for (size_t i = 0; i < arraysize(kFieldsFromPage); ++i) {
    359       FormFieldData field;
    360       field.autocomplete_attribute = kFieldsFromPage[i];
    361       form_data.fields.push_back(field);
    362     }
    363     return form_data;
    364   }
    365 
    366   void SetUpControllerWithFormData(const FormData& form_data) {
    367     if (controller_)
    368       controller_->ViewClosed();
    369 
    370     base::Callback<void(const FormStructure*, const std::string&)> callback =
    371         base::Bind(&AutofillDialogControllerTest::FinishedCallback,
    372                    base::Unretained(this));
    373     controller_ = (new testing::NiceMock<TestAutofillDialogController>(
    374         web_contents(),
    375         form_data,
    376         GURL(),
    377         metric_logger_,
    378         DIALOG_TYPE_REQUEST_AUTOCOMPLETE,
    379         callback,
    380         mock_new_card_bubble_controller_.get()))->AsWeakPtr();
    381     controller_->Init(profile());
    382     controller_->Show();
    383     controller_->OnUserNameFetchSuccess(kFakeEmail);
    384   }
    385 
    386   void FillCreditCardInputs() {
    387     DetailOutputMap cc_outputs;
    388     const DetailInputs& cc_inputs =
    389         controller()->RequestedFieldsForSection(SECTION_CC);
    390     for (size_t i = 0; i < cc_inputs.size(); ++i) {
    391       cc_outputs[&cc_inputs[i]] = cc_inputs[i].type == CREDIT_CARD_NUMBER ?
    392           ASCIIToUTF16(kTestCCNumberVisa) : ASCIIToUTF16("11");
    393     }
    394     controller()->GetView()->SetUserInput(SECTION_CC, cc_outputs);
    395   }
    396 
    397   std::vector<DialogNotification> NotificationsOfType(
    398       DialogNotification::Type type) {
    399     std::vector<DialogNotification> right_type;
    400     const std::vector<DialogNotification>& notifications =
    401         controller()->CurrentNotifications();
    402     for (size_t i = 0; i < notifications.size(); ++i) {
    403       if (notifications[i].type() == type)
    404         right_type.push_back(notifications[i]);
    405     }
    406     return right_type;
    407   }
    408 
    409   void SwitchToAutofill() {
    410     controller_->MenuModelForAccountChooser()->ActivatedAt(
    411         TestAccountChooserModel::kAutofillItemId);
    412   }
    413 
    414   void SwitchToWallet() {
    415     controller_->MenuModelForAccountChooser()->ActivatedAt(
    416         TestAccountChooserModel::kActiveWalletItemId);
    417   }
    418 
    419   void SimulateSigninError() {
    420     controller_->SimulateSigninError();
    421   }
    422 
    423   void UseBillingForShipping() {
    424     controller()->MenuModelForSection(SECTION_SHIPPING)->ActivatedAt(0);
    425   }
    426 
    427   void ValidateCCNumber(DialogSection section,
    428                         const std::string& cc_number,
    429                         bool should_pass) {
    430     DetailOutputMap outputs;
    431     const DetailInputs& inputs =
    432         controller()->RequestedFieldsForSection(section);
    433 
    434     SetOutputValue(inputs, &outputs, CREDIT_CARD_NUMBER,
    435                    ASCIIToUTF16(cc_number));
    436     ValidityData validity_data =
    437         controller()->InputsAreValid(section, outputs, VALIDATE_FINAL);
    438     EXPECT_EQ(should_pass ? 0U : 1U, validity_data.count(CREDIT_CARD_NUMBER));
    439   }
    440 
    441   void SubmitWithWalletItems(scoped_ptr<wallet::WalletItems> wallet_items) {
    442     controller()->OnDidGetWalletItems(wallet_items.Pass());
    443     AcceptAndLoadFakeFingerprint();
    444   }
    445 
    446   void AcceptAndLoadFakeFingerprint() {
    447     controller()->OnAccept();
    448     controller()->OnDidLoadRiskFingerprintData(GetFakeFingerprint().Pass());
    449   }
    450 
    451   bool ReadSetVisuallyDeemphasizedIpc() {
    452     EXPECT_EQ(1U, process()->sink().message_count());
    453     uint32 kMsgID = ChromeViewMsg_SetVisuallyDeemphasized::ID;
    454     const IPC::Message* message =
    455         process()->sink().GetFirstMessageMatching(kMsgID);
    456     EXPECT_TRUE(message);
    457     Tuple1<bool> payload;
    458     ChromeViewMsg_SetVisuallyDeemphasized::Read(message, &payload);
    459     process()->sink().ClearMessages();
    460     return payload.a;
    461   }
    462 
    463   TestAutofillDialogController* controller() { return controller_.get(); }
    464 
    465   const FormStructure* form_structure() { return form_structure_; }
    466 
    467   TestGeneratedCreditCardBubbleController* test_generated_bubble_controller() {
    468     return test_generated_bubble_controller_;
    469   }
    470 
    471   const MockNewCreditCardBubbleController* mock_new_card_bubble_controller() {
    472     return mock_new_card_bubble_controller_.get();
    473   }
    474 
    475  private:
    476   void FinishedCallback(const FormStructure* form_structure,
    477                         const std::string& google_transaction_id) {
    478     form_structure_ = form_structure;
    479     if (controller()->GetDialogType() == DIALOG_TYPE_AUTOCHECKOUT)
    480       EXPECT_TRUE(controller()->AutocheckoutIsRunning());
    481   }
    482 
    483 #if defined(OS_WIN)
    484    // http://crbug.com/227221
    485    ui::ScopedOleInitializer ole_initializer_;
    486 #endif
    487 
    488   // The controller owns itself.
    489   base::WeakPtr<TestAutofillDialogController> controller_;
    490 
    491   // Must outlive the controller.
    492   AutofillMetrics metric_logger_;
    493 
    494   // Returned when the dialog closes successfully.
    495   const FormStructure* form_structure_;
    496 
    497   // Used to monitor if the Autofill credit card bubble is shown. Owned by
    498   // |web_contents()|.
    499   TestGeneratedCreditCardBubbleController* test_generated_bubble_controller_;
    500 
    501   // Used to record when new card bubbles would show. Created in |Reset()|.
    502   scoped_ptr<MockNewCreditCardBubbleController>
    503       mock_new_card_bubble_controller_;
    504 };
    505 
    506 }  // namespace
    507 
    508 // This test makes sure nothing falls over when fields are being validity-
    509 // checked.
    510 TEST_F(AutofillDialogControllerTest, ValidityCheck) {
    511   for (size_t i = SECTION_MIN; i <= SECTION_MAX; ++i) {
    512     DialogSection section = static_cast<DialogSection>(i);
    513     const DetailInputs& shipping_inputs =
    514         controller()->RequestedFieldsForSection(section);
    515     for (DetailInputs::const_iterator iter = shipping_inputs.begin();
    516          iter != shipping_inputs.end(); ++iter) {
    517       controller()->InputValidityMessage(section, iter->type, string16());
    518     }
    519   }
    520 }
    521 
    522 // Test for phone number validation.
    523 TEST_F(AutofillDialogControllerTest, PhoneNumberValidation) {
    524   // Construct DetailOutputMap from existing data.
    525   SwitchToAutofill();
    526 
    527   AutofillProfile full_profile(test::GetVerifiedProfile());
    528   controller()->GetTestingManager()->AddTestingProfile(&full_profile);
    529 
    530   for (size_t i = 0; i < 2; ++i) {
    531     ServerFieldType phone = i == 0 ? PHONE_HOME_WHOLE_NUMBER :
    532                                      PHONE_BILLING_WHOLE_NUMBER;
    533     ServerFieldType address = i == 0 ? ADDRESS_HOME_COUNTRY :
    534                                        ADDRESS_BILLING_COUNTRY;
    535     DialogSection section = i == 0 ? SECTION_SHIPPING : SECTION_BILLING;
    536 
    537     controller()->EditClickedForSection(section);
    538 
    539     DetailOutputMap outputs;
    540     const DetailInputs& inputs =
    541         controller()->RequestedFieldsForSection(section);
    542     // Make sure country is United States.
    543     SetOutputValue(inputs, &outputs, address, ASCIIToUTF16("United States"));
    544 
    545     // Existing data should have no errors.
    546     ValidityData validity_data =
    547         controller()->InputsAreValid(section, outputs, VALIDATE_FINAL);
    548     EXPECT_EQ(0U, validity_data.count(phone));
    549 
    550     // Input an empty phone number with VALIDATE_FINAL.
    551     SetOutputValue( inputs, &outputs, phone, base::string16());
    552     validity_data =
    553         controller()->InputsAreValid(section, outputs, VALIDATE_FINAL);
    554     EXPECT_EQ(1U, validity_data.count(phone));
    555 
    556     // Input an empty phone number with VALIDATE_EDIT.
    557     validity_data =
    558         controller()->InputsAreValid(section, outputs, VALIDATE_EDIT);
    559     EXPECT_EQ(0U, validity_data.count(phone));
    560 
    561     // Input an invalid phone number.
    562     SetOutputValue(inputs, &outputs, phone, ASCIIToUTF16("ABC"));
    563     validity_data =
    564         controller()->InputsAreValid(section, outputs, VALIDATE_EDIT);
    565     EXPECT_EQ(1U, validity_data.count(phone));
    566 
    567     // Input a local phone number.
    568     SetOutputValue(inputs, &outputs, phone, ASCIIToUTF16("2155546699"));
    569     validity_data =
    570         controller()->InputsAreValid(section, outputs, VALIDATE_EDIT);
    571     EXPECT_EQ(0U, validity_data.count(phone));
    572 
    573     // Input an invalid local phone number.
    574     SetOutputValue(inputs, &outputs, phone, ASCIIToUTF16("215554669"));
    575     validity_data =
    576         controller()->InputsAreValid(section, outputs, VALIDATE_EDIT);
    577     EXPECT_EQ(1U, validity_data.count(phone));
    578 
    579     // Input an international phone number.
    580     SetOutputValue(inputs, &outputs, phone, ASCIIToUTF16("+33 892 70 12 39"));
    581     validity_data =
    582         controller()->InputsAreValid(section, outputs, VALIDATE_EDIT);
    583     EXPECT_EQ(0U, validity_data.count(phone));
    584 
    585     // Input an invalid international phone number.
    586     SetOutputValue(inputs, &outputs, phone,
    587                    ASCIIToUTF16("+112333 892 70 12 39"));
    588     validity_data =
    589         controller()->InputsAreValid(section, outputs, VALIDATE_EDIT);
    590     EXPECT_EQ(1U, validity_data.count(phone));
    591   }
    592 }
    593 
    594 TEST_F(AutofillDialogControllerTest, ExpirationDateValidity) {
    595   DetailOutputMap outputs;
    596   const DetailInputs& inputs =
    597       controller()->RequestedFieldsForSection(SECTION_CC_BILLING);
    598 
    599   ui::ComboboxModel* exp_year_model =
    600       controller()->ComboboxModelForAutofillType(CREDIT_CARD_EXP_4_DIGIT_YEAR);
    601   ui::ComboboxModel* exp_month_model =
    602       controller()->ComboboxModelForAutofillType(CREDIT_CARD_EXP_MONTH);
    603 
    604   base::string16 default_year_value =
    605       exp_year_model->GetItemAt(exp_year_model->GetDefaultIndex());
    606 
    607   base::string16 other_year_value =
    608       exp_year_model->GetItemAt(exp_year_model->GetItemCount() - 1);
    609   base::string16 other_month_value =
    610       exp_month_model->GetItemAt(exp_month_model->GetItemCount() - 1);
    611 
    612   SetOutputValue(inputs, &outputs, CREDIT_CARD_EXP_4_DIGIT_YEAR,
    613                  default_year_value);
    614 
    615   // Expiration default values "validate" with VALIDATE_EDIT.
    616   ValidityData validity_data =
    617       controller()->InputsAreValid(SECTION_CC_BILLING, outputs, VALIDATE_EDIT);
    618   EXPECT_EQ(0U, validity_data.count(CREDIT_CARD_EXP_4_DIGIT_YEAR));
    619   EXPECT_EQ(0U, validity_data.count(CREDIT_CARD_EXP_MONTH));
    620 
    621   // Expiration date with default month "validates" with VALIDATE_EDIT.
    622   SetOutputValue(inputs, &outputs, CREDIT_CARD_EXP_4_DIGIT_YEAR,
    623                  other_year_value);
    624 
    625   validity_data =
    626       controller()->InputsAreValid(SECTION_CC_BILLING, outputs, VALIDATE_EDIT);
    627   EXPECT_EQ(0U, validity_data.count(CREDIT_CARD_EXP_4_DIGIT_YEAR));
    628   EXPECT_EQ(0U, validity_data.count(CREDIT_CARD_EXP_MONTH));
    629 
    630   // Expiration date with default year "validates" with VALIDATE_EDIT.
    631   SetOutputValue(inputs, &outputs, CREDIT_CARD_EXP_MONTH, other_month_value);
    632 
    633   validity_data =
    634       controller()->InputsAreValid(SECTION_CC_BILLING, outputs, VALIDATE_EDIT);
    635   EXPECT_EQ(0U, validity_data.count(CREDIT_CARD_EXP_4_DIGIT_YEAR));
    636   EXPECT_EQ(0U, validity_data.count(CREDIT_CARD_EXP_MONTH));
    637 
    638   // Expiration default values fail with VALIDATE_FINAL.
    639   SetOutputValue(inputs, &outputs, CREDIT_CARD_EXP_4_DIGIT_YEAR,
    640                  default_year_value);
    641 
    642   validity_data =
    643       controller()->InputsAreValid(SECTION_CC_BILLING, outputs, VALIDATE_FINAL);
    644   EXPECT_EQ(1U, validity_data.count(CREDIT_CARD_EXP_4_DIGIT_YEAR));
    645   EXPECT_EQ(1U, validity_data.count(CREDIT_CARD_EXP_MONTH));
    646 
    647   // Expiration date with default month fails with VALIDATE_FINAL.
    648   SetOutputValue(inputs,
    649                  &outputs,
    650                  CREDIT_CARD_EXP_4_DIGIT_YEAR,
    651                  other_year_value);
    652 
    653   validity_data =
    654       controller()->InputsAreValid(SECTION_CC_BILLING, outputs, VALIDATE_FINAL);
    655   EXPECT_EQ(0U, validity_data.count(CREDIT_CARD_EXP_4_DIGIT_YEAR));
    656   EXPECT_EQ(1U, validity_data.count(CREDIT_CARD_EXP_MONTH));
    657 
    658   // Expiration date with default year fails with VALIDATE_FINAL.
    659   SetOutputValue(inputs, &outputs, CREDIT_CARD_EXP_MONTH, other_month_value);
    660 
    661   validity_data =
    662       controller()->InputsAreValid(SECTION_CC_BILLING, outputs, VALIDATE_FINAL);
    663   EXPECT_EQ(1U, validity_data.count(CREDIT_CARD_EXP_4_DIGIT_YEAR));
    664   EXPECT_EQ(0U, validity_data.count(CREDIT_CARD_EXP_MONTH));
    665 }
    666 
    667 TEST_F(AutofillDialogControllerTest, BillingNameValidation) {
    668   // Construct DetailOutputMap from AutofillProfile data.
    669   SwitchToAutofill();
    670 
    671   DetailOutputMap outputs;
    672   const DetailInputs& inputs =
    673       controller()->RequestedFieldsForSection(SECTION_BILLING);
    674 
    675   // Input an empty billing name with VALIDATE_FINAL.
    676   SetOutputValue(inputs, &outputs, NAME_BILLING_FULL, base::string16());
    677   ValidityData validity_data =
    678       controller()->InputsAreValid(SECTION_BILLING, outputs, VALIDATE_FINAL);
    679   EXPECT_EQ(1U, validity_data.count(NAME_BILLING_FULL));
    680 
    681   // Input an empty billing name with VALIDATE_EDIT.
    682   validity_data =
    683       controller()->InputsAreValid(SECTION_BILLING, outputs, VALIDATE_EDIT);
    684   EXPECT_EQ(0U, validity_data.count(NAME_BILLING_FULL));
    685 
    686   // Input a non-empty billing name.
    687   SetOutputValue(inputs, &outputs, NAME_BILLING_FULL, ASCIIToUTF16("Bob"));
    688   validity_data =
    689       controller()->InputsAreValid(SECTION_BILLING, outputs, VALIDATE_FINAL);
    690   EXPECT_EQ(0U, validity_data.count(NAME_BILLING_FULL));
    691 
    692   // Switch to Wallet which only considers names with with at least two names to
    693   // be valid.
    694   SwitchToWallet();
    695 
    696   // Setup some wallet state.
    697   scoped_ptr<wallet::WalletItems> wallet_items = wallet::GetTestWalletItems();
    698   controller()->OnDidGetWalletItems(wallet_items.Pass());
    699 
    700   DetailOutputMap wallet_outputs;
    701   const DetailInputs& wallet_inputs =
    702       controller()->RequestedFieldsForSection(SECTION_CC_BILLING);
    703 
    704   // Input an empty billing name with VALIDATE_FINAL. Data source should not
    705   // change this behavior.
    706   SetOutputValue(wallet_inputs, &wallet_outputs, NAME_BILLING_FULL,
    707                  base::string16());
    708   validity_data =
    709       controller()->InputsAreValid(
    710           SECTION_CC_BILLING, wallet_outputs, VALIDATE_FINAL);
    711   EXPECT_EQ(1U, validity_data.count(NAME_BILLING_FULL));
    712 
    713   // Input an empty billing name with VALIDATE_EDIT. Data source should not
    714   // change this behavior.
    715   validity_data =
    716       controller()->InputsAreValid(
    717           SECTION_CC_BILLING, wallet_outputs, VALIDATE_EDIT);
    718   EXPECT_EQ(0U, validity_data.count(NAME_BILLING_FULL));
    719 
    720   // Input a one name billing name. Wallet does not currently support this.
    721   SetOutputValue(wallet_inputs, &wallet_outputs, NAME_BILLING_FULL,
    722                  ASCIIToUTF16("Bob"));
    723   validity_data =
    724       controller()->InputsAreValid(
    725           SECTION_CC_BILLING, wallet_outputs, VALIDATE_FINAL);
    726   EXPECT_EQ(1U, validity_data.count(NAME_BILLING_FULL));
    727 
    728   // Input a two name billing name.
    729   SetOutputValue(wallet_inputs, &wallet_outputs, NAME_BILLING_FULL,
    730                  ASCIIToUTF16("Bob Barker"));
    731   validity_data =
    732       controller()->InputsAreValid(
    733           SECTION_CC_BILLING, wallet_outputs, VALIDATE_FINAL);
    734   EXPECT_EQ(0U, validity_data.count(NAME_BILLING_FULL));
    735 
    736   // Input a more than two name billing name.
    737   SetOutputValue(wallet_inputs, &wallet_outputs, NAME_BILLING_FULL,
    738                  ASCIIToUTF16("John Jacob Jingleheimer Schmidt"));
    739   validity_data =
    740       controller()->InputsAreValid(
    741           SECTION_CC_BILLING, wallet_outputs, VALIDATE_FINAL);
    742   EXPECT_EQ(0U, validity_data.count(NAME_BILLING_FULL));
    743 
    744   // Input a billing name with lots of crazy whitespace.
    745   SetOutputValue(
    746       wallet_inputs, &wallet_outputs, NAME_BILLING_FULL,
    747       ASCIIToUTF16("     \\n\\r John \\n  Jacob Jingleheimer \\t Schmidt  "));
    748   validity_data =
    749       controller()->InputsAreValid(
    750           SECTION_CC_BILLING, wallet_outputs, VALIDATE_FINAL);
    751   EXPECT_EQ(0U, validity_data.count(NAME_BILLING_FULL));
    752 }
    753 
    754 TEST_F(AutofillDialogControllerTest, CreditCardNumberValidation) {
    755   // Construct DetailOutputMap from AutofillProfile data.
    756   SwitchToAutofill();
    757 
    758   // Should accept AMEX, Visa, Master and Discover.
    759   ValidateCCNumber(SECTION_CC, kTestCCNumberVisa, true);
    760   ValidateCCNumber(SECTION_CC, kTestCCNumberMaster, true);
    761   ValidateCCNumber(SECTION_CC, kTestCCNumberDiscover, true);
    762   ValidateCCNumber(SECTION_CC, kTestCCNumberAmex, true);
    763 
    764   ValidateCCNumber(SECTION_CC, kTestCCNumberIncomplete, false);
    765   ValidateCCNumber(SECTION_CC, kTestCCNumberInvalid, false);
    766 
    767   // Switch to Wallet which will not accept AMEX.
    768   SwitchToWallet();
    769 
    770   // Setup some wallet state.
    771   controller()->OnDidGetWalletItems(wallet::GetTestWalletItems());
    772 
    773   // Should accept Visa, Master and Discover, but not AMEX.
    774   ValidateCCNumber(SECTION_CC_BILLING, kTestCCNumberVisa, true);
    775   ValidateCCNumber(SECTION_CC_BILLING, kTestCCNumberMaster, true);
    776   ValidateCCNumber(SECTION_CC_BILLING, kTestCCNumberDiscover, true);
    777 
    778   ValidateCCNumber(SECTION_CC_BILLING, kTestCCNumberAmex, false);
    779   ValidateCCNumber(SECTION_CC_BILLING, kTestCCNumberIncomplete, false);
    780   ValidateCCNumber(SECTION_CC_BILLING, kTestCCNumberInvalid, false);
    781 }
    782 
    783 TEST_F(AutofillDialogControllerTest, AutofillProfiles) {
    784   ui::MenuModel* shipping_model =
    785       controller()->MenuModelForSection(SECTION_SHIPPING);
    786   // Since the PersonalDataManager is empty, this should only have the
    787   // "use billing", "add new" and "manage" menu items.
    788   ASSERT_TRUE(shipping_model);
    789   EXPECT_EQ(3, shipping_model->GetItemCount());
    790   // On the other hand, the other models should be NULL when there's no
    791   // suggestion.
    792   EXPECT_FALSE(controller()->MenuModelForSection(SECTION_CC));
    793   EXPECT_FALSE(controller()->MenuModelForSection(SECTION_BILLING));
    794   EXPECT_FALSE(controller()->MenuModelForSection(SECTION_EMAIL));
    795 
    796   EXPECT_CALL(*controller()->GetView(), ModelChanged()).Times(3);
    797 
    798   // Empty profiles are ignored.
    799   AutofillProfile empty_profile(base::GenerateGUID(), kSettingsOrigin);
    800   empty_profile.SetRawInfo(NAME_FULL, ASCIIToUTF16("John Doe"));
    801   controller()->GetTestingManager()->AddTestingProfile(&empty_profile);
    802   shipping_model = controller()->MenuModelForSection(SECTION_SHIPPING);
    803   ASSERT_TRUE(shipping_model);
    804   EXPECT_EQ(3, shipping_model->GetItemCount());
    805   EXPECT_FALSE(controller()->MenuModelForSection(SECTION_EMAIL));
    806 
    807   // An otherwise full but unverified profile should be ignored.
    808   AutofillProfile full_profile(test::GetFullProfile());
    809   full_profile.set_origin("https://www.example.com");
    810   full_profile.SetRawInfo(ADDRESS_HOME_LINE2, string16());
    811   controller()->GetTestingManager()->AddTestingProfile(&full_profile);
    812   shipping_model = controller()->MenuModelForSection(SECTION_SHIPPING);
    813   ASSERT_TRUE(shipping_model);
    814   EXPECT_EQ(3, shipping_model->GetItemCount());
    815   EXPECT_FALSE(controller()->MenuModelForSection(SECTION_EMAIL));
    816 
    817   // A full, verified profile should be picked up.
    818   AutofillProfile verified_profile(test::GetVerifiedProfile());
    819   verified_profile.SetRawInfo(ADDRESS_HOME_LINE2, string16());
    820   controller()->GetTestingManager()->AddTestingProfile(&verified_profile);
    821   shipping_model = controller()->MenuModelForSection(SECTION_SHIPPING);
    822   ASSERT_TRUE(shipping_model);
    823   EXPECT_EQ(4, shipping_model->GetItemCount());
    824   EXPECT_TRUE(!!controller()->MenuModelForSection(SECTION_EMAIL));
    825 }
    826 
    827 // Makes sure that the choice of which Autofill profile to use for each section
    828 // is sticky.
    829 TEST_F(AutofillDialogControllerTest, AutofillProfileDefaults) {
    830   AutofillProfile full_profile(test::GetFullProfile());
    831   full_profile.set_origin(kSettingsOrigin);
    832   controller()->GetTestingManager()->AddTestingProfile(&full_profile);
    833   AutofillProfile full_profile2(test::GetFullProfile2());
    834   full_profile2.set_origin(kSettingsOrigin);
    835   controller()->GetTestingManager()->AddTestingProfile(&full_profile2);
    836 
    837   // Until a selection has been made, the default shipping suggestion is the
    838   // first one (after "use billing").
    839   SuggestionsMenuModel* shipping_model = static_cast<SuggestionsMenuModel*>(
    840       controller()->MenuModelForSection(SECTION_SHIPPING));
    841   EXPECT_EQ(1, shipping_model->checked_item());
    842 
    843   for (int i = 2; i >= 0; --i) {
    844     shipping_model = static_cast<SuggestionsMenuModel*>(
    845         controller()->MenuModelForSection(SECTION_SHIPPING));
    846     shipping_model->ExecuteCommand(i, 0);
    847     FillCreditCardInputs();
    848     controller()->OnAccept();
    849 
    850     Reset();
    851     controller()->GetTestingManager()->AddTestingProfile(&full_profile);
    852     controller()->GetTestingManager()->AddTestingProfile(&full_profile2);
    853     shipping_model = static_cast<SuggestionsMenuModel*>(
    854         controller()->MenuModelForSection(SECTION_SHIPPING));
    855     EXPECT_EQ(i, shipping_model->checked_item());
    856   }
    857 
    858   // Try again, but don't add the default profile to the PDM. The dialog
    859   // should fall back to the first profile.
    860   shipping_model->ExecuteCommand(2, 0);
    861   FillCreditCardInputs();
    862   controller()->OnAccept();
    863   Reset();
    864   controller()->GetTestingManager()->AddTestingProfile(&full_profile);
    865   shipping_model = static_cast<SuggestionsMenuModel*>(
    866       controller()->MenuModelForSection(SECTION_SHIPPING));
    867   EXPECT_EQ(1, shipping_model->checked_item());
    868 }
    869 
    870 TEST_F(AutofillDialogControllerTest, AutofillProfileVariants) {
    871   EXPECT_CALL(*controller()->GetView(), ModelChanged()).Times(1);
    872   ui::MenuModel* email_model =
    873       controller()->MenuModelForSection(SECTION_EMAIL);
    874   EXPECT_FALSE(email_model);
    875 
    876   // Set up some variant data.
    877   AutofillProfile full_profile(test::GetVerifiedProfile());
    878   std::vector<string16> names;
    879   names.push_back(ASCIIToUTF16("John Doe"));
    880   names.push_back(ASCIIToUTF16("Jane Doe"));
    881   full_profile.SetRawMultiInfo(EMAIL_ADDRESS, names);
    882   const string16 kEmail1 = ASCIIToUTF16(kFakeEmail);
    883   const string16 kEmail2 = ASCIIToUTF16("admin (at) example.com");
    884   std::vector<string16> emails;
    885   emails.push_back(kEmail1);
    886   emails.push_back(kEmail2);
    887   full_profile.SetRawMultiInfo(EMAIL_ADDRESS, emails);
    888 
    889   // Respect variants for the email address field only.
    890   controller()->GetTestingManager()->AddTestingProfile(&full_profile);
    891   ui::MenuModel* shipping_model =
    892       controller()->MenuModelForSection(SECTION_SHIPPING);
    893   EXPECT_EQ(4, shipping_model->GetItemCount());
    894   email_model = controller()->MenuModelForSection(SECTION_EMAIL);
    895   ASSERT_TRUE(!!email_model);
    896   EXPECT_EQ(4, email_model->GetItemCount());
    897 
    898   // The first one is the default.
    899   SuggestionsMenuModel* email_suggestions = static_cast<SuggestionsMenuModel*>(
    900       controller()->MenuModelForSection(SECTION_EMAIL));
    901   EXPECT_EQ(0, email_suggestions->checked_item());
    902 
    903   email_model->ActivatedAt(0);
    904   EXPECT_EQ(kEmail1,
    905             controller()->SuggestionStateForSection(SECTION_EMAIL).
    906                 vertically_compact_text);
    907   email_model->ActivatedAt(1);
    908   EXPECT_EQ(kEmail2,
    909             controller()->SuggestionStateForSection(SECTION_EMAIL).
    910                 vertically_compact_text);
    911 
    912   controller()->EditClickedForSection(SECTION_EMAIL);
    913   const DetailInputs& inputs =
    914       controller()->RequestedFieldsForSection(SECTION_EMAIL);
    915   EXPECT_EQ(kEmail2, inputs[0].initial_value);
    916 
    917   // The choice of variant is persisted across runs of the dialog.
    918   email_model->ActivatedAt(0);
    919   email_model->ActivatedAt(1);
    920   FillCreditCardInputs();
    921   controller()->OnAccept();
    922 
    923   Reset();
    924   controller()->GetTestingManager()->AddTestingProfile(&full_profile);
    925   email_suggestions = static_cast<SuggestionsMenuModel*>(
    926       controller()->MenuModelForSection(SECTION_EMAIL));
    927   EXPECT_EQ(1, email_suggestions->checked_item());
    928 }
    929 
    930 TEST_F(AutofillDialogControllerTest, SuggestValidEmail) {
    931   AutofillProfile profile(test::GetVerifiedProfile());
    932   const string16 kValidEmail = ASCIIToUTF16(kFakeEmail);
    933   profile.SetRawInfo(EMAIL_ADDRESS, kValidEmail);
    934   controller()->GetTestingManager()->AddTestingProfile(&profile);
    935 
    936   controller()->MenuModelForSection(SECTION_EMAIL)->ActivatedAt(0);
    937   EXPECT_EQ(kValidEmail,
    938             controller()->SuggestionStateForSection(SECTION_EMAIL).
    939                 vertically_compact_text);
    940 }
    941 
    942 TEST_F(AutofillDialogControllerTest, DoNotSuggestInvalidEmail) {
    943   AutofillProfile profile(test::GetVerifiedProfile());
    944   profile.SetRawInfo(EMAIL_ADDRESS, ASCIIToUTF16(".!#$%&'*+/=?^_`- (at) -.."));
    945   controller()->GetTestingManager()->AddTestingProfile(&profile);
    946   EXPECT_EQ(static_cast<ui::MenuModel*>(NULL),
    947             controller()->MenuModelForSection(SECTION_EMAIL));
    948 }
    949 
    950 TEST_F(AutofillDialogControllerTest, DoNotSuggestEmailFromIncompleteProfile) {
    951   AutofillProfile profile(test::GetVerifiedProfile());
    952   profile.SetRawInfo(EMAIL_ADDRESS, ASCIIToUTF16(kFakeEmail));
    953   profile.SetRawInfo(ADDRESS_HOME_STATE, base::string16());
    954   controller()->GetTestingManager()->AddTestingProfile(&profile);
    955   EXPECT_EQ(static_cast<ui::MenuModel*>(NULL),
    956             controller()->MenuModelForSection(SECTION_EMAIL));
    957 }
    958 
    959 TEST_F(AutofillDialogControllerTest, DoNotSuggestEmailFromInvalidProfile) {
    960   AutofillProfile profile(test::GetVerifiedProfile());
    961   profile.SetRawInfo(EMAIL_ADDRESS, ASCIIToUTF16(kFakeEmail));
    962   profile.SetRawInfo(ADDRESS_HOME_STATE, ASCIIToUTF16("C"));
    963   controller()->GetTestingManager()->AddTestingProfile(&profile);
    964   EXPECT_EQ(static_cast<ui::MenuModel*>(NULL),
    965             controller()->MenuModelForSection(SECTION_EMAIL));
    966 }
    967 
    968 TEST_F(AutofillDialogControllerTest, SuggestValidAddress) {
    969   AutofillProfile full_profile(test::GetVerifiedProfile());
    970   full_profile.set_origin(kSettingsOrigin);
    971   controller()->GetTestingManager()->AddTestingProfile(&full_profile);
    972   EXPECT_EQ(
    973       4, controller()->MenuModelForSection(SECTION_SHIPPING)->GetItemCount());
    974 }
    975 
    976 TEST_F(AutofillDialogControllerTest, DoNotSuggestInvalidAddress) {
    977   AutofillProfile full_profile(test::GetVerifiedProfile());
    978   full_profile.set_origin(kSettingsOrigin);
    979   full_profile.SetRawInfo(ADDRESS_HOME_STATE, ASCIIToUTF16("C"));
    980   controller()->GetTestingManager()->AddTestingProfile(&full_profile);
    981   EXPECT_EQ(
    982       3, controller()->MenuModelForSection(SECTION_SHIPPING)->GetItemCount());
    983 }
    984 
    985 TEST_F(AutofillDialogControllerTest, AutofillCreditCards) {
    986   // Since the PersonalDataManager is empty, this should only have the
    987   // default menu items.
    988   EXPECT_FALSE(controller()->MenuModelForSection(SECTION_CC));
    989 
    990   EXPECT_CALL(*controller()->GetView(), ModelChanged()).Times(3);
    991 
    992   // Empty cards are ignored.
    993   CreditCard empty_card(base::GenerateGUID(), kSettingsOrigin);
    994   empty_card.SetRawInfo(CREDIT_CARD_NAME, ASCIIToUTF16("John Doe"));
    995   controller()->GetTestingManager()->AddTestingCreditCard(&empty_card);
    996   EXPECT_FALSE(controller()->MenuModelForSection(SECTION_CC));
    997 
    998   // An otherwise full but unverified card should be ignored.
    999   CreditCard full_card(test::GetCreditCard());
   1000   full_card.set_origin("https://www.example.com");
   1001   controller()->GetTestingManager()->AddTestingCreditCard(&full_card);
   1002   EXPECT_FALSE(controller()->MenuModelForSection(SECTION_CC));
   1003 
   1004   // A full, verified card should be picked up.
   1005   CreditCard verified_card(test::GetCreditCard());
   1006   verified_card.set_origin(kSettingsOrigin);
   1007   controller()->GetTestingManager()->AddTestingCreditCard(&verified_card);
   1008   ui::MenuModel* credit_card_model =
   1009       controller()->MenuModelForSection(SECTION_CC);
   1010   ASSERT_TRUE(credit_card_model);
   1011   EXPECT_EQ(3, credit_card_model->GetItemCount());
   1012 }
   1013 
   1014 // Test selecting a shipping address different from billing as address.
   1015 TEST_F(AutofillDialogControllerTest, DontUseBillingAsShipping) {
   1016   AutofillProfile full_profile(test::GetVerifiedProfile());
   1017   AutofillProfile full_profile2(test::GetVerifiedProfile2());
   1018   CreditCard credit_card(test::GetVerifiedCreditCard());
   1019   controller()->GetTestingManager()->AddTestingProfile(&full_profile);
   1020   controller()->GetTestingManager()->AddTestingProfile(&full_profile2);
   1021   controller()->GetTestingManager()->AddTestingCreditCard(&credit_card);
   1022   ui::MenuModel* shipping_model =
   1023       controller()->MenuModelForSection(SECTION_SHIPPING);
   1024   shipping_model->ActivatedAt(2);
   1025 
   1026   controller()->OnAccept();
   1027   ASSERT_EQ(20U, form_structure()->field_count());
   1028   EXPECT_EQ(ADDRESS_HOME_STATE,
   1029             form_structure()->field(9)->Type().GetStorableType());
   1030   EXPECT_EQ(ADDRESS_BILLING, form_structure()->field(9)->Type().group());
   1031   EXPECT_EQ(ADDRESS_HOME_STATE,
   1032             form_structure()->field(16)->Type().GetStorableType());
   1033   EXPECT_EQ(ADDRESS_HOME, form_structure()->field(16)->Type().group());
   1034   string16 billing_state = form_structure()->field(9)->value;
   1035   string16 shipping_state = form_structure()->field(16)->value;
   1036   EXPECT_FALSE(billing_state.empty());
   1037   EXPECT_FALSE(shipping_state.empty());
   1038   EXPECT_NE(billing_state, shipping_state);
   1039 
   1040   EXPECT_EQ(CREDIT_CARD_NAME,
   1041             form_structure()->field(1)->Type().GetStorableType());
   1042   string16 cc_name = form_structure()->field(1)->value;
   1043   EXPECT_EQ(NAME_FULL, form_structure()->field(6)->Type().GetStorableType());
   1044   EXPECT_EQ(NAME_BILLING, form_structure()->field(6)->Type().group());
   1045   string16 billing_name = form_structure()->field(6)->value;
   1046   EXPECT_EQ(NAME_FULL, form_structure()->field(13)->Type().GetStorableType());
   1047   EXPECT_EQ(NAME, form_structure()->field(13)->Type().group());
   1048   string16 shipping_name = form_structure()->field(13)->value;
   1049 
   1050   EXPECT_FALSE(cc_name.empty());
   1051   EXPECT_FALSE(billing_name.empty());
   1052   EXPECT_FALSE(shipping_name.empty());
   1053   // Billing name should always be the same as cardholder name.
   1054   EXPECT_EQ(cc_name, billing_name);
   1055   EXPECT_NE(cc_name, shipping_name);
   1056 }
   1057 
   1058 // Test selecting UseBillingForShipping.
   1059 TEST_F(AutofillDialogControllerTest, UseBillingAsShipping) {
   1060   AutofillProfile full_profile(test::GetVerifiedProfile());
   1061   AutofillProfile full_profile2(test::GetVerifiedProfile2());
   1062   CreditCard credit_card(test::GetVerifiedCreditCard());
   1063   controller()->GetTestingManager()->AddTestingProfile(&full_profile);
   1064   controller()->GetTestingManager()->AddTestingProfile(&full_profile2);
   1065   controller()->GetTestingManager()->AddTestingCreditCard(&credit_card);
   1066 
   1067   // Test after setting use billing for shipping.
   1068   UseBillingForShipping();
   1069 
   1070   controller()->OnAccept();
   1071   ASSERT_EQ(20U, form_structure()->field_count());
   1072   EXPECT_EQ(ADDRESS_HOME_STATE,
   1073             form_structure()->field(9)->Type().GetStorableType());
   1074   EXPECT_EQ(ADDRESS_BILLING, form_structure()->field(9)->Type().group());
   1075   EXPECT_EQ(ADDRESS_HOME_STATE,
   1076             form_structure()->field(16)->Type().GetStorableType());
   1077   EXPECT_EQ(ADDRESS_HOME, form_structure()->field(16)->Type().group());
   1078   string16 billing_state = form_structure()->field(9)->value;
   1079   string16 shipping_state = form_structure()->field(16)->value;
   1080   EXPECT_FALSE(billing_state.empty());
   1081   EXPECT_FALSE(shipping_state.empty());
   1082   EXPECT_EQ(billing_state, shipping_state);
   1083 
   1084   EXPECT_EQ(CREDIT_CARD_NAME,
   1085             form_structure()->field(1)->Type().GetStorableType());
   1086   string16 cc_name = form_structure()->field(1)->value;
   1087   EXPECT_EQ(NAME_FULL, form_structure()->field(6)->Type().GetStorableType());
   1088   EXPECT_EQ(NAME_BILLING, form_structure()->field(6)->Type().group());
   1089   string16 billing_name = form_structure()->field(6)->value;
   1090   EXPECT_EQ(NAME_FULL, form_structure()->field(13)->Type().GetStorableType());
   1091   EXPECT_EQ(NAME, form_structure()->field(13)->Type().group());
   1092   string16 shipping_name = form_structure()->field(13)->value;
   1093 
   1094   EXPECT_FALSE(cc_name.empty());
   1095   EXPECT_FALSE(billing_name.empty());
   1096   EXPECT_FALSE(shipping_name.empty());
   1097   EXPECT_EQ(cc_name, billing_name);
   1098   EXPECT_EQ(cc_name, shipping_name);
   1099 }
   1100 
   1101 // Tests that shipping and billing telephone fields are supported, and filled
   1102 // in by their respective profiles. http://crbug.com/244515
   1103 TEST_F(AutofillDialogControllerTest, BillingVsShippingPhoneNumber) {
   1104   FormFieldData shipping_tel;
   1105   shipping_tel.autocomplete_attribute = "shipping tel";
   1106   FormFieldData billing_tel;
   1107   billing_tel.autocomplete_attribute = "billing tel";
   1108 
   1109   FormData form_data;
   1110   form_data.fields.push_back(shipping_tel);
   1111   form_data.fields.push_back(billing_tel);
   1112   SetUpControllerWithFormData(form_data);
   1113 
   1114   // The profile that will be chosen for the shipping section.
   1115   AutofillProfile shipping_profile(test::GetVerifiedProfile());
   1116   // The profile that will be chosen for the billing section.
   1117   AutofillProfile billing_profile(test::GetVerifiedProfile2());
   1118   CreditCard credit_card(test::GetVerifiedCreditCard());
   1119   controller()->GetTestingManager()->AddTestingProfile(&shipping_profile);
   1120   controller()->GetTestingManager()->AddTestingProfile(&billing_profile);
   1121   controller()->GetTestingManager()->AddTestingCreditCard(&credit_card);
   1122   ui::MenuModel* billing_model =
   1123       controller()->MenuModelForSection(SECTION_BILLING);
   1124   billing_model->ActivatedAt(1);
   1125 
   1126   controller()->OnAccept();
   1127   ASSERT_EQ(2U, form_structure()->field_count());
   1128   EXPECT_EQ(PHONE_HOME_WHOLE_NUMBER,
   1129             form_structure()->field(0)->Type().GetStorableType());
   1130   EXPECT_EQ(PHONE_HOME, form_structure()->field(0)->Type().group());
   1131   EXPECT_EQ(PHONE_HOME_WHOLE_NUMBER,
   1132             form_structure()->field(1)->Type().GetStorableType());
   1133   EXPECT_EQ(PHONE_BILLING, form_structure()->field(1)->Type().group());
   1134   EXPECT_EQ(shipping_profile.GetRawInfo(PHONE_HOME_WHOLE_NUMBER),
   1135             form_structure()->field(0)->value);
   1136   EXPECT_EQ(billing_profile.GetRawInfo(PHONE_BILLING_WHOLE_NUMBER),
   1137             form_structure()->field(1)->value);
   1138   EXPECT_NE(form_structure()->field(1)->value,
   1139             form_structure()->field(0)->value);
   1140 }
   1141 
   1142 TEST_F(AutofillDialogControllerTest, AcceptLegalDocuments) {
   1143   EXPECT_CALL(*controller()->GetTestingWalletClient(),
   1144               AcceptLegalDocuments(_, _, _)).Times(1);
   1145   EXPECT_CALL(*controller()->GetTestingWalletClient(),
   1146               GetFullWallet(_)).Times(1);
   1147   EXPECT_CALL(*controller(), LoadRiskFingerprintData()).Times(1);
   1148 
   1149   scoped_ptr<wallet::WalletItems> wallet_items = CompleteAndValidWalletItems();
   1150   wallet_items->AddLegalDocument(wallet::GetTestLegalDocument());
   1151   controller()->OnDidGetWalletItems(wallet_items.Pass());
   1152   controller()->OnAccept();
   1153   controller()->OnDidAcceptLegalDocuments();
   1154   controller()->OnDidLoadRiskFingerprintData(GetFakeFingerprint().Pass());
   1155 }
   1156 
   1157 // Makes sure the default object IDs are respected.
   1158 TEST_F(AutofillDialogControllerTest, WalletDefaultItems) {
   1159   scoped_ptr<wallet::WalletItems> wallet_items = wallet::GetTestWalletItems();
   1160   wallet_items->AddInstrument(wallet::GetTestNonDefaultMaskedInstrument());
   1161   wallet_items->AddInstrument(wallet::GetTestNonDefaultMaskedInstrument());
   1162   wallet_items->AddInstrument(wallet::GetTestMaskedInstrument());
   1163   wallet_items->AddInstrument(wallet::GetTestNonDefaultMaskedInstrument());
   1164 
   1165   wallet_items->AddAddress(wallet::GetTestNonDefaultShippingAddress());
   1166   wallet_items->AddAddress(wallet::GetTestNonDefaultShippingAddress());
   1167   wallet_items->AddAddress(wallet::GetTestNonDefaultShippingAddress());
   1168   wallet_items->AddAddress(wallet::GetTestShippingAddress());
   1169   wallet_items->AddAddress(wallet::GetTestNonDefaultShippingAddress());
   1170 
   1171   controller()->OnDidGetWalletItems(wallet_items.Pass());
   1172   // "add", "manage", and 4 suggestions.
   1173   EXPECT_EQ(6,
   1174       controller()->MenuModelForSection(SECTION_CC_BILLING)->GetItemCount());
   1175   EXPECT_TRUE(controller()->MenuModelForSection(SECTION_CC_BILLING)->
   1176       IsItemCheckedAt(2));
   1177   ASSERT_FALSE(controller()->IsEditingExistingData(SECTION_CC_BILLING));
   1178   // "use billing", "add", "manage", and 5 suggestions.
   1179   EXPECT_EQ(8,
   1180       controller()->MenuModelForSection(SECTION_SHIPPING)->GetItemCount());
   1181   EXPECT_TRUE(controller()->MenuModelForSection(SECTION_SHIPPING)->
   1182       IsItemCheckedAt(4));
   1183   ASSERT_FALSE(controller()->IsEditingExistingData(SECTION_SHIPPING));
   1184 }
   1185 
   1186 // Tests that invalid and AMEX default instruments are ignored.
   1187 TEST_F(AutofillDialogControllerTest, SelectInstrument) {
   1188   scoped_ptr<wallet::WalletItems> wallet_items = wallet::GetTestWalletItems();
   1189   // Tests if default instrument is invalid, then, the first valid instrument is
   1190   // selected instead of the default instrument.
   1191   wallet_items->AddInstrument(wallet::GetTestNonDefaultMaskedInstrument());
   1192   wallet_items->AddInstrument(wallet::GetTestNonDefaultMaskedInstrument());
   1193   wallet_items->AddInstrument(wallet::GetTestMaskedInstrumentInvalid());
   1194   wallet_items->AddInstrument(wallet::GetTestNonDefaultMaskedInstrument());
   1195 
   1196   controller()->OnDidGetWalletItems(wallet_items.Pass());
   1197   // 4 suggestions and "add", "manage".
   1198   EXPECT_EQ(6,
   1199       controller()->MenuModelForSection(SECTION_CC_BILLING)->GetItemCount());
   1200   EXPECT_TRUE(controller()->MenuModelForSection(SECTION_CC_BILLING)->
   1201       IsItemCheckedAt(0));
   1202 
   1203   // Tests if default instrument is AMEX, then, the first valid instrument is
   1204   // selected instead of the default instrument.
   1205   wallet_items = wallet::GetTestWalletItems();
   1206   wallet_items->AddInstrument(wallet::GetTestNonDefaultMaskedInstrument());
   1207   wallet_items->AddInstrument(wallet::GetTestNonDefaultMaskedInstrument());
   1208   wallet_items->AddInstrument(wallet::GetTestMaskedInstrumentAmex());
   1209   wallet_items->AddInstrument(wallet::GetTestNonDefaultMaskedInstrument());
   1210 
   1211   controller()->OnDidGetWalletItems(wallet_items.Pass());
   1212   // 4 suggestions and "add", "manage".
   1213   EXPECT_EQ(6,
   1214       controller()->MenuModelForSection(SECTION_CC_BILLING)->GetItemCount());
   1215   EXPECT_TRUE(controller()->MenuModelForSection(SECTION_CC_BILLING)->
   1216       IsItemCheckedAt(0));
   1217 
   1218   // Tests if only have AMEX and invalid instrument, then "add" is selected.
   1219   wallet_items = wallet::GetTestWalletItems();
   1220   wallet_items->AddInstrument(wallet::GetTestMaskedInstrumentInvalid());
   1221   wallet_items->AddInstrument(wallet::GetTestMaskedInstrumentAmex());
   1222 
   1223   controller()->OnDidGetWalletItems(wallet_items.Pass());
   1224   // 2 suggestions and "add", "manage".
   1225   EXPECT_EQ(4,
   1226       controller()->MenuModelForSection(SECTION_CC_BILLING)->GetItemCount());
   1227   // "add"
   1228   EXPECT_TRUE(controller()->MenuModelForSection(SECTION_CC_BILLING)->
   1229       IsItemCheckedAt(2));
   1230 }
   1231 
   1232 TEST_F(AutofillDialogControllerTest, SaveAddress) {
   1233   EXPECT_CALL(*controller()->GetView(), ModelChanged()).Times(1);
   1234   EXPECT_CALL(*controller()->GetTestingWalletClient(),
   1235               SaveToWalletMock(testing::IsNull(),
   1236                                testing::NotNull(),
   1237                                _)).Times(1);
   1238 
   1239   scoped_ptr<wallet::WalletItems> wallet_items = wallet::GetTestWalletItems();
   1240   wallet_items->AddInstrument(wallet::GetTestMaskedInstrument());
   1241   controller()->OnDidGetWalletItems(wallet_items.Pass());
   1242   // If there is no shipping address in wallet, it will default to
   1243   // "same-as-billing" instead of "add-new-item". "same-as-billing" is covered
   1244   // by the following tests. The last item in the menu is "add-new-item".
   1245   ui::MenuModel* shipping_model =
   1246       controller()->MenuModelForSection(SECTION_SHIPPING);
   1247   shipping_model->ActivatedAt(shipping_model->GetItemCount() - 1);
   1248   AcceptAndLoadFakeFingerprint();
   1249 }
   1250 
   1251 TEST_F(AutofillDialogControllerTest, SaveInstrument) {
   1252   EXPECT_CALL(*controller()->GetView(), ModelChanged()).Times(1);
   1253   EXPECT_CALL(*controller()->GetTestingWalletClient(),
   1254               SaveToWalletMock(testing::NotNull(),
   1255                                testing::IsNull(),
   1256                                _)).Times(1);
   1257 
   1258   scoped_ptr<wallet::WalletItems> wallet_items = wallet::GetTestWalletItems();
   1259   wallet_items->AddAddress(wallet::GetTestShippingAddress());
   1260   SubmitWithWalletItems(wallet_items.Pass());
   1261 }
   1262 
   1263 TEST_F(AutofillDialogControllerTest, SaveInstrumentWithInvalidInstruments) {
   1264   EXPECT_CALL(*controller()->GetView(), ModelChanged()).Times(1);
   1265   EXPECT_CALL(*controller()->GetTestingWalletClient(),
   1266               SaveToWalletMock(testing::NotNull(),
   1267                                testing::IsNull(),
   1268                                _)).Times(1);
   1269 
   1270   scoped_ptr<wallet::WalletItems> wallet_items = wallet::GetTestWalletItems();
   1271   wallet_items->AddAddress(wallet::GetTestShippingAddress());
   1272   wallet_items->AddInstrument(wallet::GetTestMaskedInstrumentInvalid());
   1273   SubmitWithWalletItems(wallet_items.Pass());
   1274 }
   1275 
   1276 TEST_F(AutofillDialogControllerTest, SaveInstrumentAndAddress) {
   1277   EXPECT_CALL(*controller()->GetTestingWalletClient(),
   1278               SaveToWalletMock(testing::NotNull(),
   1279                                testing::NotNull(),
   1280                                _)).Times(1);
   1281 
   1282   controller()->OnDidGetWalletItems(wallet::GetTestWalletItems());
   1283   AcceptAndLoadFakeFingerprint();
   1284 }
   1285 
   1286 MATCHER(IsUpdatingExistingData, "updating existing Wallet data") {
   1287   return !arg->object_id().empty();
   1288 }
   1289 
   1290 // Tests that editing an address (in wallet mode0 and submitting the dialog
   1291 // should update the existing address on the server via WalletClient.
   1292 TEST_F(AutofillDialogControllerTest, UpdateAddress) {
   1293   EXPECT_CALL(*controller()->GetTestingWalletClient(),
   1294               SaveToWalletMock(testing::IsNull(),
   1295                                IsUpdatingExistingData(),
   1296                                _)).Times(1);
   1297 
   1298   controller()->OnDidGetWalletItems(CompleteAndValidWalletItems());
   1299 
   1300   controller()->EditClickedForSection(SECTION_SHIPPING);
   1301   AcceptAndLoadFakeFingerprint();
   1302 }
   1303 
   1304 // Tests that editing an instrument (CC + address) in wallet mode updates an
   1305 // existing instrument on the server via WalletClient.
   1306 TEST_F(AutofillDialogControllerTest, UpdateInstrument) {
   1307   EXPECT_CALL(*controller()->GetTestingWalletClient(),
   1308               SaveToWalletMock(IsUpdatingExistingData(),
   1309                                testing::IsNull(),
   1310                                _)).Times(1);
   1311 
   1312   controller()->OnDidGetWalletItems(CompleteAndValidWalletItems());
   1313 
   1314   controller()->EditClickedForSection(SECTION_CC_BILLING);
   1315   AcceptAndLoadFakeFingerprint();
   1316 }
   1317 
   1318 // Test that a user is able to edit their instrument and add a new address in
   1319 // the same submission.
   1320 TEST_F(AutofillDialogControllerTest, UpdateInstrumentSaveAddress) {
   1321   EXPECT_CALL(*controller()->GetTestingWalletClient(),
   1322               SaveToWalletMock(IsUpdatingExistingData(),
   1323                                testing::NotNull(),
   1324                                _)).Times(1);
   1325 
   1326   scoped_ptr<wallet::WalletItems> wallet_items = wallet::GetTestWalletItems();
   1327   wallet_items->AddInstrument(wallet::GetTestMaskedInstrument());
   1328   controller()->OnDidGetWalletItems(wallet_items.Pass());
   1329 
   1330   controller()->EditClickedForSection(SECTION_CC_BILLING);
   1331   AcceptAndLoadFakeFingerprint();
   1332 }
   1333 
   1334 // Test that saving a new instrument and editing an address works.
   1335 TEST_F(AutofillDialogControllerTest, SaveInstrumentUpdateAddress) {
   1336   EXPECT_CALL(*controller()->GetTestingWalletClient(),
   1337               SaveToWalletMock(testing::NotNull(),
   1338                                IsUpdatingExistingData(),
   1339                                _)).Times(1);
   1340 
   1341   scoped_ptr<wallet::WalletItems> wallet_items = wallet::GetTestWalletItems();
   1342   wallet_items->AddAddress(wallet::GetTestShippingAddress());
   1343 
   1344   controller()->OnDidGetWalletItems(wallet_items.Pass());
   1345 
   1346   controller()->EditClickedForSection(SECTION_SHIPPING);
   1347   AcceptAndLoadFakeFingerprint();
   1348 }
   1349 
   1350 MATCHER(UsesLocalBillingAddress, "uses the local billing address") {
   1351   return arg->address_line_1() == ASCIIToUTF16(kEditedBillingAddress);
   1352 }
   1353 
   1354 // Tests that when using billing address for shipping, and there is no exact
   1355 // matched shipping address, then a shipping address should be added.
   1356 TEST_F(AutofillDialogControllerTest, BillingForShipping) {
   1357   EXPECT_CALL(*controller()->GetTestingWalletClient(),
   1358               SaveToWalletMock(testing::IsNull(),
   1359                                testing::NotNull(),
   1360                                _)).Times(1);
   1361 
   1362   controller()->OnDidGetWalletItems(CompleteAndValidWalletItems());
   1363   // Select "Same as billing" in the address menu.
   1364   UseBillingForShipping();
   1365 
   1366   AcceptAndLoadFakeFingerprint();
   1367 }
   1368 
   1369 // Tests that when using billing address for shipping, and there is an exact
   1370 // matched shipping address, then a shipping address should not be added.
   1371 TEST_F(AutofillDialogControllerTest, BillingForShippingHasMatch) {
   1372   EXPECT_CALL(*controller()->GetTestingWalletClient(),
   1373               SaveToWalletMock(_, _, _)).Times(0);
   1374 
   1375   scoped_ptr<wallet::WalletItems> wallet_items = wallet::GetTestWalletItems();
   1376   scoped_ptr<wallet::WalletItems::MaskedInstrument> instrument =
   1377       wallet::GetTestMaskedInstrument();
   1378   // Copy billing address as shipping address, and assign an id to it.
   1379   scoped_ptr<wallet::Address> shipping_address(
   1380       new wallet::Address(instrument->address()));
   1381   shipping_address->set_object_id("shipping_address_id");
   1382   wallet_items->AddAddress(shipping_address.Pass());
   1383   wallet_items->AddInstrument(instrument.Pass());
   1384   wallet_items->AddAddress(wallet::GetTestShippingAddress());
   1385 
   1386   controller()->OnDidGetWalletItems(wallet_items.Pass());
   1387   // Select "Same as billing" in the address menu.
   1388   UseBillingForShipping();
   1389 
   1390   AcceptAndLoadFakeFingerprint();
   1391 }
   1392 
   1393 // Test that the local view contents is used when saving a new instrument and
   1394 // the user has selected "Same as billing".
   1395 TEST_F(AutofillDialogControllerTest, SaveInstrumentSameAsBilling) {
   1396   scoped_ptr<wallet::WalletItems> wallet_items = wallet::GetTestWalletItems();
   1397   wallet_items->AddInstrument(wallet::GetTestMaskedInstrument());
   1398   controller()->OnDidGetWalletItems(wallet_items.Pass());
   1399 
   1400   controller()->EditClickedForSection(SECTION_CC_BILLING);
   1401   controller()->OnAccept();
   1402 
   1403   DetailOutputMap outputs;
   1404   const DetailInputs& inputs =
   1405       controller()->RequestedFieldsForSection(SECTION_CC_BILLING);
   1406   for (size_t i = 0; i < inputs.size(); ++i) {
   1407     const DetailInput& input = inputs[i];
   1408     outputs[&input] = input.type == ADDRESS_BILLING_LINE1 ?
   1409         ASCIIToUTF16(kEditedBillingAddress) : input.initial_value;
   1410   }
   1411   controller()->GetView()->SetUserInput(SECTION_CC_BILLING, outputs);
   1412 
   1413   EXPECT_CALL(*controller()->GetTestingWalletClient(),
   1414               SaveToWalletMock(testing::NotNull(),
   1415                                UsesLocalBillingAddress(),
   1416                                _)).Times(1);
   1417   AcceptAndLoadFakeFingerprint();
   1418 }
   1419 
   1420 TEST_F(AutofillDialogControllerTest, CancelNoSave) {
   1421   EXPECT_CALL(*controller()->GetTestingWalletClient(),
   1422               SaveToWalletMock(_, _, _)).Times(0);
   1423 
   1424   EXPECT_CALL(*controller()->GetView(), ModelChanged()).Times(1);
   1425 
   1426   controller()->OnDidGetWalletItems(wallet::GetTestWalletItems());
   1427   controller()->OnCancel();
   1428 }
   1429 
   1430 // Checks that clicking the Manage menu item opens a new tab with a different
   1431 // URL for Wallet and Autofill.
   1432 TEST_F(AutofillDialogControllerTest, ManageItem) {
   1433   AutofillProfile full_profile(test::GetVerifiedProfile());
   1434   full_profile.set_origin(kSettingsOrigin);
   1435   full_profile.SetRawInfo(ADDRESS_HOME_LINE2, string16());
   1436   controller()->GetTestingManager()->AddTestingProfile(&full_profile);
   1437   SwitchToAutofill();
   1438 
   1439   SuggestionsMenuModel* shipping = static_cast<SuggestionsMenuModel*>(
   1440       controller()->MenuModelForSection(SECTION_SHIPPING));
   1441   shipping->ExecuteCommand(shipping->GetItemCount() - 1, 0);
   1442   GURL autofill_manage_url = controller()->open_tab_url();
   1443   EXPECT_EQ("chrome", autofill_manage_url.scheme());
   1444 
   1445   SwitchToWallet();
   1446   scoped_ptr<wallet::WalletItems> wallet_items = wallet::GetTestWalletItems();
   1447   wallet_items->AddInstrument(wallet::GetTestMaskedInstrument());
   1448   controller()->OnDidGetWalletItems(wallet_items.Pass());
   1449 
   1450   controller()->SuggestionItemSelected(shipping, shipping->GetItemCount() - 1);
   1451   GURL wallet_manage_addresses_url = controller()->open_tab_url();
   1452   EXPECT_EQ("https", wallet_manage_addresses_url.scheme());
   1453 
   1454   SuggestionsMenuModel* billing = static_cast<SuggestionsMenuModel*>(
   1455       controller()->MenuModelForSection(SECTION_CC_BILLING));
   1456   controller()->SuggestionItemSelected(billing, billing->GetItemCount() - 1);
   1457   GURL wallet_manage_instruments_url = controller()->open_tab_url();
   1458   EXPECT_EQ("https", wallet_manage_instruments_url.scheme());
   1459 
   1460   EXPECT_NE(autofill_manage_url, wallet_manage_instruments_url);
   1461   EXPECT_NE(wallet_manage_instruments_url, wallet_manage_addresses_url);
   1462 }
   1463 
   1464 TEST_F(AutofillDialogControllerTest, EditClickedCancelled) {
   1465   EXPECT_CALL(*controller()->GetView(), ModelChanged()).Times(1);
   1466 
   1467   AutofillProfile full_profile(test::GetVerifiedProfile());
   1468   const string16 kEmail = ASCIIToUTF16("first (at) johndoe.com");
   1469   full_profile.SetRawInfo(EMAIL_ADDRESS, kEmail);
   1470   controller()->GetTestingManager()->AddTestingProfile(&full_profile);
   1471 
   1472   ui::MenuModel* email_model =
   1473       controller()->MenuModelForSection(SECTION_EMAIL);
   1474   EXPECT_EQ(3, email_model->GetItemCount());
   1475 
   1476   // When unedited, the initial_value should be empty.
   1477   email_model->ActivatedAt(0);
   1478   const DetailInputs& inputs0 =
   1479       controller()->RequestedFieldsForSection(SECTION_EMAIL);
   1480   EXPECT_EQ(string16(), inputs0[0].initial_value);
   1481   EXPECT_EQ(kEmail,
   1482             controller()->SuggestionStateForSection(SECTION_EMAIL).
   1483                 vertically_compact_text);
   1484 
   1485   // When edited, the initial_value should contain the value.
   1486   controller()->EditClickedForSection(SECTION_EMAIL);
   1487   const DetailInputs& inputs1 =
   1488       controller()->RequestedFieldsForSection(SECTION_EMAIL);
   1489   EXPECT_EQ(kEmail, inputs1[0].initial_value);
   1490   EXPECT_FALSE(controller()->SuggestionStateForSection(SECTION_EMAIL).visible);
   1491 
   1492   // When edit is cancelled, the initial_value should be empty.
   1493   controller()->EditCancelledForSection(SECTION_EMAIL);
   1494   const DetailInputs& inputs2 =
   1495       controller()->RequestedFieldsForSection(SECTION_EMAIL);
   1496   EXPECT_EQ(kEmail,
   1497             controller()->SuggestionStateForSection(SECTION_EMAIL).
   1498                 vertically_compact_text);
   1499   EXPECT_EQ(string16(), inputs2[0].initial_value);
   1500 }
   1501 
   1502 // Tests that editing an autofill profile and then submitting works.
   1503 TEST_F(AutofillDialogControllerTest, EditAutofillProfile) {
   1504   SwitchToAutofill();
   1505 
   1506   EXPECT_CALL(*controller()->GetView(), ModelChanged()).Times(2);
   1507 
   1508   AutofillProfile full_profile(test::GetVerifiedProfile());
   1509   CreditCard credit_card(test::GetVerifiedCreditCard());
   1510   controller()->GetTestingManager()->AddTestingProfile(&full_profile);
   1511   controller()->GetTestingManager()->AddTestingCreditCard(&credit_card);
   1512   controller()->EditClickedForSection(SECTION_SHIPPING);
   1513 
   1514   DetailOutputMap outputs;
   1515   const DetailInputs& inputs =
   1516       controller()->RequestedFieldsForSection(SECTION_SHIPPING);
   1517   for (size_t i = 0; i < inputs.size(); ++i) {
   1518     const DetailInput& input = inputs[i];
   1519     outputs[&input] = input.type == NAME_FULL ? ASCIIToUTF16("Edited Name") :
   1520                                                 input.initial_value;
   1521   }
   1522   controller()->GetView()->SetUserInput(SECTION_SHIPPING, outputs);
   1523 
   1524   // We also have to simulate CC inputs to keep the controller happy.
   1525   FillCreditCardInputs();
   1526 
   1527   controller()->OnAccept();
   1528   const AutofillProfile& edited_profile =
   1529       controller()->GetTestingManager()->imported_profile();
   1530 
   1531   for (size_t i = 0; i < inputs.size(); ++i) {
   1532     const DetailInput& input = inputs[i];
   1533     EXPECT_EQ(input.type == NAME_FULL ? ASCIIToUTF16("Edited Name") :
   1534                                         input.initial_value,
   1535               edited_profile.GetInfo(AutofillType(input.type), "en-US"));
   1536   }
   1537 }
   1538 
   1539 // Tests that adding an autofill profile and then submitting works.
   1540 TEST_F(AutofillDialogControllerTest, AddAutofillProfile) {
   1541   SwitchToAutofill();
   1542   EXPECT_CALL(*controller()->GetView(), ModelChanged()).Times(2);
   1543 
   1544   AutofillProfile full_profile(test::GetVerifiedProfile());
   1545   CreditCard credit_card(test::GetVerifiedCreditCard());
   1546   controller()->GetTestingManager()->AddTestingProfile(&full_profile);
   1547   controller()->GetTestingManager()->AddTestingCreditCard(&credit_card);
   1548 
   1549   ui::MenuModel* model = controller()->MenuModelForSection(SECTION_BILLING);
   1550   // Activate the "Add billing address" menu item.
   1551   model->ActivatedAt(model->GetItemCount() - 2);
   1552 
   1553   // Fill in the inputs from the profile.
   1554   DetailOutputMap outputs;
   1555   const DetailInputs& inputs =
   1556       controller()->RequestedFieldsForSection(SECTION_BILLING);
   1557   AutofillProfile full_profile2(test::GetVerifiedProfile2());
   1558   for (size_t i = 0; i < inputs.size(); ++i) {
   1559     const DetailInput& input = inputs[i];
   1560     outputs[&input] = full_profile2.GetInfo(AutofillType(input.type), "en-US");
   1561   }
   1562   controller()->GetView()->SetUserInput(SECTION_BILLING, outputs);
   1563 
   1564   controller()->OnAccept();
   1565   const AutofillProfile& added_profile =
   1566       controller()->GetTestingManager()->imported_profile();
   1567 
   1568   const DetailInputs& shipping_inputs =
   1569       controller()->RequestedFieldsForSection(SECTION_SHIPPING);
   1570   for (size_t i = 0; i < shipping_inputs.size(); ++i) {
   1571     const DetailInput& input = shipping_inputs[i];
   1572     EXPECT_EQ(full_profile2.GetInfo(AutofillType(input.type), "en-US"),
   1573               added_profile.GetInfo(AutofillType(input.type), "en-US"));
   1574   }
   1575 
   1576   // Also, the currently selected email address should get added to the new
   1577   // profile.
   1578   string16 original_email =
   1579       full_profile.GetInfo(AutofillType(EMAIL_ADDRESS), "en-US");
   1580   EXPECT_FALSE(original_email.empty());
   1581   EXPECT_EQ(original_email,
   1582             added_profile.GetInfo(AutofillType(EMAIL_ADDRESS), "en-US"));
   1583 }
   1584 
   1585 // Makes sure that a newly added email address gets added to an existing profile
   1586 // (as opposed to creating its own profile). http://crbug.com/240926
   1587 TEST_F(AutofillDialogControllerTest, AddEmail) {
   1588   SwitchToAutofill();
   1589   EXPECT_CALL(*controller()->GetView(), ModelChanged()).Times(2);
   1590 
   1591   AutofillProfile full_profile(test::GetVerifiedProfile());
   1592   CreditCard credit_card(test::GetVerifiedCreditCard());
   1593   controller()->GetTestingManager()->AddTestingProfile(&full_profile);
   1594   controller()->GetTestingManager()->AddTestingCreditCard(&credit_card);
   1595 
   1596   ui::MenuModel* model = controller()->MenuModelForSection(SECTION_EMAIL);
   1597   ASSERT_TRUE(model);
   1598   // Activate the "Add email address" menu item.
   1599   model->ActivatedAt(model->GetItemCount() - 2);
   1600 
   1601   // Fill in the inputs from the profile.
   1602   DetailOutputMap outputs;
   1603   const DetailInputs& inputs =
   1604       controller()->RequestedFieldsForSection(SECTION_EMAIL);
   1605   const DetailInput& input = inputs[0];
   1606   string16 new_email = ASCIIToUTF16("addemailtest (at) example.com");
   1607   outputs[&input] = new_email;
   1608   controller()->GetView()->SetUserInput(SECTION_EMAIL, outputs);
   1609 
   1610   FillCreditCardInputs();
   1611   controller()->OnAccept();
   1612   std::vector<base::string16> email_values;
   1613   full_profile.GetMultiInfo(
   1614       AutofillType(EMAIL_ADDRESS), "en-US", &email_values);
   1615   ASSERT_EQ(2U, email_values.size());
   1616   EXPECT_EQ(new_email, email_values[1]);
   1617 }
   1618 
   1619 TEST_F(AutofillDialogControllerTest, VerifyCvv) {
   1620   EXPECT_CALL(*controller()->GetTestingWalletClient(),
   1621               GetFullWallet(_)).Times(1);
   1622   EXPECT_CALL(*controller()->GetTestingWalletClient(),
   1623               AuthenticateInstrument(_, _)).Times(1);
   1624 
   1625   SubmitWithWalletItems(CompleteAndValidWalletItems());
   1626 
   1627   EXPECT_TRUE(NotificationsOfType(DialogNotification::REQUIRED_ACTION).empty());
   1628   EXPECT_TRUE(controller()->SectionIsActive(SECTION_SHIPPING));
   1629   EXPECT_TRUE(controller()->SectionIsActive(SECTION_CC_BILLING));
   1630   EXPECT_FALSE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_OK));
   1631   EXPECT_FALSE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_CANCEL));
   1632 
   1633   SuggestionState suggestion_state =
   1634       controller()->SuggestionStateForSection(SECTION_CC_BILLING);
   1635   EXPECT_TRUE(suggestion_state.extra_text.empty());
   1636 
   1637   controller()->OnDidGetFullWallet(CreateFullWallet("verify_cvv"));
   1638 
   1639   EXPECT_FALSE(
   1640       NotificationsOfType(DialogNotification::REQUIRED_ACTION).empty());
   1641   EXPECT_FALSE(controller()->SectionIsActive(SECTION_SHIPPING));
   1642   EXPECT_TRUE(controller()->SectionIsActive(SECTION_CC_BILLING));
   1643 
   1644   suggestion_state =
   1645       controller()->SuggestionStateForSection(SECTION_CC_BILLING);
   1646   EXPECT_FALSE(suggestion_state.extra_text.empty());
   1647   EXPECT_FALSE(controller()->MenuModelForSection(SECTION_CC_BILLING));
   1648 
   1649   EXPECT_TRUE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_OK));
   1650   EXPECT_TRUE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_CANCEL));
   1651 
   1652   controller()->OnAccept();
   1653 }
   1654 
   1655 TEST_F(AutofillDialogControllerTest, ErrorDuringSubmit) {
   1656   EXPECT_CALL(*controller()->GetTestingWalletClient(),
   1657               GetFullWallet(_)).Times(1);
   1658 
   1659   SubmitWithWalletItems(CompleteAndValidWalletItems());
   1660 
   1661   EXPECT_FALSE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_OK));
   1662   EXPECT_FALSE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_CANCEL));
   1663 
   1664   controller()->OnWalletError(wallet::WalletClient::UNKNOWN_ERROR);
   1665 
   1666   EXPECT_TRUE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_OK));
   1667   EXPECT_TRUE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_CANCEL));
   1668 }
   1669 
   1670 // TODO(dbeam): disallow changing accounts instead and remove this test.
   1671 TEST_F(AutofillDialogControllerTest, ChangeAccountDuringSubmit) {
   1672   EXPECT_CALL(*controller()->GetTestingWalletClient(),
   1673               GetFullWallet(_)).Times(1);
   1674 
   1675   SubmitWithWalletItems(CompleteAndValidWalletItems());
   1676 
   1677   EXPECT_FALSE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_OK));
   1678   EXPECT_FALSE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_CANCEL));
   1679 
   1680   SwitchToWallet();
   1681   SwitchToAutofill();
   1682 
   1683   EXPECT_TRUE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_OK));
   1684   EXPECT_TRUE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_CANCEL));
   1685 }
   1686 
   1687 TEST_F(AutofillDialogControllerTest, ErrorDuringVerifyCvv) {
   1688   EXPECT_CALL(*controller()->GetTestingWalletClient(),
   1689               GetFullWallet(_)).Times(1);
   1690 
   1691   SubmitWithWalletItems(CompleteAndValidWalletItems());
   1692   controller()->OnDidGetFullWallet(CreateFullWallet("verify_cvv"));
   1693 
   1694   ASSERT_TRUE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_OK));
   1695   ASSERT_TRUE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_CANCEL));
   1696 
   1697   controller()->OnWalletError(wallet::WalletClient::UNKNOWN_ERROR);
   1698 
   1699   EXPECT_TRUE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_OK));
   1700   EXPECT_TRUE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_CANCEL));
   1701 }
   1702 
   1703 // TODO(dbeam): disallow changing accounts instead and remove this test.
   1704 TEST_F(AutofillDialogControllerTest, ChangeAccountDuringVerifyCvv) {
   1705   EXPECT_CALL(*controller()->GetTestingWalletClient(),
   1706               GetFullWallet(_)).Times(1);
   1707 
   1708   SubmitWithWalletItems(CompleteAndValidWalletItems());
   1709   controller()->OnDidGetFullWallet(CreateFullWallet("verify_cvv"));
   1710 
   1711   ASSERT_TRUE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_OK));
   1712   ASSERT_TRUE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_CANCEL));
   1713 
   1714   SwitchToWallet();
   1715   SwitchToAutofill();
   1716 
   1717   EXPECT_TRUE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_OK));
   1718   EXPECT_TRUE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_CANCEL));
   1719 }
   1720 
   1721 // Simulates receiving an INVALID_FORM_FIELD required action while processing a
   1722 // |WalletClientDelegate::OnDid{Save,Update}*()| call. This can happen if Online
   1723 // Wallet's server validation differs from Chrome's local validation.
   1724 TEST_F(AutofillDialogControllerTest, WalletServerSideValidation) {
   1725   scoped_ptr<wallet::WalletItems> wallet_items = wallet::GetTestWalletItems();
   1726   wallet_items->AddInstrument(wallet::GetTestMaskedInstrument());
   1727   controller()->OnDidGetWalletItems(wallet_items.Pass());
   1728   controller()->OnAccept();
   1729 
   1730   std::vector<wallet::RequiredAction> required_actions;
   1731   required_actions.push_back(wallet::INVALID_FORM_FIELD);
   1732 
   1733   std::vector<wallet::FormFieldError> form_errors;
   1734   form_errors.push_back(
   1735       wallet::FormFieldError(wallet::FormFieldError::INVALID_POSTAL_CODE,
   1736                              wallet::FormFieldError::SHIPPING_ADDRESS));
   1737 
   1738   EXPECT_CALL(*controller()->GetView(), UpdateForErrors()).Times(1);
   1739   controller()->OnDidSaveToWallet(std::string(),
   1740                                   std::string(),
   1741                                   required_actions,
   1742                                   form_errors);
   1743 }
   1744 
   1745 // Simulates receiving unrecoverable Wallet server validation errors.
   1746 TEST_F(AutofillDialogControllerTest, WalletServerSideValidationUnrecoverable) {
   1747   scoped_ptr<wallet::WalletItems> wallet_items = wallet::GetTestWalletItems();
   1748   wallet_items->AddInstrument(wallet::GetTestMaskedInstrument());
   1749   controller()->OnDidGetWalletItems(wallet_items.Pass());
   1750   controller()->OnAccept();
   1751 
   1752   std::vector<wallet::RequiredAction> required_actions;
   1753   required_actions.push_back(wallet::INVALID_FORM_FIELD);
   1754 
   1755   std::vector<wallet::FormFieldError> form_errors;
   1756   form_errors.push_back(
   1757       wallet::FormFieldError(wallet::FormFieldError::UNKNOWN_ERROR,
   1758                              wallet::FormFieldError::UNKNOWN_LOCATION));
   1759 
   1760   controller()->OnDidSaveToWallet(std::string(),
   1761                                   std::string(),
   1762                                   required_actions,
   1763                                   form_errors);
   1764 
   1765   EXPECT_EQ(1U, NotificationsOfType(
   1766       DialogNotification::REQUIRED_ACTION).size());
   1767 }
   1768 
   1769 // Test Wallet banners are show in the right situations. These banners explain
   1770 // where Chrome got the user's data (i.e. "Got details from Wallet") or promote
   1771 // saving details into Wallet (i.e. "[x] Save details to Wallet").
   1772 TEST_F(AutofillDialogControllerTest, WalletBanners) {
   1773   CommandLine* command_line = CommandLine::ForCurrentProcess();
   1774   command_line->AppendSwitch(switches::kWalletServiceUseProd);
   1775   PrefService* prefs = profile()->GetPrefs();
   1776 
   1777   // Simulate first run.
   1778   prefs->SetBoolean(::prefs::kAutofillDialogHasPaidWithWallet, false);
   1779   SetUpControllerWithFormData(DefaultFormData());
   1780 
   1781   EXPECT_EQ(0U, NotificationsOfType(
   1782       DialogNotification::EXPLANATORY_MESSAGE).size());
   1783   EXPECT_EQ(0U, NotificationsOfType(
   1784       DialogNotification::WALLET_USAGE_CONFIRMATION).size());
   1785 
   1786   // Sign in a user with a completed account.
   1787   controller()->OnDidGetWalletItems(CompleteAndValidWalletItems());
   1788 
   1789   // Full account; should show "Details from Wallet" message.
   1790   EXPECT_EQ(1U, NotificationsOfType(
   1791       DialogNotification::EXPLANATORY_MESSAGE).size());
   1792   EXPECT_EQ(0U, NotificationsOfType(
   1793       DialogNotification::WALLET_USAGE_CONFIRMATION).size());
   1794 
   1795   // Full account; no "[x] Save details in Wallet" option should show.
   1796   SwitchToAutofill();
   1797   EXPECT_EQ(0U, NotificationsOfType(
   1798       DialogNotification::EXPLANATORY_MESSAGE).size());
   1799   EXPECT_EQ(0U, NotificationsOfType(
   1800       DialogNotification::WALLET_USAGE_CONFIRMATION).size());
   1801 
   1802   SetUpControllerWithFormData(DefaultFormData());
   1803   // |controller()| has already been initialized. Test that should not take
   1804   // effect until the next call of |SetUpControllerWithFormData()|.
   1805   prefs->SetBoolean(::prefs::kAutofillDialogHasPaidWithWallet, true);
   1806 
   1807   // Sign in a user with a incomplete account.
   1808   scoped_ptr<wallet::WalletItems> wallet_items = wallet::GetTestWalletItems();
   1809   wallet_items->AddInstrument(wallet::GetTestMaskedInstrument());
   1810   controller()->OnDidGetWalletItems(wallet_items.Pass());
   1811 
   1812   // Partial account; no "Details from Wallet" message should show, but a
   1813   // "[x] Save details in Wallet" should.
   1814   EXPECT_EQ(0U, NotificationsOfType(
   1815       DialogNotification::EXPLANATORY_MESSAGE).size());
   1816   EXPECT_EQ(1U, NotificationsOfType(
   1817       DialogNotification::WALLET_USAGE_CONFIRMATION).size());
   1818 
   1819   // Once the usage confirmation banner is shown once, it keeps showing even if
   1820   // the user switches to Autofill data.
   1821   SwitchToAutofill();
   1822   EXPECT_EQ(0U, NotificationsOfType(
   1823       DialogNotification::EXPLANATORY_MESSAGE).size());
   1824   EXPECT_EQ(1U, NotificationsOfType(
   1825       DialogNotification::WALLET_USAGE_CONFIRMATION).size());
   1826 
   1827   // A Wallet error should kill any Wallet promos.
   1828   controller()->OnWalletError(wallet::WalletClient::UNKNOWN_ERROR);
   1829 
   1830   EXPECT_EQ(1U, NotificationsOfType(
   1831       DialogNotification::WALLET_ERROR).size());
   1832   EXPECT_EQ(0U, NotificationsOfType(
   1833       DialogNotification::EXPLANATORY_MESSAGE).size());
   1834   EXPECT_EQ(0U, NotificationsOfType(
   1835       DialogNotification::WALLET_USAGE_CONFIRMATION).size());
   1836 
   1837   SetUpControllerWithFormData(DefaultFormData());
   1838   // |controller()| is error free and thinks the user has already paid w/Wallet.
   1839 
   1840   // User has already paid with wallet. Don't show promos.
   1841   EXPECT_EQ(0U, NotificationsOfType(
   1842       DialogNotification::EXPLANATORY_MESSAGE).size());
   1843   EXPECT_EQ(0U, NotificationsOfType(
   1844       DialogNotification::WALLET_USAGE_CONFIRMATION).size());
   1845 
   1846   controller()->OnDidGetWalletItems(CompleteAndValidWalletItems());
   1847 
   1848   EXPECT_EQ(0U, NotificationsOfType(
   1849       DialogNotification::EXPLANATORY_MESSAGE).size());
   1850   EXPECT_EQ(0U, NotificationsOfType(
   1851       DialogNotification::WALLET_USAGE_CONFIRMATION).size());
   1852 
   1853   wallet_items = wallet::GetTestWalletItems();
   1854   wallet_items->AddInstrument(wallet::GetTestMaskedInstrument());
   1855   controller()->OnDidGetWalletItems(wallet_items.Pass());
   1856 
   1857   SwitchToAutofill();
   1858   EXPECT_EQ(0U, NotificationsOfType(
   1859       DialogNotification::EXPLANATORY_MESSAGE).size());
   1860   EXPECT_EQ(0U, NotificationsOfType(
   1861       DialogNotification::WALLET_USAGE_CONFIRMATION).size());
   1862 }
   1863 
   1864 TEST_F(AutofillDialogControllerTest, OnAutocheckoutError) {
   1865   SwitchToAutofill();
   1866   controller()->set_dialog_type(DIALOG_TYPE_AUTOCHECKOUT);
   1867 
   1868   // We also have to simulate CC inputs to keep the controller happy.
   1869   FillCreditCardInputs();
   1870 
   1871   controller()->OnAccept();
   1872   EXPECT_TRUE(ReadSetVisuallyDeemphasizedIpc());
   1873   controller()->OnAutocheckoutError();
   1874 
   1875   EXPECT_FALSE(controller()->GetDialogButtons() & ui::DIALOG_BUTTON_CANCEL);
   1876   EXPECT_TRUE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_OK));
   1877   EXPECT_EQ(0U, NotificationsOfType(
   1878       DialogNotification::AUTOCHECKOUT_SUCCESS).size());
   1879   EXPECT_EQ(1U, NotificationsOfType(
   1880       DialogNotification::AUTOCHECKOUT_ERROR).size());
   1881 
   1882   controller()->ViewClosed();
   1883   EXPECT_FALSE(ReadSetVisuallyDeemphasizedIpc());
   1884 }
   1885 
   1886 TEST_F(AutofillDialogControllerTest, OnAutocheckoutSuccess) {
   1887   CommandLine* command_line = CommandLine::ForCurrentProcess();
   1888   command_line->AppendSwitch(switches::kWalletServiceUseProd);
   1889   controller()->set_dialog_type(DIALOG_TYPE_AUTOCHECKOUT);
   1890 
   1891   // Simulate first run.
   1892   profile()->GetPrefs()->SetBoolean(::prefs::kAutofillDialogHasPaidWithWallet,
   1893                                     false);
   1894   SetUpControllerWithFormData(DefaultFormData());
   1895   controller()->set_dialog_type(DIALOG_TYPE_AUTOCHECKOUT);
   1896 
   1897   // Sign in a user with a completed account.
   1898   controller()->OnDidGetWalletItems(CompleteAndValidWalletItems());
   1899 
   1900   // Full account; should show "Details from Wallet" message.
   1901   EXPECT_EQ(1U, NotificationsOfType(
   1902       DialogNotification::EXPLANATORY_MESSAGE).size());
   1903   EXPECT_EQ(0U, NotificationsOfType(
   1904       DialogNotification::WALLET_USAGE_CONFIRMATION).size());
   1905 
   1906   AcceptAndLoadFakeFingerprint();
   1907   EXPECT_TRUE(ReadSetVisuallyDeemphasizedIpc());
   1908   controller()->OnDidGetFullWallet(wallet::GetTestFullWallet());
   1909   EXPECT_TRUE(controller()->GetDialogOverlay().image.IsEmpty());
   1910 
   1911   EXPECT_EQ(0U, NotificationsOfType(
   1912       DialogNotification::EXPLANATORY_MESSAGE).size());
   1913 
   1914   controller()->OnAutocheckoutSuccess();
   1915   EXPECT_TRUE(controller()->GetDialogOverlay().image.IsEmpty());
   1916 
   1917   EXPECT_FALSE(controller()->GetDialogButtons() & ui::DIALOG_BUTTON_CANCEL);
   1918   EXPECT_TRUE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_OK));
   1919   EXPECT_EQ(1U, NotificationsOfType(
   1920       DialogNotification::AUTOCHECKOUT_SUCCESS).size());
   1921   EXPECT_EQ(0U, NotificationsOfType(
   1922       DialogNotification::AUTOCHECKOUT_ERROR).size());
   1923   EXPECT_EQ(0U, NotificationsOfType(
   1924       DialogNotification::EXPLANATORY_MESSAGE).size());
   1925   EXPECT_TRUE(profile()->GetPrefs()->GetBoolean(
   1926       ::prefs::kAutofillDialogHasPaidWithWallet));
   1927 
   1928   controller()->ViewClosed();
   1929   EXPECT_FALSE(ReadSetVisuallyDeemphasizedIpc());
   1930 }
   1931 
   1932 TEST_F(AutofillDialogControllerTest, ViewCancelDoesntSetPref) {
   1933   ASSERT_FALSE(profile()->GetPrefs()->HasPrefPath(
   1934       ::prefs::kAutofillDialogPayWithoutWallet));
   1935 
   1936   SwitchToAutofill();
   1937 
   1938   controller()->OnCancel();
   1939   controller()->ViewClosed();
   1940 
   1941   EXPECT_FALSE(profile()->GetPrefs()->HasPrefPath(
   1942       ::prefs::kAutofillDialogPayWithoutWallet));
   1943 }
   1944 
   1945 TEST_F(AutofillDialogControllerTest, SubmitWithSigninErrorDoesntSetPref) {
   1946   ASSERT_FALSE(profile()->GetPrefs()->HasPrefPath(
   1947       ::prefs::kAutofillDialogPayWithoutWallet));
   1948 
   1949   SimulateSigninError();
   1950   FillCreditCardInputs();
   1951   controller()->OnAccept();
   1952 
   1953   EXPECT_FALSE(profile()->GetPrefs()->HasPrefPath(
   1954       ::prefs::kAutofillDialogPayWithoutWallet));
   1955 }
   1956 
   1957 // Tests that there's an overlay shown while waiting for full wallet items,
   1958 // and on first run an additional expository wallet overlay shown after full
   1959 // wallet items are returned.
   1960 // TODO(estade): enable on other platforms when overlays are supported there.
   1961 #if defined(TOOLKIT_VIEWS)
   1962 TEST_F(AutofillDialogControllerTest, WalletFirstRun) {
   1963   // Simulate first run.
   1964   PrefService* prefs = profile()->GetPrefs();
   1965   prefs->SetBoolean(::prefs::kAutofillDialogHasPaidWithWallet, false);
   1966   SetUpControllerWithFormData(DefaultFormData());
   1967 
   1968   SwitchToWallet();
   1969   EXPECT_TRUE(controller()->GetDialogOverlay().image.IsEmpty());
   1970 
   1971   SubmitWithWalletItems(CompleteAndValidWalletItems());
   1972   EXPECT_FALSE(controller()->GetDialogOverlay().image.IsEmpty());
   1973 
   1974   EXPECT_FALSE(prefs->GetBoolean(::prefs::kAutofillDialogHasPaidWithWallet));
   1975   controller()->OnDidGetFullWallet(wallet::GetTestFullWallet());
   1976   EXPECT_FALSE(prefs->GetBoolean(::prefs::kAutofillDialogHasPaidWithWallet));
   1977   EXPECT_FALSE(controller()->GetDialogOverlay().image.IsEmpty());
   1978   EXPECT_FALSE(form_structure());
   1979 
   1980   controller()->OverlayButtonPressed();
   1981   EXPECT_TRUE(prefs->GetBoolean(::prefs::kAutofillDialogHasPaidWithWallet));
   1982   EXPECT_TRUE(form_structure());
   1983 }
   1984 #endif
   1985 
   1986 // On second run, the second overlay doesn't show.
   1987 TEST_F(AutofillDialogControllerTest, WalletSecondRun) {
   1988   SwitchToWallet();
   1989   EXPECT_TRUE(controller()->GetDialogOverlay().image.IsEmpty());
   1990 
   1991   SubmitWithWalletItems(CompleteAndValidWalletItems());
   1992   EXPECT_FALSE(controller()->GetDialogOverlay().image.IsEmpty());
   1993 
   1994   EXPECT_TRUE(profile()->GetPrefs()->GetBoolean(
   1995       ::prefs::kAutofillDialogHasPaidWithWallet));
   1996   controller()->OnDidGetFullWallet(wallet::GetTestFullWallet());
   1997   EXPECT_TRUE(profile()->GetPrefs()->GetBoolean(
   1998       ::prefs::kAutofillDialogHasPaidWithWallet));
   1999   EXPECT_TRUE(form_structure());
   2000 }
   2001 
   2002 TEST_F(AutofillDialogControllerTest, ViewSubmitSetsPref) {
   2003   ASSERT_FALSE(profile()->GetPrefs()->HasPrefPath(
   2004       ::prefs::kAutofillDialogPayWithoutWallet));
   2005 
   2006   SwitchToAutofill();
   2007   FillCreditCardInputs();
   2008   controller()->OnAccept();
   2009 
   2010   EXPECT_TRUE(profile()->GetPrefs()->HasPrefPath(
   2011       ::prefs::kAutofillDialogPayWithoutWallet));
   2012   EXPECT_TRUE(profile()->GetPrefs()->GetBoolean(
   2013       ::prefs::kAutofillDialogPayWithoutWallet));
   2014 
   2015   // Try again with a signin error (just leaves the pref alone).
   2016   SetUpControllerWithFormData(DefaultFormData());
   2017 
   2018   // Setting up the controller again should not change the pref.
   2019   EXPECT_TRUE(profile()->GetPrefs()->HasPrefPath(
   2020       ::prefs::kAutofillDialogPayWithoutWallet));
   2021   EXPECT_TRUE(profile()->GetPrefs()->GetBoolean(
   2022       ::prefs::kAutofillDialogPayWithoutWallet));
   2023 
   2024   SimulateSigninError();
   2025   FillCreditCardInputs();
   2026   controller()->OnAccept();
   2027   EXPECT_TRUE(profile()->GetPrefs()->HasPrefPath(
   2028       ::prefs::kAutofillDialogPayWithoutWallet));
   2029   EXPECT_TRUE(profile()->GetPrefs()->GetBoolean(
   2030       ::prefs::kAutofillDialogPayWithoutWallet));
   2031 
   2032   // Succesfully choosing wallet does set the pref.
   2033   SetUpControllerWithFormData(DefaultFormData());
   2034 
   2035   SwitchToWallet();
   2036   scoped_ptr<wallet::WalletItems> wallet_items = wallet::GetTestWalletItems();
   2037   wallet_items->AddInstrument(wallet::GetTestMaskedInstrument());
   2038   controller()->OnDidGetWalletItems(wallet_items.Pass());
   2039   controller()->OnAccept();
   2040   controller()->OnDidGetFullWallet(wallet::GetTestFullWallet());
   2041 
   2042   EXPECT_TRUE(profile()->GetPrefs()->HasPrefPath(
   2043       ::prefs::kAutofillDialogPayWithoutWallet));
   2044   EXPECT_FALSE(profile()->GetPrefs()->GetBoolean(
   2045       ::prefs::kAutofillDialogPayWithoutWallet));
   2046 }
   2047 
   2048 TEST_F(AutofillDialogControllerTest, HideWalletEmail) {
   2049   SwitchToAutofill();
   2050 
   2051   // Email section should be showing when using Autofill.
   2052   EXPECT_TRUE(controller()->SectionIsActive(SECTION_EMAIL));
   2053 
   2054   SwitchToWallet();
   2055 
   2056   // Setup some wallet state, submit, and get a full wallet to end the flow.
   2057   scoped_ptr<wallet::WalletItems> wallet_items = CompleteAndValidWalletItems();
   2058 
   2059   // Filling |form_structure()| depends on the current username and wallet items
   2060   // being fetched. Until both of these have occurred, the user should not be
   2061   // able to click Submit if using Wallet. The username fetch happened earlier.
   2062   EXPECT_FALSE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_OK));
   2063   controller()->OnDidGetWalletItems(wallet_items.Pass());
   2064   EXPECT_TRUE(controller()->IsDialogButtonEnabled(ui::DIALOG_BUTTON_OK));
   2065 
   2066   // Email section should be hidden when using Wallet.
   2067   EXPECT_FALSE(controller()->SectionIsActive(SECTION_EMAIL));
   2068 
   2069   controller()->OnAccept();
   2070   controller()->OnDidGetFullWallet(wallet::GetTestFullWallet());
   2071 
   2072   size_t i = 0;
   2073   for (; i < form_structure()->field_count(); ++i) {
   2074     if (form_structure()->field(i)->Type().GetStorableType() == EMAIL_ADDRESS) {
   2075       EXPECT_EQ(ASCIIToUTF16(kFakeEmail), form_structure()->field(i)->value);
   2076       break;
   2077     }
   2078   }
   2079   ASSERT_LT(i, form_structure()->field_count());
   2080 }
   2081 
   2082 // Test if autofill types of returned form structure are correct for billing
   2083 // entries.
   2084 TEST_F(AutofillDialogControllerTest, AutofillTypes) {
   2085   controller()->OnDidGetWalletItems(CompleteAndValidWalletItems());
   2086   controller()->OnAccept();
   2087   controller()->OnDidGetFullWallet(wallet::GetTestFullWallet());
   2088   ASSERT_EQ(20U, form_structure()->field_count());
   2089   EXPECT_EQ(EMAIL_ADDRESS,
   2090             form_structure()->field(0)->Type().GetStorableType());
   2091   EXPECT_EQ(CREDIT_CARD_NUMBER,
   2092             form_structure()->field(2)->Type().GetStorableType());
   2093   EXPECT_EQ(ADDRESS_HOME_STATE,
   2094             form_structure()->field(9)->Type().GetStorableType());
   2095   EXPECT_EQ(ADDRESS_BILLING, form_structure()->field(9)->Type().group());
   2096   EXPECT_EQ(ADDRESS_HOME_STATE,
   2097             form_structure()->field(16)->Type().GetStorableType());
   2098   EXPECT_EQ(ADDRESS_HOME, form_structure()->field(16)->Type().group());
   2099 }
   2100 
   2101 TEST_F(AutofillDialogControllerTest, SaveDetailsInChrome) {
   2102   SwitchToAutofill();
   2103   EXPECT_CALL(*controller()->GetView(), ModelChanged()).Times(2);
   2104 
   2105   AutofillProfile full_profile(test::GetVerifiedProfile());
   2106   controller()->GetTestingManager()->AddTestingProfile(&full_profile);
   2107 
   2108   CreditCard card(test::GetVerifiedCreditCard());
   2109   controller()->GetTestingManager()->AddTestingCreditCard(&card);
   2110   EXPECT_FALSE(controller()->ShouldOfferToSaveInChrome());
   2111 
   2112   controller()->EditClickedForSection(SECTION_EMAIL);
   2113   EXPECT_TRUE(controller()->ShouldOfferToSaveInChrome());
   2114 
   2115   controller()->EditCancelledForSection(SECTION_EMAIL);
   2116   EXPECT_FALSE(controller()->ShouldOfferToSaveInChrome());
   2117 
   2118   controller()->MenuModelForSection(SECTION_EMAIL)->ActivatedAt(1);
   2119   EXPECT_TRUE(controller()->ShouldOfferToSaveInChrome());
   2120 
   2121   profile()->set_incognito(true);
   2122   EXPECT_FALSE(controller()->ShouldOfferToSaveInChrome());
   2123 }
   2124 
   2125 // Tests that user is prompted when using instrument with minimal address.
   2126 TEST_F(AutofillDialogControllerTest, UpgradeMinimalAddress) {
   2127   // A minimal address being selected should trigger error validation in the
   2128   // view. Called once for each incomplete suggestion.
   2129   EXPECT_CALL(*controller()->GetView(), UpdateForErrors()).Times(1);
   2130 
   2131   scoped_ptr<wallet::WalletItems> wallet_items = wallet::GetTestWalletItems();
   2132   wallet_items->AddInstrument(wallet::GetTestMaskedInstrumentWithIdAndAddress(
   2133       "id", wallet::GetTestMinimalAddress()));
   2134   scoped_ptr<wallet::Address> address(wallet::GetTestShippingAddress());
   2135   address->set_is_complete_address(false);
   2136   wallet_items->AddAddress(address.Pass());
   2137   controller()->OnDidGetWalletItems(wallet_items.Pass());
   2138 
   2139   // Assert that dialog's SECTION_CC_BILLING section is in edit mode.
   2140   ASSERT_TRUE(controller()->IsEditingExistingData(SECTION_CC_BILLING));
   2141   // Shipping section should be in edit mode because of
   2142   // is_minimal_shipping_address.
   2143   ASSERT_TRUE(controller()->IsEditingExistingData(SECTION_SHIPPING));
   2144 }
   2145 
   2146 TEST_F(AutofillDialogControllerTest, RiskNeverLoadsWithPendingLegalDocuments) {
   2147   EXPECT_CALL(*controller(), LoadRiskFingerprintData()).Times(0);
   2148 
   2149   scoped_ptr<wallet::WalletItems> wallet_items = wallet::GetTestWalletItems();
   2150   wallet_items->AddLegalDocument(wallet::GetTestLegalDocument());
   2151   controller()->OnDidGetWalletItems(wallet_items.Pass());
   2152   controller()->OnAccept();
   2153 }
   2154 
   2155 TEST_F(AutofillDialogControllerTest, RiskLoadsAfterAcceptingLegalDocuments) {
   2156   EXPECT_CALL(*controller(), LoadRiskFingerprintData()).Times(0);
   2157 
   2158   scoped_ptr<wallet::WalletItems> wallet_items = wallet::GetTestWalletItems();
   2159   wallet_items->AddLegalDocument(wallet::GetTestLegalDocument());
   2160   controller()->OnDidGetWalletItems(wallet_items.Pass());
   2161 
   2162   testing::Mock::VerifyAndClear(controller());
   2163   EXPECT_CALL(*controller(), LoadRiskFingerprintData()).Times(1);
   2164 
   2165   controller()->OnAccept();
   2166 
   2167   // Simulate a risk load and verify |GetRiskData()| matches the encoded value.
   2168   controller()->OnDidAcceptLegalDocuments();
   2169   controller()->OnDidLoadRiskFingerprintData(GetFakeFingerprint().Pass());
   2170   EXPECT_EQ(kFakeFingerprintEncoded, controller()->GetRiskData());
   2171 }
   2172 
   2173 TEST_F(AutofillDialogControllerTest, NoManageMenuItemForNewWalletUsers) {
   2174   // Make sure the menu model item is created for a returning Wallet user.
   2175   scoped_ptr<wallet::WalletItems> wallet_items = wallet::GetTestWalletItems();
   2176   wallet_items->AddInstrument(wallet::GetTestMaskedInstrument());
   2177   wallet_items->AddAddress(wallet::GetTestShippingAddress());
   2178   controller()->OnDidGetWalletItems(wallet_items.Pass());
   2179 
   2180   EXPECT_TRUE(controller()->MenuModelForSection(SECTION_CC_BILLING));
   2181   // "Same as billing", "123 address", "Add address...", and "Manage addresses".
   2182   EXPECT_EQ(
   2183       4, controller()->MenuModelForSection(SECTION_SHIPPING)->GetItemCount());
   2184 
   2185   // Make sure the menu model item is not created for new Wallet users.
   2186   base::DictionaryValue dict;
   2187   scoped_ptr<base::ListValue> required_actions(new base::ListValue);
   2188   required_actions->AppendString("setup_wallet");
   2189   dict.Set("required_action", required_actions.release());
   2190   controller()->OnDidGetWalletItems(
   2191       wallet::WalletItems::CreateWalletItems(dict).Pass());
   2192 
   2193   EXPECT_FALSE(controller()->MenuModelForSection(SECTION_CC_BILLING));
   2194   // "Same as billing" and "Add address...".
   2195   EXPECT_EQ(
   2196       2, controller()->MenuModelForSection(SECTION_SHIPPING)->GetItemCount());
   2197 }
   2198 
   2199 TEST_F(AutofillDialogControllerTest, ShippingSectionCanBeHidden) {
   2200   SwitchToAutofill();
   2201 
   2202   FormFieldData email_field;
   2203   email_field.autocomplete_attribute = "email";
   2204   FormFieldData cc_field;
   2205   cc_field.autocomplete_attribute = "cc-number";
   2206   FormFieldData billing_field;
   2207   billing_field.autocomplete_attribute = "billing region";
   2208 
   2209   FormData form_data;
   2210   form_data.fields.push_back(email_field);
   2211   form_data.fields.push_back(cc_field);
   2212   form_data.fields.push_back(billing_field);
   2213 
   2214   AutofillProfile full_profile(test::GetVerifiedProfile());
   2215   controller()->GetTestingManager()->AddTestingProfile(&full_profile);
   2216   SetUpControllerWithFormData(form_data);
   2217   EXPECT_FALSE(controller()->SectionIsActive(SECTION_SHIPPING));
   2218 
   2219   FillCreditCardInputs();
   2220   controller()->OnAccept();
   2221   EXPECT_TRUE(form_structure());
   2222 }
   2223 
   2224 TEST_F(AutofillDialogControllerTest, ShippingSectionCanBeHiddenForWallet) {
   2225   SwitchToWallet();
   2226 
   2227   FormFieldData email_field;
   2228   email_field.autocomplete_attribute = "email";
   2229   FormFieldData cc_field;
   2230   cc_field.autocomplete_attribute = "cc-number";
   2231   FormFieldData billing_field;
   2232   billing_field.autocomplete_attribute = "billing region";
   2233 
   2234   FormData form_data;
   2235   form_data.fields.push_back(email_field);
   2236   form_data.fields.push_back(cc_field);
   2237   form_data.fields.push_back(billing_field);
   2238 
   2239   SetUpControllerWithFormData(form_data);
   2240   EXPECT_FALSE(controller()->SectionIsActive(SECTION_SHIPPING));
   2241   EXPECT_FALSE(controller()->IsShippingAddressRequired());
   2242 
   2243   EXPECT_CALL(*controller()->GetTestingWalletClient(),
   2244               GetFullWallet(_)).Times(1);
   2245   scoped_ptr<wallet::WalletItems> wallet_items = wallet::GetTestWalletItems();
   2246   wallet_items->AddInstrument(wallet::GetTestMaskedInstrument());
   2247   SubmitWithWalletItems(wallet_items.Pass());
   2248   controller()->OnDidGetFullWallet(wallet::GetTestFullWalletInstrumentOnly());
   2249   EXPECT_TRUE(form_structure());
   2250 }
   2251 
   2252 TEST_F(AutofillDialogControllerTest, NotProdNotification) {
   2253   // To make IsPayingWithWallet() true.
   2254   controller()->OnDidGetWalletItems(wallet::GetTestWalletItems());
   2255 
   2256   CommandLine* command_line = CommandLine::ForCurrentProcess();
   2257   ASSERT_FALSE(command_line->HasSwitch(switches::kWalletServiceUseProd));
   2258   EXPECT_FALSE(
   2259       NotificationsOfType(DialogNotification::DEVELOPER_WARNING).empty());
   2260 
   2261   command_line->AppendSwitch(switches::kWalletServiceUseProd);
   2262   EXPECT_TRUE(
   2263       NotificationsOfType(DialogNotification::DEVELOPER_WARNING).empty());
   2264 }
   2265 
   2266 // Ensure Wallet instruments marked expired by the server are shown as invalid.
   2267 TEST_F(AutofillDialogControllerTest, WalletExpiredCard) {
   2268   scoped_ptr<wallet::WalletItems> wallet_items = wallet::GetTestWalletItems();
   2269   wallet_items->AddInstrument(wallet::GetTestMaskedInstrumentExpired());
   2270   controller()->OnDidGetWalletItems(wallet_items.Pass());
   2271 
   2272   EXPECT_TRUE(controller()->IsEditingExistingData(SECTION_CC_BILLING));
   2273 
   2274   // Use |SetOutputValue()| to put the right ServerFieldTypes into the map.
   2275   const DetailInputs& inputs =
   2276       controller()->RequestedFieldsForSection(SECTION_CC_BILLING);
   2277   DetailOutputMap outputs;
   2278   SetOutputValue(inputs, &outputs, COMPANY_NAME, ASCIIToUTF16("Bluth Company"));
   2279 
   2280   ValidityData validity_data =
   2281       controller()->InputsAreValid(SECTION_CC_BILLING, outputs, VALIDATE_EDIT);
   2282   EXPECT_EQ(1U, validity_data.count(CREDIT_CARD_EXP_MONTH));
   2283   EXPECT_EQ(1U, validity_data.count(CREDIT_CARD_EXP_4_DIGIT_YEAR));
   2284 
   2285   // Make the local input year differ from the instrument.
   2286   SetOutputValue(inputs, &outputs, CREDIT_CARD_EXP_4_DIGIT_YEAR,
   2287                  ASCIIToUTF16("3002"));
   2288 
   2289   validity_data =
   2290       controller()->InputsAreValid(SECTION_CC_BILLING, outputs, VALIDATE_EDIT);
   2291   EXPECT_EQ(0U, validity_data.count(CREDIT_CARD_EXP_MONTH));
   2292   EXPECT_EQ(0U, validity_data.count(CREDIT_CARD_EXP_4_DIGIT_YEAR));
   2293 
   2294   // Make the local input month differ from the instrument.
   2295   SetOutputValue(inputs, &outputs, CREDIT_CARD_EXP_MONTH, ASCIIToUTF16("06"));
   2296 
   2297   validity_data =
   2298       controller()->InputsAreValid(SECTION_CC_BILLING, outputs, VALIDATE_EDIT);
   2299   EXPECT_EQ(0U, validity_data.count(CREDIT_CARD_EXP_MONTH));
   2300   EXPECT_EQ(0U, validity_data.count(CREDIT_CARD_EXP_4_DIGIT_YEAR));
   2301 }
   2302 
   2303 TEST_F(AutofillDialogControllerTest, ChooseAnotherInstrumentOrAddress) {
   2304   SubmitWithWalletItems(CompleteAndValidWalletItems());
   2305 
   2306   EXPECT_EQ(0U, NotificationsOfType(
   2307       DialogNotification::REQUIRED_ACTION).size());
   2308   EXPECT_CALL(*controller()->GetTestingWalletClient(),
   2309               GetWalletItems(_)).Times(1);
   2310   controller()->OnDidGetFullWallet(
   2311       CreateFullWallet("choose_another_instrument_or_address"));
   2312   EXPECT_EQ(1U, NotificationsOfType(
   2313       DialogNotification::REQUIRED_ACTION).size());
   2314   controller()->OnDidGetWalletItems(CompleteAndValidWalletItems());
   2315 
   2316   controller()->OnAccept();
   2317   EXPECT_EQ(0U, NotificationsOfType(
   2318       DialogNotification::REQUIRED_ACTION).size());
   2319 }
   2320 
   2321 // Make sure detailed steps for Autocheckout are added
   2322 // and updated correctly.
   2323 TEST_F(AutofillDialogControllerTest, DetailedSteps) {
   2324   EXPECT_CALL(*controller()->GetTestingWalletClient(),
   2325               GetFullWallet(_)).Times(1);
   2326 
   2327   controller()->set_dialog_type(DIALOG_TYPE_AUTOCHECKOUT);
   2328 
   2329   // Add steps as would normally be done by the AutocheckoutManager.
   2330   controller()->AddAutocheckoutStep(AUTOCHECKOUT_STEP_SHIPPING);
   2331   controller()->AddAutocheckoutStep(AUTOCHECKOUT_STEP_DELIVERY);
   2332   controller()->AddAutocheckoutStep(AUTOCHECKOUT_STEP_BILLING);
   2333 
   2334   scoped_ptr<wallet::WalletItems> wallet_items = wallet::GetTestWalletItems();
   2335   wallet_items->AddInstrument(wallet::GetTestMaskedInstrument());
   2336   wallet_items->AddAddress(wallet::GetTestShippingAddress());
   2337   controller()->OnDidGetWalletItems(wallet_items.Pass());
   2338   // Initiate flow - should add proxy card step since the user is using wallet
   2339   // data.
   2340   controller()->OnAccept();
   2341   EXPECT_TRUE(ReadSetVisuallyDeemphasizedIpc());
   2342   controller()->OnDidLoadRiskFingerprintData(GetFakeFingerprint().Pass());
   2343 
   2344   SuggestionState suggestion_state =
   2345       controller()->SuggestionStateForSection(SECTION_CC_BILLING);
   2346   EXPECT_TRUE(suggestion_state.extra_text.empty());
   2347 
   2348   // There should be four steps total, with the first being the card generation
   2349   // step added by the dialog controller.
   2350   EXPECT_EQ(4U, controller()->CurrentAutocheckoutSteps().size());
   2351   EXPECT_EQ(AUTOCHECKOUT_STEP_PROXY_CARD,
   2352             controller()->CurrentAutocheckoutSteps()[0].type());
   2353   EXPECT_EQ(AUTOCHECKOUT_STEP_STARTED,
   2354             controller()->CurrentAutocheckoutSteps()[0].status());
   2355 
   2356   // Simulate a wallet error. This should remove the card generation step from
   2357   // the flow, as we will have to proceed with local data.
   2358   controller()->OnWalletError(wallet::WalletClient::UNKNOWN_ERROR);
   2359 
   2360   AutofillProfile shipping_profile(test::GetVerifiedProfile());
   2361   AutofillProfile billing_profile(test::GetVerifiedProfile2());
   2362   CreditCard credit_card(test::GetVerifiedCreditCard());
   2363   controller()->GetTestingManager()->AddTestingProfile(&shipping_profile);
   2364   controller()->GetTestingManager()->AddTestingProfile(&billing_profile);
   2365   controller()->GetTestingManager()->AddTestingCreditCard(&credit_card);
   2366   ui::MenuModel* billing_model =
   2367       controller()->MenuModelForSection(SECTION_BILLING);
   2368   billing_model->ActivatedAt(1);
   2369 
   2370   // Re-initiate flow.
   2371   controller()->OnAccept();
   2372   EXPECT_TRUE(ReadSetVisuallyDeemphasizedIpc());
   2373 
   2374   // All steps should be initially unstarted.
   2375   EXPECT_EQ(3U, controller()->CurrentAutocheckoutSteps().size());
   2376   EXPECT_EQ(AUTOCHECKOUT_STEP_SHIPPING,
   2377             controller()->CurrentAutocheckoutSteps()[0].type());
   2378   EXPECT_EQ(AUTOCHECKOUT_STEP_UNSTARTED,
   2379             controller()->CurrentAutocheckoutSteps()[0].status());
   2380   EXPECT_EQ(AUTOCHECKOUT_STEP_DELIVERY,
   2381             controller()->CurrentAutocheckoutSteps()[1].type());
   2382   EXPECT_EQ(AUTOCHECKOUT_STEP_UNSTARTED,
   2383             controller()->CurrentAutocheckoutSteps()[1].status());
   2384   EXPECT_EQ(AUTOCHECKOUT_STEP_BILLING,
   2385             controller()->CurrentAutocheckoutSteps()[2].type());
   2386   EXPECT_EQ(AUTOCHECKOUT_STEP_UNSTARTED,
   2387             controller()->CurrentAutocheckoutSteps()[2].status());
   2388 
   2389   // Update steps in the same manner that we would expect to see from the
   2390   // AutocheckoutManager while progressing through a flow.
   2391   controller()->UpdateAutocheckoutStep(AUTOCHECKOUT_STEP_SHIPPING,
   2392                                        AUTOCHECKOUT_STEP_STARTED);
   2393   controller()->UpdateAutocheckoutStep(AUTOCHECKOUT_STEP_SHIPPING,
   2394                                        AUTOCHECKOUT_STEP_COMPLETED);
   2395   controller()->UpdateAutocheckoutStep(AUTOCHECKOUT_STEP_DELIVERY,
   2396                                        AUTOCHECKOUT_STEP_STARTED);
   2397 
   2398   // Verify that the steps were appropriately updated.
   2399   EXPECT_EQ(3U, controller()->CurrentAutocheckoutSteps().size());
   2400   EXPECT_EQ(AUTOCHECKOUT_STEP_SHIPPING,
   2401             controller()->CurrentAutocheckoutSteps()[0].type());
   2402   EXPECT_EQ(AUTOCHECKOUT_STEP_COMPLETED,
   2403             controller()->CurrentAutocheckoutSteps()[0].status());
   2404   EXPECT_EQ(AUTOCHECKOUT_STEP_DELIVERY,
   2405             controller()->CurrentAutocheckoutSteps()[1].type());
   2406   EXPECT_EQ(AUTOCHECKOUT_STEP_STARTED,
   2407             controller()->CurrentAutocheckoutSteps()[1].status());
   2408   EXPECT_EQ(AUTOCHECKOUT_STEP_BILLING,
   2409             controller()->CurrentAutocheckoutSteps()[2].type());
   2410   EXPECT_EQ(AUTOCHECKOUT_STEP_UNSTARTED,
   2411             controller()->CurrentAutocheckoutSteps()[2].status());
   2412 
   2413   controller()->ViewClosed();
   2414   EXPECT_FALSE(ReadSetVisuallyDeemphasizedIpc());
   2415 }
   2416 
   2417 TEST_F(AutofillDialogControllerTest, NewCardBubbleShown) {
   2418   EXPECT_CALL(*test_generated_bubble_controller(), SetupAndShow(_, _)).Times(0);
   2419 
   2420   SwitchToAutofill();
   2421   FillCreditCardInputs();
   2422   controller()->OnAccept();
   2423   controller()->ViewClosed();
   2424 
   2425   EXPECT_EQ(1, mock_new_card_bubble_controller()->bubbles_shown());
   2426 }
   2427 
   2428 TEST_F(AutofillDialogControllerTest, GeneratedCardBubbleShown) {
   2429   EXPECT_CALL(*test_generated_bubble_controller(), SetupAndShow(_, _)).Times(1);
   2430 
   2431   SubmitWithWalletItems(CompleteAndValidWalletItems());
   2432   controller()->OnDidGetFullWallet(wallet::GetTestFullWallet());
   2433   controller()->ViewClosed();
   2434 
   2435   EXPECT_EQ(0, mock_new_card_bubble_controller()->bubbles_shown());
   2436 }
   2437 
   2438 TEST_F(AutofillDialogControllerTest, ReloadWalletItemsOnActivation) {
   2439   // Switch into Wallet mode and initialize some Wallet data.
   2440   SwitchToWallet();
   2441 
   2442   scoped_ptr<wallet::WalletItems> wallet_items = wallet::GetTestWalletItems();
   2443   wallet_items->AddInstrument(wallet::GetTestMaskedInstrument());
   2444   wallet_items->AddInstrument(wallet::GetTestNonDefaultMaskedInstrument());
   2445   wallet_items->AddAddress(wallet::GetTestNonDefaultShippingAddress());
   2446   wallet_items->AddAddress(wallet::GetTestShippingAddress());
   2447   controller()->OnDidGetWalletItems(wallet_items.Pass());
   2448 
   2449   // Initially, the default entries should be selected.
   2450   ui::MenuModel* cc_billing_model =
   2451       controller()->MenuModelForSection(SECTION_CC_BILLING);
   2452   ui::MenuModel* shipping_model =
   2453       controller()->MenuModelForSection(SECTION_SHIPPING);
   2454   // "add", "manage", and 2 suggestions.
   2455   ASSERT_EQ(4, cc_billing_model->GetItemCount());
   2456   EXPECT_TRUE(cc_billing_model->IsItemCheckedAt(0));
   2457   // "use billing", "add", "manage", and 2 suggestions.
   2458   ASSERT_EQ(5, shipping_model->GetItemCount());
   2459   EXPECT_TRUE(shipping_model->IsItemCheckedAt(2));
   2460 
   2461   // Select entries other than the defaults.
   2462   cc_billing_model->ActivatedAt(1);
   2463   shipping_model->ActivatedAt(1);
   2464   // "add", "manage", and 2 suggestions.
   2465   ASSERT_EQ(4, cc_billing_model->GetItemCount());
   2466   EXPECT_TRUE(cc_billing_model->IsItemCheckedAt(1));
   2467   // "use billing", "add", "manage", and 2 suggestions.
   2468   ASSERT_EQ(5, shipping_model->GetItemCount());
   2469   EXPECT_TRUE(shipping_model-> IsItemCheckedAt(1));
   2470 
   2471   // Simulate switching away from the tab and back.  This should issue a request
   2472   // for wallet items.
   2473   EXPECT_CALL(*controller()->GetTestingWalletClient(), GetWalletItems(_));
   2474   controller()->TabActivated();
   2475 
   2476   // Simulate a response that includes different items.
   2477   wallet_items = wallet::GetTestWalletItems();
   2478   wallet_items->AddInstrument(wallet::GetTestMaskedInstrumentExpired());
   2479   wallet_items->AddInstrument(wallet::GetTestMaskedInstrument());
   2480   wallet_items->AddInstrument(wallet::GetTestNonDefaultMaskedInstrument());
   2481   wallet_items->AddAddress(wallet::GetTestNonDefaultShippingAddress());
   2482   controller()->OnDidGetWalletItems(wallet_items.Pass());
   2483 
   2484   // The previously selected entries should still be selected.
   2485   // "add", "manage", and 3 suggestions.
   2486   ASSERT_EQ(5, cc_billing_model->GetItemCount());
   2487   EXPECT_TRUE(cc_billing_model->IsItemCheckedAt(2));
   2488   // "use billing", "add", "manage", and 1 suggestion.
   2489   ASSERT_EQ(4, shipping_model->GetItemCount());
   2490   EXPECT_TRUE(shipping_model->IsItemCheckedAt(1));
   2491 }
   2492 
   2493 TEST_F(AutofillDialogControllerTest, ReloadWithEmptyWalletItems) {
   2494   SwitchToWallet();
   2495 
   2496   controller()->OnDidGetWalletItems(CompleteAndValidWalletItems());
   2497   controller()->MenuModelForSection(SECTION_CC_BILLING)->ActivatedAt(1);
   2498   controller()->MenuModelForSection(SECTION_SHIPPING)->ActivatedAt(1);
   2499 
   2500   EXPECT_CALL(*controller()->GetTestingWalletClient(), GetWalletItems(_));
   2501   controller()->TabActivated();
   2502 
   2503   controller()->OnDidGetWalletItems(wallet::GetTestWalletItems());
   2504 
   2505   EXPECT_FALSE(controller()->MenuModelForSection(SECTION_CC_BILLING));
   2506   EXPECT_EQ(
   2507       3, controller()->MenuModelForSection(SECTION_SHIPPING)->GetItemCount());
   2508 }
   2509 
   2510 TEST_F(AutofillDialogControllerTest, GeneratedCardBubbleNotShown) {
   2511   EXPECT_CALL(*test_generated_bubble_controller(), SetupAndShow(_, _)).Times(0);
   2512 
   2513   SubmitWithWalletItems(CompleteAndValidWalletItems());
   2514   controller()->set_dialog_type(DIALOG_TYPE_AUTOCHECKOUT);
   2515   controller()->OnDidGetFullWallet(wallet::GetTestFullWallet());
   2516   controller()->OnAutocheckoutError();
   2517   controller()->ViewClosed();
   2518 
   2519   EXPECT_EQ(0, mock_new_card_bubble_controller()->bubbles_shown());
   2520 }
   2521 
   2522 }  // namespace autofill
   2523