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"
39 REGISTRATION_COMPLETED
,
40 UNREGISTRATION_COMPLETED
,
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();
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
;
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
{
102 FakeMCSClient(base::Clock
* clock
,
103 ConnectionFactory
* connection_factory
,
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_
;
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
,
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
{
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_
; }
162 base::TimeDelta auto_increment_time_delta_
;
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() {
178 now_
+= auto_increment_time_delta_
;
182 void AutoAdvancingTestClock::Advance(base::TimeDelta delta
) {
186 class FakeGCMInternalsBuilder
: public GCMInternalsBuilder
{
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
,
194 ConnectionFactory
* connection_factory
,
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
;
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
,
222 ConnectionFactory
* connection_factory
,
224 GCMStatsRecorder
* recorder
) {
225 return make_scoped_ptr
<MCSClient
>(new FakeMCSClient(clock
,
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());
243 class GCMClientImplTest
: public testing::Test
,
244 public GCMClient::Delegate
{
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() {
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"));
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();
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()
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();
417 SetUpUrlFetcherFactory();
418 CompleteCheckin(kDeviceAndroidId
,
419 kDeviceSecurityToken
,
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(
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
=
456 it
!= settings
.end();
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.
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.
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.
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(
532 url_request_context_getter_
,
533 make_scoped_ptr
<Encryptor
>(new FakeEncryptor
),
537 void GCMClientImplTest::StartGCMClient() {
538 // Start loading and check-in.
539 gcm_client_
->Start(GCMClient::IMMEDIATE_START
);
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();
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.
656 BuildGCMClient(base::TimeDelta());
657 InitializeGCMClient();
659 CompleteCheckin(kDeviceAndroidId2
,
660 kDeviceSecurityToken2
,
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();
674 // Restart GCM client. The store is loaded successfully.
676 BuildGCMClient(base::TimeDelta());
677 InitializeGCMClient();
678 gcm_client()->Start(GCMClient::DELAYED_START
);
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));
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();
728 EXPECT_TRUE(ExistsRegistration(kAppId
));
731 TEST_F(GCMClientImplTest
, UnregisterApp
) {
732 EXPECT_FALSE(ExistsRegistration(kAppId
));
734 std::vector
<std::string
> senders
;
735 senders
.push_back("sender");
736 Register(kAppId
, senders
);
737 CompleteRegistration("reg_id");
738 EXPECT_TRUE(ExistsRegistration(kAppId
));
741 CompleteUnregistration(kAppId
);
743 EXPECT_EQ(UNREGISTRATION_COMPLETED
, last_event());
744 EXPECT_EQ(kAppId
, last_app_id());
745 EXPECT_EQ(GCMClient::SUCCESS
, last_result());
746 EXPECT_FALSE(ExistsRegistration(kAppId
));
749 // Tests that stopping the GCMClient also deletes pending registration requests.
750 // This is tested by checking that url fetcher contained in the request was
752 TEST_F(GCMClientImplTest
, DeletePendingRequestsWhenStopping
) {
753 std::vector
<std::string
> senders
;
754 senders
.push_back("sender");
755 Register(kAppId
, senders
);
757 gcm_client()->Stop();
759 VerifyPendingRequestFetcherDeleted();
762 TEST_F(GCMClientImplTest
, DispatchDownstreamMessage
) {
763 // Register to receive messages from kSender and kSender2 only.
764 std::vector
<std::string
> senders
;
765 senders
.push_back(kSender
);
766 senders
.push_back(kSender2
);
767 AddRegistration(kAppId
, senders
, "reg_id");
769 std::map
<std::string
, std::string
> expected_data
;
770 expected_data
["message_type"] = "gcm";
771 expected_data
["key"] = "value";
772 expected_data
["key2"] = "value2";
774 // Message for kSender will be received.
775 MCSMessage
message(BuildDownstreamMessage(kSender
, kAppId
, expected_data
));
776 EXPECT_TRUE(message
.IsValid());
777 ReceiveMessageFromMCS(message
);
779 expected_data
.erase(expected_data
.find("message_type"));
780 EXPECT_EQ(MESSAGE_RECEIVED
, last_event());
781 EXPECT_EQ(kAppId
, last_app_id());
782 EXPECT_EQ(expected_data
.size(), last_message().data
.size());
783 EXPECT_EQ(expected_data
, last_message().data
);
784 EXPECT_EQ(kSender
, last_message().sender_id
);
788 // Message for kSender2 will be received.
789 MCSMessage
message2(BuildDownstreamMessage(kSender2
, kAppId
, expected_data
));
790 EXPECT_TRUE(message2
.IsValid());
791 ReceiveMessageFromMCS(message2
);
793 EXPECT_EQ(MESSAGE_RECEIVED
, last_event());
794 EXPECT_EQ(kAppId
, last_app_id());
795 EXPECT_EQ(expected_data
.size(), last_message().data
.size());
796 EXPECT_EQ(expected_data
, last_message().data
);
797 EXPECT_EQ(kSender2
, last_message().sender_id
);
801 // Message from kSender3 will be dropped.
802 MCSMessage
message3(BuildDownstreamMessage(kSender3
, kAppId
, expected_data
));
803 EXPECT_TRUE(message3
.IsValid());
804 ReceiveMessageFromMCS(message3
);
806 EXPECT_NE(MESSAGE_RECEIVED
, last_event());
807 EXPECT_NE(kAppId
, last_app_id());
810 TEST_F(GCMClientImplTest
, DispatchDownstreamMessageSendError
) {
811 std::map
<std::string
, std::string
> expected_data
;
812 expected_data
["message_type"] = "send_error";
813 expected_data
["google.message_id"] = "007";
814 expected_data
["error_details"] = "some details";
815 MCSMessage
message(BuildDownstreamMessage(
816 kSender
, kAppId
, expected_data
));
817 EXPECT_TRUE(message
.IsValid());
818 ReceiveMessageFromMCS(message
);
820 EXPECT_EQ(MESSAGE_SEND_ERROR
, last_event());
821 EXPECT_EQ(kAppId
, last_app_id());
822 EXPECT_EQ("007", last_error_details().message_id
);
823 EXPECT_EQ(1UL, last_error_details().additional_data
.size());
824 GCMClient::MessageData::const_iterator iter
=
825 last_error_details().additional_data
.find("error_details");
826 EXPECT_TRUE(iter
!= last_error_details().additional_data
.end());
827 EXPECT_EQ("some details", iter
->second
);
830 TEST_F(GCMClientImplTest
, DispatchDownstreamMessgaesDeleted
) {
831 std::map
<std::string
, std::string
> expected_data
;
832 expected_data
["message_type"] = "deleted_messages";
833 MCSMessage
message(BuildDownstreamMessage(
834 kSender
, kAppId
, expected_data
));
835 EXPECT_TRUE(message
.IsValid());
836 ReceiveMessageFromMCS(message
);
838 EXPECT_EQ(MESSAGES_DELETED
, last_event());
839 EXPECT_EQ(kAppId
, last_app_id());
842 TEST_F(GCMClientImplTest
, SendMessage
) {
843 GCMClient::OutgoingMessage message
;
845 message
.time_to_live
= 500;
846 message
.data
["key"] = "value";
847 gcm_client()->Send(kAppId
, kSender
, message
);
849 EXPECT_EQ(kDataMessageStanzaTag
, mcs_client()->last_message_tag());
850 EXPECT_EQ(kAppId
, mcs_client()->last_data_message_stanza().category());
851 EXPECT_EQ(kSender
, mcs_client()->last_data_message_stanza().to());
852 EXPECT_EQ(500, mcs_client()->last_data_message_stanza().ttl());
853 EXPECT_EQ(CurrentTime(), mcs_client()->last_data_message_stanza().sent());
854 EXPECT_EQ("007", mcs_client()->last_data_message_stanza().id());
855 EXPECT_EQ("gcm@chrome.com", mcs_client()->last_data_message_stanza().from());
856 EXPECT_EQ(kSender
, mcs_client()->last_data_message_stanza().to());
857 EXPECT_EQ("key", mcs_client()->last_data_message_stanza().app_data(0).key());
859 mcs_client()->last_data_message_stanza().app_data(0).value());
862 TEST_F(GCMClientImplTest
, SendMessageAcknowledged
) {
863 ReceiveOnMessageSentToMCS(kAppId
, "007", MCSClient::SENT
);
864 EXPECT_EQ(MESSAGE_SEND_ACK
, last_event());
865 EXPECT_EQ(kAppId
, last_app_id());
866 EXPECT_EQ("007", last_message_id());
869 class GCMClientImplCheckinTest
: public GCMClientImplTest
{
871 GCMClientImplCheckinTest();
872 ~GCMClientImplCheckinTest() override
;
874 void SetUp() override
;
877 GCMClientImplCheckinTest::GCMClientImplCheckinTest() {
880 GCMClientImplCheckinTest::~GCMClientImplCheckinTest() {
883 void GCMClientImplCheckinTest::SetUp() {
884 testing::Test::SetUp();
885 // Creating unique temp directory that will be used by GCMStore shared between
886 // GCM Client and G-services settings.
887 ASSERT_TRUE(CreateUniqueTempDir());
888 // Time will be advancing one hour every time it is checked.
889 BuildGCMClient(base::TimeDelta::FromSeconds(kSettingsCheckinInterval
));
890 InitializeGCMClient();
894 TEST_F(GCMClientImplCheckinTest
, GServicesSettingsAfterInitialCheckin
) {
895 std::map
<std::string
, std::string
> settings
;
896 settings
["checkin_interval"] = base::Int64ToString(kSettingsCheckinInterval
);
897 settings
["checkin_url"] = "http://alternative.url/checkin";
898 settings
["gcm_hostname"] = "alternative.gcm.host";
899 settings
["gcm_secure_port"] = "7777";
900 settings
["gcm_registration_url"] = "http://alternative.url/registration";
901 CompleteCheckin(kDeviceAndroidId
,
902 kDeviceSecurityToken
,
903 GServicesSettings::CalculateDigest(settings
),
905 EXPECT_EQ(base::TimeDelta::FromSeconds(kSettingsCheckinInterval
),
906 gservices_settings().GetCheckinInterval());
907 EXPECT_EQ(GURL("http://alternative.url/checkin"),
908 gservices_settings().GetCheckinURL());
909 EXPECT_EQ(GURL("http://alternative.url/registration"),
910 gservices_settings().GetRegistrationURL());
911 EXPECT_EQ(GURL("https://alternative.gcm.host:7777"),
912 gservices_settings().GetMCSMainEndpoint());
913 EXPECT_EQ(GURL("https://alternative.gcm.host:443"),
914 gservices_settings().GetMCSFallbackEndpoint());
917 // This test only checks that periodic checkin happens.
918 TEST_F(GCMClientImplCheckinTest
, PeriodicCheckin
) {
919 std::map
<std::string
, std::string
> settings
;
920 settings
["checkin_interval"] = base::IntToString(kSettingsCheckinInterval
);
921 settings
["checkin_url"] = "http://alternative.url/checkin";
922 settings
["gcm_hostname"] = "alternative.gcm.host";
923 settings
["gcm_secure_port"] = "7777";
924 settings
["gcm_registration_url"] = "http://alternative.url/registration";
925 CompleteCheckin(kDeviceAndroidId
,
926 kDeviceSecurityToken
,
927 GServicesSettings::CalculateDigest(settings
),
930 EXPECT_EQ(2, clock()->call_count());
933 CompleteCheckin(kDeviceAndroidId
,
934 kDeviceSecurityToken
,
935 GServicesSettings::CalculateDigest(settings
),
939 TEST_F(GCMClientImplCheckinTest
, LoadGSettingsFromStore
) {
940 std::map
<std::string
, std::string
> settings
;
941 settings
["checkin_interval"] = base::IntToString(kSettingsCheckinInterval
);
942 settings
["checkin_url"] = "http://alternative.url/checkin";
943 settings
["gcm_hostname"] = "alternative.gcm.host";
944 settings
["gcm_secure_port"] = "7777";
945 settings
["gcm_registration_url"] = "http://alternative.url/registration";
946 CompleteCheckin(kDeviceAndroidId
,
947 kDeviceSecurityToken
,
948 GServicesSettings::CalculateDigest(settings
),
951 BuildGCMClient(base::TimeDelta());
952 InitializeGCMClient();
955 EXPECT_EQ(base::TimeDelta::FromSeconds(kSettingsCheckinInterval
),
956 gservices_settings().GetCheckinInterval());
957 EXPECT_EQ(GURL("http://alternative.url/checkin"),
958 gservices_settings().GetCheckinURL());
959 EXPECT_EQ(GURL("http://alternative.url/registration"),
960 gservices_settings().GetRegistrationURL());
961 EXPECT_EQ(GURL("https://alternative.gcm.host:7777"),
962 gservices_settings().GetMCSMainEndpoint());
963 EXPECT_EQ(GURL("https://alternative.gcm.host:443"),
964 gservices_settings().GetMCSFallbackEndpoint());
967 // This test only checks that periodic checkin happens.
968 TEST_F(GCMClientImplCheckinTest
, CheckinWithAccounts
) {
969 std::map
<std::string
, std::string
> settings
;
970 settings
["checkin_interval"] = base::IntToString(kSettingsCheckinInterval
);
971 settings
["checkin_url"] = "http://alternative.url/checkin";
972 settings
["gcm_hostname"] = "alternative.gcm.host";
973 settings
["gcm_secure_port"] = "7777";
974 settings
["gcm_registration_url"] = "http://alternative.url/registration";
975 CompleteCheckin(kDeviceAndroidId
,
976 kDeviceSecurityToken
,
977 GServicesSettings::CalculateDigest(settings
),
980 std::vector
<GCMClient::AccountTokenInfo
> account_tokens
;
981 account_tokens
.push_back(MakeAccountToken("test_user1@gmail.com", "token1"));
982 account_tokens
.push_back(MakeAccountToken("test_user2@gmail.com", "token2"));
983 gcm_client()->SetAccountTokens(account_tokens
);
985 EXPECT_TRUE(device_checkin_info().last_checkin_accounts
.empty());
986 EXPECT_TRUE(device_checkin_info().accounts_set
);
987 EXPECT_EQ(MakeEmailToTokenMap(account_tokens
),
988 device_checkin_info().account_tokens
);
991 CompleteCheckin(kDeviceAndroidId
,
992 kDeviceSecurityToken
,
993 GServicesSettings::CalculateDigest(settings
),
996 std::set
<std::string
> accounts
;
997 accounts
.insert("test_user1@gmail.com");
998 accounts
.insert("test_user2@gmail.com");
999 EXPECT_EQ(accounts
, device_checkin_info().last_checkin_accounts
);
1000 EXPECT_TRUE(device_checkin_info().accounts_set
);
1001 EXPECT_EQ(MakeEmailToTokenMap(account_tokens
),
1002 device_checkin_info().account_tokens
);
1005 // This test only checks that periodic checkin happens.
1006 TEST_F(GCMClientImplCheckinTest
, CheckinWhenAccountRemoved
) {
1007 std::map
<std::string
, std::string
> settings
;
1008 settings
["checkin_interval"] = base::IntToString(kSettingsCheckinInterval
);
1009 settings
["checkin_url"] = "http://alternative.url/checkin";
1010 settings
["gcm_hostname"] = "alternative.gcm.host";
1011 settings
["gcm_secure_port"] = "7777";
1012 settings
["gcm_registration_url"] = "http://alternative.url/registration";
1013 CompleteCheckin(kDeviceAndroidId
,
1014 kDeviceSecurityToken
,
1015 GServicesSettings::CalculateDigest(settings
),
1018 std::vector
<GCMClient::AccountTokenInfo
> account_tokens
;
1019 account_tokens
.push_back(MakeAccountToken("test_user1@gmail.com", "token1"));
1020 account_tokens
.push_back(MakeAccountToken("test_user2@gmail.com", "token2"));
1021 gcm_client()->SetAccountTokens(account_tokens
);
1022 PumpLoopUntilIdle();
1023 CompleteCheckin(kDeviceAndroidId
,
1024 kDeviceSecurityToken
,
1025 GServicesSettings::CalculateDigest(settings
),
1028 EXPECT_EQ(2UL, device_checkin_info().last_checkin_accounts
.size());
1029 EXPECT_TRUE(device_checkin_info().accounts_set
);
1030 EXPECT_EQ(MakeEmailToTokenMap(account_tokens
),
1031 device_checkin_info().account_tokens
);
1033 account_tokens
.erase(account_tokens
.begin() + 1);
1034 gcm_client()->SetAccountTokens(account_tokens
);
1036 PumpLoopUntilIdle();
1037 CompleteCheckin(kDeviceAndroidId
,
1038 kDeviceSecurityToken
,
1039 GServicesSettings::CalculateDigest(settings
),
1042 std::set
<std::string
> accounts
;
1043 accounts
.insert("test_user1@gmail.com");
1044 EXPECT_EQ(accounts
, device_checkin_info().last_checkin_accounts
);
1045 EXPECT_TRUE(device_checkin_info().accounts_set
);
1046 EXPECT_EQ(MakeEmailToTokenMap(account_tokens
),
1047 device_checkin_info().account_tokens
);
1050 // This test only checks that periodic checkin happens.
1051 TEST_F(GCMClientImplCheckinTest
, CheckinWhenAccountReplaced
) {
1052 std::map
<std::string
, std::string
> settings
;
1053 settings
["checkin_interval"] = base::IntToString(kSettingsCheckinInterval
);
1054 settings
["checkin_url"] = "http://alternative.url/checkin";
1055 settings
["gcm_hostname"] = "alternative.gcm.host";
1056 settings
["gcm_secure_port"] = "7777";
1057 settings
["gcm_registration_url"] = "http://alternative.url/registration";
1058 CompleteCheckin(kDeviceAndroidId
,
1059 kDeviceSecurityToken
,
1060 GServicesSettings::CalculateDigest(settings
),
1063 std::vector
<GCMClient::AccountTokenInfo
> account_tokens
;
1064 account_tokens
.push_back(MakeAccountToken("test_user1@gmail.com", "token1"));
1065 gcm_client()->SetAccountTokens(account_tokens
);
1067 PumpLoopUntilIdle();
1068 CompleteCheckin(kDeviceAndroidId
,
1069 kDeviceSecurityToken
,
1070 GServicesSettings::CalculateDigest(settings
),
1073 std::set
<std::string
> accounts
;
1074 accounts
.insert("test_user1@gmail.com");
1075 EXPECT_EQ(accounts
, device_checkin_info().last_checkin_accounts
);
1077 // This should trigger another checkin, because the list of accounts is
1079 account_tokens
.clear();
1080 account_tokens
.push_back(MakeAccountToken("test_user2@gmail.com", "token2"));
1081 gcm_client()->SetAccountTokens(account_tokens
);
1083 PumpLoopUntilIdle();
1084 CompleteCheckin(kDeviceAndroidId
,
1085 kDeviceSecurityToken
,
1086 GServicesSettings::CalculateDigest(settings
),
1090 accounts
.insert("test_user2@gmail.com");
1091 EXPECT_EQ(accounts
, device_checkin_info().last_checkin_accounts
);
1092 EXPECT_TRUE(device_checkin_info().accounts_set
);
1093 EXPECT_EQ(MakeEmailToTokenMap(account_tokens
),
1094 device_checkin_info().account_tokens
);
1097 class GCMClientImplStartAndStopTest
: public GCMClientImplTest
{
1099 GCMClientImplStartAndStopTest();
1100 ~GCMClientImplStartAndStopTest() override
;
1102 void SetUp() override
;
1104 void DefaultCompleteCheckin();
1107 GCMClientImplStartAndStopTest::GCMClientImplStartAndStopTest() {
1110 GCMClientImplStartAndStopTest::~GCMClientImplStartAndStopTest() {
1113 void GCMClientImplStartAndStopTest::SetUp() {
1114 testing::Test::SetUp();
1115 ASSERT_TRUE(CreateUniqueTempDir());
1116 BuildGCMClient(base::TimeDelta());
1117 InitializeGCMClient();
1120 void GCMClientImplStartAndStopTest::DefaultCompleteCheckin() {
1121 SetUpUrlFetcherFactory();
1122 CompleteCheckin(kDeviceAndroidId
,
1123 kDeviceSecurityToken
,
1125 std::map
<std::string
, std::string
>());
1126 PumpLoopUntilIdle();
1129 TEST_F(GCMClientImplStartAndStopTest
, StartStopAndRestart
) {
1130 // GCMClientImpl should be in INITIALIZED state at first.
1131 EXPECT_EQ(GCMClientImpl::INITIALIZED
, gcm_client_state());
1133 // Delay start the GCM.
1134 gcm_client()->Start(GCMClient::DELAYED_START
);
1135 PumpLoopUntilIdle();
1136 EXPECT_EQ(GCMClientImpl::INITIALIZED
, gcm_client_state());
1139 gcm_client()->Stop();
1140 PumpLoopUntilIdle();
1141 EXPECT_EQ(GCMClientImpl::INITIALIZED
, gcm_client_state());
1143 // Restart the GCM without delay.
1144 gcm_client()->Start(GCMClient::IMMEDIATE_START
);
1145 PumpLoopUntilIdle();
1146 EXPECT_EQ(GCMClientImpl::INITIAL_DEVICE_CHECKIN
, gcm_client_state());
1149 TEST_F(GCMClientImplStartAndStopTest
, DelayedStartAndStopImmediately
) {
1150 // GCMClientImpl should be in INITIALIZED state at first.
1151 EXPECT_EQ(GCMClientImpl::INITIALIZED
, gcm_client_state());
1153 // Delay start the GCM and then stop it immediately.
1154 gcm_client()->Start(GCMClient::DELAYED_START
);
1155 gcm_client()->Stop();
1156 PumpLoopUntilIdle();
1157 EXPECT_EQ(GCMClientImpl::INITIALIZED
, gcm_client_state());
1160 TEST_F(GCMClientImplStartAndStopTest
, ImmediateStartAndStopImmediately
) {
1161 // GCMClientImpl should be in INITIALIZED state at first.
1162 EXPECT_EQ(GCMClientImpl::INITIALIZED
, gcm_client_state());
1164 // Start the GCM and then stop it immediately.
1165 gcm_client()->Start(GCMClient::IMMEDIATE_START
);
1166 gcm_client()->Stop();
1167 PumpLoopUntilIdle();
1168 EXPECT_EQ(GCMClientImpl::INITIALIZED
, gcm_client_state());
1171 TEST_F(GCMClientImplStartAndStopTest
, DelayedStartStopAndRestart
) {
1172 // GCMClientImpl should be in INITIALIZED state at first.
1173 EXPECT_EQ(GCMClientImpl::INITIALIZED
, gcm_client_state());
1175 // Delay start the GCM and then stop and restart it immediately.
1176 gcm_client()->Start(GCMClient::DELAYED_START
);
1177 gcm_client()->Stop();
1178 gcm_client()->Start(GCMClient::DELAYED_START
);
1179 PumpLoopUntilIdle();
1180 EXPECT_EQ(GCMClientImpl::INITIALIZED
, gcm_client_state());
1183 TEST_F(GCMClientImplStartAndStopTest
, ImmediateStartStopAndRestart
) {
1184 // GCMClientImpl should be in INITIALIZED state at first.
1185 EXPECT_EQ(GCMClientImpl::INITIALIZED
, gcm_client_state());
1187 // Start the GCM and then stop and restart it immediately.
1188 gcm_client()->Start(GCMClient::IMMEDIATE_START
);
1189 gcm_client()->Stop();
1190 gcm_client()->Start(GCMClient::IMMEDIATE_START
);
1191 PumpLoopUntilIdle();
1192 EXPECT_EQ(GCMClientImpl::INITIAL_DEVICE_CHECKIN
, gcm_client_state());
1195 TEST_F(GCMClientImplStartAndStopTest
, ImmediateStartAndThenImmediateStart
) {
1196 // GCMClientImpl should be in INITIALIZED state at first.
1197 EXPECT_EQ(GCMClientImpl::INITIALIZED
, gcm_client_state());
1199 // Start the GCM immediately and complete the checkin.
1200 gcm_client()->Start(GCMClient::IMMEDIATE_START
);
1201 PumpLoopUntilIdle();
1202 EXPECT_EQ(GCMClientImpl::INITIAL_DEVICE_CHECKIN
, gcm_client_state());
1203 DefaultCompleteCheckin();
1204 EXPECT_EQ(GCMClientImpl::READY
, gcm_client_state());
1207 gcm_client()->Stop();
1208 PumpLoopUntilIdle();
1209 EXPECT_EQ(GCMClientImpl::INITIALIZED
, gcm_client_state());
1211 // Start the GCM immediately. GCMClientImpl should be in READY state.
1212 BuildGCMClient(base::TimeDelta());
1213 InitializeGCMClient();
1214 gcm_client()->Start(GCMClient::IMMEDIATE_START
);
1215 PumpLoopUntilIdle();
1216 EXPECT_EQ(GCMClientImpl::READY
, gcm_client_state());
1219 TEST_F(GCMClientImplStartAndStopTest
, ImmediateStartAndThenDelayStart
) {
1220 // GCMClientImpl should be in INITIALIZED state at first.
1221 EXPECT_EQ(GCMClientImpl::INITIALIZED
, gcm_client_state());
1223 // Start the GCM immediately and complete the checkin.
1224 gcm_client()->Start(GCMClient::IMMEDIATE_START
);
1225 PumpLoopUntilIdle();
1226 EXPECT_EQ(GCMClientImpl::INITIAL_DEVICE_CHECKIN
, gcm_client_state());
1227 DefaultCompleteCheckin();
1228 EXPECT_EQ(GCMClientImpl::READY
, gcm_client_state());
1231 gcm_client()->Stop();
1232 PumpLoopUntilIdle();
1233 EXPECT_EQ(GCMClientImpl::INITIALIZED
, gcm_client_state());
1235 // Delay start the GCM. GCMClientImpl should be in LOADED state.
1236 BuildGCMClient(base::TimeDelta());
1237 InitializeGCMClient();
1238 gcm_client()->Start(GCMClient::DELAYED_START
);
1239 PumpLoopUntilIdle();
1240 EXPECT_EQ(GCMClientImpl::LOADED
, gcm_client_state());
1243 TEST_F(GCMClientImplStartAndStopTest
, DelayedStart
) {
1244 // GCMClientImpl should be in INITIALIZED state at first.
1245 EXPECT_EQ(GCMClientImpl::INITIALIZED
, gcm_client_state());
1247 // Delay start the GCM. The store will not be loaded and GCMClientImpl should
1248 // still be in INITIALIZED state.
1249 gcm_client()->Start(GCMClient::DELAYED_START
);
1250 PumpLoopUntilIdle();
1251 EXPECT_EQ(GCMClientImpl::INITIALIZED
, gcm_client_state());
1253 // Start the GCM immediately and complete the checkin.
1254 gcm_client()->Start(GCMClient::IMMEDIATE_START
);
1255 PumpLoopUntilIdle();
1256 EXPECT_EQ(GCMClientImpl::INITIAL_DEVICE_CHECKIN
, gcm_client_state());
1257 DefaultCompleteCheckin();
1258 EXPECT_EQ(GCMClientImpl::READY
, gcm_client_state());
1261 std::vector
<std::string
> senders
;
1262 senders
.push_back("sender");
1263 Register(kAppId
, senders
);
1264 CompleteRegistration("reg_id");
1265 EXPECT_EQ(GCMClientImpl::READY
, gcm_client_state());
1268 gcm_client()->Stop();
1269 PumpLoopUntilIdle();
1270 EXPECT_EQ(GCMClientImpl::INITIALIZED
, gcm_client_state());
1272 // Delay start the GCM. GCM is indeed started without delay because the
1273 // registration record has been found.
1274 BuildGCMClient(base::TimeDelta());
1275 InitializeGCMClient();
1276 gcm_client()->Start(GCMClient::DELAYED_START
);
1277 PumpLoopUntilIdle();
1278 EXPECT_EQ(GCMClientImpl::READY
, gcm_client_state());
1281 // Test for known account mappings and last token fetching time being passed
1283 TEST_F(GCMClientImplStartAndStopTest
, OnGCMReadyAccountsAndTokenFetchingTime
) {
1284 // Start the GCM and wait until it is ready.
1285 gcm_client()->Start(GCMClient::IMMEDIATE_START
);
1286 PumpLoopUntilIdle();
1287 DefaultCompleteCheckin();
1289 base::Time expected_time
= base::Time::Now();
1290 gcm_client()->SetLastTokenFetchTime(expected_time
);
1291 AccountMapping expected_mapping
;
1292 expected_mapping
.account_id
= "accId";
1293 expected_mapping
.email
= "email@gmail.com";
1294 expected_mapping
.status
= AccountMapping::MAPPED
;
1295 expected_mapping
.status_change_timestamp
= expected_time
;
1296 gcm_client()->UpdateAccountMapping(expected_mapping
);
1297 PumpLoopUntilIdle();
1300 gcm_client()->Stop();
1301 PumpLoopUntilIdle();
1304 gcm_client()->Start(GCMClient::IMMEDIATE_START
);
1305 PumpLoopUntilIdle();
1307 EXPECT_EQ(LOADING_COMPLETED
, last_event());
1308 EXPECT_EQ(expected_time
, last_token_fetch_time());
1309 ASSERT_EQ(1UL, last_account_mappings().size());
1310 const AccountMapping
& actual_mapping
= last_account_mappings()[0];
1311 EXPECT_EQ(expected_mapping
.account_id
, actual_mapping
.account_id
);
1312 EXPECT_EQ(expected_mapping
.email
, actual_mapping
.email
);
1313 EXPECT_EQ(expected_mapping
.status
, actual_mapping
.status
);
1314 EXPECT_EQ(expected_mapping
.status_change_timestamp
,
1315 actual_mapping
.status_change_timestamp
);
1319 class GCMClientInstanceIDTest
: public GCMClientImplTest
{
1321 GCMClientInstanceIDTest();
1322 ~GCMClientInstanceIDTest() override
;
1324 void AddInstanceID(const std::string
& app_id
,
1325 const std::string
& instance_id
);
1326 void RemoveInstanceID(const std::string
& app_id
);
1327 void GetToken(const std::string
& app_id
,
1328 const std::string
& authorized_entity
,
1329 const std::string
& scope
);
1330 void DeleteToken(const std::string
& app_id
,
1331 const std::string
& authorized_entity
,
1332 const std::string
& scope
);
1333 void CompleteDeleteToken();
1334 bool ExistsToken(const std::string
& app_id
,
1335 const std::string
& authorized_entity
,
1336 const std::string
& scope
) const;
1339 GCMClientInstanceIDTest::GCMClientInstanceIDTest() {
1342 GCMClientInstanceIDTest::~GCMClientInstanceIDTest() {
1345 void GCMClientInstanceIDTest::AddInstanceID(const std::string
& app_id
,
1346 const std::string
& instance_id
) {
1347 gcm_client()->AddInstanceIDData(app_id
, instance_id
, "123");
1350 void GCMClientInstanceIDTest::RemoveInstanceID(const std::string
& app_id
) {
1351 gcm_client()->RemoveInstanceIDData(app_id
);
1354 void GCMClientInstanceIDTest::GetToken(const std::string
& app_id
,
1355 const std::string
& authorized_entity
,
1356 const std::string
& scope
) {
1357 scoped_ptr
<InstanceIDTokenInfo
> instance_id_info(new InstanceIDTokenInfo
);
1358 instance_id_info
->app_id
= app_id
;
1359 instance_id_info
->authorized_entity
= authorized_entity
;
1360 instance_id_info
->scope
= scope
;
1361 gcm_client()->Register(
1362 make_linked_ptr
<RegistrationInfo
>(instance_id_info
.release()));
1365 void GCMClientInstanceIDTest::DeleteToken(const std::string
& app_id
,
1366 const std::string
& authorized_entity
,
1367 const std::string
& scope
) {
1368 scoped_ptr
<InstanceIDTokenInfo
> instance_id_info(new InstanceIDTokenInfo
);
1369 instance_id_info
->app_id
= app_id
;
1370 instance_id_info
->authorized_entity
= authorized_entity
;
1371 instance_id_info
->scope
= scope
;
1372 gcm_client()->Unregister(
1373 make_linked_ptr
<RegistrationInfo
>(instance_id_info
.release()));
1376 void GCMClientInstanceIDTest::CompleteDeleteToken() {
1377 std::string
response(kDeleteTokenResponse
);
1378 net::TestURLFetcher
* fetcher
= url_fetcher_factory()->GetFetcherByID(0);
1379 ASSERT_TRUE(fetcher
);
1380 fetcher
->set_response_code(net::HTTP_OK
);
1381 fetcher
->SetResponseString(response
);
1382 fetcher
->delegate()->OnURLFetchComplete(fetcher
);
1383 // Give a chance for GCMStoreImpl::Backend to finish persisting data.
1384 PumpLoopUntilIdle();
1387 bool GCMClientInstanceIDTest::ExistsToken(const std::string
& app_id
,
1388 const std::string
& authorized_entity
,
1389 const std::string
& scope
) const {
1390 scoped_ptr
<InstanceIDTokenInfo
> instance_id_info(new InstanceIDTokenInfo
);
1391 instance_id_info
->app_id
= app_id
;
1392 instance_id_info
->authorized_entity
= authorized_entity
;
1393 instance_id_info
->scope
= scope
;
1394 return gcm_client()->registrations_
.count(
1395 make_linked_ptr
<RegistrationInfo
>(instance_id_info
.release())) > 0;
1398 TEST_F(GCMClientInstanceIDTest
, GetToken
) {
1399 AddInstanceID(kAppId
, kInstanceID
);
1402 EXPECT_FALSE(ExistsToken(kAppId
, kSender
, kScope
));
1403 GetToken(kAppId
, kSender
, kScope
);
1404 CompleteRegistration("token1");
1406 EXPECT_EQ(REGISTRATION_COMPLETED
, last_event());
1407 EXPECT_EQ(kAppId
, last_app_id());
1408 EXPECT_EQ("token1", last_registration_id());
1409 EXPECT_EQ(GCMClient::SUCCESS
, last_result());
1410 EXPECT_TRUE(ExistsToken(kAppId
, kSender
, kScope
));
1412 // Get another token.
1413 EXPECT_FALSE(ExistsToken(kAppId
, kSender2
, kScope
));
1414 GetToken(kAppId
, kSender2
, kScope
);
1415 CompleteRegistration("token2");
1417 EXPECT_EQ(REGISTRATION_COMPLETED
, last_event());
1418 EXPECT_EQ(kAppId
, last_app_id());
1419 EXPECT_EQ("token2", last_registration_id());
1420 EXPECT_EQ(GCMClient::SUCCESS
, last_result());
1421 EXPECT_TRUE(ExistsToken(kAppId
, kSender2
, kScope
));
1422 // The 1st token still exists.
1423 EXPECT_TRUE(ExistsToken(kAppId
, kSender
, kScope
));
1426 TEST_F(GCMClientInstanceIDTest
, DeleteSingleToken
) {
1427 AddInstanceID(kAppId
, kInstanceID
);
1430 EXPECT_FALSE(ExistsToken(kAppId
, kSender
, kScope
));
1431 GetToken(kAppId
, kSender
, kScope
);
1432 CompleteRegistration("token1");
1434 EXPECT_EQ(REGISTRATION_COMPLETED
, last_event());
1435 EXPECT_EQ(kAppId
, last_app_id());
1436 EXPECT_EQ("token1", last_registration_id());
1437 EXPECT_EQ(GCMClient::SUCCESS
, last_result());
1438 EXPECT_TRUE(ExistsToken(kAppId
, kSender
, kScope
));
1440 // Get another token.
1441 EXPECT_FALSE(ExistsToken(kAppId
, kSender2
, kScope
));
1442 GetToken(kAppId
, kSender2
, kScope
);
1443 CompleteRegistration("token2");
1445 EXPECT_EQ(REGISTRATION_COMPLETED
, last_event());
1446 EXPECT_EQ(kAppId
, last_app_id());
1447 EXPECT_EQ("token2", last_registration_id());
1448 EXPECT_EQ(GCMClient::SUCCESS
, last_result());
1449 EXPECT_TRUE(ExistsToken(kAppId
, kSender2
, kScope
));
1450 // The 1st token still exists.
1451 EXPECT_TRUE(ExistsToken(kAppId
, kSender
, kScope
));
1453 // Delete the 2nd token.
1454 DeleteToken(kAppId
, kSender2
, kScope
);
1455 CompleteDeleteToken();
1457 EXPECT_EQ(UNREGISTRATION_COMPLETED
, last_event());
1458 EXPECT_EQ(kAppId
, last_app_id());
1459 EXPECT_EQ(GCMClient::SUCCESS
, last_result());
1460 // The 2nd token is gone while the 1st token still exists.
1461 EXPECT_TRUE(ExistsToken(kAppId
, kSender
, kScope
));
1462 EXPECT_FALSE(ExistsToken(kAppId
, kSender2
, kScope
));
1464 // Delete the 1st token.
1465 DeleteToken(kAppId
, kSender
, kScope
);
1466 CompleteDeleteToken();
1468 EXPECT_EQ(UNREGISTRATION_COMPLETED
, last_event());
1469 EXPECT_EQ(kAppId
, last_app_id());
1470 EXPECT_EQ(GCMClient::SUCCESS
, last_result());
1471 // Both tokens are gone now.
1472 EXPECT_FALSE(ExistsToken(kAppId
, kSender
, kScope
));
1473 EXPECT_FALSE(ExistsToken(kAppId
, kSender
, kScope
));
1476 TEST_F(GCMClientInstanceIDTest
, DeleteAllTokens
) {
1477 AddInstanceID(kAppId
, kInstanceID
);
1480 EXPECT_FALSE(ExistsToken(kAppId
, kSender
, kScope
));
1481 GetToken(kAppId
, kSender
, kScope
);
1482 CompleteRegistration("token1");
1484 EXPECT_EQ(REGISTRATION_COMPLETED
, last_event());
1485 EXPECT_EQ(kAppId
, last_app_id());
1486 EXPECT_EQ("token1", last_registration_id());
1487 EXPECT_EQ(GCMClient::SUCCESS
, last_result());
1488 EXPECT_TRUE(ExistsToken(kAppId
, kSender
, kScope
));
1490 // Get another token.
1491 EXPECT_FALSE(ExistsToken(kAppId
, kSender2
, kScope
));
1492 GetToken(kAppId
, kSender2
, kScope
);
1493 CompleteRegistration("token2");
1495 EXPECT_EQ(REGISTRATION_COMPLETED
, last_event());
1496 EXPECT_EQ(kAppId
, last_app_id());
1497 EXPECT_EQ("token2", last_registration_id());
1498 EXPECT_EQ(GCMClient::SUCCESS
, last_result());
1499 EXPECT_TRUE(ExistsToken(kAppId
, kSender2
, kScope
));
1500 // The 1st token still exists.
1501 EXPECT_TRUE(ExistsToken(kAppId
, kSender
, kScope
));
1503 // Delete all tokens.
1504 DeleteToken(kAppId
, "*", "*");
1505 CompleteDeleteToken();
1507 EXPECT_EQ(UNREGISTRATION_COMPLETED
, last_event());
1508 EXPECT_EQ(kAppId
, last_app_id());
1509 EXPECT_EQ(GCMClient::SUCCESS
, last_result());
1510 // All tokens are gone now.
1511 EXPECT_FALSE(ExistsToken(kAppId
, kSender
, kScope
));
1512 EXPECT_FALSE(ExistsToken(kAppId
, kSender
, kScope
));
1515 TEST_F(GCMClientInstanceIDTest
, DeleteAllTokensBeforeGetAnyToken
) {
1516 AddInstanceID(kAppId
, kInstanceID
);
1518 // Delete all tokens without getting a token first.
1519 DeleteToken(kAppId
, "*", "*");
1520 // No need to call CompleteDeleteToken since unregistration request should
1521 // not be triggered.
1522 PumpLoopUntilIdle();
1524 EXPECT_EQ(UNREGISTRATION_COMPLETED
, last_event());
1525 EXPECT_EQ(kAppId
, last_app_id());
1526 EXPECT_EQ(GCMClient::SUCCESS
, last_result());