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/metrics/field_trial.h"
12 #include "base/prefs/pref_registry_simple.h"
13 #include "base/prefs/testing_pref_service.h"
14 #include "base/run_loop.h"
15 #include "base/strings/string_util.h"
16 #include "base/test/test_simple_task_runner.h"
17 #include "base/thread_task_runner_handle.h"
18 #include "base/threading/thread.h"
19 #include "components/gcm_driver/fake_gcm_app_handler.h"
20 #include "components/gcm_driver/fake_gcm_client.h"
21 #include "components/gcm_driver/fake_gcm_client_factory.h"
22 #include "components/gcm_driver/gcm_app_handler.h"
23 #include "components/gcm_driver/gcm_channel_status_request.h"
24 #include "components/gcm_driver/gcm_channel_status_syncer.h"
25 #include "components/gcm_driver/gcm_client_factory.h"
26 #include "components/gcm_driver/gcm_connection_observer.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_context_getter.h"
30 #include "net/url_request/url_request_test_util.h"
31 #include "sync/protocol/experiment_status.pb.h"
32 #include "sync/protocol/experiments_specifics.pb.h"
33 #include "testing/gtest/include/gtest/gtest.h"
39 const char kTestAppID1
[] = "TestApp1";
40 const char kTestAppID2
[] = "TestApp2";
41 const char kUserID1
[] = "user1";
42 const char kScope
[] = "GCM";
43 const char kInstanceID1
[] = "IID1";
44 const char kInstanceID2
[] = "IID2";
46 class FakeGCMConnectionObserver
: public GCMConnectionObserver
{
48 FakeGCMConnectionObserver();
49 ~FakeGCMConnectionObserver() override
;
51 // gcm::GCMConnectionObserver implementation:
52 void OnConnected(const net::IPEndPoint
& ip_endpoint
) override
;
53 void OnDisconnected() override
;
55 bool connected() const { return connected_
; }
61 FakeGCMConnectionObserver::FakeGCMConnectionObserver() : connected_(false) {
64 FakeGCMConnectionObserver::~FakeGCMConnectionObserver() {
67 void FakeGCMConnectionObserver::OnConnected(
68 const net::IPEndPoint
& ip_endpoint
) {
72 void FakeGCMConnectionObserver::OnDisconnected() {
76 void PumpCurrentLoop() {
77 base::MessageLoop::ScopedNestableTaskAllower
78 nestable_task_allower(base::MessageLoop::current());
79 base::RunLoop().RunUntilIdle();
86 std::vector
<std::string
> ToSenderList(const std::string
& sender_ids
) {
87 return base::SplitString(
88 sender_ids
, ",", base::KEEP_WHITESPACE
, base::SPLIT_WANT_NONEMPTY
);
93 class GCMDriverTest
: public testing::Test
{
101 ~GCMDriverTest() override
;
104 void SetUp() override
;
105 void TearDown() override
;
107 GCMDriverDesktop
* driver() { return driver_
.get(); }
108 FakeGCMAppHandler
* gcm_app_handler() { return gcm_app_handler_
.get(); }
109 FakeGCMConnectionObserver
* gcm_connection_observer() {
110 return gcm_connection_observer_
.get();
112 const std::string
& registration_id() const { return registration_id_
; }
113 GCMClient::Result
registration_result() const { return registration_result_
; }
114 const std::string
& send_message_id() const { return send_message_id_
; }
115 GCMClient::Result
send_result() const { return send_result_
; }
116 GCMClient::Result
unregistration_result() const {
117 return unregistration_result_
;
124 bool HasAppHandlers() const;
125 FakeGCMClient
* GetGCMClient();
128 void ShutdownDriver();
129 void AddAppHandlers();
130 void RemoveAppHandlers();
132 void Register(const std::string
& app_id
,
133 const std::vector
<std::string
>& sender_ids
,
134 WaitToFinish wait_to_finish
);
135 void Send(const std::string
& app_id
,
136 const std::string
& receiver_id
,
137 const OutgoingMessage
& message
,
138 WaitToFinish wait_to_finish
);
139 void Unregister(const std::string
& app_id
, WaitToFinish wait_to_finish
);
141 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 const base::Closure
& async_operation_completed_callback() const {
149 return async_operation_completed_callback_
;
151 void set_async_operation_completed_callback(const base::Closure
& callback
) {
152 async_operation_completed_callback_
= callback
;
156 base::ScopedTempDir temp_dir_
;
157 TestingPrefServiceSimple prefs_
;
158 scoped_refptr
<base::TestSimpleTaskRunner
> task_runner_
;
159 base::MessageLoopForUI message_loop_
;
160 base::Thread io_thread_
;
161 base::FieldTrialList field_trial_list_
;
162 scoped_ptr
<GCMDriverDesktop
> driver_
;
163 scoped_ptr
<FakeGCMAppHandler
> gcm_app_handler_
;
164 scoped_ptr
<FakeGCMConnectionObserver
> gcm_connection_observer_
;
166 base::Closure async_operation_completed_callback_
;
168 std::string registration_id_
;
169 GCMClient::Result registration_result_
;
170 std::string send_message_id_
;
171 GCMClient::Result send_result_
;
172 GCMClient::Result unregistration_result_
;
174 DISALLOW_COPY_AND_ASSIGN(GCMDriverTest
);
177 GCMDriverTest::GCMDriverTest()
178 : task_runner_(new base::TestSimpleTaskRunner()),
179 io_thread_("IOThread"),
180 field_trial_list_(NULL
),
181 registration_result_(GCMClient::UNKNOWN_ERROR
),
182 send_result_(GCMClient::UNKNOWN_ERROR
),
183 unregistration_result_(GCMClient::UNKNOWN_ERROR
) {
186 GCMDriverTest::~GCMDriverTest() {
189 void GCMDriverTest::SetUp() {
190 GCMChannelStatusSyncer::RegisterPrefs(prefs_
.registry());
192 ASSERT_TRUE(temp_dir_
.CreateUniqueTempDir());
195 void GCMDriverTest::TearDown() {
206 void GCMDriverTest::PumpIOLoop() {
207 base::RunLoop run_loop
;
208 io_thread_
.task_runner()->PostTaskAndReply(
209 FROM_HERE
, base::Bind(&PumpCurrentLoop
), run_loop
.QuitClosure());
213 void GCMDriverTest::ClearResults() {
214 registration_id_
.clear();
215 registration_result_
= GCMClient::UNKNOWN_ERROR
;
217 send_message_id_
.clear();
218 send_result_
= GCMClient::UNKNOWN_ERROR
;
220 unregistration_result_
= GCMClient::UNKNOWN_ERROR
;
223 bool GCMDriverTest::HasAppHandlers() const {
224 return !driver_
->app_handlers().empty();
227 FakeGCMClient
* GCMDriverTest::GetGCMClient() {
228 return static_cast<FakeGCMClient
*>(driver_
->GetGCMClientForTesting());
231 void GCMDriverTest::CreateDriver() {
232 scoped_refptr
<net::URLRequestContextGetter
> request_context
=
233 new net::TestURLRequestContextGetter(io_thread_
.task_runner());
234 // TODO(johnme): Need equivalent test coverage of GCMDriverAndroid.
235 driver_
.reset(new GCMDriverDesktop(
236 scoped_ptr
<GCMClientFactory
>(
237 new FakeGCMClientFactory(base::ThreadTaskRunnerHandle::Get(),
238 io_thread_
.task_runner())).Pass(),
239 GCMClient::ChromeBuildInfo(), "http://channel.status.request.url",
240 "user-agent-string", &prefs_
, temp_dir_
.path(), request_context
,
241 base::ThreadTaskRunnerHandle::Get(), io_thread_
.task_runner(),
244 gcm_app_handler_
.reset(new FakeGCMAppHandler
);
245 gcm_connection_observer_
.reset(new FakeGCMConnectionObserver
);
247 driver_
->AddConnectionObserver(gcm_connection_observer_
.get());
250 void GCMDriverTest::ShutdownDriver() {
251 if (gcm_connection_observer())
252 driver()->RemoveConnectionObserver(gcm_connection_observer());
253 driver()->Shutdown();
256 void GCMDriverTest::AddAppHandlers() {
257 driver_
->AddAppHandler(kTestAppID1
, gcm_app_handler_
.get());
258 driver_
->AddAppHandler(kTestAppID2
, gcm_app_handler_
.get());
261 void GCMDriverTest::RemoveAppHandlers() {
262 driver_
->RemoveAppHandler(kTestAppID1
);
263 driver_
->RemoveAppHandler(kTestAppID2
);
266 void GCMDriverTest::Register(const std::string
& app_id
,
267 const std::vector
<std::string
>& sender_ids
,
268 WaitToFinish wait_to_finish
) {
269 base::RunLoop run_loop
;
270 async_operation_completed_callback_
= run_loop
.QuitClosure();
271 driver_
->Register(app_id
,
273 base::Bind(&GCMDriverTest::RegisterCompleted
,
274 base::Unretained(this)));
275 if (wait_to_finish
== WAIT
)
279 void GCMDriverTest::Send(const std::string
& app_id
,
280 const std::string
& receiver_id
,
281 const OutgoingMessage
& message
,
282 WaitToFinish wait_to_finish
) {
283 base::RunLoop run_loop
;
284 async_operation_completed_callback_
= run_loop
.QuitClosure();
285 driver_
->Send(app_id
,
288 base::Bind(&GCMDriverTest::SendCompleted
,
289 base::Unretained(this)));
290 if (wait_to_finish
== WAIT
)
294 void GCMDriverTest::Unregister(const std::string
& app_id
,
295 WaitToFinish wait_to_finish
) {
296 base::RunLoop run_loop
;
297 async_operation_completed_callback_
= run_loop
.QuitClosure();
298 driver_
->Unregister(app_id
,
299 base::Bind(&GCMDriverTest::UnregisterCompleted
,
300 base::Unretained(this)));
301 if (wait_to_finish
== WAIT
)
305 void GCMDriverTest::WaitForAsyncOperation() {
306 base::RunLoop run_loop
;
307 async_operation_completed_callback_
= run_loop
.QuitClosure();
311 void GCMDriverTest::RegisterCompleted(const std::string
& registration_id
,
312 GCMClient::Result result
) {
313 registration_id_
= registration_id
;
314 registration_result_
= result
;
315 if (!async_operation_completed_callback_
.is_null())
316 async_operation_completed_callback_
.Run();
319 void GCMDriverTest::SendCompleted(const std::string
& message_id
,
320 GCMClient::Result result
) {
321 send_message_id_
= message_id
;
322 send_result_
= result
;
323 if (!async_operation_completed_callback_
.is_null())
324 async_operation_completed_callback_
.Run();
327 void GCMDriverTest::UnregisterCompleted(GCMClient::Result result
) {
328 unregistration_result_
= result
;
329 if (!async_operation_completed_callback_
.is_null())
330 async_operation_completed_callback_
.Run();
333 TEST_F(GCMDriverTest
, Create
) {
334 // Create GCMDriver first. By default GCM is set to delay start.
336 EXPECT_FALSE(driver()->IsStarted());
338 // Adding an app handler will not start GCM.
342 EXPECT_FALSE(driver()->IsStarted());
343 EXPECT_FALSE(driver()->IsConnected());
344 EXPECT_FALSE(gcm_connection_observer()->connected());
346 // The GCM registration will kick off the GCM.
347 Register(kTestAppID1
, ToSenderList("sender"), GCMDriverTest::WAIT
);
348 EXPECT_TRUE(driver()->IsStarted());
349 EXPECT_TRUE(driver()->IsConnected());
350 EXPECT_TRUE(gcm_connection_observer()->connected());
353 TEST_F(GCMDriverTest
, Shutdown
) {
355 EXPECT_FALSE(HasAppHandlers());
358 EXPECT_TRUE(HasAppHandlers());
361 EXPECT_FALSE(HasAppHandlers());
362 EXPECT_FALSE(driver()->IsConnected());
363 EXPECT_FALSE(gcm_connection_observer()->connected());
366 TEST_F(GCMDriverTest
, DisableAndReenableGCM
) {
371 EXPECT_FALSE(driver()->IsStarted());
373 // The GCM registration will kick off the GCM.
374 Register(kTestAppID1
, ToSenderList("sender"), GCMDriverTest::WAIT
);
375 EXPECT_TRUE(driver()->IsStarted());
377 // Disables the GCM. GCM will be stopped.
381 EXPECT_FALSE(driver()->IsStarted());
383 // Enables the GCM. GCM will be started.
387 EXPECT_TRUE(driver()->IsStarted());
390 TEST_F(GCMDriverTest
, StartOrStopGCMOnDemand
) {
394 EXPECT_FALSE(driver()->IsStarted());
396 // Adding an app handler will not start GCM.
397 driver()->AddAppHandler(kTestAppID1
, gcm_app_handler());
400 EXPECT_FALSE(driver()->IsStarted());
402 // The GCM registration will kick off the GCM.
403 Register(kTestAppID1
, ToSenderList("sender"), GCMDriverTest::WAIT
);
404 EXPECT_TRUE(driver()->IsStarted());
406 // Add another app handler.
407 driver()->AddAppHandler(kTestAppID2
, gcm_app_handler());
410 EXPECT_TRUE(driver()->IsStarted());
412 // GCMClient remains active after one app handler is gone.
413 driver()->RemoveAppHandler(kTestAppID1
);
416 EXPECT_TRUE(driver()->IsStarted());
418 // GCMClient should be stopped after the last app handler is gone.
419 driver()->RemoveAppHandler(kTestAppID2
);
422 EXPECT_FALSE(driver()->IsStarted());
424 // GCMClient is restarted after an app handler has been added.
425 driver()->AddAppHandler(kTestAppID2
, gcm_app_handler());
428 EXPECT_TRUE(driver()->IsStarted());
431 TEST_F(GCMDriverTest
, RegisterFailed
) {
432 std::vector
<std::string
> sender_ids
;
433 sender_ids
.push_back("sender1");
437 // Registration fails when the no app handler is added.
438 Register(kTestAppID1
, sender_ids
, GCMDriverTest::WAIT
);
439 EXPECT_TRUE(registration_id().empty());
440 EXPECT_EQ(GCMClient::UNKNOWN_ERROR
, registration_result());
444 // Registration fails when GCM is disabled.
447 Register(kTestAppID1
, sender_ids
, GCMDriverTest::WAIT
);
448 EXPECT_TRUE(registration_id().empty());
449 EXPECT_EQ(GCMClient::GCM_DISABLED
, registration_result());
452 TEST_F(GCMDriverTest
, UnregisterFailed
) {
455 // Unregistration fails when the no app handler is added.
456 Unregister(kTestAppID1
, GCMDriverTest::WAIT
);
457 EXPECT_EQ(GCMClient::UNKNOWN_ERROR
, unregistration_result());
461 // Unregistration fails when GCM is disabled.
464 Unregister(kTestAppID1
, GCMDriverTest::WAIT
);
465 EXPECT_EQ(GCMClient::GCM_DISABLED
, unregistration_result());
468 TEST_F(GCMDriverTest
, SendFailed
) {
469 OutgoingMessage message
;
471 message
.data
["key1"] = "value1";
475 // Sending fails when the no app handler is added.
476 Send(kTestAppID1
, kUserID1
, message
, GCMDriverTest::WAIT
);
477 EXPECT_TRUE(send_message_id().empty());
478 EXPECT_EQ(GCMClient::UNKNOWN_ERROR
, send_result());
482 // Sending fails when GCM is disabled.
485 Send(kTestAppID1
, kUserID1
, message
, GCMDriverTest::WAIT
);
486 EXPECT_TRUE(send_message_id().empty());
487 EXPECT_EQ(GCMClient::GCM_DISABLED
, send_result());
490 TEST_F(GCMDriverTest
, GCMClientNotReadyBeforeRegistration
) {
495 // Make GCMClient not ready until PerformDelayedStart is called.
496 GetGCMClient()->set_start_mode_overridding(
497 FakeGCMClient::FORCE_TO_ALWAYS_DELAY_START_GCM
);
501 // The registration is on hold until GCMClient is ready.
502 std::vector
<std::string
> sender_ids
;
503 sender_ids
.push_back("sender1");
504 Register(kTestAppID1
,
506 GCMDriverTest::DO_NOT_WAIT
);
509 EXPECT_TRUE(registration_id().empty());
510 EXPECT_EQ(GCMClient::UNKNOWN_ERROR
, registration_result());
512 // Register operation will be invoked after GCMClient becomes ready.
513 GetGCMClient()->PerformDelayedStart();
514 WaitForAsyncOperation();
515 EXPECT_FALSE(registration_id().empty());
516 EXPECT_EQ(GCMClient::SUCCESS
, registration_result());
519 TEST_F(GCMDriverTest
, GCMClientNotReadyBeforeSending
) {
524 // Make GCMClient not ready until PerformDelayedStart is called.
525 GetGCMClient()->set_start_mode_overridding(
526 FakeGCMClient::FORCE_TO_ALWAYS_DELAY_START_GCM
);
530 // The sending is on hold until GCMClient is ready.
531 OutgoingMessage message
;
533 message
.data
["key1"] = "value1";
534 message
.data
["key2"] = "value2";
535 Send(kTestAppID1
, kUserID1
, message
, GCMDriverTest::DO_NOT_WAIT
);
539 EXPECT_TRUE(send_message_id().empty());
540 EXPECT_EQ(GCMClient::UNKNOWN_ERROR
, send_result());
542 // Send operation will be invoked after GCMClient becomes ready.
543 GetGCMClient()->PerformDelayedStart();
544 WaitForAsyncOperation();
545 EXPECT_EQ(message
.id
, send_message_id());
546 EXPECT_EQ(GCMClient::SUCCESS
, send_result());
549 // Tests a single instance of GCMDriver.
550 class GCMDriverFunctionalTest
: public GCMDriverTest
{
552 GCMDriverFunctionalTest();
553 ~GCMDriverFunctionalTest() override
;
556 void SetUp() override
;
559 DISALLOW_COPY_AND_ASSIGN(GCMDriverFunctionalTest
);
562 GCMDriverFunctionalTest::GCMDriverFunctionalTest() {
565 GCMDriverFunctionalTest::~GCMDriverFunctionalTest() {
568 void GCMDriverFunctionalTest::SetUp() {
569 GCMDriverTest::SetUp();
577 TEST_F(GCMDriverFunctionalTest
, Register
) {
578 std::vector
<std::string
> sender_ids
;
579 sender_ids
.push_back("sender1");
580 Register(kTestAppID1
, sender_ids
, GCMDriverTest::WAIT
);
581 const std::string expected_registration_id
=
582 FakeGCMClient::GenerateGCMRegistrationID(sender_ids
);
584 EXPECT_EQ(expected_registration_id
, registration_id());
585 EXPECT_EQ(GCMClient::SUCCESS
, registration_result());
588 TEST_F(GCMDriverFunctionalTest
, RegisterError
) {
589 std::vector
<std::string
> sender_ids
;
590 sender_ids
.push_back("sender1@error");
591 Register(kTestAppID1
, sender_ids
, GCMDriverTest::WAIT
);
593 EXPECT_TRUE(registration_id().empty());
594 EXPECT_NE(GCMClient::SUCCESS
, registration_result());
597 TEST_F(GCMDriverFunctionalTest
, RegisterAgainWithSameSenderIDs
) {
598 std::vector
<std::string
> sender_ids
;
599 sender_ids
.push_back("sender1");
600 sender_ids
.push_back("sender2");
601 Register(kTestAppID1
, sender_ids
, GCMDriverTest::WAIT
);
602 const std::string expected_registration_id
=
603 FakeGCMClient::GenerateGCMRegistrationID(sender_ids
);
605 EXPECT_EQ(expected_registration_id
, registration_id());
606 EXPECT_EQ(GCMClient::SUCCESS
, registration_result());
608 // Clears the results the would be set by the Register callback in preparation
609 // to call register 2nd time.
612 // Calling register 2nd time with the same set of sender IDs but different
613 // ordering will get back the same registration ID.
614 std::vector
<std::string
> another_sender_ids
;
615 another_sender_ids
.push_back("sender2");
616 another_sender_ids
.push_back("sender1");
617 Register(kTestAppID1
, another_sender_ids
, GCMDriverTest::WAIT
);
619 EXPECT_EQ(expected_registration_id
, registration_id());
620 EXPECT_EQ(GCMClient::SUCCESS
, registration_result());
623 TEST_F(GCMDriverFunctionalTest
, RegisterAgainWithDifferentSenderIDs
) {
624 std::vector
<std::string
> sender_ids
;
625 sender_ids
.push_back("sender1");
626 Register(kTestAppID1
, sender_ids
, GCMDriverTest::WAIT
);
627 const std::string expected_registration_id
=
628 FakeGCMClient::GenerateGCMRegistrationID(sender_ids
);
630 EXPECT_EQ(expected_registration_id
, registration_id());
631 EXPECT_EQ(GCMClient::SUCCESS
, registration_result());
633 // Make sender IDs different.
634 sender_ids
.push_back("sender2");
635 const std::string expected_registration_id2
=
636 FakeGCMClient::GenerateGCMRegistrationID(sender_ids
);
638 // Calling register 2nd time with the different sender IDs will get back a new
640 Register(kTestAppID1
, sender_ids
, GCMDriverTest::WAIT
);
641 EXPECT_EQ(expected_registration_id2
, registration_id());
642 EXPECT_EQ(GCMClient::SUCCESS
, registration_result());
645 TEST_F(GCMDriverFunctionalTest
, UnregisterExplicitly
) {
646 std::vector
<std::string
> sender_ids
;
647 sender_ids
.push_back("sender1");
648 Register(kTestAppID1
, sender_ids
, GCMDriverTest::WAIT
);
650 EXPECT_FALSE(registration_id().empty());
651 EXPECT_EQ(GCMClient::SUCCESS
, registration_result());
653 Unregister(kTestAppID1
, GCMDriverTest::WAIT
);
655 EXPECT_EQ(GCMClient::SUCCESS
, unregistration_result());
658 TEST_F(GCMDriverFunctionalTest
, UnregisterWhenAsyncOperationPending
) {
659 std::vector
<std::string
> sender_ids
;
660 sender_ids
.push_back("sender1");
661 // First start registration without waiting for it to complete.
662 Register(kTestAppID1
, sender_ids
, GCMDriverTest::DO_NOT_WAIT
);
664 // Test that unregistration fails with async operation pending when there is a
665 // registration already in progress.
666 Unregister(kTestAppID1
, GCMDriverTest::WAIT
);
667 EXPECT_EQ(GCMClient::ASYNC_OPERATION_PENDING
,
668 unregistration_result());
670 // Complete the unregistration.
671 WaitForAsyncOperation();
672 EXPECT_EQ(GCMClient::SUCCESS
, registration_result());
674 // Start unregistration without waiting for it to complete. This time no async
675 // operation is pending.
676 Unregister(kTestAppID1
, GCMDriverTest::DO_NOT_WAIT
);
678 // Test that unregistration fails with async operation pending when there is
679 // an unregistration already in progress.
680 Unregister(kTestAppID1
, GCMDriverTest::WAIT
);
681 EXPECT_EQ(GCMClient::ASYNC_OPERATION_PENDING
,
682 unregistration_result());
685 // Complete unregistration.
686 WaitForAsyncOperation();
687 EXPECT_EQ(GCMClient::SUCCESS
, unregistration_result());
690 TEST_F(GCMDriverFunctionalTest
, RegisterWhenAsyncOperationPending
) {
691 std::vector
<std::string
> sender_ids
;
692 sender_ids
.push_back("sender1");
693 // First start registration without waiting for it to complete.
694 Register(kTestAppID1
, sender_ids
, GCMDriverTest::DO_NOT_WAIT
);
696 // Test that registration fails with async operation pending when there is a
697 // registration already in progress.
698 Register(kTestAppID1
, sender_ids
, GCMDriverTest::WAIT
);
699 EXPECT_EQ(GCMClient::ASYNC_OPERATION_PENDING
,
700 registration_result());
703 // Complete the registration.
704 WaitForAsyncOperation();
705 EXPECT_EQ(GCMClient::SUCCESS
, registration_result());
708 TEST_F(GCMDriverFunctionalTest
, RegisterAfterUnfinishedUnregister
) {
709 // Register and wait for it to complete.
710 std::vector
<std::string
> sender_ids
;
711 sender_ids
.push_back("sender1");
712 Register(kTestAppID1
, sender_ids
, GCMDriverTest::WAIT
);
713 EXPECT_EQ(GCMClient::SUCCESS
, registration_result());
714 EXPECT_EQ(FakeGCMClient::GenerateGCMRegistrationID(sender_ids
),
717 // Clears the results the would be set by the Register callback in preparation
718 // to call register 2nd time.
721 // Start unregistration without waiting for it to complete.
722 Unregister(kTestAppID1
, GCMDriverTest::DO_NOT_WAIT
);
724 // Register immeidately after unregistration is not completed.
725 sender_ids
.push_back("sender2");
726 Register(kTestAppID1
, sender_ids
, GCMDriverTest::WAIT
);
728 // We need one more waiting since the waiting in Register is indeed for
729 // uncompleted Unregister.
730 WaitForAsyncOperation();
731 EXPECT_EQ(GCMClient::SUCCESS
, registration_result());
732 EXPECT_EQ(FakeGCMClient::GenerateGCMRegistrationID(sender_ids
),
736 TEST_F(GCMDriverFunctionalTest
, Send
) {
737 OutgoingMessage message
;
738 message
.id
= "1@ack";
739 message
.data
["key1"] = "value1";
740 message
.data
["key2"] = "value2";
741 Send(kTestAppID1
, kUserID1
, message
, GCMDriverTest::WAIT
);
743 EXPECT_EQ(message
.id
, send_message_id());
744 EXPECT_EQ(GCMClient::SUCCESS
, send_result());
746 gcm_app_handler()->WaitForNotification();
747 EXPECT_EQ(message
.id
, gcm_app_handler()->acked_message_id());
748 EXPECT_EQ(kTestAppID1
, gcm_app_handler()->app_id());
751 TEST_F(GCMDriverFunctionalTest
, SendError
) {
752 OutgoingMessage message
;
753 // Embedding error in id will tell the mock to simulate the send error.
754 message
.id
= "1@error";
755 message
.data
["key1"] = "value1";
756 message
.data
["key2"] = "value2";
757 Send(kTestAppID1
, kUserID1
, message
, GCMDriverTest::WAIT
);
759 EXPECT_EQ(message
.id
, send_message_id());
760 EXPECT_EQ(GCMClient::SUCCESS
, send_result());
762 // Wait for the send error.
763 gcm_app_handler()->WaitForNotification();
764 EXPECT_EQ(FakeGCMAppHandler::SEND_ERROR_EVENT
,
765 gcm_app_handler()->received_event());
766 EXPECT_EQ(kTestAppID1
, gcm_app_handler()->app_id());
767 EXPECT_EQ(message
.id
,
768 gcm_app_handler()->send_error_details().message_id
);
769 EXPECT_NE(GCMClient::SUCCESS
,
770 gcm_app_handler()->send_error_details().result
);
771 EXPECT_EQ(message
.data
,
772 gcm_app_handler()->send_error_details().additional_data
);
775 TEST_F(GCMDriverFunctionalTest
, MessageReceived
) {
776 // GCM registration has to be performed otherwise GCM will not be started.
777 Register(kTestAppID1
, ToSenderList("sender"), GCMDriverTest::WAIT
);
779 IncomingMessage message
;
780 message
.data
["key1"] = "value1";
781 message
.data
["key2"] = "value2";
782 message
.sender_id
= "sender";
783 GetGCMClient()->ReceiveMessage(kTestAppID1
, message
);
784 gcm_app_handler()->WaitForNotification();
785 EXPECT_EQ(FakeGCMAppHandler::MESSAGE_EVENT
,
786 gcm_app_handler()->received_event());
787 EXPECT_EQ(kTestAppID1
, gcm_app_handler()->app_id());
788 EXPECT_EQ(message
.data
, gcm_app_handler()->message().data
);
789 EXPECT_TRUE(gcm_app_handler()->message().collapse_key
.empty());
790 EXPECT_EQ(message
.sender_id
, gcm_app_handler()->message().sender_id
);
793 TEST_F(GCMDriverFunctionalTest
, MessageWithCollapseKeyReceived
) {
794 // GCM registration has to be performed otherwise GCM will not be started.
795 Register(kTestAppID1
, ToSenderList("sender"), GCMDriverTest::WAIT
);
797 IncomingMessage message
;
798 message
.data
["key1"] = "value1";
799 message
.collapse_key
= "collapse_key_value";
800 message
.sender_id
= "sender";
801 GetGCMClient()->ReceiveMessage(kTestAppID1
, message
);
802 gcm_app_handler()->WaitForNotification();
803 EXPECT_EQ(FakeGCMAppHandler::MESSAGE_EVENT
,
804 gcm_app_handler()->received_event());
805 EXPECT_EQ(kTestAppID1
, gcm_app_handler()->app_id());
806 EXPECT_EQ(message
.data
, gcm_app_handler()->message().data
);
807 EXPECT_EQ(message
.collapse_key
,
808 gcm_app_handler()->message().collapse_key
);
811 TEST_F(GCMDriverFunctionalTest
, MessagesDeleted
) {
812 // GCM registration has to be performed otherwise GCM will not be started.
813 Register(kTestAppID1
, ToSenderList("sender"), GCMDriverTest::WAIT
);
815 GetGCMClient()->DeleteMessages(kTestAppID1
);
816 gcm_app_handler()->WaitForNotification();
817 EXPECT_EQ(FakeGCMAppHandler::MESSAGES_DELETED_EVENT
,
818 gcm_app_handler()->received_event());
819 EXPECT_EQ(kTestAppID1
, gcm_app_handler()->app_id());
822 TEST_F(GCMDriverFunctionalTest
, LastTokenFetchTime
) {
823 // GCM registration has to be performed otherwise GCM will not be started.
824 Register(kTestAppID1
, ToSenderList("sender"), GCMDriverTest::WAIT
);
826 EXPECT_EQ(base::Time(), driver()->GetLastTokenFetchTime());
827 base::Time fetch_time
= base::Time::Now();
828 driver()->SetLastTokenFetchTime(fetch_time
);
829 EXPECT_EQ(fetch_time
, driver()->GetLastTokenFetchTime());
832 // Tests a single instance of GCMDriver.
833 class GCMChannelStatusSyncerTest
: public GCMDriverTest
{
835 GCMChannelStatusSyncerTest();
836 ~GCMChannelStatusSyncerTest() override
;
839 void SetUp() override
;
841 void CompleteGCMChannelStatusRequest(bool enabled
, int poll_interval_seconds
);
842 bool CompareDelaySeconds(int64 expected_delay_seconds
,
843 int64 actual_delay_seconds
);
845 GCMChannelStatusSyncer
* syncer() {
846 return driver()->gcm_channel_status_syncer_for_testing();
850 net::TestURLFetcherFactory url_fetcher_factory_
;
852 DISALLOW_COPY_AND_ASSIGN(GCMChannelStatusSyncerTest
);
855 GCMChannelStatusSyncerTest::GCMChannelStatusSyncerTest() {
858 GCMChannelStatusSyncerTest::~GCMChannelStatusSyncerTest() {
861 void GCMChannelStatusSyncerTest::SetUp() {
862 GCMDriverTest::SetUp();
864 url_fetcher_factory_
.set_remove_fetcher_on_delete(true);
866 // Turn on all-user support.
867 ASSERT_TRUE(base::FieldTrialList::CreateFieldTrial("GCM", "Enabled"));
870 void GCMChannelStatusSyncerTest::CompleteGCMChannelStatusRequest(
871 bool enabled
, int poll_interval_seconds
) {
872 sync_pb::ExperimentStatusResponse response_proto
;
873 sync_pb::ExperimentsSpecifics
* experiment_specifics
=
874 response_proto
.add_experiment();
875 experiment_specifics
->mutable_gcm_channel()->set_enabled(enabled
);
877 if (poll_interval_seconds
)
878 response_proto
.set_poll_interval_seconds(poll_interval_seconds
);
880 std::string response_string
;
881 response_proto
.SerializeToString(&response_string
);
883 net::TestURLFetcher
* fetcher
= url_fetcher_factory_
.GetFetcherByID(0);
884 ASSERT_TRUE(fetcher
);
885 fetcher
->set_response_code(net::HTTP_OK
);
886 fetcher
->SetResponseString(response_string
);
887 fetcher
->delegate()->OnURLFetchComplete(fetcher
);
890 bool GCMChannelStatusSyncerTest::CompareDelaySeconds(
891 int64 expected_delay_seconds
, int64 actual_delay_seconds
) {
892 // Most of time, the actual delay should not be smaller than the expected
894 if (actual_delay_seconds
>= expected_delay_seconds
)
896 // It is also OK that the actual delay is a bit smaller than the expected
897 // delay in case that the test runs slowly.
898 return expected_delay_seconds
- actual_delay_seconds
< 30;
901 TEST_F(GCMChannelStatusSyncerTest
, DisableAndEnable
) {
902 // Create GCMDriver first. By default, GCM is enabled.
904 EXPECT_TRUE(driver()->gcm_enabled());
905 EXPECT_TRUE(syncer()->gcm_enabled());
907 // Remove delay such that the request could be executed immediately.
908 syncer()->set_delay_removed_for_testing(true);
910 // GCM is still enabled at this point.
912 EXPECT_TRUE(driver()->gcm_enabled());
913 EXPECT_TRUE(syncer()->gcm_enabled());
915 // Wait until the GCM channel status request gets triggered.
918 // Complete the request that disables the GCM.
919 CompleteGCMChannelStatusRequest(false, 0);
920 EXPECT_FALSE(driver()->gcm_enabled());
921 EXPECT_FALSE(syncer()->gcm_enabled());
922 EXPECT_FALSE(driver()->IsStarted());
924 // Wait until next GCM channel status request gets triggered.
927 // Complete the request that enables the GCM.
928 CompleteGCMChannelStatusRequest(true, 0);
929 EXPECT_TRUE(driver()->gcm_enabled());
930 EXPECT_TRUE(syncer()->gcm_enabled());
933 TEST_F(GCMChannelStatusSyncerTest
, DisableRestartAndEnable
) {
934 // Create GCMDriver first. By default, GCM is enabled.
936 EXPECT_TRUE(driver()->gcm_enabled());
937 EXPECT_TRUE(syncer()->gcm_enabled());
939 // Remove delay such that the request could be executed immediately.
940 syncer()->set_delay_removed_for_testing(true);
942 // GCM is still enabled at this point.
944 EXPECT_TRUE(driver()->gcm_enabled());
945 EXPECT_TRUE(syncer()->gcm_enabled());
947 // Wait until the GCM channel status request gets triggered.
950 // Complete the request that disables the GCM.
951 CompleteGCMChannelStatusRequest(false, 0);
952 EXPECT_FALSE(driver()->gcm_enabled());
953 EXPECT_FALSE(syncer()->gcm_enabled());
955 // Simulate browser start by recreating GCMDriver.
959 // Remove delay such that the request could be executed immediately.
960 syncer()->set_delay_removed_for_testing(true);
962 // GCM is still disabled.
963 EXPECT_FALSE(driver()->gcm_enabled());
964 EXPECT_FALSE(syncer()->gcm_enabled());
967 EXPECT_FALSE(driver()->gcm_enabled());
968 EXPECT_FALSE(syncer()->gcm_enabled());
970 // Wait until the GCM channel status request gets triggered.
973 // Complete the request that re-enables the GCM.
974 CompleteGCMChannelStatusRequest(true, 0);
975 EXPECT_TRUE(driver()->gcm_enabled());
976 EXPECT_TRUE(syncer()->gcm_enabled());
979 TEST_F(GCMChannelStatusSyncerTest
, FirstTimePolling
) {
984 // The 1st request should be triggered shortly without jittering.
985 EXPECT_EQ(GCMChannelStatusSyncer::first_time_delay_seconds(),
986 syncer()->current_request_delay_interval().InSeconds());
989 TEST_F(GCMChannelStatusSyncerTest
, SubsequentPollingWithDefaultInterval
) {
990 // Create GCMDriver first. GCM is not started.
993 // Remove delay such that the request could be executed immediately.
994 syncer()->set_delay_removed_for_testing(true);
996 // Now GCM is started.
999 // Wait until the GCM channel status request gets triggered.
1002 // Keep delay such that we can find out the computed delay time.
1003 syncer()->set_delay_removed_for_testing(false);
1005 // Complete the request. The default interval is intact.
1006 CompleteGCMChannelStatusRequest(true, 0);
1008 // The next request should be scheduled at the expected default interval.
1009 int64 actual_delay_seconds
=
1010 syncer()->current_request_delay_interval().InSeconds();
1011 int64 expected_delay_seconds
=
1012 GCMChannelStatusRequest::default_poll_interval_seconds();
1013 EXPECT_TRUE(CompareDelaySeconds(expected_delay_seconds
, actual_delay_seconds
))
1014 << "expected delay: " << expected_delay_seconds
1015 << " actual delay: " << actual_delay_seconds
;
1017 // Simulate browser start by recreating GCMDriver.
1022 // After start-up, the request should still be scheduled at the expected
1023 // default interval.
1024 actual_delay_seconds
=
1025 syncer()->current_request_delay_interval().InSeconds();
1026 EXPECT_TRUE(CompareDelaySeconds(expected_delay_seconds
, actual_delay_seconds
))
1027 << "expected delay: " << expected_delay_seconds
1028 << " actual delay: " << actual_delay_seconds
;
1031 TEST_F(GCMChannelStatusSyncerTest
, SubsequentPollingWithUpdatedInterval
) {
1032 // Create GCMDriver first. GCM is not started.
1035 // Remove delay such that the request could be executed immediately.
1036 syncer()->set_delay_removed_for_testing(true);
1038 // Now GCM is started.
1041 // Wait until the GCM channel status request gets triggered.
1044 // Keep delay such that we can find out the computed delay time.
1045 syncer()->set_delay_removed_for_testing(false);
1047 // Complete the request. The interval is being changed.
1048 int new_poll_interval_seconds
=
1049 GCMChannelStatusRequest::default_poll_interval_seconds() * 2;
1050 CompleteGCMChannelStatusRequest(true, new_poll_interval_seconds
);
1052 // The next request should be scheduled at the expected updated interval.
1053 int64 actual_delay_seconds
=
1054 syncer()->current_request_delay_interval().InSeconds();
1055 int64 expected_delay_seconds
= new_poll_interval_seconds
;
1056 EXPECT_TRUE(CompareDelaySeconds(expected_delay_seconds
, actual_delay_seconds
))
1057 << "expected delay: " << expected_delay_seconds
1058 << " actual delay: " << actual_delay_seconds
;
1060 // Simulate browser start by recreating GCMDriver.
1065 // After start-up, the request should still be scheduled at the expected
1066 // updated interval.
1067 actual_delay_seconds
=
1068 syncer()->current_request_delay_interval().InSeconds();
1069 EXPECT_TRUE(CompareDelaySeconds(expected_delay_seconds
, actual_delay_seconds
))
1070 << "expected delay: " << expected_delay_seconds
1071 << " actual delay: " << actual_delay_seconds
;
1074 class GCMDriverInstanceIDTest
: public GCMDriverTest
{
1076 GCMDriverInstanceIDTest();
1077 ~GCMDriverInstanceIDTest() override
;
1080 void GetInstanceID(const std::string
& app_id
, WaitToFinish wait_to_finish
);
1081 void GetInstanceIDDataCompleted(const std::string
& instance_id
,
1082 const std::string
& extra_data
);
1083 void GetToken(const std::string
& app_id
,
1084 const std::string
& authorized_entity
,
1085 const std::string
& scope
,
1086 WaitToFinish wait_to_finish
);
1087 void DeleteToken(const std::string
& app_id
,
1088 const std::string
& authorized_entity
,
1089 const std::string
& scope
,
1090 WaitToFinish wait_to_finish
);
1092 std::string
instance_id() const { return instance_id_
; }
1093 std::string
extra_data() const { return extra_data_
; }
1096 std::string instance_id_
;
1097 std::string extra_data_
;
1099 DISALLOW_COPY_AND_ASSIGN(GCMDriverInstanceIDTest
);
1102 GCMDriverInstanceIDTest::GCMDriverInstanceIDTest() {
1105 GCMDriverInstanceIDTest::~GCMDriverInstanceIDTest() {
1108 void GCMDriverInstanceIDTest::GetReady() {
1115 void GCMDriverInstanceIDTest::GetInstanceID(const std::string
& app_id
,
1116 WaitToFinish wait_to_finish
) {
1117 base::RunLoop run_loop
;
1118 set_async_operation_completed_callback(run_loop
.QuitClosure());
1119 driver()->GetInstanceIDData(app_id
,
1120 base::Bind(&GCMDriverInstanceIDTest::GetInstanceIDDataCompleted
,
1121 base::Unretained(this)));
1122 if (wait_to_finish
== WAIT
)
1126 void GCMDriverInstanceIDTest::GetInstanceIDDataCompleted(
1127 const std::string
& instance_id
, const std::string
& extra_data
) {
1128 instance_id_
= instance_id
;
1129 extra_data_
= extra_data
;
1130 if (!async_operation_completed_callback().is_null())
1131 async_operation_completed_callback().Run();
1134 void GCMDriverInstanceIDTest::GetToken(const std::string
& app_id
,
1135 const std::string
& authorized_entity
,
1136 const std::string
& scope
,
1137 WaitToFinish wait_to_finish
) {
1138 base::RunLoop run_loop
;
1139 set_async_operation_completed_callback(run_loop
.QuitClosure());
1140 std::map
<std::string
, std::string
> options
;
1141 driver()->GetToken(app_id
,
1145 base::Bind(&GCMDriverTest::RegisterCompleted
,
1146 base::Unretained(this)));
1147 if (wait_to_finish
== WAIT
)
1151 void GCMDriverInstanceIDTest::DeleteToken(const std::string
& app_id
,
1152 const std::string
& authorized_entity
,
1153 const std::string
& scope
,
1154 WaitToFinish wait_to_finish
) {
1155 base::RunLoop run_loop
;
1156 set_async_operation_completed_callback(run_loop
.QuitClosure());
1157 driver()->DeleteToken(app_id
,
1160 base::Bind(&GCMDriverTest::UnregisterCompleted
,
1161 base::Unretained(this)));
1162 if (wait_to_finish
== WAIT
)
1166 TEST_F(GCMDriverInstanceIDTest
, InstanceIDData
) {
1169 driver()->AddInstanceIDData(kTestAppID1
, kInstanceID1
, "Foo");
1170 GetInstanceID(kTestAppID1
, GCMDriverTest::WAIT
);
1172 EXPECT_EQ(kInstanceID1
, instance_id());
1173 EXPECT_EQ("Foo", extra_data());
1175 driver()->RemoveInstanceIDData(kTestAppID1
);
1176 GetInstanceID(kTestAppID1
, GCMDriverTest::WAIT
);
1178 EXPECT_TRUE(instance_id().empty());
1179 EXPECT_TRUE(extra_data().empty());
1182 TEST_F(GCMDriverInstanceIDTest
, GCMClientNotReadyBeforeInstanceIDData
) {
1187 // Make GCMClient not ready until PerformDelayedStart is called.
1188 GetGCMClient()->set_start_mode_overridding(
1189 FakeGCMClient::FORCE_TO_ALWAYS_DELAY_START_GCM
);
1193 // All operations are on hold until GCMClient is ready.
1194 driver()->AddInstanceIDData(kTestAppID1
, kInstanceID1
, "Foo");
1195 driver()->AddInstanceIDData(kTestAppID2
, kInstanceID2
, "Bar");
1196 driver()->RemoveInstanceIDData(kTestAppID1
);
1197 GetInstanceID(kTestAppID2
, GCMDriverTest::DO_NOT_WAIT
);
1200 EXPECT_TRUE(instance_id().empty());
1201 EXPECT_TRUE(extra_data().empty());
1203 // All operations will be performed after GCMClient becomes ready.
1204 GetGCMClient()->PerformDelayedStart();
1205 WaitForAsyncOperation();
1206 EXPECT_EQ(kInstanceID2
, instance_id());
1207 EXPECT_EQ("Bar", extra_data());
1210 TEST_F(GCMDriverInstanceIDTest
, GetToken
) {
1213 const std::string expected_token
=
1214 FakeGCMClient::GenerateInstanceIDToken(kUserID1
, kScope
);
1215 GetToken(kTestAppID1
, kUserID1
, kScope
, GCMDriverTest::WAIT
);
1217 EXPECT_EQ(expected_token
, registration_id());
1218 EXPECT_EQ(GCMClient::SUCCESS
, registration_result());
1221 TEST_F(GCMDriverInstanceIDTest
, GetTokenError
) {
1224 std::string error_entity
= "sender@error";
1225 GetToken(kTestAppID1
, error_entity
, kScope
, GCMDriverTest::WAIT
);
1227 EXPECT_TRUE(registration_id().empty());
1228 EXPECT_NE(GCMClient::SUCCESS
, registration_result());
1231 TEST_F(GCMDriverInstanceIDTest
, GCMClientNotReadyBeforeGetToken
) {
1236 // Make GCMClient not ready until PerformDelayedStart is called.
1237 GetGCMClient()->set_start_mode_overridding(
1238 FakeGCMClient::FORCE_TO_ALWAYS_DELAY_START_GCM
);
1242 // GetToken operation is on hold until GCMClient is ready.
1243 GetToken(kTestAppID1
, kUserID1
, kScope
, GCMDriverTest::DO_NOT_WAIT
);
1246 EXPECT_TRUE(registration_id().empty());
1247 EXPECT_EQ(GCMClient::UNKNOWN_ERROR
, registration_result());
1249 // GetToken operation will be invoked after GCMClient becomes ready.
1250 GetGCMClient()->PerformDelayedStart();
1251 WaitForAsyncOperation();
1252 EXPECT_FALSE(registration_id().empty());
1253 EXPECT_EQ(GCMClient::SUCCESS
, registration_result());
1256 TEST_F(GCMDriverInstanceIDTest
, DeleteToken
) {
1259 const std::string expected_token
=
1260 FakeGCMClient::GenerateInstanceIDToken(kUserID1
, kScope
);
1261 GetToken(kTestAppID1
, kUserID1
, kScope
, GCMDriverTest::WAIT
);
1262 EXPECT_EQ(expected_token
, registration_id());
1263 EXPECT_EQ(GCMClient::SUCCESS
, registration_result());
1265 DeleteToken(kTestAppID1
, kUserID1
, kScope
, GCMDriverTest::WAIT
);
1266 EXPECT_EQ(GCMClient::SUCCESS
, unregistration_result());
1269 TEST_F(GCMDriverInstanceIDTest
, GCMClientNotReadyBeforeDeleteToken
) {
1274 // Make GCMClient not ready until PerformDelayedStart is called.
1275 GetGCMClient()->set_start_mode_overridding(
1276 FakeGCMClient::FORCE_TO_ALWAYS_DELAY_START_GCM
);
1280 // DeleteToken operation is on hold until GCMClient is ready.
1281 DeleteToken(kTestAppID1
, kUserID1
, kScope
, GCMDriverTest::DO_NOT_WAIT
);
1284 EXPECT_EQ(GCMClient::UNKNOWN_ERROR
, unregistration_result());
1286 // DeleteToken operation will be invoked after GCMClient becomes ready.
1287 GetGCMClient()->PerformDelayedStart();
1288 WaitForAsyncOperation();
1289 EXPECT_EQ(GCMClient::SUCCESS
, unregistration_result());