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 std::vector
<std::string
> senders
;
88 Tokenize(sender_ids
, ",", &senders
);
94 class GCMDriverTest
: public testing::Test
{
102 ~GCMDriverTest() override
;
105 void SetUp() override
;
106 void TearDown() override
;
108 GCMDriverDesktop
* driver() { return driver_
.get(); }
109 FakeGCMAppHandler
* gcm_app_handler() { return gcm_app_handler_
.get(); }
110 FakeGCMConnectionObserver
* gcm_connection_observer() {
111 return gcm_connection_observer_
.get();
113 const std::string
& registration_id() const { return registration_id_
; }
114 GCMClient::Result
registration_result() const { return registration_result_
; }
115 const std::string
& send_message_id() const { return send_message_id_
; }
116 GCMClient::Result
send_result() const { return send_result_
; }
117 GCMClient::Result
unregistration_result() const {
118 return unregistration_result_
;
125 bool HasAppHandlers() const;
126 FakeGCMClient
* GetGCMClient();
129 void ShutdownDriver();
130 void AddAppHandlers();
131 void RemoveAppHandlers();
133 void Register(const std::string
& app_id
,
134 const std::vector
<std::string
>& sender_ids
,
135 WaitToFinish wait_to_finish
);
136 void Send(const std::string
& app_id
,
137 const std::string
& receiver_id
,
138 const GCMClient::OutgoingMessage
& message
,
139 WaitToFinish wait_to_finish
);
140 void Unregister(const std::string
& app_id
, WaitToFinish wait_to_finish
);
142 void WaitForAsyncOperation();
144 void RegisterCompleted(const std::string
& registration_id
,
145 GCMClient::Result result
);
146 void SendCompleted(const std::string
& message_id
, GCMClient::Result result
);
147 void UnregisterCompleted(GCMClient::Result result
);
149 const base::Closure
& async_operation_completed_callback() const {
150 return async_operation_completed_callback_
;
152 void set_async_operation_completed_callback(const base::Closure
& callback
) {
153 async_operation_completed_callback_
= callback
;
157 base::ScopedTempDir temp_dir_
;
158 TestingPrefServiceSimple prefs_
;
159 scoped_refptr
<base::TestSimpleTaskRunner
> task_runner_
;
160 base::MessageLoopForUI message_loop_
;
161 base::Thread io_thread_
;
162 base::FieldTrialList field_trial_list_
;
163 scoped_ptr
<GCMDriverDesktop
> driver_
;
164 scoped_ptr
<FakeGCMAppHandler
> gcm_app_handler_
;
165 scoped_ptr
<FakeGCMConnectionObserver
> gcm_connection_observer_
;
167 base::Closure async_operation_completed_callback_
;
169 std::string registration_id_
;
170 GCMClient::Result registration_result_
;
171 std::string send_message_id_
;
172 GCMClient::Result send_result_
;
173 GCMClient::Result unregistration_result_
;
175 DISALLOW_COPY_AND_ASSIGN(GCMDriverTest
);
178 GCMDriverTest::GCMDriverTest()
179 : task_runner_(new base::TestSimpleTaskRunner()),
180 io_thread_("IOThread"),
181 field_trial_list_(NULL
),
182 registration_result_(GCMClient::UNKNOWN_ERROR
),
183 send_result_(GCMClient::UNKNOWN_ERROR
),
184 unregistration_result_(GCMClient::UNKNOWN_ERROR
) {
187 GCMDriverTest::~GCMDriverTest() {
190 void GCMDriverTest::SetUp() {
191 GCMChannelStatusSyncer::RegisterPrefs(prefs_
.registry());
193 ASSERT_TRUE(temp_dir_
.CreateUniqueTempDir());
196 void GCMDriverTest::TearDown() {
207 void GCMDriverTest::PumpIOLoop() {
208 base::RunLoop run_loop
;
209 io_thread_
.task_runner()->PostTaskAndReply(
210 FROM_HERE
, base::Bind(&PumpCurrentLoop
), run_loop
.QuitClosure());
214 void GCMDriverTest::ClearResults() {
215 registration_id_
.clear();
216 registration_result_
= GCMClient::UNKNOWN_ERROR
;
218 send_message_id_
.clear();
219 send_result_
= GCMClient::UNKNOWN_ERROR
;
221 unregistration_result_
= GCMClient::UNKNOWN_ERROR
;
224 bool GCMDriverTest::HasAppHandlers() const {
225 return !driver_
->app_handlers().empty();
228 FakeGCMClient
* GCMDriverTest::GetGCMClient() {
229 return static_cast<FakeGCMClient
*>(driver_
->GetGCMClientForTesting());
232 void GCMDriverTest::CreateDriver() {
233 scoped_refptr
<net::URLRequestContextGetter
> request_context
=
234 new net::TestURLRequestContextGetter(io_thread_
.task_runner());
235 // TODO(johnme): Need equivalent test coverage of GCMDriverAndroid.
236 driver_
.reset(new GCMDriverDesktop(
237 scoped_ptr
<GCMClientFactory
>(
238 new FakeGCMClientFactory(base::ThreadTaskRunnerHandle::Get(),
239 io_thread_
.task_runner())).Pass(),
240 GCMClient::ChromeBuildInfo(), "http://channel.status.request.url",
241 "user-agent-string", &prefs_
, temp_dir_
.path(), request_context
,
242 base::ThreadTaskRunnerHandle::Get(), io_thread_
.task_runner(),
245 gcm_app_handler_
.reset(new FakeGCMAppHandler
);
246 gcm_connection_observer_
.reset(new FakeGCMConnectionObserver
);
248 driver_
->AddConnectionObserver(gcm_connection_observer_
.get());
251 void GCMDriverTest::ShutdownDriver() {
252 if (gcm_connection_observer())
253 driver()->RemoveConnectionObserver(gcm_connection_observer());
254 driver()->Shutdown();
257 void GCMDriverTest::AddAppHandlers() {
258 driver_
->AddAppHandler(kTestAppID1
, gcm_app_handler_
.get());
259 driver_
->AddAppHandler(kTestAppID2
, gcm_app_handler_
.get());
262 void GCMDriverTest::RemoveAppHandlers() {
263 driver_
->RemoveAppHandler(kTestAppID1
);
264 driver_
->RemoveAppHandler(kTestAppID2
);
267 void GCMDriverTest::Register(const std::string
& app_id
,
268 const std::vector
<std::string
>& sender_ids
,
269 WaitToFinish wait_to_finish
) {
270 base::RunLoop run_loop
;
271 async_operation_completed_callback_
= run_loop
.QuitClosure();
272 driver_
->Register(app_id
,
274 base::Bind(&GCMDriverTest::RegisterCompleted
,
275 base::Unretained(this)));
276 if (wait_to_finish
== WAIT
)
280 void GCMDriverTest::Send(const std::string
& app_id
,
281 const std::string
& receiver_id
,
282 const GCMClient::OutgoingMessage
& message
,
283 WaitToFinish wait_to_finish
) {
284 base::RunLoop run_loop
;
285 async_operation_completed_callback_
= run_loop
.QuitClosure();
286 driver_
->Send(app_id
,
289 base::Bind(&GCMDriverTest::SendCompleted
,
290 base::Unretained(this)));
291 if (wait_to_finish
== WAIT
)
295 void GCMDriverTest::Unregister(const std::string
& app_id
,
296 WaitToFinish wait_to_finish
) {
297 base::RunLoop run_loop
;
298 async_operation_completed_callback_
= run_loop
.QuitClosure();
299 driver_
->Unregister(app_id
,
300 base::Bind(&GCMDriverTest::UnregisterCompleted
,
301 base::Unretained(this)));
302 if (wait_to_finish
== WAIT
)
306 void GCMDriverTest::WaitForAsyncOperation() {
307 base::RunLoop run_loop
;
308 async_operation_completed_callback_
= run_loop
.QuitClosure();
312 void GCMDriverTest::RegisterCompleted(const std::string
& registration_id
,
313 GCMClient::Result result
) {
314 registration_id_
= registration_id
;
315 registration_result_
= result
;
316 if (!async_operation_completed_callback_
.is_null())
317 async_operation_completed_callback_
.Run();
320 void GCMDriverTest::SendCompleted(const std::string
& message_id
,
321 GCMClient::Result result
) {
322 send_message_id_
= message_id
;
323 send_result_
= result
;
324 if (!async_operation_completed_callback_
.is_null())
325 async_operation_completed_callback_
.Run();
328 void GCMDriverTest::UnregisterCompleted(GCMClient::Result result
) {
329 unregistration_result_
= result
;
330 if (!async_operation_completed_callback_
.is_null())
331 async_operation_completed_callback_
.Run();
334 TEST_F(GCMDriverTest
, Create
) {
335 // Create GCMDriver first. By default GCM is set to delay start.
337 EXPECT_FALSE(driver()->IsStarted());
339 // Adding an app handler will not start GCM.
343 EXPECT_FALSE(driver()->IsStarted());
344 EXPECT_FALSE(driver()->IsConnected());
345 EXPECT_FALSE(gcm_connection_observer()->connected());
347 // The GCM registration will kick off the GCM.
348 Register(kTestAppID1
, ToSenderList("sender"), GCMDriverTest::WAIT
);
349 EXPECT_TRUE(driver()->IsStarted());
350 EXPECT_TRUE(driver()->IsConnected());
351 EXPECT_TRUE(gcm_connection_observer()->connected());
354 TEST_F(GCMDriverTest
, Shutdown
) {
356 EXPECT_FALSE(HasAppHandlers());
359 EXPECT_TRUE(HasAppHandlers());
362 EXPECT_FALSE(HasAppHandlers());
363 EXPECT_FALSE(driver()->IsConnected());
364 EXPECT_FALSE(gcm_connection_observer()->connected());
367 TEST_F(GCMDriverTest
, DisableAndReenableGCM
) {
372 EXPECT_FALSE(driver()->IsStarted());
374 // The GCM registration will kick off the GCM.
375 Register(kTestAppID1
, ToSenderList("sender"), GCMDriverTest::WAIT
);
376 EXPECT_TRUE(driver()->IsStarted());
378 // Disables the GCM. GCM will be stopped.
382 EXPECT_FALSE(driver()->IsStarted());
384 // Enables the GCM. GCM will be started.
388 EXPECT_TRUE(driver()->IsStarted());
391 TEST_F(GCMDriverTest
, StartOrStopGCMOnDemand
) {
395 EXPECT_FALSE(driver()->IsStarted());
397 // Adding an app handler will not start GCM.
398 driver()->AddAppHandler(kTestAppID1
, gcm_app_handler());
401 EXPECT_FALSE(driver()->IsStarted());
403 // The GCM registration will kick off the GCM.
404 Register(kTestAppID1
, ToSenderList("sender"), GCMDriverTest::WAIT
);
405 EXPECT_TRUE(driver()->IsStarted());
407 // Add another app handler.
408 driver()->AddAppHandler(kTestAppID2
, gcm_app_handler());
411 EXPECT_TRUE(driver()->IsStarted());
413 // GCMClient remains active after one app handler is gone.
414 driver()->RemoveAppHandler(kTestAppID1
);
417 EXPECT_TRUE(driver()->IsStarted());
419 // GCMClient should be stopped after the last app handler is gone.
420 driver()->RemoveAppHandler(kTestAppID2
);
423 EXPECT_FALSE(driver()->IsStarted());
425 // GCMClient is restarted after an app handler has been added.
426 driver()->AddAppHandler(kTestAppID2
, gcm_app_handler());
429 EXPECT_TRUE(driver()->IsStarted());
432 TEST_F(GCMDriverTest
, RegisterFailed
) {
433 std::vector
<std::string
> sender_ids
;
434 sender_ids
.push_back("sender1");
438 // Registration fails when the no app handler is added.
439 Register(kTestAppID1
, sender_ids
, GCMDriverTest::WAIT
);
440 EXPECT_TRUE(registration_id().empty());
441 EXPECT_EQ(GCMClient::UNKNOWN_ERROR
, registration_result());
445 // Registration fails when GCM is disabled.
448 Register(kTestAppID1
, sender_ids
, GCMDriverTest::WAIT
);
449 EXPECT_TRUE(registration_id().empty());
450 EXPECT_EQ(GCMClient::GCM_DISABLED
, registration_result());
453 TEST_F(GCMDriverTest
, UnregisterFailed
) {
456 // Unregistration fails when the no app handler is added.
457 Unregister(kTestAppID1
, GCMDriverTest::WAIT
);
458 EXPECT_EQ(GCMClient::UNKNOWN_ERROR
, unregistration_result());
462 // Unregistration fails when GCM is disabled.
465 Unregister(kTestAppID1
, GCMDriverTest::WAIT
);
466 EXPECT_EQ(GCMClient::GCM_DISABLED
, unregistration_result());
469 TEST_F(GCMDriverTest
, SendFailed
) {
470 GCMClient::OutgoingMessage message
;
472 message
.data
["key1"] = "value1";
476 // Sending fails when the no app handler is added.
477 Send(kTestAppID1
, kUserID1
, message
, GCMDriverTest::WAIT
);
478 EXPECT_TRUE(send_message_id().empty());
479 EXPECT_EQ(GCMClient::UNKNOWN_ERROR
, send_result());
483 // Sending fails when GCM is disabled.
486 Send(kTestAppID1
, kUserID1
, message
, GCMDriverTest::WAIT
);
487 EXPECT_TRUE(send_message_id().empty());
488 EXPECT_EQ(GCMClient::GCM_DISABLED
, send_result());
491 TEST_F(GCMDriverTest
, GCMClientNotReadyBeforeRegistration
) {
496 // Make GCMClient not ready until PerformDelayedStart is called.
497 GetGCMClient()->set_start_mode_overridding(
498 FakeGCMClient::FORCE_TO_ALWAYS_DELAY_START_GCM
);
502 // The registration is on hold until GCMClient is ready.
503 std::vector
<std::string
> sender_ids
;
504 sender_ids
.push_back("sender1");
505 Register(kTestAppID1
,
507 GCMDriverTest::DO_NOT_WAIT
);
510 EXPECT_TRUE(registration_id().empty());
511 EXPECT_EQ(GCMClient::UNKNOWN_ERROR
, registration_result());
513 // Register operation will be invoked after GCMClient becomes ready.
514 GetGCMClient()->PerformDelayedStart();
515 WaitForAsyncOperation();
516 EXPECT_FALSE(registration_id().empty());
517 EXPECT_EQ(GCMClient::SUCCESS
, registration_result());
520 TEST_F(GCMDriverTest
, GCMClientNotReadyBeforeSending
) {
525 // Make GCMClient not ready until PerformDelayedStart is called.
526 GetGCMClient()->set_start_mode_overridding(
527 FakeGCMClient::FORCE_TO_ALWAYS_DELAY_START_GCM
);
531 // The sending is on hold until GCMClient is ready.
532 GCMClient::OutgoingMessage message
;
534 message
.data
["key1"] = "value1";
535 message
.data
["key2"] = "value2";
536 Send(kTestAppID1
, kUserID1
, message
, GCMDriverTest::DO_NOT_WAIT
);
540 EXPECT_TRUE(send_message_id().empty());
541 EXPECT_EQ(GCMClient::UNKNOWN_ERROR
, send_result());
543 // Send operation will be invoked after GCMClient becomes ready.
544 GetGCMClient()->PerformDelayedStart();
545 WaitForAsyncOperation();
546 EXPECT_EQ(message
.id
, send_message_id());
547 EXPECT_EQ(GCMClient::SUCCESS
, send_result());
550 // Tests a single instance of GCMDriver.
551 class GCMDriverFunctionalTest
: public GCMDriverTest
{
553 GCMDriverFunctionalTest();
554 ~GCMDriverFunctionalTest() override
;
557 void SetUp() override
;
560 DISALLOW_COPY_AND_ASSIGN(GCMDriverFunctionalTest
);
563 GCMDriverFunctionalTest::GCMDriverFunctionalTest() {
566 GCMDriverFunctionalTest::~GCMDriverFunctionalTest() {
569 void GCMDriverFunctionalTest::SetUp() {
570 GCMDriverTest::SetUp();
578 TEST_F(GCMDriverFunctionalTest
, Register
) {
579 std::vector
<std::string
> sender_ids
;
580 sender_ids
.push_back("sender1");
581 Register(kTestAppID1
, sender_ids
, GCMDriverTest::WAIT
);
582 const std::string expected_registration_id
=
583 FakeGCMClient::GenerateGCMRegistrationID(sender_ids
);
585 EXPECT_EQ(expected_registration_id
, registration_id());
586 EXPECT_EQ(GCMClient::SUCCESS
, registration_result());
589 TEST_F(GCMDriverFunctionalTest
, RegisterError
) {
590 std::vector
<std::string
> sender_ids
;
591 sender_ids
.push_back("sender1@error");
592 Register(kTestAppID1
, sender_ids
, GCMDriverTest::WAIT
);
594 EXPECT_TRUE(registration_id().empty());
595 EXPECT_NE(GCMClient::SUCCESS
, registration_result());
598 TEST_F(GCMDriverFunctionalTest
, RegisterAgainWithSameSenderIDs
) {
599 std::vector
<std::string
> sender_ids
;
600 sender_ids
.push_back("sender1");
601 sender_ids
.push_back("sender2");
602 Register(kTestAppID1
, sender_ids
, GCMDriverTest::WAIT
);
603 const std::string expected_registration_id
=
604 FakeGCMClient::GenerateGCMRegistrationID(sender_ids
);
606 EXPECT_EQ(expected_registration_id
, registration_id());
607 EXPECT_EQ(GCMClient::SUCCESS
, registration_result());
609 // Clears the results the would be set by the Register callback in preparation
610 // to call register 2nd time.
613 // Calling register 2nd time with the same set of sender IDs but different
614 // ordering will get back the same registration ID.
615 std::vector
<std::string
> another_sender_ids
;
616 another_sender_ids
.push_back("sender2");
617 another_sender_ids
.push_back("sender1");
618 Register(kTestAppID1
, another_sender_ids
, GCMDriverTest::WAIT
);
620 EXPECT_EQ(expected_registration_id
, registration_id());
621 EXPECT_EQ(GCMClient::SUCCESS
, registration_result());
624 TEST_F(GCMDriverFunctionalTest
, RegisterAgainWithDifferentSenderIDs
) {
625 std::vector
<std::string
> sender_ids
;
626 sender_ids
.push_back("sender1");
627 Register(kTestAppID1
, sender_ids
, GCMDriverTest::WAIT
);
628 const std::string expected_registration_id
=
629 FakeGCMClient::GenerateGCMRegistrationID(sender_ids
);
631 EXPECT_EQ(expected_registration_id
, registration_id());
632 EXPECT_EQ(GCMClient::SUCCESS
, registration_result());
634 // Make sender IDs different.
635 sender_ids
.push_back("sender2");
636 const std::string expected_registration_id2
=
637 FakeGCMClient::GenerateGCMRegistrationID(sender_ids
);
639 // Calling register 2nd time with the different sender IDs will get back a new
641 Register(kTestAppID1
, sender_ids
, GCMDriverTest::WAIT
);
642 EXPECT_EQ(expected_registration_id2
, registration_id());
643 EXPECT_EQ(GCMClient::SUCCESS
, registration_result());
646 TEST_F(GCMDriverFunctionalTest
, UnregisterExplicitly
) {
647 std::vector
<std::string
> sender_ids
;
648 sender_ids
.push_back("sender1");
649 Register(kTestAppID1
, sender_ids
, GCMDriverTest::WAIT
);
651 EXPECT_FALSE(registration_id().empty());
652 EXPECT_EQ(GCMClient::SUCCESS
, registration_result());
654 Unregister(kTestAppID1
, GCMDriverTest::WAIT
);
656 EXPECT_EQ(GCMClient::SUCCESS
, unregistration_result());
659 TEST_F(GCMDriverFunctionalTest
, UnregisterWhenAsyncOperationPending
) {
660 std::vector
<std::string
> sender_ids
;
661 sender_ids
.push_back("sender1");
662 // First start registration without waiting for it to complete.
663 Register(kTestAppID1
, sender_ids
, GCMDriverTest::DO_NOT_WAIT
);
665 // Test that unregistration fails with async operation pending when there is a
666 // registration already in progress.
667 Unregister(kTestAppID1
, GCMDriverTest::WAIT
);
668 EXPECT_EQ(GCMClient::ASYNC_OPERATION_PENDING
,
669 unregistration_result());
671 // Complete the unregistration.
672 WaitForAsyncOperation();
673 EXPECT_EQ(GCMClient::SUCCESS
, registration_result());
675 // Start unregistration without waiting for it to complete. This time no async
676 // operation is pending.
677 Unregister(kTestAppID1
, GCMDriverTest::DO_NOT_WAIT
);
679 // Test that unregistration fails with async operation pending when there is
680 // an unregistration already in progress.
681 Unregister(kTestAppID1
, GCMDriverTest::WAIT
);
682 EXPECT_EQ(GCMClient::ASYNC_OPERATION_PENDING
,
683 unregistration_result());
686 // Complete unregistration.
687 WaitForAsyncOperation();
688 EXPECT_EQ(GCMClient::SUCCESS
, unregistration_result());
691 TEST_F(GCMDriverFunctionalTest
, RegisterWhenAsyncOperationPending
) {
692 std::vector
<std::string
> sender_ids
;
693 sender_ids
.push_back("sender1");
694 // First start registration without waiting for it to complete.
695 Register(kTestAppID1
, sender_ids
, GCMDriverTest::DO_NOT_WAIT
);
697 // Test that registration fails with async operation pending when there is a
698 // registration already in progress.
699 Register(kTestAppID1
, sender_ids
, GCMDriverTest::WAIT
);
700 EXPECT_EQ(GCMClient::ASYNC_OPERATION_PENDING
,
701 registration_result());
704 // Complete the registration.
705 WaitForAsyncOperation();
706 EXPECT_EQ(GCMClient::SUCCESS
, registration_result());
709 TEST_F(GCMDriverFunctionalTest
, RegisterAfterUnfinishedUnregister
) {
710 // Register and wait for it to complete.
711 std::vector
<std::string
> sender_ids
;
712 sender_ids
.push_back("sender1");
713 Register(kTestAppID1
, sender_ids
, GCMDriverTest::WAIT
);
714 EXPECT_EQ(GCMClient::SUCCESS
, registration_result());
715 EXPECT_EQ(FakeGCMClient::GenerateGCMRegistrationID(sender_ids
),
718 // Clears the results the would be set by the Register callback in preparation
719 // to call register 2nd time.
722 // Start unregistration without waiting for it to complete.
723 Unregister(kTestAppID1
, GCMDriverTest::DO_NOT_WAIT
);
725 // Register immeidately after unregistration is not completed.
726 sender_ids
.push_back("sender2");
727 Register(kTestAppID1
, sender_ids
, GCMDriverTest::WAIT
);
729 // We need one more waiting since the waiting in Register is indeed for
730 // uncompleted Unregister.
731 WaitForAsyncOperation();
732 EXPECT_EQ(GCMClient::SUCCESS
, registration_result());
733 EXPECT_EQ(FakeGCMClient::GenerateGCMRegistrationID(sender_ids
),
737 TEST_F(GCMDriverFunctionalTest
, Send
) {
738 GCMClient::OutgoingMessage message
;
739 message
.id
= "1@ack";
740 message
.data
["key1"] = "value1";
741 message
.data
["key2"] = "value2";
742 Send(kTestAppID1
, kUserID1
, message
, GCMDriverTest::WAIT
);
744 EXPECT_EQ(message
.id
, send_message_id());
745 EXPECT_EQ(GCMClient::SUCCESS
, send_result());
747 gcm_app_handler()->WaitForNotification();
748 EXPECT_EQ(message
.id
, gcm_app_handler()->acked_message_id());
749 EXPECT_EQ(kTestAppID1
, gcm_app_handler()->app_id());
752 TEST_F(GCMDriverFunctionalTest
, SendError
) {
753 GCMClient::OutgoingMessage message
;
754 // Embedding error in id will tell the mock to simulate the send error.
755 message
.id
= "1@error";
756 message
.data
["key1"] = "value1";
757 message
.data
["key2"] = "value2";
758 Send(kTestAppID1
, kUserID1
, message
, GCMDriverTest::WAIT
);
760 EXPECT_EQ(message
.id
, send_message_id());
761 EXPECT_EQ(GCMClient::SUCCESS
, send_result());
763 // Wait for the send error.
764 gcm_app_handler()->WaitForNotification();
765 EXPECT_EQ(FakeGCMAppHandler::SEND_ERROR_EVENT
,
766 gcm_app_handler()->received_event());
767 EXPECT_EQ(kTestAppID1
, gcm_app_handler()->app_id());
768 EXPECT_EQ(message
.id
,
769 gcm_app_handler()->send_error_details().message_id
);
770 EXPECT_NE(GCMClient::SUCCESS
,
771 gcm_app_handler()->send_error_details().result
);
772 EXPECT_EQ(message
.data
,
773 gcm_app_handler()->send_error_details().additional_data
);
776 TEST_F(GCMDriverFunctionalTest
, MessageReceived
) {
777 // GCM registration has to be performed otherwise GCM will not be started.
778 Register(kTestAppID1
, ToSenderList("sender"), GCMDriverTest::WAIT
);
780 GCMClient::IncomingMessage message
;
781 message
.data
["key1"] = "value1";
782 message
.data
["key2"] = "value2";
783 message
.sender_id
= "sender";
784 GetGCMClient()->ReceiveMessage(kTestAppID1
, message
);
785 gcm_app_handler()->WaitForNotification();
786 EXPECT_EQ(FakeGCMAppHandler::MESSAGE_EVENT
,
787 gcm_app_handler()->received_event());
788 EXPECT_EQ(kTestAppID1
, gcm_app_handler()->app_id());
789 EXPECT_EQ(message
.data
, gcm_app_handler()->message().data
);
790 EXPECT_TRUE(gcm_app_handler()->message().collapse_key
.empty());
791 EXPECT_EQ(message
.sender_id
, gcm_app_handler()->message().sender_id
);
794 TEST_F(GCMDriverFunctionalTest
, MessageWithCollapseKeyReceived
) {
795 // GCM registration has to be performed otherwise GCM will not be started.
796 Register(kTestAppID1
, ToSenderList("sender"), GCMDriverTest::WAIT
);
798 GCMClient::IncomingMessage message
;
799 message
.data
["key1"] = "value1";
800 message
.collapse_key
= "collapse_key_value";
801 message
.sender_id
= "sender";
802 GetGCMClient()->ReceiveMessage(kTestAppID1
, message
);
803 gcm_app_handler()->WaitForNotification();
804 EXPECT_EQ(FakeGCMAppHandler::MESSAGE_EVENT
,
805 gcm_app_handler()->received_event());
806 EXPECT_EQ(kTestAppID1
, gcm_app_handler()->app_id());
807 EXPECT_EQ(message
.data
, gcm_app_handler()->message().data
);
808 EXPECT_EQ(message
.collapse_key
,
809 gcm_app_handler()->message().collapse_key
);
812 TEST_F(GCMDriverFunctionalTest
, MessagesDeleted
) {
813 // GCM registration has to be performed otherwise GCM will not be started.
814 Register(kTestAppID1
, ToSenderList("sender"), GCMDriverTest::WAIT
);
816 GetGCMClient()->DeleteMessages(kTestAppID1
);
817 gcm_app_handler()->WaitForNotification();
818 EXPECT_EQ(FakeGCMAppHandler::MESSAGES_DELETED_EVENT
,
819 gcm_app_handler()->received_event());
820 EXPECT_EQ(kTestAppID1
, gcm_app_handler()->app_id());
823 TEST_F(GCMDriverFunctionalTest
, LastTokenFetchTime
) {
824 // GCM registration has to be performed otherwise GCM will not be started.
825 Register(kTestAppID1
, ToSenderList("sender"), GCMDriverTest::WAIT
);
827 EXPECT_EQ(base::Time(), driver()->GetLastTokenFetchTime());
828 base::Time fetch_time
= base::Time::Now();
829 driver()->SetLastTokenFetchTime(fetch_time
);
830 EXPECT_EQ(fetch_time
, driver()->GetLastTokenFetchTime());
833 // Tests a single instance of GCMDriver.
834 class GCMChannelStatusSyncerTest
: public GCMDriverTest
{
836 GCMChannelStatusSyncerTest();
837 ~GCMChannelStatusSyncerTest() override
;
840 void SetUp() override
;
842 void CompleteGCMChannelStatusRequest(bool enabled
, int poll_interval_seconds
);
843 bool CompareDelaySeconds(int64 expected_delay_seconds
,
844 int64 actual_delay_seconds
);
846 GCMChannelStatusSyncer
* syncer() {
847 return driver()->gcm_channel_status_syncer_for_testing();
851 net::TestURLFetcherFactory url_fetcher_factory_
;
853 DISALLOW_COPY_AND_ASSIGN(GCMChannelStatusSyncerTest
);
856 GCMChannelStatusSyncerTest::GCMChannelStatusSyncerTest() {
859 GCMChannelStatusSyncerTest::~GCMChannelStatusSyncerTest() {
862 void GCMChannelStatusSyncerTest::SetUp() {
863 GCMDriverTest::SetUp();
865 url_fetcher_factory_
.set_remove_fetcher_on_delete(true);
867 // Turn on all-user support.
868 ASSERT_TRUE(base::FieldTrialList::CreateFieldTrial("GCM", "Enabled"));
871 void GCMChannelStatusSyncerTest::CompleteGCMChannelStatusRequest(
872 bool enabled
, int poll_interval_seconds
) {
873 sync_pb::ExperimentStatusResponse response_proto
;
874 sync_pb::ExperimentsSpecifics
* experiment_specifics
=
875 response_proto
.add_experiment();
876 experiment_specifics
->mutable_gcm_channel()->set_enabled(enabled
);
878 if (poll_interval_seconds
)
879 response_proto
.set_poll_interval_seconds(poll_interval_seconds
);
881 std::string response_string
;
882 response_proto
.SerializeToString(&response_string
);
884 net::TestURLFetcher
* fetcher
= url_fetcher_factory_
.GetFetcherByID(0);
885 ASSERT_TRUE(fetcher
);
886 fetcher
->set_response_code(net::HTTP_OK
);
887 fetcher
->SetResponseString(response_string
);
888 fetcher
->delegate()->OnURLFetchComplete(fetcher
);
891 bool GCMChannelStatusSyncerTest::CompareDelaySeconds(
892 int64 expected_delay_seconds
, int64 actual_delay_seconds
) {
893 // Most of time, the actual delay should not be smaller than the expected
895 if (actual_delay_seconds
>= expected_delay_seconds
)
897 // It is also OK that the actual delay is a bit smaller than the expected
898 // delay in case that the test runs slowly.
899 return expected_delay_seconds
- actual_delay_seconds
< 30;
902 TEST_F(GCMChannelStatusSyncerTest
, DisableAndEnable
) {
903 // Create GCMDriver first. By default, GCM is enabled.
905 EXPECT_TRUE(driver()->gcm_enabled());
906 EXPECT_TRUE(syncer()->gcm_enabled());
908 // Remove delay such that the request could be executed immediately.
909 syncer()->set_delay_removed_for_testing(true);
911 // GCM is still enabled at this point.
913 EXPECT_TRUE(driver()->gcm_enabled());
914 EXPECT_TRUE(syncer()->gcm_enabled());
916 // Wait until the GCM channel status request gets triggered.
919 // Complete the request that disables the GCM.
920 CompleteGCMChannelStatusRequest(false, 0);
921 EXPECT_FALSE(driver()->gcm_enabled());
922 EXPECT_FALSE(syncer()->gcm_enabled());
923 EXPECT_FALSE(driver()->IsStarted());
925 // Wait until next GCM channel status request gets triggered.
928 // Complete the request that enables the GCM.
929 CompleteGCMChannelStatusRequest(true, 0);
930 EXPECT_TRUE(driver()->gcm_enabled());
931 EXPECT_TRUE(syncer()->gcm_enabled());
934 TEST_F(GCMChannelStatusSyncerTest
, DisableRestartAndEnable
) {
935 // Create GCMDriver first. By default, GCM is enabled.
937 EXPECT_TRUE(driver()->gcm_enabled());
938 EXPECT_TRUE(syncer()->gcm_enabled());
940 // Remove delay such that the request could be executed immediately.
941 syncer()->set_delay_removed_for_testing(true);
943 // GCM is still enabled at this point.
945 EXPECT_TRUE(driver()->gcm_enabled());
946 EXPECT_TRUE(syncer()->gcm_enabled());
948 // Wait until the GCM channel status request gets triggered.
951 // Complete the request that disables the GCM.
952 CompleteGCMChannelStatusRequest(false, 0);
953 EXPECT_FALSE(driver()->gcm_enabled());
954 EXPECT_FALSE(syncer()->gcm_enabled());
956 // Simulate browser start by recreating GCMDriver.
960 // Remove delay such that the request could be executed immediately.
961 syncer()->set_delay_removed_for_testing(true);
963 // GCM is still disabled.
964 EXPECT_FALSE(driver()->gcm_enabled());
965 EXPECT_FALSE(syncer()->gcm_enabled());
968 EXPECT_FALSE(driver()->gcm_enabled());
969 EXPECT_FALSE(syncer()->gcm_enabled());
971 // Wait until the GCM channel status request gets triggered.
974 // Complete the request that re-enables the GCM.
975 CompleteGCMChannelStatusRequest(true, 0);
976 EXPECT_TRUE(driver()->gcm_enabled());
977 EXPECT_TRUE(syncer()->gcm_enabled());
980 TEST_F(GCMChannelStatusSyncerTest
, FirstTimePolling
) {
985 // The 1st request should be triggered shortly without jittering.
986 EXPECT_EQ(GCMChannelStatusSyncer::first_time_delay_seconds(),
987 syncer()->current_request_delay_interval().InSeconds());
990 TEST_F(GCMChannelStatusSyncerTest
, SubsequentPollingWithDefaultInterval
) {
991 // Create GCMDriver first. GCM is not started.
994 // Remove delay such that the request could be executed immediately.
995 syncer()->set_delay_removed_for_testing(true);
997 // Now GCM is started.
1000 // Wait until the GCM channel status request gets triggered.
1003 // Keep delay such that we can find out the computed delay time.
1004 syncer()->set_delay_removed_for_testing(false);
1006 // Complete the request. The default interval is intact.
1007 CompleteGCMChannelStatusRequest(true, 0);
1009 // The next request should be scheduled at the expected default interval.
1010 int64 actual_delay_seconds
=
1011 syncer()->current_request_delay_interval().InSeconds();
1012 int64 expected_delay_seconds
=
1013 GCMChannelStatusRequest::default_poll_interval_seconds();
1014 EXPECT_TRUE(CompareDelaySeconds(expected_delay_seconds
, actual_delay_seconds
))
1015 << "expected delay: " << expected_delay_seconds
1016 << " actual delay: " << actual_delay_seconds
;
1018 // Simulate browser start by recreating GCMDriver.
1023 // After start-up, the request should still be scheduled at the expected
1024 // default interval.
1025 actual_delay_seconds
=
1026 syncer()->current_request_delay_interval().InSeconds();
1027 EXPECT_TRUE(CompareDelaySeconds(expected_delay_seconds
, actual_delay_seconds
))
1028 << "expected delay: " << expected_delay_seconds
1029 << " actual delay: " << actual_delay_seconds
;
1032 TEST_F(GCMChannelStatusSyncerTest
, SubsequentPollingWithUpdatedInterval
) {
1033 // Create GCMDriver first. GCM is not started.
1036 // Remove delay such that the request could be executed immediately.
1037 syncer()->set_delay_removed_for_testing(true);
1039 // Now GCM is started.
1042 // Wait until the GCM channel status request gets triggered.
1045 // Keep delay such that we can find out the computed delay time.
1046 syncer()->set_delay_removed_for_testing(false);
1048 // Complete the request. The interval is being changed.
1049 int new_poll_interval_seconds
=
1050 GCMChannelStatusRequest::default_poll_interval_seconds() * 2;
1051 CompleteGCMChannelStatusRequest(true, new_poll_interval_seconds
);
1053 // The next request should be scheduled at the expected updated interval.
1054 int64 actual_delay_seconds
=
1055 syncer()->current_request_delay_interval().InSeconds();
1056 int64 expected_delay_seconds
= new_poll_interval_seconds
;
1057 EXPECT_TRUE(CompareDelaySeconds(expected_delay_seconds
, actual_delay_seconds
))
1058 << "expected delay: " << expected_delay_seconds
1059 << " actual delay: " << actual_delay_seconds
;
1061 // Simulate browser start by recreating GCMDriver.
1066 // After start-up, the request should still be scheduled at the expected
1067 // updated interval.
1068 actual_delay_seconds
=
1069 syncer()->current_request_delay_interval().InSeconds();
1070 EXPECT_TRUE(CompareDelaySeconds(expected_delay_seconds
, actual_delay_seconds
))
1071 << "expected delay: " << expected_delay_seconds
1072 << " actual delay: " << actual_delay_seconds
;
1075 class GCMDriverInstanceIDTest
: public GCMDriverTest
{
1077 GCMDriverInstanceIDTest();
1078 ~GCMDriverInstanceIDTest() override
;
1081 void GetInstanceID(const std::string
& app_id
, WaitToFinish wait_to_finish
);
1082 void GetInstanceIDDataCompleted(const std::string
& instance_id
,
1083 const std::string
& extra_data
);
1084 void GetToken(const std::string
& app_id
,
1085 const std::string
& authorized_entity
,
1086 const std::string
& scope
,
1087 WaitToFinish wait_to_finish
);
1088 void DeleteToken(const std::string
& app_id
,
1089 const std::string
& authorized_entity
,
1090 const std::string
& scope
,
1091 WaitToFinish wait_to_finish
);
1093 std::string
instance_id() const { return instance_id_
; }
1094 std::string
extra_data() const { return extra_data_
; }
1097 std::string instance_id_
;
1098 std::string extra_data_
;
1100 DISALLOW_COPY_AND_ASSIGN(GCMDriverInstanceIDTest
);
1103 GCMDriverInstanceIDTest::GCMDriverInstanceIDTest() {
1106 GCMDriverInstanceIDTest::~GCMDriverInstanceIDTest() {
1109 void GCMDriverInstanceIDTest::GetReady() {
1116 void GCMDriverInstanceIDTest::GetInstanceID(const std::string
& app_id
,
1117 WaitToFinish wait_to_finish
) {
1118 base::RunLoop run_loop
;
1119 set_async_operation_completed_callback(run_loop
.QuitClosure());
1120 driver()->GetInstanceIDData(app_id
,
1121 base::Bind(&GCMDriverInstanceIDTest::GetInstanceIDDataCompleted
,
1122 base::Unretained(this)));
1123 if (wait_to_finish
== WAIT
)
1127 void GCMDriverInstanceIDTest::GetInstanceIDDataCompleted(
1128 const std::string
& instance_id
, const std::string
& extra_data
) {
1129 instance_id_
= instance_id
;
1130 extra_data_
= extra_data
;
1131 if (!async_operation_completed_callback().is_null())
1132 async_operation_completed_callback().Run();
1135 void GCMDriverInstanceIDTest::GetToken(const std::string
& app_id
,
1136 const std::string
& authorized_entity
,
1137 const std::string
& scope
,
1138 WaitToFinish wait_to_finish
) {
1139 base::RunLoop run_loop
;
1140 set_async_operation_completed_callback(run_loop
.QuitClosure());
1141 std::map
<std::string
, std::string
> options
;
1142 driver()->GetToken(app_id
,
1146 base::Bind(&GCMDriverTest::RegisterCompleted
,
1147 base::Unretained(this)));
1148 if (wait_to_finish
== WAIT
)
1152 void GCMDriverInstanceIDTest::DeleteToken(const std::string
& app_id
,
1153 const std::string
& authorized_entity
,
1154 const std::string
& scope
,
1155 WaitToFinish wait_to_finish
) {
1156 base::RunLoop run_loop
;
1157 set_async_operation_completed_callback(run_loop
.QuitClosure());
1158 driver()->DeleteToken(app_id
,
1161 base::Bind(&GCMDriverTest::UnregisterCompleted
,
1162 base::Unretained(this)));
1163 if (wait_to_finish
== WAIT
)
1167 TEST_F(GCMDriverInstanceIDTest
, InstanceIDData
) {
1170 driver()->AddInstanceIDData(kTestAppID1
, kInstanceID1
, "Foo");
1171 GetInstanceID(kTestAppID1
, GCMDriverTest::WAIT
);
1173 EXPECT_EQ(kInstanceID1
, instance_id());
1174 EXPECT_EQ("Foo", extra_data());
1176 driver()->RemoveInstanceIDData(kTestAppID1
);
1177 GetInstanceID(kTestAppID1
, GCMDriverTest::WAIT
);
1179 EXPECT_TRUE(instance_id().empty());
1180 EXPECT_TRUE(extra_data().empty());
1183 TEST_F(GCMDriverInstanceIDTest
, GCMClientNotReadyBeforeInstanceIDData
) {
1188 // Make GCMClient not ready until PerformDelayedStart is called.
1189 GetGCMClient()->set_start_mode_overridding(
1190 FakeGCMClient::FORCE_TO_ALWAYS_DELAY_START_GCM
);
1194 // All operations are on hold until GCMClient is ready.
1195 driver()->AddInstanceIDData(kTestAppID1
, kInstanceID1
, "Foo");
1196 driver()->AddInstanceIDData(kTestAppID2
, kInstanceID2
, "Bar");
1197 driver()->RemoveInstanceIDData(kTestAppID1
);
1198 GetInstanceID(kTestAppID2
, GCMDriverTest::DO_NOT_WAIT
);
1201 EXPECT_TRUE(instance_id().empty());
1202 EXPECT_TRUE(extra_data().empty());
1204 // All operations will be performed after GCMClient becomes ready.
1205 GetGCMClient()->PerformDelayedStart();
1206 WaitForAsyncOperation();
1207 EXPECT_EQ(kInstanceID2
, instance_id());
1208 EXPECT_EQ("Bar", extra_data());
1211 TEST_F(GCMDriverInstanceIDTest
, GetToken
) {
1214 const std::string expected_token
=
1215 FakeGCMClient::GenerateInstanceIDToken(kUserID1
, kScope
);
1216 GetToken(kTestAppID1
, kUserID1
, kScope
, GCMDriverTest::WAIT
);
1218 EXPECT_EQ(expected_token
, registration_id());
1219 EXPECT_EQ(GCMClient::SUCCESS
, registration_result());
1222 TEST_F(GCMDriverInstanceIDTest
, GetTokenError
) {
1225 std::string error_entity
= "sender@error";
1226 GetToken(kTestAppID1
, error_entity
, kScope
, GCMDriverTest::WAIT
);
1228 EXPECT_TRUE(registration_id().empty());
1229 EXPECT_NE(GCMClient::SUCCESS
, registration_result());
1232 TEST_F(GCMDriverInstanceIDTest
, GCMClientNotReadyBeforeGetToken
) {
1237 // Make GCMClient not ready until PerformDelayedStart is called.
1238 GetGCMClient()->set_start_mode_overridding(
1239 FakeGCMClient::FORCE_TO_ALWAYS_DELAY_START_GCM
);
1243 // GetToken operation is on hold until GCMClient is ready.
1244 GetToken(kTestAppID1
, kUserID1
, kScope
, GCMDriverTest::DO_NOT_WAIT
);
1247 EXPECT_TRUE(registration_id().empty());
1248 EXPECT_EQ(GCMClient::UNKNOWN_ERROR
, registration_result());
1250 // GetToken operation will be invoked after GCMClient becomes ready.
1251 GetGCMClient()->PerformDelayedStart();
1252 WaitForAsyncOperation();
1253 EXPECT_FALSE(registration_id().empty());
1254 EXPECT_EQ(GCMClient::SUCCESS
, registration_result());
1257 TEST_F(GCMDriverInstanceIDTest
, DeleteToken
) {
1260 const std::string expected_token
=
1261 FakeGCMClient::GenerateInstanceIDToken(kUserID1
, kScope
);
1262 GetToken(kTestAppID1
, kUserID1
, kScope
, GCMDriverTest::WAIT
);
1263 EXPECT_EQ(expected_token
, registration_id());
1264 EXPECT_EQ(GCMClient::SUCCESS
, registration_result());
1266 DeleteToken(kTestAppID1
, kUserID1
, kScope
, GCMDriverTest::WAIT
);
1267 EXPECT_EQ(GCMClient::SUCCESS
, unregistration_result());
1270 TEST_F(GCMDriverInstanceIDTest
, GCMClientNotReadyBeforeDeleteToken
) {
1275 // Make GCMClient not ready until PerformDelayedStart is called.
1276 GetGCMClient()->set_start_mode_overridding(
1277 FakeGCMClient::FORCE_TO_ALWAYS_DELAY_START_GCM
);
1281 // DeleteToken operation is on hold until GCMClient is ready.
1282 DeleteToken(kTestAppID1
, kUserID1
, kScope
, GCMDriverTest::DO_NOT_WAIT
);
1285 EXPECT_EQ(GCMClient::UNKNOWN_ERROR
, unregistration_result());
1287 // DeleteToken operation will be invoked after GCMClient becomes ready.
1288 GetGCMClient()->PerformDelayedStart();
1289 WaitForAsyncOperation();
1290 EXPECT_EQ(GCMClient::SUCCESS
, unregistration_result());