cygprofile: increase timeouts to allow showing web contents
[chromium-blink-merge.git] / components / gcm_driver / gcm_client_impl_unittest.cc
blob3fbb2e722a0546f8bd2b42df13ca96866a92a0a5
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=";
59 const char kRawData[] = "example raw data";
61 const char kInstanceID[] = "iid_1";
62 const char kScope[] = "GCM";
63 const char kDeleteTokenResponse[] = "token=foo";
65 // Helper for building arbitrary data messages.
66 MCSMessage BuildDownstreamMessage(
67 const std::string& project_id,
68 const std::string& app_id,
69 const std::map<std::string, std::string>& data,
70 const std::string& raw_data) {
71 mcs_proto::DataMessageStanza data_message;
72 data_message.set_from(project_id);
73 data_message.set_category(app_id);
74 for (std::map<std::string, std::string>::const_iterator iter = data.begin();
75 iter != data.end();
76 ++iter) {
77 mcs_proto::AppData* app_data = data_message.add_app_data();
78 app_data->set_key(iter->first);
79 app_data->set_value(iter->second);
81 data_message.set_raw_data(raw_data);
82 return MCSMessage(kDataMessageStanzaTag, data_message);
85 GCMClient::AccountTokenInfo MakeAccountToken(const std::string& email,
86 const std::string& token) {
87 GCMClient::AccountTokenInfo account_token;
88 account_token.email = email;
89 account_token.access_token = token;
90 return account_token;
93 std::map<std::string, std::string> MakeEmailToTokenMap(
94 const std::vector<GCMClient::AccountTokenInfo>& account_tokens) {
95 std::map<std::string, std::string> email_token_map;
96 for (std::vector<GCMClient::AccountTokenInfo>::const_iterator iter =
97 account_tokens.begin(); iter != account_tokens.end(); ++iter) {
98 email_token_map[iter->email] = iter->access_token;
100 return email_token_map;
103 class FakeMCSClient : public MCSClient {
104 public:
105 FakeMCSClient(base::Clock* clock,
106 ConnectionFactory* connection_factory,
107 GCMStore* gcm_store,
108 GCMStatsRecorder* recorder);
109 ~FakeMCSClient() override;
110 void Login(uint64 android_id, uint64 security_token) override;
111 void SendMessage(const MCSMessage& message) override;
113 uint64 last_android_id() const { return last_android_id_; }
114 uint64 last_security_token() const { return last_security_token_; }
115 uint8 last_message_tag() const { return last_message_tag_; }
116 const mcs_proto::DataMessageStanza& last_data_message_stanza() const {
117 return last_data_message_stanza_;
120 private:
121 uint64 last_android_id_;
122 uint64 last_security_token_;
123 uint8 last_message_tag_;
124 mcs_proto::DataMessageStanza last_data_message_stanza_;
127 FakeMCSClient::FakeMCSClient(base::Clock* clock,
128 ConnectionFactory* connection_factory,
129 GCMStore* gcm_store,
130 GCMStatsRecorder* recorder)
131 : MCSClient("", clock, connection_factory, gcm_store, recorder),
132 last_android_id_(0u),
133 last_security_token_(0u),
134 last_message_tag_(kNumProtoTypes) {
137 FakeMCSClient::~FakeMCSClient() {
140 void FakeMCSClient::Login(uint64 android_id, uint64 security_token) {
141 last_android_id_ = android_id;
142 last_security_token_ = security_token;
145 void FakeMCSClient::SendMessage(const MCSMessage& message) {
146 last_message_tag_ = message.tag();
147 if (last_message_tag_ == kDataMessageStanzaTag) {
148 last_data_message_stanza_.CopyFrom(
149 reinterpret_cast<const mcs_proto::DataMessageStanza&>(
150 message.GetProtobuf()));
154 class AutoAdvancingTestClock : public base::Clock {
155 public:
156 explicit AutoAdvancingTestClock(base::TimeDelta auto_increment_time_delta);
157 ~AutoAdvancingTestClock() override;
159 base::Time Now() override;
160 void Advance(TimeDelta delta);
161 int call_count() const { return call_count_; }
163 private:
164 int call_count_;
165 base::TimeDelta auto_increment_time_delta_;
166 base::Time now_;
168 DISALLOW_COPY_AND_ASSIGN(AutoAdvancingTestClock);
171 AutoAdvancingTestClock::AutoAdvancingTestClock(
172 base::TimeDelta auto_increment_time_delta)
173 : call_count_(0), auto_increment_time_delta_(auto_increment_time_delta) {
176 AutoAdvancingTestClock::~AutoAdvancingTestClock() {
179 base::Time AutoAdvancingTestClock::Now() {
180 call_count_++;
181 now_ += auto_increment_time_delta_;
182 return now_;
185 void AutoAdvancingTestClock::Advance(base::TimeDelta delta) {
186 now_ += delta;
189 class FakeGCMInternalsBuilder : public GCMInternalsBuilder {
190 public:
191 FakeGCMInternalsBuilder(base::TimeDelta clock_step);
192 ~FakeGCMInternalsBuilder() override;
194 scoped_ptr<base::Clock> BuildClock() override;
195 scoped_ptr<MCSClient> BuildMCSClient(const std::string& version,
196 base::Clock* clock,
197 ConnectionFactory* connection_factory,
198 GCMStore* gcm_store,
199 GCMStatsRecorder* recorder) override;
200 scoped_ptr<ConnectionFactory> BuildConnectionFactory(
201 const std::vector<GURL>& endpoints,
202 const net::BackoffEntry::Policy& backoff_policy,
203 const scoped_refptr<net::HttpNetworkSession>& gcm_network_session,
204 const scoped_refptr<net::HttpNetworkSession>& http_network_session,
205 net::NetLog* net_log,
206 GCMStatsRecorder* recorder) override;
208 private:
209 base::TimeDelta clock_step_;
212 FakeGCMInternalsBuilder::FakeGCMInternalsBuilder(base::TimeDelta clock_step)
213 : clock_step_(clock_step) {
216 FakeGCMInternalsBuilder::~FakeGCMInternalsBuilder() {}
218 scoped_ptr<base::Clock> FakeGCMInternalsBuilder::BuildClock() {
219 return make_scoped_ptr<base::Clock>(new AutoAdvancingTestClock(clock_step_));
222 scoped_ptr<MCSClient> FakeGCMInternalsBuilder::BuildMCSClient(
223 const std::string& version,
224 base::Clock* clock,
225 ConnectionFactory* connection_factory,
226 GCMStore* gcm_store,
227 GCMStatsRecorder* recorder) {
228 return make_scoped_ptr<MCSClient>(new FakeMCSClient(clock,
229 connection_factory,
230 gcm_store,
231 recorder));
234 scoped_ptr<ConnectionFactory> FakeGCMInternalsBuilder::BuildConnectionFactory(
235 const std::vector<GURL>& endpoints,
236 const net::BackoffEntry::Policy& backoff_policy,
237 const scoped_refptr<net::HttpNetworkSession>& gcm_network_session,
238 const scoped_refptr<net::HttpNetworkSession>& http_network_session,
239 net::NetLog* net_log,
240 GCMStatsRecorder* recorder) {
241 return make_scoped_ptr<ConnectionFactory>(new FakeConnectionFactory());
244 } // namespace
246 class GCMClientImplTest : public testing::Test,
247 public GCMClient::Delegate {
248 public:
249 GCMClientImplTest();
250 ~GCMClientImplTest() override;
252 void SetUp() override;
254 void SetUpUrlFetcherFactory();
256 void BuildGCMClient(base::TimeDelta clock_step);
257 void InitializeGCMClient();
258 void StartGCMClient();
259 void Register(const std::string& app_id,
260 const std::vector<std::string>& senders);
261 void Unregister(const std::string& app_id);
262 void ReceiveMessageFromMCS(const MCSMessage& message);
263 void ReceiveOnMessageSentToMCS(
264 const std::string& app_id,
265 const std::string& message_id,
266 const MCSClient::MessageSendStatus status);
267 void CompleteCheckin(uint64 android_id,
268 uint64 security_token,
269 const std::string& digest,
270 const std::map<std::string, std::string>& settings);
271 void CompleteRegistration(const std::string& registration_id);
272 void CompleteUnregistration(const std::string& app_id);
273 void VerifyPendingRequestFetcherDeleted();
275 bool ExistsRegistration(const std::string& app_id) const;
276 void AddRegistration(const std::string& app_id,
277 const std::vector<std::string>& sender_ids,
278 const std::string& registration_id);
280 // GCMClient::Delegate overrides (for verification).
281 void OnRegisterFinished(const linked_ptr<RegistrationInfo>& registration_info,
282 const std::string& registration_id,
283 GCMClient::Result result) override;
284 void OnUnregisterFinished(
285 const linked_ptr<RegistrationInfo>& registration_info,
286 GCMClient::Result result) override;
287 void OnSendFinished(const std::string& app_id,
288 const std::string& message_id,
289 GCMClient::Result result) override {}
290 void OnMessageReceived(const std::string& registration_id,
291 const IncomingMessage& message) override;
292 void OnMessagesDeleted(const std::string& app_id) override;
293 void OnMessageSendError(
294 const std::string& app_id,
295 const gcm::GCMClient::SendErrorDetails& send_error_details) override;
296 void OnSendAcknowledged(const std::string& app_id,
297 const std::string& message_id) override;
298 void OnGCMReady(const std::vector<AccountMapping>& account_mappings,
299 const base::Time& last_token_fetch_time) override;
300 void OnActivityRecorded() override {}
301 void OnConnected(const net::IPEndPoint& ip_endpoint) override {}
302 void OnDisconnected() override {}
304 GCMClientImpl* gcm_client() const { return gcm_client_.get(); }
305 GCMClientImpl::State gcm_client_state() const {
306 return gcm_client_->state_;
308 FakeMCSClient* mcs_client() const {
309 return reinterpret_cast<FakeMCSClient*>(gcm_client_->mcs_client_.get());
311 ConnectionFactory* connection_factory() const {
312 return gcm_client_->connection_factory_.get();
315 const GCMClientImpl::CheckinInfo& device_checkin_info() const {
316 return gcm_client_->device_checkin_info_;
319 void reset_last_event() {
320 last_event_ = NONE;
321 last_app_id_.clear();
322 last_registration_id_.clear();
323 last_message_id_.clear();
324 last_result_ = GCMClient::UNKNOWN_ERROR;
325 last_account_mappings_.clear();
326 last_token_fetch_time_ = base::Time();
329 LastEvent last_event() const { return last_event_; }
330 const std::string& last_app_id() const { return last_app_id_; }
331 const std::string& last_registration_id() const {
332 return last_registration_id_;
334 const std::string& last_message_id() const { return last_message_id_; }
335 GCMClient::Result last_result() const { return last_result_; }
336 const IncomingMessage& last_message() const { return last_message_; }
337 const GCMClient::SendErrorDetails& last_error_details() const {
338 return last_error_details_;
340 const base::Time& last_token_fetch_time() const {
341 return last_token_fetch_time_;
343 const std::vector<AccountMapping>& last_account_mappings() {
344 return last_account_mappings_;
347 const GServicesSettings& gservices_settings() const {
348 return gcm_client_->gservices_settings_;
351 const base::FilePath& temp_directory_path() const {
352 return temp_directory_.path();
355 base::FilePath gcm_store_path() const {
356 // Pass an non-existent directory as store path to match the exact
357 // behavior in the production code. Currently GCMStoreImpl checks if
358 // the directory exist or not to determine the store existence.
359 return temp_directory_.path().Append(FILE_PATH_LITERAL("GCM Store"));
362 int64 CurrentTime();
364 // Tooling.
365 void PumpLoopUntilIdle();
366 bool CreateUniqueTempDir();
367 AutoAdvancingTestClock* clock() const {
368 return reinterpret_cast<AutoAdvancingTestClock*>(gcm_client_->clock_.get());
370 net::TestURLFetcherFactory* url_fetcher_factory() {
371 return &url_fetcher_factory_;
373 base::TestMockTimeTaskRunner* task_runner() {
374 return task_runner_.get();
377 private:
378 // Variables used for verification.
379 LastEvent last_event_;
380 std::string last_app_id_;
381 std::string last_registration_id_;
382 std::string last_message_id_;
383 GCMClient::Result last_result_;
384 IncomingMessage last_message_;
385 GCMClient::SendErrorDetails last_error_details_;
386 base::Time last_token_fetch_time_;
387 std::vector<AccountMapping> last_account_mappings_;
389 scoped_ptr<GCMClientImpl> gcm_client_;
391 net::TestURLFetcherFactory url_fetcher_factory_;
393 scoped_refptr<base::TestMockTimeTaskRunner> task_runner_;
394 base::ThreadTaskRunnerHandle task_runner_handle_;
396 // Injected to GCM client:
397 base::ScopedTempDir temp_directory_;
398 scoped_refptr<net::TestURLRequestContextGetter> url_request_context_getter_;
401 GCMClientImplTest::GCMClientImplTest()
402 : last_event_(NONE),
403 last_result_(GCMClient::UNKNOWN_ERROR),
404 task_runner_(new base::TestMockTimeTaskRunner),
405 task_runner_handle_(task_runner_),
406 url_request_context_getter_(
407 new net::TestURLRequestContextGetter(task_runner_)) {
410 GCMClientImplTest::~GCMClientImplTest() {}
412 void GCMClientImplTest::SetUp() {
413 testing::Test::SetUp();
414 ASSERT_TRUE(CreateUniqueTempDir());
415 BuildGCMClient(base::TimeDelta());
416 InitializeGCMClient();
417 StartGCMClient();
418 SetUpUrlFetcherFactory();
419 CompleteCheckin(kDeviceAndroidId,
420 kDeviceSecurityToken,
421 std::string(),
422 std::map<std::string, std::string>());
425 void GCMClientImplTest::SetUpUrlFetcherFactory() {
426 url_fetcher_factory_.set_remove_fetcher_on_delete(true);
429 void GCMClientImplTest::PumpLoopUntilIdle() {
430 task_runner_->RunUntilIdle();
433 bool GCMClientImplTest::CreateUniqueTempDir() {
434 return temp_directory_.CreateUniqueTempDir();
437 void GCMClientImplTest::BuildGCMClient(base::TimeDelta clock_step) {
438 gcm_client_.reset(new GCMClientImpl(make_scoped_ptr<GCMInternalsBuilder>(
439 new FakeGCMInternalsBuilder(clock_step))));
442 void GCMClientImplTest::CompleteCheckin(
443 uint64 android_id,
444 uint64 security_token,
445 const std::string& digest,
446 const std::map<std::string, std::string>& settings) {
447 checkin_proto::AndroidCheckinResponse response;
448 response.set_stats_ok(true);
449 response.set_android_id(android_id);
450 response.set_security_token(security_token);
452 // For testing G-services settings.
453 if (!digest.empty()) {
454 response.set_digest(digest);
455 for (std::map<std::string, std::string>::const_iterator it =
456 settings.begin();
457 it != settings.end();
458 ++it) {
459 checkin_proto::GservicesSetting* setting = response.add_setting();
460 setting->set_name(it->first);
461 setting->set_value(it->second);
463 response.set_settings_diff(false);
466 std::string response_string;
467 response.SerializeToString(&response_string);
469 net::TestURLFetcher* fetcher = url_fetcher_factory_.GetFetcherByID(0);
470 ASSERT_TRUE(fetcher);
471 fetcher->set_response_code(net::HTTP_OK);
472 fetcher->SetResponseString(response_string);
473 fetcher->delegate()->OnURLFetchComplete(fetcher);
474 // Give a chance for GCMStoreImpl::Backend to finish persisting data.
475 PumpLoopUntilIdle();
478 void GCMClientImplTest::CompleteRegistration(
479 const std::string& registration_id) {
480 std::string response(kRegistrationResponsePrefix);
481 response.append(registration_id);
482 net::TestURLFetcher* fetcher = url_fetcher_factory_.GetFetcherByID(0);
483 ASSERT_TRUE(fetcher);
484 fetcher->set_response_code(net::HTTP_OK);
485 fetcher->SetResponseString(response);
486 fetcher->delegate()->OnURLFetchComplete(fetcher);
487 // Give a chance for GCMStoreImpl::Backend to finish persisting data.
488 PumpLoopUntilIdle();
491 void GCMClientImplTest::CompleteUnregistration(
492 const std::string& app_id) {
493 std::string response(kUnregistrationResponsePrefix);
494 response.append(app_id);
495 net::TestURLFetcher* fetcher = url_fetcher_factory_.GetFetcherByID(0);
496 ASSERT_TRUE(fetcher);
497 fetcher->set_response_code(net::HTTP_OK);
498 fetcher->SetResponseString(response);
499 fetcher->delegate()->OnURLFetchComplete(fetcher);
500 // Give a chance for GCMStoreImpl::Backend to finish persisting data.
501 PumpLoopUntilIdle();
504 void GCMClientImplTest::VerifyPendingRequestFetcherDeleted() {
505 net::TestURLFetcher* fetcher = url_fetcher_factory_.GetFetcherByID(0);
506 EXPECT_FALSE(fetcher);
509 bool GCMClientImplTest::ExistsRegistration(const std::string& app_id) const {
510 return ExistsGCMRegistrationInMap(gcm_client_->registrations_, app_id);
513 void GCMClientImplTest::AddRegistration(
514 const std::string& app_id,
515 const std::vector<std::string>& sender_ids,
516 const std::string& registration_id) {
517 linked_ptr<GCMRegistrationInfo> registration(new GCMRegistrationInfo);
518 registration->app_id = app_id;
519 registration->sender_ids = sender_ids;
520 gcm_client_->registrations_[registration] = registration_id;
523 void GCMClientImplTest::InitializeGCMClient() {
524 clock()->Advance(base::TimeDelta::FromMilliseconds(1));
526 // Actual initialization.
527 GCMClient::ChromeBuildInfo chrome_build_info;
528 chrome_build_info.version = kChromeVersion;
529 gcm_client_->Initialize(
530 chrome_build_info,
531 gcm_store_path(),
532 task_runner_,
533 url_request_context_getter_,
534 make_scoped_ptr<Encryptor>(new FakeEncryptor),
535 this);
538 void GCMClientImplTest::StartGCMClient() {
539 // Start loading and check-in.
540 gcm_client_->Start(GCMClient::IMMEDIATE_START);
542 PumpLoopUntilIdle();
545 void GCMClientImplTest::Register(const std::string& app_id,
546 const std::vector<std::string>& senders) {
547 scoped_ptr<GCMRegistrationInfo> gcm_info(new GCMRegistrationInfo);
548 gcm_info->app_id = app_id;
549 gcm_info->sender_ids = senders;
550 gcm_client()->Register(make_linked_ptr<RegistrationInfo>(gcm_info.release()));
553 void GCMClientImplTest::Unregister(const std::string& app_id) {
554 scoped_ptr<GCMRegistrationInfo> gcm_info(new GCMRegistrationInfo);
555 gcm_info->app_id = app_id;
556 gcm_client()->Unregister(
557 make_linked_ptr<RegistrationInfo>(gcm_info.release()));
560 void GCMClientImplTest::ReceiveMessageFromMCS(const MCSMessage& message) {
561 gcm_client_->recorder_.RecordConnectionInitiated(std::string());
562 gcm_client_->recorder_.RecordConnectionSuccess();
563 gcm_client_->OnMessageReceivedFromMCS(message);
566 void GCMClientImplTest::ReceiveOnMessageSentToMCS(
567 const std::string& app_id,
568 const std::string& message_id,
569 const MCSClient::MessageSendStatus status) {
570 gcm_client_->OnMessageSentToMCS(0LL, app_id, message_id, status);
573 void GCMClientImplTest::OnGCMReady(
574 const std::vector<AccountMapping>& account_mappings,
575 const base::Time& last_token_fetch_time) {
576 last_event_ = LOADING_COMPLETED;
577 last_account_mappings_ = account_mappings;
578 last_token_fetch_time_ = last_token_fetch_time;
581 void GCMClientImplTest::OnMessageReceived(const std::string& registration_id,
582 const 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 std::string() /* raw_data */));
823 EXPECT_TRUE(message.IsValid());
824 ReceiveMessageFromMCS(message);
826 expected_data.erase(expected_data.find("message_type"));
827 EXPECT_EQ(MESSAGE_RECEIVED, last_event());
828 EXPECT_EQ(kAppId, last_app_id());
829 EXPECT_EQ(expected_data.size(), last_message().data.size());
830 EXPECT_EQ(expected_data, last_message().data);
831 EXPECT_EQ(kSender, last_message().sender_id);
833 reset_last_event();
835 // Message for kSender2 will be received.
836 MCSMessage message2(BuildDownstreamMessage(kSender2, kAppId, expected_data,
837 std::string() /* raw_data */));
838 EXPECT_TRUE(message2.IsValid());
839 ReceiveMessageFromMCS(message2);
841 EXPECT_EQ(MESSAGE_RECEIVED, last_event());
842 EXPECT_EQ(kAppId, last_app_id());
843 EXPECT_EQ(expected_data.size(), last_message().data.size());
844 EXPECT_EQ(expected_data, last_message().data);
845 EXPECT_EQ(kSender2, last_message().sender_id);
847 reset_last_event();
849 // Message from kSender3 will be dropped.
850 MCSMessage message3(BuildDownstreamMessage(kSender3, kAppId, expected_data,
851 std::string() /* raw_data */));
852 EXPECT_TRUE(message3.IsValid());
853 ReceiveMessageFromMCS(message3);
855 EXPECT_NE(MESSAGE_RECEIVED, last_event());
856 EXPECT_NE(kAppId, last_app_id());
859 TEST_F(GCMClientImplTest, DispatchDownstreamMessageRawData) {
860 std::vector<std::string> senders(1, kSender);
861 AddRegistration(kAppId, senders, "reg_id");
863 std::map<std::string, std::string> expected_data;
865 MCSMessage message(BuildDownstreamMessage(kSender, kAppId, expected_data,
866 kRawData));
867 EXPECT_TRUE(message.IsValid());
868 ReceiveMessageFromMCS(message);
870 EXPECT_EQ(MESSAGE_RECEIVED, last_event());
871 EXPECT_EQ(kAppId, last_app_id());
872 EXPECT_EQ(expected_data.size(), last_message().data.size());
873 EXPECT_EQ(kSender, last_message().sender_id);
874 EXPECT_EQ(kRawData, last_message().raw_data);
877 TEST_F(GCMClientImplTest, DispatchDownstreamMessageSendError) {
878 std::map<std::string, std::string> expected_data;
879 expected_data["message_type"] = "send_error";
880 expected_data["google.message_id"] = "007";
881 expected_data["error_details"] = "some details";
882 MCSMessage message(BuildDownstreamMessage(kSender, kAppId, expected_data,
883 std::string() /* raw_data */));
884 EXPECT_TRUE(message.IsValid());
885 ReceiveMessageFromMCS(message);
887 EXPECT_EQ(MESSAGE_SEND_ERROR, last_event());
888 EXPECT_EQ(kAppId, last_app_id());
889 EXPECT_EQ("007", last_error_details().message_id);
890 EXPECT_EQ(1UL, last_error_details().additional_data.size());
891 MessageData::const_iterator iter =
892 last_error_details().additional_data.find("error_details");
893 EXPECT_TRUE(iter != last_error_details().additional_data.end());
894 EXPECT_EQ("some details", iter->second);
897 TEST_F(GCMClientImplTest, DispatchDownstreamMessgaesDeleted) {
898 std::map<std::string, std::string> expected_data;
899 expected_data["message_type"] = "deleted_messages";
900 MCSMessage message(BuildDownstreamMessage(kSender, kAppId, expected_data,
901 std::string() /* raw_data */));
902 EXPECT_TRUE(message.IsValid());
903 ReceiveMessageFromMCS(message);
905 EXPECT_EQ(MESSAGES_DELETED, last_event());
906 EXPECT_EQ(kAppId, last_app_id());
909 TEST_F(GCMClientImplTest, SendMessage) {
910 OutgoingMessage message;
911 message.id = "007";
912 message.time_to_live = 500;
913 message.data["key"] = "value";
914 gcm_client()->Send(kAppId, kSender, message);
916 EXPECT_EQ(kDataMessageStanzaTag, mcs_client()->last_message_tag());
917 EXPECT_EQ(kAppId, mcs_client()->last_data_message_stanza().category());
918 EXPECT_EQ(kSender, mcs_client()->last_data_message_stanza().to());
919 EXPECT_EQ(500, mcs_client()->last_data_message_stanza().ttl());
920 EXPECT_EQ(CurrentTime(), mcs_client()->last_data_message_stanza().sent());
921 EXPECT_EQ("007", mcs_client()->last_data_message_stanza().id());
922 EXPECT_EQ("gcm@chrome.com", mcs_client()->last_data_message_stanza().from());
923 EXPECT_EQ(kSender, mcs_client()->last_data_message_stanza().to());
924 EXPECT_EQ("key", mcs_client()->last_data_message_stanza().app_data(0).key());
925 EXPECT_EQ("value",
926 mcs_client()->last_data_message_stanza().app_data(0).value());
929 TEST_F(GCMClientImplTest, SendMessageAcknowledged) {
930 ReceiveOnMessageSentToMCS(kAppId, "007", MCSClient::SENT);
931 EXPECT_EQ(MESSAGE_SEND_ACK, last_event());
932 EXPECT_EQ(kAppId, last_app_id());
933 EXPECT_EQ("007", last_message_id());
936 class GCMClientImplCheckinTest : public GCMClientImplTest {
937 public:
938 GCMClientImplCheckinTest();
939 ~GCMClientImplCheckinTest() override;
941 void SetUp() override;
944 GCMClientImplCheckinTest::GCMClientImplCheckinTest() {
947 GCMClientImplCheckinTest::~GCMClientImplCheckinTest() {
950 void GCMClientImplCheckinTest::SetUp() {
951 testing::Test::SetUp();
952 // Creating unique temp directory that will be used by GCMStore shared between
953 // GCM Client and G-services settings.
954 ASSERT_TRUE(CreateUniqueTempDir());
955 // Time will be advancing one hour every time it is checked.
956 BuildGCMClient(base::TimeDelta::FromSeconds(kSettingsCheckinInterval));
957 InitializeGCMClient();
958 StartGCMClient();
961 TEST_F(GCMClientImplCheckinTest, GServicesSettingsAfterInitialCheckin) {
962 std::map<std::string, std::string> settings;
963 settings["checkin_interval"] = base::Int64ToString(kSettingsCheckinInterval);
964 settings["checkin_url"] = "http://alternative.url/checkin";
965 settings["gcm_hostname"] = "alternative.gcm.host";
966 settings["gcm_secure_port"] = "7777";
967 settings["gcm_registration_url"] = "http://alternative.url/registration";
968 CompleteCheckin(kDeviceAndroidId,
969 kDeviceSecurityToken,
970 GServicesSettings::CalculateDigest(settings),
971 settings);
972 EXPECT_EQ(base::TimeDelta::FromSeconds(kSettingsCheckinInterval),
973 gservices_settings().GetCheckinInterval());
974 EXPECT_EQ(GURL("http://alternative.url/checkin"),
975 gservices_settings().GetCheckinURL());
976 EXPECT_EQ(GURL("http://alternative.url/registration"),
977 gservices_settings().GetRegistrationURL());
978 EXPECT_EQ(GURL("https://alternative.gcm.host:7777"),
979 gservices_settings().GetMCSMainEndpoint());
980 EXPECT_EQ(GURL("https://alternative.gcm.host:443"),
981 gservices_settings().GetMCSFallbackEndpoint());
984 // This test only checks that periodic checkin happens.
985 TEST_F(GCMClientImplCheckinTest, PeriodicCheckin) {
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 EXPECT_EQ(2, clock()->call_count());
999 PumpLoopUntilIdle();
1000 CompleteCheckin(kDeviceAndroidId,
1001 kDeviceSecurityToken,
1002 GServicesSettings::CalculateDigest(settings),
1003 settings);
1006 TEST_F(GCMClientImplCheckinTest, LoadGSettingsFromStore) {
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),
1016 settings);
1018 BuildGCMClient(base::TimeDelta());
1019 InitializeGCMClient();
1020 StartGCMClient();
1022 EXPECT_EQ(base::TimeDelta::FromSeconds(kSettingsCheckinInterval),
1023 gservices_settings().GetCheckinInterval());
1024 EXPECT_EQ(GURL("http://alternative.url/checkin"),
1025 gservices_settings().GetCheckinURL());
1026 EXPECT_EQ(GURL("http://alternative.url/registration"),
1027 gservices_settings().GetRegistrationURL());
1028 EXPECT_EQ(GURL("https://alternative.gcm.host:7777"),
1029 gservices_settings().GetMCSMainEndpoint());
1030 EXPECT_EQ(GURL("https://alternative.gcm.host:443"),
1031 gservices_settings().GetMCSFallbackEndpoint());
1034 // This test only checks that periodic checkin happens.
1035 TEST_F(GCMClientImplCheckinTest, CheckinWithAccounts) {
1036 std::map<std::string, std::string> settings;
1037 settings["checkin_interval"] = base::IntToString(kSettingsCheckinInterval);
1038 settings["checkin_url"] = "http://alternative.url/checkin";
1039 settings["gcm_hostname"] = "alternative.gcm.host";
1040 settings["gcm_secure_port"] = "7777";
1041 settings["gcm_registration_url"] = "http://alternative.url/registration";
1042 CompleteCheckin(kDeviceAndroidId,
1043 kDeviceSecurityToken,
1044 GServicesSettings::CalculateDigest(settings),
1045 settings);
1047 std::vector<GCMClient::AccountTokenInfo> account_tokens;
1048 account_tokens.push_back(MakeAccountToken("test_user1@gmail.com", "token1"));
1049 account_tokens.push_back(MakeAccountToken("test_user2@gmail.com", "token2"));
1050 gcm_client()->SetAccountTokens(account_tokens);
1052 EXPECT_TRUE(device_checkin_info().last_checkin_accounts.empty());
1053 EXPECT_TRUE(device_checkin_info().accounts_set);
1054 EXPECT_EQ(MakeEmailToTokenMap(account_tokens),
1055 device_checkin_info().account_tokens);
1057 PumpLoopUntilIdle();
1058 CompleteCheckin(kDeviceAndroidId,
1059 kDeviceSecurityToken,
1060 GServicesSettings::CalculateDigest(settings),
1061 settings);
1063 std::set<std::string> accounts;
1064 accounts.insert("test_user1@gmail.com");
1065 accounts.insert("test_user2@gmail.com");
1066 EXPECT_EQ(accounts, device_checkin_info().last_checkin_accounts);
1067 EXPECT_TRUE(device_checkin_info().accounts_set);
1068 EXPECT_EQ(MakeEmailToTokenMap(account_tokens),
1069 device_checkin_info().account_tokens);
1072 // This test only checks that periodic checkin happens.
1073 TEST_F(GCMClientImplCheckinTest, CheckinWhenAccountRemoved) {
1074 std::map<std::string, std::string> settings;
1075 settings["checkin_interval"] = base::IntToString(kSettingsCheckinInterval);
1076 settings["checkin_url"] = "http://alternative.url/checkin";
1077 settings["gcm_hostname"] = "alternative.gcm.host";
1078 settings["gcm_secure_port"] = "7777";
1079 settings["gcm_registration_url"] = "http://alternative.url/registration";
1080 CompleteCheckin(kDeviceAndroidId,
1081 kDeviceSecurityToken,
1082 GServicesSettings::CalculateDigest(settings),
1083 settings);
1085 std::vector<GCMClient::AccountTokenInfo> account_tokens;
1086 account_tokens.push_back(MakeAccountToken("test_user1@gmail.com", "token1"));
1087 account_tokens.push_back(MakeAccountToken("test_user2@gmail.com", "token2"));
1088 gcm_client()->SetAccountTokens(account_tokens);
1089 PumpLoopUntilIdle();
1090 CompleteCheckin(kDeviceAndroidId,
1091 kDeviceSecurityToken,
1092 GServicesSettings::CalculateDigest(settings),
1093 settings);
1095 EXPECT_EQ(2UL, device_checkin_info().last_checkin_accounts.size());
1096 EXPECT_TRUE(device_checkin_info().accounts_set);
1097 EXPECT_EQ(MakeEmailToTokenMap(account_tokens),
1098 device_checkin_info().account_tokens);
1100 account_tokens.erase(account_tokens.begin() + 1);
1101 gcm_client()->SetAccountTokens(account_tokens);
1103 PumpLoopUntilIdle();
1104 CompleteCheckin(kDeviceAndroidId,
1105 kDeviceSecurityToken,
1106 GServicesSettings::CalculateDigest(settings),
1107 settings);
1109 std::set<std::string> accounts;
1110 accounts.insert("test_user1@gmail.com");
1111 EXPECT_EQ(accounts, device_checkin_info().last_checkin_accounts);
1112 EXPECT_TRUE(device_checkin_info().accounts_set);
1113 EXPECT_EQ(MakeEmailToTokenMap(account_tokens),
1114 device_checkin_info().account_tokens);
1117 // This test only checks that periodic checkin happens.
1118 TEST_F(GCMClientImplCheckinTest, CheckinWhenAccountReplaced) {
1119 std::map<std::string, std::string> settings;
1120 settings["checkin_interval"] = base::IntToString(kSettingsCheckinInterval);
1121 settings["checkin_url"] = "http://alternative.url/checkin";
1122 settings["gcm_hostname"] = "alternative.gcm.host";
1123 settings["gcm_secure_port"] = "7777";
1124 settings["gcm_registration_url"] = "http://alternative.url/registration";
1125 CompleteCheckin(kDeviceAndroidId,
1126 kDeviceSecurityToken,
1127 GServicesSettings::CalculateDigest(settings),
1128 settings);
1130 std::vector<GCMClient::AccountTokenInfo> account_tokens;
1131 account_tokens.push_back(MakeAccountToken("test_user1@gmail.com", "token1"));
1132 gcm_client()->SetAccountTokens(account_tokens);
1134 PumpLoopUntilIdle();
1135 CompleteCheckin(kDeviceAndroidId,
1136 kDeviceSecurityToken,
1137 GServicesSettings::CalculateDigest(settings),
1138 settings);
1140 std::set<std::string> accounts;
1141 accounts.insert("test_user1@gmail.com");
1142 EXPECT_EQ(accounts, device_checkin_info().last_checkin_accounts);
1144 // This should trigger another checkin, because the list of accounts is
1145 // different.
1146 account_tokens.clear();
1147 account_tokens.push_back(MakeAccountToken("test_user2@gmail.com", "token2"));
1148 gcm_client()->SetAccountTokens(account_tokens);
1150 PumpLoopUntilIdle();
1151 CompleteCheckin(kDeviceAndroidId,
1152 kDeviceSecurityToken,
1153 GServicesSettings::CalculateDigest(settings),
1154 settings);
1156 accounts.clear();
1157 accounts.insert("test_user2@gmail.com");
1158 EXPECT_EQ(accounts, device_checkin_info().last_checkin_accounts);
1159 EXPECT_TRUE(device_checkin_info().accounts_set);
1160 EXPECT_EQ(MakeEmailToTokenMap(account_tokens),
1161 device_checkin_info().account_tokens);
1164 class GCMClientImplStartAndStopTest : public GCMClientImplTest {
1165 public:
1166 GCMClientImplStartAndStopTest();
1167 ~GCMClientImplStartAndStopTest() override;
1169 void SetUp() override;
1171 void DefaultCompleteCheckin();
1174 GCMClientImplStartAndStopTest::GCMClientImplStartAndStopTest() {
1177 GCMClientImplStartAndStopTest::~GCMClientImplStartAndStopTest() {
1180 void GCMClientImplStartAndStopTest::SetUp() {
1181 testing::Test::SetUp();
1182 ASSERT_TRUE(CreateUniqueTempDir());
1183 BuildGCMClient(base::TimeDelta());
1184 InitializeGCMClient();
1187 void GCMClientImplStartAndStopTest::DefaultCompleteCheckin() {
1188 SetUpUrlFetcherFactory();
1189 CompleteCheckin(kDeviceAndroidId,
1190 kDeviceSecurityToken,
1191 std::string(),
1192 std::map<std::string, std::string>());
1193 PumpLoopUntilIdle();
1196 TEST_F(GCMClientImplStartAndStopTest, StartStopAndRestart) {
1197 // GCMClientImpl should be in INITIALIZED state at first.
1198 EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
1200 // Delay start the GCM.
1201 gcm_client()->Start(GCMClient::DELAYED_START);
1202 PumpLoopUntilIdle();
1203 EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
1205 // Stop the GCM.
1206 gcm_client()->Stop();
1207 PumpLoopUntilIdle();
1208 EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
1210 // Restart the GCM without delay.
1211 gcm_client()->Start(GCMClient::IMMEDIATE_START);
1212 PumpLoopUntilIdle();
1213 EXPECT_EQ(GCMClientImpl::INITIAL_DEVICE_CHECKIN, gcm_client_state());
1216 TEST_F(GCMClientImplStartAndStopTest, DelayedStartAndStopImmediately) {
1217 // GCMClientImpl should be in INITIALIZED state at first.
1218 EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
1220 // Delay start the GCM and then stop it immediately.
1221 gcm_client()->Start(GCMClient::DELAYED_START);
1222 gcm_client()->Stop();
1223 PumpLoopUntilIdle();
1224 EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
1227 TEST_F(GCMClientImplStartAndStopTest, ImmediateStartAndStopImmediately) {
1228 // GCMClientImpl should be in INITIALIZED state at first.
1229 EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
1231 // Start the GCM and then stop it immediately.
1232 gcm_client()->Start(GCMClient::IMMEDIATE_START);
1233 gcm_client()->Stop();
1234 PumpLoopUntilIdle();
1235 EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
1238 TEST_F(GCMClientImplStartAndStopTest, DelayedStartStopAndRestart) {
1239 // GCMClientImpl should be in INITIALIZED state at first.
1240 EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
1242 // Delay start the GCM and then stop and restart it immediately.
1243 gcm_client()->Start(GCMClient::DELAYED_START);
1244 gcm_client()->Stop();
1245 gcm_client()->Start(GCMClient::DELAYED_START);
1246 PumpLoopUntilIdle();
1247 EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
1250 TEST_F(GCMClientImplStartAndStopTest, ImmediateStartStopAndRestart) {
1251 // GCMClientImpl should be in INITIALIZED state at first.
1252 EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
1254 // Start the GCM and then stop and restart it immediately.
1255 gcm_client()->Start(GCMClient::IMMEDIATE_START);
1256 gcm_client()->Stop();
1257 gcm_client()->Start(GCMClient::IMMEDIATE_START);
1258 PumpLoopUntilIdle();
1259 EXPECT_EQ(GCMClientImpl::INITIAL_DEVICE_CHECKIN, gcm_client_state());
1262 TEST_F(GCMClientImplStartAndStopTest, ImmediateStartAndThenImmediateStart) {
1263 // GCMClientImpl should be in INITIALIZED state at first.
1264 EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
1266 // Start the GCM immediately and complete the checkin.
1267 gcm_client()->Start(GCMClient::IMMEDIATE_START);
1268 PumpLoopUntilIdle();
1269 EXPECT_EQ(GCMClientImpl::INITIAL_DEVICE_CHECKIN, gcm_client_state());
1270 DefaultCompleteCheckin();
1271 EXPECT_EQ(GCMClientImpl::READY, gcm_client_state());
1273 // Stop the GCM.
1274 gcm_client()->Stop();
1275 PumpLoopUntilIdle();
1276 EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
1278 // Start the GCM immediately. GCMClientImpl should be in READY state.
1279 BuildGCMClient(base::TimeDelta());
1280 InitializeGCMClient();
1281 gcm_client()->Start(GCMClient::IMMEDIATE_START);
1282 PumpLoopUntilIdle();
1283 EXPECT_EQ(GCMClientImpl::READY, gcm_client_state());
1286 TEST_F(GCMClientImplStartAndStopTest, ImmediateStartAndThenDelayStart) {
1287 // GCMClientImpl should be in INITIALIZED state at first.
1288 EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
1290 // Start the GCM immediately and complete the checkin.
1291 gcm_client()->Start(GCMClient::IMMEDIATE_START);
1292 PumpLoopUntilIdle();
1293 EXPECT_EQ(GCMClientImpl::INITIAL_DEVICE_CHECKIN, gcm_client_state());
1294 DefaultCompleteCheckin();
1295 EXPECT_EQ(GCMClientImpl::READY, gcm_client_state());
1297 // Stop the GCM.
1298 gcm_client()->Stop();
1299 PumpLoopUntilIdle();
1300 EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
1302 // Delay start the GCM. GCMClientImpl should be in LOADED state.
1303 BuildGCMClient(base::TimeDelta());
1304 InitializeGCMClient();
1305 gcm_client()->Start(GCMClient::DELAYED_START);
1306 PumpLoopUntilIdle();
1307 EXPECT_EQ(GCMClientImpl::LOADED, gcm_client_state());
1310 TEST_F(GCMClientImplStartAndStopTest, DelayedStartRace) {
1311 // GCMClientImpl should be in INITIALIZED state at first.
1312 EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
1314 // Delay start the GCM, then start it immediately while it's still loading.
1315 gcm_client()->Start(GCMClient::DELAYED_START);
1316 gcm_client()->Start(GCMClient::IMMEDIATE_START);
1317 PumpLoopUntilIdle();
1318 EXPECT_EQ(GCMClientImpl::INITIAL_DEVICE_CHECKIN, gcm_client_state());
1319 DefaultCompleteCheckin();
1320 EXPECT_EQ(GCMClientImpl::READY, gcm_client_state());
1323 TEST_F(GCMClientImplStartAndStopTest, DelayedStart) {
1324 // GCMClientImpl should be in INITIALIZED state at first.
1325 EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
1327 // Delay start the GCM. The store will not be loaded and GCMClientImpl should
1328 // still be in INITIALIZED state.
1329 gcm_client()->Start(GCMClient::DELAYED_START);
1330 PumpLoopUntilIdle();
1331 EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
1333 // Start the GCM immediately and complete the checkin.
1334 gcm_client()->Start(GCMClient::IMMEDIATE_START);
1335 PumpLoopUntilIdle();
1336 EXPECT_EQ(GCMClientImpl::INITIAL_DEVICE_CHECKIN, gcm_client_state());
1337 DefaultCompleteCheckin();
1338 EXPECT_EQ(GCMClientImpl::READY, gcm_client_state());
1340 // Registration.
1341 std::vector<std::string> senders;
1342 senders.push_back("sender");
1343 Register(kAppId, senders);
1344 CompleteRegistration("reg_id");
1345 EXPECT_EQ(GCMClientImpl::READY, gcm_client_state());
1347 // Stop the GCM.
1348 gcm_client()->Stop();
1349 PumpLoopUntilIdle();
1350 EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
1352 // Delay start the GCM. GCM is indeed started without delay because the
1353 // registration record has been found.
1354 BuildGCMClient(base::TimeDelta());
1355 InitializeGCMClient();
1356 gcm_client()->Start(GCMClient::DELAYED_START);
1357 PumpLoopUntilIdle();
1358 EXPECT_EQ(GCMClientImpl::READY, gcm_client_state());
1361 // Test for known account mappings and last token fetching time being passed
1362 // to OnGCMReady.
1363 TEST_F(GCMClientImplStartAndStopTest, OnGCMReadyAccountsAndTokenFetchingTime) {
1364 // Start the GCM and wait until it is ready.
1365 gcm_client()->Start(GCMClient::IMMEDIATE_START);
1366 PumpLoopUntilIdle();
1367 DefaultCompleteCheckin();
1369 base::Time expected_time = base::Time::Now();
1370 gcm_client()->SetLastTokenFetchTime(expected_time);
1371 AccountMapping expected_mapping;
1372 expected_mapping.account_id = "accId";
1373 expected_mapping.email = "email@gmail.com";
1374 expected_mapping.status = AccountMapping::MAPPED;
1375 expected_mapping.status_change_timestamp = expected_time;
1376 gcm_client()->UpdateAccountMapping(expected_mapping);
1377 PumpLoopUntilIdle();
1379 // Stop the GCM.
1380 gcm_client()->Stop();
1381 PumpLoopUntilIdle();
1383 // Restart the GCM.
1384 gcm_client()->Start(GCMClient::IMMEDIATE_START);
1385 PumpLoopUntilIdle();
1387 EXPECT_EQ(LOADING_COMPLETED, last_event());
1388 EXPECT_EQ(expected_time, last_token_fetch_time());
1389 ASSERT_EQ(1UL, last_account_mappings().size());
1390 const AccountMapping& actual_mapping = last_account_mappings()[0];
1391 EXPECT_EQ(expected_mapping.account_id, actual_mapping.account_id);
1392 EXPECT_EQ(expected_mapping.email, actual_mapping.email);
1393 EXPECT_EQ(expected_mapping.status, actual_mapping.status);
1394 EXPECT_EQ(expected_mapping.status_change_timestamp,
1395 actual_mapping.status_change_timestamp);
1399 class GCMClientInstanceIDTest : public GCMClientImplTest {
1400 public:
1401 GCMClientInstanceIDTest();
1402 ~GCMClientInstanceIDTest() override;
1404 void AddInstanceID(const std::string& app_id,
1405 const std::string& instance_id);
1406 void RemoveInstanceID(const std::string& app_id);
1407 void GetToken(const std::string& app_id,
1408 const std::string& authorized_entity,
1409 const std::string& scope);
1410 void DeleteToken(const std::string& app_id,
1411 const std::string& authorized_entity,
1412 const std::string& scope);
1413 void CompleteDeleteToken();
1414 bool ExistsToken(const std::string& app_id,
1415 const std::string& authorized_entity,
1416 const std::string& scope) const;
1419 GCMClientInstanceIDTest::GCMClientInstanceIDTest() {
1422 GCMClientInstanceIDTest::~GCMClientInstanceIDTest() {
1425 void GCMClientInstanceIDTest::AddInstanceID(const std::string& app_id,
1426 const std::string& instance_id) {
1427 gcm_client()->AddInstanceIDData(app_id, instance_id, "123");
1430 void GCMClientInstanceIDTest::RemoveInstanceID(const std::string& app_id) {
1431 gcm_client()->RemoveInstanceIDData(app_id);
1434 void GCMClientInstanceIDTest::GetToken(const std::string& app_id,
1435 const std::string& authorized_entity,
1436 const std::string& scope) {
1437 scoped_ptr<InstanceIDTokenInfo> instance_id_info(new InstanceIDTokenInfo);
1438 instance_id_info->app_id = app_id;
1439 instance_id_info->authorized_entity = authorized_entity;
1440 instance_id_info->scope = scope;
1441 gcm_client()->Register(
1442 make_linked_ptr<RegistrationInfo>(instance_id_info.release()));
1445 void GCMClientInstanceIDTest::DeleteToken(const std::string& app_id,
1446 const std::string& authorized_entity,
1447 const std::string& scope) {
1448 scoped_ptr<InstanceIDTokenInfo> instance_id_info(new InstanceIDTokenInfo);
1449 instance_id_info->app_id = app_id;
1450 instance_id_info->authorized_entity = authorized_entity;
1451 instance_id_info->scope = scope;
1452 gcm_client()->Unregister(
1453 make_linked_ptr<RegistrationInfo>(instance_id_info.release()));
1456 void GCMClientInstanceIDTest::CompleteDeleteToken() {
1457 std::string response(kDeleteTokenResponse);
1458 net::TestURLFetcher* fetcher = url_fetcher_factory()->GetFetcherByID(0);
1459 ASSERT_TRUE(fetcher);
1460 fetcher->set_response_code(net::HTTP_OK);
1461 fetcher->SetResponseString(response);
1462 fetcher->delegate()->OnURLFetchComplete(fetcher);
1463 // Give a chance for GCMStoreImpl::Backend to finish persisting data.
1464 PumpLoopUntilIdle();
1467 bool GCMClientInstanceIDTest::ExistsToken(const std::string& app_id,
1468 const std::string& authorized_entity,
1469 const std::string& scope) const {
1470 scoped_ptr<InstanceIDTokenInfo> instance_id_info(new InstanceIDTokenInfo);
1471 instance_id_info->app_id = app_id;
1472 instance_id_info->authorized_entity = authorized_entity;
1473 instance_id_info->scope = scope;
1474 return gcm_client()->registrations_.count(
1475 make_linked_ptr<RegistrationInfo>(instance_id_info.release())) > 0;
1478 TEST_F(GCMClientInstanceIDTest, GetToken) {
1479 AddInstanceID(kAppId, kInstanceID);
1481 // Get a token.
1482 EXPECT_FALSE(ExistsToken(kAppId, kSender, kScope));
1483 GetToken(kAppId, kSender, kScope);
1484 CompleteRegistration("token1");
1486 EXPECT_EQ(REGISTRATION_COMPLETED, last_event());
1487 EXPECT_EQ(kAppId, last_app_id());
1488 EXPECT_EQ("token1", last_registration_id());
1489 EXPECT_EQ(GCMClient::SUCCESS, last_result());
1490 EXPECT_TRUE(ExistsToken(kAppId, kSender, kScope));
1492 // Get another token.
1493 EXPECT_FALSE(ExistsToken(kAppId, kSender2, kScope));
1494 GetToken(kAppId, kSender2, kScope);
1495 CompleteRegistration("token2");
1497 EXPECT_EQ(REGISTRATION_COMPLETED, last_event());
1498 EXPECT_EQ(kAppId, last_app_id());
1499 EXPECT_EQ("token2", last_registration_id());
1500 EXPECT_EQ(GCMClient::SUCCESS, last_result());
1501 EXPECT_TRUE(ExistsToken(kAppId, kSender2, kScope));
1502 // The 1st token still exists.
1503 EXPECT_TRUE(ExistsToken(kAppId, kSender, kScope));
1506 TEST_F(GCMClientInstanceIDTest, DeleteInvalidToken) {
1507 AddInstanceID(kAppId, kInstanceID);
1509 // Delete an invalid token.
1510 DeleteToken(kAppId, "Foo@#$", kScope);
1511 PumpLoopUntilIdle();
1513 EXPECT_EQ(UNREGISTRATION_COMPLETED, last_event());
1514 EXPECT_EQ(kAppId, last_app_id());
1515 EXPECT_EQ(GCMClient::INVALID_PARAMETER, last_result());
1517 reset_last_event();
1519 // Delete a non-existing token.
1520 DeleteToken(kAppId, kSender, kScope);
1521 PumpLoopUntilIdle();
1523 EXPECT_EQ(UNREGISTRATION_COMPLETED, last_event());
1524 EXPECT_EQ(kAppId, last_app_id());
1525 EXPECT_EQ(GCMClient::INVALID_PARAMETER, last_result());
1528 TEST_F(GCMClientInstanceIDTest, DeleteSingleToken) {
1529 AddInstanceID(kAppId, kInstanceID);
1531 // Get a token.
1532 EXPECT_FALSE(ExistsToken(kAppId, kSender, kScope));
1533 GetToken(kAppId, kSender, kScope);
1534 CompleteRegistration("token1");
1536 EXPECT_EQ(REGISTRATION_COMPLETED, last_event());
1537 EXPECT_EQ(kAppId, last_app_id());
1538 EXPECT_EQ("token1", last_registration_id());
1539 EXPECT_EQ(GCMClient::SUCCESS, last_result());
1540 EXPECT_TRUE(ExistsToken(kAppId, kSender, kScope));
1542 reset_last_event();
1544 // Get another token.
1545 EXPECT_FALSE(ExistsToken(kAppId, kSender2, kScope));
1546 GetToken(kAppId, kSender2, kScope);
1547 CompleteRegistration("token2");
1549 EXPECT_EQ(REGISTRATION_COMPLETED, last_event());
1550 EXPECT_EQ(kAppId, last_app_id());
1551 EXPECT_EQ("token2", last_registration_id());
1552 EXPECT_EQ(GCMClient::SUCCESS, last_result());
1553 EXPECT_TRUE(ExistsToken(kAppId, kSender2, kScope));
1554 // The 1st token still exists.
1555 EXPECT_TRUE(ExistsToken(kAppId, kSender, kScope));
1557 reset_last_event();
1559 // Delete the 2nd token.
1560 DeleteToken(kAppId, kSender2, kScope);
1561 CompleteDeleteToken();
1563 EXPECT_EQ(UNREGISTRATION_COMPLETED, last_event());
1564 EXPECT_EQ(kAppId, last_app_id());
1565 EXPECT_EQ(GCMClient::SUCCESS, last_result());
1566 // The 2nd token is gone while the 1st token still exists.
1567 EXPECT_TRUE(ExistsToken(kAppId, kSender, kScope));
1568 EXPECT_FALSE(ExistsToken(kAppId, kSender2, kScope));
1570 reset_last_event();
1572 // Delete the 1st token.
1573 DeleteToken(kAppId, kSender, kScope);
1574 CompleteDeleteToken();
1576 EXPECT_EQ(UNREGISTRATION_COMPLETED, last_event());
1577 EXPECT_EQ(kAppId, last_app_id());
1578 EXPECT_EQ(GCMClient::SUCCESS, last_result());
1579 // Both tokens are gone now.
1580 EXPECT_FALSE(ExistsToken(kAppId, kSender, kScope));
1581 EXPECT_FALSE(ExistsToken(kAppId, kSender, kScope));
1583 reset_last_event();
1585 // Trying to delete the token again will get an error.
1586 DeleteToken(kAppId, kSender, kScope);
1587 PumpLoopUntilIdle();
1589 EXPECT_EQ(UNREGISTRATION_COMPLETED, last_event());
1590 EXPECT_EQ(kAppId, last_app_id());
1591 EXPECT_EQ(GCMClient::INVALID_PARAMETER, last_result());
1594 TEST_F(GCMClientInstanceIDTest, DeleteAllTokens) {
1595 AddInstanceID(kAppId, kInstanceID);
1597 // Get a token.
1598 EXPECT_FALSE(ExistsToken(kAppId, kSender, kScope));
1599 GetToken(kAppId, kSender, kScope);
1600 CompleteRegistration("token1");
1602 EXPECT_EQ(REGISTRATION_COMPLETED, last_event());
1603 EXPECT_EQ(kAppId, last_app_id());
1604 EXPECT_EQ("token1", last_registration_id());
1605 EXPECT_EQ(GCMClient::SUCCESS, last_result());
1606 EXPECT_TRUE(ExistsToken(kAppId, kSender, kScope));
1608 reset_last_event();
1610 // Get another token.
1611 EXPECT_FALSE(ExistsToken(kAppId, kSender2, kScope));
1612 GetToken(kAppId, kSender2, kScope);
1613 CompleteRegistration("token2");
1615 EXPECT_EQ(REGISTRATION_COMPLETED, last_event());
1616 EXPECT_EQ(kAppId, last_app_id());
1617 EXPECT_EQ("token2", last_registration_id());
1618 EXPECT_EQ(GCMClient::SUCCESS, last_result());
1619 EXPECT_TRUE(ExistsToken(kAppId, kSender2, kScope));
1620 // The 1st token still exists.
1621 EXPECT_TRUE(ExistsToken(kAppId, kSender, kScope));
1623 reset_last_event();
1625 // Delete all tokens.
1626 DeleteToken(kAppId, "*", "*");
1627 CompleteDeleteToken();
1629 EXPECT_EQ(UNREGISTRATION_COMPLETED, last_event());
1630 EXPECT_EQ(kAppId, last_app_id());
1631 EXPECT_EQ(GCMClient::SUCCESS, last_result());
1632 // All tokens are gone now.
1633 EXPECT_FALSE(ExistsToken(kAppId, kSender, kScope));
1634 EXPECT_FALSE(ExistsToken(kAppId, kSender, kScope));
1637 TEST_F(GCMClientInstanceIDTest, DeleteAllTokensBeforeGetAnyToken) {
1638 AddInstanceID(kAppId, kInstanceID);
1640 // Delete all tokens without getting a token first.
1641 DeleteToken(kAppId, "*", "*");
1642 // No need to call CompleteDeleteToken since unregistration request should
1643 // not be triggered.
1644 PumpLoopUntilIdle();
1646 EXPECT_EQ(UNREGISTRATION_COMPLETED, last_event());
1647 EXPECT_EQ(kAppId, last_app_id());
1648 EXPECT_EQ(GCMClient::SUCCESS, last_result());
1651 } // namespace gcm