Home | History | Annotate | Download | only in wallet
      1 // Copyright 2013 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 "base/json/json_reader.h"
      6 #include "base/json/json_writer.h"
      7 #include "base/logging.h"
      8 #include "base/memory/scoped_ptr.h"
      9 #include "base/message_loop/message_loop.h"
     10 #include "base/run_loop.h"
     11 #include "base/strings/string_number_conversions.h"
     12 #include "base/strings/string_split.h"
     13 #include "base/strings/string_util.h"
     14 #include "base/strings/stringprintf.h"
     15 #include "base/values.h"
     16 #include "components/autofill/content/browser/wallet/full_wallet.h"
     17 #include "components/autofill/content/browser/wallet/instrument.h"
     18 #include "components/autofill/content/browser/wallet/wallet_client.h"
     19 #include "components/autofill/content/browser/wallet/wallet_client_delegate.h"
     20 #include "components/autofill/content/browser/wallet/wallet_items.h"
     21 #include "components/autofill/content/browser/wallet/wallet_test_util.h"
     22 #include "components/autofill/core/browser/autofill_metrics.h"
     23 #include "content/public/test/test_browser_thread_bundle.h"
     24 #include "net/base/escape.h"
     25 #include "net/base/net_errors.h"
     26 #include "net/http/http_request_headers.h"
     27 #include "net/http/http_status_code.h"
     28 #include "net/url_request/test_url_fetcher_factory.h"
     29 #include "net/url_request/url_fetcher_delegate.h"
     30 #include "net/url_request/url_request_status.h"
     31 #include "net/url_request/url_request_test_util.h"
     32 #include "testing/gmock/include/gmock/gmock.h"
     33 #include "testing/gtest/include/gtest/gtest.h"
     34 #include "url/gurl.h"
     35 
     36 namespace autofill {
     37 namespace wallet {
     38 
     39 namespace {
     40 
     41 const char kGoogleTransactionId[] = "google-transaction-id";
     42 const char kMerchantUrl[] = "https://example.com/path?key=value";
     43 
     44 const char kGetFullWalletValidResponse[] =
     45     "{"
     46     "  \"expiration_month\":12,"
     47     "  \"expiration_year\":3000,"
     48     "  \"iin\":\"iin\","
     49     "  \"rest\":\"rest\","
     50     "  \"billing_address\":"
     51     "  {"
     52     "    \"id\":\"id\","
     53     "    \"phone_number\":\"phone_number\","
     54     "    \"postal_address\":"
     55     "    {"
     56     "      \"recipient_name\":\"recipient_name\","
     57     "      \"address_line\":"
     58     "      ["
     59     "        \"address_line_1\","
     60     "        \"address_line_2\""
     61     "      ],"
     62     "      \"locality_name\":\"locality_name\","
     63     "      \"administrative_area_name\":\"administrative_area_name\","
     64     "      \"postal_code_number\":\"postal_code_number\","
     65     "      \"country_name_code\":\"US\","
     66     "      \"language_code\":\"language_code\""
     67     "    }"
     68     "  },"
     69     "  \"shipping_address\":"
     70     "  {"
     71     "    \"id\":\"ship_id\","
     72     "    \"phone_number\":\"ship_phone_number\","
     73     "    \"postal_address\":"
     74     "    {"
     75     "      \"recipient_name\":\"ship_recipient_name\","
     76     "      \"address_line\":"
     77     "      ["
     78     "        \"ship_address_line_1\","
     79     "        \"ship_address_line_2\""
     80     "      ],"
     81     "      \"locality_name\":\"ship_locality_name\","
     82     "      \"administrative_area_name\":\"ship_administrative_area_name\","
     83     "      \"postal_code_number\":\"ship_postal_code_number\","
     84     "      \"country_name_code\":\"US\","
     85     "      \"language_code\":\"ship_language_code\""
     86     "    }"
     87     "  },"
     88     "  \"required_action\":"
     89     "  ["
     90     "  ]"
     91     "}";
     92 
     93 const char kGetFullWalletInvalidResponse[] =
     94     "{"
     95     "  \"garbage\":123"
     96     "}";
     97 
     98 const char kGetWalletItemsValidResponse[] =
     99     "{"
    100     "  \"required_action\":"
    101     "  ["
    102     "  ],"
    103     "  \"google_transaction_id\":\"google_transaction_id\","
    104     "  \"instrument\":"
    105     "  ["
    106     "    {"
    107     "      \"descriptive_name\":\"descriptive_name\","
    108     "      \"type\":\"VISA\","
    109     "      \"last_four_digits\":\"4111\","
    110     "      \"expiration_month\":12,"
    111     "      \"expiration_year\":3000,"
    112     "      \"brand\":\"monkeys\","
    113     "      \"billing_address\":"
    114     "      {"
    115     "        \"name\":\"name\","
    116     "        \"address1\":\"address1\","
    117     "        \"address2\":\"address2\","
    118     "        \"city\":\"city\","
    119     "        \"state\":\"state\","
    120     "        \"postal_code\":\"postal_code\","
    121     "        \"phone_number\":\"phone_number\","
    122     "        \"country_code\":\"US\","
    123     "        \"language_code\":\"language_code\""
    124     "      },"
    125     "      \"status\":\"VALID\","
    126     "      \"object_id\":\"default_instrument_id\""
    127     "    }"
    128     "  ],"
    129     "  \"default_instrument_id\":\"default_instrument_id\","
    130     "  \"obfuscated_gaia_id\":\"obfuscated_gaia_id\","
    131     "  \"address\":"
    132     "  ["
    133     "  ],"
    134     "  \"default_address_id\":\"default_address_id\","
    135     "  \"required_legal_document\":"
    136     "  ["
    137     "  ]"
    138     "}";
    139 
    140 const char kSaveAddressValidResponse[] =
    141     "{"
    142     "  \"shipping_address_id\":\"saved_address_id\""
    143     "}";
    144 
    145 const char kSaveAddressWithRequiredActionsValidResponse[] =
    146     "{"
    147     "  \"form_field_error\":"
    148     "  ["
    149     "    {"
    150     "      \"location\":\"SHIPPING_ADDRESS\","
    151     "      \"type\":\"INVALID_POSTAL_CODE\""
    152     "    }"
    153     "  ],"
    154     "  \"required_action\":"
    155     "  ["
    156     "    \"  \\treqUIRE_PhOnE_number   \\n\\r\","
    157     "    \"INVALID_form_field\""
    158     "  ]"
    159     "}";
    160 
    161 const char kSaveWithInvalidRequiredActionsResponse[] =
    162     "{"
    163     "  \"required_action\":"
    164     "  ["
    165     "    \"  setup_wallet\","
    166     "    \"  \\treqUIRE_PhOnE_number   \\n\\r\","
    167     "    \"INVALID_form_field\""
    168     "  ]"
    169     "}";
    170 
    171 const char kSaveInvalidResponse[] =
    172     "{"
    173     "  \"garbage\":123"
    174     "}";
    175 
    176 const char kSaveInstrumentValidResponse[] =
    177     "{"
    178     "  \"instrument_id\":\"instrument_id\""
    179     "}";
    180 
    181 const char kSaveInstrumentWithRequiredActionsValidResponse[] =
    182     "{"
    183     "  \"form_field_error\":"
    184     "  ["
    185     "    {"
    186     "      \"location\":\"SHIPPING_ADDRESS\","
    187     "      \"type\":\"INVALID_POSTAL_CODE\""
    188     "    }"
    189     "  ],"
    190     "  \"required_action\":"
    191     "  ["
    192     "    \"  \\treqUIRE_PhOnE_number   \\n\\r\","
    193     "    \"INVALID_form_field\""
    194     "  ]"
    195     "}";
    196 
    197 const char kSaveInstrumentAndAddressValidResponse[] =
    198     "{"
    199     "  \"shipping_address_id\":\"saved_address_id\","
    200     "  \"instrument_id\":\"saved_instrument_id\""
    201     "}";
    202 
    203 const char kSaveInstrumentAndAddressWithRequiredActionsValidResponse[] =
    204     "{"
    205     "  \"form_field_error\":"
    206     "  ["
    207     "    {"
    208     "      \"location\":\"SHIPPING_ADDRESS\","
    209     "      \"type\":\"INVALID_POSTAL_CODE\""
    210     "    }"
    211     "  ],"
    212     "  \"required_action\":"
    213     "  ["
    214     "    \"  \\treqUIRE_PhOnE_number   \\n\\r\","
    215     "    \"INVALID_form_field\""
    216     "  ]"
    217     "}";
    218 
    219 const char kUpdateInstrumentValidResponse[] =
    220     "{"
    221     "  \"instrument_id\":\"instrument_id\""
    222     "}";
    223 
    224 const char kUpdateAddressValidResponse[] =
    225     "{"
    226     "  \"shipping_address_id\":\"shipping_address_id\""
    227     "}";
    228 
    229 const char kUpdateWithRequiredActionsValidResponse[] =
    230     "{"
    231     "  \"form_field_error\":"
    232     "  ["
    233     "    {"
    234     "      \"location\":\"SHIPPING_ADDRESS\","
    235     "      \"type\":\"INVALID_POSTAL_CODE\""
    236     "    }"
    237     "  ],"
    238     "  \"required_action\":"
    239     "  ["
    240     "    \"  \\treqUIRE_PhOnE_number   \\n\\r\","
    241     "    \"INVALID_form_field\""
    242     "  ]"
    243     "}";
    244 
    245 const char kUpdateMalformedResponse[] =
    246     "{"
    247     "  \"cheese\":\"monkeys\""
    248     "}";
    249 
    250 const char kAuthenticateInstrumentFailureResponse[] =
    251     "{"
    252     "  \"auth_result\":\"anything else\""
    253     "}";
    254 
    255 const char kAuthenticateInstrumentSuccessResponse[] =
    256     "{"
    257     "  \"auth_result\":\"SUCCESS\""
    258     "}";
    259 
    260 const char kErrorResponse[] =
    261     "{"
    262     "  \"error_type\":\"APPLICATION_ERROR\","
    263     "  \"error_detail\":\"error_detail\","
    264     "  \"application_error\":\"application_error\","
    265     "  \"debug_data\":"
    266     "  {"
    267     "    \"debug_message\":\"debug_message\","
    268     "    \"stack_trace\":\"stack_trace\""
    269     "  },"
    270     "  \"application_error_data\":\"application_error_data\","
    271     "  \"wallet_error\":"
    272     "  {"
    273     "    \"error_type\":\"SERVICE_UNAVAILABLE\","
    274     "    \"error_detail\":\"error_detail\","
    275     "    \"message_for_user\":"
    276     "    {"
    277     "      \"text\":\"text\","
    278     "      \"subtext\":\"subtext\","
    279     "      \"details\":\"details\""
    280     "    }"
    281     "  }"
    282     "}";
    283 
    284 const char kErrorTypeMissingInResponse[] =
    285     "{"
    286     "  \"error_type\":\"Not APPLICATION_ERROR\","
    287     "  \"error_detail\":\"error_detail\","
    288     "  \"application_error\":\"application_error\","
    289     "  \"debug_data\":"
    290     "  {"
    291     "    \"debug_message\":\"debug_message\","
    292     "    \"stack_trace\":\"stack_trace\""
    293     "  },"
    294     "  \"application_error_data\":\"application_error_data\""
    295     "}";
    296 
    297 // The JSON below is used to test against the request payload being sent to
    298 // Online Wallet. It's indented differently since JSONWriter creates compact
    299 // JSON from DictionaryValues. NB: The values must be alphabetical to pass
    300 // the tests.
    301 
    302 const char kAcceptLegalDocumentsValidRequest[] =
    303     "{"
    304         "\"accepted_legal_document\":"
    305         "["
    306             "\"doc_id_1\","
    307             "\"doc_id_2\""
    308         "],"
    309         "\"google_transaction_id\":\"google-transaction-id\","
    310         "\"merchant_domain\":\"https://example.com/\""
    311     "}";
    312 
    313 const char kAuthenticateInstrumentValidRequest[] =
    314     "{"
    315         "\"instrument_id\":\"instrument_id\","
    316         "\"risk_params\":\"risky business\""
    317     "}";
    318 
    319 const char kGetFullWalletValidRequest[] =
    320     "{"
    321         "\"feature\":\"REQUEST_AUTOCOMPLETE\","
    322         "\"google_transaction_id\":\"google_transaction_id\","
    323         "\"merchant_domain\":\"https://example.com/\","
    324         "\"new_wallet_user\":false,"
    325         "\"phone_number_required\":true,"
    326         "\"risk_params\":\"risky business\","
    327         "\"selected_address_id\":\"shipping_address_id\","
    328         "\"selected_instrument_id\":\"instrument_id\","
    329         "\"supported_risk_challenge\":"
    330         "["
    331         "],"
    332         "\"use_minimal_addresses\":false"
    333     "}";
    334 
    335 const char kGetFullWalletValidRequestNewUser[] =
    336     "{"
    337         "\"feature\":\"REQUEST_AUTOCOMPLETE\","
    338         "\"google_transaction_id\":\"google_transaction_id\","
    339         "\"merchant_domain\":\"https://example.com/\","
    340         "\"new_wallet_user\":true,"
    341         "\"phone_number_required\":true,"
    342         "\"risk_params\":\"risky business\","
    343         "\"selected_address_id\":\"shipping_address_id\","
    344         "\"selected_instrument_id\":\"instrument_id\","
    345         "\"supported_risk_challenge\":"
    346         "["
    347         "],"
    348         "\"use_minimal_addresses\":false"
    349     "}";
    350 
    351 const char kGetFullWalletWithRiskCapabilitesValidRequest[] =
    352     "{"
    353         "\"feature\":\"REQUEST_AUTOCOMPLETE\","
    354         "\"google_transaction_id\":\"google_transaction_id\","
    355         "\"merchant_domain\":\"https://example.com/\","
    356         "\"new_wallet_user\":false,"
    357         "\"phone_number_required\":true,"
    358         "\"risk_params\":\"risky business\","
    359         "\"selected_address_id\":\"shipping_address_id\","
    360         "\"selected_instrument_id\":\"instrument_id\","
    361         "\"supported_risk_challenge\":"
    362         "["
    363             "\"VERIFY_CVC\""
    364         "],"
    365         "\"use_minimal_addresses\":false"
    366     "}";
    367 
    368 const char kGetWalletItemsValidRequest[] =
    369     "{"
    370         "\"merchant_domain\":\"https://example.com/\","
    371         "\"phone_number_required\":true,"
    372         "\"shipping_address_required\":true,"
    373         "\"use_minimal_addresses\":false"
    374     "}";
    375 
    376 const char kGetWalletItemsNoShippingRequest[] =
    377     "{"
    378         "\"merchant_domain\":\"https://example.com/\","
    379         "\"phone_number_required\":true,"
    380         "\"shipping_address_required\":false,"
    381         "\"use_minimal_addresses\":false"
    382     "}";
    383 
    384 const char kSaveAddressValidRequest[] =
    385     "{"
    386         "\"merchant_domain\":\"https://example.com/\","
    387         "\"phone_number_required\":true,"
    388         "\"risk_params\":\"risky business\","
    389         "\"shipping_address\":"
    390         "{"
    391             "\"phone_number\":\"save_phone_number\","
    392             "\"postal_address\":"
    393             "{"
    394                 "\"address_line\":"
    395                 "["
    396                     "\"save_address_line_1\","
    397                     "\"save_address_line_2\""
    398                 "],"
    399                 "\"administrative_area_name\":\"save_admin_area_name\","
    400                 "\"country_name_code\":\"US\","
    401                 "\"dependent_locality_name\":\"save_dependent_locality_name\","
    402                 "\"language_code\":\"save_language_code\","
    403                 "\"locality_name\":\"save_locality_name\","
    404                 "\"postal_code_number\":\"save_postal_code_number\","
    405                 "\"recipient_name\":\"save_recipient_name\","
    406                 "\"sorting_code\":\"save_sorting_code\""
    407             "}"
    408         "},"
    409         "\"use_minimal_addresses\":false"
    410     "}";
    411 
    412 const char kSaveInstrumentValidRequest[] =
    413     "{"
    414         "\"instrument\":"
    415         "{"
    416             "\"credit_card\":"
    417             "{"
    418                 "\"address\":"
    419                 "{"
    420                     "\"address_line\":"
    421                     "["
    422                         "\"address_line_1\","
    423                         "\"address_line_2\""
    424                     "],"
    425                     "\"administrative_area_name\":\"admin_area_name\","
    426                     "\"country_name_code\":\"US\","
    427                     "\"dependent_locality_name\":\"dependent_locality_name\","
    428                     "\"language_code\":\"language_code\","
    429                     "\"locality_name\":\"locality_name\","
    430                     "\"postal_code_number\":\"postal_code_number\","
    431                     "\"recipient_name\":\"recipient_name\","
    432                     "\"sorting_code\":\"sorting_code\""
    433                 "},"
    434                 "\"exp_month\":12,"
    435                 "\"exp_year\":3000,"
    436                 "\"fop_type\":\"VISA\","
    437                 "\"last_4_digits\":\"4448\""
    438             "},"
    439             "\"type\":\"CREDIT_CARD\""
    440         "},"
    441         "\"instrument_phone_number\":\"phone_number\","
    442         "\"merchant_domain\":\"https://example.com/\","
    443         "\"phone_number_required\":true,"
    444         "\"risk_params\":\"risky business\","
    445         "\"use_minimal_addresses\":false"
    446       "}";
    447 
    448 const char kSaveInstrumentAndAddressValidRequest[] =
    449     "{"
    450         "\"instrument\":"
    451         "{"
    452             "\"credit_card\":"
    453             "{"
    454                 "\"address\":"
    455                 "{"
    456                     "\"address_line\":"
    457                     "["
    458                         "\"address_line_1\","
    459                         "\"address_line_2\""
    460                     "],"
    461                     "\"administrative_area_name\":\"admin_area_name\","
    462                     "\"country_name_code\":\"US\","
    463                     "\"dependent_locality_name\":\"dependent_locality_name\","
    464                     "\"language_code\":\"language_code\","
    465                     "\"locality_name\":\"locality_name\","
    466                     "\"postal_code_number\":\"postal_code_number\","
    467                     "\"recipient_name\":\"recipient_name\","
    468                     "\"sorting_code\":\"sorting_code\""
    469                 "},"
    470                 "\"exp_month\":12,"
    471                 "\"exp_year\":3000,"
    472                 "\"fop_type\":\"VISA\","
    473                 "\"last_4_digits\":\"4448\""
    474             "},"
    475             "\"type\":\"CREDIT_CARD\""
    476         "},"
    477         "\"instrument_phone_number\":\"phone_number\","
    478         "\"merchant_domain\":\"https://example.com/\","
    479         "\"phone_number_required\":true,"
    480         "\"risk_params\":\"risky business\","
    481         "\"shipping_address\":"
    482         "{"
    483             "\"phone_number\":\"save_phone_number\","
    484             "\"postal_address\":"
    485             "{"
    486                 "\"address_line\":"
    487                 "["
    488                     "\"save_address_line_1\","
    489                     "\"save_address_line_2\""
    490                 "],"
    491                 "\"administrative_area_name\":\"save_admin_area_name\","
    492                 "\"country_name_code\":\"US\","
    493                 "\"dependent_locality_name\":\"save_dependent_locality_name\","
    494                 "\"language_code\":\"save_language_code\","
    495                 "\"locality_name\":\"save_locality_name\","
    496                 "\"postal_code_number\":\"save_postal_code_number\","
    497                 "\"recipient_name\":\"save_recipient_name\","
    498                 "\"sorting_code\":\"save_sorting_code\""
    499             "}"
    500         "},"
    501         "\"use_minimal_addresses\":false"
    502     "}";
    503 
    504 const char kUpdateAddressValidRequest[] =
    505     "{"
    506         "\"merchant_domain\":\"https://example.com/\","
    507         "\"phone_number_required\":true,"
    508         "\"risk_params\":\"risky business\","
    509         "\"shipping_address\":"
    510         "{"
    511             "\"id\":\"address_id\","
    512             "\"phone_number\":\"ship_phone_number\","
    513             "\"postal_address\":"
    514             "{"
    515                 "\"address_line\":"
    516                 "["
    517                     "\"ship_address_line_1\","
    518                     "\"ship_address_line_2\""
    519                 "],"
    520                 "\"administrative_area_name\":\"ship_admin_area_name\","
    521                 "\"country_name_code\":\"US\","
    522                 "\"dependent_locality_name\":\"ship_dependent_locality_name\","
    523                 "\"language_code\":\"ship_language_code\","
    524                 "\"locality_name\":\"ship_locality_name\","
    525                 "\"postal_code_number\":\"ship_postal_code_number\","
    526                 "\"recipient_name\":\"ship_recipient_name\","
    527                 "\"sorting_code\":\"ship_sorting_code\""
    528             "}"
    529         "},"
    530         "\"use_minimal_addresses\":false"
    531     "}";
    532 
    533 const char kUpdateInstrumentAddressValidRequest[] =
    534     "{"
    535         "\"instrument_phone_number\":\"phone_number\","
    536         "\"merchant_domain\":\"https://example.com/\","
    537         "\"phone_number_required\":true,"
    538         "\"risk_params\":\"risky business\","
    539         "\"upgraded_billing_address\":"
    540         "{"
    541             "\"address_line\":"
    542             "["
    543                 "\"address_line_1\","
    544                 "\"address_line_2\""
    545             "],"
    546             "\"administrative_area_name\":\"admin_area_name\","
    547             "\"country_name_code\":\"US\","
    548             "\"dependent_locality_name\":\"dependent_locality_name\","
    549             "\"language_code\":\"language_code\","
    550             "\"locality_name\":\"locality_name\","
    551             "\"postal_code_number\":\"postal_code_number\","
    552             "\"recipient_name\":\"recipient_name\","
    553             "\"sorting_code\":\"sorting_code\""
    554         "},"
    555         "\"upgraded_instrument_id\":\"default_instrument_id\","
    556         "\"use_minimal_addresses\":false"
    557     "}";
    558 
    559 const char kUpdateInstrumentAddressWithNameChangeValidRequest[] =
    560     "{"
    561         "\"instrument_phone_number\":\"phone_number\","
    562         "\"merchant_domain\":\"https://example.com/\","
    563         "\"phone_number_required\":true,"
    564         "\"risk_params\":\"risky business\","
    565         "\"upgraded_billing_address\":"
    566         "{"
    567             "\"address_line\":"
    568             "["
    569                 "\"address_line_1\","
    570                 "\"address_line_2\""
    571             "],"
    572             "\"administrative_area_name\":\"admin_area_name\","
    573             "\"country_name_code\":\"US\","
    574             "\"dependent_locality_name\":\"dependent_locality_name\","
    575             "\"language_code\":\"language_code\","
    576             "\"locality_name\":\"locality_name\","
    577             "\"postal_code_number\":\"postal_code_number\","
    578             "\"recipient_name\":\"recipient_name\","
    579             "\"sorting_code\":\"sorting_code\""
    580         "},"
    581         "\"upgraded_instrument_id\":\"default_instrument_id\","
    582         "\"use_minimal_addresses\":false"
    583     "}";
    584 
    585 const char kUpdateInstrumentExpirationDateValidRequest[] =
    586     "{"
    587         "\"instrument\":"
    588         "{"
    589             "\"credit_card\":"
    590             "{"
    591                 "\"exp_month\":12,"
    592                 "\"exp_year\":3001"
    593             "},"
    594             "\"type\":\"CREDIT_CARD\""
    595         "},"
    596         "\"merchant_domain\":\"https://example.com/\","
    597         "\"phone_number_required\":true,"
    598         "\"risk_params\":\"risky business\","
    599         "\"upgraded_instrument_id\":\"instrument_id\","
    600         "\"use_minimal_addresses\":false"
    601     "}";
    602 
    603 class MockAutofillMetrics : public AutofillMetrics {
    604  public:
    605   MockAutofillMetrics() {}
    606   MOCK_CONST_METHOD2(LogWalletApiCallDuration,
    607                      void(WalletApiCallMetric metric,
    608                           const base::TimeDelta& duration));
    609   MOCK_CONST_METHOD1(LogWalletErrorMetric, void(WalletErrorMetric metric));
    610   MOCK_CONST_METHOD1(LogWalletRequiredActionMetric,
    611                      void(WalletRequiredActionMetric action));
    612   MOCK_CONST_METHOD1(LogWalletMalformedResponseMetric,
    613                      void(WalletApiCallMetric metric));
    614  private:
    615   DISALLOW_COPY_AND_ASSIGN(MockAutofillMetrics);
    616 };
    617 
    618 class MockWalletClientDelegate : public WalletClientDelegate {
    619  public:
    620   MockWalletClientDelegate()
    621       : full_wallets_received_(0),
    622         wallet_items_received_(0),
    623         is_shipping_required_(true) {}
    624   ~MockWalletClientDelegate() {}
    625 
    626   virtual const AutofillMetrics& GetMetricLogger() const OVERRIDE {
    627     return metric_logger_;
    628   }
    629 
    630   virtual std::string GetRiskData() const OVERRIDE {
    631     return "risky business";
    632   }
    633 
    634   virtual std::string GetWalletCookieValue() const OVERRIDE {
    635     return "gdToken";
    636   }
    637 
    638   virtual bool IsShippingAddressRequired() const OVERRIDE {
    639     return is_shipping_required_;
    640   }
    641 
    642   void SetIsShippingAddressRequired(bool is_shipping_required) {
    643     is_shipping_required_ = is_shipping_required;
    644   }
    645 
    646   void ExpectLogWalletApiCallDuration(
    647       AutofillMetrics::WalletApiCallMetric metric,
    648       size_t times) {
    649     EXPECT_CALL(metric_logger_,
    650                 LogWalletApiCallDuration(metric, testing::_)).Times(times);
    651   }
    652 
    653   void ExpectLogWalletMalformedResponse(
    654       AutofillMetrics::WalletApiCallMetric metric) {
    655     EXPECT_CALL(metric_logger_,
    656                 LogWalletMalformedResponseMetric(metric)).Times(1);
    657   }
    658 
    659   void ExpectWalletErrorMetric(AutofillMetrics::WalletErrorMetric metric) {
    660     EXPECT_CALL(metric_logger_, LogWalletErrorMetric(metric)).Times(1);
    661   }
    662 
    663   void ExpectWalletRequiredActionMetric(
    664       AutofillMetrics::WalletRequiredActionMetric metric) {
    665     EXPECT_CALL(metric_logger_,
    666                 LogWalletRequiredActionMetric(metric)).Times(1);
    667   }
    668 
    669   void ExpectBaselineMetrics() {
    670     EXPECT_CALL(
    671         metric_logger_,
    672         LogWalletErrorMetric(
    673             AutofillMetrics::WALLET_ERROR_BASELINE_ISSUED_REQUEST))
    674                 .Times(1);
    675     ExpectWalletRequiredActionMetric(
    676         AutofillMetrics::WALLET_REQUIRED_ACTION_BASELINE_ISSUED_REQUEST);
    677   }
    678 
    679   MockAutofillMetrics* metric_logger() {
    680     return &metric_logger_;
    681   }
    682 
    683   MOCK_METHOD0(OnDidAcceptLegalDocuments, void());
    684   MOCK_METHOD1(OnDidAuthenticateInstrument, void(bool success));
    685   MOCK_METHOD4(OnDidSaveToWallet,
    686                void(const std::string& instrument_id,
    687                     const std::string& shipping_address_id,
    688                     const std::vector<RequiredAction>& required_actions,
    689                     const std::vector<FormFieldError>& form_field_errors));
    690   MOCK_METHOD1(OnWalletError, void(WalletClient::ErrorType error_type));
    691 
    692   virtual void OnDidGetFullWallet(scoped_ptr<FullWallet> full_wallet) OVERRIDE {
    693     EXPECT_TRUE(full_wallet);
    694     ++full_wallets_received_;
    695   }
    696   virtual void OnDidGetWalletItems(scoped_ptr<WalletItems> wallet_items)
    697       OVERRIDE {
    698     EXPECT_TRUE(wallet_items);
    699     ++wallet_items_received_;
    700   }
    701   size_t full_wallets_received() const { return full_wallets_received_; }
    702   size_t wallet_items_received() const { return wallet_items_received_; }
    703 
    704  private:
    705   size_t full_wallets_received_;
    706   size_t wallet_items_received_;
    707   bool is_shipping_required_;
    708 
    709   testing::StrictMock<MockAutofillMetrics> metric_logger_;
    710 };
    711 
    712 }  // namespace
    713 
    714 class WalletClientTest : public testing::Test {
    715  public:
    716   WalletClientTest()
    717       : request_context_(new net::TestURLRequestContextGetter(
    718             base::MessageLoopProxy::current())) {}
    719   virtual ~WalletClientTest() {}
    720 
    721   virtual void SetUp() OVERRIDE {
    722     wallet_client_.reset(
    723         new WalletClient(request_context_,
    724                          &delegate_,
    725                          GURL(kMerchantUrl)));
    726   }
    727 
    728   virtual void TearDown() OVERRIDE {
    729     wallet_client_.reset();
    730   }
    731 
    732   void VerifyAndFinishRequest(net::HttpStatusCode response_code,
    733                               const std::string& request_body,
    734                               const std::string& response_body) {
    735     net::TestURLFetcher* fetcher = factory_.GetFetcherByID(0);
    736     ASSERT_TRUE(fetcher);
    737 
    738     const std::string& upload_data = fetcher->upload_data();
    739     EXPECT_EQ(request_body, GetData(upload_data));
    740     net::HttpRequestHeaders request_headers;
    741     fetcher->GetExtraRequestHeaders(&request_headers);
    742     std::string auth_header_value;
    743     EXPECT_TRUE(request_headers.GetHeader(
    744         net::HttpRequestHeaders::kAuthorization,
    745         &auth_header_value));
    746     EXPECT_EQ("GoogleLogin auth=gdToken", auth_header_value);
    747 
    748     fetcher->set_response_code(response_code);
    749     fetcher->SetResponseString(response_body);
    750     fetcher->delegate()->OnURLFetchComplete(fetcher);
    751 
    752     // Pump the message loop to catch up to any asynchronous tasks that might
    753     // have been posted from OnURLFetchComplete().
    754     base::RunLoop().RunUntilIdle();
    755   }
    756 
    757   void VerifyAndFinishFormEncodedRequest(net::HttpStatusCode response_code,
    758                                          const std::string& json_payload,
    759                                          const std::string& response_body,
    760                                          size_t expected_parameter_number) {
    761     net::TestURLFetcher* fetcher = factory_.GetFetcherByID(0);
    762     ASSERT_TRUE(fetcher);
    763 
    764     net::HttpRequestHeaders request_headers;
    765     fetcher->GetExtraRequestHeaders(&request_headers);
    766     std::string auth_header_value;
    767     EXPECT_TRUE(request_headers.GetHeader(
    768         net::HttpRequestHeaders::kAuthorization,
    769         &auth_header_value));
    770     EXPECT_EQ("GoogleLogin auth=gdToken", auth_header_value);
    771 
    772     const std::string& upload_data = fetcher->upload_data();
    773     std::vector<std::pair<std::string, std::string> > tokens;
    774     base::SplitStringIntoKeyValuePairs(upload_data, '=', '&', &tokens);
    775     EXPECT_EQ(tokens.size(), expected_parameter_number);
    776 
    777     size_t num_params = 0U;
    778     for (size_t i = 0; i < tokens.size(); ++i) {
    779       const std::string& key = tokens[i].first;
    780       const std::string& value = tokens[i].second;
    781 
    782       if (key == "request_content_type") {
    783         EXPECT_EQ("application/json", value);
    784         num_params++;
    785       }
    786 
    787       if (key == "request") {
    788         EXPECT_EQ(json_payload,
    789                   GetData(
    790                       net::UnescapeURLComponent(
    791                           value, net::UnescapeRule::URL_SPECIAL_CHARS |
    792                           net::UnescapeRule::REPLACE_PLUS_WITH_SPACE)));
    793         num_params++;
    794       }
    795 
    796       if (key == "cvn") {
    797         EXPECT_EQ("123", value);
    798         num_params++;
    799       }
    800 
    801       if (key == "card_number") {
    802         EXPECT_EQ("4444444444444448", value);
    803         num_params++;
    804       }
    805 
    806       if (key == "otp") {
    807         EXPECT_FALSE(value.empty());
    808         num_params++;
    809       }
    810     }
    811     EXPECT_EQ(expected_parameter_number, num_params);
    812 
    813     fetcher->set_response_code(response_code);
    814     fetcher->SetResponseString(response_body);
    815     fetcher->delegate()->OnURLFetchComplete(fetcher);
    816   }
    817 
    818   void TestWalletErrorCode(
    819       const std::string& error_type_string,
    820       const std::string& message_type_for_buyer_string,
    821       WalletClient::ErrorType expected_error_type,
    822       AutofillMetrics::WalletErrorMetric expected_autofill_metric) {
    823     static const char kResponseTemplate[] =
    824         "{"
    825         "  \"error_type\":\"APPLICATION_ERROR\","
    826         "  \"error_detail\":\"error_detail\","
    827         "  \"application_error\":\"application_error\","
    828         "  \"debug_data\":"
    829         "  {"
    830         "    \"debug_message\":\"debug_message\","
    831         "    \"stack_trace\":\"stack_trace\""
    832         "  },"
    833         "  \"application_error_data\":\"application_error_data\","
    834         "  \"wallet_error\":"
    835         "  {"
    836         "    \"error_type\":\"%s\","
    837         "    %s"  // Placeholder for |user_error_type|.
    838         "    \"error_detail\":\"error_detail\","
    839         "    \"message_for_user\":"
    840         "    {"
    841         "      \"text\":\"text\","
    842         "      \"subtext\":\"subtext\","
    843         "      \"details\":\"details\""
    844         "    }"
    845         "  }"
    846         "}";
    847     EXPECT_CALL(delegate_, OnWalletError(expected_error_type)).Times(1);
    848     delegate_.ExpectLogWalletApiCallDuration(
    849         AutofillMetrics::GET_WALLET_ITEMS, 1);
    850     delegate_.ExpectBaselineMetrics();
    851     delegate_.ExpectWalletErrorMetric(expected_autofill_metric);
    852 
    853     wallet_client_->GetWalletItems();
    854     std::string buyer_error;
    855     if (!message_type_for_buyer_string.empty()) {
    856       buyer_error = base::StringPrintf("\"message_type_for_buyer\":\"%s\",",
    857                                        message_type_for_buyer_string.c_str());
    858     }
    859     std::string response = base::StringPrintf(kResponseTemplate,
    860                                               error_type_string.c_str(),
    861                                               buyer_error.c_str());
    862     VerifyAndFinishRequest(net::HTTP_INTERNAL_SERVER_ERROR,
    863                            kGetWalletItemsValidRequest,
    864                            response);
    865   }
    866 
    867  protected:
    868   content::TestBrowserThreadBundle thread_bundle_;
    869   scoped_ptr<WalletClient> wallet_client_;
    870   scoped_refptr<net::TestURLRequestContextGetter> request_context_;
    871   MockWalletClientDelegate delegate_;
    872 
    873  private:
    874   std::string GetData(const std::string& upload_data) {
    875     scoped_ptr<base::Value> root(base::JSONReader::Read(upload_data));
    876 
    877     // If this is not a JSON dictionary, return plain text.
    878     if (!root || !root->IsType(base::Value::TYPE_DICTIONARY))
    879       return upload_data;
    880 
    881     // Remove api_key entry (to prevent accidental leak), return JSON as text.
    882     base::DictionaryValue* dict =
    883         static_cast<base::DictionaryValue*>(root.get());
    884     dict->Remove("api_key", NULL);
    885     std::string clean_upload_data;
    886     base::JSONWriter::Write(dict, &clean_upload_data);
    887     return clean_upload_data;
    888   }
    889 
    890   net::TestURLFetcherFactory factory_;
    891 };
    892 
    893 TEST_F(WalletClientTest, WalletErrorCodes) {
    894   struct {
    895     std::string error_type_string;
    896     std::string message_type_for_buyer_string;
    897     WalletClient::ErrorType expected_error_type;
    898     AutofillMetrics::WalletErrorMetric expected_autofill_metric;
    899   } test_cases[] = {
    900       // General |BUYER_ACCOUNT_ERROR| with no |message_type_for_buyer_string|.
    901       {
    902           "buyer_account_error",
    903           "",
    904           WalletClient::BUYER_ACCOUNT_ERROR,
    905           AutofillMetrics::WALLET_BUYER_ACCOUNT_ERROR
    906       },
    907       // |BUYER_ACCOUNT_ERROR| with "buyer_legal_address_not_supported" in
    908       // message_type_for_buyer field.
    909       {
    910           "buyer_account_error",
    911           "bla_country_not_supported",
    912           WalletClient::BUYER_LEGAL_ADDRESS_NOT_SUPPORTED,
    913           AutofillMetrics::WALLET_BUYER_LEGAL_ADDRESS_NOT_SUPPORTED
    914       },
    915       // |BUYER_ACCOUNT_ERROR| with KYC error code in message_type_for_buyer
    916       // field.
    917       {
    918           "buyer_account_error",
    919           "buyer_kyc_error",
    920           WalletClient::UNVERIFIED_KNOW_YOUR_CUSTOMER_STATUS,
    921           AutofillMetrics::WALLET_UNVERIFIED_KNOW_YOUR_CUSTOMER_STATUS
    922       },
    923       // |BUYER_ACCOUNT_ERROR| with un-recognizable |message_type_for_buyer|.
    924       {
    925           "buyer_account_error",
    926           "random_string",
    927           WalletClient::BUYER_ACCOUNT_ERROR,
    928           AutofillMetrics::WALLET_BUYER_ACCOUNT_ERROR
    929       },
    930       // The following are other error types we could get from Wallet.
    931       {
    932           "unsupported_merchant",
    933           "",
    934           WalletClient::UNSUPPORTED_MERCHANT,
    935           AutofillMetrics::WALLET_UNSUPPORTED_MERCHANT
    936       },
    937       {
    938           "internal_error",
    939           "",
    940           WalletClient::INTERNAL_ERROR,
    941           AutofillMetrics::WALLET_INTERNAL_ERROR
    942       },
    943       {
    944           "invalid_params",
    945           "",
    946           WalletClient::INVALID_PARAMS,
    947           AutofillMetrics::WALLET_INVALID_PARAMS
    948       },
    949       {
    950           "service_unavailable",
    951           "",
    952           WalletClient::SERVICE_UNAVAILABLE,
    953           AutofillMetrics::WALLET_SERVICE_UNAVAILABLE
    954       },
    955       {
    956           "unsupported_api_version",
    957           "",
    958           WalletClient::UNSUPPORTED_API_VERSION,
    959           AutofillMetrics::WALLET_UNSUPPORTED_API_VERSION
    960       },
    961       // Any un-recognizable |error_type| is a |UNKNOWN_ERROR|.
    962       {
    963           "random_string_1",
    964           "",
    965           WalletClient::UNKNOWN_ERROR,
    966           AutofillMetrics::WALLET_UNKNOWN_ERROR
    967       },
    968       {
    969           "random_string_2",
    970           "",
    971           WalletClient::UNKNOWN_ERROR,
    972           AutofillMetrics::WALLET_UNKNOWN_ERROR
    973       },
    974   };
    975 
    976   for (size_t i = 0; i < ARRAYSIZE_UNSAFE(test_cases); ++i) {
    977     SCOPED_TRACE(
    978         base::StringPrintf(
    979             "%s - %s",
    980             test_cases[i].error_type_string.c_str(),
    981             test_cases[i].message_type_for_buyer_string.c_str()));
    982     TestWalletErrorCode(test_cases[i].error_type_string,
    983                         test_cases[i].message_type_for_buyer_string,
    984                         test_cases[i].expected_error_type,
    985                         test_cases[i].expected_autofill_metric);
    986   }
    987 }
    988 
    989 TEST_F(WalletClientTest, WalletErrorResponseMissing) {
    990   EXPECT_CALL(delegate_, OnWalletError(
    991       WalletClient::UNKNOWN_ERROR)).Times(1);
    992   delegate_.ExpectLogWalletApiCallDuration(
    993       AutofillMetrics::GET_WALLET_ITEMS, 1);
    994   delegate_.ExpectBaselineMetrics();
    995   delegate_.ExpectWalletErrorMetric(AutofillMetrics::WALLET_UNKNOWN_ERROR);
    996 
    997   wallet_client_->GetWalletItems();
    998   VerifyAndFinishRequest(net::HTTP_INTERNAL_SERVER_ERROR,
    999                          kGetWalletItemsValidRequest,
   1000                          kErrorTypeMissingInResponse);
   1001 }
   1002 
   1003 TEST_F(WalletClientTest, NetworkFailureOnExpectedResponse) {
   1004   EXPECT_CALL(delegate_, OnWalletError(WalletClient::NETWORK_ERROR)).Times(1);
   1005   delegate_.ExpectLogWalletApiCallDuration(AutofillMetrics::GET_WALLET_ITEMS,
   1006                                            1);
   1007   delegate_.ExpectBaselineMetrics();
   1008   delegate_.ExpectWalletErrorMetric(AutofillMetrics::WALLET_NETWORK_ERROR);
   1009 
   1010   wallet_client_->GetWalletItems();
   1011   VerifyAndFinishRequest(net::HTTP_UNAUTHORIZED,
   1012                          kGetWalletItemsValidRequest,
   1013                          std::string());
   1014 }
   1015 
   1016 TEST_F(WalletClientTest, RequestError) {
   1017   EXPECT_CALL(delegate_, OnWalletError(WalletClient::BAD_REQUEST)).Times(1);
   1018   delegate_.ExpectLogWalletApiCallDuration(
   1019       AutofillMetrics::GET_WALLET_ITEMS, 1);
   1020   delegate_.ExpectBaselineMetrics();
   1021   delegate_.ExpectWalletErrorMetric(AutofillMetrics::WALLET_BAD_REQUEST);
   1022 
   1023   wallet_client_->GetWalletItems();
   1024   VerifyAndFinishRequest(net::HTTP_BAD_REQUEST,
   1025                          kGetWalletItemsValidRequest,
   1026                          std::string());
   1027 }
   1028 
   1029 TEST_F(WalletClientTest, GetFullWalletSuccess) {
   1030   delegate_.ExpectLogWalletApiCallDuration(AutofillMetrics::GET_FULL_WALLET, 1);
   1031   delegate_.ExpectBaselineMetrics();
   1032 
   1033   WalletClient::FullWalletRequest full_wallet_request(
   1034       "instrument_id",
   1035       "shipping_address_id",
   1036       "google_transaction_id",
   1037       std::vector<WalletClient::RiskCapability>(),
   1038       false);
   1039   wallet_client_->GetFullWallet(full_wallet_request);
   1040 
   1041   VerifyAndFinishFormEncodedRequest(net::HTTP_OK,
   1042                                     kGetFullWalletValidRequest,
   1043                                     kGetFullWalletValidResponse,
   1044                                     3U);
   1045   EXPECT_EQ(1U, delegate_.full_wallets_received());
   1046 }
   1047 
   1048 TEST_F(WalletClientTest, GetFullWalletSuccessNewuser) {
   1049   delegate_.ExpectLogWalletApiCallDuration(AutofillMetrics::GET_FULL_WALLET, 1);
   1050   delegate_.ExpectBaselineMetrics();
   1051 
   1052   WalletClient::FullWalletRequest full_wallet_request(
   1053       "instrument_id",
   1054       "shipping_address_id",
   1055       "google_transaction_id",
   1056       std::vector<WalletClient::RiskCapability>(),
   1057       true);
   1058   wallet_client_->GetFullWallet(full_wallet_request);
   1059 
   1060   VerifyAndFinishFormEncodedRequest(net::HTTP_OK,
   1061                                     kGetFullWalletValidRequestNewUser,
   1062                                     kGetFullWalletValidResponse,
   1063                                     3U);
   1064   EXPECT_EQ(1U, delegate_.full_wallets_received());
   1065 }
   1066 
   1067 TEST_F(WalletClientTest, GetFullWalletWithRiskCapabilitesSuccess) {
   1068   delegate_.ExpectLogWalletApiCallDuration(AutofillMetrics::GET_FULL_WALLET, 1);
   1069   delegate_.ExpectBaselineMetrics();
   1070 
   1071   std::vector<WalletClient::RiskCapability> risk_capabilities;
   1072   risk_capabilities.push_back(WalletClient::VERIFY_CVC);
   1073   WalletClient::FullWalletRequest full_wallet_request(
   1074       "instrument_id",
   1075       "shipping_address_id",
   1076       "google_transaction_id",
   1077       risk_capabilities,
   1078       false);
   1079   wallet_client_->GetFullWallet(full_wallet_request);
   1080 
   1081   VerifyAndFinishFormEncodedRequest(
   1082       net::HTTP_OK,
   1083       kGetFullWalletWithRiskCapabilitesValidRequest,
   1084       kGetFullWalletValidResponse,
   1085       3U);
   1086   EXPECT_EQ(1U, delegate_.full_wallets_received());
   1087 }
   1088 
   1089 
   1090 TEST_F(WalletClientTest, GetFullWalletMalformedResponse) {
   1091   EXPECT_CALL(delegate_,
   1092               OnWalletError(WalletClient::MALFORMED_RESPONSE)).Times(1);
   1093   delegate_.ExpectLogWalletApiCallDuration(AutofillMetrics::GET_FULL_WALLET, 1);
   1094   delegate_.ExpectBaselineMetrics();
   1095   delegate_.ExpectWalletErrorMetric(AutofillMetrics::WALLET_MALFORMED_RESPONSE);
   1096   delegate_.ExpectLogWalletMalformedResponse(AutofillMetrics::GET_FULL_WALLET);
   1097 
   1098   WalletClient::FullWalletRequest full_wallet_request(
   1099       "instrument_id",
   1100       "shipping_address_id",
   1101       "google_transaction_id",
   1102       std::vector<WalletClient::RiskCapability>(),
   1103       false);
   1104   wallet_client_->GetFullWallet(full_wallet_request);
   1105 
   1106   VerifyAndFinishFormEncodedRequest(net::HTTP_OK,
   1107                                     kGetFullWalletValidRequest,
   1108                                     kGetFullWalletInvalidResponse,
   1109                                     3U);
   1110   EXPECT_EQ(0U, delegate_.full_wallets_received());
   1111 }
   1112 
   1113 TEST_F(WalletClientTest, AcceptLegalDocuments) {
   1114   EXPECT_CALL(delegate_, OnDidAcceptLegalDocuments()).Times(1);
   1115   delegate_.ExpectLogWalletApiCallDuration(
   1116       AutofillMetrics::ACCEPT_LEGAL_DOCUMENTS,
   1117       1);
   1118   delegate_.ExpectBaselineMetrics();
   1119 
   1120   ScopedVector<WalletItems::LegalDocument> docs;
   1121   base::DictionaryValue document;
   1122   document.SetString("legal_document_id", "doc_id_1");
   1123   document.SetString("display_name", "doc_1");
   1124   docs.push_back(
   1125       WalletItems::LegalDocument::CreateLegalDocument(document).release());
   1126   document.SetString("legal_document_id", "doc_id_2");
   1127   document.SetString("display_name", "doc_2");
   1128   docs.push_back(
   1129       WalletItems::LegalDocument::CreateLegalDocument(document).release());
   1130   docs.push_back(
   1131       WalletItems::LegalDocument::CreatePrivacyPolicyDocument().release());
   1132   wallet_client_->AcceptLegalDocuments(docs.get(),
   1133                                        kGoogleTransactionId);
   1134   VerifyAndFinishRequest(net::HTTP_OK,
   1135                          kAcceptLegalDocumentsValidRequest,
   1136                          ")}'");  // Invalid JSON. Should be ignored.
   1137 }
   1138 
   1139 TEST_F(WalletClientTest, AuthenticateInstrumentSucceeded) {
   1140   EXPECT_CALL(delegate_, OnDidAuthenticateInstrument(true)).Times(1);
   1141   delegate_.ExpectLogWalletApiCallDuration(
   1142       AutofillMetrics::AUTHENTICATE_INSTRUMENT,
   1143       1);
   1144   delegate_.ExpectBaselineMetrics();
   1145 
   1146   wallet_client_->AuthenticateInstrument("instrument_id", "123");
   1147 
   1148   VerifyAndFinishFormEncodedRequest(net::HTTP_OK,
   1149                                     kAuthenticateInstrumentValidRequest,
   1150                                     kAuthenticateInstrumentSuccessResponse,
   1151                                     3U);
   1152 }
   1153 
   1154 TEST_F(WalletClientTest, AuthenticateInstrumentFailed) {
   1155   EXPECT_CALL(delegate_, OnDidAuthenticateInstrument(false)).Times(1);
   1156   delegate_.ExpectLogWalletApiCallDuration(
   1157       AutofillMetrics::AUTHENTICATE_INSTRUMENT,
   1158       1);
   1159   delegate_.ExpectBaselineMetrics();
   1160 
   1161   wallet_client_->AuthenticateInstrument("instrument_id", "123");
   1162 
   1163   VerifyAndFinishFormEncodedRequest(net::HTTP_OK,
   1164                                     kAuthenticateInstrumentValidRequest,
   1165                                     kAuthenticateInstrumentFailureResponse,
   1166                                     3U);
   1167 }
   1168 
   1169 TEST_F(WalletClientTest, AuthenticateInstrumentFailedMalformedResponse) {
   1170   EXPECT_CALL(delegate_,
   1171               OnWalletError(WalletClient::MALFORMED_RESPONSE)).Times(1);
   1172   delegate_.ExpectLogWalletApiCallDuration(
   1173       AutofillMetrics::AUTHENTICATE_INSTRUMENT,
   1174       1);
   1175   delegate_.ExpectBaselineMetrics();
   1176   delegate_.ExpectWalletErrorMetric(AutofillMetrics::WALLET_MALFORMED_RESPONSE);
   1177   delegate_.ExpectLogWalletMalformedResponse(
   1178       AutofillMetrics::AUTHENTICATE_INSTRUMENT);
   1179 
   1180   wallet_client_->AuthenticateInstrument("instrument_id", "123");
   1181 
   1182   VerifyAndFinishFormEncodedRequest(net::HTTP_OK,
   1183                                     kAuthenticateInstrumentValidRequest,
   1184                                     kSaveInvalidResponse,
   1185                                     3U);
   1186 }
   1187 
   1188 // TODO(ahutter): Add failure tests for GetWalletItems.
   1189 
   1190 TEST_F(WalletClientTest, GetWalletItems) {
   1191   delegate_.ExpectLogWalletApiCallDuration(AutofillMetrics::GET_WALLET_ITEMS,
   1192                                            1);
   1193   delegate_.ExpectBaselineMetrics();
   1194 
   1195   wallet_client_->GetWalletItems();
   1196 
   1197   VerifyAndFinishRequest(net::HTTP_OK,
   1198                          kGetWalletItemsValidRequest,
   1199                          kGetWalletItemsValidResponse);
   1200   EXPECT_EQ(1U, delegate_.wallet_items_received());
   1201 }
   1202 
   1203 TEST_F(WalletClientTest, GetWalletItemsRespectsDelegateForShippingRequired) {
   1204   delegate_.ExpectLogWalletApiCallDuration(AutofillMetrics::GET_WALLET_ITEMS,
   1205                                            1);
   1206   delegate_.ExpectBaselineMetrics();
   1207   delegate_.SetIsShippingAddressRequired(false);
   1208 
   1209   wallet_client_->GetWalletItems();
   1210 
   1211   VerifyAndFinishRequest(net::HTTP_OK,
   1212                          kGetWalletItemsNoShippingRequest,
   1213                          kGetWalletItemsValidResponse);
   1214   EXPECT_EQ(1U, delegate_.wallet_items_received());
   1215 }
   1216 
   1217 TEST_F(WalletClientTest, SaveAddressSucceeded) {
   1218   EXPECT_CALL(delegate_,
   1219               OnDidSaveToWallet(std::string(),
   1220                                 "saved_address_id",
   1221                                 std::vector<RequiredAction>(),
   1222                                 std::vector<FormFieldError>())).Times(1);
   1223   delegate_.ExpectLogWalletApiCallDuration(AutofillMetrics::SAVE_TO_WALLET, 1);
   1224   delegate_.ExpectBaselineMetrics();
   1225 
   1226   scoped_ptr<Address> address = GetTestSaveableAddress();
   1227   wallet_client_->SaveToWallet(scoped_ptr<Instrument>(),
   1228                                address.Pass(),
   1229                                NULL,
   1230                                NULL);
   1231   VerifyAndFinishRequest(net::HTTP_OK,
   1232                          kSaveAddressValidRequest,
   1233                          kSaveAddressValidResponse);
   1234 }
   1235 
   1236 TEST_F(WalletClientTest, SaveAddressWithRequiredActionsSucceeded) {
   1237   delegate_.ExpectLogWalletApiCallDuration(AutofillMetrics::SAVE_TO_WALLET, 1);
   1238   delegate_.ExpectBaselineMetrics();
   1239   delegate_.ExpectWalletRequiredActionMetric(
   1240       AutofillMetrics::REQUIRE_PHONE_NUMBER);
   1241   delegate_.ExpectWalletRequiredActionMetric(
   1242       AutofillMetrics::INVALID_FORM_FIELD);
   1243 
   1244   std::vector<RequiredAction> required_actions;
   1245   required_actions.push_back(REQUIRE_PHONE_NUMBER);
   1246   required_actions.push_back(INVALID_FORM_FIELD);
   1247 
   1248   std::vector<FormFieldError> form_errors;
   1249   form_errors.push_back(FormFieldError(FormFieldError::INVALID_POSTAL_CODE,
   1250                                        FormFieldError::SHIPPING_ADDRESS));
   1251 
   1252   EXPECT_CALL(delegate_,
   1253               OnDidSaveToWallet(std::string(),
   1254                                 std::string(),
   1255                                 required_actions,
   1256                                 form_errors)).Times(1);
   1257 
   1258   scoped_ptr<Address> address = GetTestSaveableAddress();
   1259   wallet_client_->SaveToWallet(scoped_ptr<Instrument>(),
   1260                                address.Pass(),
   1261                                NULL,
   1262                                NULL);
   1263   VerifyAndFinishRequest(net::HTTP_OK,
   1264                          kSaveAddressValidRequest,
   1265                          kSaveAddressWithRequiredActionsValidResponse);
   1266 }
   1267 
   1268 TEST_F(WalletClientTest, SaveAddressFailedInvalidRequiredAction) {
   1269   EXPECT_CALL(delegate_,
   1270               OnWalletError(WalletClient::MALFORMED_RESPONSE)).Times(1);
   1271   delegate_.ExpectLogWalletApiCallDuration(AutofillMetrics::SAVE_TO_WALLET, 1);
   1272   delegate_.ExpectBaselineMetrics();
   1273   delegate_.ExpectWalletErrorMetric(AutofillMetrics::WALLET_MALFORMED_RESPONSE);
   1274   delegate_.ExpectLogWalletMalformedResponse(AutofillMetrics::SAVE_TO_WALLET);
   1275 
   1276   scoped_ptr<Address> address = GetTestSaveableAddress();
   1277   wallet_client_->SaveToWallet(scoped_ptr<Instrument>(),
   1278                                address.Pass(),
   1279                                NULL,
   1280                                NULL);
   1281   VerifyAndFinishRequest(net::HTTP_OK,
   1282                          kSaveAddressValidRequest,
   1283                          kSaveWithInvalidRequiredActionsResponse);
   1284 }
   1285 
   1286 TEST_F(WalletClientTest, SaveAddressFailedMalformedResponse) {
   1287   EXPECT_CALL(delegate_,
   1288               OnWalletError(WalletClient::MALFORMED_RESPONSE)).Times(1);
   1289   delegate_.ExpectLogWalletApiCallDuration(AutofillMetrics::SAVE_TO_WALLET, 1);
   1290   delegate_.ExpectBaselineMetrics();
   1291   delegate_.ExpectWalletErrorMetric(AutofillMetrics::WALLET_MALFORMED_RESPONSE);
   1292   delegate_.ExpectLogWalletMalformedResponse(AutofillMetrics::SAVE_TO_WALLET);
   1293 
   1294   scoped_ptr<Address> address = GetTestSaveableAddress();
   1295   wallet_client_->SaveToWallet(scoped_ptr<Instrument>(),
   1296                                address.Pass(),
   1297                                NULL,
   1298                                NULL);
   1299   VerifyAndFinishRequest(net::HTTP_OK,
   1300                          kSaveAddressValidRequest,
   1301                          kSaveInvalidResponse);
   1302 }
   1303 
   1304 TEST_F(WalletClientTest, SaveInstrumentSucceeded) {
   1305   EXPECT_CALL(delegate_,
   1306               OnDidSaveToWallet("instrument_id",
   1307                                 std::string(),
   1308                                 std::vector<RequiredAction>(),
   1309                                 std::vector<FormFieldError>())).Times(1);
   1310   delegate_.ExpectLogWalletApiCallDuration(AutofillMetrics::SAVE_TO_WALLET, 1);
   1311   delegate_.ExpectBaselineMetrics();
   1312 
   1313   scoped_ptr<Instrument> instrument = GetTestInstrument();
   1314   wallet_client_->SaveToWallet(instrument.Pass(),
   1315                                scoped_ptr<Address>(),
   1316                                NULL,
   1317                                NULL);
   1318 
   1319   VerifyAndFinishFormEncodedRequest(net::HTTP_OK,
   1320                                     kSaveInstrumentValidRequest,
   1321                                     kSaveInstrumentValidResponse,
   1322                                     4U);
   1323 }
   1324 
   1325 TEST_F(WalletClientTest, SaveInstrumentWithRequiredActionsSucceeded) {
   1326   delegate_.ExpectLogWalletApiCallDuration(AutofillMetrics::SAVE_TO_WALLET, 1);
   1327   delegate_.ExpectBaselineMetrics();
   1328   delegate_.ExpectWalletRequiredActionMetric(
   1329       AutofillMetrics::REQUIRE_PHONE_NUMBER);
   1330   delegate_.ExpectWalletRequiredActionMetric(
   1331       AutofillMetrics::INVALID_FORM_FIELD);
   1332 
   1333   std::vector<RequiredAction> required_actions;
   1334   required_actions.push_back(REQUIRE_PHONE_NUMBER);
   1335   required_actions.push_back(INVALID_FORM_FIELD);
   1336 
   1337   std::vector<FormFieldError> form_errors;
   1338   form_errors.push_back(FormFieldError(FormFieldError::INVALID_POSTAL_CODE,
   1339                                        FormFieldError::SHIPPING_ADDRESS));
   1340 
   1341   EXPECT_CALL(delegate_,
   1342               OnDidSaveToWallet(std::string(),
   1343                                 std::string(),
   1344                                 required_actions,
   1345                                 form_errors)).Times(1);
   1346 
   1347   scoped_ptr<Instrument> instrument = GetTestInstrument();
   1348   wallet_client_->SaveToWallet(instrument.Pass(),
   1349                                scoped_ptr<Address>(),
   1350                                NULL,
   1351                                NULL);
   1352 
   1353   VerifyAndFinishFormEncodedRequest(
   1354       net::HTTP_OK,
   1355       kSaveInstrumentValidRequest,
   1356       kSaveInstrumentWithRequiredActionsValidResponse,
   1357       4U);
   1358 }
   1359 
   1360 TEST_F(WalletClientTest, SaveInstrumentFailedInvalidRequiredActions) {
   1361   delegate_.ExpectLogWalletApiCallDuration(AutofillMetrics::SAVE_TO_WALLET, 1);
   1362   delegate_.ExpectBaselineMetrics();
   1363   delegate_.ExpectWalletErrorMetric(AutofillMetrics::WALLET_MALFORMED_RESPONSE);
   1364   delegate_.ExpectLogWalletMalformedResponse(AutofillMetrics::SAVE_TO_WALLET);
   1365 
   1366   EXPECT_CALL(delegate_,
   1367               OnWalletError(WalletClient::MALFORMED_RESPONSE));
   1368 
   1369   scoped_ptr<Instrument> instrument = GetTestInstrument();
   1370   wallet_client_->SaveToWallet(instrument.Pass(),
   1371                                scoped_ptr<Address>(),
   1372                                NULL,
   1373                                NULL);
   1374 
   1375   VerifyAndFinishFormEncodedRequest(net::HTTP_OK,
   1376                                     kSaveInstrumentValidRequest,
   1377                                     kSaveWithInvalidRequiredActionsResponse,
   1378                                     4U);
   1379 }
   1380 
   1381 TEST_F(WalletClientTest, SaveInstrumentFailedMalformedResponse) {
   1382   EXPECT_CALL(delegate_,
   1383               OnWalletError(WalletClient::MALFORMED_RESPONSE)).Times(1);
   1384   delegate_.ExpectLogWalletApiCallDuration(AutofillMetrics::SAVE_TO_WALLET, 1);
   1385   delegate_.ExpectBaselineMetrics();
   1386   delegate_.ExpectWalletErrorMetric(AutofillMetrics::WALLET_MALFORMED_RESPONSE);
   1387   delegate_.ExpectLogWalletMalformedResponse(AutofillMetrics::SAVE_TO_WALLET);
   1388 
   1389   scoped_ptr<Instrument> instrument = GetTestInstrument();
   1390   wallet_client_->SaveToWallet(instrument.Pass(),
   1391                                scoped_ptr<Address>(),
   1392                                NULL,
   1393                                NULL);
   1394 
   1395   VerifyAndFinishFormEncodedRequest(net::HTTP_OK,
   1396                                     kSaveInstrumentValidRequest,
   1397                                     kSaveInvalidResponse,
   1398                                     4U);
   1399 }
   1400 
   1401 TEST_F(WalletClientTest, SaveInstrumentAndAddressSucceeded) {
   1402   EXPECT_CALL(delegate_,
   1403               OnDidSaveToWallet("saved_instrument_id",
   1404                                 "saved_address_id",
   1405                                 std::vector<RequiredAction>(),
   1406                                 std::vector<FormFieldError>())).Times(1);
   1407   delegate_.ExpectLogWalletApiCallDuration(
   1408       AutofillMetrics::SAVE_TO_WALLET,
   1409       1);
   1410   delegate_.ExpectBaselineMetrics();
   1411 
   1412   scoped_ptr<Instrument> instrument = GetTestInstrument();
   1413   scoped_ptr<Address> address = GetTestSaveableAddress();
   1414   wallet_client_->SaveToWallet(instrument.Pass(), address.Pass(), NULL, NULL);
   1415 
   1416   VerifyAndFinishFormEncodedRequest(net::HTTP_OK,
   1417                                     kSaveInstrumentAndAddressValidRequest,
   1418                                     kSaveInstrumentAndAddressValidResponse,
   1419                                     4U);
   1420 }
   1421 
   1422 TEST_F(WalletClientTest, SaveInstrumentAndAddressWithRequiredActionsSucceeded) {
   1423   delegate_.ExpectLogWalletApiCallDuration(
   1424       AutofillMetrics::SAVE_TO_WALLET,
   1425       1);
   1426   delegate_.ExpectBaselineMetrics();
   1427   delegate_.ExpectWalletRequiredActionMetric(
   1428       AutofillMetrics::REQUIRE_PHONE_NUMBER);
   1429   delegate_.ExpectWalletRequiredActionMetric(
   1430       AutofillMetrics::INVALID_FORM_FIELD);
   1431 
   1432   std::vector<RequiredAction> required_actions;
   1433   required_actions.push_back(REQUIRE_PHONE_NUMBER);
   1434   required_actions.push_back(INVALID_FORM_FIELD);
   1435 
   1436   std::vector<FormFieldError> form_errors;
   1437   form_errors.push_back(FormFieldError(FormFieldError::INVALID_POSTAL_CODE,
   1438                                        FormFieldError::SHIPPING_ADDRESS));
   1439 
   1440   EXPECT_CALL(delegate_,
   1441               OnDidSaveToWallet(std::string(),
   1442                                 std::string(),
   1443                                 required_actions,
   1444                                 form_errors)).Times(1);
   1445 
   1446   scoped_ptr<Instrument> instrument = GetTestInstrument();
   1447   scoped_ptr<Address> address = GetTestSaveableAddress();
   1448   wallet_client_->SaveToWallet(instrument.Pass(), address.Pass(), NULL, NULL);
   1449 
   1450   VerifyAndFinishFormEncodedRequest(
   1451       net::HTTP_OK,
   1452       kSaveInstrumentAndAddressValidRequest,
   1453       kSaveInstrumentAndAddressWithRequiredActionsValidResponse,
   1454       4U);
   1455 }
   1456 
   1457 TEST_F(WalletClientTest, SaveInstrumentAndAddressFailedInvalidRequiredAction) {
   1458   EXPECT_CALL(delegate_,
   1459               OnWalletError(WalletClient::MALFORMED_RESPONSE)).Times(1);
   1460   delegate_.ExpectLogWalletApiCallDuration(
   1461       AutofillMetrics::SAVE_TO_WALLET,
   1462       1);
   1463   delegate_.ExpectBaselineMetrics();
   1464   delegate_.ExpectWalletErrorMetric(AutofillMetrics::WALLET_MALFORMED_RESPONSE);
   1465   delegate_.ExpectLogWalletMalformedResponse(AutofillMetrics::SAVE_TO_WALLET);
   1466 
   1467   scoped_ptr<Instrument> instrument = GetTestInstrument();
   1468   scoped_ptr<Address> address = GetTestSaveableAddress();
   1469   wallet_client_->SaveToWallet(instrument.Pass(), address.Pass(), NULL, NULL);
   1470 
   1471   VerifyAndFinishFormEncodedRequest(net::HTTP_OK,
   1472                                     kSaveInstrumentAndAddressValidRequest,
   1473                                     kSaveWithInvalidRequiredActionsResponse,
   1474                                     4U);
   1475 }
   1476 
   1477 TEST_F(WalletClientTest, UpdateAddressSucceeded) {
   1478   EXPECT_CALL(delegate_,
   1479               OnDidSaveToWallet(std::string(),
   1480                                 "shipping_address_id",
   1481                                 std::vector<RequiredAction>(),
   1482                                 std::vector<FormFieldError>())).Times(1);
   1483   delegate_.ExpectLogWalletApiCallDuration(AutofillMetrics::SAVE_TO_WALLET, 1);
   1484   delegate_.ExpectBaselineMetrics();
   1485 
   1486   scoped_ptr<Address> reference_address = GetTestNonDefaultShippingAddress();
   1487   wallet_client_->SaveToWallet(scoped_ptr<Instrument>(),
   1488                                GetTestShippingAddress(),
   1489                                NULL,
   1490                                reference_address.get());
   1491 
   1492   VerifyAndFinishRequest(net::HTTP_OK,
   1493                          kUpdateAddressValidRequest,
   1494                          kUpdateAddressValidResponse);
   1495 }
   1496 
   1497 TEST_F(WalletClientTest, UpdateAddressWithRequiredActionsSucceeded) {
   1498   delegate_.ExpectLogWalletApiCallDuration(AutofillMetrics::SAVE_TO_WALLET, 1);
   1499   delegate_.ExpectBaselineMetrics();
   1500   delegate_.ExpectWalletRequiredActionMetric(
   1501       AutofillMetrics::REQUIRE_PHONE_NUMBER);
   1502   delegate_.ExpectWalletRequiredActionMetric(
   1503       AutofillMetrics::INVALID_FORM_FIELD);
   1504 
   1505   std::vector<RequiredAction> required_actions;
   1506   required_actions.push_back(REQUIRE_PHONE_NUMBER);
   1507   required_actions.push_back(INVALID_FORM_FIELD);
   1508 
   1509   std::vector<FormFieldError> form_errors;
   1510   form_errors.push_back(FormFieldError(FormFieldError::INVALID_POSTAL_CODE,
   1511                                        FormFieldError::SHIPPING_ADDRESS));
   1512 
   1513   EXPECT_CALL(delegate_, OnDidSaveToWallet(std::string(),
   1514                                            std::string(),
   1515                                            required_actions,
   1516                                            form_errors)).Times(1);
   1517 
   1518   scoped_ptr<Address> reference_address = GetTestNonDefaultShippingAddress();
   1519   wallet_client_->SaveToWallet(scoped_ptr<Instrument>(),
   1520                                GetTestShippingAddress(),
   1521                                NULL,
   1522                                reference_address.get());
   1523 
   1524   VerifyAndFinishRequest(net::HTTP_OK,
   1525                          kUpdateAddressValidRequest,
   1526                          kUpdateWithRequiredActionsValidResponse);
   1527 }
   1528 
   1529 TEST_F(WalletClientTest, UpdateAddressFailedInvalidRequiredAction) {
   1530   EXPECT_CALL(delegate_,
   1531               OnWalletError(WalletClient::MALFORMED_RESPONSE)).Times(1);
   1532   delegate_.ExpectLogWalletApiCallDuration(AutofillMetrics::SAVE_TO_WALLET, 1);
   1533   delegate_.ExpectBaselineMetrics();
   1534   delegate_.ExpectWalletErrorMetric(AutofillMetrics::WALLET_MALFORMED_RESPONSE);
   1535   delegate_.ExpectLogWalletMalformedResponse(AutofillMetrics::SAVE_TO_WALLET);
   1536 
   1537   scoped_ptr<Address> reference_address = GetTestNonDefaultShippingAddress();
   1538   wallet_client_->SaveToWallet(scoped_ptr<Instrument>(),
   1539                                GetTestShippingAddress(),
   1540                                NULL,
   1541                                reference_address.get());
   1542 
   1543   VerifyAndFinishRequest(net::HTTP_OK,
   1544                          kUpdateAddressValidRequest,
   1545                          kSaveWithInvalidRequiredActionsResponse);
   1546 }
   1547 
   1548 TEST_F(WalletClientTest, UpdateAddressMalformedResponse) {
   1549   EXPECT_CALL(delegate_,
   1550               OnWalletError(WalletClient::MALFORMED_RESPONSE)).Times(1);
   1551   delegate_.ExpectLogWalletApiCallDuration(AutofillMetrics::SAVE_TO_WALLET, 1);
   1552   delegate_.ExpectBaselineMetrics();
   1553   delegate_.ExpectWalletErrorMetric(AutofillMetrics::WALLET_MALFORMED_RESPONSE);
   1554   delegate_.ExpectLogWalletMalformedResponse(AutofillMetrics::SAVE_TO_WALLET);
   1555 
   1556   scoped_ptr<Address> reference_address = GetTestNonDefaultShippingAddress();
   1557   wallet_client_->SaveToWallet(scoped_ptr<Instrument>(),
   1558                                GetTestShippingAddress(),
   1559                                NULL,
   1560                                reference_address.get());
   1561 
   1562   VerifyAndFinishRequest(net::HTTP_OK,
   1563                          kUpdateAddressValidRequest,
   1564                          kUpdateMalformedResponse);
   1565 }
   1566 
   1567 TEST_F(WalletClientTest, UpdateInstrumentAddressSucceeded) {
   1568   EXPECT_CALL(delegate_,
   1569               OnDidSaveToWallet("instrument_id",
   1570                                 std::string(),
   1571                                 std::vector<RequiredAction>(),
   1572                                 std::vector<FormFieldError>())).Times(1);
   1573   delegate_.ExpectLogWalletApiCallDuration(AutofillMetrics::SAVE_TO_WALLET,
   1574                                            1);
   1575   delegate_.ExpectBaselineMetrics();
   1576 
   1577   scoped_ptr<WalletItems::MaskedInstrument> reference_instrument =
   1578       GetTestMaskedInstrument();
   1579   wallet_client_->SaveToWallet(GetTestAddressUpgradeInstrument(),
   1580                                scoped_ptr<Address>(),
   1581                                reference_instrument.get(),
   1582                                NULL);
   1583 
   1584   VerifyAndFinishRequest(net::HTTP_OK,
   1585                          kUpdateInstrumentAddressValidRequest,
   1586                          kUpdateInstrumentValidResponse);
   1587 }
   1588 
   1589 TEST_F(WalletClientTest, UpdateInstrumentExpirationDateSuceeded) {
   1590   EXPECT_CALL(delegate_,
   1591               OnDidSaveToWallet("instrument_id",
   1592                                 std::string(),
   1593                                 std::vector<RequiredAction>(),
   1594                                 std::vector<FormFieldError>())).Times(1);
   1595   delegate_.ExpectLogWalletApiCallDuration(AutofillMetrics::SAVE_TO_WALLET,
   1596                                            1);
   1597   delegate_.ExpectBaselineMetrics();
   1598 
   1599   scoped_ptr<Instrument> instrument = GetTestExpirationDateChangeInstrument();
   1600   scoped_ptr<WalletItems::MaskedInstrument> reference_instrument =
   1601       GetTestMaskedInstrumentWithId("instrument_id");
   1602 
   1603   int new_month = instrument->expiration_month();
   1604   int new_year = instrument->expiration_year();
   1605   ASSERT_TRUE(new_month != reference_instrument->expiration_month() ||
   1606               new_year != reference_instrument->expiration_year());
   1607 
   1608   wallet_client_->SaveToWallet(instrument.Pass(),
   1609                                scoped_ptr<Address>(),
   1610                                reference_instrument.get(),
   1611                                NULL);
   1612 
   1613   VerifyAndFinishFormEncodedRequest(net::HTTP_OK,
   1614                                     kUpdateInstrumentExpirationDateValidRequest,
   1615                                     kUpdateInstrumentValidResponse,
   1616                                     3U);
   1617 }
   1618 
   1619 TEST_F(WalletClientTest, UpdateInstrumentAddressWithNameChangeSucceeded) {
   1620   EXPECT_CALL(delegate_,
   1621               OnDidSaveToWallet("instrument_id",
   1622                                 std::string(),
   1623                                 std::vector<RequiredAction>(),
   1624                                 std::vector<FormFieldError>())).Times(1);
   1625   delegate_.ExpectLogWalletApiCallDuration(AutofillMetrics::SAVE_TO_WALLET,
   1626                                            1);
   1627   delegate_.ExpectBaselineMetrics();
   1628 
   1629   scoped_ptr<WalletItems::MaskedInstrument> reference_instrument =
   1630       GetTestMaskedInstrument();
   1631   wallet_client_->SaveToWallet(GetTestAddressNameChangeInstrument(),
   1632                                scoped_ptr<Address>(),
   1633                                reference_instrument.get(),
   1634                                NULL);
   1635 
   1636   VerifyAndFinishFormEncodedRequest(
   1637       net::HTTP_OK,
   1638       kUpdateInstrumentAddressWithNameChangeValidRequest,
   1639       kUpdateInstrumentValidResponse,
   1640       3U);
   1641 }
   1642 
   1643 TEST_F(WalletClientTest, UpdateInstrumentWithRequiredActionsSucceeded) {
   1644   delegate_.ExpectLogWalletApiCallDuration(AutofillMetrics::SAVE_TO_WALLET,
   1645                                            1);
   1646   delegate_.ExpectBaselineMetrics();
   1647   delegate_.ExpectWalletRequiredActionMetric(
   1648       AutofillMetrics::REQUIRE_PHONE_NUMBER);
   1649   delegate_.ExpectWalletRequiredActionMetric(
   1650       AutofillMetrics::INVALID_FORM_FIELD);
   1651 
   1652   std::vector<RequiredAction> required_actions;
   1653   required_actions.push_back(REQUIRE_PHONE_NUMBER);
   1654   required_actions.push_back(INVALID_FORM_FIELD);
   1655 
   1656   std::vector<FormFieldError> form_errors;
   1657   form_errors.push_back(FormFieldError(FormFieldError::INVALID_POSTAL_CODE,
   1658                                        FormFieldError::SHIPPING_ADDRESS));
   1659 
   1660   EXPECT_CALL(delegate_,
   1661               OnDidSaveToWallet(std::string(),
   1662                                 std::string(),
   1663                                 required_actions,
   1664                                 form_errors)).Times(1);
   1665 
   1666   scoped_ptr<WalletItems::MaskedInstrument> reference_instrument =
   1667       GetTestMaskedInstrument();
   1668   wallet_client_->SaveToWallet(GetTestAddressUpgradeInstrument(),
   1669                                scoped_ptr<Address>(),
   1670                                reference_instrument.get(),
   1671                                NULL);
   1672 
   1673   VerifyAndFinishRequest(net::HTTP_OK,
   1674                          kUpdateInstrumentAddressValidRequest,
   1675                          kUpdateWithRequiredActionsValidResponse);
   1676 }
   1677 
   1678 TEST_F(WalletClientTest, UpdateInstrumentFailedInvalidRequiredAction) {
   1679   EXPECT_CALL(delegate_,
   1680               OnWalletError(WalletClient::MALFORMED_RESPONSE)).Times(1);
   1681   delegate_.ExpectLogWalletApiCallDuration(AutofillMetrics::SAVE_TO_WALLET,
   1682                                            1);
   1683   delegate_.ExpectBaselineMetrics();
   1684   delegate_.ExpectWalletErrorMetric(AutofillMetrics::WALLET_MALFORMED_RESPONSE);
   1685   delegate_.ExpectLogWalletMalformedResponse(AutofillMetrics::SAVE_TO_WALLET);
   1686 
   1687   scoped_ptr<WalletItems::MaskedInstrument> reference_instrument =
   1688       GetTestMaskedInstrument();
   1689   wallet_client_->SaveToWallet(GetTestAddressUpgradeInstrument(),
   1690                                scoped_ptr<Address>(),
   1691                                reference_instrument.get(),
   1692                                NULL);
   1693 
   1694   VerifyAndFinishRequest(net::HTTP_OK,
   1695                          kUpdateInstrumentAddressValidRequest,
   1696                          kSaveWithInvalidRequiredActionsResponse);
   1697 }
   1698 
   1699 TEST_F(WalletClientTest, UpdateInstrumentMalformedResponse) {
   1700   EXPECT_CALL(delegate_,
   1701               OnWalletError(WalletClient::MALFORMED_RESPONSE)).Times(1);
   1702   delegate_.ExpectLogWalletApiCallDuration(AutofillMetrics::SAVE_TO_WALLET,
   1703                                            1);
   1704   delegate_.ExpectBaselineMetrics();
   1705   delegate_.ExpectWalletErrorMetric(AutofillMetrics::WALLET_MALFORMED_RESPONSE);
   1706   delegate_.ExpectLogWalletMalformedResponse(AutofillMetrics::SAVE_TO_WALLET);
   1707 
   1708   scoped_ptr<WalletItems::MaskedInstrument> reference_instrument =
   1709       GetTestMaskedInstrument();
   1710   wallet_client_->SaveToWallet(GetTestAddressUpgradeInstrument(),
   1711                                scoped_ptr<Address>(),
   1712                                reference_instrument.get(),
   1713                                NULL);
   1714 
   1715   VerifyAndFinishRequest(net::HTTP_OK,
   1716                          kUpdateInstrumentAddressValidRequest,
   1717                          kUpdateMalformedResponse);
   1718 }
   1719 
   1720 TEST_F(WalletClientTest, HasRequestInProgress) {
   1721   EXPECT_FALSE(wallet_client_->HasRequestInProgress());
   1722   delegate_.ExpectLogWalletApiCallDuration(AutofillMetrics::GET_WALLET_ITEMS,
   1723                                            1);
   1724   delegate_.ExpectBaselineMetrics();
   1725 
   1726   wallet_client_->GetWalletItems();
   1727   EXPECT_TRUE(wallet_client_->HasRequestInProgress());
   1728 
   1729   VerifyAndFinishRequest(net::HTTP_OK,
   1730                          kGetWalletItemsValidRequest,
   1731                          kGetWalletItemsValidResponse);
   1732   EXPECT_FALSE(wallet_client_->HasRequestInProgress());
   1733 }
   1734 
   1735 TEST_F(WalletClientTest, ErrorResponse) {
   1736   EXPECT_FALSE(wallet_client_->HasRequestInProgress());
   1737   delegate_.ExpectBaselineMetrics();
   1738   wallet_client_->GetWalletItems();
   1739   EXPECT_TRUE(wallet_client_->HasRequestInProgress());
   1740   testing::Mock::VerifyAndClear(delegate_.metric_logger());
   1741 
   1742   EXPECT_CALL(delegate_, OnWalletError(
   1743       WalletClient::SERVICE_UNAVAILABLE)).Times(1);
   1744   delegate_.ExpectLogWalletApiCallDuration(AutofillMetrics::GET_WALLET_ITEMS,
   1745                                            1);
   1746   delegate_.ExpectWalletErrorMetric(
   1747       AutofillMetrics::WALLET_SERVICE_UNAVAILABLE);
   1748 
   1749   VerifyAndFinishRequest(net::HTTP_INTERNAL_SERVER_ERROR,
   1750                          kGetWalletItemsValidRequest,
   1751                          kErrorResponse);
   1752 }
   1753 
   1754 TEST_F(WalletClientTest, CancelRequest) {
   1755   EXPECT_FALSE(wallet_client_->HasRequestInProgress());
   1756   delegate_.ExpectLogWalletApiCallDuration(AutofillMetrics::GET_WALLET_ITEMS,
   1757                                            0);
   1758   delegate_.ExpectBaselineMetrics();
   1759 
   1760   wallet_client_->GetWalletItems();
   1761   EXPECT_TRUE(wallet_client_->HasRequestInProgress());
   1762   wallet_client_->CancelRequest();
   1763   EXPECT_FALSE(wallet_client_->HasRequestInProgress());
   1764 }
   1765 
   1766 }  // namespace wallet
   1767 }  // namespace autofill
   1768