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