Update V8 to version 4.5.91.
[chromium-blink-merge.git] / components / gcm_driver / gcm_client_impl_unittest.cc
blob37851c08fa2f727cc7c794fb34d570d2400299c8
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.
5 #include "components/gcm_driver/gcm_client_impl.h"
7 #include "base/command_line.h"
8 #include "base/files/file_path.h"
9 #include "base/files/file_util.h"
10 #include "base/files/scoped_temp_dir.h"
11 #include "base/memory/scoped_ptr.h"
12 #include "base/strings/string_number_conversions.h"
13 #include "base/test/test_mock_time_task_runner.h"
14 #include "base/thread_task_runner_handle.h"
15 #include "base/time/clock.h"
16 #include "base/timer/timer.h"
17 #include "google_apis/gcm/base/fake_encryptor.h"
18 #include "google_apis/gcm/base/mcs_message.h"
19 #include "google_apis/gcm/base/mcs_util.h"
20 #include "google_apis/gcm/engine/fake_connection_factory.h"
21 #include "google_apis/gcm/engine/fake_connection_handler.h"
22 #include "google_apis/gcm/engine/gservices_settings.h"
23 #include "google_apis/gcm/monitoring/gcm_stats_recorder.h"
24 #include "google_apis/gcm/protocol/android_checkin.pb.h"
25 #include "google_apis/gcm/protocol/checkin.pb.h"
26 #include "google_apis/gcm/protocol/mcs.pb.h"
27 #include "net/url_request/test_url_fetcher_factory.h"
28 #include "net/url_request/url_fetcher_delegate.h"
29 #include "net/url_request/url_request_test_util.h"
30 #include "testing/gtest/include/gtest/gtest.h"
32 namespace gcm {
34 namespace {
36 enum LastEvent {
37 NONE,
38 LOADING_COMPLETED,
39 REGISTRATION_COMPLETED,
40 UNREGISTRATION_COMPLETED,
41 MESSAGE_SEND_ERROR,
42 MESSAGE_SEND_ACK,
43 MESSAGE_RECEIVED,
44 MESSAGES_DELETED,
47 const char kChromeVersion[] = "45.0.0.1";
48 const uint64 kDeviceAndroidId = 54321;
49 const uint64 kDeviceSecurityToken = 12345;
50 const uint64 kDeviceAndroidId2 = 11111;
51 const uint64 kDeviceSecurityToken2 = 2222;
52 const int64 kSettingsCheckinInterval = 16 * 60 * 60;
53 const char kAppId[] = "app_id";
54 const char kSender[] = "project_id";
55 const char kSender2[] = "project_id2";
56 const char kSender3[] = "project_id3";
57 const char kRegistrationResponsePrefix[] = "token=";
58 const char kUnregistrationResponsePrefix[] = "deleted=";
60 const char kInstanceID[] = "iid_1";
61 const char kScope[] = "GCM";
62 const char kDeleteTokenResponse[] = "token=foo";
64 // Helper for building arbitrary data messages.
65 MCSMessage BuildDownstreamMessage(
66 const std::string& project_id,
67 const std::string& app_id,
68 const std::map<std::string, std::string>& data) {
69 mcs_proto::DataMessageStanza data_message;
70 data_message.set_from(project_id);
71 data_message.set_category(app_id);
72 for (std::map<std::string, std::string>::const_iterator iter = data.begin();
73 iter != data.end();
74 ++iter) {
75 mcs_proto::AppData* app_data = data_message.add_app_data();
76 app_data->set_key(iter->first);
77 app_data->set_value(iter->second);
79 return MCSMessage(kDataMessageStanzaTag, data_message);
82 GCMClient::AccountTokenInfo MakeAccountToken(const std::string& email,
83 const std::string& token) {
84 GCMClient::AccountTokenInfo account_token;
85 account_token.email = email;
86 account_token.access_token = token;
87 return account_token;
90 std::map<std::string, std::string> MakeEmailToTokenMap(
91 const std::vector<GCMClient::AccountTokenInfo>& account_tokens) {
92 std::map<std::string, std::string> email_token_map;
93 for (std::vector<GCMClient::AccountTokenInfo>::const_iterator iter =
94 account_tokens.begin(); iter != account_tokens.end(); ++iter) {
95 email_token_map[iter->email] = iter->access_token;
97 return email_token_map;
100 class FakeMCSClient : public MCSClient {
101 public:
102 FakeMCSClient(base::Clock* clock,
103 ConnectionFactory* connection_factory,
104 GCMStore* gcm_store,
105 GCMStatsRecorder* recorder);
106 ~FakeMCSClient() override;
107 void Login(uint64 android_id, uint64 security_token) override;
108 void SendMessage(const MCSMessage& message) override;
110 uint64 last_android_id() const { return last_android_id_; }
111 uint64 last_security_token() const { return last_security_token_; }
112 uint8 last_message_tag() const { return last_message_tag_; }
113 const mcs_proto::DataMessageStanza& last_data_message_stanza() const {
114 return last_data_message_stanza_;
117 private:
118 uint64 last_android_id_;
119 uint64 last_security_token_;
120 uint8 last_message_tag_;
121 mcs_proto::DataMessageStanza last_data_message_stanza_;
124 FakeMCSClient::FakeMCSClient(base::Clock* clock,
125 ConnectionFactory* connection_factory,
126 GCMStore* gcm_store,
127 GCMStatsRecorder* recorder)
128 : MCSClient("", clock, connection_factory, gcm_store, recorder),
129 last_android_id_(0u),
130 last_security_token_(0u),
131 last_message_tag_(kNumProtoTypes) {
134 FakeMCSClient::~FakeMCSClient() {
137 void FakeMCSClient::Login(uint64 android_id, uint64 security_token) {
138 last_android_id_ = android_id;
139 last_security_token_ = security_token;
142 void FakeMCSClient::SendMessage(const MCSMessage& message) {
143 last_message_tag_ = message.tag();
144 if (last_message_tag_ == kDataMessageStanzaTag) {
145 last_data_message_stanza_.CopyFrom(
146 reinterpret_cast<const mcs_proto::DataMessageStanza&>(
147 message.GetProtobuf()));
151 class AutoAdvancingTestClock : public base::Clock {
152 public:
153 explicit AutoAdvancingTestClock(base::TimeDelta auto_increment_time_delta);
154 ~AutoAdvancingTestClock() override;
156 base::Time Now() override;
157 void Advance(TimeDelta delta);
158 int call_count() const { return call_count_; }
160 private:
161 int call_count_;
162 base::TimeDelta auto_increment_time_delta_;
163 base::Time now_;
165 DISALLOW_COPY_AND_ASSIGN(AutoAdvancingTestClock);
168 AutoAdvancingTestClock::AutoAdvancingTestClock(
169 base::TimeDelta auto_increment_time_delta)
170 : call_count_(0), auto_increment_time_delta_(auto_increment_time_delta) {
173 AutoAdvancingTestClock::~AutoAdvancingTestClock() {
176 base::Time AutoAdvancingTestClock::Now() {
177 call_count_++;
178 now_ += auto_increment_time_delta_;
179 return now_;
182 void AutoAdvancingTestClock::Advance(base::TimeDelta delta) {
183 now_ += delta;
186 class FakeGCMInternalsBuilder : public GCMInternalsBuilder {
187 public:
188 FakeGCMInternalsBuilder(base::TimeDelta clock_step);
189 ~FakeGCMInternalsBuilder() override;
191 scoped_ptr<base::Clock> BuildClock() override;
192 scoped_ptr<MCSClient> BuildMCSClient(const std::string& version,
193 base::Clock* clock,
194 ConnectionFactory* connection_factory,
195 GCMStore* gcm_store,
196 GCMStatsRecorder* recorder) override;
197 scoped_ptr<ConnectionFactory> BuildConnectionFactory(
198 const std::vector<GURL>& endpoints,
199 const net::BackoffEntry::Policy& backoff_policy,
200 const scoped_refptr<net::HttpNetworkSession>& gcm_network_session,
201 const scoped_refptr<net::HttpNetworkSession>& http_network_session,
202 net::NetLog* net_log,
203 GCMStatsRecorder* recorder) override;
205 private:
206 base::TimeDelta clock_step_;
209 FakeGCMInternalsBuilder::FakeGCMInternalsBuilder(base::TimeDelta clock_step)
210 : clock_step_(clock_step) {
213 FakeGCMInternalsBuilder::~FakeGCMInternalsBuilder() {}
215 scoped_ptr<base::Clock> FakeGCMInternalsBuilder::BuildClock() {
216 return make_scoped_ptr<base::Clock>(new AutoAdvancingTestClock(clock_step_));
219 scoped_ptr<MCSClient> FakeGCMInternalsBuilder::BuildMCSClient(
220 const std::string& version,
221 base::Clock* clock,
222 ConnectionFactory* connection_factory,
223 GCMStore* gcm_store,
224 GCMStatsRecorder* recorder) {
225 return make_scoped_ptr<MCSClient>(new FakeMCSClient(clock,
226 connection_factory,
227 gcm_store,
228 recorder));
231 scoped_ptr<ConnectionFactory> FakeGCMInternalsBuilder::BuildConnectionFactory(
232 const std::vector<GURL>& endpoints,
233 const net::BackoffEntry::Policy& backoff_policy,
234 const scoped_refptr<net::HttpNetworkSession>& gcm_network_session,
235 const scoped_refptr<net::HttpNetworkSession>& http_network_session,
236 net::NetLog* net_log,
237 GCMStatsRecorder* recorder) {
238 return make_scoped_ptr<ConnectionFactory>(new FakeConnectionFactory());
241 } // namespace
243 class GCMClientImplTest : public testing::Test,
244 public GCMClient::Delegate {
245 public:
246 GCMClientImplTest();
247 ~GCMClientImplTest() override;
249 void SetUp() override;
251 void SetUpUrlFetcherFactory();
253 void BuildGCMClient(base::TimeDelta clock_step);
254 void InitializeGCMClient();
255 void StartGCMClient();
256 void Register(const std::string& app_id,
257 const std::vector<std::string>& senders);
258 void Unregister(const std::string& app_id);
259 void ReceiveMessageFromMCS(const MCSMessage& message);
260 void ReceiveOnMessageSentToMCS(
261 const std::string& app_id,
262 const std::string& message_id,
263 const MCSClient::MessageSendStatus status);
264 void CompleteCheckin(uint64 android_id,
265 uint64 security_token,
266 const std::string& digest,
267 const std::map<std::string, std::string>& settings);
268 void CompleteRegistration(const std::string& registration_id);
269 void CompleteUnregistration(const std::string& app_id);
270 void VerifyPendingRequestFetcherDeleted();
272 bool ExistsRegistration(const std::string& app_id) const;
273 void AddRegistration(const std::string& app_id,
274 const std::vector<std::string>& sender_ids,
275 const std::string& registration_id);
277 // GCMClient::Delegate overrides (for verification).
278 void OnRegisterFinished(const linked_ptr<RegistrationInfo>& registration_info,
279 const std::string& registration_id,
280 GCMClient::Result result) override;
281 void OnUnregisterFinished(
282 const linked_ptr<RegistrationInfo>& registration_info,
283 GCMClient::Result result) override;
284 void OnSendFinished(const std::string& app_id,
285 const std::string& message_id,
286 GCMClient::Result result) override {}
287 void OnMessageReceived(const std::string& registration_id,
288 const GCMClient::IncomingMessage& message) override;
289 void OnMessagesDeleted(const std::string& app_id) override;
290 void OnMessageSendError(
291 const std::string& app_id,
292 const gcm::GCMClient::SendErrorDetails& send_error_details) override;
293 void OnSendAcknowledged(const std::string& app_id,
294 const std::string& message_id) override;
295 void OnGCMReady(const std::vector<AccountMapping>& account_mappings,
296 const base::Time& last_token_fetch_time) override;
297 void OnActivityRecorded() override {}
298 void OnConnected(const net::IPEndPoint& ip_endpoint) override {}
299 void OnDisconnected() override {}
301 GCMClientImpl* gcm_client() const { return gcm_client_.get(); }
302 GCMClientImpl::State gcm_client_state() const {
303 return gcm_client_->state_;
305 FakeMCSClient* mcs_client() const {
306 return reinterpret_cast<FakeMCSClient*>(gcm_client_->mcs_client_.get());
308 ConnectionFactory* connection_factory() const {
309 return gcm_client_->connection_factory_.get();
312 const GCMClientImpl::CheckinInfo& device_checkin_info() const {
313 return gcm_client_->device_checkin_info_;
316 void reset_last_event() {
317 last_event_ = NONE;
318 last_app_id_.clear();
319 last_registration_id_.clear();
320 last_message_id_.clear();
321 last_result_ = GCMClient::UNKNOWN_ERROR;
322 last_account_mappings_.clear();
323 last_token_fetch_time_ = base::Time();
326 LastEvent last_event() const { return last_event_; }
327 const std::string& last_app_id() const { return last_app_id_; }
328 const std::string& last_registration_id() const {
329 return last_registration_id_;
331 const std::string& last_message_id() const { return last_message_id_; }
332 GCMClient::Result last_result() const { return last_result_; }
333 const GCMClient::IncomingMessage& last_message() const {
334 return last_message_;
336 const GCMClient::SendErrorDetails& last_error_details() const {
337 return last_error_details_;
339 const base::Time& last_token_fetch_time() const {
340 return last_token_fetch_time_;
342 const std::vector<AccountMapping>& last_account_mappings() {
343 return last_account_mappings_;
346 const GServicesSettings& gservices_settings() const {
347 return gcm_client_->gservices_settings_;
350 const base::FilePath& temp_directory_path() const {
351 return temp_directory_.path();
354 base::FilePath gcm_store_path() const {
355 // Pass an non-existent directory as store path to match the exact
356 // behavior in the production code. Currently GCMStoreImpl checks if
357 // the directory exist or not to determine the store existence.
358 return temp_directory_.path().Append(FILE_PATH_LITERAL("GCM Store"));
361 int64 CurrentTime();
363 // Tooling.
364 void PumpLoopUntilIdle();
365 bool CreateUniqueTempDir();
366 AutoAdvancingTestClock* clock() const {
367 return reinterpret_cast<AutoAdvancingTestClock*>(gcm_client_->clock_.get());
369 net::TestURLFetcherFactory* url_fetcher_factory() {
370 return &url_fetcher_factory_;
372 base::TestMockTimeTaskRunner* task_runner() {
373 return task_runner_.get();
376 private:
377 // Variables used for verification.
378 LastEvent last_event_;
379 std::string last_app_id_;
380 std::string last_registration_id_;
381 std::string last_message_id_;
382 GCMClient::Result last_result_;
383 GCMClient::IncomingMessage last_message_;
384 GCMClient::SendErrorDetails last_error_details_;
385 base::Time last_token_fetch_time_;
386 std::vector<AccountMapping> last_account_mappings_;
388 scoped_ptr<GCMClientImpl> gcm_client_;
390 net::TestURLFetcherFactory url_fetcher_factory_;
392 scoped_refptr<base::TestMockTimeTaskRunner> task_runner_;
393 base::ThreadTaskRunnerHandle task_runner_handle_;
395 // Injected to GCM client:
396 base::ScopedTempDir temp_directory_;
397 scoped_refptr<net::TestURLRequestContextGetter> url_request_context_getter_;
400 GCMClientImplTest::GCMClientImplTest()
401 : last_event_(NONE),
402 last_result_(GCMClient::UNKNOWN_ERROR),
403 task_runner_(new base::TestMockTimeTaskRunner),
404 task_runner_handle_(task_runner_),
405 url_request_context_getter_(
406 new net::TestURLRequestContextGetter(task_runner_)) {
409 GCMClientImplTest::~GCMClientImplTest() {}
411 void GCMClientImplTest::SetUp() {
412 testing::Test::SetUp();
413 ASSERT_TRUE(CreateUniqueTempDir());
414 BuildGCMClient(base::TimeDelta());
415 InitializeGCMClient();
416 StartGCMClient();
417 SetUpUrlFetcherFactory();
418 CompleteCheckin(kDeviceAndroidId,
419 kDeviceSecurityToken,
420 std::string(),
421 std::map<std::string, std::string>());
424 void GCMClientImplTest::SetUpUrlFetcherFactory() {
425 url_fetcher_factory_.set_remove_fetcher_on_delete(true);
428 void GCMClientImplTest::PumpLoopUntilIdle() {
429 task_runner_->RunUntilIdle();
432 bool GCMClientImplTest::CreateUniqueTempDir() {
433 return temp_directory_.CreateUniqueTempDir();
436 void GCMClientImplTest::BuildGCMClient(base::TimeDelta clock_step) {
437 gcm_client_.reset(new GCMClientImpl(make_scoped_ptr<GCMInternalsBuilder>(
438 new FakeGCMInternalsBuilder(clock_step))));
441 void GCMClientImplTest::CompleteCheckin(
442 uint64 android_id,
443 uint64 security_token,
444 const std::string& digest,
445 const std::map<std::string, std::string>& settings) {
446 checkin_proto::AndroidCheckinResponse response;
447 response.set_stats_ok(true);
448 response.set_android_id(android_id);
449 response.set_security_token(security_token);
451 // For testing G-services settings.
452 if (!digest.empty()) {
453 response.set_digest(digest);
454 for (std::map<std::string, std::string>::const_iterator it =
455 settings.begin();
456 it != settings.end();
457 ++it) {
458 checkin_proto::GservicesSetting* setting = response.add_setting();
459 setting->set_name(it->first);
460 setting->set_value(it->second);
462 response.set_settings_diff(false);
465 std::string response_string;
466 response.SerializeToString(&response_string);
468 net::TestURLFetcher* fetcher = url_fetcher_factory_.GetFetcherByID(0);
469 ASSERT_TRUE(fetcher);
470 fetcher->set_response_code(net::HTTP_OK);
471 fetcher->SetResponseString(response_string);
472 fetcher->delegate()->OnURLFetchComplete(fetcher);
473 // Give a chance for GCMStoreImpl::Backend to finish persisting data.
474 PumpLoopUntilIdle();
477 void GCMClientImplTest::CompleteRegistration(
478 const std::string& registration_id) {
479 std::string response(kRegistrationResponsePrefix);
480 response.append(registration_id);
481 net::TestURLFetcher* fetcher = url_fetcher_factory_.GetFetcherByID(0);
482 ASSERT_TRUE(fetcher);
483 fetcher->set_response_code(net::HTTP_OK);
484 fetcher->SetResponseString(response);
485 fetcher->delegate()->OnURLFetchComplete(fetcher);
486 // Give a chance for GCMStoreImpl::Backend to finish persisting data.
487 PumpLoopUntilIdle();
490 void GCMClientImplTest::CompleteUnregistration(
491 const std::string& app_id) {
492 std::string response(kUnregistrationResponsePrefix);
493 response.append(app_id);
494 net::TestURLFetcher* fetcher = url_fetcher_factory_.GetFetcherByID(0);
495 ASSERT_TRUE(fetcher);
496 fetcher->set_response_code(net::HTTP_OK);
497 fetcher->SetResponseString(response);
498 fetcher->delegate()->OnURLFetchComplete(fetcher);
499 // Give a chance for GCMStoreImpl::Backend to finish persisting data.
500 PumpLoopUntilIdle();
503 void GCMClientImplTest::VerifyPendingRequestFetcherDeleted() {
504 net::TestURLFetcher* fetcher = url_fetcher_factory_.GetFetcherByID(0);
505 EXPECT_FALSE(fetcher);
508 bool GCMClientImplTest::ExistsRegistration(const std::string& app_id) const {
509 return ExistsGCMRegistrationInMap(gcm_client_->registrations_, app_id);
512 void GCMClientImplTest::AddRegistration(
513 const std::string& app_id,
514 const std::vector<std::string>& sender_ids,
515 const std::string& registration_id) {
516 linked_ptr<GCMRegistrationInfo> registration(new GCMRegistrationInfo);
517 registration->app_id = app_id;
518 registration->sender_ids = sender_ids;
519 gcm_client_->registrations_[registration] = registration_id;
522 void GCMClientImplTest::InitializeGCMClient() {
523 clock()->Advance(base::TimeDelta::FromMilliseconds(1));
525 // Actual initialization.
526 GCMClient::ChromeBuildInfo chrome_build_info;
527 chrome_build_info.version = kChromeVersion;
528 gcm_client_->Initialize(
529 chrome_build_info,
530 gcm_store_path(),
531 task_runner_,
532 url_request_context_getter_,
533 make_scoped_ptr<Encryptor>(new FakeEncryptor),
534 this);
537 void GCMClientImplTest::StartGCMClient() {
538 // Start loading and check-in.
539 gcm_client_->Start(GCMClient::IMMEDIATE_START);
541 PumpLoopUntilIdle();
544 void GCMClientImplTest::Register(const std::string& app_id,
545 const std::vector<std::string>& senders) {
546 scoped_ptr<GCMRegistrationInfo> gcm_info(new GCMRegistrationInfo);
547 gcm_info->app_id = app_id;
548 gcm_info->sender_ids = senders;
549 gcm_client()->Register(make_linked_ptr<RegistrationInfo>(gcm_info.release()));
552 void GCMClientImplTest::Unregister(const std::string& app_id) {
553 scoped_ptr<GCMRegistrationInfo> gcm_info(new GCMRegistrationInfo);
554 gcm_info->app_id = app_id;
555 gcm_client()->Unregister(
556 make_linked_ptr<RegistrationInfo>(gcm_info.release()));
559 void GCMClientImplTest::ReceiveMessageFromMCS(const MCSMessage& message) {
560 gcm_client_->recorder_.RecordConnectionInitiated(std::string());
561 gcm_client_->recorder_.RecordConnectionSuccess();
562 gcm_client_->OnMessageReceivedFromMCS(message);
565 void GCMClientImplTest::ReceiveOnMessageSentToMCS(
566 const std::string& app_id,
567 const std::string& message_id,
568 const MCSClient::MessageSendStatus status) {
569 gcm_client_->OnMessageSentToMCS(0LL, app_id, message_id, status);
572 void GCMClientImplTest::OnGCMReady(
573 const std::vector<AccountMapping>& account_mappings,
574 const base::Time& last_token_fetch_time) {
575 last_event_ = LOADING_COMPLETED;
576 last_account_mappings_ = account_mappings;
577 last_token_fetch_time_ = last_token_fetch_time;
580 void GCMClientImplTest::OnMessageReceived(
581 const std::string& registration_id,
582 const GCMClient::IncomingMessage& message) {
583 last_event_ = MESSAGE_RECEIVED;
584 last_app_id_ = registration_id;
585 last_message_ = message;
588 void GCMClientImplTest::OnRegisterFinished(
589 const linked_ptr<RegistrationInfo>& registration_info,
590 const std::string& registration_id,
591 GCMClient::Result result) {
592 last_event_ = REGISTRATION_COMPLETED;
593 last_app_id_ = registration_info->app_id;
594 last_registration_id_ = registration_id;
595 last_result_ = result;
598 void GCMClientImplTest::OnUnregisterFinished(
599 const linked_ptr<RegistrationInfo>& registration_info,
600 GCMClient::Result result) {
601 last_event_ = UNREGISTRATION_COMPLETED;
602 last_app_id_ = registration_info->app_id;
603 last_result_ = result;
606 void GCMClientImplTest::OnMessagesDeleted(const std::string& app_id) {
607 last_event_ = MESSAGES_DELETED;
608 last_app_id_ = app_id;
611 void GCMClientImplTest::OnMessageSendError(
612 const std::string& app_id,
613 const gcm::GCMClient::SendErrorDetails& send_error_details) {
614 last_event_ = MESSAGE_SEND_ERROR;
615 last_app_id_ = app_id;
616 last_error_details_ = send_error_details;
619 void GCMClientImplTest::OnSendAcknowledged(const std::string& app_id,
620 const std::string& message_id) {
621 last_event_ = MESSAGE_SEND_ACK;
622 last_app_id_ = app_id;
623 last_message_id_ = message_id;
626 int64 GCMClientImplTest::CurrentTime() {
627 return clock()->Now().ToInternalValue() / base::Time::kMicrosecondsPerSecond;
630 TEST_F(GCMClientImplTest, LoadingCompleted) {
631 EXPECT_EQ(LOADING_COMPLETED, last_event());
632 EXPECT_EQ(kDeviceAndroidId, mcs_client()->last_android_id());
633 EXPECT_EQ(kDeviceSecurityToken, mcs_client()->last_security_token());
635 // Checking freshly loaded CheckinInfo.
636 EXPECT_EQ(kDeviceAndroidId, device_checkin_info().android_id);
637 EXPECT_EQ(kDeviceSecurityToken, device_checkin_info().secret);
638 EXPECT_TRUE(device_checkin_info().last_checkin_accounts.empty());
639 EXPECT_TRUE(device_checkin_info().accounts_set);
640 EXPECT_TRUE(device_checkin_info().account_tokens.empty());
643 TEST_F(GCMClientImplTest, LoadingBusted) {
644 // Close the GCM store.
645 gcm_client()->Stop();
646 PumpLoopUntilIdle();
648 // Mess up the store.
649 base::FilePath store_file_path =
650 gcm_store_path().Append(FILE_PATH_LITERAL("CURRENT"));
651 ASSERT_TRUE(base::AppendToFile(store_file_path, "A", 1));
653 // Restart GCM client. The store should be reset and the loading should
654 // complete successfully.
655 reset_last_event();
656 BuildGCMClient(base::TimeDelta());
657 InitializeGCMClient();
658 StartGCMClient();
659 CompleteCheckin(kDeviceAndroidId2,
660 kDeviceSecurityToken2,
661 std::string(),
662 std::map<std::string, std::string>());
664 EXPECT_EQ(LOADING_COMPLETED, last_event());
665 EXPECT_EQ(kDeviceAndroidId2, mcs_client()->last_android_id());
666 EXPECT_EQ(kDeviceSecurityToken2, mcs_client()->last_security_token());
669 TEST_F(GCMClientImplTest, DestroyStoreWhenNotNeeded) {
670 // Close the GCM store.
671 gcm_client()->Stop();
672 PumpLoopUntilIdle();
674 // Restart GCM client. The store is loaded successfully.
675 reset_last_event();
676 BuildGCMClient(base::TimeDelta());
677 InitializeGCMClient();
678 gcm_client()->Start(GCMClient::DELAYED_START);
679 PumpLoopUntilIdle();
681 EXPECT_EQ(GCMClientImpl::LOADED, gcm_client_state());
682 EXPECT_TRUE(device_checkin_info().android_id);
683 EXPECT_TRUE(device_checkin_info().secret);
685 // Fast forward the clock to trigger the store destroying logic.
686 task_runner()->FastForwardBy(base::TimeDelta::FromMilliseconds(300000));
687 PumpLoopUntilIdle();
689 EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
690 EXPECT_FALSE(device_checkin_info().android_id);
691 EXPECT_FALSE(device_checkin_info().secret);
694 TEST_F(GCMClientImplTest, RegisterApp) {
695 EXPECT_FALSE(ExistsRegistration(kAppId));
697 std::vector<std::string> senders;
698 senders.push_back("sender");
699 Register(kAppId, senders);
700 CompleteRegistration("reg_id");
702 EXPECT_EQ(REGISTRATION_COMPLETED, last_event());
703 EXPECT_EQ(kAppId, last_app_id());
704 EXPECT_EQ("reg_id", last_registration_id());
705 EXPECT_EQ(GCMClient::SUCCESS, last_result());
706 EXPECT_TRUE(ExistsRegistration(kAppId));
709 TEST_F(GCMClientImplTest, DISABLED_RegisterAppFromCache) {
710 EXPECT_FALSE(ExistsRegistration(kAppId));
712 std::vector<std::string> senders;
713 senders.push_back("sender");
714 Register(kAppId, senders);
715 CompleteRegistration("reg_id");
716 EXPECT_TRUE(ExistsRegistration(kAppId));
718 EXPECT_EQ(kAppId, last_app_id());
719 EXPECT_EQ("reg_id", last_registration_id());
720 EXPECT_EQ(GCMClient::SUCCESS, last_result());
721 EXPECT_EQ(REGISTRATION_COMPLETED, last_event());
723 // Recreate GCMClient in order to load from the persistent store.
724 BuildGCMClient(base::TimeDelta());
725 InitializeGCMClient();
726 StartGCMClient();
728 EXPECT_TRUE(ExistsRegistration(kAppId));
731 TEST_F(GCMClientImplTest, RegisterPreviousSenderAgain) {
732 EXPECT_FALSE(ExistsRegistration(kAppId));
734 // Register a sender.
735 std::vector<std::string> senders;
736 senders.push_back("sender");
737 Register(kAppId, senders);
738 CompleteRegistration("reg_id");
740 EXPECT_EQ(REGISTRATION_COMPLETED, last_event());
741 EXPECT_EQ(kAppId, last_app_id());
742 EXPECT_EQ("reg_id", last_registration_id());
743 EXPECT_EQ(GCMClient::SUCCESS, last_result());
744 EXPECT_TRUE(ExistsRegistration(kAppId));
746 reset_last_event();
748 // Register a different sender. Different registration ID from previous one
749 // should be returned.
750 std::vector<std::string> senders2;
751 senders2.push_back("sender2");
752 Register(kAppId, senders2);
753 CompleteRegistration("reg_id2");
755 EXPECT_EQ(REGISTRATION_COMPLETED, last_event());
756 EXPECT_EQ(kAppId, last_app_id());
757 EXPECT_EQ("reg_id2", last_registration_id());
758 EXPECT_EQ(GCMClient::SUCCESS, last_result());
759 EXPECT_TRUE(ExistsRegistration(kAppId));
761 reset_last_event();
763 // Register the 1st sender again. Different registration ID from previous one
764 // should be returned.
765 std::vector<std::string> senders3;
766 senders3.push_back("sender");
767 Register(kAppId, senders3);
768 CompleteRegistration("reg_id");
770 EXPECT_EQ(REGISTRATION_COMPLETED, last_event());
771 EXPECT_EQ(kAppId, last_app_id());
772 EXPECT_EQ("reg_id", last_registration_id());
773 EXPECT_EQ(GCMClient::SUCCESS, last_result());
774 EXPECT_TRUE(ExistsRegistration(kAppId));
777 TEST_F(GCMClientImplTest, UnregisterApp) {
778 EXPECT_FALSE(ExistsRegistration(kAppId));
780 std::vector<std::string> senders;
781 senders.push_back("sender");
782 Register(kAppId, senders);
783 CompleteRegistration("reg_id");
784 EXPECT_TRUE(ExistsRegistration(kAppId));
786 Unregister(kAppId);
787 CompleteUnregistration(kAppId);
789 EXPECT_EQ(UNREGISTRATION_COMPLETED, last_event());
790 EXPECT_EQ(kAppId, last_app_id());
791 EXPECT_EQ(GCMClient::SUCCESS, last_result());
792 EXPECT_FALSE(ExistsRegistration(kAppId));
795 // Tests that stopping the GCMClient also deletes pending registration requests.
796 // This is tested by checking that url fetcher contained in the request was
797 // deleted.
798 TEST_F(GCMClientImplTest, DeletePendingRequestsWhenStopping) {
799 std::vector<std::string> senders;
800 senders.push_back("sender");
801 Register(kAppId, senders);
803 gcm_client()->Stop();
804 PumpLoopUntilIdle();
805 VerifyPendingRequestFetcherDeleted();
808 TEST_F(GCMClientImplTest, DispatchDownstreamMessage) {
809 // Register to receive messages from kSender and kSender2 only.
810 std::vector<std::string> senders;
811 senders.push_back(kSender);
812 senders.push_back(kSender2);
813 AddRegistration(kAppId, senders, "reg_id");
815 std::map<std::string, std::string> expected_data;
816 expected_data["message_type"] = "gcm";
817 expected_data["key"] = "value";
818 expected_data["key2"] = "value2";
820 // Message for kSender will be received.
821 MCSMessage message(BuildDownstreamMessage(kSender, kAppId, expected_data));
822 EXPECT_TRUE(message.IsValid());
823 ReceiveMessageFromMCS(message);
825 expected_data.erase(expected_data.find("message_type"));
826 EXPECT_EQ(MESSAGE_RECEIVED, last_event());
827 EXPECT_EQ(kAppId, last_app_id());
828 EXPECT_EQ(expected_data.size(), last_message().data.size());
829 EXPECT_EQ(expected_data, last_message().data);
830 EXPECT_EQ(kSender, last_message().sender_id);
832 reset_last_event();
834 // Message for kSender2 will be received.
835 MCSMessage message2(BuildDownstreamMessage(kSender2, kAppId, expected_data));
836 EXPECT_TRUE(message2.IsValid());
837 ReceiveMessageFromMCS(message2);
839 EXPECT_EQ(MESSAGE_RECEIVED, last_event());
840 EXPECT_EQ(kAppId, last_app_id());
841 EXPECT_EQ(expected_data.size(), last_message().data.size());
842 EXPECT_EQ(expected_data, last_message().data);
843 EXPECT_EQ(kSender2, last_message().sender_id);
845 reset_last_event();
847 // Message from kSender3 will be dropped.
848 MCSMessage message3(BuildDownstreamMessage(kSender3, kAppId, expected_data));
849 EXPECT_TRUE(message3.IsValid());
850 ReceiveMessageFromMCS(message3);
852 EXPECT_NE(MESSAGE_RECEIVED, last_event());
853 EXPECT_NE(kAppId, last_app_id());
856 TEST_F(GCMClientImplTest, DispatchDownstreamMessageSendError) {
857 std::map<std::string, std::string> expected_data;
858 expected_data["message_type"] = "send_error";
859 expected_data["google.message_id"] = "007";
860 expected_data["error_details"] = "some details";
861 MCSMessage message(BuildDownstreamMessage(
862 kSender, kAppId, expected_data));
863 EXPECT_TRUE(message.IsValid());
864 ReceiveMessageFromMCS(message);
866 EXPECT_EQ(MESSAGE_SEND_ERROR, last_event());
867 EXPECT_EQ(kAppId, last_app_id());
868 EXPECT_EQ("007", last_error_details().message_id);
869 EXPECT_EQ(1UL, last_error_details().additional_data.size());
870 GCMClient::MessageData::const_iterator iter =
871 last_error_details().additional_data.find("error_details");
872 EXPECT_TRUE(iter != last_error_details().additional_data.end());
873 EXPECT_EQ("some details", iter->second);
876 TEST_F(GCMClientImplTest, DispatchDownstreamMessgaesDeleted) {
877 std::map<std::string, std::string> expected_data;
878 expected_data["message_type"] = "deleted_messages";
879 MCSMessage message(BuildDownstreamMessage(
880 kSender, kAppId, expected_data));
881 EXPECT_TRUE(message.IsValid());
882 ReceiveMessageFromMCS(message);
884 EXPECT_EQ(MESSAGES_DELETED, last_event());
885 EXPECT_EQ(kAppId, last_app_id());
888 TEST_F(GCMClientImplTest, SendMessage) {
889 GCMClient::OutgoingMessage message;
890 message.id = "007";
891 message.time_to_live = 500;
892 message.data["key"] = "value";
893 gcm_client()->Send(kAppId, kSender, message);
895 EXPECT_EQ(kDataMessageStanzaTag, mcs_client()->last_message_tag());
896 EXPECT_EQ(kAppId, mcs_client()->last_data_message_stanza().category());
897 EXPECT_EQ(kSender, mcs_client()->last_data_message_stanza().to());
898 EXPECT_EQ(500, mcs_client()->last_data_message_stanza().ttl());
899 EXPECT_EQ(CurrentTime(), mcs_client()->last_data_message_stanza().sent());
900 EXPECT_EQ("007", mcs_client()->last_data_message_stanza().id());
901 EXPECT_EQ("gcm@chrome.com", mcs_client()->last_data_message_stanza().from());
902 EXPECT_EQ(kSender, mcs_client()->last_data_message_stanza().to());
903 EXPECT_EQ("key", mcs_client()->last_data_message_stanza().app_data(0).key());
904 EXPECT_EQ("value",
905 mcs_client()->last_data_message_stanza().app_data(0).value());
908 TEST_F(GCMClientImplTest, SendMessageAcknowledged) {
909 ReceiveOnMessageSentToMCS(kAppId, "007", MCSClient::SENT);
910 EXPECT_EQ(MESSAGE_SEND_ACK, last_event());
911 EXPECT_EQ(kAppId, last_app_id());
912 EXPECT_EQ("007", last_message_id());
915 class GCMClientImplCheckinTest : public GCMClientImplTest {
916 public:
917 GCMClientImplCheckinTest();
918 ~GCMClientImplCheckinTest() override;
920 void SetUp() override;
923 GCMClientImplCheckinTest::GCMClientImplCheckinTest() {
926 GCMClientImplCheckinTest::~GCMClientImplCheckinTest() {
929 void GCMClientImplCheckinTest::SetUp() {
930 testing::Test::SetUp();
931 // Creating unique temp directory that will be used by GCMStore shared between
932 // GCM Client and G-services settings.
933 ASSERT_TRUE(CreateUniqueTempDir());
934 // Time will be advancing one hour every time it is checked.
935 BuildGCMClient(base::TimeDelta::FromSeconds(kSettingsCheckinInterval));
936 InitializeGCMClient();
937 StartGCMClient();
940 TEST_F(GCMClientImplCheckinTest, GServicesSettingsAfterInitialCheckin) {
941 std::map<std::string, std::string> settings;
942 settings["checkin_interval"] = base::Int64ToString(kSettingsCheckinInterval);
943 settings["checkin_url"] = "http://alternative.url/checkin";
944 settings["gcm_hostname"] = "alternative.gcm.host";
945 settings["gcm_secure_port"] = "7777";
946 settings["gcm_registration_url"] = "http://alternative.url/registration";
947 CompleteCheckin(kDeviceAndroidId,
948 kDeviceSecurityToken,
949 GServicesSettings::CalculateDigest(settings),
950 settings);
951 EXPECT_EQ(base::TimeDelta::FromSeconds(kSettingsCheckinInterval),
952 gservices_settings().GetCheckinInterval());
953 EXPECT_EQ(GURL("http://alternative.url/checkin"),
954 gservices_settings().GetCheckinURL());
955 EXPECT_EQ(GURL("http://alternative.url/registration"),
956 gservices_settings().GetRegistrationURL());
957 EXPECT_EQ(GURL("https://alternative.gcm.host:7777"),
958 gservices_settings().GetMCSMainEndpoint());
959 EXPECT_EQ(GURL("https://alternative.gcm.host:443"),
960 gservices_settings().GetMCSFallbackEndpoint());
963 // This test only checks that periodic checkin happens.
964 TEST_F(GCMClientImplCheckinTest, PeriodicCheckin) {
965 std::map<std::string, std::string> settings;
966 settings["checkin_interval"] = base::IntToString(kSettingsCheckinInterval);
967 settings["checkin_url"] = "http://alternative.url/checkin";
968 settings["gcm_hostname"] = "alternative.gcm.host";
969 settings["gcm_secure_port"] = "7777";
970 settings["gcm_registration_url"] = "http://alternative.url/registration";
971 CompleteCheckin(kDeviceAndroidId,
972 kDeviceSecurityToken,
973 GServicesSettings::CalculateDigest(settings),
974 settings);
976 EXPECT_EQ(2, clock()->call_count());
978 PumpLoopUntilIdle();
979 CompleteCheckin(kDeviceAndroidId,
980 kDeviceSecurityToken,
981 GServicesSettings::CalculateDigest(settings),
982 settings);
985 TEST_F(GCMClientImplCheckinTest, LoadGSettingsFromStore) {
986 std::map<std::string, std::string> settings;
987 settings["checkin_interval"] = base::IntToString(kSettingsCheckinInterval);
988 settings["checkin_url"] = "http://alternative.url/checkin";
989 settings["gcm_hostname"] = "alternative.gcm.host";
990 settings["gcm_secure_port"] = "7777";
991 settings["gcm_registration_url"] = "http://alternative.url/registration";
992 CompleteCheckin(kDeviceAndroidId,
993 kDeviceSecurityToken,
994 GServicesSettings::CalculateDigest(settings),
995 settings);
997 BuildGCMClient(base::TimeDelta());
998 InitializeGCMClient();
999 StartGCMClient();
1001 EXPECT_EQ(base::TimeDelta::FromSeconds(kSettingsCheckinInterval),
1002 gservices_settings().GetCheckinInterval());
1003 EXPECT_EQ(GURL("http://alternative.url/checkin"),
1004 gservices_settings().GetCheckinURL());
1005 EXPECT_EQ(GURL("http://alternative.url/registration"),
1006 gservices_settings().GetRegistrationURL());
1007 EXPECT_EQ(GURL("https://alternative.gcm.host:7777"),
1008 gservices_settings().GetMCSMainEndpoint());
1009 EXPECT_EQ(GURL("https://alternative.gcm.host:443"),
1010 gservices_settings().GetMCSFallbackEndpoint());
1013 // This test only checks that periodic checkin happens.
1014 TEST_F(GCMClientImplCheckinTest, CheckinWithAccounts) {
1015 std::map<std::string, std::string> settings;
1016 settings["checkin_interval"] = base::IntToString(kSettingsCheckinInterval);
1017 settings["checkin_url"] = "http://alternative.url/checkin";
1018 settings["gcm_hostname"] = "alternative.gcm.host";
1019 settings["gcm_secure_port"] = "7777";
1020 settings["gcm_registration_url"] = "http://alternative.url/registration";
1021 CompleteCheckin(kDeviceAndroidId,
1022 kDeviceSecurityToken,
1023 GServicesSettings::CalculateDigest(settings),
1024 settings);
1026 std::vector<GCMClient::AccountTokenInfo> account_tokens;
1027 account_tokens.push_back(MakeAccountToken("test_user1@gmail.com", "token1"));
1028 account_tokens.push_back(MakeAccountToken("test_user2@gmail.com", "token2"));
1029 gcm_client()->SetAccountTokens(account_tokens);
1031 EXPECT_TRUE(device_checkin_info().last_checkin_accounts.empty());
1032 EXPECT_TRUE(device_checkin_info().accounts_set);
1033 EXPECT_EQ(MakeEmailToTokenMap(account_tokens),
1034 device_checkin_info().account_tokens);
1036 PumpLoopUntilIdle();
1037 CompleteCheckin(kDeviceAndroidId,
1038 kDeviceSecurityToken,
1039 GServicesSettings::CalculateDigest(settings),
1040 settings);
1042 std::set<std::string> accounts;
1043 accounts.insert("test_user1@gmail.com");
1044 accounts.insert("test_user2@gmail.com");
1045 EXPECT_EQ(accounts, device_checkin_info().last_checkin_accounts);
1046 EXPECT_TRUE(device_checkin_info().accounts_set);
1047 EXPECT_EQ(MakeEmailToTokenMap(account_tokens),
1048 device_checkin_info().account_tokens);
1051 // This test only checks that periodic checkin happens.
1052 TEST_F(GCMClientImplCheckinTest, CheckinWhenAccountRemoved) {
1053 std::map<std::string, std::string> settings;
1054 settings["checkin_interval"] = base::IntToString(kSettingsCheckinInterval);
1055 settings["checkin_url"] = "http://alternative.url/checkin";
1056 settings["gcm_hostname"] = "alternative.gcm.host";
1057 settings["gcm_secure_port"] = "7777";
1058 settings["gcm_registration_url"] = "http://alternative.url/registration";
1059 CompleteCheckin(kDeviceAndroidId,
1060 kDeviceSecurityToken,
1061 GServicesSettings::CalculateDigest(settings),
1062 settings);
1064 std::vector<GCMClient::AccountTokenInfo> account_tokens;
1065 account_tokens.push_back(MakeAccountToken("test_user1@gmail.com", "token1"));
1066 account_tokens.push_back(MakeAccountToken("test_user2@gmail.com", "token2"));
1067 gcm_client()->SetAccountTokens(account_tokens);
1068 PumpLoopUntilIdle();
1069 CompleteCheckin(kDeviceAndroidId,
1070 kDeviceSecurityToken,
1071 GServicesSettings::CalculateDigest(settings),
1072 settings);
1074 EXPECT_EQ(2UL, device_checkin_info().last_checkin_accounts.size());
1075 EXPECT_TRUE(device_checkin_info().accounts_set);
1076 EXPECT_EQ(MakeEmailToTokenMap(account_tokens),
1077 device_checkin_info().account_tokens);
1079 account_tokens.erase(account_tokens.begin() + 1);
1080 gcm_client()->SetAccountTokens(account_tokens);
1082 PumpLoopUntilIdle();
1083 CompleteCheckin(kDeviceAndroidId,
1084 kDeviceSecurityToken,
1085 GServicesSettings::CalculateDigest(settings),
1086 settings);
1088 std::set<std::string> accounts;
1089 accounts.insert("test_user1@gmail.com");
1090 EXPECT_EQ(accounts, device_checkin_info().last_checkin_accounts);
1091 EXPECT_TRUE(device_checkin_info().accounts_set);
1092 EXPECT_EQ(MakeEmailToTokenMap(account_tokens),
1093 device_checkin_info().account_tokens);
1096 // This test only checks that periodic checkin happens.
1097 TEST_F(GCMClientImplCheckinTest, CheckinWhenAccountReplaced) {
1098 std::map<std::string, std::string> settings;
1099 settings["checkin_interval"] = base::IntToString(kSettingsCheckinInterval);
1100 settings["checkin_url"] = "http://alternative.url/checkin";
1101 settings["gcm_hostname"] = "alternative.gcm.host";
1102 settings["gcm_secure_port"] = "7777";
1103 settings["gcm_registration_url"] = "http://alternative.url/registration";
1104 CompleteCheckin(kDeviceAndroidId,
1105 kDeviceSecurityToken,
1106 GServicesSettings::CalculateDigest(settings),
1107 settings);
1109 std::vector<GCMClient::AccountTokenInfo> account_tokens;
1110 account_tokens.push_back(MakeAccountToken("test_user1@gmail.com", "token1"));
1111 gcm_client()->SetAccountTokens(account_tokens);
1113 PumpLoopUntilIdle();
1114 CompleteCheckin(kDeviceAndroidId,
1115 kDeviceSecurityToken,
1116 GServicesSettings::CalculateDigest(settings),
1117 settings);
1119 std::set<std::string> accounts;
1120 accounts.insert("test_user1@gmail.com");
1121 EXPECT_EQ(accounts, device_checkin_info().last_checkin_accounts);
1123 // This should trigger another checkin, because the list of accounts is
1124 // different.
1125 account_tokens.clear();
1126 account_tokens.push_back(MakeAccountToken("test_user2@gmail.com", "token2"));
1127 gcm_client()->SetAccountTokens(account_tokens);
1129 PumpLoopUntilIdle();
1130 CompleteCheckin(kDeviceAndroidId,
1131 kDeviceSecurityToken,
1132 GServicesSettings::CalculateDigest(settings),
1133 settings);
1135 accounts.clear();
1136 accounts.insert("test_user2@gmail.com");
1137 EXPECT_EQ(accounts, device_checkin_info().last_checkin_accounts);
1138 EXPECT_TRUE(device_checkin_info().accounts_set);
1139 EXPECT_EQ(MakeEmailToTokenMap(account_tokens),
1140 device_checkin_info().account_tokens);
1143 class GCMClientImplStartAndStopTest : public GCMClientImplTest {
1144 public:
1145 GCMClientImplStartAndStopTest();
1146 ~GCMClientImplStartAndStopTest() override;
1148 void SetUp() override;
1150 void DefaultCompleteCheckin();
1153 GCMClientImplStartAndStopTest::GCMClientImplStartAndStopTest() {
1156 GCMClientImplStartAndStopTest::~GCMClientImplStartAndStopTest() {
1159 void GCMClientImplStartAndStopTest::SetUp() {
1160 testing::Test::SetUp();
1161 ASSERT_TRUE(CreateUniqueTempDir());
1162 BuildGCMClient(base::TimeDelta());
1163 InitializeGCMClient();
1166 void GCMClientImplStartAndStopTest::DefaultCompleteCheckin() {
1167 SetUpUrlFetcherFactory();
1168 CompleteCheckin(kDeviceAndroidId,
1169 kDeviceSecurityToken,
1170 std::string(),
1171 std::map<std::string, std::string>());
1172 PumpLoopUntilIdle();
1175 TEST_F(GCMClientImplStartAndStopTest, StartStopAndRestart) {
1176 // GCMClientImpl should be in INITIALIZED state at first.
1177 EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
1179 // Delay start the GCM.
1180 gcm_client()->Start(GCMClient::DELAYED_START);
1181 PumpLoopUntilIdle();
1182 EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
1184 // Stop the GCM.
1185 gcm_client()->Stop();
1186 PumpLoopUntilIdle();
1187 EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
1189 // Restart the GCM without delay.
1190 gcm_client()->Start(GCMClient::IMMEDIATE_START);
1191 PumpLoopUntilIdle();
1192 EXPECT_EQ(GCMClientImpl::INITIAL_DEVICE_CHECKIN, gcm_client_state());
1195 TEST_F(GCMClientImplStartAndStopTest, DelayedStartAndStopImmediately) {
1196 // GCMClientImpl should be in INITIALIZED state at first.
1197 EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
1199 // Delay start the GCM and then stop it immediately.
1200 gcm_client()->Start(GCMClient::DELAYED_START);
1201 gcm_client()->Stop();
1202 PumpLoopUntilIdle();
1203 EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
1206 TEST_F(GCMClientImplStartAndStopTest, ImmediateStartAndStopImmediately) {
1207 // GCMClientImpl should be in INITIALIZED state at first.
1208 EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
1210 // Start the GCM and then stop it immediately.
1211 gcm_client()->Start(GCMClient::IMMEDIATE_START);
1212 gcm_client()->Stop();
1213 PumpLoopUntilIdle();
1214 EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
1217 TEST_F(GCMClientImplStartAndStopTest, DelayedStartStopAndRestart) {
1218 // GCMClientImpl should be in INITIALIZED state at first.
1219 EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
1221 // Delay start the GCM and then stop and restart it immediately.
1222 gcm_client()->Start(GCMClient::DELAYED_START);
1223 gcm_client()->Stop();
1224 gcm_client()->Start(GCMClient::DELAYED_START);
1225 PumpLoopUntilIdle();
1226 EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
1229 TEST_F(GCMClientImplStartAndStopTest, ImmediateStartStopAndRestart) {
1230 // GCMClientImpl should be in INITIALIZED state at first.
1231 EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
1233 // Start the GCM and then stop and restart it immediately.
1234 gcm_client()->Start(GCMClient::IMMEDIATE_START);
1235 gcm_client()->Stop();
1236 gcm_client()->Start(GCMClient::IMMEDIATE_START);
1237 PumpLoopUntilIdle();
1238 EXPECT_EQ(GCMClientImpl::INITIAL_DEVICE_CHECKIN, gcm_client_state());
1241 TEST_F(GCMClientImplStartAndStopTest, ImmediateStartAndThenImmediateStart) {
1242 // GCMClientImpl should be in INITIALIZED state at first.
1243 EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
1245 // Start the GCM immediately and complete the checkin.
1246 gcm_client()->Start(GCMClient::IMMEDIATE_START);
1247 PumpLoopUntilIdle();
1248 EXPECT_EQ(GCMClientImpl::INITIAL_DEVICE_CHECKIN, gcm_client_state());
1249 DefaultCompleteCheckin();
1250 EXPECT_EQ(GCMClientImpl::READY, gcm_client_state());
1252 // Stop the GCM.
1253 gcm_client()->Stop();
1254 PumpLoopUntilIdle();
1255 EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
1257 // Start the GCM immediately. GCMClientImpl should be in READY state.
1258 BuildGCMClient(base::TimeDelta());
1259 InitializeGCMClient();
1260 gcm_client()->Start(GCMClient::IMMEDIATE_START);
1261 PumpLoopUntilIdle();
1262 EXPECT_EQ(GCMClientImpl::READY, gcm_client_state());
1265 TEST_F(GCMClientImplStartAndStopTest, ImmediateStartAndThenDelayStart) {
1266 // GCMClientImpl should be in INITIALIZED state at first.
1267 EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
1269 // Start the GCM immediately and complete the checkin.
1270 gcm_client()->Start(GCMClient::IMMEDIATE_START);
1271 PumpLoopUntilIdle();
1272 EXPECT_EQ(GCMClientImpl::INITIAL_DEVICE_CHECKIN, gcm_client_state());
1273 DefaultCompleteCheckin();
1274 EXPECT_EQ(GCMClientImpl::READY, gcm_client_state());
1276 // Stop the GCM.
1277 gcm_client()->Stop();
1278 PumpLoopUntilIdle();
1279 EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
1281 // Delay start the GCM. GCMClientImpl should be in LOADED state.
1282 BuildGCMClient(base::TimeDelta());
1283 InitializeGCMClient();
1284 gcm_client()->Start(GCMClient::DELAYED_START);
1285 PumpLoopUntilIdle();
1286 EXPECT_EQ(GCMClientImpl::LOADED, gcm_client_state());
1289 TEST_F(GCMClientImplStartAndStopTest, DelayedStart) {
1290 // GCMClientImpl should be in INITIALIZED state at first.
1291 EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
1293 // Delay start the GCM. The store will not be loaded and GCMClientImpl should
1294 // still be in INITIALIZED state.
1295 gcm_client()->Start(GCMClient::DELAYED_START);
1296 PumpLoopUntilIdle();
1297 EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
1299 // Start the GCM immediately and complete the checkin.
1300 gcm_client()->Start(GCMClient::IMMEDIATE_START);
1301 PumpLoopUntilIdle();
1302 EXPECT_EQ(GCMClientImpl::INITIAL_DEVICE_CHECKIN, gcm_client_state());
1303 DefaultCompleteCheckin();
1304 EXPECT_EQ(GCMClientImpl::READY, gcm_client_state());
1306 // Registration.
1307 std::vector<std::string> senders;
1308 senders.push_back("sender");
1309 Register(kAppId, senders);
1310 CompleteRegistration("reg_id");
1311 EXPECT_EQ(GCMClientImpl::READY, gcm_client_state());
1313 // Stop the GCM.
1314 gcm_client()->Stop();
1315 PumpLoopUntilIdle();
1316 EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
1318 // Delay start the GCM. GCM is indeed started without delay because the
1319 // registration record has been found.
1320 BuildGCMClient(base::TimeDelta());
1321 InitializeGCMClient();
1322 gcm_client()->Start(GCMClient::DELAYED_START);
1323 PumpLoopUntilIdle();
1324 EXPECT_EQ(GCMClientImpl::READY, gcm_client_state());
1327 // Test for known account mappings and last token fetching time being passed
1328 // to OnGCMReady.
1329 TEST_F(GCMClientImplStartAndStopTest, OnGCMReadyAccountsAndTokenFetchingTime) {
1330 // Start the GCM and wait until it is ready.
1331 gcm_client()->Start(GCMClient::IMMEDIATE_START);
1332 PumpLoopUntilIdle();
1333 DefaultCompleteCheckin();
1335 base::Time expected_time = base::Time::Now();
1336 gcm_client()->SetLastTokenFetchTime(expected_time);
1337 AccountMapping expected_mapping;
1338 expected_mapping.account_id = "accId";
1339 expected_mapping.email = "email@gmail.com";
1340 expected_mapping.status = AccountMapping::MAPPED;
1341 expected_mapping.status_change_timestamp = expected_time;
1342 gcm_client()->UpdateAccountMapping(expected_mapping);
1343 PumpLoopUntilIdle();
1345 // Stop the GCM.
1346 gcm_client()->Stop();
1347 PumpLoopUntilIdle();
1349 // Restart the GCM.
1350 gcm_client()->Start(GCMClient::IMMEDIATE_START);
1351 PumpLoopUntilIdle();
1353 EXPECT_EQ(LOADING_COMPLETED, last_event());
1354 EXPECT_EQ(expected_time, last_token_fetch_time());
1355 ASSERT_EQ(1UL, last_account_mappings().size());
1356 const AccountMapping& actual_mapping = last_account_mappings()[0];
1357 EXPECT_EQ(expected_mapping.account_id, actual_mapping.account_id);
1358 EXPECT_EQ(expected_mapping.email, actual_mapping.email);
1359 EXPECT_EQ(expected_mapping.status, actual_mapping.status);
1360 EXPECT_EQ(expected_mapping.status_change_timestamp,
1361 actual_mapping.status_change_timestamp);
1365 class GCMClientInstanceIDTest : public GCMClientImplTest {
1366 public:
1367 GCMClientInstanceIDTest();
1368 ~GCMClientInstanceIDTest() override;
1370 void AddInstanceID(const std::string& app_id,
1371 const std::string& instance_id);
1372 void RemoveInstanceID(const std::string& app_id);
1373 void GetToken(const std::string& app_id,
1374 const std::string& authorized_entity,
1375 const std::string& scope);
1376 void DeleteToken(const std::string& app_id,
1377 const std::string& authorized_entity,
1378 const std::string& scope);
1379 void CompleteDeleteToken();
1380 bool ExistsToken(const std::string& app_id,
1381 const std::string& authorized_entity,
1382 const std::string& scope) const;
1385 GCMClientInstanceIDTest::GCMClientInstanceIDTest() {
1388 GCMClientInstanceIDTest::~GCMClientInstanceIDTest() {
1391 void GCMClientInstanceIDTest::AddInstanceID(const std::string& app_id,
1392 const std::string& instance_id) {
1393 gcm_client()->AddInstanceIDData(app_id, instance_id, "123");
1396 void GCMClientInstanceIDTest::RemoveInstanceID(const std::string& app_id) {
1397 gcm_client()->RemoveInstanceIDData(app_id);
1400 void GCMClientInstanceIDTest::GetToken(const std::string& app_id,
1401 const std::string& authorized_entity,
1402 const std::string& scope) {
1403 scoped_ptr<InstanceIDTokenInfo> instance_id_info(new InstanceIDTokenInfo);
1404 instance_id_info->app_id = app_id;
1405 instance_id_info->authorized_entity = authorized_entity;
1406 instance_id_info->scope = scope;
1407 gcm_client()->Register(
1408 make_linked_ptr<RegistrationInfo>(instance_id_info.release()));
1411 void GCMClientInstanceIDTest::DeleteToken(const std::string& app_id,
1412 const std::string& authorized_entity,
1413 const std::string& scope) {
1414 scoped_ptr<InstanceIDTokenInfo> instance_id_info(new InstanceIDTokenInfo);
1415 instance_id_info->app_id = app_id;
1416 instance_id_info->authorized_entity = authorized_entity;
1417 instance_id_info->scope = scope;
1418 gcm_client()->Unregister(
1419 make_linked_ptr<RegistrationInfo>(instance_id_info.release()));
1422 void GCMClientInstanceIDTest::CompleteDeleteToken() {
1423 std::string response(kDeleteTokenResponse);
1424 net::TestURLFetcher* fetcher = url_fetcher_factory()->GetFetcherByID(0);
1425 ASSERT_TRUE(fetcher);
1426 fetcher->set_response_code(net::HTTP_OK);
1427 fetcher->SetResponseString(response);
1428 fetcher->delegate()->OnURLFetchComplete(fetcher);
1429 // Give a chance for GCMStoreImpl::Backend to finish persisting data.
1430 PumpLoopUntilIdle();
1433 bool GCMClientInstanceIDTest::ExistsToken(const std::string& app_id,
1434 const std::string& authorized_entity,
1435 const std::string& scope) const {
1436 scoped_ptr<InstanceIDTokenInfo> instance_id_info(new InstanceIDTokenInfo);
1437 instance_id_info->app_id = app_id;
1438 instance_id_info->authorized_entity = authorized_entity;
1439 instance_id_info->scope = scope;
1440 return gcm_client()->registrations_.count(
1441 make_linked_ptr<RegistrationInfo>(instance_id_info.release())) > 0;
1444 TEST_F(GCMClientInstanceIDTest, GetToken) {
1445 AddInstanceID(kAppId, kInstanceID);
1447 // Get a token.
1448 EXPECT_FALSE(ExistsToken(kAppId, kSender, kScope));
1449 GetToken(kAppId, kSender, kScope);
1450 CompleteRegistration("token1");
1452 EXPECT_EQ(REGISTRATION_COMPLETED, last_event());
1453 EXPECT_EQ(kAppId, last_app_id());
1454 EXPECT_EQ("token1", last_registration_id());
1455 EXPECT_EQ(GCMClient::SUCCESS, last_result());
1456 EXPECT_TRUE(ExistsToken(kAppId, kSender, kScope));
1458 // Get another token.
1459 EXPECT_FALSE(ExistsToken(kAppId, kSender2, kScope));
1460 GetToken(kAppId, kSender2, kScope);
1461 CompleteRegistration("token2");
1463 EXPECT_EQ(REGISTRATION_COMPLETED, last_event());
1464 EXPECT_EQ(kAppId, last_app_id());
1465 EXPECT_EQ("token2", last_registration_id());
1466 EXPECT_EQ(GCMClient::SUCCESS, last_result());
1467 EXPECT_TRUE(ExistsToken(kAppId, kSender2, kScope));
1468 // The 1st token still exists.
1469 EXPECT_TRUE(ExistsToken(kAppId, kSender, kScope));
1472 TEST_F(GCMClientInstanceIDTest, DeleteInvalidToken) {
1473 AddInstanceID(kAppId, kInstanceID);
1475 // Delete an invalid token.
1476 DeleteToken(kAppId, "Foo@#$", kScope);
1477 PumpLoopUntilIdle();
1479 EXPECT_EQ(UNREGISTRATION_COMPLETED, last_event());
1480 EXPECT_EQ(kAppId, last_app_id());
1481 EXPECT_EQ(GCMClient::INVALID_PARAMETER, last_result());
1483 reset_last_event();
1485 // Delete a non-existing token.
1486 DeleteToken(kAppId, kSender, kScope);
1487 PumpLoopUntilIdle();
1489 EXPECT_EQ(UNREGISTRATION_COMPLETED, last_event());
1490 EXPECT_EQ(kAppId, last_app_id());
1491 EXPECT_EQ(GCMClient::INVALID_PARAMETER, last_result());
1494 TEST_F(GCMClientInstanceIDTest, DeleteSingleToken) {
1495 AddInstanceID(kAppId, kInstanceID);
1497 // Get a token.
1498 EXPECT_FALSE(ExistsToken(kAppId, kSender, kScope));
1499 GetToken(kAppId, kSender, kScope);
1500 CompleteRegistration("token1");
1502 EXPECT_EQ(REGISTRATION_COMPLETED, last_event());
1503 EXPECT_EQ(kAppId, last_app_id());
1504 EXPECT_EQ("token1", last_registration_id());
1505 EXPECT_EQ(GCMClient::SUCCESS, last_result());
1506 EXPECT_TRUE(ExistsToken(kAppId, kSender, kScope));
1508 reset_last_event();
1510 // Get another token.
1511 EXPECT_FALSE(ExistsToken(kAppId, kSender2, kScope));
1512 GetToken(kAppId, kSender2, kScope);
1513 CompleteRegistration("token2");
1515 EXPECT_EQ(REGISTRATION_COMPLETED, last_event());
1516 EXPECT_EQ(kAppId, last_app_id());
1517 EXPECT_EQ("token2", last_registration_id());
1518 EXPECT_EQ(GCMClient::SUCCESS, last_result());
1519 EXPECT_TRUE(ExistsToken(kAppId, kSender2, kScope));
1520 // The 1st token still exists.
1521 EXPECT_TRUE(ExistsToken(kAppId, kSender, kScope));
1523 reset_last_event();
1525 // Delete the 2nd token.
1526 DeleteToken(kAppId, kSender2, kScope);
1527 CompleteDeleteToken();
1529 EXPECT_EQ(UNREGISTRATION_COMPLETED, last_event());
1530 EXPECT_EQ(kAppId, last_app_id());
1531 EXPECT_EQ(GCMClient::SUCCESS, last_result());
1532 // The 2nd token is gone while the 1st token still exists.
1533 EXPECT_TRUE(ExistsToken(kAppId, kSender, kScope));
1534 EXPECT_FALSE(ExistsToken(kAppId, kSender2, kScope));
1536 reset_last_event();
1538 // Delete the 1st token.
1539 DeleteToken(kAppId, kSender, kScope);
1540 CompleteDeleteToken();
1542 EXPECT_EQ(UNREGISTRATION_COMPLETED, last_event());
1543 EXPECT_EQ(kAppId, last_app_id());
1544 EXPECT_EQ(GCMClient::SUCCESS, last_result());
1545 // Both tokens are gone now.
1546 EXPECT_FALSE(ExistsToken(kAppId, kSender, kScope));
1547 EXPECT_FALSE(ExistsToken(kAppId, kSender, kScope));
1549 reset_last_event();
1551 // Trying to delete the token again will get an error.
1552 DeleteToken(kAppId, kSender, kScope);
1553 PumpLoopUntilIdle();
1555 EXPECT_EQ(UNREGISTRATION_COMPLETED, last_event());
1556 EXPECT_EQ(kAppId, last_app_id());
1557 EXPECT_EQ(GCMClient::INVALID_PARAMETER, last_result());
1560 TEST_F(GCMClientInstanceIDTest, DeleteAllTokens) {
1561 AddInstanceID(kAppId, kInstanceID);
1563 // Get a token.
1564 EXPECT_FALSE(ExistsToken(kAppId, kSender, kScope));
1565 GetToken(kAppId, kSender, kScope);
1566 CompleteRegistration("token1");
1568 EXPECT_EQ(REGISTRATION_COMPLETED, last_event());
1569 EXPECT_EQ(kAppId, last_app_id());
1570 EXPECT_EQ("token1", last_registration_id());
1571 EXPECT_EQ(GCMClient::SUCCESS, last_result());
1572 EXPECT_TRUE(ExistsToken(kAppId, kSender, kScope));
1574 reset_last_event();
1576 // Get another token.
1577 EXPECT_FALSE(ExistsToken(kAppId, kSender2, kScope));
1578 GetToken(kAppId, kSender2, kScope);
1579 CompleteRegistration("token2");
1581 EXPECT_EQ(REGISTRATION_COMPLETED, last_event());
1582 EXPECT_EQ(kAppId, last_app_id());
1583 EXPECT_EQ("token2", last_registration_id());
1584 EXPECT_EQ(GCMClient::SUCCESS, last_result());
1585 EXPECT_TRUE(ExistsToken(kAppId, kSender2, kScope));
1586 // The 1st token still exists.
1587 EXPECT_TRUE(ExistsToken(kAppId, kSender, kScope));
1589 reset_last_event();
1591 // Delete all tokens.
1592 DeleteToken(kAppId, "*", "*");
1593 CompleteDeleteToken();
1595 EXPECT_EQ(UNREGISTRATION_COMPLETED, last_event());
1596 EXPECT_EQ(kAppId, last_app_id());
1597 EXPECT_EQ(GCMClient::SUCCESS, last_result());
1598 // All tokens are gone now.
1599 EXPECT_FALSE(ExistsToken(kAppId, kSender, kScope));
1600 EXPECT_FALSE(ExistsToken(kAppId, kSender, kScope));
1603 TEST_F(GCMClientInstanceIDTest, DeleteAllTokensBeforeGetAnyToken) {
1604 AddInstanceID(kAppId, kInstanceID);
1606 // Delete all tokens without getting a token first.
1607 DeleteToken(kAppId, "*", "*");
1608 // No need to call CompleteDeleteToken since unregistration request should
1609 // not be triggered.
1610 PumpLoopUntilIdle();
1612 EXPECT_EQ(UNREGISTRATION_COMPLETED, last_event());
1613 EXPECT_EQ(kAppId, last_app_id());
1614 EXPECT_EQ(GCMClient::SUCCESS, last_result());
1617 } // namespace gcm