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