[Android] Add tests for toolbar of Chrome Custom Tabs
[chromium-blink-merge.git] / components / gcm_driver / gcm_client_impl_unittest.cc
blobfc578e1d693bb70f4d2705ed55c099f0b67496ea
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/run_loop.h"
13 #include "base/strings/string_number_conversions.h"
14 #include "base/time/clock.h"
15 #include "base/timer/timer.h"
16 #include "google_apis/gcm/base/fake_encryptor.h"
17 #include "google_apis/gcm/base/mcs_message.h"
18 #include "google_apis/gcm/base/mcs_util.h"
19 #include "google_apis/gcm/engine/fake_connection_factory.h"
20 #include "google_apis/gcm/engine/fake_connection_handler.h"
21 #include "google_apis/gcm/engine/gservices_settings.h"
22 #include "google_apis/gcm/monitoring/gcm_stats_recorder.h"
23 #include "google_apis/gcm/protocol/android_checkin.pb.h"
24 #include "google_apis/gcm/protocol/checkin.pb.h"
25 #include "google_apis/gcm/protocol/mcs.pb.h"
26 #include "net/url_request/test_url_fetcher_factory.h"
27 #include "net/url_request/url_fetcher_delegate.h"
28 #include "net/url_request/url_request_test_util.h"
29 #include "testing/gtest/include/gtest/gtest.h"
31 namespace gcm {
33 namespace {
35 enum LastEvent {
36 NONE,
37 LOADING_COMPLETED,
38 REGISTRATION_COMPLETED,
39 UNREGISTRATION_COMPLETED,
40 MESSAGE_SEND_ERROR,
41 MESSAGE_SEND_ACK,
42 MESSAGE_RECEIVED,
43 MESSAGES_DELETED,
46 const char kChromeVersion[] = "45.0.0.1";
47 const uint64 kDeviceAndroidId = 54321;
48 const uint64 kDeviceSecurityToken = 12345;
49 const uint64 kDeviceAndroidId2 = 11111;
50 const uint64 kDeviceSecurityToken2 = 2222;
51 const int64 kSettingsCheckinInterval = 16 * 60 * 60;
52 const char kAppId[] = "app_id";
53 const char kSender[] = "project_id";
54 const char kSender2[] = "project_id2";
55 const char kSender3[] = "project_id3";
56 const char kRegistrationResponsePrefix[] = "token=";
57 const char kUnregistrationResponsePrefix[] = "deleted=";
59 const char kInstanceID[] = "iid_1";
60 const char kScope[] = "GCM";
61 const char kDeleteTokenResponse[] = "token=foo";
63 // Helper for building arbitrary data messages.
64 MCSMessage BuildDownstreamMessage(
65 const std::string& project_id,
66 const std::string& app_id,
67 const std::map<std::string, std::string>& data) {
68 mcs_proto::DataMessageStanza data_message;
69 data_message.set_from(project_id);
70 data_message.set_category(app_id);
71 for (std::map<std::string, std::string>::const_iterator iter = data.begin();
72 iter != data.end();
73 ++iter) {
74 mcs_proto::AppData* app_data = data_message.add_app_data();
75 app_data->set_key(iter->first);
76 app_data->set_value(iter->second);
78 return MCSMessage(kDataMessageStanzaTag, data_message);
81 GCMClient::AccountTokenInfo MakeAccountToken(const std::string& email,
82 const std::string& token) {
83 GCMClient::AccountTokenInfo account_token;
84 account_token.email = email;
85 account_token.access_token = token;
86 return account_token;
89 std::map<std::string, std::string> MakeEmailToTokenMap(
90 const std::vector<GCMClient::AccountTokenInfo>& account_tokens) {
91 std::map<std::string, std::string> email_token_map;
92 for (std::vector<GCMClient::AccountTokenInfo>::const_iterator iter =
93 account_tokens.begin(); iter != account_tokens.end(); ++iter) {
94 email_token_map[iter->email] = iter->access_token;
96 return email_token_map;
99 class FakeMCSClient : public MCSClient {
100 public:
101 FakeMCSClient(base::Clock* clock,
102 ConnectionFactory* connection_factory,
103 GCMStore* gcm_store,
104 GCMStatsRecorder* recorder);
105 ~FakeMCSClient() override;
106 void Login(uint64 android_id, uint64 security_token) override;
107 void SendMessage(const MCSMessage& message) override;
109 uint64 last_android_id() const { return last_android_id_; }
110 uint64 last_security_token() const { return last_security_token_; }
111 uint8 last_message_tag() const { return last_message_tag_; }
112 const mcs_proto::DataMessageStanza& last_data_message_stanza() const {
113 return last_data_message_stanza_;
116 private:
117 uint64 last_android_id_;
118 uint64 last_security_token_;
119 uint8 last_message_tag_;
120 mcs_proto::DataMessageStanza last_data_message_stanza_;
123 FakeMCSClient::FakeMCSClient(base::Clock* clock,
124 ConnectionFactory* connection_factory,
125 GCMStore* gcm_store,
126 GCMStatsRecorder* recorder)
127 : MCSClient("", clock, connection_factory, gcm_store, recorder),
128 last_android_id_(0u),
129 last_security_token_(0u),
130 last_message_tag_(kNumProtoTypes) {
133 FakeMCSClient::~FakeMCSClient() {
136 void FakeMCSClient::Login(uint64 android_id, uint64 security_token) {
137 last_android_id_ = android_id;
138 last_security_token_ = security_token;
141 void FakeMCSClient::SendMessage(const MCSMessage& message) {
142 last_message_tag_ = message.tag();
143 if (last_message_tag_ == kDataMessageStanzaTag) {
144 last_data_message_stanza_.CopyFrom(
145 reinterpret_cast<const mcs_proto::DataMessageStanza&>(
146 message.GetProtobuf()));
150 class AutoAdvancingTestClock : public base::Clock {
151 public:
152 explicit AutoAdvancingTestClock(base::TimeDelta auto_increment_time_delta);
153 ~AutoAdvancingTestClock() override;
155 base::Time Now() override;
156 void Advance(TimeDelta delta);
157 int call_count() const { return call_count_; }
159 private:
160 int call_count_;
161 base::TimeDelta auto_increment_time_delta_;
162 base::Time now_;
164 DISALLOW_COPY_AND_ASSIGN(AutoAdvancingTestClock);
167 AutoAdvancingTestClock::AutoAdvancingTestClock(
168 base::TimeDelta auto_increment_time_delta)
169 : call_count_(0), auto_increment_time_delta_(auto_increment_time_delta) {
172 AutoAdvancingTestClock::~AutoAdvancingTestClock() {
175 base::Time AutoAdvancingTestClock::Now() {
176 call_count_++;
177 now_ += auto_increment_time_delta_;
178 return now_;
181 void AutoAdvancingTestClock::Advance(base::TimeDelta delta) {
182 now_ += delta;
185 class FakeGCMInternalsBuilder : public GCMInternalsBuilder {
186 public:
187 FakeGCMInternalsBuilder(base::TimeDelta clock_step);
188 ~FakeGCMInternalsBuilder() override;
190 scoped_ptr<base::Clock> BuildClock() override;
191 scoped_ptr<MCSClient> BuildMCSClient(const std::string& version,
192 base::Clock* clock,
193 ConnectionFactory* connection_factory,
194 GCMStore* gcm_store,
195 GCMStatsRecorder* recorder) override;
196 scoped_ptr<ConnectionFactory> BuildConnectionFactory(
197 const std::vector<GURL>& endpoints,
198 const net::BackoffEntry::Policy& backoff_policy,
199 const scoped_refptr<net::HttpNetworkSession>& gcm_network_session,
200 const scoped_refptr<net::HttpNetworkSession>& http_network_session,
201 net::NetLog* net_log,
202 GCMStatsRecorder* recorder) override;
204 private:
205 base::TimeDelta clock_step_;
208 FakeGCMInternalsBuilder::FakeGCMInternalsBuilder(base::TimeDelta clock_step)
209 : clock_step_(clock_step) {
212 FakeGCMInternalsBuilder::~FakeGCMInternalsBuilder() {}
214 scoped_ptr<base::Clock> FakeGCMInternalsBuilder::BuildClock() {
215 return make_scoped_ptr<base::Clock>(new AutoAdvancingTestClock(clock_step_));
218 scoped_ptr<MCSClient> FakeGCMInternalsBuilder::BuildMCSClient(
219 const std::string& version,
220 base::Clock* clock,
221 ConnectionFactory* connection_factory,
222 GCMStore* gcm_store,
223 GCMStatsRecorder* recorder) {
224 return make_scoped_ptr<MCSClient>(new FakeMCSClient(clock,
225 connection_factory,
226 gcm_store,
227 recorder));
230 scoped_ptr<ConnectionFactory> FakeGCMInternalsBuilder::BuildConnectionFactory(
231 const std::vector<GURL>& endpoints,
232 const net::BackoffEntry::Policy& backoff_policy,
233 const scoped_refptr<net::HttpNetworkSession>& gcm_network_session,
234 const scoped_refptr<net::HttpNetworkSession>& http_network_session,
235 net::NetLog* net_log,
236 GCMStatsRecorder* recorder) {
237 return make_scoped_ptr<ConnectionFactory>(new FakeConnectionFactory());
240 } // namespace
242 class GCMClientImplTest : public testing::Test,
243 public GCMClient::Delegate {
244 public:
245 GCMClientImplTest();
246 ~GCMClientImplTest() override;
248 void SetUp() override;
250 void SetUpUrlFetcherFactory();
252 void BuildGCMClient(base::TimeDelta clock_step);
253 void InitializeGCMClient();
254 void StartGCMClient();
255 void Register(const std::string& app_id,
256 const std::vector<std::string>& senders);
257 void Unregister(const std::string& app_id);
258 void ReceiveMessageFromMCS(const MCSMessage& message);
259 void ReceiveOnMessageSentToMCS(
260 const std::string& app_id,
261 const std::string& message_id,
262 const MCSClient::MessageSendStatus status);
263 void CompleteCheckin(uint64 android_id,
264 uint64 security_token,
265 const std::string& digest,
266 const std::map<std::string, std::string>& settings);
267 void CompleteRegistration(const std::string& registration_id);
268 void CompleteUnregistration(const std::string& app_id);
269 void VerifyPendingRequestFetcherDeleted();
271 bool ExistsRegistration(const std::string& app_id) const;
272 void AddRegistration(const std::string& app_id,
273 const std::vector<std::string>& sender_ids,
274 const std::string& registration_id);
276 // GCMClient::Delegate overrides (for verification).
277 void OnRegisterFinished(const linked_ptr<RegistrationInfo>& registration_info,
278 const std::string& registration_id,
279 GCMClient::Result result) override;
280 void OnUnregisterFinished(
281 const linked_ptr<RegistrationInfo>& registration_info,
282 GCMClient::Result result) override;
283 void OnSendFinished(const std::string& app_id,
284 const std::string& message_id,
285 GCMClient::Result result) override {}
286 void OnMessageReceived(const std::string& registration_id,
287 const GCMClient::IncomingMessage& message) override;
288 void OnMessagesDeleted(const std::string& app_id) override;
289 void OnMessageSendError(
290 const std::string& app_id,
291 const gcm::GCMClient::SendErrorDetails& send_error_details) override;
292 void OnSendAcknowledged(const std::string& app_id,
293 const std::string& message_id) override;
294 void OnGCMReady(const std::vector<AccountMapping>& account_mappings,
295 const base::Time& last_token_fetch_time) override;
296 void OnActivityRecorded() override {}
297 void OnConnected(const net::IPEndPoint& ip_endpoint) override {}
298 void OnDisconnected() override {}
300 GCMClientImpl* gcm_client() const { return gcm_client_.get(); }
301 GCMClientImpl::State gcm_client_state() const {
302 return gcm_client_->state_;
304 FakeMCSClient* mcs_client() const {
305 return reinterpret_cast<FakeMCSClient*>(gcm_client_->mcs_client_.get());
307 ConnectionFactory* connection_factory() const {
308 return gcm_client_->connection_factory_.get();
311 const GCMClientImpl::CheckinInfo& device_checkin_info() const {
312 return gcm_client_->device_checkin_info_;
315 void reset_last_event() {
316 last_event_ = NONE;
317 last_app_id_.clear();
318 last_registration_id_.clear();
319 last_message_id_.clear();
320 last_result_ = GCMClient::UNKNOWN_ERROR;
321 last_account_mappings_.clear();
322 last_token_fetch_time_ = base::Time();
325 LastEvent last_event() const { return last_event_; }
326 const std::string& last_app_id() const { return last_app_id_; }
327 const std::string& last_registration_id() const {
328 return last_registration_id_;
330 const std::string& last_message_id() const { return last_message_id_; }
331 GCMClient::Result last_result() const { return last_result_; }
332 const GCMClient::IncomingMessage& last_message() const {
333 return last_message_;
335 const GCMClient::SendErrorDetails& last_error_details() const {
336 return last_error_details_;
338 const base::Time& last_token_fetch_time() const {
339 return last_token_fetch_time_;
341 const std::vector<AccountMapping>& last_account_mappings() {
342 return last_account_mappings_;
345 const GServicesSettings& gservices_settings() const {
346 return gcm_client_->gservices_settings_;
349 const base::FilePath& temp_directory_path() const {
350 return temp_directory_.path();
353 int64 CurrentTime();
355 // Tooling.
356 void PumpLoop();
357 void PumpLoopUntilIdle();
358 void QuitLoop();
359 void InitializeLoop();
360 bool CreateUniqueTempDir();
361 AutoAdvancingTestClock* clock() const {
362 return reinterpret_cast<AutoAdvancingTestClock*>(gcm_client_->clock_.get());
364 net::TestURLFetcherFactory* url_fetcher_factory() {
365 return &url_fetcher_factory_;
368 private:
369 // Variables used for verification.
370 LastEvent last_event_;
371 std::string last_app_id_;
372 std::string last_registration_id_;
373 std::string last_message_id_;
374 GCMClient::Result last_result_;
375 GCMClient::IncomingMessage last_message_;
376 GCMClient::SendErrorDetails last_error_details_;
377 base::Time last_token_fetch_time_;
378 std::vector<AccountMapping> last_account_mappings_;
380 scoped_ptr<GCMClientImpl> gcm_client_;
382 base::MessageLoop message_loop_;
383 scoped_ptr<base::RunLoop> run_loop_;
384 net::TestURLFetcherFactory url_fetcher_factory_;
386 // Injected to GCM client:
387 base::ScopedTempDir temp_directory_;
388 scoped_refptr<net::TestURLRequestContextGetter> url_request_context_getter_;
391 GCMClientImplTest::GCMClientImplTest()
392 : last_event_(NONE),
393 last_result_(GCMClient::UNKNOWN_ERROR),
394 url_request_context_getter_(
395 new net::TestURLRequestContextGetter(message_loop_.task_runner())) {
398 GCMClientImplTest::~GCMClientImplTest() {}
400 void GCMClientImplTest::SetUp() {
401 testing::Test::SetUp();
402 ASSERT_TRUE(CreateUniqueTempDir());
403 InitializeLoop();
404 BuildGCMClient(base::TimeDelta());
405 InitializeGCMClient();
406 StartGCMClient();
407 SetUpUrlFetcherFactory();
408 CompleteCheckin(kDeviceAndroidId,
409 kDeviceSecurityToken,
410 std::string(),
411 std::map<std::string, std::string>());
414 void GCMClientImplTest::SetUpUrlFetcherFactory() {
415 url_fetcher_factory_.set_remove_fetcher_on_delete(true);
418 void GCMClientImplTest::PumpLoop() {
419 run_loop_->Run();
420 run_loop_.reset(new base::RunLoop());
423 void GCMClientImplTest::PumpLoopUntilIdle() {
424 run_loop_->RunUntilIdle();
425 run_loop_.reset(new base::RunLoop());
428 void GCMClientImplTest::QuitLoop() {
429 if (run_loop_ && run_loop_->running())
430 run_loop_->Quit();
433 void GCMClientImplTest::InitializeLoop() {
434 run_loop_.reset(new base::RunLoop);
437 bool GCMClientImplTest::CreateUniqueTempDir() {
438 return temp_directory_.CreateUniqueTempDir();
441 void GCMClientImplTest::BuildGCMClient(base::TimeDelta clock_step) {
442 gcm_client_.reset(new GCMClientImpl(make_scoped_ptr<GCMInternalsBuilder>(
443 new FakeGCMInternalsBuilder(clock_step))));
446 void GCMClientImplTest::CompleteCheckin(
447 uint64 android_id,
448 uint64 security_token,
449 const std::string& digest,
450 const std::map<std::string, std::string>& settings) {
451 checkin_proto::AndroidCheckinResponse response;
452 response.set_stats_ok(true);
453 response.set_android_id(android_id);
454 response.set_security_token(security_token);
456 // For testing G-services settings.
457 if (!digest.empty()) {
458 response.set_digest(digest);
459 for (std::map<std::string, std::string>::const_iterator it =
460 settings.begin();
461 it != settings.end();
462 ++it) {
463 checkin_proto::GservicesSetting* setting = response.add_setting();
464 setting->set_name(it->first);
465 setting->set_value(it->second);
467 response.set_settings_diff(false);
470 std::string response_string;
471 response.SerializeToString(&response_string);
473 net::TestURLFetcher* fetcher = url_fetcher_factory_.GetFetcherByID(0);
474 ASSERT_TRUE(fetcher);
475 fetcher->set_response_code(net::HTTP_OK);
476 fetcher->SetResponseString(response_string);
477 fetcher->delegate()->OnURLFetchComplete(fetcher);
480 void GCMClientImplTest::CompleteRegistration(
481 const std::string& registration_id) {
482 std::string response(kRegistrationResponsePrefix);
483 response.append(registration_id);
484 net::TestURLFetcher* fetcher = url_fetcher_factory_.GetFetcherByID(0);
485 ASSERT_TRUE(fetcher);
486 fetcher->set_response_code(net::HTTP_OK);
487 fetcher->SetResponseString(response);
488 fetcher->delegate()->OnURLFetchComplete(fetcher);
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);
502 void GCMClientImplTest::VerifyPendingRequestFetcherDeleted() {
503 net::TestURLFetcher* fetcher = url_fetcher_factory_.GetFetcherByID(0);
504 EXPECT_FALSE(fetcher);
507 bool GCMClientImplTest::ExistsRegistration(const std::string& app_id) const {
508 return ExistsGCMRegistrationInMap(gcm_client_->registrations_, app_id);
511 void GCMClientImplTest::AddRegistration(
512 const std::string& app_id,
513 const std::vector<std::string>& sender_ids,
514 const std::string& registration_id) {
515 linked_ptr<GCMRegistrationInfo> registration(new GCMRegistrationInfo);
516 registration->app_id = app_id;
517 registration->sender_ids = sender_ids;
518 gcm_client_->registrations_[registration] = registration_id;
521 void GCMClientImplTest::InitializeGCMClient() {
522 clock()->Advance(base::TimeDelta::FromMilliseconds(1));
524 // Actual initialization.
525 GCMClient::ChromeBuildInfo chrome_build_info;
526 chrome_build_info.version = kChromeVersion;
527 gcm_client_->Initialize(chrome_build_info, temp_directory_.path(),
528 message_loop_.task_runner(),
529 url_request_context_getter_,
530 make_scoped_ptr<Encryptor>(new FakeEncryptor), this);
533 void GCMClientImplTest::StartGCMClient() {
534 // Start loading and check-in.
535 gcm_client_->Start(GCMClient::IMMEDIATE_START);
537 PumpLoopUntilIdle();
540 void GCMClientImplTest::Register(const std::string& app_id,
541 const std::vector<std::string>& senders) {
542 scoped_ptr<GCMRegistrationInfo> gcm_info(new GCMRegistrationInfo);
543 gcm_info->app_id = app_id;
544 gcm_info->sender_ids = senders;
545 gcm_client()->Register(make_linked_ptr<RegistrationInfo>(gcm_info.release()));
548 void GCMClientImplTest::Unregister(const std::string& app_id) {
549 scoped_ptr<GCMRegistrationInfo> gcm_info(new GCMRegistrationInfo);
550 gcm_info->app_id = app_id;
551 gcm_client()->Unregister(
552 make_linked_ptr<RegistrationInfo>(gcm_info.release()));
555 void GCMClientImplTest::ReceiveMessageFromMCS(const MCSMessage& message) {
556 gcm_client_->recorder_.RecordConnectionInitiated(std::string());
557 gcm_client_->recorder_.RecordConnectionSuccess();
558 gcm_client_->OnMessageReceivedFromMCS(message);
561 void GCMClientImplTest::ReceiveOnMessageSentToMCS(
562 const std::string& app_id,
563 const std::string& message_id,
564 const MCSClient::MessageSendStatus status) {
565 gcm_client_->OnMessageSentToMCS(0LL, app_id, message_id, status);
568 void GCMClientImplTest::OnGCMReady(
569 const std::vector<AccountMapping>& account_mappings,
570 const base::Time& last_token_fetch_time) {
571 last_event_ = LOADING_COMPLETED;
572 last_account_mappings_ = account_mappings;
573 last_token_fetch_time_ = last_token_fetch_time;
574 QuitLoop();
577 void GCMClientImplTest::OnMessageReceived(
578 const std::string& registration_id,
579 const GCMClient::IncomingMessage& message) {
580 last_event_ = MESSAGE_RECEIVED;
581 last_app_id_ = registration_id;
582 last_message_ = message;
583 QuitLoop();
586 void GCMClientImplTest::OnRegisterFinished(
587 const linked_ptr<RegistrationInfo>& registration_info,
588 const std::string& registration_id,
589 GCMClient::Result result) {
590 last_event_ = REGISTRATION_COMPLETED;
591 last_app_id_ = registration_info->app_id;
592 last_registration_id_ = registration_id;
593 last_result_ = result;
596 void GCMClientImplTest::OnUnregisterFinished(
597 const linked_ptr<RegistrationInfo>& registration_info,
598 GCMClient::Result result) {
599 last_event_ = UNREGISTRATION_COMPLETED;
600 last_app_id_ = registration_info->app_id;
601 last_result_ = result;
604 void GCMClientImplTest::OnMessagesDeleted(const std::string& app_id) {
605 last_event_ = MESSAGES_DELETED;
606 last_app_id_ = app_id;
609 void GCMClientImplTest::OnMessageSendError(
610 const std::string& app_id,
611 const gcm::GCMClient::SendErrorDetails& send_error_details) {
612 last_event_ = MESSAGE_SEND_ERROR;
613 last_app_id_ = app_id;
614 last_error_details_ = send_error_details;
617 void GCMClientImplTest::OnSendAcknowledged(const std::string& app_id,
618 const std::string& message_id) {
619 last_event_ = MESSAGE_SEND_ACK;
620 last_app_id_ = app_id;
621 last_message_id_ = message_id;
624 int64 GCMClientImplTest::CurrentTime() {
625 return clock()->Now().ToInternalValue() / base::Time::kMicrosecondsPerSecond;
628 TEST_F(GCMClientImplTest, LoadingCompleted) {
629 EXPECT_EQ(LOADING_COMPLETED, last_event());
630 EXPECT_EQ(kDeviceAndroidId, mcs_client()->last_android_id());
631 EXPECT_EQ(kDeviceSecurityToken, mcs_client()->last_security_token());
633 // Checking freshly loaded CheckinInfo.
634 EXPECT_EQ(kDeviceAndroidId, device_checkin_info().android_id);
635 EXPECT_EQ(kDeviceSecurityToken, device_checkin_info().secret);
636 EXPECT_TRUE(device_checkin_info().last_checkin_accounts.empty());
637 EXPECT_TRUE(device_checkin_info().accounts_set);
638 EXPECT_TRUE(device_checkin_info().account_tokens.empty());
641 TEST_F(GCMClientImplTest, LoadingBusted) {
642 // Close the GCM store.
643 gcm_client()->Stop();
644 PumpLoopUntilIdle();
646 // Mess up the store.
647 base::FilePath store_file_path =
648 temp_directory_path().Append(FILE_PATH_LITERAL("CURRENT"));
649 ASSERT_TRUE(base::AppendToFile(store_file_path, "A", 1));
651 // Restart GCM client. The store should be reset and the loading should
652 // complete successfully.
653 reset_last_event();
654 BuildGCMClient(base::TimeDelta());
655 InitializeGCMClient();
656 StartGCMClient();
657 CompleteCheckin(kDeviceAndroidId2,
658 kDeviceSecurityToken2,
659 std::string(),
660 std::map<std::string, std::string>());
662 EXPECT_EQ(LOADING_COMPLETED, last_event());
663 EXPECT_EQ(kDeviceAndroidId2, mcs_client()->last_android_id());
664 EXPECT_EQ(kDeviceSecurityToken2, mcs_client()->last_security_token());
667 TEST_F(GCMClientImplTest, RegisterApp) {
668 EXPECT_FALSE(ExistsRegistration(kAppId));
670 std::vector<std::string> senders;
671 senders.push_back("sender");
672 Register(kAppId, senders);
673 CompleteRegistration("reg_id");
675 EXPECT_EQ(REGISTRATION_COMPLETED, last_event());
676 EXPECT_EQ(kAppId, last_app_id());
677 EXPECT_EQ("reg_id", last_registration_id());
678 EXPECT_EQ(GCMClient::SUCCESS, last_result());
679 EXPECT_TRUE(ExistsRegistration(kAppId));
682 TEST_F(GCMClientImplTest, DISABLED_RegisterAppFromCache) {
683 EXPECT_FALSE(ExistsRegistration(kAppId));
685 std::vector<std::string> senders;
686 senders.push_back("sender");
687 Register(kAppId, senders);
688 CompleteRegistration("reg_id");
689 EXPECT_TRUE(ExistsRegistration(kAppId));
691 EXPECT_EQ(kAppId, last_app_id());
692 EXPECT_EQ("reg_id", last_registration_id());
693 EXPECT_EQ(GCMClient::SUCCESS, last_result());
694 EXPECT_EQ(REGISTRATION_COMPLETED, last_event());
696 // Recreate GCMClient in order to load from the persistent store.
697 BuildGCMClient(base::TimeDelta());
698 InitializeGCMClient();
699 StartGCMClient();
701 EXPECT_TRUE(ExistsRegistration(kAppId));
704 TEST_F(GCMClientImplTest, UnregisterApp) {
705 EXPECT_FALSE(ExistsRegistration(kAppId));
707 std::vector<std::string> senders;
708 senders.push_back("sender");
709 Register(kAppId, senders);
710 CompleteRegistration("reg_id");
711 EXPECT_TRUE(ExistsRegistration(kAppId));
713 Unregister(kAppId);
714 CompleteUnregistration(kAppId);
716 EXPECT_EQ(UNREGISTRATION_COMPLETED, last_event());
717 EXPECT_EQ(kAppId, last_app_id());
718 EXPECT_EQ(GCMClient::SUCCESS, last_result());
719 EXPECT_FALSE(ExistsRegistration(kAppId));
722 // Tests that stopping the GCMClient also deletes pending registration requests.
723 // This is tested by checking that url fetcher contained in the request was
724 // deleted.
725 TEST_F(GCMClientImplTest, DeletePendingRequestsWhenStopping) {
726 std::vector<std::string> senders;
727 senders.push_back("sender");
728 Register(kAppId, senders);
730 gcm_client()->Stop();
731 VerifyPendingRequestFetcherDeleted();
734 TEST_F(GCMClientImplTest, DispatchDownstreamMessage) {
735 // Register to receive messages from kSender and kSender2 only.
736 std::vector<std::string> senders;
737 senders.push_back(kSender);
738 senders.push_back(kSender2);
739 AddRegistration(kAppId, senders, "reg_id");
741 std::map<std::string, std::string> expected_data;
742 expected_data["message_type"] = "gcm";
743 expected_data["key"] = "value";
744 expected_data["key2"] = "value2";
746 // Message for kSender will be received.
747 MCSMessage message(BuildDownstreamMessage(kSender, kAppId, expected_data));
748 EXPECT_TRUE(message.IsValid());
749 ReceiveMessageFromMCS(message);
751 expected_data.erase(expected_data.find("message_type"));
752 EXPECT_EQ(MESSAGE_RECEIVED, last_event());
753 EXPECT_EQ(kAppId, last_app_id());
754 EXPECT_EQ(expected_data.size(), last_message().data.size());
755 EXPECT_EQ(expected_data, last_message().data);
756 EXPECT_EQ(kSender, last_message().sender_id);
758 reset_last_event();
760 // Message for kSender2 will be received.
761 MCSMessage message2(BuildDownstreamMessage(kSender2, kAppId, expected_data));
762 EXPECT_TRUE(message2.IsValid());
763 ReceiveMessageFromMCS(message2);
765 EXPECT_EQ(MESSAGE_RECEIVED, last_event());
766 EXPECT_EQ(kAppId, last_app_id());
767 EXPECT_EQ(expected_data.size(), last_message().data.size());
768 EXPECT_EQ(expected_data, last_message().data);
769 EXPECT_EQ(kSender2, last_message().sender_id);
771 reset_last_event();
773 // Message from kSender3 will be dropped.
774 MCSMessage message3(BuildDownstreamMessage(kSender3, kAppId, expected_data));
775 EXPECT_TRUE(message3.IsValid());
776 ReceiveMessageFromMCS(message3);
778 EXPECT_NE(MESSAGE_RECEIVED, last_event());
779 EXPECT_NE(kAppId, last_app_id());
782 TEST_F(GCMClientImplTest, DispatchDownstreamMessageSendError) {
783 std::map<std::string, std::string> expected_data;
784 expected_data["message_type"] = "send_error";
785 expected_data["google.message_id"] = "007";
786 expected_data["error_details"] = "some details";
787 MCSMessage message(BuildDownstreamMessage(
788 kSender, kAppId, expected_data));
789 EXPECT_TRUE(message.IsValid());
790 ReceiveMessageFromMCS(message);
792 EXPECT_EQ(MESSAGE_SEND_ERROR, last_event());
793 EXPECT_EQ(kAppId, last_app_id());
794 EXPECT_EQ("007", last_error_details().message_id);
795 EXPECT_EQ(1UL, last_error_details().additional_data.size());
796 GCMClient::MessageData::const_iterator iter =
797 last_error_details().additional_data.find("error_details");
798 EXPECT_TRUE(iter != last_error_details().additional_data.end());
799 EXPECT_EQ("some details", iter->second);
802 TEST_F(GCMClientImplTest, DispatchDownstreamMessgaesDeleted) {
803 std::map<std::string, std::string> expected_data;
804 expected_data["message_type"] = "deleted_messages";
805 MCSMessage message(BuildDownstreamMessage(
806 kSender, kAppId, expected_data));
807 EXPECT_TRUE(message.IsValid());
808 ReceiveMessageFromMCS(message);
810 EXPECT_EQ(MESSAGES_DELETED, last_event());
811 EXPECT_EQ(kAppId, last_app_id());
814 TEST_F(GCMClientImplTest, SendMessage) {
815 GCMClient::OutgoingMessage message;
816 message.id = "007";
817 message.time_to_live = 500;
818 message.data["key"] = "value";
819 gcm_client()->Send(kAppId, kSender, message);
821 EXPECT_EQ(kDataMessageStanzaTag, mcs_client()->last_message_tag());
822 EXPECT_EQ(kAppId, mcs_client()->last_data_message_stanza().category());
823 EXPECT_EQ(kSender, mcs_client()->last_data_message_stanza().to());
824 EXPECT_EQ(500, mcs_client()->last_data_message_stanza().ttl());
825 EXPECT_EQ(CurrentTime(), mcs_client()->last_data_message_stanza().sent());
826 EXPECT_EQ("007", mcs_client()->last_data_message_stanza().id());
827 EXPECT_EQ("gcm@chrome.com", mcs_client()->last_data_message_stanza().from());
828 EXPECT_EQ(kSender, mcs_client()->last_data_message_stanza().to());
829 EXPECT_EQ("key", mcs_client()->last_data_message_stanza().app_data(0).key());
830 EXPECT_EQ("value",
831 mcs_client()->last_data_message_stanza().app_data(0).value());
834 TEST_F(GCMClientImplTest, SendMessageAcknowledged) {
835 ReceiveOnMessageSentToMCS(kAppId, "007", MCSClient::SENT);
836 EXPECT_EQ(MESSAGE_SEND_ACK, last_event());
837 EXPECT_EQ(kAppId, last_app_id());
838 EXPECT_EQ("007", last_message_id());
841 class GCMClientImplCheckinTest : public GCMClientImplTest {
842 public:
843 GCMClientImplCheckinTest();
844 ~GCMClientImplCheckinTest() override;
846 void SetUp() override;
849 GCMClientImplCheckinTest::GCMClientImplCheckinTest() {
852 GCMClientImplCheckinTest::~GCMClientImplCheckinTest() {
855 void GCMClientImplCheckinTest::SetUp() {
856 testing::Test::SetUp();
857 // Creating unique temp directory that will be used by GCMStore shared between
858 // GCM Client and G-services settings.
859 ASSERT_TRUE(CreateUniqueTempDir());
860 InitializeLoop();
861 // Time will be advancing one hour every time it is checked.
862 BuildGCMClient(base::TimeDelta::FromSeconds(kSettingsCheckinInterval));
863 InitializeGCMClient();
864 StartGCMClient();
867 TEST_F(GCMClientImplCheckinTest, GServicesSettingsAfterInitialCheckin) {
868 std::map<std::string, std::string> settings;
869 settings["checkin_interval"] = base::Int64ToString(kSettingsCheckinInterval);
870 settings["checkin_url"] = "http://alternative.url/checkin";
871 settings["gcm_hostname"] = "alternative.gcm.host";
872 settings["gcm_secure_port"] = "7777";
873 settings["gcm_registration_url"] = "http://alternative.url/registration";
874 CompleteCheckin(kDeviceAndroidId,
875 kDeviceSecurityToken,
876 GServicesSettings::CalculateDigest(settings),
877 settings);
878 EXPECT_EQ(base::TimeDelta::FromSeconds(kSettingsCheckinInterval),
879 gservices_settings().GetCheckinInterval());
880 EXPECT_EQ(GURL("http://alternative.url/checkin"),
881 gservices_settings().GetCheckinURL());
882 EXPECT_EQ(GURL("http://alternative.url/registration"),
883 gservices_settings().GetRegistrationURL());
884 EXPECT_EQ(GURL("https://alternative.gcm.host:7777"),
885 gservices_settings().GetMCSMainEndpoint());
886 EXPECT_EQ(GURL("https://alternative.gcm.host:443"),
887 gservices_settings().GetMCSFallbackEndpoint());
890 // This test only checks that periodic checkin happens.
891 TEST_F(GCMClientImplCheckinTest, PeriodicCheckin) {
892 std::map<std::string, std::string> settings;
893 settings["checkin_interval"] = base::IntToString(kSettingsCheckinInterval);
894 settings["checkin_url"] = "http://alternative.url/checkin";
895 settings["gcm_hostname"] = "alternative.gcm.host";
896 settings["gcm_secure_port"] = "7777";
897 settings["gcm_registration_url"] = "http://alternative.url/registration";
898 CompleteCheckin(kDeviceAndroidId,
899 kDeviceSecurityToken,
900 GServicesSettings::CalculateDigest(settings),
901 settings);
903 EXPECT_EQ(2, clock()->call_count());
905 PumpLoopUntilIdle();
906 CompleteCheckin(kDeviceAndroidId,
907 kDeviceSecurityToken,
908 GServicesSettings::CalculateDigest(settings),
909 settings);
912 TEST_F(GCMClientImplCheckinTest, LoadGSettingsFromStore) {
913 std::map<std::string, std::string> settings;
914 settings["checkin_interval"] = base::IntToString(kSettingsCheckinInterval);
915 settings["checkin_url"] = "http://alternative.url/checkin";
916 settings["gcm_hostname"] = "alternative.gcm.host";
917 settings["gcm_secure_port"] = "7777";
918 settings["gcm_registration_url"] = "http://alternative.url/registration";
919 CompleteCheckin(kDeviceAndroidId,
920 kDeviceSecurityToken,
921 GServicesSettings::CalculateDigest(settings),
922 settings);
924 BuildGCMClient(base::TimeDelta());
925 InitializeGCMClient();
926 StartGCMClient();
928 EXPECT_EQ(base::TimeDelta::FromSeconds(kSettingsCheckinInterval),
929 gservices_settings().GetCheckinInterval());
930 EXPECT_EQ(GURL("http://alternative.url/checkin"),
931 gservices_settings().GetCheckinURL());
932 EXPECT_EQ(GURL("http://alternative.url/registration"),
933 gservices_settings().GetRegistrationURL());
934 EXPECT_EQ(GURL("https://alternative.gcm.host:7777"),
935 gservices_settings().GetMCSMainEndpoint());
936 EXPECT_EQ(GURL("https://alternative.gcm.host:443"),
937 gservices_settings().GetMCSFallbackEndpoint());
940 // This test only checks that periodic checkin happens.
941 TEST_F(GCMClientImplCheckinTest, CheckinWithAccounts) {
942 std::map<std::string, std::string> settings;
943 settings["checkin_interval"] = base::IntToString(kSettingsCheckinInterval);
944 settings["checkin_url"] = "http://alternative.url/checkin";
945 settings["gcm_hostname"] = "alternative.gcm.host";
946 settings["gcm_secure_port"] = "7777";
947 settings["gcm_registration_url"] = "http://alternative.url/registration";
948 CompleteCheckin(kDeviceAndroidId,
949 kDeviceSecurityToken,
950 GServicesSettings::CalculateDigest(settings),
951 settings);
953 std::vector<GCMClient::AccountTokenInfo> account_tokens;
954 account_tokens.push_back(MakeAccountToken("test_user1@gmail.com", "token1"));
955 account_tokens.push_back(MakeAccountToken("test_user2@gmail.com", "token2"));
956 gcm_client()->SetAccountTokens(account_tokens);
958 EXPECT_TRUE(device_checkin_info().last_checkin_accounts.empty());
959 EXPECT_TRUE(device_checkin_info().accounts_set);
960 EXPECT_EQ(MakeEmailToTokenMap(account_tokens),
961 device_checkin_info().account_tokens);
963 PumpLoopUntilIdle();
964 CompleteCheckin(kDeviceAndroidId,
965 kDeviceSecurityToken,
966 GServicesSettings::CalculateDigest(settings),
967 settings);
969 std::set<std::string> accounts;
970 accounts.insert("test_user1@gmail.com");
971 accounts.insert("test_user2@gmail.com");
972 EXPECT_EQ(accounts, device_checkin_info().last_checkin_accounts);
973 EXPECT_TRUE(device_checkin_info().accounts_set);
974 EXPECT_EQ(MakeEmailToTokenMap(account_tokens),
975 device_checkin_info().account_tokens);
978 // This test only checks that periodic checkin happens.
979 TEST_F(GCMClientImplCheckinTest, CheckinWhenAccountRemoved) {
980 std::map<std::string, std::string> settings;
981 settings["checkin_interval"] = base::IntToString(kSettingsCheckinInterval);
982 settings["checkin_url"] = "http://alternative.url/checkin";
983 settings["gcm_hostname"] = "alternative.gcm.host";
984 settings["gcm_secure_port"] = "7777";
985 settings["gcm_registration_url"] = "http://alternative.url/registration";
986 CompleteCheckin(kDeviceAndroidId,
987 kDeviceSecurityToken,
988 GServicesSettings::CalculateDigest(settings),
989 settings);
991 std::vector<GCMClient::AccountTokenInfo> account_tokens;
992 account_tokens.push_back(MakeAccountToken("test_user1@gmail.com", "token1"));
993 account_tokens.push_back(MakeAccountToken("test_user2@gmail.com", "token2"));
994 gcm_client()->SetAccountTokens(account_tokens);
995 PumpLoopUntilIdle();
996 CompleteCheckin(kDeviceAndroidId,
997 kDeviceSecurityToken,
998 GServicesSettings::CalculateDigest(settings),
999 settings);
1001 EXPECT_EQ(2UL, device_checkin_info().last_checkin_accounts.size());
1002 EXPECT_TRUE(device_checkin_info().accounts_set);
1003 EXPECT_EQ(MakeEmailToTokenMap(account_tokens),
1004 device_checkin_info().account_tokens);
1006 account_tokens.erase(account_tokens.begin() + 1);
1007 gcm_client()->SetAccountTokens(account_tokens);
1009 PumpLoopUntilIdle();
1010 CompleteCheckin(kDeviceAndroidId,
1011 kDeviceSecurityToken,
1012 GServicesSettings::CalculateDigest(settings),
1013 settings);
1015 std::set<std::string> accounts;
1016 accounts.insert("test_user1@gmail.com");
1017 EXPECT_EQ(accounts, device_checkin_info().last_checkin_accounts);
1018 EXPECT_TRUE(device_checkin_info().accounts_set);
1019 EXPECT_EQ(MakeEmailToTokenMap(account_tokens),
1020 device_checkin_info().account_tokens);
1023 // This test only checks that periodic checkin happens.
1024 TEST_F(GCMClientImplCheckinTest, CheckinWhenAccountReplaced) {
1025 std::map<std::string, std::string> settings;
1026 settings["checkin_interval"] = base::IntToString(kSettingsCheckinInterval);
1027 settings["checkin_url"] = "http://alternative.url/checkin";
1028 settings["gcm_hostname"] = "alternative.gcm.host";
1029 settings["gcm_secure_port"] = "7777";
1030 settings["gcm_registration_url"] = "http://alternative.url/registration";
1031 CompleteCheckin(kDeviceAndroidId,
1032 kDeviceSecurityToken,
1033 GServicesSettings::CalculateDigest(settings),
1034 settings);
1036 std::vector<GCMClient::AccountTokenInfo> account_tokens;
1037 account_tokens.push_back(MakeAccountToken("test_user1@gmail.com", "token1"));
1038 gcm_client()->SetAccountTokens(account_tokens);
1040 PumpLoopUntilIdle();
1041 CompleteCheckin(kDeviceAndroidId,
1042 kDeviceSecurityToken,
1043 GServicesSettings::CalculateDigest(settings),
1044 settings);
1046 std::set<std::string> accounts;
1047 accounts.insert("test_user1@gmail.com");
1048 EXPECT_EQ(accounts, device_checkin_info().last_checkin_accounts);
1050 // This should trigger another checkin, because the list of accounts is
1051 // different.
1052 account_tokens.clear();
1053 account_tokens.push_back(MakeAccountToken("test_user2@gmail.com", "token2"));
1054 gcm_client()->SetAccountTokens(account_tokens);
1056 PumpLoopUntilIdle();
1057 CompleteCheckin(kDeviceAndroidId,
1058 kDeviceSecurityToken,
1059 GServicesSettings::CalculateDigest(settings),
1060 settings);
1062 accounts.clear();
1063 accounts.insert("test_user2@gmail.com");
1064 EXPECT_EQ(accounts, device_checkin_info().last_checkin_accounts);
1065 EXPECT_TRUE(device_checkin_info().accounts_set);
1066 EXPECT_EQ(MakeEmailToTokenMap(account_tokens),
1067 device_checkin_info().account_tokens);
1070 class GCMClientImplStartAndStopTest : public GCMClientImplTest {
1071 public:
1072 GCMClientImplStartAndStopTest();
1073 ~GCMClientImplStartAndStopTest() override;
1075 void SetUp() override;
1077 void DefaultCompleteCheckin();
1080 GCMClientImplStartAndStopTest::GCMClientImplStartAndStopTest() {
1083 GCMClientImplStartAndStopTest::~GCMClientImplStartAndStopTest() {
1086 void GCMClientImplStartAndStopTest::SetUp() {
1087 testing::Test::SetUp();
1088 ASSERT_TRUE(CreateUniqueTempDir());
1089 InitializeLoop();
1090 BuildGCMClient(base::TimeDelta());
1091 InitializeGCMClient();
1094 void GCMClientImplStartAndStopTest::DefaultCompleteCheckin() {
1095 SetUpUrlFetcherFactory();
1096 CompleteCheckin(kDeviceAndroidId,
1097 kDeviceSecurityToken,
1098 std::string(),
1099 std::map<std::string, std::string>());
1100 PumpLoopUntilIdle();
1103 TEST_F(GCMClientImplStartAndStopTest, StartStopAndRestart) {
1104 // GCMClientImpl should be in INITIALIZED state at first.
1105 EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
1107 // Delay start the GCM.
1108 gcm_client()->Start(GCMClient::DELAYED_START);
1109 PumpLoopUntilIdle();
1110 EXPECT_EQ(GCMClientImpl::LOADED, gcm_client_state());
1112 // Stop the GCM.
1113 gcm_client()->Stop();
1114 PumpLoopUntilIdle();
1115 EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
1117 // Restart the GCM without delay.
1118 gcm_client()->Start(GCMClient::IMMEDIATE_START);
1119 PumpLoopUntilIdle();
1120 EXPECT_EQ(GCMClientImpl::INITIAL_DEVICE_CHECKIN, gcm_client_state());
1123 TEST_F(GCMClientImplStartAndStopTest, StartAndStopImmediately) {
1124 // GCMClientImpl should be in INITIALIZED state at first.
1125 EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
1127 // Delay start the GCM and then stop it immediately.
1128 gcm_client()->Start(GCMClient::DELAYED_START);
1129 gcm_client()->Stop();
1130 PumpLoopUntilIdle();
1131 EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
1133 // Start the GCM and then stop it immediately.
1134 gcm_client()->Start(GCMClient::IMMEDIATE_START);
1135 gcm_client()->Stop();
1136 PumpLoopUntilIdle();
1137 EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
1140 TEST_F(GCMClientImplStartAndStopTest, StartStopAndRestartImmediately) {
1141 // GCMClientImpl should be in INITIALIZED state at first.
1142 EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
1144 // Delay start the GCM and then stop and restart it immediately.
1145 gcm_client()->Start(GCMClient::DELAYED_START);
1146 gcm_client()->Stop();
1147 gcm_client()->Start(GCMClient::DELAYED_START);
1148 PumpLoopUntilIdle();
1149 EXPECT_EQ(GCMClientImpl::LOADED, gcm_client_state());
1151 // Start the GCM and then stop and restart it immediately.
1152 gcm_client()->Start(GCMClient::IMMEDIATE_START);
1153 gcm_client()->Stop();
1154 gcm_client()->Start(GCMClient::IMMEDIATE_START);
1155 PumpLoopUntilIdle();
1156 EXPECT_EQ(GCMClientImpl::INITIAL_DEVICE_CHECKIN, gcm_client_state());
1159 TEST_F(GCMClientImplStartAndStopTest, DelayStart) {
1160 // GCMClientImpl should be in INITIALIZED state at first.
1161 EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
1163 // Delay start the GCM.
1164 gcm_client()->Start(GCMClient::DELAYED_START);
1165 PumpLoopUntilIdle();
1166 EXPECT_EQ(GCMClientImpl::LOADED, gcm_client_state());
1168 // Start the GCM immediately and complete the checkin.
1169 gcm_client()->Start(GCMClient::IMMEDIATE_START);
1170 PumpLoopUntilIdle();
1171 EXPECT_EQ(GCMClientImpl::INITIAL_DEVICE_CHECKIN, gcm_client_state());
1172 DefaultCompleteCheckin();
1173 EXPECT_EQ(GCMClientImpl::READY, gcm_client_state());
1175 // Registration.
1176 std::vector<std::string> senders;
1177 senders.push_back("sender");
1178 Register(kAppId, senders);
1179 CompleteRegistration("reg_id");
1180 EXPECT_EQ(GCMClientImpl::READY, gcm_client_state());
1182 // Stop the GCM.
1183 gcm_client()->Stop();
1184 PumpLoopUntilIdle();
1185 EXPECT_EQ(GCMClientImpl::INITIALIZED, gcm_client_state());
1187 // Delay start the GCM. GCM is indeed started without delay because the
1188 // registration record has been found.
1189 gcm_client()->Start(GCMClient::DELAYED_START);
1190 PumpLoopUntilIdle();
1191 EXPECT_EQ(GCMClientImpl::READY, gcm_client_state());
1194 // Test for known account mappings and last token fetching time being passed
1195 // to OnGCMReady.
1196 TEST_F(GCMClientImplStartAndStopTest, OnGCMReadyAccountsAndTokenFetchingTime) {
1197 // Start the GCM and wait until it is ready.
1198 gcm_client()->Start(GCMClient::IMMEDIATE_START);
1199 PumpLoopUntilIdle();
1200 DefaultCompleteCheckin();
1202 base::Time expected_time = base::Time::Now();
1203 gcm_client()->SetLastTokenFetchTime(expected_time);
1204 AccountMapping expected_mapping;
1205 expected_mapping.account_id = "accId";
1206 expected_mapping.email = "email@gmail.com";
1207 expected_mapping.status = AccountMapping::MAPPED;
1208 expected_mapping.status_change_timestamp = expected_time;
1209 gcm_client()->UpdateAccountMapping(expected_mapping);
1210 PumpLoopUntilIdle();
1212 // Stop the GCM.
1213 gcm_client()->Stop();
1214 PumpLoopUntilIdle();
1216 // Restart the GCM.
1217 gcm_client()->Start(GCMClient::IMMEDIATE_START);
1218 PumpLoopUntilIdle();
1220 EXPECT_EQ(LOADING_COMPLETED, last_event());
1221 EXPECT_EQ(expected_time, last_token_fetch_time());
1222 ASSERT_EQ(1UL, last_account_mappings().size());
1223 const AccountMapping& actual_mapping = last_account_mappings()[0];
1224 EXPECT_EQ(expected_mapping.account_id, actual_mapping.account_id);
1225 EXPECT_EQ(expected_mapping.email, actual_mapping.email);
1226 EXPECT_EQ(expected_mapping.status, actual_mapping.status);
1227 EXPECT_EQ(expected_mapping.status_change_timestamp,
1228 actual_mapping.status_change_timestamp);
1232 class GCMClientInstanceIDTest : public GCMClientImplTest {
1233 public:
1234 GCMClientInstanceIDTest();
1235 ~GCMClientInstanceIDTest() override;
1237 void AddInstanceID(const std::string& app_id,
1238 const std::string& instance_id);
1239 void RemoveInstanceID(const std::string& app_id);
1240 void GetToken(const std::string& app_id,
1241 const std::string& authorized_entity,
1242 const std::string& scope);
1243 void DeleteToken(const std::string& app_id,
1244 const std::string& authorized_entity,
1245 const std::string& scope);
1246 void CompleteDeleteToken();
1247 bool ExistsToken(const std::string& app_id,
1248 const std::string& authorized_entity,
1249 const std::string& scope) const;
1252 GCMClientInstanceIDTest::GCMClientInstanceIDTest() {
1255 GCMClientInstanceIDTest::~GCMClientInstanceIDTest() {
1258 void GCMClientInstanceIDTest::AddInstanceID(const std::string& app_id,
1259 const std::string& instance_id) {
1260 gcm_client()->AddInstanceIDData(app_id, instance_id, "123");
1263 void GCMClientInstanceIDTest::RemoveInstanceID(const std::string& app_id) {
1264 gcm_client()->RemoveInstanceIDData(app_id);
1267 void GCMClientInstanceIDTest::GetToken(const std::string& app_id,
1268 const std::string& authorized_entity,
1269 const std::string& scope) {
1270 scoped_ptr<InstanceIDTokenInfo> instance_id_info(new InstanceIDTokenInfo);
1271 instance_id_info->app_id = app_id;
1272 instance_id_info->authorized_entity = authorized_entity;
1273 instance_id_info->scope = scope;
1274 gcm_client()->Register(
1275 make_linked_ptr<RegistrationInfo>(instance_id_info.release()));
1278 void GCMClientInstanceIDTest::DeleteToken(const std::string& app_id,
1279 const std::string& authorized_entity,
1280 const std::string& scope) {
1281 scoped_ptr<InstanceIDTokenInfo> instance_id_info(new InstanceIDTokenInfo);
1282 instance_id_info->app_id = app_id;
1283 instance_id_info->authorized_entity = authorized_entity;
1284 instance_id_info->scope = scope;
1285 gcm_client()->Unregister(
1286 make_linked_ptr<RegistrationInfo>(instance_id_info.release()));
1289 void GCMClientInstanceIDTest::CompleteDeleteToken() {
1290 std::string response(kDeleteTokenResponse);
1291 net::TestURLFetcher* fetcher = url_fetcher_factory()->GetFetcherByID(0);
1292 ASSERT_TRUE(fetcher);
1293 fetcher->set_response_code(net::HTTP_OK);
1294 fetcher->SetResponseString(response);
1295 fetcher->delegate()->OnURLFetchComplete(fetcher);
1298 bool GCMClientInstanceIDTest::ExistsToken(const std::string& app_id,
1299 const std::string& authorized_entity,
1300 const std::string& scope) const {
1301 scoped_ptr<InstanceIDTokenInfo> instance_id_info(new InstanceIDTokenInfo);
1302 instance_id_info->app_id = app_id;
1303 instance_id_info->authorized_entity = authorized_entity;
1304 instance_id_info->scope = scope;
1305 return gcm_client()->registrations_.count(
1306 make_linked_ptr<RegistrationInfo>(instance_id_info.release())) > 0;
1309 TEST_F(GCMClientInstanceIDTest, GetToken) {
1310 AddInstanceID(kAppId, kInstanceID);
1312 // Get a token.
1313 EXPECT_FALSE(ExistsToken(kAppId, kSender, kScope));
1314 GetToken(kAppId, kSender, kScope);
1315 CompleteRegistration("token1");
1317 EXPECT_EQ(REGISTRATION_COMPLETED, last_event());
1318 EXPECT_EQ(kAppId, last_app_id());
1319 EXPECT_EQ("token1", last_registration_id());
1320 EXPECT_EQ(GCMClient::SUCCESS, last_result());
1321 EXPECT_TRUE(ExistsToken(kAppId, kSender, kScope));
1323 // Get another token.
1324 EXPECT_FALSE(ExistsToken(kAppId, kSender2, kScope));
1325 GetToken(kAppId, kSender2, kScope);
1326 CompleteRegistration("token2");
1328 EXPECT_EQ(REGISTRATION_COMPLETED, last_event());
1329 EXPECT_EQ(kAppId, last_app_id());
1330 EXPECT_EQ("token2", last_registration_id());
1331 EXPECT_EQ(GCMClient::SUCCESS, last_result());
1332 EXPECT_TRUE(ExistsToken(kAppId, kSender2, kScope));
1333 // The 1st token still exists.
1334 EXPECT_TRUE(ExistsToken(kAppId, kSender, kScope));
1337 TEST_F(GCMClientInstanceIDTest, DeleteSingleToken) {
1338 AddInstanceID(kAppId, kInstanceID);
1340 // Get a token.
1341 EXPECT_FALSE(ExistsToken(kAppId, kSender, kScope));
1342 GetToken(kAppId, kSender, kScope);
1343 CompleteRegistration("token1");
1345 EXPECT_EQ(REGISTRATION_COMPLETED, last_event());
1346 EXPECT_EQ(kAppId, last_app_id());
1347 EXPECT_EQ("token1", last_registration_id());
1348 EXPECT_EQ(GCMClient::SUCCESS, last_result());
1349 EXPECT_TRUE(ExistsToken(kAppId, kSender, kScope));
1351 // Get another token.
1352 EXPECT_FALSE(ExistsToken(kAppId, kSender2, kScope));
1353 GetToken(kAppId, kSender2, kScope);
1354 CompleteRegistration("token2");
1356 EXPECT_EQ(REGISTRATION_COMPLETED, last_event());
1357 EXPECT_EQ(kAppId, last_app_id());
1358 EXPECT_EQ("token2", last_registration_id());
1359 EXPECT_EQ(GCMClient::SUCCESS, last_result());
1360 EXPECT_TRUE(ExistsToken(kAppId, kSender2, kScope));
1361 // The 1st token still exists.
1362 EXPECT_TRUE(ExistsToken(kAppId, kSender, kScope));
1364 // Delete the 2nd token.
1365 DeleteToken(kAppId, kSender2, kScope);
1366 CompleteDeleteToken();
1368 EXPECT_EQ(UNREGISTRATION_COMPLETED, last_event());
1369 EXPECT_EQ(kAppId, last_app_id());
1370 EXPECT_EQ(GCMClient::SUCCESS, last_result());
1371 // The 2nd token is gone while the 1st token still exists.
1372 EXPECT_TRUE(ExistsToken(kAppId, kSender, kScope));
1373 EXPECT_FALSE(ExistsToken(kAppId, kSender2, kScope));
1375 // Delete the 1st token.
1376 DeleteToken(kAppId, kSender, kScope);
1377 CompleteDeleteToken();
1379 EXPECT_EQ(UNREGISTRATION_COMPLETED, last_event());
1380 EXPECT_EQ(kAppId, last_app_id());
1381 EXPECT_EQ(GCMClient::SUCCESS, last_result());
1382 // Both tokens are gone now.
1383 EXPECT_FALSE(ExistsToken(kAppId, kSender, kScope));
1384 EXPECT_FALSE(ExistsToken(kAppId, kSender, kScope));
1387 TEST_F(GCMClientInstanceIDTest, DeleteMultiTokens) {
1388 AddInstanceID(kAppId, kInstanceID);
1390 // Get a token.
1391 EXPECT_FALSE(ExistsToken(kAppId, kSender, kScope));
1392 GetToken(kAppId, kSender, kScope);
1393 CompleteRegistration("token1");
1395 EXPECT_EQ(REGISTRATION_COMPLETED, last_event());
1396 EXPECT_EQ(kAppId, last_app_id());
1397 EXPECT_EQ("token1", last_registration_id());
1398 EXPECT_EQ(GCMClient::SUCCESS, last_result());
1399 EXPECT_TRUE(ExistsToken(kAppId, kSender, kScope));
1401 // Get another token.
1402 EXPECT_FALSE(ExistsToken(kAppId, kSender2, kScope));
1403 GetToken(kAppId, kSender2, kScope);
1404 CompleteRegistration("token2");
1406 EXPECT_EQ(REGISTRATION_COMPLETED, last_event());
1407 EXPECT_EQ(kAppId, last_app_id());
1408 EXPECT_EQ("token2", last_registration_id());
1409 EXPECT_EQ(GCMClient::SUCCESS, last_result());
1410 EXPECT_TRUE(ExistsToken(kAppId, kSender2, kScope));
1411 // The 1st token still exists.
1412 EXPECT_TRUE(ExistsToken(kAppId, kSender, kScope));
1414 // Delete all tokens.
1415 DeleteToken(kAppId, "*", "*");
1416 CompleteDeleteToken();
1418 EXPECT_EQ(UNREGISTRATION_COMPLETED, last_event());
1419 EXPECT_EQ(kAppId, last_app_id());
1420 EXPECT_EQ(GCMClient::SUCCESS, last_result());
1421 // All tokens are gone now.
1422 EXPECT_FALSE(ExistsToken(kAppId, kSender, kScope));
1423 EXPECT_FALSE(ExistsToken(kAppId, kSender, kScope));
1426 } // namespace gcm