Fix AfterTyping experiment for Android.
[chromium-blink-merge.git] / components / gcm_driver / gcm_client_impl_unittest.cc
blob673f45d326a92c0efb9fefa8ad2b66f0c7a1a946
1 // Copyright 2014 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "components/gcm_driver/gcm_client_impl.h"
7 #include "base/command_line.h"
8 #include "base/files/file_path.h"
9 #include "base/files/file_util.h"
10 #include "base/files/scoped_temp_dir.h"
11 #include "base/memory/scoped_ptr.h"
12 #include "base/strings/string_number_conversions.h"
13 #include "base/test/test_mock_time_task_runner.h"
14 #include "base/thread_task_runner_handle.h"
15 #include "base/time/clock.h"
16 #include "base/timer/timer.h"
17 #include "google_apis/gcm/base/fake_encryptor.h"
18 #include "google_apis/gcm/base/mcs_message.h"
19 #include "google_apis/gcm/base/mcs_util.h"
20 #include "google_apis/gcm/engine/fake_connection_factory.h"
21 #include "google_apis/gcm/engine/fake_connection_handler.h"
22 #include "google_apis/gcm/engine/gservices_settings.h"
23 #include "google_apis/gcm/monitoring/gcm_stats_recorder.h"
24 #include "google_apis/gcm/protocol/android_checkin.pb.h"
25 #include "google_apis/gcm/protocol/checkin.pb.h"
26 #include "google_apis/gcm/protocol/mcs.pb.h"
27 #include "net/url_request/test_url_fetcher_factory.h"
28 #include "net/url_request/url_fetcher_delegate.h"
29 #include "net/url_request/url_request_test_util.h"
30 #include "testing/gtest/include/gtest/gtest.h"
32 namespace gcm {
34 namespace {
36 enum LastEvent {
37 NONE,
38 LOADING_COMPLETED,
39 REGISTRATION_COMPLETED,
40 UNREGISTRATION_COMPLETED,
41 MESSAGE_SEND_ERROR,
42 MESSAGE_SEND_ACK,
43 MESSAGE_RECEIVED,
44 MESSAGES_DELETED,
47 const char kChromeVersion[] = "45.0.0.1";
48 const uint64 kDeviceAndroidId = 54321;
49 const uint64 kDeviceSecurityToken = 12345;
50 const uint64 kDeviceAndroidId2 = 11111;
51 const uint64 kDeviceSecurityToken2 = 2222;
52 const int64 kSettingsCheckinInterval = 16 * 60 * 60;
53 const char kAppId[] = "app_id";
54 const char kSender[] = "project_id";
55 const char kSender2[] = "project_id2";
56 const char kSender3[] = "project_id3";
57 const char kRegistrationResponsePrefix[] = "token=";
58 const char kUnregistrationResponsePrefix[] = "deleted=";
60 const char kInstanceID[] = "iid_1";
61 const char kScope[] = "GCM";
62 const char kDeleteTokenResponse[] = "token=foo";
64 // Helper for building arbitrary data messages.
65 MCSMessage BuildDownstreamMessage(
66 const std::string& project_id,
67 const std::string& app_id,
68 const std::map<std::string, std::string>& data) {
69 mcs_proto::DataMessageStanza data_message;
70 data_message.set_from(project_id);
71 data_message.set_category(app_id);
72 for (std::map<std::string, std::string>::const_iterator iter = data.begin();
73 iter != data.end();
74 ++iter) {
75 mcs_proto::AppData* app_data = data_message.add_app_data();
76 app_data->set_key(iter->first);
77 app_data->set_value(iter->second);
79 return MCSMessage(kDataMessageStanzaTag, data_message);
82 GCMClient::AccountTokenInfo MakeAccountToken(const std::string& email,
83 const std::string& token) {
84 GCMClient::AccountTokenInfo account_token;
85 account_token.email = email;
86 account_token.access_token = token;
87 return account_token;
90 std::map<std::string, std::string> MakeEmailToTokenMap(
91 const std::vector<GCMClient::AccountTokenInfo>& account_tokens) {
92 std::map<std::string, std::string> email_token_map;
93 for (std::vector<GCMClient::AccountTokenInfo>::const_iterator iter =
94 account_tokens.begin(); iter != account_tokens.end(); ++iter) {
95 email_token_map[iter->email] = iter->access_token;
97 return email_token_map;
100 class FakeMCSClient : public MCSClient {
101 public:
102 FakeMCSClient(base::Clock* clock,
103 ConnectionFactory* connection_factory,
104 GCMStore* gcm_store,
105 GCMStatsRecorder* recorder);
106 ~FakeMCSClient() override;
107 void Login(uint64 android_id, uint64 security_token) override;
108 void SendMessage(const MCSMessage& message) override;
110 uint64 last_android_id() const { return last_android_id_; }
111 uint64 last_security_token() const { return last_security_token_; }
112 uint8 last_message_tag() const { return last_message_tag_; }
113 const mcs_proto::DataMessageStanza& last_data_message_stanza() const {
114 return last_data_message_stanza_;
117 private:
118 uint64 last_android_id_;
119 uint64 last_security_token_;
120 uint8 last_message_tag_;
121 mcs_proto::DataMessageStanza last_data_message_stanza_;
124 FakeMCSClient::FakeMCSClient(base::Clock* clock,
125 ConnectionFactory* connection_factory,
126 GCMStore* gcm_store,
127 GCMStatsRecorder* recorder)
128 : MCSClient("", clock, connection_factory, gcm_store, recorder),
129 last_android_id_(0u),
130 last_security_token_(0u),
131 last_message_tag_(kNumProtoTypes) {
134 FakeMCSClient::~FakeMCSClient() {
137 void FakeMCSClient::Login(uint64 android_id, uint64 security_token) {
138 last_android_id_ = android_id;
139 last_security_token_ = security_token;
142 void FakeMCSClient::SendMessage(const MCSMessage& message) {
143 last_message_tag_ = message.tag();
144 if (last_message_tag_ == kDataMessageStanzaTag) {
145 last_data_message_stanza_.CopyFrom(
146 reinterpret_cast<const mcs_proto::DataMessageStanza&>(
147 message.GetProtobuf()));
151 class AutoAdvancingTestClock : public base::Clock {
152 public:
153 explicit AutoAdvancingTestClock(base::TimeDelta auto_increment_time_delta);
154 ~AutoAdvancingTestClock() override;
156 base::Time Now() override;
157 void Advance(TimeDelta delta);
158 int call_count() const { return call_count_; }
160 private:
161 int call_count_;
162 base::TimeDelta auto_increment_time_delta_;
163 base::Time now_;
165 DISALLOW_COPY_AND_ASSIGN(AutoAdvancingTestClock);
168 AutoAdvancingTestClock::AutoAdvancingTestClock(
169 base::TimeDelta auto_increment_time_delta)
170 : call_count_(0), auto_increment_time_delta_(auto_increment_time_delta) {
173 AutoAdvancingTestClock::~AutoAdvancingTestClock() {
176 base::Time AutoAdvancingTestClock::Now() {
177 call_count_++;
178 now_ += auto_increment_time_delta_;
179 return now_;
182 void AutoAdvancingTestClock::Advance(base::TimeDelta delta) {
183 now_ += delta;
186 class FakeGCMInternalsBuilder : public GCMInternalsBuilder {
187 public:
188 FakeGCMInternalsBuilder(base::TimeDelta clock_step);
189 ~FakeGCMInternalsBuilder() override;
191 scoped_ptr<base::Clock> BuildClock() override;
192 scoped_ptr<MCSClient> BuildMCSClient(const std::string& version,
193 base::Clock* clock,
194 ConnectionFactory* connection_factory,
195 GCMStore* gcm_store,
196 GCMStatsRecorder* recorder) override;
197 scoped_ptr<ConnectionFactory> BuildConnectionFactory(
198 const std::vector<GURL>& endpoints,
199 const net::BackoffEntry::Policy& backoff_policy,
200 const scoped_refptr<net::HttpNetworkSession>& gcm_network_session,
201 const scoped_refptr<net::HttpNetworkSession>& http_network_session,
202 net::NetLog* net_log,
203 GCMStatsRecorder* recorder) override;
205 private:
206 base::TimeDelta clock_step_;
209 FakeGCMInternalsBuilder::FakeGCMInternalsBuilder(base::TimeDelta clock_step)
210 : clock_step_(clock_step) {
213 FakeGCMInternalsBuilder::~FakeGCMInternalsBuilder() {}
215 scoped_ptr<base::Clock> FakeGCMInternalsBuilder::BuildClock() {
216 return make_scoped_ptr<base::Clock>(new AutoAdvancingTestClock(clock_step_));
219 scoped_ptr<MCSClient> FakeGCMInternalsBuilder::BuildMCSClient(
220 const std::string& version,
221 base::Clock* clock,
222 ConnectionFactory* connection_factory,
223 GCMStore* gcm_store,
224 GCMStatsRecorder* recorder) {
225 return make_scoped_ptr<MCSClient>(new FakeMCSClient(clock,
226 connection_factory,
227 gcm_store,
228 recorder));
231 scoped_ptr<ConnectionFactory> FakeGCMInternalsBuilder::BuildConnectionFactory(
232 const std::vector<GURL>& endpoints,
233 const net::BackoffEntry::Policy& backoff_policy,
234 const scoped_refptr<net::HttpNetworkSession>& gcm_network_session,
235 const scoped_refptr<net::HttpNetworkSession>& http_network_session,
236 net::NetLog* net_log,
237 GCMStatsRecorder* recorder) {
238 return make_scoped_ptr<ConnectionFactory>(new FakeConnectionFactory());
241 } // namespace
243 class GCMClientImplTest : public testing::Test,
244 public GCMClient::Delegate {
245 public:
246 GCMClientImplTest();
247 ~GCMClientImplTest() override;
249 void SetUp() override;
251 void SetUpUrlFetcherFactory();
253 void BuildGCMClient(base::TimeDelta clock_step);
254 void InitializeGCMClient();
255 void StartGCMClient();
256 void Register(const std::string& app_id,
257 const std::vector<std::string>& senders);
258 void Unregister(const std::string& app_id);
259 void ReceiveMessageFromMCS(const MCSMessage& message);
260 void ReceiveOnMessageSentToMCS(
261 const std::string& app_id,
262 const std::string& message_id,
263 const MCSClient::MessageSendStatus status);
264 void CompleteCheckin(uint64 android_id,
265 uint64 security_token,
266 const std::string& digest,
267 const std::map<std::string, std::string>& settings);
268 void CompleteRegistration(const std::string& registration_id);
269 void CompleteUnregistration(const std::string& app_id);
270 void VerifyPendingRequestFetcherDeleted();
272 bool ExistsRegistration(const std::string& app_id) const;
273 void AddRegistration(const std::string& app_id,
274 const std::vector<std::string>& sender_ids,
275 const std::string& registration_id);
277 // GCMClient::Delegate overrides (for verification).
278 void OnRegisterFinished(const linked_ptr<RegistrationInfo>& registration_info,
279 const std::string& registration_id,
280 GCMClient::Result result) override;
281 void OnUnregisterFinished(
282 const linked_ptr<RegistrationInfo>& registration_info,
283 GCMClient::Result result) override;
284 void OnSendFinished(const std::string& app_id,
285 const std::string& message_id,
286 GCMClient::Result result) override {}
287 void OnMessageReceived(const std::string& registration_id,
288 const GCMClient::IncomingMessage& message) override;
289 void OnMessagesDeleted(const std::string& app_id) override;
290 void OnMessageSendError(
291 const std::string& app_id,
292 const gcm::GCMClient::SendErrorDetails& send_error_details) override;
293 void OnSendAcknowledged(const std::string& app_id,
294 const std::string& message_id) override;
295 void OnGCMReady(const std::vector<AccountMapping>& account_mappings,
296 const base::Time& last_token_fetch_time) override;
297 void OnActivityRecorded() override {}
298 void OnConnected(const net::IPEndPoint& ip_endpoint) override {}
299 void OnDisconnected() override {}
301 GCMClientImpl* gcm_client() const { return gcm_client_.get(); }
302 GCMClientImpl::State gcm_client_state() const {
303 return gcm_client_->state_;
305 FakeMCSClient* mcs_client() const {
306 return reinterpret_cast<FakeMCSClient*>(gcm_client_->mcs_client_.get());
308 ConnectionFactory* connection_factory() const {
309 return gcm_client_->connection_factory_.get();
312 const GCMClientImpl::CheckinInfo& device_checkin_info() const {
313 return gcm_client_->device_checkin_info_;
316 void reset_last_event() {
317 last_event_ = NONE;
318 last_app_id_.clear();
319 last_registration_id_.clear();
320 last_message_id_.clear();
321 last_result_ = GCMClient::UNKNOWN_ERROR;
322 last_account_mappings_.clear();
323 last_token_fetch_time_ = base::Time();
326 LastEvent last_event() const { return last_event_; }
327 const std::string& last_app_id() const { return last_app_id_; }
328 const std::string& last_registration_id() const {
329 return last_registration_id_;
331 const std::string& last_message_id() const { return last_message_id_; }
332 GCMClient::Result last_result() const { return last_result_; }
333 const GCMClient::IncomingMessage& last_message() const {
334 return last_message_;
336 const GCMClient::SendErrorDetails& last_error_details() const {
337 return last_error_details_;
339 const base::Time& last_token_fetch_time() const {
340 return last_token_fetch_time_;
342 const std::vector<AccountMapping>& last_account_mappings() {
343 return last_account_mappings_;
346 const GServicesSettings& gservices_settings() const {
347 return gcm_client_->gservices_settings_;
350 const base::FilePath& temp_directory_path() const {
351 return temp_directory_.path();
354 base::FilePath gcm_store_path() const {
355 // Pass an non-existent directory as store path to match the exact
356 // behavior in the production code. Currently GCMStoreImpl checks if
357 // the directory exist or not to determine the store existence.
358 return temp_directory_.path().Append(FILE_PATH_LITERAL("GCM Store"));
361 int64 CurrentTime();
363 // Tooling.
364 void PumpLoopUntilIdle();
365 bool CreateUniqueTempDir();
366 AutoAdvancingTestClock* clock() const {
367 return reinterpret_cast<AutoAdvancingTestClock*>(gcm_client_->clock_.get());
369 net::TestURLFetcherFactory* url_fetcher_factory() {
370 return &url_fetcher_factory_;
372 base::TestMockTimeTaskRunner* task_runner() {
373 return task_runner_.get();
376 private:
377 // Variables used for verification.
378 LastEvent last_event_;
379 std::string last_app_id_;
380 std::string last_registration_id_;
381 std::string last_message_id_;
382 GCMClient::Result last_result_;
383 GCMClient::IncomingMessage last_message_;
384 GCMClient::SendErrorDetails last_error_details_;
385 base::Time last_token_fetch_time_;
386 std::vector<AccountMapping> last_account_mappings_;
388 scoped_ptr<GCMClientImpl> gcm_client_;
390 net::TestURLFetcherFactory url_fetcher_factory_;
392 scoped_refptr<base::TestMockTimeTaskRunner> task_runner_;
393 base::ThreadTaskRunnerHandle task_runner_handle_;
395 // Injected to GCM client:
396 base::ScopedTempDir temp_directory_;
397 scoped_refptr<net::TestURLRequestContextGetter> url_request_context_getter_;
400 GCMClientImplTest::GCMClientImplTest()
401 : last_event_(NONE),
402 last_result_(GCMClient::UNKNOWN_ERROR),
403 task_runner_(new base::TestMockTimeTaskRunner),
404 task_runner_handle_(task_runner_),
405 url_request_context_getter_(
406 new net::TestURLRequestContextGetter(task_runner_)) {
409 GCMClientImplTest::~GCMClientImplTest() {}
411 void GCMClientImplTest::SetUp() {
412 testing::Test::SetUp();
413 ASSERT_TRUE(CreateUniqueTempDir());
414 BuildGCMClient(base::TimeDelta());
415 InitializeGCMClient();
416 StartGCMClient();
417 SetUpUrlFetcherFactory();
418 CompleteCheckin(kDeviceAndroidId,
419 kDeviceSecurityToken,
420 std::string(),
421 std::map<std::string, std::string>());
424 void GCMClientImplTest::SetUpUrlFetcherFactory() {
425 url_fetcher_factory_.set_remove_fetcher_on_delete(true);
428 void GCMClientImplTest::PumpLoopUntilIdle() {
429 task_runner_->RunUntilIdle();
432 bool GCMClientImplTest::CreateUniqueTempDir() {
433 return temp_directory_.CreateUniqueTempDir();
436 void GCMClientImplTest::BuildGCMClient(base::TimeDelta clock_step) {
437 gcm_client_.reset(new GCMClientImpl(make_scoped_ptr<GCMInternalsBuilder>(
438 new FakeGCMInternalsBuilder(clock_step))));
441 void GCMClientImplTest::CompleteCheckin(
442 uint64 android_id,
443 uint64 security_token,
444 const std::string& digest,
445 const std::map<std::string, std::string>& settings) {
446 checkin_proto::AndroidCheckinResponse response;
447 response.set_stats_ok(true);
448 response.set_android_id(android_id);
449 response.set_security_token(security_token);
451 // For testing G-services settings.
452 if (!digest.empty()) {
453 response.set_digest(digest);
454 for (std::map<std::string, std::string>::const_iterator it =
455 settings.begin();
456 it != settings.end();
457 ++it) {
458 checkin_proto::GservicesSetting* setting = response.add_setting();
459 setting->set_name(it->first);
460 setting->set_value(it->second);
462 response.set_settings_diff(false);
465 std::string response_string;
466 response.SerializeToString(&response_string);
468 net::TestURLFetcher* fetcher = url_fetcher_factory_.GetFetcherByID(0);
469 ASSERT_TRUE(fetcher);
470 fetcher->set_response_code(net::HTTP_OK);
471 fetcher->SetResponseString(response_string);
472 fetcher->delegate()->OnURLFetchComplete(fetcher);
475 void GCMClientImplTest::CompleteRegistration(
476 const std::string& registration_id) {
477 std::string response(kRegistrationResponsePrefix);
478 response.append(registration_id);
479 net::TestURLFetcher* fetcher = url_fetcher_factory_.GetFetcherByID(0);
480 ASSERT_TRUE(fetcher);
481 fetcher->set_response_code(net::HTTP_OK);
482 fetcher->SetResponseString(response);
483 fetcher->delegate()->OnURLFetchComplete(fetcher);
486 void GCMClientImplTest::CompleteUnregistration(
487 const std::string& app_id) {
488 std::string response(kUnregistrationResponsePrefix);
489 response.append(app_id);
490 net::TestURLFetcher* fetcher = url_fetcher_factory_.GetFetcherByID(0);
491 ASSERT_TRUE(fetcher);
492 fetcher->set_response_code(net::HTTP_OK);
493 fetcher->SetResponseString(response);
494 fetcher->delegate()->OnURLFetchComplete(fetcher);
497 void GCMClientImplTest::VerifyPendingRequestFetcherDeleted() {
498 net::TestURLFetcher* fetcher = url_fetcher_factory_.GetFetcherByID(0);
499 EXPECT_FALSE(fetcher);
502 bool GCMClientImplTest::ExistsRegistration(const std::string& app_id) const {
503 return ExistsGCMRegistrationInMap(gcm_client_->registrations_, app_id);
506 void GCMClientImplTest::AddRegistration(
507 const std::string& app_id,
508 const std::vector<std::string>& sender_ids,
509 const std::string& registration_id) {
510 linked_ptr<GCMRegistrationInfo> registration(new GCMRegistrationInfo);
511 registration->app_id = app_id;
512 registration->sender_ids = sender_ids;
513 gcm_client_->registrations_[registration] = registration_id;
516 void GCMClientImplTest::InitializeGCMClient() {
517 clock()->Advance(base::TimeDelta::FromMilliseconds(1));
519 // Actual initialization.
520 GCMClient::ChromeBuildInfo chrome_build_info;
521 chrome_build_info.version = kChromeVersion;
522 gcm_client_->Initialize(
523 chrome_build_info,
524 gcm_store_path(),
525 task_runner_,
526 url_request_context_getter_,
527 make_scoped_ptr<Encryptor>(new FakeEncryptor),
528 this);
531 void GCMClientImplTest::StartGCMClient() {
532 // Start loading and check-in.
533 gcm_client_->Start(GCMClient::IMMEDIATE_START);
535 PumpLoopUntilIdle();
538 void GCMClientImplTest::Register(const std::string& app_id,
539 const std::vector<std::string>& senders) {
540 scoped_ptr<GCMRegistrationInfo> gcm_info(new GCMRegistrationInfo);
541 gcm_info->app_id = app_id;
542 gcm_info->sender_ids = senders;
543 gcm_client()->Register(make_linked_ptr<RegistrationInfo>(gcm_info.release()));
546 void GCMClientImplTest::Unregister(const std::string& app_id) {
547 scoped_ptr<GCMRegistrationInfo> gcm_info(new GCMRegistrationInfo);
548 gcm_info->app_id = app_id;
549 gcm_client()->Unregister(
550 make_linked_ptr<RegistrationInfo>(gcm_info.release()));
553 void GCMClientImplTest::ReceiveMessageFromMCS(const MCSMessage& message) {
554 gcm_client_->recorder_.RecordConnectionInitiated(std::string());
555 gcm_client_->recorder_.RecordConnectionSuccess();
556 gcm_client_->OnMessageReceivedFromMCS(message);
559 void GCMClientImplTest::ReceiveOnMessageSentToMCS(
560 const std::string& app_id,
561 const std::string& message_id,
562 const MCSClient::MessageSendStatus status) {
563 gcm_client_->OnMessageSentToMCS(0LL, app_id, message_id, status);
566 void GCMClientImplTest::OnGCMReady(
567 const std::vector<AccountMapping>& account_mappings,
568 const base::Time& last_token_fetch_time) {
569 last_event_ = LOADING_COMPLETED;
570 last_account_mappings_ = account_mappings;
571 last_token_fetch_time_ = last_token_fetch_time;
574 void GCMClientImplTest::OnMessageReceived(
575 const std::string& registration_id,
576 const GCMClient::IncomingMessage& message) {
577 last_event_ = MESSAGE_RECEIVED;
578 last_app_id_ = registration_id;
579 last_message_ = message;
582 void GCMClientImplTest::OnRegisterFinished(
583 const linked_ptr<RegistrationInfo>& registration_info,
584 const std::string& registration_id,
585 GCMClient::Result result) {
586 last_event_ = REGISTRATION_COMPLETED;
587 last_app_id_ = registration_info->app_id;
588 last_registration_id_ = registration_id;
589 last_result_ = result;
592 void GCMClientImplTest::OnUnregisterFinished(
593 const linked_ptr<RegistrationInfo>& registration_info,
594 GCMClient::Result result) {
595 last_event_ = UNREGISTRATION_COMPLETED;
596 last_app_id_ = registration_info->app_id;
597 last_result_ = result;
600 void GCMClientImplTest::OnMessagesDeleted(const std::string& app_id) {
601 last_event_ = MESSAGES_DELETED;
602 last_app_id_ = app_id;
605 void GCMClientImplTest::OnMessageSendError(
606 const std::string& app_id,
607 const gcm::GCMClient::SendErrorDetails& send_error_details) {
608 last_event_ = MESSAGE_SEND_ERROR;
609 last_app_id_ = app_id;
610 last_error_details_ = send_error_details;
613 void GCMClientImplTest::OnSendAcknowledged(const std::string& app_id,
614 const std::string& message_id) {
615 last_event_ = MESSAGE_SEND_ACK;
616 last_app_id_ = app_id;
617 last_message_id_ = message_id;
620 int64 GCMClientImplTest::CurrentTime() {
621 return clock()->Now().ToInternalValue() / base::Time::kMicrosecondsPerSecond;
624 TEST_F(GCMClientImplTest, LoadingCompleted) {
625 EXPECT_EQ(LOADING_COMPLETED, last_event());
626 EXPECT_EQ(kDeviceAndroidId, mcs_client()->last_android_id());
627 EXPECT_EQ(kDeviceSecurityToken, mcs_client()->last_security_token());
629 // Checking freshly loaded CheckinInfo.
630 EXPECT_EQ(kDeviceAndroidId, device_checkin_info().android_id);
631 EXPECT_EQ(kDeviceSecurityToken, device_checkin_info().secret);
632 EXPECT_TRUE(device_checkin_info().last_checkin_accounts.empty());
633 EXPECT_TRUE(device_checkin_info().accounts_set);
634 EXPECT_TRUE(device_checkin_info().account_tokens.empty());
637 TEST_F(GCMClientImplTest, LoadingBusted) {
638 // Close the GCM store.
639 gcm_client()->Stop();
640 PumpLoopUntilIdle();
642 // Mess up the store.
643 base::FilePath store_file_path =
644 gcm_store_path().Append(FILE_PATH_LITERAL("CURRENT"));
645 ASSERT_TRUE(base::AppendToFile(store_file_path, "A", 1));
647 // Restart GCM client. The store should be reset and the loading should
648 // complete successfully.
649 reset_last_event();
650 BuildGCMClient(base::TimeDelta());
651 InitializeGCMClient();
652 StartGCMClient();
653 CompleteCheckin(kDeviceAndroidId2,
654 kDeviceSecurityToken2,
655 std::string(),
656 std::map<std::string, std::string>());
658 EXPECT_EQ(LOADING_COMPLETED, last_event());
659 EXPECT_EQ(kDeviceAndroidId2, mcs_client()->last_android_id());
660 EXPECT_EQ(kDeviceSecurityToken2, mcs_client()->last_security_token());
663 TEST_F(GCMClientImplTest, DestroyStoreWhenNotNeeded) {
664 // Close the GCM store.
665 gcm_client()->Stop();
666 PumpLoopUntilIdle();
668 // Restart GCM client. The store is loaded successfully.
669 reset_last_event();
670 BuildGCMClient(base::TimeDelta());
671 InitializeGCMClient();
672 gcm_client()->Start(GCMClient::DELAYED_START);
673 PumpLoopUntilIdle();
675 EXPECT_EQ(GCMClientImpl::LOADED, gcm_client_state());
676 EXPECT_TRUE(device_checkin_info().android_id);
677 EXPECT_TRUE(device_checkin_info().secret);
679 // Fast forward the clock to trigger the store destroying logic.
680 task_runner()->FastForwardBy(base::TimeDelta::FromMilliseconds(300000));
681 PumpLoopUntilIdle();
683 EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
684 EXPECT_FALSE(device_checkin_info().android_id);
685 EXPECT_FALSE(device_checkin_info().secret);
688 TEST_F(GCMClientImplTest, RegisterApp) {
689 EXPECT_FALSE(ExistsRegistration(kAppId));
691 std::vector<std::string> senders;
692 senders.push_back("sender");
693 Register(kAppId, senders);
694 CompleteRegistration("reg_id");
696 EXPECT_EQ(REGISTRATION_COMPLETED, last_event());
697 EXPECT_EQ(kAppId, last_app_id());
698 EXPECT_EQ("reg_id", last_registration_id());
699 EXPECT_EQ(GCMClient::SUCCESS, last_result());
700 EXPECT_TRUE(ExistsRegistration(kAppId));
703 TEST_F(GCMClientImplTest, DISABLED_RegisterAppFromCache) {
704 EXPECT_FALSE(ExistsRegistration(kAppId));
706 std::vector<std::string> senders;
707 senders.push_back("sender");
708 Register(kAppId, senders);
709 CompleteRegistration("reg_id");
710 EXPECT_TRUE(ExistsRegistration(kAppId));
712 EXPECT_EQ(kAppId, last_app_id());
713 EXPECT_EQ("reg_id", last_registration_id());
714 EXPECT_EQ(GCMClient::SUCCESS, last_result());
715 EXPECT_EQ(REGISTRATION_COMPLETED, last_event());
717 // Recreate GCMClient in order to load from the persistent store.
718 BuildGCMClient(base::TimeDelta());
719 InitializeGCMClient();
720 StartGCMClient();
722 EXPECT_TRUE(ExistsRegistration(kAppId));
725 TEST_F(GCMClientImplTest, UnregisterApp) {
726 EXPECT_FALSE(ExistsRegistration(kAppId));
728 std::vector<std::string> senders;
729 senders.push_back("sender");
730 Register(kAppId, senders);
731 CompleteRegistration("reg_id");
732 EXPECT_TRUE(ExistsRegistration(kAppId));
734 Unregister(kAppId);
735 CompleteUnregistration(kAppId);
737 EXPECT_EQ(UNREGISTRATION_COMPLETED, last_event());
738 EXPECT_EQ(kAppId, last_app_id());
739 EXPECT_EQ(GCMClient::SUCCESS, last_result());
740 EXPECT_FALSE(ExistsRegistration(kAppId));
743 // Tests that stopping the GCMClient also deletes pending registration requests.
744 // This is tested by checking that url fetcher contained in the request was
745 // deleted.
746 TEST_F(GCMClientImplTest, DeletePendingRequestsWhenStopping) {
747 std::vector<std::string> senders;
748 senders.push_back("sender");
749 Register(kAppId, senders);
751 gcm_client()->Stop();
752 VerifyPendingRequestFetcherDeleted();
755 TEST_F(GCMClientImplTest, DispatchDownstreamMessage) {
756 // Register to receive messages from kSender and kSender2 only.
757 std::vector<std::string> senders;
758 senders.push_back(kSender);
759 senders.push_back(kSender2);
760 AddRegistration(kAppId, senders, "reg_id");
762 std::map<std::string, std::string> expected_data;
763 expected_data["message_type"] = "gcm";
764 expected_data["key"] = "value";
765 expected_data["key2"] = "value2";
767 // Message for kSender will be received.
768 MCSMessage message(BuildDownstreamMessage(kSender, kAppId, expected_data));
769 EXPECT_TRUE(message.IsValid());
770 ReceiveMessageFromMCS(message);
772 expected_data.erase(expected_data.find("message_type"));
773 EXPECT_EQ(MESSAGE_RECEIVED, last_event());
774 EXPECT_EQ(kAppId, last_app_id());
775 EXPECT_EQ(expected_data.size(), last_message().data.size());
776 EXPECT_EQ(expected_data, last_message().data);
777 EXPECT_EQ(kSender, last_message().sender_id);
779 reset_last_event();
781 // Message for kSender2 will be received.
782 MCSMessage message2(BuildDownstreamMessage(kSender2, kAppId, expected_data));
783 EXPECT_TRUE(message2.IsValid());
784 ReceiveMessageFromMCS(message2);
786 EXPECT_EQ(MESSAGE_RECEIVED, last_event());
787 EXPECT_EQ(kAppId, last_app_id());
788 EXPECT_EQ(expected_data.size(), last_message().data.size());
789 EXPECT_EQ(expected_data, last_message().data);
790 EXPECT_EQ(kSender2, last_message().sender_id);
792 reset_last_event();
794 // Message from kSender3 will be dropped.
795 MCSMessage message3(BuildDownstreamMessage(kSender3, kAppId, expected_data));
796 EXPECT_TRUE(message3.IsValid());
797 ReceiveMessageFromMCS(message3);
799 EXPECT_NE(MESSAGE_RECEIVED, last_event());
800 EXPECT_NE(kAppId, last_app_id());
803 TEST_F(GCMClientImplTest, DispatchDownstreamMessageSendError) {
804 std::map<std::string, std::string> expected_data;
805 expected_data["message_type"] = "send_error";
806 expected_data["google.message_id"] = "007";
807 expected_data["error_details"] = "some details";
808 MCSMessage message(BuildDownstreamMessage(
809 kSender, kAppId, expected_data));
810 EXPECT_TRUE(message.IsValid());
811 ReceiveMessageFromMCS(message);
813 EXPECT_EQ(MESSAGE_SEND_ERROR, last_event());
814 EXPECT_EQ(kAppId, last_app_id());
815 EXPECT_EQ("007", last_error_details().message_id);
816 EXPECT_EQ(1UL, last_error_details().additional_data.size());
817 GCMClient::MessageData::const_iterator iter =
818 last_error_details().additional_data.find("error_details");
819 EXPECT_TRUE(iter != last_error_details().additional_data.end());
820 EXPECT_EQ("some details", iter->second);
823 TEST_F(GCMClientImplTest, DispatchDownstreamMessgaesDeleted) {
824 std::map<std::string, std::string> expected_data;
825 expected_data["message_type"] = "deleted_messages";
826 MCSMessage message(BuildDownstreamMessage(
827 kSender, kAppId, expected_data));
828 EXPECT_TRUE(message.IsValid());
829 ReceiveMessageFromMCS(message);
831 EXPECT_EQ(MESSAGES_DELETED, last_event());
832 EXPECT_EQ(kAppId, last_app_id());
835 TEST_F(GCMClientImplTest, SendMessage) {
836 GCMClient::OutgoingMessage message;
837 message.id = "007";
838 message.time_to_live = 500;
839 message.data["key"] = "value";
840 gcm_client()->Send(kAppId, kSender, message);
842 EXPECT_EQ(kDataMessageStanzaTag, mcs_client()->last_message_tag());
843 EXPECT_EQ(kAppId, mcs_client()->last_data_message_stanza().category());
844 EXPECT_EQ(kSender, mcs_client()->last_data_message_stanza().to());
845 EXPECT_EQ(500, mcs_client()->last_data_message_stanza().ttl());
846 EXPECT_EQ(CurrentTime(), mcs_client()->last_data_message_stanza().sent());
847 EXPECT_EQ("007", mcs_client()->last_data_message_stanza().id());
848 EXPECT_EQ("gcm@chrome.com", mcs_client()->last_data_message_stanza().from());
849 EXPECT_EQ(kSender, mcs_client()->last_data_message_stanza().to());
850 EXPECT_EQ("key", mcs_client()->last_data_message_stanza().app_data(0).key());
851 EXPECT_EQ("value",
852 mcs_client()->last_data_message_stanza().app_data(0).value());
855 TEST_F(GCMClientImplTest, SendMessageAcknowledged) {
856 ReceiveOnMessageSentToMCS(kAppId, "007", MCSClient::SENT);
857 EXPECT_EQ(MESSAGE_SEND_ACK, last_event());
858 EXPECT_EQ(kAppId, last_app_id());
859 EXPECT_EQ("007", last_message_id());
862 class GCMClientImplCheckinTest : public GCMClientImplTest {
863 public:
864 GCMClientImplCheckinTest();
865 ~GCMClientImplCheckinTest() override;
867 void SetUp() override;
870 GCMClientImplCheckinTest::GCMClientImplCheckinTest() {
873 GCMClientImplCheckinTest::~GCMClientImplCheckinTest() {
876 void GCMClientImplCheckinTest::SetUp() {
877 testing::Test::SetUp();
878 // Creating unique temp directory that will be used by GCMStore shared between
879 // GCM Client and G-services settings.
880 ASSERT_TRUE(CreateUniqueTempDir());
881 // Time will be advancing one hour every time it is checked.
882 BuildGCMClient(base::TimeDelta::FromSeconds(kSettingsCheckinInterval));
883 InitializeGCMClient();
884 StartGCMClient();
887 TEST_F(GCMClientImplCheckinTest, GServicesSettingsAfterInitialCheckin) {
888 std::map<std::string, std::string> settings;
889 settings["checkin_interval"] = base::Int64ToString(kSettingsCheckinInterval);
890 settings["checkin_url"] = "http://alternative.url/checkin";
891 settings["gcm_hostname"] = "alternative.gcm.host";
892 settings["gcm_secure_port"] = "7777";
893 settings["gcm_registration_url"] = "http://alternative.url/registration";
894 CompleteCheckin(kDeviceAndroidId,
895 kDeviceSecurityToken,
896 GServicesSettings::CalculateDigest(settings),
897 settings);
898 EXPECT_EQ(base::TimeDelta::FromSeconds(kSettingsCheckinInterval),
899 gservices_settings().GetCheckinInterval());
900 EXPECT_EQ(GURL("http://alternative.url/checkin"),
901 gservices_settings().GetCheckinURL());
902 EXPECT_EQ(GURL("http://alternative.url/registration"),
903 gservices_settings().GetRegistrationURL());
904 EXPECT_EQ(GURL("https://alternative.gcm.host:7777"),
905 gservices_settings().GetMCSMainEndpoint());
906 EXPECT_EQ(GURL("https://alternative.gcm.host:443"),
907 gservices_settings().GetMCSFallbackEndpoint());
910 // This test only checks that periodic checkin happens.
911 TEST_F(GCMClientImplCheckinTest, PeriodicCheckin) {
912 std::map<std::string, std::string> settings;
913 settings["checkin_interval"] = base::IntToString(kSettingsCheckinInterval);
914 settings["checkin_url"] = "http://alternative.url/checkin";
915 settings["gcm_hostname"] = "alternative.gcm.host";
916 settings["gcm_secure_port"] = "7777";
917 settings["gcm_registration_url"] = "http://alternative.url/registration";
918 CompleteCheckin(kDeviceAndroidId,
919 kDeviceSecurityToken,
920 GServicesSettings::CalculateDigest(settings),
921 settings);
923 EXPECT_EQ(2, clock()->call_count());
925 PumpLoopUntilIdle();
926 CompleteCheckin(kDeviceAndroidId,
927 kDeviceSecurityToken,
928 GServicesSettings::CalculateDigest(settings),
929 settings);
932 TEST_F(GCMClientImplCheckinTest, LoadGSettingsFromStore) {
933 std::map<std::string, std::string> settings;
934 settings["checkin_interval"] = base::IntToString(kSettingsCheckinInterval);
935 settings["checkin_url"] = "http://alternative.url/checkin";
936 settings["gcm_hostname"] = "alternative.gcm.host";
937 settings["gcm_secure_port"] = "7777";
938 settings["gcm_registration_url"] = "http://alternative.url/registration";
939 CompleteCheckin(kDeviceAndroidId,
940 kDeviceSecurityToken,
941 GServicesSettings::CalculateDigest(settings),
942 settings);
944 BuildGCMClient(base::TimeDelta());
945 InitializeGCMClient();
946 StartGCMClient();
948 EXPECT_EQ(base::TimeDelta::FromSeconds(kSettingsCheckinInterval),
949 gservices_settings().GetCheckinInterval());
950 EXPECT_EQ(GURL("http://alternative.url/checkin"),
951 gservices_settings().GetCheckinURL());
952 EXPECT_EQ(GURL("http://alternative.url/registration"),
953 gservices_settings().GetRegistrationURL());
954 EXPECT_EQ(GURL("https://alternative.gcm.host:7777"),
955 gservices_settings().GetMCSMainEndpoint());
956 EXPECT_EQ(GURL("https://alternative.gcm.host:443"),
957 gservices_settings().GetMCSFallbackEndpoint());
960 // This test only checks that periodic checkin happens.
961 TEST_F(GCMClientImplCheckinTest, CheckinWithAccounts) {
962 std::map<std::string, std::string> settings;
963 settings["checkin_interval"] = base::IntToString(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);
973 std::vector<GCMClient::AccountTokenInfo> account_tokens;
974 account_tokens.push_back(MakeAccountToken("test_user1@gmail.com", "token1"));
975 account_tokens.push_back(MakeAccountToken("test_user2@gmail.com", "token2"));
976 gcm_client()->SetAccountTokens(account_tokens);
978 EXPECT_TRUE(device_checkin_info().last_checkin_accounts.empty());
979 EXPECT_TRUE(device_checkin_info().accounts_set);
980 EXPECT_EQ(MakeEmailToTokenMap(account_tokens),
981 device_checkin_info().account_tokens);
983 PumpLoopUntilIdle();
984 CompleteCheckin(kDeviceAndroidId,
985 kDeviceSecurityToken,
986 GServicesSettings::CalculateDigest(settings),
987 settings);
989 std::set<std::string> accounts;
990 accounts.insert("test_user1@gmail.com");
991 accounts.insert("test_user2@gmail.com");
992 EXPECT_EQ(accounts, device_checkin_info().last_checkin_accounts);
993 EXPECT_TRUE(device_checkin_info().accounts_set);
994 EXPECT_EQ(MakeEmailToTokenMap(account_tokens),
995 device_checkin_info().account_tokens);
998 // This test only checks that periodic checkin happens.
999 TEST_F(GCMClientImplCheckinTest, CheckinWhenAccountRemoved) {
1000 std::map<std::string, std::string> settings;
1001 settings["checkin_interval"] = base::IntToString(kSettingsCheckinInterval);
1002 settings["checkin_url"] = "http://alternative.url/checkin";
1003 settings["gcm_hostname"] = "alternative.gcm.host";
1004 settings["gcm_secure_port"] = "7777";
1005 settings["gcm_registration_url"] = "http://alternative.url/registration";
1006 CompleteCheckin(kDeviceAndroidId,
1007 kDeviceSecurityToken,
1008 GServicesSettings::CalculateDigest(settings),
1009 settings);
1011 std::vector<GCMClient::AccountTokenInfo> account_tokens;
1012 account_tokens.push_back(MakeAccountToken("test_user1@gmail.com", "token1"));
1013 account_tokens.push_back(MakeAccountToken("test_user2@gmail.com", "token2"));
1014 gcm_client()->SetAccountTokens(account_tokens);
1015 PumpLoopUntilIdle();
1016 CompleteCheckin(kDeviceAndroidId,
1017 kDeviceSecurityToken,
1018 GServicesSettings::CalculateDigest(settings),
1019 settings);
1021 EXPECT_EQ(2UL, device_checkin_info().last_checkin_accounts.size());
1022 EXPECT_TRUE(device_checkin_info().accounts_set);
1023 EXPECT_EQ(MakeEmailToTokenMap(account_tokens),
1024 device_checkin_info().account_tokens);
1026 account_tokens.erase(account_tokens.begin() + 1);
1027 gcm_client()->SetAccountTokens(account_tokens);
1029 PumpLoopUntilIdle();
1030 CompleteCheckin(kDeviceAndroidId,
1031 kDeviceSecurityToken,
1032 GServicesSettings::CalculateDigest(settings),
1033 settings);
1035 std::set<std::string> accounts;
1036 accounts.insert("test_user1@gmail.com");
1037 EXPECT_EQ(accounts, device_checkin_info().last_checkin_accounts);
1038 EXPECT_TRUE(device_checkin_info().accounts_set);
1039 EXPECT_EQ(MakeEmailToTokenMap(account_tokens),
1040 device_checkin_info().account_tokens);
1043 // This test only checks that periodic checkin happens.
1044 TEST_F(GCMClientImplCheckinTest, CheckinWhenAccountReplaced) {
1045 std::map<std::string, std::string> settings;
1046 settings["checkin_interval"] = base::IntToString(kSettingsCheckinInterval);
1047 settings["checkin_url"] = "http://alternative.url/checkin";
1048 settings["gcm_hostname"] = "alternative.gcm.host";
1049 settings["gcm_secure_port"] = "7777";
1050 settings["gcm_registration_url"] = "http://alternative.url/registration";
1051 CompleteCheckin(kDeviceAndroidId,
1052 kDeviceSecurityToken,
1053 GServicesSettings::CalculateDigest(settings),
1054 settings);
1056 std::vector<GCMClient::AccountTokenInfo> account_tokens;
1057 account_tokens.push_back(MakeAccountToken("test_user1@gmail.com", "token1"));
1058 gcm_client()->SetAccountTokens(account_tokens);
1060 PumpLoopUntilIdle();
1061 CompleteCheckin(kDeviceAndroidId,
1062 kDeviceSecurityToken,
1063 GServicesSettings::CalculateDigest(settings),
1064 settings);
1066 std::set<std::string> accounts;
1067 accounts.insert("test_user1@gmail.com");
1068 EXPECT_EQ(accounts, device_checkin_info().last_checkin_accounts);
1070 // This should trigger another checkin, because the list of accounts is
1071 // different.
1072 account_tokens.clear();
1073 account_tokens.push_back(MakeAccountToken("test_user2@gmail.com", "token2"));
1074 gcm_client()->SetAccountTokens(account_tokens);
1076 PumpLoopUntilIdle();
1077 CompleteCheckin(kDeviceAndroidId,
1078 kDeviceSecurityToken,
1079 GServicesSettings::CalculateDigest(settings),
1080 settings);
1082 accounts.clear();
1083 accounts.insert("test_user2@gmail.com");
1084 EXPECT_EQ(accounts, device_checkin_info().last_checkin_accounts);
1085 EXPECT_TRUE(device_checkin_info().accounts_set);
1086 EXPECT_EQ(MakeEmailToTokenMap(account_tokens),
1087 device_checkin_info().account_tokens);
1090 class GCMClientImplStartAndStopTest : public GCMClientImplTest {
1091 public:
1092 GCMClientImplStartAndStopTest();
1093 ~GCMClientImplStartAndStopTest() override;
1095 void SetUp() override;
1097 void DefaultCompleteCheckin();
1100 GCMClientImplStartAndStopTest::GCMClientImplStartAndStopTest() {
1103 GCMClientImplStartAndStopTest::~GCMClientImplStartAndStopTest() {
1106 void GCMClientImplStartAndStopTest::SetUp() {
1107 testing::Test::SetUp();
1108 ASSERT_TRUE(CreateUniqueTempDir());
1109 BuildGCMClient(base::TimeDelta());
1110 InitializeGCMClient();
1113 void GCMClientImplStartAndStopTest::DefaultCompleteCheckin() {
1114 SetUpUrlFetcherFactory();
1115 CompleteCheckin(kDeviceAndroidId,
1116 kDeviceSecurityToken,
1117 std::string(),
1118 std::map<std::string, std::string>());
1119 PumpLoopUntilIdle();
1122 TEST_F(GCMClientImplStartAndStopTest, StartStopAndRestart) {
1123 // GCMClientImpl should be in INITIALIZED state at first.
1124 EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
1126 // Delay start the GCM.
1127 gcm_client()->Start(GCMClient::DELAYED_START);
1128 PumpLoopUntilIdle();
1129 EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
1131 // Stop the GCM.
1132 gcm_client()->Stop();
1133 PumpLoopUntilIdle();
1134 EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
1136 // Restart the GCM without delay.
1137 gcm_client()->Start(GCMClient::IMMEDIATE_START);
1138 PumpLoopUntilIdle();
1139 EXPECT_EQ(GCMClientImpl::INITIAL_DEVICE_CHECKIN, gcm_client_state());
1142 TEST_F(GCMClientImplStartAndStopTest, DelayedStartAndStopImmediately) {
1143 // GCMClientImpl should be in INITIALIZED state at first.
1144 EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
1146 // Delay start the GCM and then stop it immediately.
1147 gcm_client()->Start(GCMClient::DELAYED_START);
1148 gcm_client()->Stop();
1149 PumpLoopUntilIdle();
1150 EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
1153 TEST_F(GCMClientImplStartAndStopTest, ImmediateStartAndStopImmediately) {
1154 // GCMClientImpl should be in INITIALIZED state at first.
1155 EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
1157 // Start the GCM and then stop it immediately.
1158 gcm_client()->Start(GCMClient::IMMEDIATE_START);
1159 gcm_client()->Stop();
1160 PumpLoopUntilIdle();
1161 EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
1164 TEST_F(GCMClientImplStartAndStopTest, DelayedStartStopAndRestart) {
1165 // GCMClientImpl should be in INITIALIZED state at first.
1166 EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
1168 // Delay start the GCM and then stop and restart it immediately.
1169 gcm_client()->Start(GCMClient::DELAYED_START);
1170 gcm_client()->Stop();
1171 gcm_client()->Start(GCMClient::DELAYED_START);
1172 PumpLoopUntilIdle();
1173 EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
1176 TEST_F(GCMClientImplStartAndStopTest, ImmediateStartStopAndRestart) {
1177 // GCMClientImpl should be in INITIALIZED state at first.
1178 EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
1180 // Start the GCM and then stop and restart it immediately.
1181 gcm_client()->Start(GCMClient::IMMEDIATE_START);
1182 gcm_client()->Stop();
1183 gcm_client()->Start(GCMClient::IMMEDIATE_START);
1184 PumpLoopUntilIdle();
1185 EXPECT_EQ(GCMClientImpl::INITIAL_DEVICE_CHECKIN, gcm_client_state());
1188 TEST_F(GCMClientImplStartAndStopTest, ImmediateStartAndThenImmediateStart) {
1189 // GCMClientImpl should be in INITIALIZED state at first.
1190 EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
1192 // Start the GCM immediately and complete the checkin.
1193 gcm_client()->Start(GCMClient::IMMEDIATE_START);
1194 PumpLoopUntilIdle();
1195 EXPECT_EQ(GCMClientImpl::INITIAL_DEVICE_CHECKIN, gcm_client_state());
1196 DefaultCompleteCheckin();
1197 EXPECT_EQ(GCMClientImpl::READY, gcm_client_state());
1199 // Stop the GCM.
1200 gcm_client()->Stop();
1201 PumpLoopUntilIdle();
1202 EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
1204 // Start the GCM immediately. GCMClientImpl should be in READY state.
1205 BuildGCMClient(base::TimeDelta());
1206 InitializeGCMClient();
1207 gcm_client()->Start(GCMClient::IMMEDIATE_START);
1208 PumpLoopUntilIdle();
1209 EXPECT_EQ(GCMClientImpl::READY, gcm_client_state());
1212 TEST_F(GCMClientImplStartAndStopTest, ImmediateStartAndThenDelayStart) {
1213 // GCMClientImpl should be in INITIALIZED state at first.
1214 EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
1216 // Start the GCM immediately and complete the checkin.
1217 gcm_client()->Start(GCMClient::IMMEDIATE_START);
1218 PumpLoopUntilIdle();
1219 EXPECT_EQ(GCMClientImpl::INITIAL_DEVICE_CHECKIN, gcm_client_state());
1220 DefaultCompleteCheckin();
1221 EXPECT_EQ(GCMClientImpl::READY, gcm_client_state());
1223 // Stop the GCM.
1224 gcm_client()->Stop();
1225 PumpLoopUntilIdle();
1226 EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
1228 // Delay start the GCM. GCMClientImpl should be in LOADED state.
1229 BuildGCMClient(base::TimeDelta());
1230 InitializeGCMClient();
1231 gcm_client()->Start(GCMClient::DELAYED_START);
1232 PumpLoopUntilIdle();
1233 EXPECT_EQ(GCMClientImpl::LOADED, gcm_client_state());
1236 TEST_F(GCMClientImplStartAndStopTest, DelayedStart) {
1237 // GCMClientImpl should be in INITIALIZED state at first.
1238 EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
1240 // Delay start the GCM. The store will not be loaded and GCMClientImpl should
1241 // still be in INITIALIZED state.
1242 gcm_client()->Start(GCMClient::DELAYED_START);
1243 PumpLoopUntilIdle();
1244 EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
1246 // Start the GCM immediately and complete the checkin.
1247 gcm_client()->Start(GCMClient::IMMEDIATE_START);
1248 PumpLoopUntilIdle();
1249 EXPECT_EQ(GCMClientImpl::INITIAL_DEVICE_CHECKIN, gcm_client_state());
1250 DefaultCompleteCheckin();
1251 EXPECT_EQ(GCMClientImpl::READY, gcm_client_state());
1253 // Registration.
1254 std::vector<std::string> senders;
1255 senders.push_back("sender");
1256 Register(kAppId, senders);
1257 CompleteRegistration("reg_id");
1258 EXPECT_EQ(GCMClientImpl::READY, gcm_client_state());
1260 // Stop the GCM.
1261 gcm_client()->Stop();
1262 PumpLoopUntilIdle();
1263 EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
1265 // Delay start the GCM. GCM is indeed started without delay because the
1266 // registration record has been found.
1267 BuildGCMClient(base::TimeDelta());
1268 InitializeGCMClient();
1269 gcm_client()->Start(GCMClient::DELAYED_START);
1270 PumpLoopUntilIdle();
1271 EXPECT_EQ(GCMClientImpl::READY, gcm_client_state());
1274 // Test for known account mappings and last token fetching time being passed
1275 // to OnGCMReady.
1276 TEST_F(GCMClientImplStartAndStopTest, OnGCMReadyAccountsAndTokenFetchingTime) {
1277 // Start the GCM and wait until it is ready.
1278 gcm_client()->Start(GCMClient::IMMEDIATE_START);
1279 PumpLoopUntilIdle();
1280 DefaultCompleteCheckin();
1282 base::Time expected_time = base::Time::Now();
1283 gcm_client()->SetLastTokenFetchTime(expected_time);
1284 AccountMapping expected_mapping;
1285 expected_mapping.account_id = "accId";
1286 expected_mapping.email = "email@gmail.com";
1287 expected_mapping.status = AccountMapping::MAPPED;
1288 expected_mapping.status_change_timestamp = expected_time;
1289 gcm_client()->UpdateAccountMapping(expected_mapping);
1290 PumpLoopUntilIdle();
1292 // Stop the GCM.
1293 gcm_client()->Stop();
1294 PumpLoopUntilIdle();
1296 // Restart the GCM.
1297 gcm_client()->Start(GCMClient::IMMEDIATE_START);
1298 PumpLoopUntilIdle();
1300 EXPECT_EQ(LOADING_COMPLETED, last_event());
1301 EXPECT_EQ(expected_time, last_token_fetch_time());
1302 ASSERT_EQ(1UL, last_account_mappings().size());
1303 const AccountMapping& actual_mapping = last_account_mappings()[0];
1304 EXPECT_EQ(expected_mapping.account_id, actual_mapping.account_id);
1305 EXPECT_EQ(expected_mapping.email, actual_mapping.email);
1306 EXPECT_EQ(expected_mapping.status, actual_mapping.status);
1307 EXPECT_EQ(expected_mapping.status_change_timestamp,
1308 actual_mapping.status_change_timestamp);
1312 class GCMClientInstanceIDTest : public GCMClientImplTest {
1313 public:
1314 GCMClientInstanceIDTest();
1315 ~GCMClientInstanceIDTest() override;
1317 void AddInstanceID(const std::string& app_id,
1318 const std::string& instance_id);
1319 void RemoveInstanceID(const std::string& app_id);
1320 void GetToken(const std::string& app_id,
1321 const std::string& authorized_entity,
1322 const std::string& scope);
1323 void DeleteToken(const std::string& app_id,
1324 const std::string& authorized_entity,
1325 const std::string& scope);
1326 void CompleteDeleteToken();
1327 bool ExistsToken(const std::string& app_id,
1328 const std::string& authorized_entity,
1329 const std::string& scope) const;
1332 GCMClientInstanceIDTest::GCMClientInstanceIDTest() {
1335 GCMClientInstanceIDTest::~GCMClientInstanceIDTest() {
1338 void GCMClientInstanceIDTest::AddInstanceID(const std::string& app_id,
1339 const std::string& instance_id) {
1340 gcm_client()->AddInstanceIDData(app_id, instance_id, "123");
1343 void GCMClientInstanceIDTest::RemoveInstanceID(const std::string& app_id) {
1344 gcm_client()->RemoveInstanceIDData(app_id);
1347 void GCMClientInstanceIDTest::GetToken(const std::string& app_id,
1348 const std::string& authorized_entity,
1349 const std::string& scope) {
1350 scoped_ptr<InstanceIDTokenInfo> instance_id_info(new InstanceIDTokenInfo);
1351 instance_id_info->app_id = app_id;
1352 instance_id_info->authorized_entity = authorized_entity;
1353 instance_id_info->scope = scope;
1354 gcm_client()->Register(
1355 make_linked_ptr<RegistrationInfo>(instance_id_info.release()));
1358 void GCMClientInstanceIDTest::DeleteToken(const std::string& app_id,
1359 const std::string& authorized_entity,
1360 const std::string& scope) {
1361 scoped_ptr<InstanceIDTokenInfo> instance_id_info(new InstanceIDTokenInfo);
1362 instance_id_info->app_id = app_id;
1363 instance_id_info->authorized_entity = authorized_entity;
1364 instance_id_info->scope = scope;
1365 gcm_client()->Unregister(
1366 make_linked_ptr<RegistrationInfo>(instance_id_info.release()));
1369 void GCMClientInstanceIDTest::CompleteDeleteToken() {
1370 std::string response(kDeleteTokenResponse);
1371 net::TestURLFetcher* fetcher = url_fetcher_factory()->GetFetcherByID(0);
1372 ASSERT_TRUE(fetcher);
1373 fetcher->set_response_code(net::HTTP_OK);
1374 fetcher->SetResponseString(response);
1375 fetcher->delegate()->OnURLFetchComplete(fetcher);
1378 bool GCMClientInstanceIDTest::ExistsToken(const std::string& app_id,
1379 const std::string& authorized_entity,
1380 const std::string& scope) const {
1381 scoped_ptr<InstanceIDTokenInfo> instance_id_info(new InstanceIDTokenInfo);
1382 instance_id_info->app_id = app_id;
1383 instance_id_info->authorized_entity = authorized_entity;
1384 instance_id_info->scope = scope;
1385 return gcm_client()->registrations_.count(
1386 make_linked_ptr<RegistrationInfo>(instance_id_info.release())) > 0;
1389 TEST_F(GCMClientInstanceIDTest, GetToken) {
1390 AddInstanceID(kAppId, kInstanceID);
1392 // Get a token.
1393 EXPECT_FALSE(ExistsToken(kAppId, kSender, kScope));
1394 GetToken(kAppId, kSender, kScope);
1395 CompleteRegistration("token1");
1397 EXPECT_EQ(REGISTRATION_COMPLETED, last_event());
1398 EXPECT_EQ(kAppId, last_app_id());
1399 EXPECT_EQ("token1", last_registration_id());
1400 EXPECT_EQ(GCMClient::SUCCESS, last_result());
1401 EXPECT_TRUE(ExistsToken(kAppId, kSender, kScope));
1403 // Get another token.
1404 EXPECT_FALSE(ExistsToken(kAppId, kSender2, kScope));
1405 GetToken(kAppId, kSender2, kScope);
1406 CompleteRegistration("token2");
1408 EXPECT_EQ(REGISTRATION_COMPLETED, last_event());
1409 EXPECT_EQ(kAppId, last_app_id());
1410 EXPECT_EQ("token2", last_registration_id());
1411 EXPECT_EQ(GCMClient::SUCCESS, last_result());
1412 EXPECT_TRUE(ExistsToken(kAppId, kSender2, kScope));
1413 // The 1st token still exists.
1414 EXPECT_TRUE(ExistsToken(kAppId, kSender, kScope));
1417 TEST_F(GCMClientInstanceIDTest, DeleteSingleToken) {
1418 AddInstanceID(kAppId, kInstanceID);
1420 // Get a token.
1421 EXPECT_FALSE(ExistsToken(kAppId, kSender, kScope));
1422 GetToken(kAppId, kSender, kScope);
1423 CompleteRegistration("token1");
1425 EXPECT_EQ(REGISTRATION_COMPLETED, last_event());
1426 EXPECT_EQ(kAppId, last_app_id());
1427 EXPECT_EQ("token1", last_registration_id());
1428 EXPECT_EQ(GCMClient::SUCCESS, last_result());
1429 EXPECT_TRUE(ExistsToken(kAppId, kSender, kScope));
1431 // Get another token.
1432 EXPECT_FALSE(ExistsToken(kAppId, kSender2, kScope));
1433 GetToken(kAppId, kSender2, kScope);
1434 CompleteRegistration("token2");
1436 EXPECT_EQ(REGISTRATION_COMPLETED, last_event());
1437 EXPECT_EQ(kAppId, last_app_id());
1438 EXPECT_EQ("token2", last_registration_id());
1439 EXPECT_EQ(GCMClient::SUCCESS, last_result());
1440 EXPECT_TRUE(ExistsToken(kAppId, kSender2, kScope));
1441 // The 1st token still exists.
1442 EXPECT_TRUE(ExistsToken(kAppId, kSender, kScope));
1444 // Delete the 2nd token.
1445 DeleteToken(kAppId, kSender2, kScope);
1446 CompleteDeleteToken();
1448 EXPECT_EQ(UNREGISTRATION_COMPLETED, last_event());
1449 EXPECT_EQ(kAppId, last_app_id());
1450 EXPECT_EQ(GCMClient::SUCCESS, last_result());
1451 // The 2nd token is gone while the 1st token still exists.
1452 EXPECT_TRUE(ExistsToken(kAppId, kSender, kScope));
1453 EXPECT_FALSE(ExistsToken(kAppId, kSender2, kScope));
1455 // Delete the 1st token.
1456 DeleteToken(kAppId, kSender, kScope);
1457 CompleteDeleteToken();
1459 EXPECT_EQ(UNREGISTRATION_COMPLETED, last_event());
1460 EXPECT_EQ(kAppId, last_app_id());
1461 EXPECT_EQ(GCMClient::SUCCESS, last_result());
1462 // Both tokens are gone now.
1463 EXPECT_FALSE(ExistsToken(kAppId, kSender, kScope));
1464 EXPECT_FALSE(ExistsToken(kAppId, kSender, kScope));
1467 TEST_F(GCMClientInstanceIDTest, DeleteMultiTokens) {
1468 AddInstanceID(kAppId, kInstanceID);
1470 // Get a token.
1471 EXPECT_FALSE(ExistsToken(kAppId, kSender, kScope));
1472 GetToken(kAppId, kSender, kScope);
1473 CompleteRegistration("token1");
1475 EXPECT_EQ(REGISTRATION_COMPLETED, last_event());
1476 EXPECT_EQ(kAppId, last_app_id());
1477 EXPECT_EQ("token1", last_registration_id());
1478 EXPECT_EQ(GCMClient::SUCCESS, last_result());
1479 EXPECT_TRUE(ExistsToken(kAppId, kSender, kScope));
1481 // Get another token.
1482 EXPECT_FALSE(ExistsToken(kAppId, kSender2, kScope));
1483 GetToken(kAppId, kSender2, kScope);
1484 CompleteRegistration("token2");
1486 EXPECT_EQ(REGISTRATION_COMPLETED, last_event());
1487 EXPECT_EQ(kAppId, last_app_id());
1488 EXPECT_EQ("token2", last_registration_id());
1489 EXPECT_EQ(GCMClient::SUCCESS, last_result());
1490 EXPECT_TRUE(ExistsToken(kAppId, kSender2, kScope));
1491 // The 1st token still exists.
1492 EXPECT_TRUE(ExistsToken(kAppId, kSender, kScope));
1494 // Delete all tokens.
1495 DeleteToken(kAppId, "*", "*");
1496 CompleteDeleteToken();
1498 EXPECT_EQ(UNREGISTRATION_COMPLETED, last_event());
1499 EXPECT_EQ(kAppId, last_app_id());
1500 EXPECT_EQ(GCMClient::SUCCESS, last_result());
1501 // All tokens are gone now.
1502 EXPECT_FALSE(ExistsToken(kAppId, kSender, kScope));
1503 EXPECT_FALSE(ExistsToken(kAppId, kSender, kScope));
1506 } // namespace gcm