summaryrefslogtreecommitdiffstats
path: root/chrome/browser/services/gcm/gcm_profile_service_unittest.cc
blob: 96310b2adeb02c4fbd970a08e5273a5f391ca6d5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include <algorithm>
#include <map>

#include "base/bind.h"
#include "base/command_line.h"
#include "base/message_loop/message_loop.h"
#include "base/prefs/pref_service.h"
#include "base/run_loop.h"
#include "chrome/browser/chrome_notification_types.h"
#include "chrome/browser/extensions/state_store.h"
#include "chrome/browser/extensions/test_extension_service.h"
#include "chrome/browser/extensions/test_extension_system.h"
#include "chrome/browser/services/gcm/gcm_client_factory.h"
#include "chrome/browser/services/gcm/gcm_client_mock.h"
#include "chrome/browser/services/gcm/gcm_event_router.h"
#include "chrome/browser/services/gcm/gcm_profile_service.h"
#include "chrome/browser/services/gcm/gcm_profile_service_factory.h"
#include "chrome/browser/signin/signin_manager_base.h"
#include "chrome/browser/signin/signin_manager_factory.h"
#include "chrome/browser/ui/browser.h"
#include "chrome/common/extensions/features/feature_channel.h"
#include "chrome/common/pref_names.h"
#include "chrome/test/base/testing_profile.h"
#include "components/webdata/encryptor/encryptor.h"
#include "content/public/browser/browser_thread.h"
#include "content/public/browser/notification_service.h"
#include "content/public/test/test_browser_thread_bundle.h"
#include "extensions/common/extension.h"
#include "extensions/common/manifest_constants.h"
#include "testing/gtest/include/gtest/gtest.h"

#if defined(OS_CHROMEOS)
#include "chrome/browser/chromeos/login/user_manager.h"
#include "chrome/browser/chromeos/settings/cros_settings.h"
#include "chrome/browser/chromeos/settings/device_settings_service.h"
#endif

using namespace extensions;

namespace gcm {

namespace {

const char kTestExtensionName[] = "FooBar";
const char kTestingUsername[] = "user1@example.com";
const char kTestingUsername2[] = "user2@example.com";
const char kTestingUsername3[] = "user3@example.com";
const char kTestingAppId[] = "TestApp1";
const char kTestingAppId2[] = "TestApp2";
const char kTestingSha1Cert[] = "testing_cert1";
const char kUserId[] = "user1";
const char kUserId2[] = "user2";

// Helper class for asynchrnous waiting.
class Waiter {
 public:
  Waiter() {}
  virtual ~Waiter() {}

  // Waits until the asynchrnous operation finishes.
  void WaitUntilCompleted() {
    run_loop_.reset(new base::RunLoop);
    run_loop_->Run();
  }

  // Signals that the asynchronous operation finishes.
  void SignalCompleted() {
    if (run_loop_ && run_loop_->running())
      run_loop_->Quit();
  }

  // Runs until IO loop becomes idle.
  void PumpIOLoop() {
    content::BrowserThread::PostTask(
        content::BrowserThread::IO,
        FROM_HERE,
        base::Bind(&Waiter::OnIOLoopPump, base::Unretained(this)));

    WaitUntilCompleted();
  }

 private:
  void PumpIOLoopCompleted() {
    DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));

    SignalCompleted();
  }

  void OnIOLoopPump() {
    DCHECK(content::BrowserThread::CurrentlyOn(content::BrowserThread::IO));

    base::MessageLoop::current()->RunUntilIdle();

    content::BrowserThread::PostTask(
        content::BrowserThread::UI,
        FROM_HERE,
        base::Bind(&Waiter::PumpIOLoopCompleted,
                   base::Unretained(this)));
  }

  scoped_ptr<base::RunLoop> run_loop_;
};

class FakeSigninManager : public SigninManagerBase {
 public:
  explicit FakeSigninManager(Profile* profile) {
    Initialize(profile, NULL);
  }

  virtual ~FakeSigninManager() {
  }

  void SignIn(const std::string& username) {
    SetAuthenticatedUsername(username);

    GoogleServiceSigninSuccessDetails details(GetAuthenticatedUsername(),
                                              std::string());
    content::NotificationService::current()->Notify(
        chrome::NOTIFICATION_GOOGLE_SIGNIN_SUCCESSFUL,
        content::Source<Profile>(profile_),
        content::Details<const GoogleServiceSigninSuccessDetails>(&details));
  }

  void SignOut() {
    clear_authenticated_username();

    GoogleServiceSignoutDetails details(GetAuthenticatedUsername());
    content::NotificationService::current()->Notify(
        chrome::NOTIFICATION_GOOGLE_SIGNED_OUT,
        content::Source<Profile>(profile_),
        content::Details<const GoogleServiceSignoutDetails>(&details));
  }
};

}  // namespace

class FakeGCMEventRouter : public GCMEventRouter {
 public:
  enum Event {
    NO_EVENT,
    MESSAGE_EVENT,
    MESSAGES_DELETED_EVENT,
    SEND_ERROR_EVENT
  };

  explicit FakeGCMEventRouter(Waiter* waiter)
      : waiter_(waiter),
        received_event_(NO_EVENT),
        send_error_result_(GCMClient::SUCCESS) {
  }

  virtual ~FakeGCMEventRouter() {
  }

  virtual void OnMessage(const std::string& app_id,
                         const GCMClient::IncomingMessage& message) OVERRIDE {
    clear_results();
    received_event_ = MESSAGE_EVENT;
    app_id_ = app_id;
    message_ = message;
    waiter_->SignalCompleted();
  }

  virtual void OnMessagesDeleted(const std::string& app_id) OVERRIDE {
    clear_results();
    received_event_ = MESSAGES_DELETED_EVENT;
    app_id_ = app_id;
    waiter_->SignalCompleted();
  }

  virtual void OnSendError(const std::string& app_id,
                           const std::string& message_id,
                           GCMClient::Result result) OVERRIDE {
    clear_results();
    received_event_ = SEND_ERROR_EVENT;
    app_id_ = app_id;
    send_error_message_id_ = message_id;
    send_error_result_ = result;
    waiter_->SignalCompleted();
  }

  Event received_event() const { return received_event_; }
  const std::string& app_id() const { return app_id_; }
  const GCMClient::IncomingMessage& message() const { return message_; }
  const std::string& send_message_id() const { return send_error_message_id_; }
  GCMClient::Result send_result() const { return send_error_result_; }

  void clear_results() {
    received_event_ = NO_EVENT;
    app_id_.clear();
    message_.data.clear();
    send_error_message_id_.clear();
    send_error_result_ = GCMClient::UNKNOWN_ERROR;
  }

 private:
  Waiter* waiter_;
  Event received_event_;
  std::string app_id_;
  GCMClient::IncomingMessage message_;
  std::string send_error_message_id_;
  GCMClient::Result send_error_result_;
};

class FakeGCMClientFactory : public GCMClientFactory {
 public:
  explicit FakeGCMClientFactory(GCMClientMock::Status gcm_client_initial_status)
      : gcm_client_initial_status_(gcm_client_initial_status),
        gcm_client_(NULL) {
  }

  virtual ~FakeGCMClientFactory() {
  }

  virtual scoped_ptr<GCMClient> BuildInstance() OVERRIDE {
    DCHECK(!gcm_client_);
    gcm_client_ = new GCMClientMock(gcm_client_initial_status_);
    return scoped_ptr<GCMClient>(gcm_client_);
  }

  GCMClientMock* gcm_client() const { return gcm_client_; }

 private:
  GCMClientMock::Status gcm_client_initial_status_;
  GCMClientMock* gcm_client_;

  DISALLOW_COPY_AND_ASSIGN(FakeGCMClientFactory);
};

class GCMProfileServiceTestConsumer : public GCMProfileService::TestingDelegate{
 public:
  static BrowserContextKeyedService* BuildFakeSigninManager(
      content::BrowserContext* context) {
    return new FakeSigninManager(static_cast<Profile*>(context));
  }

  static BrowserContextKeyedService* BuildGCMProfileService(
      content::BrowserContext* context) {
    return new GCMProfileService(static_cast<Profile*>(context));
  }

  explicit GCMProfileServiceTestConsumer(Waiter* waiter)
      : waiter_(waiter),
        extension_service_(NULL),
        signin_manager_(NULL),
        gcm_client_initial_status_(GCMClientMock::READY),
        registration_result_(GCMClient::SUCCESS),
        has_persisted_registration_info_(false),
        send_result_(GCMClient::SUCCESS) {
    // Create a new profile.
    profile_.reset(new TestingProfile);

    // Use a fake version of SigninManager.
    signin_manager_ = static_cast<FakeSigninManager*>(
        SigninManagerFactory::GetInstance()->SetTestingFactoryAndUse(
            profile(), &GCMProfileServiceTestConsumer::BuildFakeSigninManager));

    // Create extension service in order to uninstall the extension.
    extensions::TestExtensionSystem* extension_system(
        static_cast<extensions::TestExtensionSystem*>(
            extensions::ExtensionSystem::Get(profile())));
    extension_system->CreateExtensionService(
        CommandLine::ForCurrentProcess(), base::FilePath(), false);
    extension_service_ = extension_system->Get(profile())->extension_service();

    // Allow a testing delegate to be passed to GCMProfileService instance.
    GCMProfileService::enable_gcm_for_testing_ = true;
    CreateGCMProfileServiceInstance();

    // Mock a GCMEventRouter.
    gcm_event_router_.reset(new FakeGCMEventRouter(waiter_));
  }

  virtual ~GCMProfileServiceTestConsumer() {
  }

  // Returns a barebones test extension.
  scoped_refptr<Extension> CreateExtension() {
#if defined(OS_WIN)
    base::FilePath path(FILE_PATH_LITERAL("c:\\foo"));
#elif defined(OS_POSIX)
    base::FilePath path(FILE_PATH_LITERAL("/foo"));
#endif

    base::DictionaryValue manifest;
    manifest.SetString(manifest_keys::kVersion, "1.0.0.0");
    manifest.SetString(manifest_keys::kName, kTestExtensionName);
    base::ListValue* permission_list = new base::ListValue;
    permission_list->Append(base::Value::CreateStringValue("gcm"));
    manifest.Set(manifest_keys::kPermissions, permission_list);

    // TODO(jianli): Once the GCM API enters stable, remove |channel|.
    ScopedCurrentChannel channel(chrome::VersionInfo::CHANNEL_UNKNOWN);
    std::string error;
    scoped_refptr<Extension> extension =
        Extension::Create(path.AppendASCII(kTestExtensionName),
                          Manifest::INVALID_LOCATION,
                          manifest,
                          Extension::NO_FLAGS,
                          &error);
    EXPECT_TRUE(extension.get()) << error;
    EXPECT_TRUE(extension->HasAPIPermission(APIPermission::kGcm));

    extension_service_->AddExtension(extension.get());
    return extension;
  }

  void UninstallExtension(const extensions::Extension* extension) {
    extension_service_->UninstallExtension(extension->id(), false, NULL);
  }

  void ReloadExtension(const extensions::Extension* extension) {
    extension_service_->UnloadExtension(
        extension->id(), UnloadedExtensionInfo::REASON_TERMINATE);
    extension_service_->AddExtension(extension);
  }

  void CreateGCMProfileServiceInstance() {
    GCMProfileService* gcm_profile_service = static_cast<GCMProfileService*>(
        GCMProfileServiceFactory::GetInstance()->SetTestingFactoryAndUse(
            profile(), &GCMProfileServiceTestConsumer::BuildGCMProfileService));
    gcm_profile_service->set_testing_delegate(this);
    gcm_client_factory_.reset(
        new FakeGCMClientFactory(gcm_client_initial_status_));
    gcm_profile_service->Initialize(gcm_client_factory_.get());
  }

  void CheckIn(const std::string& username) {
    signin_manager_->SignIn(username);

    // This will cause GCMProfileService to be created if not yet. This will
    // also kick off the check-in if not yet.
    GetGCMProfileService();

    // Wait till the asynchronous check-in is done.
    waiter_->WaitUntilCompleted();
  }

  void Register(const std::string& app_id,
                const std::vector<std::string>& sender_ids) {
    GetGCMProfileService()->Register(
        app_id,
        sender_ids,
        kTestingSha1Cert,
        base::Bind(&GCMProfileServiceTestConsumer::RegisterCompleted,
                   base::Unretained(this)));
  }

  void RegisterCompleted(const std::string& registration_id,
                         GCMClient::Result result) {
    registration_id_ = registration_id;
    registration_result_ = result;
    waiter_->SignalCompleted();
  }

  bool HasPersistedRegistrationInfo(const std::string& app_id) {
    StateStore* storage = ExtensionSystem::Get(profile())->state_store();
    if (!storage)
      return false;
    has_persisted_registration_info_ = false;
    storage->GetExtensionValue(
        app_id,
        GCMProfileService::GetPersistentRegisterKeyForTesting(),
        base::Bind(
            &GCMProfileServiceTestConsumer::ReadRegistrationInfoFinished,
            base::Unretained(this)));
    waiter_->WaitUntilCompleted();
    return has_persisted_registration_info_;
  }

  void ReadRegistrationInfoFinished(scoped_ptr<base::Value> value) {
    has_persisted_registration_info_ = value.get() != NULL;
    waiter_->SignalCompleted();
  }

  void Send(const std::string& app_id,
            const std::string& receiver_id,
            const GCMClient::OutgoingMessage& message) {
    GetGCMProfileService()->Send(
        app_id,
        receiver_id,
        message,
        base::Bind(&GCMProfileServiceTestConsumer::SendCompleted,
                   base::Unretained(this)));
  }

  void SendCompleted(const std::string& message_id, GCMClient::Result result) {
    send_message_id_ = message_id;
    send_result_ = result;
    waiter_->SignalCompleted();
  }

  GCMProfileService* GetGCMProfileService() const {
    return GCMProfileServiceFactory::GetForProfile(profile());
  }

  GCMClientMock* GetGCMClient() const {
    return gcm_client_factory_->gcm_client();
  }

  const std::string& GetUsername() const {
    return GetGCMProfileService()->username_;
  }

  bool ExistsCachedRegistrationInfo() const {
    return !GetGCMProfileService()->registration_info_map_.empty();
  }

  Profile* profile() const { return profile_.get(); }
  FakeSigninManager* signin_manager() const { return signin_manager_; }
  FakeGCMEventRouter* gcm_event_router() const {
    return gcm_event_router_.get();
  }

  void set_gcm_client_initial_status(GCMClientMock::Status status) {
    gcm_client_initial_status_ = status;
  }

  GCMClient::CheckinInfo checkin_info() const { return checkin_info_; }
  const std::string& registration_id() const { return registration_id_; }
  GCMClient::Result registration_result() const { return registration_result_; }
  const std::string& send_message_id() const { return send_message_id_; }
  GCMClient::Result send_result() const { return send_result_; }

  void clear_checkin_info() { checkin_info_.Reset(); }
  void clear_registration_result() {
    registration_id_.clear();
    registration_result_ = GCMClient::UNKNOWN_ERROR;
  }
  void clear_send_result() {
    send_message_id_.clear();
    send_result_ = GCMClient::UNKNOWN_ERROR;;
  }

 private:
  // Overridden from GCMProfileService::TestingDelegate:
  virtual GCMEventRouter* GetEventRouter() const OVERRIDE {
    return gcm_event_router_.get();
  }

  virtual void CheckInFinished(const GCMClient::CheckinInfo& checkin_info,
                               GCMClient::Result result) OVERRIDE {
    checkin_info_ = checkin_info;
    waiter_->SignalCompleted();
  }

  Waiter* waiter_;  // Not owned.
  scoped_ptr<TestingProfile> profile_;
  ExtensionService* extension_service_;  // Not owned.
  FakeSigninManager* signin_manager_;  // Not owned.
  scoped_ptr<FakeGCMEventRouter> gcm_event_router_;
  scoped_ptr<FakeGCMClientFactory> gcm_client_factory_;

  GCMClientMock::Status gcm_client_initial_status_;

  GCMClient::CheckinInfo checkin_info_;

  std::string registration_id_;
  GCMClient::Result registration_result_;
  bool has_persisted_registration_info_;

  std::string send_message_id_;
  GCMClient::Result send_result_;

  DISALLOW_COPY_AND_ASSIGN(GCMProfileServiceTestConsumer);
};

class GCMProfileServiceTest : public testing::Test {
 public:
  GCMProfileServiceTest() {
  }

  virtual ~GCMProfileServiceTest() {
  }

  // Overridden from test::Test:
  virtual void SetUp() OVERRIDE {
    // Make BrowserThread work in unittest.
    thread_bundle_.reset(new content::TestBrowserThreadBundle(
        content::TestBrowserThreadBundle::REAL_IO_THREAD));

    // This is needed to create extension service under CrOS.
#if defined(OS_CHROMEOS)
    test_user_manager_.reset(new chromeos::ScopedTestUserManager());
#endif

    // Encryptor ends up needing access to the keychain on OS X. So use the mock
    // keychain to prevent prompts.
#if defined(OS_MACOSX)
    Encryptor::UseMockKeychain(true);
#endif

    // Create a main profile consumer.
    consumer_.reset(new GCMProfileServiceTestConsumer(&waiter_));
  }

  virtual void TearDown() OVERRIDE {
#if defined(OS_CHROMEOS)
    test_user_manager_.reset();
#endif

    consumer_.reset();
    base::RunLoop().RunUntilIdle();
  }

  void WaitUntilCompleted() {
    waiter_.WaitUntilCompleted();
  }

  void SignalCompleted() {
    waiter_.SignalCompleted();
  }

  void PumpIOLoop() {
    waiter_.PumpIOLoop();
  }

  Profile* profile() const { return consumer_->profile(); }
  GCMProfileServiceTestConsumer* consumer() const { return consumer_.get(); }

 protected:
  Waiter waiter_;

 private:
  scoped_ptr<content::TestBrowserThreadBundle> thread_bundle_;
#if defined(OS_CHROMEOS)
  chromeos::ScopedTestDeviceSettingsService test_device_settings_service_;
  chromeos::ScopedTestCrosSettings test_cros_settings_;
  scoped_ptr<chromeos::ScopedTestUserManager> test_user_manager_;
#endif

  scoped_ptr<GCMProfileServiceTestConsumer> consumer_;

  DISALLOW_COPY_AND_ASSIGN(GCMProfileServiceTest);
};

class ScopedGCMClientMockSimulateServerError {
 public:
  ScopedGCMClientMockSimulateServerError(
      GCMProfileServiceTestConsumer* consumer)
      : consumer_(consumer) {
    consumer_->GetGCMClient()->set_simulate_server_error(true);
  }

  ~ScopedGCMClientMockSimulateServerError() {
    consumer_->GetGCMClient()->set_simulate_server_error(false);
  }

 private:
  GCMProfileServiceTestConsumer* consumer_;

  DISALLOW_COPY_AND_ASSIGN(ScopedGCMClientMockSimulateServerError);
};

TEST_F(GCMProfileServiceTest, Incognito) {
  EXPECT_TRUE(GCMProfileServiceFactory::GetForProfile(profile()));

  // Create an incognito profile.
  TestingProfile::Builder incognito_profile_builder;
  incognito_profile_builder.SetIncognito();
  scoped_ptr<TestingProfile> incognito_profile =
      incognito_profile_builder.Build();
  incognito_profile->SetOriginalProfile(profile());

  EXPECT_FALSE(GCMProfileServiceFactory::GetForProfile(
      incognito_profile.get()));
}

TEST_F(GCMProfileServiceTest, CreateGCMProfileServiceBeforeProfileSignIn) {
  // This will cause GCMProfileService to be created. No check-in should be
  // initiated at this moment since the profile has not been signed in yet.
  consumer()->GetGCMProfileService();
  EXPECT_TRUE(consumer()->GetUsername().empty());
  EXPECT_FALSE(consumer()->checkin_info().IsValid());

  // Sign in to a profile. This will kick off the check-in.
  consumer()->signin_manager()->SignIn(kTestingUsername);

  // Wait till the asynchronous check-in is done.
  WaitUntilCompleted();

  // Verify the check-in result.
  EXPECT_TRUE(consumer()->checkin_info().IsValid());

  GCMClient::CheckinInfo expected_checkin_info =
      GCMClientMock::GetCheckinInfoFromUsername(kTestingUsername);
  EXPECT_EQ(expected_checkin_info.android_id,
            consumer()->checkin_info().android_id);
  EXPECT_EQ(expected_checkin_info.secret, consumer()->checkin_info().secret);
}

TEST_F(GCMProfileServiceTest, CreateGCMProfileServiceAfterProfileSignIn) {
  // Sign in to a profile. This will not initiate the check-in.
  consumer()->signin_manager()->SignIn(kTestingUsername);

  // This will cause GCMProfileService to be created and the check-in to be
  // invoked.
  consumer()->GetGCMProfileService();
  EXPECT_FALSE(consumer()->GetUsername().empty());
  EXPECT_FALSE(consumer()->checkin_info().IsValid());

  // Wait till the asynchronous check-in is done.
  WaitUntilCompleted();

  // Verify the check-in result.
  EXPECT_TRUE(consumer()->checkin_info().IsValid());

  GCMClient::CheckinInfo expected_checkin_info =
      GCMClientMock::GetCheckinInfoFromUsername(kTestingUsername);
  EXPECT_EQ(expected_checkin_info.android_id,
            consumer()->checkin_info().android_id);
  EXPECT_EQ(expected_checkin_info.secret, consumer()->checkin_info().secret);
}

TEST_F(GCMProfileServiceTest, RegsiterWhenNotSignedIn) {
  std::vector<std::string> sender_ids;
  sender_ids.push_back("sender1");
  consumer()->Register(kTestingAppId, sender_ids);

  EXPECT_TRUE(consumer()->registration_id().empty());
  EXPECT_EQ(GCMClient::NOT_SIGNED_IN, consumer()->registration_result());
}

TEST_F(GCMProfileServiceTest, SendWhenNotSignedIn) {
  GCMClient::OutgoingMessage message;
  message.id = "1";
  message.data["key1"] = "value1";
  consumer()->Send(kTestingAppId, kUserId, message);

  EXPECT_TRUE(consumer()->send_message_id().empty());
  EXPECT_EQ(GCMClient::NOT_SIGNED_IN, consumer()->send_result());
}

// Tests single-profile. CheckIn is initiated by default.
class GCMProfileServiceSingleProfileTest : public GCMProfileServiceTest {
 public:
  GCMProfileServiceSingleProfileTest() {
  }

  virtual ~GCMProfileServiceSingleProfileTest() {
  }

  virtual void SetUp() OVERRIDE {
    GCMProfileServiceTest::SetUp();

    consumer()->CheckIn(kTestingUsername);
  }
};

TEST_F(GCMProfileServiceSingleProfileTest, CheckInFromPrefsStore) {
  // The first check-in should be successful.
  EXPECT_TRUE(consumer()->checkin_info().IsValid());
  GCMClient::CheckinInfo saved_checkin_info = consumer()->checkin_info();
  consumer()->clear_checkin_info();

  // Check-in should not reach the server. Forcing GCMClient server error should
  // help catch this.
  ScopedGCMClientMockSimulateServerError gcm_client_simulate_server_error(
      consumer());

  // Recreate GCMProfileService to test reading the check-in info from the
  // prefs store.
  consumer()->CreateGCMProfileServiceInstance();

  EXPECT_EQ(saved_checkin_info.android_id,
            consumer()->checkin_info().android_id);
  EXPECT_EQ(saved_checkin_info.secret, consumer()->checkin_info().secret);
}

TEST_F(GCMProfileServiceSingleProfileTest, CheckOut) {
  EXPECT_TRUE(profile()->GetPrefs()->HasPrefPath(prefs::kGCMUserAccountID));
  EXPECT_TRUE(profile()->GetPrefs()->HasPrefPath(prefs::kGCMUserToken));

  // This will trigger check-out.
  consumer()->signin_manager()->SignOut();

  EXPECT_FALSE(profile()->GetPrefs()->HasPrefPath(prefs::kGCMUserAccountID));
  EXPECT_FALSE(profile()->GetPrefs()->HasPrefPath(prefs::kGCMUserToken));
}

TEST_F(GCMProfileServiceSingleProfileTest, CheckOutAndThenCheckIn) {
  // The first check-in should be successful.
  EXPECT_TRUE(consumer()->checkin_info().IsValid());

  // This will trigger check-out.
  consumer()->signin_manager()->SignOut();

  // Sign-in with a different username.
  consumer()->CheckIn(kTestingUsername2);

  GCMClient::CheckinInfo expected_checkin_info =
      GCMClientMock::GetCheckinInfoFromUsername(kTestingUsername2);
  EXPECT_EQ(expected_checkin_info.android_id,
            consumer()->checkin_info().android_id);
  EXPECT_EQ(expected_checkin_info.secret, consumer()->checkin_info().secret);
}

TEST_F(GCMProfileServiceSingleProfileTest, Register) {
  std::vector<std::string> sender_ids;
  sender_ids.push_back("sender1");
  consumer()->Register(kTestingAppId, sender_ids);
  std::string expected_registration_id =
      GCMClientMock::GetRegistrationIdFromSenderIds(sender_ids);

  WaitUntilCompleted();
  EXPECT_EQ(expected_registration_id, consumer()->registration_id());
  EXPECT_EQ(GCMClient::SUCCESS, consumer()->registration_result());
}

TEST_F(GCMProfileServiceSingleProfileTest, DoubleRegister) {
  std::vector<std::string> sender_ids;
  sender_ids.push_back("sender1");
  consumer()->Register(kTestingAppId, sender_ids);
  std::string expected_registration_id =
      GCMClientMock::GetRegistrationIdFromSenderIds(sender_ids);

  // Calling regsiter 2nd time without waiting 1st one to finish will fail
  // immediately.
  sender_ids.push_back("sender2");
  consumer()->Register(kTestingAppId, sender_ids);
  EXPECT_TRUE(consumer()->registration_id().empty());
  EXPECT_EQ(GCMClient::ASYNC_OPERATION_PENDING,
            consumer()->registration_result());

  // The 1st register is still doing fine.
  WaitUntilCompleted();
  EXPECT_EQ(expected_registration_id, consumer()->registration_id());
  EXPECT_EQ(GCMClient::SUCCESS, consumer()->registration_result());
}

TEST_F(GCMProfileServiceSingleProfileTest, RegisterError) {
  std::vector<std::string> sender_ids;
  sender_ids.push_back("sender1@error");
  consumer()->Register(kTestingAppId, sender_ids);

  WaitUntilCompleted();
  EXPECT_TRUE(consumer()->registration_id().empty());
  EXPECT_NE(GCMClient::SUCCESS, consumer()->registration_result());
}

TEST_F(GCMProfileServiceSingleProfileTest, RegisterAgainWithSameSenderIDs) {
  std::vector<std::string> sender_ids;
  sender_ids.push_back("sender1");
  sender_ids.push_back("sender2");
  consumer()->Register(kTestingAppId, sender_ids);
  std::string expected_registration_id =
      GCMClientMock::GetRegistrationIdFromSenderIds(sender_ids);

  WaitUntilCompleted();
  EXPECT_EQ(expected_registration_id, consumer()->registration_id());
  EXPECT_EQ(GCMClient::SUCCESS, consumer()->registration_result());

  // Clears the results the would be set by the Register callback in preparation
  // to call register 2nd time.
  consumer()->clear_registration_result();

  // Calling register 2nd time with the same set of sender IDs but different
  // ordering will get back the same registration ID. There is no need to wait
  // since register simply returns the cached registration ID.
  std::vector<std::string> another_sender_ids;
  another_sender_ids.push_back("sender2");
  another_sender_ids.push_back("sender1");
  consumer()->Register(kTestingAppId, another_sender_ids);
  EXPECT_EQ(expected_registration_id, consumer()->registration_id());
  EXPECT_EQ(GCMClient::SUCCESS, consumer()->registration_result());
}

TEST_F(GCMProfileServiceSingleProfileTest,
       RegisterAgainWithDifferentSenderIDs) {
  std::vector<std::string> sender_ids;
  sender_ids.push_back("sender1");
  consumer()->Register(kTestingAppId, sender_ids);
  std::string expected_registration_id =
      GCMClientMock::GetRegistrationIdFromSenderIds(sender_ids);

  WaitUntilCompleted();
  EXPECT_EQ(expected_registration_id, consumer()->registration_id());
  EXPECT_EQ(GCMClient::SUCCESS, consumer()->registration_result());

  // Make sender IDs different.
  sender_ids.push_back("sender2");
  std::string expected_registration_id2 =
      GCMClientMock::GetRegistrationIdFromSenderIds(sender_ids);

  // Calling register 2nd time with the different sender IDs will get back a new
  // registration ID.
  consumer()->Register(kTestingAppId, sender_ids);
  WaitUntilCompleted();
  EXPECT_EQ(expected_registration_id2, consumer()->registration_id());
  EXPECT_EQ(GCMClient::SUCCESS, consumer()->registration_result());
}

TEST_F(GCMProfileServiceSingleProfileTest, ReadRegistrationFromStateStore) {
  scoped_refptr<Extension> extension(consumer()->CreateExtension());

  std::vector<std::string> sender_ids;
  sender_ids.push_back("sender1");
  consumer()->Register(extension->id(), sender_ids);

  WaitUntilCompleted();
  EXPECT_FALSE(consumer()->registration_id().empty());
  EXPECT_EQ(GCMClient::SUCCESS, consumer()->registration_result());
  std::string old_registration_id = consumer()->registration_id();

  // Clears the results that would be set by the Register callback in
  // preparation to call register 2nd time.
  consumer()->clear_registration_result();

  // Simulate start-up by recreating GCMProfileService.
  consumer()->CreateGCMProfileServiceInstance();

  // Simulate start-up by reloading extension.
  consumer()->ReloadExtension(extension);

  // Register should not reach the server. Forcing GCMClient server error should
  // help catch this.
  ScopedGCMClientMockSimulateServerError gcm_client_simulate_server_error(
      consumer());

  // This should read the registration info from the extension's state store.
  // We still need to wait since the reading from state store might happen at
  // the same time.
  consumer()->Register(extension->id(), sender_ids);
  WaitUntilCompleted();
  EXPECT_EQ(old_registration_id, consumer()->registration_id());
  EXPECT_EQ(GCMClient::SUCCESS, consumer()->registration_result());
}

TEST_F(GCMProfileServiceSingleProfileTest,
       GCMClientReadyAfterReadingRegistration) {
  scoped_refptr<Extension> extension(consumer()->CreateExtension());

  std::vector<std::string> sender_ids;
  sender_ids.push_back("sender1");
  consumer()->Register(extension->id(), sender_ids);

  WaitUntilCompleted();
  EXPECT_FALSE(consumer()->registration_id().empty());
  EXPECT_EQ(GCMClient::SUCCESS, consumer()->registration_result());
  std::string old_registration_id = consumer()->registration_id();

  // Clears the results that would be set by the Register callback in
  // preparation to call register 2nd time.
  consumer()->clear_registration_result();

  // Needs to create a GCMClient instance that is not ready initiallly.
  consumer()->set_gcm_client_initial_status(GCMClientMock::NOT_READY);

  // Simulate start-up by recreating GCMProfileService.
  consumer()->CreateGCMProfileServiceInstance();

  // Simulate start-up by reloading extension.
  consumer()->ReloadExtension(extension);

  // Read the registration info from the extension's state store.
  // This would hold up because GCMClient is in loading state.
  consumer()->Register(extension->id(), sender_ids);
  base::RunLoop().RunUntilIdle();
  EXPECT_TRUE(consumer()->registration_id().empty());
  EXPECT_EQ(GCMClient::UNKNOWN_ERROR, consumer()->registration_result());

  // Register operation will be invoked after GCMClient becomes ready.
  consumer()->GetGCMClient()->SetReady();
  WaitUntilCompleted();
  EXPECT_EQ(old_registration_id, consumer()->registration_id());
  EXPECT_EQ(GCMClient::SUCCESS, consumer()->registration_result());
}

TEST_F(GCMProfileServiceSingleProfileTest, RegisterAfterSignOut) {
  // This will trigger check-out.
  consumer()->signin_manager()->SignOut();

  std::vector<std::string> sender_ids;
  sender_ids.push_back("sender1");
  consumer()->Register(kTestingAppId, sender_ids);

  EXPECT_TRUE(consumer()->registration_id().empty());
  EXPECT_EQ(GCMClient::NOT_SIGNED_IN, consumer()->registration_result());
}

TEST_F(GCMProfileServiceSingleProfileTest, Unregister) {
  scoped_refptr<Extension> extension(consumer()->CreateExtension());

  std::vector<std::string> sender_ids;
  sender_ids.push_back("sender1");
  consumer()->Register(extension->id(), sender_ids);

  WaitUntilCompleted();
  EXPECT_FALSE(consumer()->registration_id().empty());
  EXPECT_EQ(GCMClient::SUCCESS, consumer()->registration_result());

  // The registration info should be cached.
  EXPECT_TRUE(consumer()->ExistsCachedRegistrationInfo());

  // The registration info should be persisted.
  EXPECT_TRUE(consumer()->HasPersistedRegistrationInfo(extension->id()));

  // Uninstall the extension.
  consumer()->UninstallExtension(extension);
  base::MessageLoop::current()->RunUntilIdle();

  // The cached registration info should be removed.
  EXPECT_FALSE(consumer()->ExistsCachedRegistrationInfo());

  // The persisted registration info should be removed.
  EXPECT_FALSE(consumer()->HasPersistedRegistrationInfo(extension->id()));
}

TEST_F(GCMProfileServiceSingleProfileTest, Send) {
  GCMClient::OutgoingMessage message;
  message.id = "1";
  message.data["key1"] = "value1";
  message.data["key2"] = "value2";
  consumer()->Send(kTestingAppId, kUserId, message);

  // Wait for the send callback is called.
  WaitUntilCompleted();
  EXPECT_EQ(consumer()->send_message_id(), message.id);
  EXPECT_EQ(GCMClient::SUCCESS, consumer()->send_result());
}

TEST_F(GCMProfileServiceSingleProfileTest, SendAfterSignOut) {
  // This will trigger check-out.
  consumer()->signin_manager()->SignOut();

  GCMClient::OutgoingMessage message;
  message.id = "1";
  message.data["key1"] = "value1";
  message.data["key2"] = "value2";
  consumer()->Send(kTestingAppId, kUserId, message);

  EXPECT_TRUE(consumer()->send_message_id().empty());
  EXPECT_EQ(GCMClient::NOT_SIGNED_IN, consumer()->send_result());
}

TEST_F(GCMProfileServiceSingleProfileTest, SendError) {
  GCMClient::OutgoingMessage message;
  // Embedding error in id will tell the mock to simulate the send error.
  message.id = "1@error";
  message.data["key1"] = "value1";
  message.data["key2"] = "value2";
  consumer()->Send(kTestingAppId, kUserId, message);

  // Wait for the send callback is called.
  WaitUntilCompleted();
  EXPECT_EQ(consumer()->send_message_id(), message.id);
  EXPECT_EQ(GCMClient::SUCCESS, consumer()->send_result());

  // Wait for the send error.
  WaitUntilCompleted();
  EXPECT_EQ(FakeGCMEventRouter::SEND_ERROR_EVENT,
            consumer()->gcm_event_router()->received_event());
  EXPECT_EQ(kTestingAppId, consumer()->gcm_event_router()->app_id());
  EXPECT_EQ(consumer()->send_message_id(),
            consumer()->gcm_event_router()->send_message_id());
  EXPECT_NE(GCMClient::SUCCESS,
            consumer()->gcm_event_router()->send_result());
}

TEST_F(GCMProfileServiceSingleProfileTest, MessageReceived) {
  GCMClient::IncomingMessage message;
  message.data["key1"] = "value1";
  message.data["key2"] = "value2";
  consumer()->GetGCMClient()->ReceiveMessage(
      kTestingUsername, kTestingAppId, message);
  WaitUntilCompleted();
  EXPECT_EQ(FakeGCMEventRouter::MESSAGE_EVENT,
            consumer()->gcm_event_router()->received_event());
  EXPECT_EQ(kTestingAppId, consumer()->gcm_event_router()->app_id());
  EXPECT_TRUE(message.data == consumer()->gcm_event_router()->message().data);
}

TEST_F(GCMProfileServiceSingleProfileTest, MessageReceivedAfterSignOut) {
  // This will trigger check-out.
  consumer()->signin_manager()->SignOut();

  GCMClient::IncomingMessage message;
  message.data["key1"] = "value1";
  message.data["key2"] = "value2";
  consumer()->GetGCMClient()->ReceiveMessage(
      kTestingUsername, kTestingAppId, message);
  PumpIOLoop();

  EXPECT_EQ(FakeGCMEventRouter::NO_EVENT,
            consumer()->gcm_event_router()->received_event());
  EXPECT_TRUE(consumer()->gcm_event_router()->app_id().empty());
}

TEST_F(GCMProfileServiceSingleProfileTest, MessagesDeleted) {
  consumer()->GetGCMClient()->DeleteMessages(kTestingUsername, kTestingAppId);
  WaitUntilCompleted();
  EXPECT_EQ(FakeGCMEventRouter::MESSAGES_DELETED_EVENT,
            consumer()->gcm_event_router()->received_event());
  EXPECT_EQ(kTestingAppId, consumer()->gcm_event_router()->app_id());
}

TEST_F(GCMProfileServiceSingleProfileTest, MessagesDeletedAfterSignOut) {
  // This will trigger check-out.
  consumer()->signin_manager()->SignOut();

  consumer()->GetGCMClient()->DeleteMessages(kTestingUsername, kTestingAppId);
  PumpIOLoop();

  EXPECT_EQ(FakeGCMEventRouter::NO_EVENT,
            consumer()->gcm_event_router()->received_event());
  EXPECT_TRUE(consumer()->gcm_event_router()->app_id().empty());
}

class GCMProfileServiceMultiProfileTest : public GCMProfileServiceTest {
 public:
  GCMProfileServiceMultiProfileTest() {
  }

  virtual ~GCMProfileServiceMultiProfileTest() {
  }

  virtual void SetUp() OVERRIDE {
    GCMProfileServiceTest::SetUp();

    // Create a 2nd profile consumer.
    consumer2_.reset(new GCMProfileServiceTestConsumer(&waiter_));

    // This will cause GetGCMProfileService to be created for each profile.
    consumer()->GetGCMProfileService();
    consumer2()->GetGCMProfileService();

    // Initiate check-in for each profile.
    consumer2()->signin_manager()->SignIn(kTestingUsername2);
    consumer()->signin_manager()->SignIn(kTestingUsername);

    // Wait till all the asynchronous check-ins are done.
    WaitUntilCompleted();
    WaitUntilCompleted();
  }

  virtual void TearDown() OVERRIDE {
    consumer2_.reset();

    GCMProfileServiceTest::TearDown();
  }

  Profile* profile2() const { return consumer2_->profile(); }
  GCMProfileServiceTestConsumer* consumer2() const { return consumer2_.get(); }

 protected:
  scoped_ptr<GCMProfileServiceTestConsumer> consumer2_;
};

TEST_F(GCMProfileServiceMultiProfileTest, CheckIn) {
  GCMClient::CheckinInfo expected_checkin_info =
      GCMClientMock::GetCheckinInfoFromUsername(kTestingUsername);
  EXPECT_EQ(expected_checkin_info.android_id,
            consumer()->checkin_info().android_id);
  EXPECT_EQ(expected_checkin_info.secret, consumer()->checkin_info().secret);

  expected_checkin_info =
      GCMClientMock::GetCheckinInfoFromUsername(kTestingUsername2);
  EXPECT_EQ(expected_checkin_info.android_id,
            consumer2()->checkin_info().android_id);
  EXPECT_EQ(expected_checkin_info.secret, consumer2()->checkin_info().secret);
}

TEST_F(GCMProfileServiceMultiProfileTest, Register) {
  // Register an app.
  std::vector<std::string> sender_ids;
  sender_ids.push_back("sender1");
  consumer()->Register(kTestingAppId, sender_ids);

  // Register the same app in a different profile.
  std::vector<std::string> sender_ids2;
  sender_ids2.push_back("foo");
  sender_ids2.push_back("bar");
  consumer2()->Register(kTestingAppId, sender_ids2);

  WaitUntilCompleted();
  WaitUntilCompleted();

  EXPECT_EQ(GCMClientMock::GetRegistrationIdFromSenderIds(sender_ids),
            consumer()->registration_id());
  EXPECT_EQ(GCMClient::SUCCESS, consumer()->registration_result());

  EXPECT_EQ(GCMClientMock::GetRegistrationIdFromSenderIds(sender_ids2),
            consumer2()->registration_id());
  EXPECT_EQ(GCMClient::SUCCESS, consumer()->registration_result());

  // Register a different app in a different profile.
  std::vector<std::string> sender_ids3;
  sender_ids3.push_back("sender1");
  sender_ids3.push_back("sender2");
  sender_ids3.push_back("sender3");
  consumer2()->Register(kTestingAppId2, sender_ids3);

  WaitUntilCompleted();

  EXPECT_EQ(GCMClientMock::GetRegistrationIdFromSenderIds(sender_ids3),
            consumer2()->registration_id());
  EXPECT_EQ(GCMClient::SUCCESS, consumer2()->registration_result());
}

TEST_F(GCMProfileServiceMultiProfileTest, Send) {
  // Send a message from one app in one profile.
  GCMClient::OutgoingMessage message;
  message.id = "1";
  message.data["key1"] = "value1";
  message.data["key2"] = "value2";
  consumer()->Send(kTestingAppId, kUserId, message);

  // Send a message from same app in another profile.
  GCMClient::OutgoingMessage message2;
  message2.id = "2";
  message2.data["foo"] = "bar";
  consumer2()->Send(kTestingAppId, kUserId2, message2);

  WaitUntilCompleted();
  WaitUntilCompleted();

  EXPECT_EQ(consumer()->send_message_id(), message.id);
  EXPECT_EQ(GCMClient::SUCCESS, consumer()->send_result());

  EXPECT_EQ(consumer2()->send_message_id(), message2.id);
  EXPECT_EQ(GCMClient::SUCCESS, consumer2()->send_result());

  // Send another message from different app in another profile.
  GCMClient::OutgoingMessage message3;
  message3.id = "3";
  message3.data["hello"] = "world";
  consumer2()->Send(kTestingAppId2, kUserId, message3);

  WaitUntilCompleted();

  EXPECT_EQ(consumer2()->send_message_id(), message3.id);
  EXPECT_EQ(GCMClient::SUCCESS, consumer()->send_result());
}

TEST_F(GCMProfileServiceMultiProfileTest, MessageReceived) {
  // Trigger an incoming message for an app in one profile.
  GCMClient::IncomingMessage message;
  message.data["key1"] = "value1";
  message.data["key2"] = "value2";
  consumer()->GetGCMClient()->ReceiveMessage(
      kTestingUsername, kTestingAppId, message);

  // Trigger an incoming message for the same app in another profile.
  GCMClient::IncomingMessage message2;
  message2.data["foo"] = "bar";
  consumer2()->GetGCMClient()->ReceiveMessage(
      kTestingUsername2, kTestingAppId, message2);

  WaitUntilCompleted();
  WaitUntilCompleted();

  EXPECT_EQ(FakeGCMEventRouter::MESSAGE_EVENT,
            consumer()->gcm_event_router()->received_event());
  EXPECT_EQ(kTestingAppId, consumer()->gcm_event_router()->app_id());
  EXPECT_TRUE(message.data == consumer()->gcm_event_router()->message().data);

  EXPECT_EQ(FakeGCMEventRouter::MESSAGE_EVENT,
            consumer2()->gcm_event_router()->received_event());
  EXPECT_EQ(kTestingAppId, consumer2()->gcm_event_router()->app_id());
  EXPECT_TRUE(message2.data == consumer2()->gcm_event_router()->message().data);

  // Trigger another incoming message for a different app in another profile.
  GCMClient::IncomingMessage message3;
  message3.data["bar1"] = "foo1";
  message3.data["bar2"] = "foo2";
  consumer2()->GetGCMClient()->ReceiveMessage(
      kTestingUsername2, kTestingAppId2, message3);

  WaitUntilCompleted();

  EXPECT_EQ(FakeGCMEventRouter::MESSAGE_EVENT,
            consumer2()->gcm_event_router()->received_event());
  EXPECT_EQ(kTestingAppId2, consumer2()->gcm_event_router()->app_id());
  EXPECT_TRUE(message3.data == consumer2()->gcm_event_router()->message().data);
}

// Test a set of GCM operations on multiple profiles.
// 1) Register 1 app in profile1 and register 2 apps in profile2;
// 2) Send a message from profile1;
// 3) Receive a message to an app in profile1 and receive a message for each of
//    two apps in profile2;
// 4) Send a message foe ach of two apps in profile2;
// 5) Sign out of profile1.
// 6) The app in profile1 should not receive message and deleted_messages
//    events;
// 7) The app in profile2 could still receive these events;
// 8) Sign into profile1 with a different user.
// 9) The message to the signed-out user will be ingored.
// 10) The message to the new signed-in user will be routed.
TEST_F(GCMProfileServiceMultiProfileTest, Combined) {
  // Register an app.
  std::vector<std::string> sender_ids;
  sender_ids.push_back("sender1");
  consumer()->Register(kTestingAppId, sender_ids);

  // Register the same app in a different profile.
  std::vector<std::string> sender_ids2;
  sender_ids2.push_back("foo");
  sender_ids2.push_back("bar");
  consumer2()->Register(kTestingAppId, sender_ids2);

  // Register a different app in a different profile.
  std::vector<std::string> sender_ids3;
  sender_ids3.push_back("sender1");
  sender_ids3.push_back("sender2");
  sender_ids3.push_back("sender3");
  consumer2()->Register(kTestingAppId2, sender_ids3);

  WaitUntilCompleted();
  WaitUntilCompleted();
  WaitUntilCompleted();

  EXPECT_EQ(GCMClientMock::GetRegistrationIdFromSenderIds(sender_ids),
            consumer()->registration_id());
  EXPECT_EQ(GCMClient::SUCCESS, consumer()->registration_result());

  EXPECT_EQ(GCMClientMock::GetRegistrationIdFromSenderIds(sender_ids3),
            consumer2()->registration_id());
  EXPECT_EQ(GCMClient::SUCCESS, consumer()->registration_result());

  // Send a message from one profile.
  GCMClient::OutgoingMessage out_message;
  out_message.id = "1";
  out_message.data["out1"] = "out_data1";
  out_message.data["out1_2"] = "out_data1_2";
  consumer()->Send(kTestingAppId, kUserId, out_message);

  WaitUntilCompleted();

  EXPECT_EQ(consumer()->send_message_id(), out_message.id);
  EXPECT_EQ(GCMClient::SUCCESS, consumer()->send_result());

  // Trigger an incoming message for an app in one profile.
  GCMClient::IncomingMessage in_message;
  in_message.data["in1"] = "in_data1";
  in_message.data["in1_2"] = "in_data1_2";
  consumer()->GetGCMClient()->ReceiveMessage(
      kTestingUsername, kTestingAppId, in_message);

  WaitUntilCompleted();

  EXPECT_EQ(FakeGCMEventRouter::MESSAGE_EVENT,
            consumer()->gcm_event_router()->received_event());
  EXPECT_EQ(kTestingAppId, consumer()->gcm_event_router()->app_id());
  EXPECT_TRUE(
      in_message.data == consumer()->gcm_event_router()->message().data);

  // Trigger 2 incoming messages, one for each app respectively, in another
  // profile.
  GCMClient::IncomingMessage in_message2;
  in_message2.data["in2"] = "in_data2";
  consumer2()->GetGCMClient()->ReceiveMessage(
      kTestingUsername2, kTestingAppId2, in_message2);

  GCMClient::IncomingMessage in_message3;
  in_message3.data["in3"] = "in_data3";
  in_message3.data["in3_2"] = "in_data3_2";
  consumer2()->GetGCMClient()->ReceiveMessage(
      kTestingUsername2, kTestingAppId, in_message3);

  consumer2()->gcm_event_router()->clear_results();
  WaitUntilCompleted();

  EXPECT_EQ(FakeGCMEventRouter::MESSAGE_EVENT,
            consumer2()->gcm_event_router()->received_event());
  EXPECT_EQ(kTestingAppId2, consumer2()->gcm_event_router()->app_id());
  EXPECT_TRUE(
      in_message2.data == consumer2()->gcm_event_router()->message().data);

  consumer2()->gcm_event_router()->clear_results();
  WaitUntilCompleted();

  EXPECT_EQ(FakeGCMEventRouter::MESSAGE_EVENT,
            consumer2()->gcm_event_router()->received_event());
  EXPECT_EQ(kTestingAppId, consumer2()->gcm_event_router()->app_id());
  EXPECT_TRUE(
      in_message3.data == consumer2()->gcm_event_router()->message().data);

  // Send two messages, one for each app respectively, from another profile.
  GCMClient::OutgoingMessage out_message2;
  out_message2.id = "2";
  out_message2.data["out2"] = "out_data2";
  consumer2()->Send(kTestingAppId, kUserId2, out_message2);

  GCMClient::OutgoingMessage out_message3;
  out_message3.id = "2";
  out_message3.data["out3"] = "out_data3";
  consumer2()->Send(kTestingAppId2, kUserId2, out_message3);

  WaitUntilCompleted();

  EXPECT_EQ(consumer2()->send_message_id(), out_message2.id);
  EXPECT_EQ(GCMClient::SUCCESS, consumer2()->send_result());

  WaitUntilCompleted();

  EXPECT_EQ(consumer2()->send_message_id(), out_message3.id);
  EXPECT_EQ(GCMClient::SUCCESS, consumer2()->send_result());

  // Sign out of one profile.
  consumer()->signin_manager()->SignOut();
  PumpIOLoop();

  // Incoming message will be ingored for the signed-out profile.
  GCMClient::IncomingMessage in_message4;
  in_message4.data["in4"] = "in_data4";
  consumer()->GetGCMClient()->ReceiveMessage(
      kTestingUsername, kTestingAppId, in_message4);

  consumer()->gcm_event_router()->clear_results();
  PumpIOLoop();

  EXPECT_EQ(FakeGCMEventRouter::NO_EVENT,
            consumer()->gcm_event_router()->received_event());
  EXPECT_TRUE(consumer()->gcm_event_router()->app_id().empty());

  // Deleted messages event will be ingored for the signed-out profile.
  consumer()->GetGCMClient()->DeleteMessages(kTestingUsername, kTestingAppId);

  PumpIOLoop();

  EXPECT_EQ(FakeGCMEventRouter::NO_EVENT,
            consumer()->gcm_event_router()->received_event());
  EXPECT_TRUE(consumer()->gcm_event_router()->app_id().empty());

  // Deleted messages event will go through for another signed-in profile.
  consumer2()->GetGCMClient()->DeleteMessages(
      kTestingUsername2, kTestingAppId2);

  consumer2()->gcm_event_router()->clear_results();
  WaitUntilCompleted();

  EXPECT_EQ(FakeGCMEventRouter::MESSAGES_DELETED_EVENT,
            consumer2()->gcm_event_router()->received_event());
  EXPECT_EQ(kTestingAppId2, consumer2()->gcm_event_router()->app_id());

  // Send error event will go through for another signed-in profile.
  GCMClient::OutgoingMessage out_message4;
  out_message4.id = "1@error";
  out_message4.data["out4"] = "out_data4";
  consumer2()->Send(kTestingAppId, kUserId, out_message4);

  WaitUntilCompleted();
  EXPECT_EQ(consumer2()->send_message_id(), out_message4.id);
  EXPECT_EQ(GCMClient::SUCCESS, consumer2()->send_result());

  consumer2()->gcm_event_router()->clear_results();
  WaitUntilCompleted();
  EXPECT_EQ(FakeGCMEventRouter::SEND_ERROR_EVENT,
            consumer2()->gcm_event_router()->received_event());
  EXPECT_EQ(kTestingAppId, consumer2()->gcm_event_router()->app_id());
  EXPECT_EQ(consumer2()->send_message_id(),
            consumer2()->gcm_event_router()->send_message_id());
  EXPECT_NE(GCMClient::SUCCESS,
            consumer2()->gcm_event_router()->send_result());

  // Sign in with a different user.
  consumer()->signin_manager()->SignIn(kTestingUsername3);
  WaitUntilCompleted();

  // Incoming message will still be ingored for the signed-out user.
  consumer()->GetGCMClient()->ReceiveMessage(
      kTestingUsername, kTestingAppId, in_message4);

  consumer()->gcm_event_router()->clear_results();
  PumpIOLoop();

  EXPECT_EQ(FakeGCMEventRouter::NO_EVENT,
            consumer()->gcm_event_router()->received_event());
  EXPECT_TRUE(consumer()->gcm_event_router()->app_id().empty());

  // Incoming message will go through for the new signed-in user.
  GCMClient::IncomingMessage in_message5;
  in_message5.data["in5"] = "in_data5";
  consumer()->GetGCMClient()->ReceiveMessage(
      kTestingUsername3, kTestingAppId, in_message5);

  consumer()->gcm_event_router()->clear_results();
  WaitUntilCompleted();

  EXPECT_EQ(FakeGCMEventRouter::MESSAGE_EVENT,
            consumer()->gcm_event_router()->received_event());
  EXPECT_TRUE(
      in_message5.data == consumer()->gcm_event_router()->message().data);
}

}  // namespace gcm