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