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