Upstream version 7.36.149.0
[platform/framework/web/crosswalk.git] / src / chrome / browser / services / gcm / gcm_service_unittest.cc
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.
4
5 #include "chrome/browser/services/gcm/gcm_service.h"
6
7 #include "base/bind.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/run_loop.h"
13 #include "base/strings/string_util.h"
14 #include "chrome/browser/services/gcm/fake_gcm_client_factory.h"
15 #include "chrome/browser/services/gcm/gcm_app_handler.h"
16 #include "chrome/browser/services/gcm/gcm_client_factory.h"
17 #include "chrome/browser/services/gcm/gcm_client_mock.h"
18 #include "content/public/browser/browser_thread.h"
19 #include "content/public/test/test_browser_thread_bundle.h"
20 #include "google_apis/gaia/fake_identity_provider.h"
21 #include "google_apis/gaia/fake_oauth2_token_service.h"
22 #include "net/url_request/url_request_context_getter.h"
23 #include "net/url_request/url_request_test_util.h"
24 #include "testing/gtest/include/gtest/gtest.h"
25
26 namespace gcm {
27
28 namespace {
29
30 const char kTestAccountID1[] = "user1@example.com";
31 const char kTestAccountID2[] = "user2@example.com";
32 const char kTestAccountID3[] = "user3@example.com";
33 const char kTestAppID1[] = "TestApp1";
34 const char kTestAppID2[] = "TestApp2";
35 const char kUserID1[] = "user1";
36 const char kUserID2[] = "user2";
37
38 void PumpCurrentLoop() {
39   base::MessageLoop::ScopedNestableTaskAllower
40       nestable_task_allower(base::MessageLoop::current());
41   base::RunLoop().RunUntilIdle();
42 }
43
44 void PumpUILoop() {
45   PumpCurrentLoop();
46 }
47
48 void PumpIOLoop() {
49   base::RunLoop run_loop;
50   content::BrowserThread::PostTaskAndReply(content::BrowserThread::IO,
51                                            FROM_HERE,
52                                            base::Bind(&PumpCurrentLoop),
53                                            run_loop.QuitClosure());
54   run_loop.Run();
55 }
56
57 std::vector<std::string> ToSenderList(const std::string& sender_ids) {
58   std::vector<std::string> senders;
59   Tokenize(sender_ids, ",", &senders);
60   return senders;
61 }
62
63 class FakeGCMAppHandler : public GCMAppHandler {
64  public:
65   enum Event {
66     NO_EVENT,
67     MESSAGE_EVENT,
68     MESSAGES_DELETED_EVENT,
69     SEND_ERROR_EVENT
70   };
71
72   FakeGCMAppHandler();
73   virtual ~FakeGCMAppHandler();
74
75   const Event& received_event() const { return received_event_; }
76   const std::string& app_id() const { return app_id_; }
77   const GCMClient::IncomingMessage& message() const { return message_; }
78   const GCMClient::SendErrorDetails& send_error_details() const {
79     return send_error_details_;
80   }
81
82   void WaitForNotification();
83
84   // GCMAppHandler:
85   virtual void ShutdownHandler() OVERRIDE;
86   virtual void OnMessage(const std::string& app_id,
87                          const GCMClient::IncomingMessage& message) OVERRIDE;
88   virtual void OnMessagesDeleted(const std::string& app_id) OVERRIDE;
89   virtual void OnSendError(
90       const std::string& app_id,
91       const GCMClient::SendErrorDetails& send_error_details) OVERRIDE;
92
93  private:
94   void ClearResults();
95
96   scoped_ptr<base::RunLoop> run_loop_;
97
98   Event received_event_;
99   std::string app_id_;
100   GCMClient::IncomingMessage message_;
101   GCMClient::SendErrorDetails send_error_details_;
102
103   DISALLOW_COPY_AND_ASSIGN(FakeGCMAppHandler);
104 };
105
106 class TestGCMService : public GCMService {
107  public:
108   TestGCMService(
109       bool start_automatically,
110       scoped_ptr<IdentityProvider> identity_provider,
111       const scoped_refptr<net::URLRequestContextGetter>& request_context);
112   virtual ~TestGCMService();
113
114  protected:
115   // GCMService:
116   virtual bool ShouldStartAutomatically() const OVERRIDE;
117   virtual base::FilePath GetStorePath() const OVERRIDE;
118   virtual scoped_refptr<net::URLRequestContextGetter>
119       GetURLRequestContextGetter() const OVERRIDE;
120
121  private:
122   base::ScopedTempDir temp_dir_;
123   scoped_refptr<net::URLRequestContextGetter> request_context_;
124   const bool start_automatically_;
125
126   DISALLOW_COPY_AND_ASSIGN(TestGCMService);
127 };
128
129 FakeGCMAppHandler::FakeGCMAppHandler() : received_event_(NO_EVENT) {
130 }
131
132 FakeGCMAppHandler::~FakeGCMAppHandler() {
133 }
134
135 void FakeGCMAppHandler::WaitForNotification() {
136   run_loop_.reset(new base::RunLoop);
137   run_loop_->Run();
138   run_loop_.reset();
139 }
140
141 void FakeGCMAppHandler::ShutdownHandler() {
142 }
143
144 void FakeGCMAppHandler::OnMessage(const std::string& app_id,
145                                   const GCMClient::IncomingMessage& message) {
146   ClearResults();
147   received_event_ = MESSAGE_EVENT;
148   app_id_ = app_id;
149   message_ = message;
150   if (run_loop_)
151     run_loop_->Quit();
152 }
153
154 void FakeGCMAppHandler::OnMessagesDeleted(const std::string& app_id) {
155   ClearResults();
156   received_event_ = MESSAGES_DELETED_EVENT;
157   app_id_ = app_id;
158   if (run_loop_)
159     run_loop_->Quit();
160 }
161
162 void FakeGCMAppHandler::OnSendError(
163     const std::string& app_id,
164     const GCMClient::SendErrorDetails& send_error_details) {
165   ClearResults();
166   received_event_ = SEND_ERROR_EVENT;
167   app_id_ = app_id;
168   send_error_details_ = send_error_details;
169   if (run_loop_)
170     run_loop_->Quit();
171 }
172
173 void FakeGCMAppHandler::ClearResults() {
174   received_event_ = NO_EVENT;
175   app_id_.clear();
176   message_ = GCMClient::IncomingMessage();
177   send_error_details_ = GCMClient::SendErrorDetails();
178 }
179
180 TestGCMService::TestGCMService(
181     bool start_automatically,
182     scoped_ptr<IdentityProvider> identity_provider,
183     const scoped_refptr<net::URLRequestContextGetter>& request_context)
184     : GCMService(identity_provider.Pass()),
185       request_context_(request_context),
186       start_automatically_(start_automatically) {
187   if (!temp_dir_.CreateUniqueTempDir())
188     ADD_FAILURE();
189 }
190
191 TestGCMService::~TestGCMService() {
192 }
193
194 bool TestGCMService::ShouldStartAutomatically() const {
195   return start_automatically_;
196 }
197
198 base::FilePath TestGCMService::GetStorePath() const {
199   return temp_dir_.path();
200 }
201
202 scoped_refptr<net::URLRequestContextGetter>
203 TestGCMService::GetURLRequestContextGetter() const {
204   return request_context_;
205 }
206
207 }  // namespace
208
209 class TestGCMServiceWrapper {
210  public:
211   enum WaitToFinish {
212     DO_NOT_WAIT,
213     WAIT
214   };
215
216   explicit TestGCMServiceWrapper(
217       const scoped_refptr<net::URLRequestContextGetter>& request_context);
218   ~TestGCMServiceWrapper();
219
220   TestGCMService* service() { return service_.get(); }
221   FakeGCMAppHandler* gcm_app_handler() { return gcm_app_handler_.get(); }
222   const std::string& registration_id() const { return registration_id_; }
223   GCMClient::Result registration_result() const { return registration_result_; }
224   const std::string& send_message_id() const { return send_message_id_; }
225   GCMClient::Result send_result() const { return send_result_; }
226   GCMClient::Result unregistration_result() const {
227     return unregistration_result_;
228   }
229
230   void ClearRegistrationResult();
231   void ClearUnregistrationResult();
232
233   bool ServiceHasAppHandlers() const;
234   GCMClientMock* GetGCMClient();
235
236   void CreateService(bool start_automatically,
237                      GCMClientMock::LoadingDelay gcm_client_loading_delay);
238
239   void SignIn(const std::string& account_id);
240   void SignOut();
241
242   void Register(const std::string& app_id,
243                 const std::vector<std::string>& sender_ids,
244                 WaitToFinish wait_to_finish);
245   void Send(const std::string& app_id,
246             const std::string& receiver_id,
247             const GCMClient::OutgoingMessage& message,
248             WaitToFinish wait_to_finish);
249   void Unregister(const std::string& app_id, WaitToFinish wait_to_finish);
250
251   void WaitForAsyncOperation();
252
253  private:
254   void RegisterCompleted(const std::string& registration_id,
255                          GCMClient::Result result);
256   void SendCompleted(const std::string& message_id, GCMClient::Result result);
257   void UnregisterCompleted(GCMClient::Result result);
258
259   scoped_refptr<net::URLRequestContextGetter> request_context_;
260   FakeOAuth2TokenService token_service_;
261   scoped_ptr<FakeIdentityProvider> identity_provider_owner_;
262   FakeIdentityProvider* identity_provider_;
263   scoped_ptr<TestGCMService> service_;
264   scoped_ptr<FakeGCMAppHandler> gcm_app_handler_;
265
266   base::Closure async_operation_completed_callback_;
267
268   std::string registration_id_;
269   GCMClient::Result registration_result_;
270   std::string send_message_id_;
271   GCMClient::Result send_result_;
272   GCMClient::Result unregistration_result_;
273
274   DISALLOW_COPY_AND_ASSIGN(TestGCMServiceWrapper);
275 };
276
277 TestGCMServiceWrapper::TestGCMServiceWrapper(
278     const scoped_refptr<net::URLRequestContextGetter>& request_context)
279     : request_context_(request_context),
280       identity_provider_(NULL),
281       registration_result_(GCMClient::UNKNOWN_ERROR),
282       send_result_(GCMClient::UNKNOWN_ERROR),
283       unregistration_result_(GCMClient::UNKNOWN_ERROR) {
284   identity_provider_owner_.reset(new FakeIdentityProvider(&token_service_));
285   identity_provider_ = identity_provider_owner_.get();
286 }
287
288 TestGCMServiceWrapper::~TestGCMServiceWrapper() {
289   if (!service_)
290     return;
291
292   service_->ShutdownService();
293   service_.reset();
294   PumpIOLoop();
295 }
296
297 void TestGCMServiceWrapper::ClearRegistrationResult() {
298   registration_id_.clear();
299   registration_result_ = GCMClient::UNKNOWN_ERROR;
300 }
301
302 void TestGCMServiceWrapper::ClearUnregistrationResult() {
303   unregistration_result_ = GCMClient::UNKNOWN_ERROR;
304 }
305
306 bool TestGCMServiceWrapper::ServiceHasAppHandlers() const {
307   return !service_->app_handlers_.empty();
308 }
309
310 GCMClientMock* TestGCMServiceWrapper::GetGCMClient() {
311   return static_cast<GCMClientMock*>(service_->GetGCMClientForTesting());
312 }
313
314 void TestGCMServiceWrapper::CreateService(
315     bool start_automatically,
316     GCMClientMock::LoadingDelay gcm_client_loading_delay) {
317   service_.reset(new TestGCMService(
318       start_automatically,
319       identity_provider_owner_.PassAs<IdentityProvider>(),
320       request_context_));
321   service_->Initialize(scoped_ptr<GCMClientFactory>(
322       new FakeGCMClientFactory(gcm_client_loading_delay)));
323
324   gcm_app_handler_.reset(new FakeGCMAppHandler);
325   service_->AddAppHandler(kTestAppID1, gcm_app_handler_.get());
326   service_->AddAppHandler(kTestAppID2, gcm_app_handler_.get());
327 }
328
329 void TestGCMServiceWrapper::SignIn(const std::string& account_id) {
330   token_service_.AddAccount(account_id);
331   identity_provider_->LogIn(account_id);
332   PumpIOLoop();
333   PumpUILoop();
334 }
335
336 void TestGCMServiceWrapper::SignOut() {
337   identity_provider_->LogOut();
338   PumpIOLoop();
339   PumpUILoop();
340 }
341
342 void TestGCMServiceWrapper::Register(const std::string& app_id,
343                                      const std::vector<std::string>& sender_ids,
344                                      WaitToFinish wait_to_finish) {
345   base::RunLoop run_loop;
346   async_operation_completed_callback_ = run_loop.QuitClosure();
347   service_->Register(app_id,
348                      sender_ids,
349                      base::Bind(&TestGCMServiceWrapper::RegisterCompleted,
350                                 base::Unretained(this)));
351   if (wait_to_finish == WAIT)
352     run_loop.Run();
353 }
354
355 void TestGCMServiceWrapper::Send(const std::string& app_id,
356                                  const std::string& receiver_id,
357                                  const GCMClient::OutgoingMessage& message,
358                                  WaitToFinish wait_to_finish) {
359   base::RunLoop run_loop;
360   async_operation_completed_callback_ = run_loop.QuitClosure();
361   service_->Send(app_id,
362                  receiver_id,
363                  message,
364                  base::Bind(&TestGCMServiceWrapper::SendCompleted,
365                             base::Unretained(this)));
366   if (wait_to_finish == WAIT)
367     run_loop.Run();
368 }
369
370 void TestGCMServiceWrapper::Unregister(const std::string& app_id,
371                                        WaitToFinish wait_to_finish) {
372   base::RunLoop run_loop;
373   async_operation_completed_callback_ = run_loop.QuitClosure();
374   service_->Unregister(app_id,
375                        base::Bind(&TestGCMServiceWrapper::UnregisterCompleted,
376                                   base::Unretained(this)));
377   if (wait_to_finish == WAIT)
378     run_loop.Run();
379 }
380
381 void TestGCMServiceWrapper::WaitForAsyncOperation() {
382   base::RunLoop run_loop;
383   async_operation_completed_callback_ = run_loop.QuitClosure();
384   run_loop.Run();
385 }
386
387 void TestGCMServiceWrapper::RegisterCompleted(
388     const std::string& registration_id,
389     GCMClient::Result result) {
390   registration_id_ = registration_id;
391   registration_result_ = result;
392   if (!async_operation_completed_callback_.is_null())
393     async_operation_completed_callback_.Run();
394 }
395
396 void TestGCMServiceWrapper::SendCompleted(const std::string& message_id,
397                                           GCMClient::Result result) {
398   send_message_id_ = message_id;
399   send_result_ = result;
400   if (!async_operation_completed_callback_.is_null())
401     async_operation_completed_callback_.Run();
402 }
403
404 void TestGCMServiceWrapper::UnregisterCompleted(GCMClient::Result result) {
405   unregistration_result_ = result;
406   if (!async_operation_completed_callback_.is_null())
407     async_operation_completed_callback_.Run();
408 }
409
410 class GCMServiceTest : public testing::Test {
411  protected:
412   GCMServiceTest();
413   virtual ~GCMServiceTest();
414
415   // testing::Test:
416   virtual void SetUp() OVERRIDE;
417   virtual void TearDown() OVERRIDE;
418
419   scoped_ptr<content::TestBrowserThreadBundle> thread_bundle_;
420   scoped_refptr<net::URLRequestContextGetter> request_context_;
421   scoped_ptr<TestGCMServiceWrapper> wrapper_;
422
423  private:
424   DISALLOW_COPY_AND_ASSIGN(GCMServiceTest);
425 };
426
427 GCMServiceTest::GCMServiceTest() {
428 }
429
430 GCMServiceTest::~GCMServiceTest() {
431 }
432
433 void GCMServiceTest::SetUp() {
434   thread_bundle_.reset(new content::TestBrowserThreadBundle(
435       content::TestBrowserThreadBundle::REAL_IO_THREAD));
436   request_context_ = new net::TestURLRequestContextGetter(
437       content::BrowserThread::GetMessageLoopProxyForThread(
438           content::BrowserThread::IO));
439   wrapper_.reset(new TestGCMServiceWrapper(request_context_));
440 }
441
442 void GCMServiceTest::TearDown() {
443   wrapper_.reset();
444 }
445
446 TEST_F(GCMServiceTest, CreateGCMServiceBeforeSignIn) {
447   // Create CreateGMCService first.
448   wrapper_->CreateService(true, GCMClientMock::NO_DELAY_LOADING);
449   EXPECT_FALSE(wrapper_->service()->IsStarted());
450
451   // Sign in. This will kick off the check-in.
452   wrapper_->SignIn(kTestAccountID1);
453   EXPECT_TRUE(wrapper_->service()->IsStarted());
454 }
455
456 TEST_F(GCMServiceTest, CreateGCMServiceAfterSignIn) {
457   // Sign in. This will not initiate the check-in.
458   wrapper_->SignIn(kTestAccountID1);
459
460   // Create GCMeService after sign-in.
461   wrapper_->CreateService(true, GCMClientMock::NO_DELAY_LOADING);
462   EXPECT_TRUE(wrapper_->service()->IsStarted());
463 }
464
465 TEST_F(GCMServiceTest, Shutdown) {
466   wrapper_->CreateService(true, GCMClientMock::NO_DELAY_LOADING);
467   EXPECT_TRUE(wrapper_->ServiceHasAppHandlers());
468
469   wrapper_->service()->ShutdownService();
470   EXPECT_FALSE(wrapper_->ServiceHasAppHandlers());
471 }
472
473 TEST_F(GCMServiceTest, SignInAndSignOutUnderPositiveChannelSignal) {
474   wrapper_->CreateService(true, GCMClientMock::NO_DELAY_LOADING);
475   wrapper_->SignIn(kTestAccountID1);
476
477   // GCMClient should be loaded.
478   EXPECT_TRUE(wrapper_->service()->IsGCMClientReady());
479   EXPECT_EQ(GCMClientMock::LOADED, wrapper_->GetGCMClient()->status());
480
481   wrapper_->SignOut();
482
483   // GCMClient should be checked out.
484   EXPECT_FALSE(wrapper_->service()->IsGCMClientReady());
485   EXPECT_EQ(GCMClientMock::CHECKED_OUT, wrapper_->GetGCMClient()->status());
486 }
487
488 TEST_F(GCMServiceTest, SignInAndSignOutUnderNonPositiveChannelSignal) {
489   // Non-positive channel signal will prevent GCMClient from checking in during
490   // sign-in.
491   wrapper_->CreateService(false, GCMClientMock::NO_DELAY_LOADING);
492   wrapper_->SignIn(kTestAccountID1);
493
494   // GCMClient should not be loaded.
495   EXPECT_FALSE(wrapper_->service()->IsGCMClientReady());
496   EXPECT_EQ(GCMClientMock::UNINITIALIZED, wrapper_->GetGCMClient()->status());
497
498   wrapper_->SignOut();
499
500   // Check-out should still be performed.
501   EXPECT_FALSE(wrapper_->service()->IsGCMClientReady());
502   EXPECT_EQ(GCMClientMock::CHECKED_OUT, wrapper_->GetGCMClient()->status());
503 }
504
505 TEST_F(GCMServiceTest, SignOutAndThenSignIn) {
506   wrapper_->CreateService(true, GCMClientMock::NO_DELAY_LOADING);
507   wrapper_->SignIn(kTestAccountID1);
508
509   // GCMClient should be loaded.
510   EXPECT_TRUE(wrapper_->service()->IsGCMClientReady());
511   EXPECT_EQ(GCMClientMock::LOADED, wrapper_->GetGCMClient()->status());
512
513   wrapper_->SignOut();
514
515   // GCMClient should be checked out.
516   EXPECT_FALSE(wrapper_->service()->IsGCMClientReady());
517   EXPECT_EQ(GCMClientMock::CHECKED_OUT, wrapper_->GetGCMClient()->status());
518
519   // Sign-in with a different account.
520   wrapper_->SignIn(kTestAccountID2);
521
522   // GCMClient should be loaded again.
523   EXPECT_TRUE(wrapper_->service()->IsGCMClientReady());
524   EXPECT_EQ(GCMClientMock::LOADED, wrapper_->GetGCMClient()->status());
525 }
526
527 TEST_F(GCMServiceTest, StopAndRestartGCM) {
528   wrapper_->CreateService(true, GCMClientMock::NO_DELAY_LOADING);
529   wrapper_->SignIn(kTestAccountID1);
530
531   // GCMClient should be loaded.
532   EXPECT_TRUE(wrapper_->service()->IsGCMClientReady());
533   EXPECT_EQ(GCMClientMock::LOADED, wrapper_->GetGCMClient()->status());
534
535   // Stops the GCM.
536   wrapper_->service()->Stop();
537   PumpIOLoop();
538   PumpUILoop();
539
540   // GCMClient should be stopped.
541   EXPECT_FALSE(wrapper_->service()->IsGCMClientReady());
542   EXPECT_EQ(GCMClientMock::STOPPED, wrapper_->GetGCMClient()->status());
543
544   // Restarts the GCM.
545   wrapper_->service()->Start();
546   PumpIOLoop();
547   PumpUILoop();
548
549   // GCMClient should be loaded.
550   EXPECT_TRUE(wrapper_->service()->IsGCMClientReady());
551   EXPECT_EQ(GCMClientMock::LOADED, wrapper_->GetGCMClient()->status());
552
553   // Stops the GCM.
554   wrapper_->service()->Stop();
555   PumpIOLoop();
556   PumpUILoop();
557
558   // GCMClient should be stopped.
559   EXPECT_FALSE(wrapper_->service()->IsGCMClientReady());
560   EXPECT_EQ(GCMClientMock::STOPPED, wrapper_->GetGCMClient()->status());
561
562   // Sign out.
563   wrapper_->SignOut();
564
565   // GCMClient should be checked out.
566   EXPECT_FALSE(wrapper_->service()->IsGCMClientReady());
567   EXPECT_EQ(GCMClientMock::CHECKED_OUT, wrapper_->GetGCMClient()->status());
568 }
569
570 TEST_F(GCMServiceTest, RegisterWhenNotSignedIn) {
571   wrapper_->CreateService(true, GCMClientMock::NO_DELAY_LOADING);
572
573   std::vector<std::string> sender_ids;
574   sender_ids.push_back("sender1");
575   wrapper_->Register(kTestAppID1, sender_ids, TestGCMServiceWrapper::WAIT);
576
577   EXPECT_TRUE(wrapper_->registration_id().empty());
578   EXPECT_EQ(GCMClient::NOT_SIGNED_IN, wrapper_->registration_result());
579 }
580
581 TEST_F(GCMServiceTest, RegisterUnderNonPositiveChannelSignal) {
582   // Non-positive channel signal will prevent GCMClient from checking in during
583   // sign-in.
584   wrapper_->CreateService(false, GCMClientMock::NO_DELAY_LOADING);
585   wrapper_->SignIn(kTestAccountID1);
586
587   // GCMClient should not be checked in.
588   EXPECT_FALSE(wrapper_->service()->IsGCMClientReady());
589   EXPECT_EQ(GCMClientMock::UNINITIALIZED, wrapper_->GetGCMClient()->status());
590
591   // Invoking register will make GCMClient checked in.
592   std::vector<std::string> sender_ids;
593   sender_ids.push_back("sender1");
594   wrapper_->Register(kTestAppID1, sender_ids, TestGCMServiceWrapper::WAIT);
595
596   // GCMClient should be checked in.
597   EXPECT_TRUE(wrapper_->service()->IsGCMClientReady());
598   EXPECT_EQ(GCMClientMock::LOADED, wrapper_->GetGCMClient()->status());
599
600   // Registration should succeed.
601   const std::string expected_registration_id =
602       GCMClientMock::GetRegistrationIdFromSenderIds(sender_ids);
603   EXPECT_EQ(expected_registration_id, wrapper_->registration_id());
604   EXPECT_EQ(GCMClient::SUCCESS, wrapper_->registration_result());
605 }
606
607 TEST_F(GCMServiceTest, SendWhenNotSignedIn) {
608   wrapper_->CreateService(true, GCMClientMock::NO_DELAY_LOADING);
609
610   GCMClient::OutgoingMessage message;
611   message.id = "1";
612   message.data["key1"] = "value1";
613   wrapper_->Send(kTestAppID1, kUserID1, message, TestGCMServiceWrapper::WAIT);
614
615   EXPECT_TRUE(wrapper_->send_message_id().empty());
616   EXPECT_EQ(GCMClient::NOT_SIGNED_IN, wrapper_->send_result());
617 }
618
619 TEST_F(GCMServiceTest, SendUnderNonPositiveChannelSignal) {
620   // Non-positive channel signal will prevent GCMClient from checking in during
621   // sign-in.
622   wrapper_->CreateService(false, GCMClientMock::NO_DELAY_LOADING);
623   wrapper_->SignIn(kTestAccountID1);
624
625   // GCMClient should not be checked in.
626   EXPECT_FALSE(wrapper_->service()->IsGCMClientReady());
627   EXPECT_EQ(GCMClientMock::UNINITIALIZED, wrapper_->GetGCMClient()->status());
628
629   // Invoking send will make GCMClient checked in.
630   GCMClient::OutgoingMessage message;
631   message.id = "1";
632   message.data["key1"] = "value1";
633   wrapper_->Send(kTestAppID1, kUserID1, message, TestGCMServiceWrapper::WAIT);
634
635   // GCMClient should be checked in.
636   EXPECT_TRUE(wrapper_->service()->IsGCMClientReady());
637   EXPECT_EQ(GCMClientMock::LOADED, wrapper_->GetGCMClient()->status());
638
639   // Sending should succeed.
640   EXPECT_EQ(message.id, wrapper_->send_message_id());
641   EXPECT_EQ(GCMClient::SUCCESS, wrapper_->send_result());
642 }
643
644 // Tests a single instance of GCMService.
645 class GCMServiceSingleInstanceTest : public GCMServiceTest {
646  public:
647   GCMServiceSingleInstanceTest();
648   virtual ~GCMServiceSingleInstanceTest();
649
650   // GCMServiceTest:
651   virtual void SetUp() OVERRIDE;
652
653  private:
654   DISALLOW_COPY_AND_ASSIGN(GCMServiceSingleInstanceTest);
655 };
656
657 GCMServiceSingleInstanceTest::GCMServiceSingleInstanceTest() {
658 }
659
660 GCMServiceSingleInstanceTest::~GCMServiceSingleInstanceTest() {
661 }
662
663 void GCMServiceSingleInstanceTest::SetUp() {
664   GCMServiceTest::SetUp();
665
666   wrapper_->CreateService(true, GCMClientMock::NO_DELAY_LOADING);
667   wrapper_->SignIn(kTestAccountID1);
668 }
669
670 TEST_F(GCMServiceSingleInstanceTest, Register) {
671   std::vector<std::string> sender_ids;
672   sender_ids.push_back("sender1");
673   wrapper_->Register(kTestAppID1, sender_ids, TestGCMServiceWrapper::WAIT);
674   const std::string expected_registration_id =
675       GCMClientMock::GetRegistrationIdFromSenderIds(sender_ids);
676
677   EXPECT_EQ(expected_registration_id, wrapper_->registration_id());
678   EXPECT_EQ(GCMClient::SUCCESS, wrapper_->registration_result());
679 }
680
681 TEST_F(GCMServiceSingleInstanceTest, RegisterError) {
682   std::vector<std::string> sender_ids;
683   sender_ids.push_back("sender1@error");
684   wrapper_->Register(kTestAppID1, sender_ids, TestGCMServiceWrapper::WAIT);
685
686   EXPECT_TRUE(wrapper_->registration_id().empty());
687   EXPECT_NE(GCMClient::SUCCESS, wrapper_->registration_result());
688 }
689
690 TEST_F(GCMServiceSingleInstanceTest, RegisterAgainWithSameSenderIDs) {
691   std::vector<std::string> sender_ids;
692   sender_ids.push_back("sender1");
693   sender_ids.push_back("sender2");
694   wrapper_->Register(kTestAppID1, sender_ids, TestGCMServiceWrapper::WAIT);
695   const std::string expected_registration_id =
696       GCMClientMock::GetRegistrationIdFromSenderIds(sender_ids);
697
698   EXPECT_EQ(expected_registration_id, wrapper_->registration_id());
699   EXPECT_EQ(GCMClient::SUCCESS, wrapper_->registration_result());
700
701   // Clears the results the would be set by the Register callback in preparation
702   // to call register 2nd time.
703   wrapper_->ClearRegistrationResult();
704
705   // Calling register 2nd time with the same set of sender IDs but different
706   // ordering will get back the same registration ID.
707   std::vector<std::string> another_sender_ids;
708   another_sender_ids.push_back("sender2");
709   another_sender_ids.push_back("sender1");
710   wrapper_->Register(kTestAppID1,
711                      another_sender_ids,
712                      TestGCMServiceWrapper::WAIT);
713
714   EXPECT_EQ(expected_registration_id, wrapper_->registration_id());
715   EXPECT_EQ(GCMClient::SUCCESS, wrapper_->registration_result());
716 }
717
718 TEST_F(GCMServiceSingleInstanceTest, RegisterAgainWithDifferentSenderIDs) {
719   std::vector<std::string> sender_ids;
720   sender_ids.push_back("sender1");
721   wrapper_->Register(kTestAppID1, sender_ids, TestGCMServiceWrapper::WAIT);
722   const std::string expected_registration_id =
723       GCMClientMock::GetRegistrationIdFromSenderIds(sender_ids);
724
725   EXPECT_EQ(expected_registration_id, wrapper_->registration_id());
726   EXPECT_EQ(GCMClient::SUCCESS, wrapper_->registration_result());
727
728   // Make sender IDs different.
729   sender_ids.push_back("sender2");
730   const std::string expected_registration_id2 =
731       GCMClientMock::GetRegistrationIdFromSenderIds(sender_ids);
732
733   // Calling register 2nd time with the different sender IDs will get back a new
734   // registration ID.
735   wrapper_->Register(kTestAppID1, sender_ids, TestGCMServiceWrapper::WAIT);
736   EXPECT_EQ(expected_registration_id2, wrapper_->registration_id());
737   EXPECT_EQ(GCMClient::SUCCESS, wrapper_->registration_result());
738 }
739
740 TEST_F(GCMServiceSingleInstanceTest, GCMClientNotReadyBeforeRegistration) {
741   // Make GCMClient not ready initially.
742   wrapper_.reset(new TestGCMServiceWrapper(request_context_));
743   wrapper_->CreateService(true, GCMClientMock::DELAY_LOADING);
744   wrapper_->SignIn(kTestAccountID1);
745
746   // The registration is on hold until GCMClient is ready.
747   std::vector<std::string> sender_ids;
748   sender_ids.push_back("sender1");
749   wrapper_->Register(kTestAppID1,
750                      sender_ids,
751                      TestGCMServiceWrapper::DO_NOT_WAIT);
752   PumpIOLoop();
753   PumpUILoop();
754   EXPECT_TRUE(wrapper_->registration_id().empty());
755   EXPECT_EQ(GCMClient::UNKNOWN_ERROR, wrapper_->registration_result());
756
757   // Register operation will be invoked after GCMClient becomes ready.
758   wrapper_->GetGCMClient()->PerformDelayedLoading();
759   wrapper_->WaitForAsyncOperation();
760   EXPECT_FALSE(wrapper_->registration_id().empty());
761   EXPECT_EQ(GCMClient::SUCCESS, wrapper_->registration_result());
762 }
763
764 TEST_F(GCMServiceSingleInstanceTest, RegisterAfterSignOut) {
765   // This will trigger check-out.
766   wrapper_->SignOut();
767
768   std::vector<std::string> sender_ids;
769   sender_ids.push_back("sender1");
770   wrapper_->Register(kTestAppID1, sender_ids, TestGCMServiceWrapper::WAIT);
771
772   EXPECT_TRUE(wrapper_->registration_id().empty());
773   EXPECT_EQ(GCMClient::NOT_SIGNED_IN, wrapper_->registration_result());
774 }
775
776 TEST_F(GCMServiceSingleInstanceTest, UnregisterExplicitly) {
777   std::vector<std::string> sender_ids;
778   sender_ids.push_back("sender1");
779   wrapper_->Register(kTestAppID1, sender_ids, TestGCMServiceWrapper::WAIT);
780
781   EXPECT_FALSE(wrapper_->registration_id().empty());
782   EXPECT_EQ(GCMClient::SUCCESS, wrapper_->registration_result());
783
784   wrapper_->Unregister(kTestAppID1, TestGCMServiceWrapper::WAIT);
785
786   EXPECT_EQ(GCMClient::SUCCESS, wrapper_->unregistration_result());
787 }
788
789 TEST_F(GCMServiceSingleInstanceTest, UnregisterWhenAsyncOperationPending) {
790   std::vector<std::string> sender_ids;
791   sender_ids.push_back("sender1");
792   // First start registration without waiting for it to complete.
793   wrapper_->Register(kTestAppID1,
794                      sender_ids,
795                      TestGCMServiceWrapper::DO_NOT_WAIT);
796
797   // Test that unregistration fails with async operation pending when there is a
798   // registration already in progress.
799   wrapper_->Unregister(kTestAppID1, TestGCMServiceWrapper::WAIT);
800   EXPECT_EQ(GCMClient::ASYNC_OPERATION_PENDING,
801             wrapper_->unregistration_result());
802
803   // Complete the unregistration.
804   wrapper_->WaitForAsyncOperation();
805   EXPECT_EQ(GCMClient::SUCCESS, wrapper_->registration_result());
806
807   // Start unregistration without waiting for it to complete. This time no async
808   // operation is pending.
809   wrapper_->Unregister(kTestAppID1, TestGCMServiceWrapper::DO_NOT_WAIT);
810
811   // Test that unregistration fails with async operation pending when there is
812   // an unregistration already in progress.
813   wrapper_->Unregister(kTestAppID1, TestGCMServiceWrapper::WAIT);
814   EXPECT_EQ(GCMClient::ASYNC_OPERATION_PENDING,
815             wrapper_->unregistration_result());
816   wrapper_->ClearUnregistrationResult();
817
818   // Complete unregistration.
819   wrapper_->WaitForAsyncOperation();
820   EXPECT_EQ(GCMClient::SUCCESS, wrapper_->unregistration_result());
821 }
822
823 TEST_F(GCMServiceSingleInstanceTest, RegisterWhenAsyncOperationPending) {
824   std::vector<std::string> sender_ids;
825   sender_ids.push_back("sender1");
826   // First start registration without waiting for it to complete.
827   wrapper_->Register(kTestAppID1,
828                      sender_ids,
829                      TestGCMServiceWrapper::DO_NOT_WAIT);
830
831   // Test that registration fails with async operation pending when there is a
832   // registration already in progress.
833   wrapper_->Register(kTestAppID1, sender_ids, TestGCMServiceWrapper::WAIT);
834   EXPECT_EQ(GCMClient::ASYNC_OPERATION_PENDING,
835             wrapper_->registration_result());
836   wrapper_->ClearRegistrationResult();
837
838   // Complete the registration.
839   wrapper_->WaitForAsyncOperation();
840   EXPECT_EQ(GCMClient::SUCCESS, wrapper_->registration_result());
841
842   // Start unregistration without waiting for it to complete. This time no async
843   // operation is pending.
844   wrapper_->Unregister(kTestAppID1, TestGCMServiceWrapper::DO_NOT_WAIT);
845
846   // Test that registration fails with async operation pending when there is an
847   // unregistration already in progress.
848   wrapper_->Register(kTestAppID1, sender_ids, TestGCMServiceWrapper::WAIT);
849   EXPECT_EQ(GCMClient::ASYNC_OPERATION_PENDING,
850             wrapper_->registration_result());
851
852   // Complete the first unregistration expecting success.
853   wrapper_->WaitForAsyncOperation();
854   EXPECT_EQ(GCMClient::SUCCESS, wrapper_->unregistration_result());
855
856   // Test that it is ok to register again after unregistration.
857   wrapper_->Register(kTestAppID1, sender_ids, TestGCMServiceWrapper::WAIT);
858   EXPECT_EQ(GCMClient::SUCCESS, wrapper_->registration_result());
859 }
860
861 TEST_F(GCMServiceSingleInstanceTest, Send) {
862   GCMClient::OutgoingMessage message;
863   message.id = "1";
864   message.data["key1"] = "value1";
865   message.data["key2"] = "value2";
866   wrapper_->Send(kTestAppID1, kUserID1, message, TestGCMServiceWrapper::WAIT);
867
868   EXPECT_EQ(message.id, wrapper_->send_message_id());
869   EXPECT_EQ(GCMClient::SUCCESS, wrapper_->send_result());
870 }
871
872 TEST_F(GCMServiceSingleInstanceTest, GCMClientNotReadyBeforeSending) {
873   // Make GCMClient not ready initially.
874   wrapper_.reset(new TestGCMServiceWrapper(request_context_));
875   wrapper_->CreateService(true, GCMClientMock::DELAY_LOADING);
876   wrapper_->SignIn(kTestAccountID1);
877
878   // The sending is on hold until GCMClient is ready.
879   GCMClient::OutgoingMessage message;
880   message.id = "1";
881   message.data["key1"] = "value1";
882   message.data["key2"] = "value2";
883   wrapper_->Send(kTestAppID1,
884                  kUserID1,
885                  message,
886                  TestGCMServiceWrapper::DO_NOT_WAIT);
887   PumpIOLoop();
888   PumpUILoop();
889
890   EXPECT_TRUE(wrapper_->send_message_id().empty());
891   EXPECT_EQ(GCMClient::UNKNOWN_ERROR, wrapper_->send_result());
892
893   // Send operation will be invoked after GCMClient becomes ready.
894   wrapper_->GetGCMClient()->PerformDelayedLoading();
895   wrapper_->WaitForAsyncOperation();
896   EXPECT_EQ(message.id, wrapper_->send_message_id());
897   EXPECT_EQ(GCMClient::SUCCESS, wrapper_->send_result());
898 }
899
900 TEST_F(GCMServiceSingleInstanceTest, SendAfterSignOut) {
901   // This will trigger check-out.
902   wrapper_->SignOut();
903
904   GCMClient::OutgoingMessage message;
905   message.id = "1";
906   message.data["key1"] = "value1";
907   message.data["key2"] = "value2";
908   wrapper_->Send(kTestAppID1, kUserID1, message, TestGCMServiceWrapper::WAIT);
909
910   EXPECT_TRUE(wrapper_->send_message_id().empty());
911   EXPECT_EQ(GCMClient::NOT_SIGNED_IN, wrapper_->send_result());
912 }
913
914 TEST_F(GCMServiceSingleInstanceTest, SendError) {
915   GCMClient::OutgoingMessage message;
916   // Embedding error in id will tell the mock to simulate the send error.
917   message.id = "1@error";
918   message.data["key1"] = "value1";
919   message.data["key2"] = "value2";
920   wrapper_->Send(kTestAppID1, kUserID1, message, TestGCMServiceWrapper::WAIT);
921
922   EXPECT_EQ(message.id, wrapper_->send_message_id());
923   EXPECT_EQ(GCMClient::SUCCESS, wrapper_->send_result());
924
925   // Wait for the send error.
926   wrapper_->gcm_app_handler()->WaitForNotification();
927   EXPECT_EQ(FakeGCMAppHandler::SEND_ERROR_EVENT,
928             wrapper_->gcm_app_handler()->received_event());
929   EXPECT_EQ(kTestAppID1, wrapper_->gcm_app_handler()->app_id());
930   EXPECT_EQ(message.id,
931             wrapper_->gcm_app_handler()->send_error_details().message_id);
932   EXPECT_NE(GCMClient::SUCCESS,
933             wrapper_->gcm_app_handler()->send_error_details().result);
934   EXPECT_EQ(message.data,
935             wrapper_->gcm_app_handler()->send_error_details().additional_data);
936 }
937
938 TEST_F(GCMServiceSingleInstanceTest, MessageReceived) {
939   wrapper_->Register(kTestAppID1,
940                      ToSenderList("sender"),
941                      TestGCMServiceWrapper::WAIT);
942   GCMClient::IncomingMessage message;
943   message.data["key1"] = "value1";
944   message.data["key2"] = "value2";
945   message.sender_id = "sender";
946   wrapper_->GetGCMClient()->ReceiveMessage(kTestAppID1, message);
947   wrapper_->gcm_app_handler()->WaitForNotification();
948   EXPECT_EQ(FakeGCMAppHandler::MESSAGE_EVENT,
949             wrapper_->gcm_app_handler()->received_event());
950   EXPECT_EQ(kTestAppID1, wrapper_->gcm_app_handler()->app_id());
951   EXPECT_EQ(message.data, wrapper_->gcm_app_handler()->message().data);
952   EXPECT_TRUE(wrapper_->gcm_app_handler()->message().collapse_key.empty());
953   EXPECT_EQ(message.sender_id,
954             wrapper_->gcm_app_handler()->message().sender_id);
955 }
956
957 TEST_F(GCMServiceSingleInstanceTest, MessageWithCollapseKeyReceived) {
958   wrapper_->Register(kTestAppID1,
959                      ToSenderList("sender"),
960                      TestGCMServiceWrapper::WAIT);
961   GCMClient::IncomingMessage message;
962   message.data["key1"] = "value1";
963   message.collapse_key = "collapse_key_value";
964   message.sender_id = "sender";
965   wrapper_->GetGCMClient()->ReceiveMessage(kTestAppID1, message);
966   wrapper_->gcm_app_handler()->WaitForNotification();
967   EXPECT_EQ(FakeGCMAppHandler::MESSAGE_EVENT,
968             wrapper_->gcm_app_handler()->received_event());
969   EXPECT_EQ(kTestAppID1, wrapper_->gcm_app_handler()->app_id());
970   EXPECT_EQ(message.data, wrapper_->gcm_app_handler()->message().data);
971   EXPECT_EQ(message.collapse_key,
972             wrapper_->gcm_app_handler()->message().collapse_key);
973 }
974
975 TEST_F(GCMServiceSingleInstanceTest, MessagesDeleted) {
976   wrapper_->GetGCMClient()->DeleteMessages(kTestAppID1);
977   wrapper_->gcm_app_handler()->WaitForNotification();
978   EXPECT_EQ(FakeGCMAppHandler::MESSAGES_DELETED_EVENT,
979             wrapper_->gcm_app_handler()->received_event());
980   EXPECT_EQ(kTestAppID1, wrapper_->gcm_app_handler()->app_id());
981 }
982
983 // Tests to make sure that concurrent GCMService instances work correctly
984 // regardless how GCMClient is created.
985 class GCMServiceMultipleInstanceTest : public GCMServiceTest {
986  protected:
987   GCMServiceMultipleInstanceTest();
988   virtual ~GCMServiceMultipleInstanceTest();
989
990   // GCMServiceTest:
991   virtual void SetUp() OVERRIDE;
992   virtual void TearDown() OVERRIDE;
993
994   scoped_ptr<TestGCMServiceWrapper> wrapper2_;
995
996  private:
997   DISALLOW_COPY_AND_ASSIGN(GCMServiceMultipleInstanceTest);
998 };
999
1000 GCMServiceMultipleInstanceTest::GCMServiceMultipleInstanceTest() {
1001 }
1002
1003 GCMServiceMultipleInstanceTest::~GCMServiceMultipleInstanceTest() {
1004 }
1005
1006 void GCMServiceMultipleInstanceTest::SetUp() {
1007   GCMServiceTest::SetUp();
1008
1009   wrapper2_.reset(new TestGCMServiceWrapper(request_context_));
1010
1011   wrapper_->CreateService(true, GCMClientMock::NO_DELAY_LOADING);
1012   wrapper2_->CreateService(true, GCMClientMock::NO_DELAY_LOADING);
1013
1014   // Initiate check-in for each instance.
1015   wrapper_->SignIn(kTestAccountID1);
1016   wrapper2_->SignIn(kTestAccountID2);
1017 }
1018
1019 void GCMServiceMultipleInstanceTest::TearDown() {
1020   wrapper2_.reset();
1021 }
1022
1023 TEST_F(GCMServiceMultipleInstanceTest, Register) {
1024   // Register an app.
1025   std::vector<std::string> sender_ids;
1026   sender_ids.push_back("sender1");
1027   wrapper_->Register(kTestAppID1, sender_ids, TestGCMServiceWrapper::WAIT);
1028
1029   // Register the same app in a different instance.
1030   std::vector<std::string> sender_ids2;
1031   sender_ids2.push_back("foo");
1032   sender_ids2.push_back("bar");
1033   wrapper2_->Register(kTestAppID1, sender_ids2, TestGCMServiceWrapper::WAIT);
1034
1035   EXPECT_EQ(GCMClientMock::GetRegistrationIdFromSenderIds(sender_ids),
1036             wrapper_->registration_id());
1037   EXPECT_EQ(GCMClient::SUCCESS, wrapper_->registration_result());
1038
1039   EXPECT_EQ(GCMClientMock::GetRegistrationIdFromSenderIds(sender_ids2),
1040             wrapper2_->registration_id());
1041   EXPECT_EQ(GCMClient::SUCCESS, wrapper2_->registration_result());
1042
1043   // Register a different app in a different instance.
1044   std::vector<std::string> sender_ids3;
1045   sender_ids3.push_back("sender1");
1046   sender_ids3.push_back("sender2");
1047   sender_ids3.push_back("sender3");
1048   wrapper2_->Register(kTestAppID2, sender_ids3, TestGCMServiceWrapper::WAIT);
1049
1050   EXPECT_EQ(GCMClientMock::GetRegistrationIdFromSenderIds(sender_ids3),
1051             wrapper2_->registration_id());
1052   EXPECT_EQ(GCMClient::SUCCESS, wrapper2_->registration_result());
1053 }
1054
1055 TEST_F(GCMServiceMultipleInstanceTest, Send) {
1056   // Send a message from one app in one instance.
1057   GCMClient::OutgoingMessage message;
1058   message.id = "1";
1059   message.data["key1"] = "value1";
1060   message.data["key2"] = "value2";
1061   wrapper_->Send(kTestAppID1, kUserID1, message, TestGCMServiceWrapper::WAIT);
1062
1063   // Send a message from same app in another instance.
1064   GCMClient::OutgoingMessage message2;
1065   message2.id = "2";
1066   message2.data["foo"] = "bar";
1067   wrapper2_->Send(kTestAppID1, kUserID2, message2, TestGCMServiceWrapper::WAIT);
1068
1069   EXPECT_EQ(message.id, wrapper_->send_message_id());
1070   EXPECT_EQ(GCMClient::SUCCESS, wrapper_->send_result());
1071
1072   EXPECT_EQ(message2.id, wrapper2_->send_message_id());
1073   EXPECT_EQ(GCMClient::SUCCESS, wrapper2_->send_result());
1074
1075   // Send another message from different app in another instance.
1076   GCMClient::OutgoingMessage message3;
1077   message3.id = "3";
1078   message3.data["hello"] = "world";
1079   wrapper2_->Send(kTestAppID2, kUserID1, message3, TestGCMServiceWrapper::WAIT);
1080
1081   EXPECT_EQ(message3.id, wrapper2_->send_message_id());
1082   EXPECT_EQ(GCMClient::SUCCESS, wrapper2_->send_result());
1083 }
1084
1085 TEST_F(GCMServiceMultipleInstanceTest, MessageReceived) {
1086   wrapper_->Register(kTestAppID1,
1087                      ToSenderList("sender"),
1088                      TestGCMServiceWrapper::WAIT);
1089   wrapper2_->Register(kTestAppID1,
1090                       ToSenderList("sender"),
1091                       TestGCMServiceWrapper::WAIT);
1092   wrapper2_->Register(kTestAppID2,
1093                       ToSenderList("sender2"),
1094                       TestGCMServiceWrapper::WAIT);
1095
1096   // Trigger an incoming message for an app in one instance.
1097   GCMClient::IncomingMessage message;
1098   message.data["key1"] = "value1";
1099   message.data["key2"] = "value2";
1100   message.sender_id = "sender";
1101   wrapper_->GetGCMClient()->ReceiveMessage(kTestAppID1, message);
1102   wrapper_->gcm_app_handler()->WaitForNotification();
1103
1104   // Trigger an incoming message for the same app in another instance.
1105   GCMClient::IncomingMessage message2;
1106   message2.data["foo"] = "bar";
1107   message2.sender_id = "sender";
1108   wrapper2_->GetGCMClient()->ReceiveMessage(kTestAppID1, message2);
1109   wrapper2_->gcm_app_handler()->WaitForNotification();
1110
1111   EXPECT_EQ(FakeGCMAppHandler::MESSAGE_EVENT,
1112             wrapper_->gcm_app_handler()->received_event());
1113   EXPECT_EQ(kTestAppID1, wrapper_->gcm_app_handler()->app_id());
1114   EXPECT_EQ(message.data, wrapper_->gcm_app_handler()->message().data);
1115   EXPECT_EQ("sender", wrapper_->gcm_app_handler()->message().sender_id);
1116
1117   EXPECT_EQ(FakeGCMAppHandler::MESSAGE_EVENT,
1118             wrapper2_->gcm_app_handler()->received_event());
1119   EXPECT_EQ(kTestAppID1, wrapper2_->gcm_app_handler()->app_id());
1120   EXPECT_EQ(message2.data, wrapper2_->gcm_app_handler()->message().data);
1121   EXPECT_EQ("sender", wrapper2_->gcm_app_handler()->message().sender_id);
1122
1123   // Trigger another incoming message for a different app in another instance.
1124   GCMClient::IncomingMessage message3;
1125   message3.data["bar1"] = "foo1";
1126   message3.data["bar2"] = "foo2";
1127   message3.sender_id = "sender2";
1128   wrapper2_->GetGCMClient()->ReceiveMessage(kTestAppID2, message3);
1129   wrapper2_->gcm_app_handler()->WaitForNotification();
1130
1131   EXPECT_EQ(FakeGCMAppHandler::MESSAGE_EVENT,
1132             wrapper2_->gcm_app_handler()->received_event());
1133   EXPECT_EQ(kTestAppID2, wrapper2_->gcm_app_handler()->app_id());
1134   EXPECT_EQ(message3.data, wrapper2_->gcm_app_handler()->message().data);
1135   EXPECT_EQ("sender2", wrapper2_->gcm_app_handler()->message().sender_id);
1136 }
1137
1138 // Test a set of GCM operations on multiple instances.
1139 // 1) Register 1 app in instance 1 and register 2 apps in instance 2;
1140 // 2) Send a message from instance 1;
1141 // 3) Receive a message to an app in instance 1 and receive a message for each
1142 //    of the two apps in instance 2;
1143 // 4) Send a message for each of the two apps in instance 2;
1144 // 5) Sign out of instance 1.
1145 // 6) Register/send stops working for instance 1;
1146 // 7) The app in instance 2 can still receive these events;
1147 // 8) Sign into instance 1 with a different account.
1148 // 9) The message to the newly signed-in account will be routed.
1149 TEST_F(GCMServiceMultipleInstanceTest, Combined) {
1150   // Register an app.
1151   std::vector<std::string> sender_ids;
1152   sender_ids.push_back("sender1");
1153   wrapper_->Register(kTestAppID1, sender_ids, TestGCMServiceWrapper::WAIT);
1154
1155   // Register the same app in a different instance.
1156   std::vector<std::string> sender_ids2;
1157   sender_ids2.push_back("foo");
1158   sender_ids2.push_back("bar");
1159   wrapper2_->Register(kTestAppID1, sender_ids2, TestGCMServiceWrapper::WAIT);
1160
1161   // Register a different app in a different instance.
1162   std::vector<std::string> sender_ids3;
1163   sender_ids3.push_back("sender1");
1164   sender_ids3.push_back("sender2");
1165   sender_ids3.push_back("sender3");
1166   wrapper2_->Register(kTestAppID2, sender_ids3, TestGCMServiceWrapper::WAIT);
1167
1168   EXPECT_EQ(GCMClientMock::GetRegistrationIdFromSenderIds(sender_ids),
1169             wrapper_->registration_id());
1170   EXPECT_EQ(GCMClient::SUCCESS, wrapper_->registration_result());
1171
1172   EXPECT_EQ(GCMClientMock::GetRegistrationIdFromSenderIds(sender_ids3),
1173             wrapper2_->registration_id());
1174   EXPECT_EQ(GCMClient::SUCCESS, wrapper2_->registration_result());
1175
1176   // Send a message from one instance.
1177   GCMClient::OutgoingMessage out_message;
1178   out_message.id = "1";
1179   out_message.data["out1"] = "out_data1";
1180   out_message.data["out1_2"] = "out_data1_2";
1181   wrapper_->Send(kTestAppID1,
1182                  kUserID1,
1183                  out_message,
1184                  TestGCMServiceWrapper::WAIT);
1185
1186   EXPECT_EQ(out_message.id, wrapper_->send_message_id());
1187   EXPECT_EQ(GCMClient::SUCCESS, wrapper_->send_result());
1188
1189   // Trigger an incoming message for an app in one instance.
1190   GCMClient::IncomingMessage in_message;
1191   in_message.data["in1"] = "in_data1";
1192   in_message.data["in1_2"] = "in_data1_2";
1193   in_message.sender_id = "sender1";
1194   wrapper_->GetGCMClient()->ReceiveMessage(kTestAppID1, in_message);
1195   wrapper_->gcm_app_handler()->WaitForNotification();
1196
1197   EXPECT_EQ(FakeGCMAppHandler::MESSAGE_EVENT,
1198             wrapper_->gcm_app_handler()->received_event());
1199   EXPECT_EQ(kTestAppID1, wrapper_->gcm_app_handler()->app_id());
1200   EXPECT_EQ(in_message.data, wrapper_->gcm_app_handler()->message().data);
1201
1202   // Trigger 2 incoming messages, one for each app respectively, in another
1203   // instance.
1204   GCMClient::IncomingMessage in_message2;
1205   in_message2.data["in2"] = "in_data2";
1206   in_message2.sender_id = "sender3";
1207   wrapper2_->GetGCMClient()->ReceiveMessage(kTestAppID2, in_message2);
1208
1209   GCMClient::IncomingMessage in_message3;
1210   in_message3.data["in3"] = "in_data3";
1211   in_message3.data["in3_2"] = "in_data3_2";
1212   in_message3.sender_id = "foo";
1213   wrapper2_->GetGCMClient()->ReceiveMessage(kTestAppID1, in_message3);
1214
1215   wrapper2_->gcm_app_handler()->WaitForNotification();
1216
1217   EXPECT_EQ(FakeGCMAppHandler::MESSAGE_EVENT,
1218             wrapper2_->gcm_app_handler()->received_event());
1219   EXPECT_EQ(kTestAppID2, wrapper2_->gcm_app_handler()->app_id());
1220   EXPECT_EQ(in_message2.data, wrapper2_->gcm_app_handler()->message().data);
1221
1222   wrapper2_->gcm_app_handler()->WaitForNotification();
1223
1224   EXPECT_EQ(FakeGCMAppHandler::MESSAGE_EVENT,
1225             wrapper2_->gcm_app_handler()->received_event());
1226   EXPECT_EQ(kTestAppID1, wrapper2_->gcm_app_handler()->app_id());
1227   EXPECT_EQ(in_message3.data, wrapper2_->gcm_app_handler()->message().data);
1228
1229   // Send two messages, one for each app respectively, from another instance.
1230   GCMClient::OutgoingMessage out_message2;
1231   out_message2.id = "2";
1232   out_message2.data["out2"] = "out_data2";
1233   wrapper2_->Send(kTestAppID1,
1234                   kUserID2,
1235                   out_message2,
1236                   TestGCMServiceWrapper::WAIT);
1237
1238   GCMClient::OutgoingMessage out_message3;
1239   out_message3.id = "3";
1240   out_message3.data["out3"] = "out_data3";
1241   wrapper2_->Send(kTestAppID2,
1242                   kUserID2,
1243                   out_message3,
1244                   TestGCMServiceWrapper::DO_NOT_WAIT);
1245
1246   EXPECT_EQ(out_message2.id, wrapper2_->send_message_id());
1247   EXPECT_EQ(GCMClient::SUCCESS, wrapper2_->send_result());
1248
1249   wrapper2_->WaitForAsyncOperation();
1250
1251   EXPECT_EQ(out_message3.id, wrapper2_->send_message_id());
1252   EXPECT_EQ(GCMClient::SUCCESS, wrapper2_->send_result());
1253
1254   // Sign out of one instance.
1255   wrapper_->SignOut();
1256
1257   // Register/send stops working for signed-out instance.
1258   wrapper_->Register(kTestAppID1, sender_ids, TestGCMServiceWrapper::WAIT);
1259   EXPECT_TRUE(wrapper_->registration_id().empty());
1260   EXPECT_EQ(GCMClient::NOT_SIGNED_IN, wrapper_->registration_result());
1261
1262   wrapper_->Send(kTestAppID2,
1263                  kUserID2,
1264                  out_message3,
1265                  TestGCMServiceWrapper::WAIT);
1266   EXPECT_TRUE(wrapper_->send_message_id().empty());
1267   EXPECT_EQ(GCMClient::NOT_SIGNED_IN, wrapper_->send_result());
1268
1269   // Deleted messages event will go through for another signed-in instance.
1270   wrapper2_->GetGCMClient()->DeleteMessages(kTestAppID2);
1271   wrapper2_->gcm_app_handler()->WaitForNotification();
1272
1273   EXPECT_EQ(FakeGCMAppHandler::MESSAGES_DELETED_EVENT,
1274             wrapper2_->gcm_app_handler()->received_event());
1275   EXPECT_EQ(kTestAppID2, wrapper2_->gcm_app_handler()->app_id());
1276
1277   // Send error event will go through for another signed-in instance.
1278   GCMClient::OutgoingMessage out_message4;
1279   out_message4.id = "1@error";
1280   out_message4.data["out4"] = "out_data4";
1281   wrapper2_->Send(kTestAppID1,
1282                   kUserID1,
1283                   out_message4,
1284                   TestGCMServiceWrapper::WAIT);
1285
1286   EXPECT_EQ(out_message4.id, wrapper2_->send_message_id());
1287   EXPECT_EQ(GCMClient::SUCCESS, wrapper2_->send_result());
1288
1289   wrapper2_->gcm_app_handler()->WaitForNotification();
1290   EXPECT_EQ(FakeGCMAppHandler::SEND_ERROR_EVENT,
1291             wrapper2_->gcm_app_handler()->received_event());
1292   EXPECT_EQ(kTestAppID1, wrapper2_->gcm_app_handler()->app_id());
1293   EXPECT_EQ(out_message4.id,
1294             wrapper2_->gcm_app_handler()->send_error_details().message_id);
1295   EXPECT_NE(GCMClient::SUCCESS,
1296             wrapper2_->gcm_app_handler()->send_error_details().result);
1297   EXPECT_EQ(out_message4.data,
1298             wrapper2_->gcm_app_handler()->send_error_details().additional_data);
1299
1300   // Sign in with a different account.
1301   wrapper_->SignIn(kTestAccountID3);
1302
1303   // Signing out cleared all registrations, so we need to register again.
1304   wrapper_->Register(kTestAppID1,
1305                      ToSenderList("sender1"),
1306                      TestGCMServiceWrapper::WAIT);
1307
1308   // Incoming message will go through for the new signed-in account.
1309   GCMClient::IncomingMessage in_message5;
1310   in_message5.data["in5"] = "in_data5";
1311   in_message5.sender_id = "sender1";
1312   wrapper_->GetGCMClient()->ReceiveMessage(kTestAppID1, in_message5);
1313
1314   wrapper_->gcm_app_handler()->WaitForNotification();
1315
1316   EXPECT_EQ(FakeGCMAppHandler::MESSAGE_EVENT,
1317             wrapper_->gcm_app_handler()->received_event());
1318   EXPECT_EQ(in_message5.data, wrapper_->gcm_app_handler()->message().data);
1319 }
1320
1321 }  // namespace gcm