Upstream version 5.34.104.0
[platform/framework/web/crosswalk.git] / src / google_apis / gcm / engine / registration_request_unittest.cc
1 // Copyright 2014 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 <map>
6 #include <string>
7 #include <vector>
8
9 #include "base/strings/string_number_conversions.h"
10 #include "base/strings/string_tokenizer.h"
11 #include "google_apis/gcm/engine/registration_request.h"
12 #include "net/url_request/test_url_fetcher_factory.h"
13 #include "net/url_request/url_request_test_util.h"
14 #include "testing/gtest/include/gtest/gtest.h"
15
16 namespace gcm {
17
18 namespace {
19 const uint64 kAndroidId = 42UL;
20 const char kCert[] = "0DEADBEEF420";
21 const char kDeveloperId[] = "Project1";
22 const char kLoginHeader[] = "AidLogin";
23 const char kAppId[] = "TestAppId";
24 const uint64 kSecurityToken = 77UL;
25
26 // Backoff policy for testing registration request.
27 const net::BackoffEntry::Policy kDefaultBackoffPolicy = {
28   // Number of initial errors (in sequence) to ignore before applying
29   // exponential back-off rules.
30   // Explicitly set to 2 to skip the delay on the first retry, as we are not
31   // trying to test the backoff itself, but rather the fact that retry happens.
32   2,
33
34   // Initial delay for exponential back-off in ms.
35   15000,  // 15 seconds.
36
37   // Factor by which the waiting time will be multiplied.
38   2,
39
40   // Fuzzing percentage. ex: 10% will spread requests randomly
41   // between 90%-100% of the calculated time.
42   0.5,  // 50%.
43
44   // Maximum amount of time we are willing to delay our request in ms.
45   1000 * 60 * 5, // 5 minutes.
46
47   // Time to keep an entry from being discarded even when it
48   // has no significant state, -1 to never discard.
49   -1,
50
51   // Don't use initial delay unless the last request was an error.
52   false,
53 };
54
55 }  // namespace
56
57 class RegistrationRequestTest : public testing::Test {
58  public:
59   RegistrationRequestTest();
60   virtual ~RegistrationRequestTest();
61
62   void RegistrationCallback(RegistrationRequest::Status status,
63                             const std::string& registration_id);
64
65   void CreateRequest(const std::string& sender_ids);
66   void SetResponseStatusAndString(net::HttpStatusCode status_code,
67                                   const std::string& response_body);
68   void CompleteFetch();
69
70  protected:
71   RegistrationRequest::Status status_;
72   std::string registration_id_;
73   bool callback_called_;
74   std::map<std::string, std::string> extras_;
75   scoped_ptr<RegistrationRequest> request_;
76   base::MessageLoop message_loop_;
77   net::TestURLFetcherFactory url_fetcher_factory_;
78   scoped_refptr<net::TestURLRequestContextGetter> url_request_context_getter_;
79 };
80
81 RegistrationRequestTest::RegistrationRequestTest()
82     : status_(RegistrationRequest::SUCCESS),
83       callback_called_(false),
84       url_request_context_getter_(new net::TestURLRequestContextGetter(
85           message_loop_.message_loop_proxy())) {}
86
87 RegistrationRequestTest::~RegistrationRequestTest() {}
88
89 void RegistrationRequestTest::RegistrationCallback(
90     RegistrationRequest::Status status,
91     const std::string& registration_id) {
92   status_ = status;
93   registration_id_ = registration_id;
94   callback_called_ = true;
95 }
96
97 void RegistrationRequestTest::CreateRequest(const std::string& sender_ids) {
98   std::vector<std::string> senders;
99   base::StringTokenizer tokenizer(sender_ids, ",");
100   while (tokenizer.GetNext())
101     senders.push_back(tokenizer.token());
102
103   request_.reset(new RegistrationRequest(
104       RegistrationRequest::RequestInfo(kAndroidId,
105                                        kSecurityToken,
106                                        kAppId,
107                                        kCert,
108                                        senders),
109       kDefaultBackoffPolicy,
110       base::Bind(&RegistrationRequestTest::RegistrationCallback,
111                  base::Unretained(this)),
112       url_request_context_getter_.get()));
113 }
114
115 void RegistrationRequestTest::SetResponseStatusAndString(
116     net::HttpStatusCode status_code,
117     const std::string& response_body) {
118   net::TestURLFetcher* fetcher = url_fetcher_factory_.GetFetcherByID(0);
119   ASSERT_TRUE(fetcher);
120   fetcher->set_response_code(status_code);
121   fetcher->SetResponseString(response_body);
122 }
123
124 void RegistrationRequestTest::CompleteFetch() {
125   registration_id_.clear();
126   status_ = RegistrationRequest::SUCCESS;
127   callback_called_ = false;
128
129   net::TestURLFetcher* fetcher = url_fetcher_factory_.GetFetcherByID(0);
130   ASSERT_TRUE(fetcher);
131   fetcher->delegate()->OnURLFetchComplete(fetcher);
132 }
133
134 TEST_F(RegistrationRequestTest, RequestDataPassedToFetcher) {
135   CreateRequest(kDeveloperId);
136   request_->Start();
137
138   // Get data sent by request.
139   net::TestURLFetcher* fetcher = url_fetcher_factory_.GetFetcherByID(0);
140   ASSERT_TRUE(fetcher);
141
142   // Verify that authorization header was put together properly.
143   net::HttpRequestHeaders headers;
144   fetcher->GetExtraRequestHeaders(&headers);
145   std::string auth_header;
146   headers.GetHeader(net::HttpRequestHeaders::kAuthorization, &auth_header);
147   base::StringTokenizer auth_tokenizer(auth_header, " :");
148   ASSERT_TRUE(auth_tokenizer.GetNext());
149   EXPECT_EQ(kLoginHeader, auth_tokenizer.token());
150   ASSERT_TRUE(auth_tokenizer.GetNext());
151   EXPECT_EQ(base::Uint64ToString(kAndroidId), auth_tokenizer.token());
152   ASSERT_TRUE(auth_tokenizer.GetNext());
153   EXPECT_EQ(base::Uint64ToString(kSecurityToken), auth_tokenizer.token());
154
155   std::map<std::string, std::string> expected_pairs;
156   expected_pairs["app"] = kAppId;
157   expected_pairs["sender"] = kDeveloperId;
158   expected_pairs["cert"] = kCert;
159   expected_pairs["device"] = base::Uint64ToString(kAndroidId);
160
161   // Verify data was formatted properly.
162   std::string upload_data = fetcher->upload_data();
163   base::StringTokenizer data_tokenizer(upload_data, "&=");
164   while (data_tokenizer.GetNext()) {
165     std::map<std::string, std::string>::iterator iter =
166         expected_pairs.find(data_tokenizer.token());
167     ASSERT_TRUE(iter != expected_pairs.end());
168     ASSERT_TRUE(data_tokenizer.GetNext());
169     EXPECT_EQ(iter->second, data_tokenizer.token());
170     // Ensure that none of the keys appears twice.
171     expected_pairs.erase(iter);
172   }
173
174   EXPECT_EQ(0UL, expected_pairs.size());
175 }
176
177 TEST_F(RegistrationRequestTest, RequestRegistrationWithMultipleSenderIds) {
178   CreateRequest("sender1,sender2@gmail.com");
179   request_->Start();
180
181   net::TestURLFetcher* fetcher = url_fetcher_factory_.GetFetcherByID(0);
182   ASSERT_TRUE(fetcher);
183
184   // Verify data was formatted properly.
185   std::string upload_data = fetcher->upload_data();
186   base::StringTokenizer data_tokenizer(upload_data, "&=");
187
188   // Skip all tokens until you hit entry for senders.
189   while (data_tokenizer.GetNext() && data_tokenizer.token() != "sender")
190     continue;
191
192   ASSERT_TRUE(data_tokenizer.GetNext());
193   std::string senders(net::UnescapeURLComponent(data_tokenizer.token(),
194       net::UnescapeRule::URL_SPECIAL_CHARS));
195   base::StringTokenizer sender_tokenizer(senders, ",");
196   ASSERT_TRUE(sender_tokenizer.GetNext());
197   EXPECT_EQ("sender1", sender_tokenizer.token());
198   ASSERT_TRUE(sender_tokenizer.GetNext());
199   EXPECT_EQ("sender2@gmail.com", sender_tokenizer.token());
200 }
201
202 TEST_F(RegistrationRequestTest, ResponseParsing) {
203   CreateRequest("sender1,sender2");
204   request_->Start();
205
206   SetResponseStatusAndString(net::HTTP_OK, "token=2501");
207   CompleteFetch();
208
209   EXPECT_TRUE(callback_called_);
210   EXPECT_EQ(RegistrationRequest::SUCCESS, status_);
211   EXPECT_EQ("2501", registration_id_);
212 }
213
214 TEST_F(RegistrationRequestTest, ResponseHttpStatusNotOK) {
215   CreateRequest("sender1,sender2");
216   request_->Start();
217
218   SetResponseStatusAndString(net::HTTP_UNAUTHORIZED, "token=2501");
219   CompleteFetch();
220
221   EXPECT_FALSE(callback_called_);
222
223   SetResponseStatusAndString(net::HTTP_OK, "token=2501");
224   CompleteFetch();
225
226   EXPECT_TRUE(callback_called_);
227   EXPECT_EQ(RegistrationRequest::SUCCESS, status_);
228   EXPECT_EQ("2501", registration_id_);
229 }
230
231 TEST_F(RegistrationRequestTest, ResponseMissingRegistrationId) {
232   CreateRequest("sender1,sender2");
233   request_->Start();
234
235   SetResponseStatusAndString(net::HTTP_OK, "");
236   CompleteFetch();
237
238   EXPECT_FALSE(callback_called_);
239
240   SetResponseStatusAndString(net::HTTP_OK, "some error in response");
241   CompleteFetch();
242
243   EXPECT_FALSE(callback_called_);
244
245   // Ensuring a retry happened and succeeds.
246   SetResponseStatusAndString(net::HTTP_OK, "token=2501");
247   CompleteFetch();
248
249   EXPECT_TRUE(callback_called_);
250   EXPECT_EQ(RegistrationRequest::SUCCESS, status_);
251   EXPECT_EQ("2501", registration_id_);
252 }
253
254 TEST_F(RegistrationRequestTest, ResponseDeviceRegistrationError) {
255   CreateRequest("sender1,sender2");
256   request_->Start();
257
258   SetResponseStatusAndString(net::HTTP_OK, "Error=PHONE_REGISTRATION_ERROR");
259   CompleteFetch();
260
261   EXPECT_FALSE(callback_called_);
262
263   // Ensuring a retry happened and succeeds.
264   SetResponseStatusAndString(net::HTTP_OK, "token=2501");
265   CompleteFetch();
266
267   EXPECT_TRUE(callback_called_);
268   EXPECT_EQ(RegistrationRequest::SUCCESS, status_);
269   EXPECT_EQ("2501", registration_id_);
270 }
271
272 TEST_F(RegistrationRequestTest, ResponseAuthenticationError) {
273   CreateRequest("sender1,sender2");
274   request_->Start();
275
276   SetResponseStatusAndString(net::HTTP_OK, "Error=AUTHENTICATION_FAILED");
277   CompleteFetch();
278
279   EXPECT_FALSE(callback_called_);
280
281   // Ensuring a retry happened and succeeds.
282   SetResponseStatusAndString(net::HTTP_OK, "token=2501");
283   CompleteFetch();
284
285   EXPECT_TRUE(callback_called_);
286   EXPECT_EQ(RegistrationRequest::SUCCESS, status_);
287   EXPECT_EQ("2501", registration_id_);
288 }
289
290 TEST_F(RegistrationRequestTest, ResponseInvalidParameters) {
291   CreateRequest("sender1,sender2");
292   request_->Start();
293
294   SetResponseStatusAndString(net::HTTP_OK, "Error=INVALID_PARAMETERS");
295   CompleteFetch();
296
297   EXPECT_TRUE(callback_called_);
298   EXPECT_EQ(RegistrationRequest::INVALID_PARAMETERS, status_);
299   EXPECT_EQ(std::string(), registration_id_);
300 }
301
302 TEST_F(RegistrationRequestTest, ResponseInvalidSender) {
303   CreateRequest("sender1,sender2");
304   request_->Start();
305
306   SetResponseStatusAndString(net::HTTP_OK, "Error=INVALID_SENDER");
307   CompleteFetch();
308
309   EXPECT_TRUE(callback_called_);
310   EXPECT_EQ(RegistrationRequest::INVALID_SENDER, status_);
311   EXPECT_EQ(std::string(), registration_id_);
312 }
313
314 }  // namespace gcm