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