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_driver_desktop.h"
8 #include "base/bind_helpers.h"
9 #include "base/files/scoped_temp_dir.h"
10 #include "base/location.h"
11 #include "base/message_loop/message_loop.h"
12 #include "base/message_loop/message_loop_proxy.h"
13 #include "base/metrics/field_trial.h"
14 #include "base/prefs/pref_registry_simple.h"
15 #include "base/prefs/testing_pref_service.h"
16 #include "base/run_loop.h"
17 #include "base/strings/string_util.h"
18 #include "base/test/test_simple_task_runner.h"
19 #include "base/threading/thread.h"
20 #include "components/gcm_driver/fake_gcm_app_handler.h"
21 #include "components/gcm_driver/fake_gcm_client.h"
22 #include "components/gcm_driver/fake_gcm_client_factory.h"
23 #include "components/gcm_driver/gcm_app_handler.h"
24 #include "components/gcm_driver/gcm_channel_status_request.h"
25 #include "components/gcm_driver/gcm_channel_status_syncer.h"
26 #include "components/gcm_driver/gcm_client_factory.h"
27 #include "components/gcm_driver/gcm_connection_observer.h"
28 #include "net/url_request/test_url_fetcher_factory.h"
29 #include "net/url_request/url_fetcher_delegate.h"
30 #include "net/url_request/url_request_context_getter.h"
31 #include "net/url_request/url_request_test_util.h"
32 #include "sync/protocol/experiment_status.pb.h"
33 #include "sync/protocol/experiments_specifics.pb.h"
34 #include "testing/gtest/include/gtest/gtest.h"
40 const char kTestAppID1
[] = "TestApp1";
41 const char kTestAppID2
[] = "TestApp2";
42 const char kUserID1
[] = "user1";
44 class FakeGCMConnectionObserver
: public GCMConnectionObserver
{
46 FakeGCMConnectionObserver();
47 ~FakeGCMConnectionObserver() override
;
49 // gcm::GCMConnectionObserver implementation:
50 void OnConnected(const net::IPEndPoint
& ip_endpoint
) override
;
51 void OnDisconnected() override
;
53 bool connected() const { return connected_
; }
59 FakeGCMConnectionObserver::FakeGCMConnectionObserver() : connected_(false) {
62 FakeGCMConnectionObserver::~FakeGCMConnectionObserver() {
65 void FakeGCMConnectionObserver::OnConnected(
66 const net::IPEndPoint
& ip_endpoint
) {
70 void FakeGCMConnectionObserver::OnDisconnected() {
74 void PumpCurrentLoop() {
75 base::MessageLoop::ScopedNestableTaskAllower
76 nestable_task_allower(base::MessageLoop::current());
77 base::RunLoop().RunUntilIdle();
84 std::vector
<std::string
> ToSenderList(const std::string
& sender_ids
) {
85 std::vector
<std::string
> senders
;
86 Tokenize(sender_ids
, ",", &senders
);
92 class GCMDriverTest
: public testing::Test
{
100 ~GCMDriverTest() override
;
103 void SetUp() override
;
104 void TearDown() override
;
106 GCMDriverDesktop
* driver() { return driver_
.get(); }
107 FakeGCMAppHandler
* gcm_app_handler() { return gcm_app_handler_
.get(); }
108 FakeGCMConnectionObserver
* gcm_connection_observer() {
109 return gcm_connection_observer_
.get();
111 const std::string
& registration_id() const { return registration_id_
; }
112 GCMClient::Result
registration_result() const { return registration_result_
; }
113 const std::string
& send_message_id() const { return send_message_id_
; }
114 GCMClient::Result
send_result() const { return send_result_
; }
115 GCMClient::Result
unregistration_result() const {
116 return unregistration_result_
;
123 bool HasAppHandlers() const;
124 FakeGCMClient
* GetGCMClient();
127 void ShutdownDriver();
128 void AddAppHandlers();
129 void RemoveAppHandlers();
131 void Register(const std::string
& app_id
,
132 const std::vector
<std::string
>& sender_ids
,
133 WaitToFinish wait_to_finish
);
134 void Send(const std::string
& app_id
,
135 const std::string
& receiver_id
,
136 const GCMClient::OutgoingMessage
& message
,
137 WaitToFinish wait_to_finish
);
138 void Unregister(const std::string
& app_id
, WaitToFinish wait_to_finish
);
140 void WaitForAsyncOperation();
143 void RegisterCompleted(const std::string
& registration_id
,
144 GCMClient::Result result
);
145 void SendCompleted(const std::string
& message_id
, GCMClient::Result result
);
146 void UnregisterCompleted(GCMClient::Result result
);
148 base::ScopedTempDir temp_dir_
;
149 TestingPrefServiceSimple prefs_
;
150 scoped_refptr
<base::TestSimpleTaskRunner
> task_runner_
;
151 base::MessageLoopForUI message_loop_
;
152 base::Thread io_thread_
;
153 base::FieldTrialList field_trial_list_
;
154 scoped_ptr
<GCMDriverDesktop
> driver_
;
155 scoped_ptr
<FakeGCMAppHandler
> gcm_app_handler_
;
156 scoped_ptr
<FakeGCMConnectionObserver
> gcm_connection_observer_
;
158 base::Closure async_operation_completed_callback_
;
160 std::string registration_id_
;
161 GCMClient::Result registration_result_
;
162 std::string send_message_id_
;
163 GCMClient::Result send_result_
;
164 GCMClient::Result unregistration_result_
;
166 DISALLOW_COPY_AND_ASSIGN(GCMDriverTest
);
169 GCMDriverTest::GCMDriverTest()
170 : task_runner_(new base::TestSimpleTaskRunner()),
171 io_thread_("IOThread"),
172 field_trial_list_(NULL
),
173 registration_result_(GCMClient::UNKNOWN_ERROR
),
174 send_result_(GCMClient::UNKNOWN_ERROR
),
175 unregistration_result_(GCMClient::UNKNOWN_ERROR
) {
178 GCMDriverTest::~GCMDriverTest() {
181 void GCMDriverTest::SetUp() {
182 GCMChannelStatusSyncer::RegisterPrefs(prefs_
.registry());
184 ASSERT_TRUE(temp_dir_
.CreateUniqueTempDir());
187 void GCMDriverTest::TearDown() {
198 void GCMDriverTest::PumpIOLoop() {
199 base::RunLoop run_loop
;
200 io_thread_
.message_loop_proxy()->PostTaskAndReply(
202 base::Bind(&PumpCurrentLoop
),
203 run_loop
.QuitClosure());
207 void GCMDriverTest::ClearResults() {
208 registration_id_
.clear();
209 registration_result_
= GCMClient::UNKNOWN_ERROR
;
211 send_message_id_
.clear();
212 send_result_
= GCMClient::UNKNOWN_ERROR
;
214 unregistration_result_
= GCMClient::UNKNOWN_ERROR
;
217 bool GCMDriverTest::HasAppHandlers() const {
218 return !driver_
->app_handlers().empty();
221 FakeGCMClient
* GCMDriverTest::GetGCMClient() {
222 return static_cast<FakeGCMClient
*>(driver_
->GetGCMClientForTesting());
225 void GCMDriverTest::CreateDriver() {
226 scoped_refptr
<net::URLRequestContextGetter
> request_context
=
227 new net::TestURLRequestContextGetter(io_thread_
.message_loop_proxy());
228 // TODO(johnme): Need equivalent test coverage of GCMDriverAndroid.
229 driver_
.reset(new GCMDriverDesktop(
230 scoped_ptr
<GCMClientFactory
>(
231 new FakeGCMClientFactory(base::MessageLoopProxy::current(),
232 io_thread_
.message_loop_proxy())).Pass(),
233 GCMClient::ChromeBuildInfo(),
234 "http://channel.status.request.url",
239 base::MessageLoopProxy::current(),
240 io_thread_
.message_loop_proxy(),
243 gcm_app_handler_
.reset(new FakeGCMAppHandler
);
244 gcm_connection_observer_
.reset(new FakeGCMConnectionObserver
);
246 driver_
->AddConnectionObserver(gcm_connection_observer_
.get());
249 void GCMDriverTest::ShutdownDriver() {
250 if (gcm_connection_observer())
251 driver()->RemoveConnectionObserver(gcm_connection_observer());
252 driver()->Shutdown();
255 void GCMDriverTest::AddAppHandlers() {
256 driver_
->AddAppHandler(kTestAppID1
, gcm_app_handler_
.get());
257 driver_
->AddAppHandler(kTestAppID2
, gcm_app_handler_
.get());
260 void GCMDriverTest::RemoveAppHandlers() {
261 driver_
->RemoveAppHandler(kTestAppID1
);
262 driver_
->RemoveAppHandler(kTestAppID2
);
265 void GCMDriverTest::Register(const std::string
& app_id
,
266 const std::vector
<std::string
>& sender_ids
,
267 WaitToFinish wait_to_finish
) {
268 base::RunLoop run_loop
;
269 async_operation_completed_callback_
= run_loop
.QuitClosure();
270 driver_
->Register(app_id
,
272 base::Bind(&GCMDriverTest::RegisterCompleted
,
273 base::Unretained(this)));
274 if (wait_to_finish
== WAIT
)
278 void GCMDriverTest::Send(const std::string
& app_id
,
279 const std::string
& receiver_id
,
280 const GCMClient::OutgoingMessage
& message
,
281 WaitToFinish wait_to_finish
) {
282 base::RunLoop run_loop
;
283 async_operation_completed_callback_
= run_loop
.QuitClosure();
284 driver_
->Send(app_id
,
287 base::Bind(&GCMDriverTest::SendCompleted
,
288 base::Unretained(this)));
289 if (wait_to_finish
== WAIT
)
293 void GCMDriverTest::Unregister(const std::string
& app_id
,
294 WaitToFinish wait_to_finish
) {
295 base::RunLoop run_loop
;
296 async_operation_completed_callback_
= run_loop
.QuitClosure();
297 driver_
->Unregister(app_id
,
298 base::Bind(&GCMDriverTest::UnregisterCompleted
,
299 base::Unretained(this)));
300 if (wait_to_finish
== WAIT
)
304 void GCMDriverTest::WaitForAsyncOperation() {
305 base::RunLoop run_loop
;
306 async_operation_completed_callback_
= run_loop
.QuitClosure();
310 void GCMDriverTest::RegisterCompleted(const std::string
& registration_id
,
311 GCMClient::Result result
) {
312 registration_id_
= registration_id
;
313 registration_result_
= result
;
314 if (!async_operation_completed_callback_
.is_null())
315 async_operation_completed_callback_
.Run();
318 void GCMDriverTest::SendCompleted(const std::string
& message_id
,
319 GCMClient::Result result
) {
320 send_message_id_
= message_id
;
321 send_result_
= result
;
322 if (!async_operation_completed_callback_
.is_null())
323 async_operation_completed_callback_
.Run();
326 void GCMDriverTest::UnregisterCompleted(GCMClient::Result result
) {
327 unregistration_result_
= result
;
328 if (!async_operation_completed_callback_
.is_null())
329 async_operation_completed_callback_
.Run();
332 TEST_F(GCMDriverTest
, Create
) {
333 // Create GCMDriver first. By default GCM is set to delay start.
335 EXPECT_FALSE(driver()->IsStarted());
337 // Adding an app handler will not start GCM.
341 EXPECT_FALSE(driver()->IsStarted());
342 EXPECT_FALSE(driver()->IsConnected());
343 EXPECT_FALSE(gcm_connection_observer()->connected());
345 // The GCM registration will kick off the GCM.
346 Register(kTestAppID1
, ToSenderList("sender"), GCMDriverTest::WAIT
);
347 EXPECT_TRUE(driver()->IsStarted());
348 EXPECT_TRUE(driver()->IsConnected());
349 EXPECT_TRUE(gcm_connection_observer()->connected());
352 TEST_F(GCMDriverTest
, Shutdown
) {
354 EXPECT_FALSE(HasAppHandlers());
357 EXPECT_TRUE(HasAppHandlers());
360 EXPECT_FALSE(HasAppHandlers());
361 EXPECT_FALSE(driver()->IsConnected());
362 EXPECT_FALSE(gcm_connection_observer()->connected());
365 TEST_F(GCMDriverTest
, DisableAndReenableGCM
) {
370 EXPECT_FALSE(driver()->IsStarted());
372 // The GCM registration will kick off the GCM.
373 Register(kTestAppID1
, ToSenderList("sender"), GCMDriverTest::WAIT
);
374 EXPECT_TRUE(driver()->IsStarted());
376 // Disables the GCM. GCM will be stopped.
380 EXPECT_FALSE(driver()->IsStarted());
382 // Enables the GCM. GCM will be started.
386 EXPECT_TRUE(driver()->IsStarted());
389 TEST_F(GCMDriverTest
, StartOrStopGCMOnDemand
) {
393 EXPECT_FALSE(driver()->IsStarted());
395 // Adding an app handler will not start GCM.
396 driver()->AddAppHandler(kTestAppID1
, gcm_app_handler());
399 EXPECT_FALSE(driver()->IsStarted());
401 // The GCM registration will kick off the GCM.
402 Register(kTestAppID1
, ToSenderList("sender"), GCMDriverTest::WAIT
);
403 EXPECT_TRUE(driver()->IsStarted());
405 // Add another app handler.
406 driver()->AddAppHandler(kTestAppID2
, gcm_app_handler());
409 EXPECT_TRUE(driver()->IsStarted());
411 // GCMClient remains active after one app handler is gone.
412 driver()->RemoveAppHandler(kTestAppID1
);
415 EXPECT_TRUE(driver()->IsStarted());
417 // GCMClient should be stopped after the last app handler is gone.
418 driver()->RemoveAppHandler(kTestAppID2
);
421 EXPECT_FALSE(driver()->IsStarted());
423 // GCMClient is restarted after an app handler has been added.
424 driver()->AddAppHandler(kTestAppID2
, gcm_app_handler());
427 EXPECT_TRUE(driver()->IsStarted());
430 TEST_F(GCMDriverTest
, RegisterFailed
) {
431 std::vector
<std::string
> sender_ids
;
432 sender_ids
.push_back("sender1");
436 // Registration fails when the no app handler is added.
437 Register(kTestAppID1
, sender_ids
, GCMDriverTest::WAIT
);
438 EXPECT_TRUE(registration_id().empty());
439 EXPECT_EQ(GCMClient::UNKNOWN_ERROR
, registration_result());
443 // Registration fails when GCM is disabled.
446 Register(kTestAppID1
, sender_ids
, GCMDriverTest::WAIT
);
447 EXPECT_TRUE(registration_id().empty());
448 EXPECT_EQ(GCMClient::GCM_DISABLED
, registration_result());
451 TEST_F(GCMDriverTest
, UnregisterFailed
) {
454 // Unregistration fails when the no app handler is added.
455 Unregister(kTestAppID1
, GCMDriverTest::WAIT
);
456 EXPECT_EQ(GCMClient::UNKNOWN_ERROR
, unregistration_result());
460 // Unregistration fails when GCM is disabled.
463 Unregister(kTestAppID1
, GCMDriverTest::WAIT
);
464 EXPECT_EQ(GCMClient::GCM_DISABLED
, unregistration_result());
467 TEST_F(GCMDriverTest
, SendFailed
) {
468 GCMClient::OutgoingMessage message
;
470 message
.data
["key1"] = "value1";
474 // Sending fails when the no app handler is added.
475 Send(kTestAppID1
, kUserID1
, message
, GCMDriverTest::WAIT
);
476 EXPECT_TRUE(send_message_id().empty());
477 EXPECT_EQ(GCMClient::UNKNOWN_ERROR
, send_result());
481 // Sending fails when GCM is disabled.
484 Send(kTestAppID1
, kUserID1
, message
, GCMDriverTest::WAIT
);
485 EXPECT_TRUE(send_message_id().empty());
486 EXPECT_EQ(GCMClient::GCM_DISABLED
, send_result());
489 TEST_F(GCMDriverTest
, GCMClientNotReadyBeforeRegistration
) {
494 // Make GCMClient not ready until PerformDelayedStart is called.
495 GetGCMClient()->set_start_mode_overridding(
496 FakeGCMClient::FORCE_TO_ALWAYS_DELAY_START_GCM
);
500 // The registration is on hold until GCMClient is ready.
501 std::vector
<std::string
> sender_ids
;
502 sender_ids
.push_back("sender1");
503 Register(kTestAppID1
,
505 GCMDriverTest::DO_NOT_WAIT
);
508 EXPECT_TRUE(registration_id().empty());
509 EXPECT_EQ(GCMClient::UNKNOWN_ERROR
, registration_result());
511 // Register operation will be invoked after GCMClient becomes ready.
512 GetGCMClient()->PerformDelayedStart();
513 WaitForAsyncOperation();
514 EXPECT_FALSE(registration_id().empty());
515 EXPECT_EQ(GCMClient::SUCCESS
, registration_result());
518 TEST_F(GCMDriverTest
, GCMClientNotReadyBeforeSending
) {
523 // Make GCMClient not ready until PerformDelayedStart is called.
524 GetGCMClient()->set_start_mode_overridding(
525 FakeGCMClient::FORCE_TO_ALWAYS_DELAY_START_GCM
);
529 // The sending is on hold until GCMClient is ready.
530 GCMClient::OutgoingMessage message
;
532 message
.data
["key1"] = "value1";
533 message
.data
["key2"] = "value2";
534 Send(kTestAppID1
, kUserID1
, message
, GCMDriverTest::DO_NOT_WAIT
);
538 EXPECT_TRUE(send_message_id().empty());
539 EXPECT_EQ(GCMClient::UNKNOWN_ERROR
, send_result());
541 // Send operation will be invoked after GCMClient becomes ready.
542 GetGCMClient()->PerformDelayedStart();
543 WaitForAsyncOperation();
544 EXPECT_EQ(message
.id
, send_message_id());
545 EXPECT_EQ(GCMClient::SUCCESS
, send_result());
548 // Tests a single instance of GCMDriver.
549 class GCMDriverFunctionalTest
: public GCMDriverTest
{
551 GCMDriverFunctionalTest();
552 ~GCMDriverFunctionalTest() override
;
555 void SetUp() override
;
558 DISALLOW_COPY_AND_ASSIGN(GCMDriverFunctionalTest
);
561 GCMDriverFunctionalTest::GCMDriverFunctionalTest() {
564 GCMDriverFunctionalTest::~GCMDriverFunctionalTest() {
567 void GCMDriverFunctionalTest::SetUp() {
568 GCMDriverTest::SetUp();
576 TEST_F(GCMDriverFunctionalTest
, Register
) {
577 std::vector
<std::string
> sender_ids
;
578 sender_ids
.push_back("sender1");
579 Register(kTestAppID1
, sender_ids
, GCMDriverTest::WAIT
);
580 const std::string expected_registration_id
=
581 GetGCMClient()->GetRegistrationIdFromSenderIds(sender_ids
);
583 EXPECT_EQ(expected_registration_id
, registration_id());
584 EXPECT_EQ(GCMClient::SUCCESS
, registration_result());
587 TEST_F(GCMDriverFunctionalTest
, RegisterError
) {
588 std::vector
<std::string
> sender_ids
;
589 sender_ids
.push_back("sender1@error");
590 Register(kTestAppID1
, sender_ids
, GCMDriverTest::WAIT
);
592 EXPECT_TRUE(registration_id().empty());
593 EXPECT_NE(GCMClient::SUCCESS
, registration_result());
596 TEST_F(GCMDriverFunctionalTest
, RegisterAgainWithSameSenderIDs
) {
597 std::vector
<std::string
> sender_ids
;
598 sender_ids
.push_back("sender1");
599 sender_ids
.push_back("sender2");
600 Register(kTestAppID1
, sender_ids
, GCMDriverTest::WAIT
);
601 const std::string expected_registration_id
=
602 GetGCMClient()->GetRegistrationIdFromSenderIds(sender_ids
);
604 EXPECT_EQ(expected_registration_id
, registration_id());
605 EXPECT_EQ(GCMClient::SUCCESS
, registration_result());
607 // Clears the results the would be set by the Register callback in preparation
608 // to call register 2nd time.
611 // Calling register 2nd time with the same set of sender IDs but different
612 // ordering will get back the same registration ID.
613 std::vector
<std::string
> another_sender_ids
;
614 another_sender_ids
.push_back("sender2");
615 another_sender_ids
.push_back("sender1");
616 Register(kTestAppID1
, another_sender_ids
, GCMDriverTest::WAIT
);
618 EXPECT_EQ(expected_registration_id
, registration_id());
619 EXPECT_EQ(GCMClient::SUCCESS
, registration_result());
622 TEST_F(GCMDriverFunctionalTest
, RegisterAgainWithDifferentSenderIDs
) {
623 std::vector
<std::string
> sender_ids
;
624 sender_ids
.push_back("sender1");
625 Register(kTestAppID1
, sender_ids
, GCMDriverTest::WAIT
);
626 const std::string expected_registration_id
=
627 GetGCMClient()->GetRegistrationIdFromSenderIds(sender_ids
);
629 EXPECT_EQ(expected_registration_id
, registration_id());
630 EXPECT_EQ(GCMClient::SUCCESS
, registration_result());
632 // Make sender IDs different.
633 sender_ids
.push_back("sender2");
634 const std::string expected_registration_id2
=
635 GetGCMClient()->GetRegistrationIdFromSenderIds(sender_ids
);
637 // Calling register 2nd time with the different sender IDs will get back a new
639 Register(kTestAppID1
, sender_ids
, GCMDriverTest::WAIT
);
640 EXPECT_EQ(expected_registration_id2
, registration_id());
641 EXPECT_EQ(GCMClient::SUCCESS
, registration_result());
644 TEST_F(GCMDriverFunctionalTest
, UnregisterExplicitly
) {
645 std::vector
<std::string
> sender_ids
;
646 sender_ids
.push_back("sender1");
647 Register(kTestAppID1
, sender_ids
, GCMDriverTest::WAIT
);
649 EXPECT_FALSE(registration_id().empty());
650 EXPECT_EQ(GCMClient::SUCCESS
, registration_result());
652 Unregister(kTestAppID1
, GCMDriverTest::WAIT
);
654 EXPECT_EQ(GCMClient::SUCCESS
, unregistration_result());
657 TEST_F(GCMDriverFunctionalTest
, UnregisterWhenAsyncOperationPending
) {
658 std::vector
<std::string
> sender_ids
;
659 sender_ids
.push_back("sender1");
660 // First start registration without waiting for it to complete.
661 Register(kTestAppID1
, sender_ids
, GCMDriverTest::DO_NOT_WAIT
);
663 // Test that unregistration fails with async operation pending when there is a
664 // registration already in progress.
665 Unregister(kTestAppID1
, GCMDriverTest::WAIT
);
666 EXPECT_EQ(GCMClient::ASYNC_OPERATION_PENDING
,
667 unregistration_result());
669 // Complete the unregistration.
670 WaitForAsyncOperation();
671 EXPECT_EQ(GCMClient::SUCCESS
, registration_result());
673 // Start unregistration without waiting for it to complete. This time no async
674 // operation is pending.
675 Unregister(kTestAppID1
, GCMDriverTest::DO_NOT_WAIT
);
677 // Test that unregistration fails with async operation pending when there is
678 // an unregistration already in progress.
679 Unregister(kTestAppID1
, GCMDriverTest::WAIT
);
680 EXPECT_EQ(GCMClient::ASYNC_OPERATION_PENDING
,
681 unregistration_result());
684 // Complete unregistration.
685 WaitForAsyncOperation();
686 EXPECT_EQ(GCMClient::SUCCESS
, unregistration_result());
689 TEST_F(GCMDriverFunctionalTest
, RegisterWhenAsyncOperationPending
) {
690 std::vector
<std::string
> sender_ids
;
691 sender_ids
.push_back("sender1");
692 // First start registration without waiting for it to complete.
693 Register(kTestAppID1
, sender_ids
, GCMDriverTest::DO_NOT_WAIT
);
695 // Test that registration fails with async operation pending when there is a
696 // registration already in progress.
697 Register(kTestAppID1
, sender_ids
, GCMDriverTest::WAIT
);
698 EXPECT_EQ(GCMClient::ASYNC_OPERATION_PENDING
,
699 registration_result());
702 // Complete the registration.
703 WaitForAsyncOperation();
704 EXPECT_EQ(GCMClient::SUCCESS
, registration_result());
707 TEST_F(GCMDriverFunctionalTest
, RegisterAfterUnfinishedUnregister
) {
708 // Register and wait for it to complete.
709 std::vector
<std::string
> sender_ids
;
710 sender_ids
.push_back("sender1");
711 Register(kTestAppID1
, sender_ids
, GCMDriverTest::WAIT
);
712 EXPECT_EQ(GCMClient::SUCCESS
, registration_result());
713 EXPECT_EQ(GetGCMClient()->GetRegistrationIdFromSenderIds(sender_ids
),
716 // Clears the results the would be set by the Register callback in preparation
717 // to call register 2nd time.
720 // Start unregistration without waiting for it to complete.
721 Unregister(kTestAppID1
, GCMDriverTest::DO_NOT_WAIT
);
723 // Register immeidately after unregistration is not completed.
724 sender_ids
.push_back("sender2");
725 Register(kTestAppID1
, sender_ids
, GCMDriverTest::WAIT
);
727 // We need one more waiting since the waiting in Register is indeed for
728 // uncompleted Unregister.
729 WaitForAsyncOperation();
730 EXPECT_EQ(GCMClient::SUCCESS
, registration_result());
731 EXPECT_EQ(GetGCMClient()->GetRegistrationIdFromSenderIds(sender_ids
),
735 TEST_F(GCMDriverFunctionalTest
, Send
) {
736 GCMClient::OutgoingMessage message
;
737 message
.id
= "1@ack";
738 message
.data
["key1"] = "value1";
739 message
.data
["key2"] = "value2";
740 Send(kTestAppID1
, kUserID1
, message
, GCMDriverTest::WAIT
);
742 EXPECT_EQ(message
.id
, send_message_id());
743 EXPECT_EQ(GCMClient::SUCCESS
, send_result());
745 gcm_app_handler()->WaitForNotification();
746 EXPECT_EQ(message
.id
, gcm_app_handler()->acked_message_id());
747 EXPECT_EQ(kTestAppID1
, gcm_app_handler()->app_id());
750 TEST_F(GCMDriverFunctionalTest
, SendError
) {
751 GCMClient::OutgoingMessage message
;
752 // Embedding error in id will tell the mock to simulate the send error.
753 message
.id
= "1@error";
754 message
.data
["key1"] = "value1";
755 message
.data
["key2"] = "value2";
756 Send(kTestAppID1
, kUserID1
, message
, GCMDriverTest::WAIT
);
758 EXPECT_EQ(message
.id
, send_message_id());
759 EXPECT_EQ(GCMClient::SUCCESS
, send_result());
761 // Wait for the send error.
762 gcm_app_handler()->WaitForNotification();
763 EXPECT_EQ(FakeGCMAppHandler::SEND_ERROR_EVENT
,
764 gcm_app_handler()->received_event());
765 EXPECT_EQ(kTestAppID1
, gcm_app_handler()->app_id());
766 EXPECT_EQ(message
.id
,
767 gcm_app_handler()->send_error_details().message_id
);
768 EXPECT_NE(GCMClient::SUCCESS
,
769 gcm_app_handler()->send_error_details().result
);
770 EXPECT_EQ(message
.data
,
771 gcm_app_handler()->send_error_details().additional_data
);
774 TEST_F(GCMDriverFunctionalTest
, MessageReceived
) {
775 // GCM registration has to be performed otherwise GCM will not be started.
776 Register(kTestAppID1
, ToSenderList("sender"), GCMDriverTest::WAIT
);
778 GCMClient::IncomingMessage message
;
779 message
.data
["key1"] = "value1";
780 message
.data
["key2"] = "value2";
781 message
.sender_id
= "sender";
782 GetGCMClient()->ReceiveMessage(kTestAppID1
, message
);
783 gcm_app_handler()->WaitForNotification();
784 EXPECT_EQ(FakeGCMAppHandler::MESSAGE_EVENT
,
785 gcm_app_handler()->received_event());
786 EXPECT_EQ(kTestAppID1
, gcm_app_handler()->app_id());
787 EXPECT_EQ(message
.data
, gcm_app_handler()->message().data
);
788 EXPECT_TRUE(gcm_app_handler()->message().collapse_key
.empty());
789 EXPECT_EQ(message
.sender_id
, gcm_app_handler()->message().sender_id
);
792 TEST_F(GCMDriverFunctionalTest
, MessageWithCollapseKeyReceived
) {
793 // GCM registration has to be performed otherwise GCM will not be started.
794 Register(kTestAppID1
, ToSenderList("sender"), GCMDriverTest::WAIT
);
796 GCMClient::IncomingMessage message
;
797 message
.data
["key1"] = "value1";
798 message
.collapse_key
= "collapse_key_value";
799 message
.sender_id
= "sender";
800 GetGCMClient()->ReceiveMessage(kTestAppID1
, message
);
801 gcm_app_handler()->WaitForNotification();
802 EXPECT_EQ(FakeGCMAppHandler::MESSAGE_EVENT
,
803 gcm_app_handler()->received_event());
804 EXPECT_EQ(kTestAppID1
, gcm_app_handler()->app_id());
805 EXPECT_EQ(message
.data
, gcm_app_handler()->message().data
);
806 EXPECT_EQ(message
.collapse_key
,
807 gcm_app_handler()->message().collapse_key
);
810 TEST_F(GCMDriverFunctionalTest
, MessagesDeleted
) {
811 // GCM registration has to be performed otherwise GCM will not be started.
812 Register(kTestAppID1
, ToSenderList("sender"), GCMDriverTest::WAIT
);
814 GetGCMClient()->DeleteMessages(kTestAppID1
);
815 gcm_app_handler()->WaitForNotification();
816 EXPECT_EQ(FakeGCMAppHandler::MESSAGES_DELETED_EVENT
,
817 gcm_app_handler()->received_event());
818 EXPECT_EQ(kTestAppID1
, gcm_app_handler()->app_id());
821 TEST_F(GCMDriverFunctionalTest
, LastTokenFetchTime
) {
822 // GCM registration has to be performed otherwise GCM will not be started.
823 Register(kTestAppID1
, ToSenderList("sender"), GCMDriverTest::WAIT
);
825 EXPECT_EQ(base::Time(), driver()->GetLastTokenFetchTime());
826 base::Time fetch_time
= base::Time::Now();
827 driver()->SetLastTokenFetchTime(fetch_time
);
828 EXPECT_EQ(fetch_time
, driver()->GetLastTokenFetchTime());
831 // Tests a single instance of GCMDriver.
832 class GCMChannelStatusSyncerTest
: public GCMDriverTest
{
834 GCMChannelStatusSyncerTest();
835 ~GCMChannelStatusSyncerTest() override
;
838 void SetUp() override
;
840 void CompleteGCMChannelStatusRequest(bool enabled
, int poll_interval_seconds
);
841 bool CompareDelaySeconds(int64 expected_delay_seconds
,
842 int64 actual_delay_seconds
);
844 GCMChannelStatusSyncer
* syncer() {
845 return driver()->gcm_channel_status_syncer_for_testing();
849 net::TestURLFetcherFactory url_fetcher_factory_
;
851 DISALLOW_COPY_AND_ASSIGN(GCMChannelStatusSyncerTest
);
854 GCMChannelStatusSyncerTest::GCMChannelStatusSyncerTest() {
857 GCMChannelStatusSyncerTest::~GCMChannelStatusSyncerTest() {
860 void GCMChannelStatusSyncerTest::SetUp() {
861 GCMDriverTest::SetUp();
863 url_fetcher_factory_
.set_remove_fetcher_on_delete(true);
865 // Turn on all-user support.
866 ASSERT_TRUE(base::FieldTrialList::CreateFieldTrial("GCM", "Enabled"));
869 void GCMChannelStatusSyncerTest::CompleteGCMChannelStatusRequest(
870 bool enabled
, int poll_interval_seconds
) {
871 sync_pb::ExperimentStatusResponse response_proto
;
872 sync_pb::ExperimentsSpecifics
* experiment_specifics
=
873 response_proto
.add_experiment();
874 experiment_specifics
->mutable_gcm_channel()->set_enabled(enabled
);
876 if (poll_interval_seconds
)
877 response_proto
.set_poll_interval_seconds(poll_interval_seconds
);
879 std::string response_string
;
880 response_proto
.SerializeToString(&response_string
);
882 net::TestURLFetcher
* fetcher
= url_fetcher_factory_
.GetFetcherByID(0);
883 ASSERT_TRUE(fetcher
);
884 fetcher
->set_response_code(net::HTTP_OK
);
885 fetcher
->SetResponseString(response_string
);
886 fetcher
->delegate()->OnURLFetchComplete(fetcher
);
889 bool GCMChannelStatusSyncerTest::CompareDelaySeconds(
890 int64 expected_delay_seconds
, int64 actual_delay_seconds
) {
891 // Most of time, the actual delay should not be smaller than the expected
893 if (actual_delay_seconds
>= expected_delay_seconds
)
895 // It is also OK that the actual delay is a bit smaller than the expected
896 // delay in case that the test runs slowly.
897 return expected_delay_seconds
- actual_delay_seconds
< 30;
900 TEST_F(GCMChannelStatusSyncerTest
, DisableAndEnable
) {
901 // Create GCMDriver first. By default, GCM is enabled.
903 EXPECT_TRUE(driver()->gcm_enabled());
904 EXPECT_TRUE(syncer()->gcm_enabled());
906 // Remove delay such that the request could be executed immediately.
907 syncer()->set_delay_removed_for_testing(true);
909 // GCM is still enabled at this point.
911 EXPECT_TRUE(driver()->gcm_enabled());
912 EXPECT_TRUE(syncer()->gcm_enabled());
914 // Wait until the GCM channel status request gets triggered.
917 // Complete the request that disables the GCM.
918 CompleteGCMChannelStatusRequest(false, 0);
919 EXPECT_FALSE(driver()->gcm_enabled());
920 EXPECT_FALSE(syncer()->gcm_enabled());
921 EXPECT_FALSE(driver()->IsStarted());
923 // Wait until next GCM channel status request gets triggered.
926 // Complete the request that enables the GCM.
927 CompleteGCMChannelStatusRequest(true, 0);
928 EXPECT_TRUE(driver()->gcm_enabled());
929 EXPECT_TRUE(syncer()->gcm_enabled());
932 TEST_F(GCMChannelStatusSyncerTest
, DisableRestartAndEnable
) {
933 // Create GCMDriver first. By default, GCM is enabled.
935 EXPECT_TRUE(driver()->gcm_enabled());
936 EXPECT_TRUE(syncer()->gcm_enabled());
938 // Remove delay such that the request could be executed immediately.
939 syncer()->set_delay_removed_for_testing(true);
941 // GCM is still enabled at this point.
943 EXPECT_TRUE(driver()->gcm_enabled());
944 EXPECT_TRUE(syncer()->gcm_enabled());
946 // Wait until the GCM channel status request gets triggered.
949 // Complete the request that disables the GCM.
950 CompleteGCMChannelStatusRequest(false, 0);
951 EXPECT_FALSE(driver()->gcm_enabled());
952 EXPECT_FALSE(syncer()->gcm_enabled());
954 // Simulate browser start by recreating GCMDriver.
958 // Remove delay such that the request could be executed immediately.
959 syncer()->set_delay_removed_for_testing(true);
961 // GCM is still disabled.
962 EXPECT_FALSE(driver()->gcm_enabled());
963 EXPECT_FALSE(syncer()->gcm_enabled());
966 EXPECT_FALSE(driver()->gcm_enabled());
967 EXPECT_FALSE(syncer()->gcm_enabled());
969 // Wait until the GCM channel status request gets triggered.
972 // Complete the request that re-enables the GCM.
973 CompleteGCMChannelStatusRequest(true, 0);
974 EXPECT_TRUE(driver()->gcm_enabled());
975 EXPECT_TRUE(syncer()->gcm_enabled());
978 TEST_F(GCMChannelStatusSyncerTest
, FirstTimePolling
) {
983 // The 1st request should be triggered shortly without jittering.
984 EXPECT_EQ(GCMChannelStatusSyncer::first_time_delay_seconds(),
985 syncer()->current_request_delay_interval().InSeconds());
988 TEST_F(GCMChannelStatusSyncerTest
, SubsequentPollingWithDefaultInterval
) {
989 // Create GCMDriver first. GCM is not started.
992 // Remove delay such that the request could be executed immediately.
993 syncer()->set_delay_removed_for_testing(true);
995 // Now GCM is started.
998 // Wait until the GCM channel status request gets triggered.
1001 // Keep delay such that we can find out the computed delay time.
1002 syncer()->set_delay_removed_for_testing(false);
1004 // Complete the request. The default interval is intact.
1005 CompleteGCMChannelStatusRequest(true, 0);
1007 // The next request should be scheduled at the expected default interval.
1008 int64 actual_delay_seconds
=
1009 syncer()->current_request_delay_interval().InSeconds();
1010 int64 expected_delay_seconds
=
1011 GCMChannelStatusRequest::default_poll_interval_seconds();
1012 EXPECT_TRUE(CompareDelaySeconds(expected_delay_seconds
, actual_delay_seconds
))
1013 << "expected delay: " << expected_delay_seconds
1014 << " actual delay: " << actual_delay_seconds
;
1016 // Simulate browser start by recreating GCMDriver.
1021 // After start-up, the request should still be scheduled at the expected
1022 // default interval.
1023 actual_delay_seconds
=
1024 syncer()->current_request_delay_interval().InSeconds();
1025 EXPECT_TRUE(CompareDelaySeconds(expected_delay_seconds
, actual_delay_seconds
))
1026 << "expected delay: " << expected_delay_seconds
1027 << " actual delay: " << actual_delay_seconds
;
1030 TEST_F(GCMChannelStatusSyncerTest
, SubsequentPollingWithUpdatedInterval
) {
1031 // Create GCMDriver first. GCM is not started.
1034 // Remove delay such that the request could be executed immediately.
1035 syncer()->set_delay_removed_for_testing(true);
1037 // Now GCM is started.
1040 // Wait until the GCM channel status request gets triggered.
1043 // Keep delay such that we can find out the computed delay time.
1044 syncer()->set_delay_removed_for_testing(false);
1046 // Complete the request. The interval is being changed.
1047 int new_poll_interval_seconds
=
1048 GCMChannelStatusRequest::default_poll_interval_seconds() * 2;
1049 CompleteGCMChannelStatusRequest(true, new_poll_interval_seconds
);
1051 // The next request should be scheduled at the expected updated interval.
1052 int64 actual_delay_seconds
=
1053 syncer()->current_request_delay_interval().InSeconds();
1054 int64 expected_delay_seconds
= new_poll_interval_seconds
;
1055 EXPECT_TRUE(CompareDelaySeconds(expected_delay_seconds
, actual_delay_seconds
))
1056 << "expected delay: " << expected_delay_seconds
1057 << " actual delay: " << actual_delay_seconds
;
1059 // Simulate browser start by recreating GCMDriver.
1064 // After start-up, the request should still be scheduled at the expected
1065 // updated interval.
1066 actual_delay_seconds
=
1067 syncer()->current_request_delay_interval().InSeconds();
1068 EXPECT_TRUE(CompareDelaySeconds(expected_delay_seconds
, actual_delay_seconds
))
1069 << "expected delay: " << expected_delay_seconds
1070 << " actual delay: " << actual_delay_seconds
;