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