File: mcs_client_unittest.cc

package info (click to toggle)
chromium 139.0.7258.127-1
  • links: PTS, VCS
  • area: main
  • in suites:
  • size: 6,122,068 kB
  • sloc: cpp: 35,100,771; ansic: 7,163,530; javascript: 4,103,002; python: 1,436,920; asm: 946,517; xml: 746,709; pascal: 187,653; perl: 88,691; sh: 88,436; objc: 79,953; sql: 51,488; cs: 44,583; fortran: 24,137; makefile: 22,147; tcl: 15,277; php: 13,980; yacc: 8,984; ruby: 7,485; awk: 3,720; lisp: 3,096; lex: 1,327; ada: 727; jsp: 228; sed: 36
file content (1204 lines) | stat: -rw-r--r-- 45,490 bytes parent folder | download | duplicates (11)
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
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#include "google_apis/gcm/engine/mcs_client.h"

#include <stddef.h>
#include <stdint.h>

#include <memory>
#include <utility>

#include "base/command_line.h"
#include "base/files/scoped_temp_dir.h"
#include "base/functional/bind.h"
#include "base/functional/callback_helpers.h"
#include "base/memory/ptr_util.h"
#include "base/run_loop.h"
#include "base/strings/string_number_conversions.h"
#include "base/task/sequenced_task_runner.h"
#include "base/task/single_thread_task_runner.h"
#include "base/test/simple_test_clock.h"
#include "base/test/task_environment.h"
#include "base/timer/timer.h"
#include "google_apis/gcm/base/fake_encryptor.h"
#include "google_apis/gcm/base/mcs_util.h"
#include "google_apis/gcm/engine/fake_connection_factory.h"
#include "google_apis/gcm/engine/fake_connection_handler.h"
#include "google_apis/gcm/engine/gcm_store_impl.h"
#include "google_apis/gcm/monitoring/fake_gcm_stats_recorder.h"
#include "testing/gtest/include/gtest/gtest.h"

namespace gcm {

namespace {

const uint64_t kAndroidId = 54321;
const uint64_t kSecurityToken = 12345;

// Number of messages to send when testing batching.
// Note: must be even for tests that split batches in half.
const int kMessageBatchSize = 6;

// The number of unacked messages the client will receive before sending a
// stream ack.
// TODO(zea): get this (and other constants) directly from the mcs client.
const int kAckLimitSize = 10;

// TTL value for reliable messages.
const int kTTLValue = 5 * 60;  // 5 minutes.

// Specifies whether immediate ACK should be requested.
enum RequestImmediateAck {
  IMMEDIATE_ACK_IGNORE,  // Ignores the field and does not set it.
  IMMEDIATE_ACK_NO,      // Sets the field to false.
  IMMEDIATE_ACK_YES      // Sets the field to true.
};

// Helper for building arbitrary data messages.
MCSMessage BuildDataMessage(const std::string& from,
                            const std::string& category,
                            const std::string& message_id,
                            int last_stream_id_received,
                            const std::string& persistent_id,
                            int ttl,
                            uint64_t sent,
                            int queued,
                            const std::string& token,
                            const uint64_t& user_id,
                            RequestImmediateAck immediate_ack) {
  mcs_proto::DataMessageStanza data_message;
  data_message.set_id(message_id);
  data_message.set_from(from);
  data_message.set_category(category);
  data_message.set_last_stream_id_received(last_stream_id_received);
  if (!persistent_id.empty())
    data_message.set_persistent_id(persistent_id);
  data_message.set_ttl(ttl);
  data_message.set_sent(sent);
  data_message.set_queued(queued);
  data_message.set_token(token);
  data_message.set_device_user_id(user_id);
  if (immediate_ack != IMMEDIATE_ACK_IGNORE) {
    data_message.set_immediate_ack(immediate_ack == IMMEDIATE_ACK_YES);
  }
  return MCSMessage(kDataMessageStanzaTag, data_message);
}

// MCSClient with overriden exposed persistent id logic.
class TestMCSClient : public MCSClient {
 public:
  TestMCSClient(base::Clock* clock,
                ConnectionFactory* connection_factory,
                GCMStore* gcm_store,
                scoped_refptr<base::SequencedTaskRunner> io_task_runner,
                gcm::GCMStatsRecorder* recorder)
      : MCSClient("",
                  clock,
                  connection_factory,
                  gcm_store,
                  io_task_runner,
                  recorder),
        next_id_(0) {}

  std::string GetNextPersistentId() override {
    return base::NumberToString(++next_id_);
  }

 private:
  uint32_t next_id_;
};

class TestConnectionListener : public ConnectionFactory::ConnectionListener {
 public:
  TestConnectionListener() : disconnect_counter_(0) { }
  ~TestConnectionListener() override { }

  void OnConnected(const GURL& current_server,
                   const net::IPEndPoint& ip_endpoint) override { }
  void OnDisconnected() override {
    ++disconnect_counter_;
  }

  int get_disconnect_counter() const { return disconnect_counter_; }
 private:
  int disconnect_counter_;
};

class MCSClientTest : public testing::Test {
 public:
  MCSClientTest();
  ~MCSClientTest() override;

  void SetUp() override;
  void TearDown() override;

  void BuildMCSClient();
  void InitializeClient();
  void StoreCredentials();
  void LoginClient(const std::vector<std::string>& acknowledged_ids);
  void LoginClientWithHeartbeat(
      const std::vector<std::string>& acknowledged_ids,
      int heartbeat_interval_ms);
  void AddExpectedLoginRequest(const std::vector<std::string>& acknowledged_ids,
                               int heartbeat_interval_ms);

  base::SimpleTestClock* clock() { return &clock_; }
  TestMCSClient* mcs_client() const { return mcs_client_.get(); }
  FakeConnectionFactory* connection_factory() {
    return &connection_factory_;
  }
  bool init_success() const { return init_success_; }
  uint64_t restored_android_id() const { return restored_android_id_; }
  uint64_t restored_security_token() const { return restored_security_token_; }
  MCSMessage* received_message() const { return received_message_.get(); }
  std::string sent_message_id() const { return sent_message_id_;}
  MCSClient::MessageSendStatus message_send_status() const {
    return message_send_status_;
  }

  void SetDeviceCredentialsCallback(bool success);

  FakeConnectionHandler* GetFakeHandler() const;

  void WaitForMCSEvent();
  void PumpLoop();

 private:
  void ErrorCallback();
  void MessageReceivedCallback(const MCSMessage& message);
  void MessageSentCallback(int64_t user_serial_number,
                           const std::string& app_id,
                           const std::string& message_id,
                           MCSClient::MessageSendStatus status);

  base::SimpleTestClock clock_;

  base::ScopedTempDir temp_directory_;
  base::test::TaskEnvironment task_environment_;
  std::unique_ptr<base::RunLoop> run_loop_;
  std::unique_ptr<GCMStore> gcm_store_;

  FakeConnectionFactory connection_factory_;
  std::unique_ptr<TestMCSClient> mcs_client_;
  bool init_success_;
  uint64_t restored_android_id_;
  uint64_t restored_security_token_;
  std::unique_ptr<MCSMessage> received_message_;
  std::string sent_message_id_;
  MCSClient::MessageSendStatus message_send_status_;

  gcm::FakeGCMStatsRecorder recorder_;
};

MCSClientTest::MCSClientTest()
    : run_loop_(new base::RunLoop()),
      init_success_(true),
      restored_android_id_(0),
      restored_security_token_(0),
      message_send_status_(MCSClient::SENT) {
  EXPECT_TRUE(temp_directory_.CreateUniqueTempDir());
  run_loop_ = std::make_unique<base::RunLoop>();

  // Advance the clock to a non-zero time.
  clock_.Advance(base::Seconds(1));
}

MCSClientTest::~MCSClientTest() {}

void MCSClientTest::SetUp() {
  testing::Test::SetUp();
}

void MCSClientTest::TearDown() {
  gcm_store_.reset();
  task_environment_.RunUntilIdle();
  testing::Test::TearDown();
}

void MCSClientTest::BuildMCSClient() {
  gcm_store_ = std::make_unique<GCMStoreImpl>(
      temp_directory_.GetPath(), task_environment_.GetMainThreadTaskRunner(),
      base::WrapUnique<Encryptor>(new FakeEncryptor));
  mcs_client_ = std::make_unique<TestMCSClient>(
      &clock_, &connection_factory_, gcm_store_.get(),
      base::SingleThreadTaskRunner::GetCurrentDefault(), &recorder_);
}

void MCSClientTest::InitializeClient() {
  gcm_store_->Load(
      GCMStore::CREATE_IF_MISSING,
      base::BindOnce(
          &MCSClient::Initialize, base::Unretained(mcs_client_.get()),
          base::BindRepeating(&MCSClientTest::ErrorCallback,
                              base::Unretained(this)),
          base::BindRepeating(&MCSClientTest::MessageReceivedCallback,
                              base::Unretained(this)),
          base::BindRepeating(&MCSClientTest::MessageSentCallback,
                              base::Unretained(this))));
  run_loop_->RunUntilIdle();
  run_loop_ = std::make_unique<base::RunLoop>();
}

void MCSClientTest::LoginClient(
    const std::vector<std::string>& acknowledged_ids) {
  LoginClientWithHeartbeat(acknowledged_ids, 0);
}

void MCSClientTest::LoginClientWithHeartbeat(
    const std::vector<std::string>& acknowledged_ids,
    int heartbeat_interval_ms) {
  AddExpectedLoginRequest(acknowledged_ids, heartbeat_interval_ms);
  mcs_client_->Login(kAndroidId, kSecurityToken);
  run_loop_->Run();
  run_loop_ = std::make_unique<base::RunLoop>();
}

void MCSClientTest::AddExpectedLoginRequest(
    const std::vector<std::string>& acknowledged_ids,
    int heartbeat_interval_ms) {
  std::unique_ptr<mcs_proto::LoginRequest> login_request =
      BuildLoginRequest(kAndroidId, kSecurityToken, "");
  for (size_t i = 0; i < acknowledged_ids.size(); ++i)
    login_request->add_received_persistent_id(acknowledged_ids[i]);
  if (heartbeat_interval_ms) {
    mcs_proto::Setting* setting = login_request->add_setting();
    setting->set_name("hbping");
    setting->set_value(base::NumberToString(heartbeat_interval_ms));
  }
  GetFakeHandler()->ExpectOutgoingMessage(
      MCSMessage(kLoginRequestTag, std::move(login_request)));
}

void MCSClientTest::StoreCredentials() {
  gcm_store_->SetDeviceCredentials(
      kAndroidId, kSecurityToken,
      base::BindOnce(&MCSClientTest::SetDeviceCredentialsCallback,
                     base::Unretained(this)));
  run_loop_->Run();
  run_loop_ = std::make_unique<base::RunLoop>();
}

FakeConnectionHandler* MCSClientTest::GetFakeHandler() const {
  return reinterpret_cast<FakeConnectionHandler*>(
      connection_factory_.GetConnectionHandler());
}

void MCSClientTest::WaitForMCSEvent() {
  run_loop_->Run();
  run_loop_ = std::make_unique<base::RunLoop>();
}

void MCSClientTest::PumpLoop() {
  run_loop_->RunUntilIdle();
  run_loop_ = std::make_unique<base::RunLoop>();
}

void MCSClientTest::ErrorCallback() {
  init_success_ = false;
  DVLOG(1) << "Error callback invoked, killing loop.";
  run_loop_->Quit();
}

void MCSClientTest::MessageReceivedCallback(const MCSMessage& message) {
  received_message_ = std::make_unique<MCSMessage>(message);
  DVLOG(1) << "Message received callback invoked, killing loop.";
  run_loop_->Quit();
}

void MCSClientTest::MessageSentCallback(int64_t user_serial_number,
                                        const std::string& app_id,
                                        const std::string& message_id,
                                        MCSClient::MessageSendStatus status) {
  DVLOG(1) << "Message sent callback invoked, killing loop.";
  sent_message_id_ = message_id;
  message_send_status_ = status;
  run_loop_->Quit();
}

void MCSClientTest::SetDeviceCredentialsCallback(bool success) {
  ASSERT_TRUE(success);
  run_loop_->Quit();
}

// Initialize a new client.
TEST_F(MCSClientTest, InitializeNew) {
  BuildMCSClient();
  InitializeClient();
  EXPECT_TRUE(init_success());
}

// Initialize a new client, shut it down, then restart the client. Should
// reload the existing device credentials.
TEST_F(MCSClientTest, InitializeExisting) {
  BuildMCSClient();
  InitializeClient();
  LoginClient(std::vector<std::string>());

  // Rebuild the client, to reload from the GCM store.
  StoreCredentials();
  BuildMCSClient();
  InitializeClient();
  EXPECT_TRUE(init_success());
}

// Log in successfully to the MCS endpoint.
TEST_F(MCSClientTest, LoginSuccess) {
  BuildMCSClient();
  InitializeClient();
  LoginClient(std::vector<std::string>());
  EXPECT_TRUE(connection_factory()->IsEndpointReachable());
  EXPECT_TRUE(init_success());
  ASSERT_TRUE(received_message());
  EXPECT_EQ(kLoginResponseTag, received_message()->tag());
}

// Encounter a server error during the login attempt. Should trigger a
// reconnect.
TEST_F(MCSClientTest, FailLogin) {
  BuildMCSClient();
  InitializeClient();
  GetFakeHandler()->set_fail_login(true);
  connection_factory()->set_delay_reconnect(true);
  LoginClient(std::vector<std::string>());
  EXPECT_FALSE(connection_factory()->IsEndpointReachable());
  EXPECT_FALSE(init_success());
  EXPECT_FALSE(received_message());
  EXPECT_TRUE(connection_factory()->reconnect_pending());
}

// Send a message without RMQ support.
TEST_F(MCSClientTest, SendMessageNoRMQ) {
  BuildMCSClient();
  InitializeClient();
  LoginClient(std::vector<std::string>());
  MCSMessage message(BuildDataMessage("from", "category", "X", 1, "", 0, 1, 0,
                                      "", 0, IMMEDIATE_ACK_NO));
  GetFakeHandler()->ExpectOutgoingMessage(message);
  mcs_client()->SendMessage(message);
  EXPECT_TRUE(GetFakeHandler()->AllOutgoingMessagesReceived());
}

// Send a message without RMQ support while disconnected. Message send should
// fail immediately, invoking callback.
TEST_F(MCSClientTest, SendMessageNoRMQWhileDisconnected) {
  BuildMCSClient();
  InitializeClient();

  EXPECT_TRUE(sent_message_id().empty());
  MCSMessage message(BuildDataMessage("from", "category", "X", 1, "", 0, 1, 0,
                                      "", 0, IMMEDIATE_ACK_NO));
  mcs_client()->SendMessage(message);

  // Message sent callback should be invoked, but no message should actually
  // be sent.
  EXPECT_EQ("X", sent_message_id());
  EXPECT_EQ(MCSClient::NO_CONNECTION_ON_ZERO_TTL, message_send_status());
  EXPECT_TRUE(GetFakeHandler()->AllOutgoingMessagesReceived());
}

// Send a message with RMQ support.
TEST_F(MCSClientTest, SendMessageRMQ) {
  BuildMCSClient();
  InitializeClient();
  LoginClient(std::vector<std::string>());
  MCSMessage message(BuildDataMessage("from", "category", "X", 1, "1",
                                      kTTLValue, 1, 0, "", 0,
                                      IMMEDIATE_ACK_NO));
  GetFakeHandler()->ExpectOutgoingMessage(message);
  mcs_client()->SendMessage(message);
  EXPECT_TRUE(GetFakeHandler()->AllOutgoingMessagesReceived());
}

// Send a message with RMQ support while disconnected. On reconnect, the message
// should be resent.
TEST_F(MCSClientTest, SendMessageRMQWhileDisconnected) {
  BuildMCSClient();
  InitializeClient();
  LoginClient(std::vector<std::string>());
  GetFakeHandler()->set_fail_send(true);
  MCSMessage message(BuildDataMessage("from", "category", "X", 1, "1",
                                      kTTLValue, 1, 0, "", 0,
                                      IMMEDIATE_ACK_NO));

  // The initial (failed) send.
  GetFakeHandler()->ExpectOutgoingMessage(message);
  // The login request.
  GetFakeHandler()->ExpectOutgoingMessage(MCSMessage(
      kLoginRequestTag, BuildLoginRequest(kAndroidId, kSecurityToken, "")));
  // The second (re)send.
  MCSMessage message2(BuildDataMessage("from", "category", "X", 1, "1",
                                       kTTLValue, 1, kTTLValue - 1, "", 0,
                                       IMMEDIATE_ACK_NO));
  GetFakeHandler()->ExpectOutgoingMessage(message2);
  mcs_client()->SendMessage(message);
  PumpLoop();         // Wait for the queuing to happen.
  EXPECT_EQ(MCSClient::QUEUED, message_send_status());
  EXPECT_EQ("X", sent_message_id());
  EXPECT_FALSE(GetFakeHandler()->AllOutgoingMessagesReceived());
  GetFakeHandler()->set_fail_send(false);
  clock()->Advance(base::Seconds(kTTLValue - 1));
  connection_factory()->Connect();
  WaitForMCSEvent();  // Wait for the login to finish.
  PumpLoop();         // Wait for the send to happen.

  // Receive the ack.
  std::unique_ptr<mcs_proto::IqStanza> ack = BuildStreamAck();
  ack->set_last_stream_id_received(2);
  GetFakeHandler()->ReceiveMessage(MCSMessage(kIqStanzaTag, std::move(ack)));
  WaitForMCSEvent();

  EXPECT_EQ(MCSClient::SENT, message_send_status());
  EXPECT_EQ("X", sent_message_id());
  EXPECT_TRUE(GetFakeHandler()->AllOutgoingMessagesReceived());
}

// Send a message with RMQ support without receiving an acknowledgement. On
// restart the message should be resent.
TEST_F(MCSClientTest, SendMessageRMQOnRestart) {
  BuildMCSClient();
  InitializeClient();
  LoginClient(std::vector<std::string>());
  GetFakeHandler()->set_fail_send(true);
  MCSMessage message(BuildDataMessage("from", "category", "X", 1, "1",
                                      kTTLValue, 1, 0, "", 0,
                                      IMMEDIATE_ACK_NO));

  // The initial (failed) send.
  GetFakeHandler()->ExpectOutgoingMessage(message);
  GetFakeHandler()->set_fail_send(false);
  mcs_client()->SendMessage(message);
  PumpLoop();
  EXPECT_TRUE(GetFakeHandler()->AllOutgoingMessagesReceived());

  // Rebuild the client, which should resend the old message.
  StoreCredentials();
  BuildMCSClient();
  InitializeClient();

  clock()->Advance(base::Seconds(kTTLValue - 1));
  MCSMessage message2(BuildDataMessage("from", "category", "X", 1, "1",
                                       kTTLValue, 1, kTTLValue - 1, "", 0,
                                       IMMEDIATE_ACK_NO));
  LoginClient(std::vector<std::string>());
  GetFakeHandler()->ExpectOutgoingMessage(message2);
  PumpLoop();
  EXPECT_TRUE(GetFakeHandler()->AllOutgoingMessagesReceived());
}

// Send messages with RMQ support, followed by receiving a stream ack. On
// restart nothing should be recent.
TEST_F(MCSClientTest, SendMessageRMQWithStreamAck) {
  BuildMCSClient();
  InitializeClient();
  LoginClient(std::vector<std::string>());

  // Send some messages.
  for (int i = 1; i <= kMessageBatchSize; ++i) {
    MCSMessage message(BuildDataMessage("from", "category", "X", 1,
                                        base::NumberToString(i), kTTLValue, 1,
                                        0, "", 0, IMMEDIATE_ACK_NO));
    GetFakeHandler()->ExpectOutgoingMessage(message);
    mcs_client()->SendMessage(message);
    PumpLoop();
  }
  EXPECT_TRUE(GetFakeHandler()->AllOutgoingMessagesReceived());

  // Receive the ack.
  std::unique_ptr<mcs_proto::IqStanza> ack = BuildStreamAck();
  ack->set_last_stream_id_received(kMessageBatchSize + 1);
  GetFakeHandler()->ReceiveMessage(MCSMessage(kIqStanzaTag, std::move(ack)));
  WaitForMCSEvent();

  // Reconnect and ensure no messages are resent.
  StoreCredentials();
  BuildMCSClient();
  InitializeClient();
  LoginClient(std::vector<std::string>());
  PumpLoop();
}

// Send messages with RMQ support. On restart, receive a SelectiveAck with
// the login response. No messages should be resent.
TEST_F(MCSClientTest, SendMessageRMQAckOnReconnect) {
  BuildMCSClient();
  InitializeClient();
  LoginClient(std::vector<std::string>());

  // Send some messages.
  std::vector<std::string> id_list;
  for (int i = 1; i <= kMessageBatchSize; ++i) {
    id_list.push_back(base::NumberToString(i));
    MCSMessage message(BuildDataMessage("from", "category", id_list.back(), 1,
                                        id_list.back(), kTTLValue, 1, 0, "", 0,
                                        IMMEDIATE_ACK_NO));
    GetFakeHandler()->ExpectOutgoingMessage(message);
    mcs_client()->SendMessage(message);
    PumpLoop();
  }
  EXPECT_TRUE(GetFakeHandler()->AllOutgoingMessagesReceived());

  // Rebuild the client, and receive an acknowledgment for the messages as
  // part of the login response.
  StoreCredentials();
  BuildMCSClient();
  InitializeClient();
  LoginClient(std::vector<std::string>());
  std::unique_ptr<mcs_proto::IqStanza> ack(BuildSelectiveAck(id_list));
  GetFakeHandler()->ReceiveMessage(MCSMessage(kIqStanzaTag, std::move(ack)));
  EXPECT_TRUE(GetFakeHandler()->AllOutgoingMessagesReceived());
}

// Send messages with RMQ support. On restart, receive a SelectiveAck with
// the login response that only acks some messages. The unacked messages should
// be resent.
TEST_F(MCSClientTest, SendMessageRMQPartialAckOnReconnect) {
  BuildMCSClient();
  InitializeClient();
  LoginClient(std::vector<std::string>());

  // Send some messages.
  std::vector<std::string> id_list;
  for (int i = 1; i <= kMessageBatchSize; ++i) {
    id_list.push_back(base::NumberToString(i));
    MCSMessage message(BuildDataMessage("from", "category", id_list.back(), 1,
                                        id_list.back(), kTTLValue, 1, 0, "", 0,
                                        IMMEDIATE_ACK_NO));
    GetFakeHandler()->ExpectOutgoingMessage(message);
    mcs_client()->SendMessage(message);
    PumpLoop();
  }
  EXPECT_TRUE(GetFakeHandler()->AllOutgoingMessagesReceived());

  // Rebuild the client, and receive an acknowledgment for the messages as
  // part of the login response.
  StoreCredentials();
  BuildMCSClient();
  InitializeClient();
  LoginClient(std::vector<std::string>());

  std::vector<std::string> acked_ids, remaining_ids;
  acked_ids.insert(acked_ids.end(),
                   id_list.begin(),
                   id_list.begin() + kMessageBatchSize / 2);
  remaining_ids.insert(remaining_ids.end(),
                       id_list.begin() + kMessageBatchSize / 2,
                       id_list.end());
  for (int i = 1; i <= kMessageBatchSize / 2; ++i) {
    MCSMessage message(BuildDataMessage(
        "from", "category", remaining_ids[i - 1], 2, remaining_ids[i - 1],
        kTTLValue, 1, 0, "", 0, IMMEDIATE_ACK_NO));
    GetFakeHandler()->ExpectOutgoingMessage(message);
  }
  std::unique_ptr<mcs_proto::IqStanza> ack(BuildSelectiveAck(acked_ids));
  GetFakeHandler()->ReceiveMessage(MCSMessage(kIqStanzaTag, std::move(ack)));
  WaitForMCSEvent();
  PumpLoop();
  EXPECT_TRUE(GetFakeHandler()->AllOutgoingMessagesReceived());
}

// Handle a selective ack that only acks some messages. The remaining unacked
// messages should be resent. On restart, those same unacked messages should be
// resent, and any pending acks for incoming messages should also be resent.
TEST_F(MCSClientTest, SelectiveAckMidStream) {
  BuildMCSClient();
  InitializeClient();
  LoginClient(std::vector<std::string>());

  // Server stream id 2 ("s1").
  // Acks client stream id 0 (login).
  MCSMessage sMessage1(BuildDataMessage("from", "category", "X", 0, "s1",
                                        kTTLValue, 1, 0, "", 0,
                                        IMMEDIATE_ACK_NO));
  GetFakeHandler()->ReceiveMessage(sMessage1);
  WaitForMCSEvent();
  PumpLoop();

  // Client stream id 1 ("1").
  // Acks server stream id 2 ("s1").
  MCSMessage cMessage1(BuildDataMessage("from", "category", "Y", 2, "1",
                                        kTTLValue, 1, 0, "", 0,
                                        IMMEDIATE_ACK_NO));
  GetFakeHandler()->ExpectOutgoingMessage(cMessage1);
  mcs_client()->SendMessage(cMessage1);
  PumpLoop();
  EXPECT_TRUE(GetFakeHandler()->AllOutgoingMessagesReceived());

  // Server stream id 3 ("s2").
  // Acks client stream id 1 ("1").
  // Confirms ack of server stream id 2 ("s1").
  MCSMessage sMessage2(BuildDataMessage("from", "category", "X", 1, "s2",
                                        kTTLValue, 1, 0, "", 0,
                                        IMMEDIATE_ACK_NO));
  GetFakeHandler()->ReceiveMessage(sMessage2);
  WaitForMCSEvent();
  PumpLoop();

  // Client Stream id 2 ("2").
  // Acks server stream id 3 ("s2").
  MCSMessage cMessage2(BuildDataMessage("from", "category", "Y", 3, "2",
                                        kTTLValue, 1, 0, "", 0,
                                        IMMEDIATE_ACK_NO));
  GetFakeHandler()->ExpectOutgoingMessage(cMessage2);
  mcs_client()->SendMessage(cMessage2);
  PumpLoop();
  EXPECT_TRUE(GetFakeHandler()->AllOutgoingMessagesReceived());

  // Simulate the last message being dropped by having the server selectively
  // ack client message "1".
  // Client message "2" should be resent, acking server stream id 4 (selective
  // ack).
  MCSMessage cMessage3(BuildDataMessage("from", "category", "Y", 4, "2",
                                        kTTLValue, 1, 0, "", 0,
                                        IMMEDIATE_ACK_NO));
  GetFakeHandler()->ExpectOutgoingMessage(cMessage3);
  std::vector<std::string> acked_ids(1, "1");
  std::unique_ptr<mcs_proto::IqStanza> ack(BuildSelectiveAck(acked_ids));
  GetFakeHandler()->ReceiveMessage(MCSMessage(kIqStanzaTag, std::move(ack)));
  WaitForMCSEvent();
  PumpLoop();
  EXPECT_TRUE(GetFakeHandler()->AllOutgoingMessagesReceived());

  // Rebuild the client without any further acks from server. Note that this
  // resets the stream ids.
  // Sever message "s2" should be acked as part of login.
  // Client message "2" should be resent.
  StoreCredentials();
  BuildMCSClient();
  InitializeClient();

  acked_ids[0] = "s2";
  LoginClient(acked_ids);

  MCSMessage cMessage4(BuildDataMessage("from", "category", "Y", 1, "2",
                                        kTTLValue, 1, 0, "", 0,
                                        IMMEDIATE_ACK_NO));
  GetFakeHandler()->ExpectOutgoingMessage(cMessage4);
  PumpLoop();
  EXPECT_TRUE(GetFakeHandler()->AllOutgoingMessagesReceived());
}

// Receive some messages. On restart, the login request should contain the
// appropriate acknowledged ids.
TEST_F(MCSClientTest, AckOnLogin) {
  BuildMCSClient();
  InitializeClient();
  LoginClient(std::vector<std::string>());

  // Receive some messages.
  std::vector<std::string> id_list;
  for (int i = 1; i <= kMessageBatchSize; ++i) {
    id_list.push_back(base::NumberToString(i));
    MCSMessage message(BuildDataMessage("from", "category", "X", 1,
                                        id_list.back(), kTTLValue, 1, 0, "", 0,
                                        IMMEDIATE_ACK_NO));
    GetFakeHandler()->ReceiveMessage(message);
    WaitForMCSEvent();
    PumpLoop();
  }

  // Restart the client.
  StoreCredentials();
  BuildMCSClient();
  InitializeClient();
  LoginClient(id_list);
}

// Receive some messages. On the next send, the outgoing message should contain
// the appropriate last stream id received field to ack the received messages.
TEST_F(MCSClientTest, AckOnSend) {
  BuildMCSClient();
  InitializeClient();
  LoginClient(std::vector<std::string>());

  // Receive some messages.
  std::vector<std::string> id_list;
  for (int i = 1; i <= kMessageBatchSize; ++i) {
    id_list.push_back(base::NumberToString(i));
    MCSMessage message(BuildDataMessage("from", "category", id_list.back(), 1,
                                        id_list.back(), kTTLValue, 1, 0, "", 0,
                                        IMMEDIATE_ACK_NO));
    GetFakeHandler()->ReceiveMessage(message);
    PumpLoop();
  }

  // Trigger a message send, which should acknowledge via stream ack.
  MCSMessage message(BuildDataMessage("from", "category", "X",
                                      kMessageBatchSize + 1, "1", kTTLValue, 1,
                                      0, "", 0, IMMEDIATE_ACK_NO));
  GetFakeHandler()->ExpectOutgoingMessage(message);
  mcs_client()->SendMessage(message);
  EXPECT_TRUE(GetFakeHandler()->AllOutgoingMessagesReceived());
}

// Receive the ack limit in messages, which should trigger an automatic
// stream ack. Receive a heartbeat to confirm the ack.
TEST_F(MCSClientTest, AckWhenLimitReachedWithHeartbeat) {
  BuildMCSClient();
  InitializeClient();
  LoginClient(std::vector<std::string>());

  // The stream ack.
  std::unique_ptr<mcs_proto::IqStanza> ack = BuildStreamAck();
  ack->set_last_stream_id_received(kAckLimitSize + 1);
  GetFakeHandler()->ExpectOutgoingMessage(
      MCSMessage(kIqStanzaTag, std::move(ack)));

  // Receive some messages.
  std::vector<std::string> id_list;
  for (int i = 1; i <= kAckLimitSize; ++i) {
    id_list.push_back(base::NumberToString(i));
    MCSMessage message(BuildDataMessage("from", "category", id_list.back(), 1,
                                        id_list.back(), kTTLValue, 1, 0, "", 0,
                                        IMMEDIATE_ACK_NO));
    GetFakeHandler()->ReceiveMessage(message);
    WaitForMCSEvent();
    PumpLoop();
  }
  EXPECT_TRUE(GetFakeHandler()->AllOutgoingMessagesReceived());

  // Receive a heartbeat confirming the ack (and receive the heartbeat ack).
  std::unique_ptr<mcs_proto::HeartbeatPing> heartbeat(
      new mcs_proto::HeartbeatPing());
  heartbeat->set_last_stream_id_received(2);

  std::unique_ptr<mcs_proto::HeartbeatAck> heartbeat_ack(
      new mcs_proto::HeartbeatAck());
  heartbeat_ack->set_last_stream_id_received(kAckLimitSize + 2);
  GetFakeHandler()->ExpectOutgoingMessage(
      MCSMessage(kHeartbeatAckTag, std::move(heartbeat_ack)));

  GetFakeHandler()->ReceiveMessage(
      MCSMessage(kHeartbeatPingTag, std::move(heartbeat)));
  PumpLoop();
  EXPECT_TRUE(GetFakeHandler()->AllOutgoingMessagesReceived());

  // Rebuild the client. Nothing should be sent on login.
  StoreCredentials();
  BuildMCSClient();
  InitializeClient();
  LoginClient(std::vector<std::string>());
  EXPECT_TRUE(GetFakeHandler()->AllOutgoingMessagesReceived());
}

// If a message's TTL has expired by the time it reaches the front of the send
// queue, it should be dropped.
TEST_F(MCSClientTest, ExpiredTTLOnSend) {
  BuildMCSClient();
  InitializeClient();
  LoginClient(std::vector<std::string>());
  MCSMessage message(BuildDataMessage("from", "category", "X", 1, "1",
                                      kTTLValue, 1, 0, "", 0,
                                      IMMEDIATE_ACK_NO));

  // Advance time to after the TTL.
  clock()->Advance(base::Seconds(kTTLValue + 2));
  EXPECT_TRUE(sent_message_id().empty());
  mcs_client()->SendMessage(message);

  // No messages should be sent, but the callback should still be invoked.
  EXPECT_EQ("X", sent_message_id());
  EXPECT_EQ(MCSClient::TTL_EXCEEDED, message_send_status());
  EXPECT_TRUE(GetFakeHandler()->AllOutgoingMessagesReceived());
}

TEST_F(MCSClientTest, ExpiredTTLOnRestart) {
  BuildMCSClient();
  InitializeClient();
  LoginClient(std::vector<std::string>());
  GetFakeHandler()->set_fail_send(true);
  MCSMessage message(BuildDataMessage("from", "category", "X", 1, "1",
                                      kTTLValue, 1, 0, "", 0,
                                      IMMEDIATE_ACK_NO));

  // The initial (failed) send.
  GetFakeHandler()->ExpectOutgoingMessage(message);
  GetFakeHandler()->set_fail_send(false);
  mcs_client()->SendMessage(message);
  PumpLoop();
  EXPECT_TRUE(GetFakeHandler()->AllOutgoingMessagesReceived());

  // Move the clock forward and rebuild the client, which should fail the
  // message send on restart.
  clock()->Advance(base::Seconds(kTTLValue + 2));
  StoreCredentials();
  BuildMCSClient();
  InitializeClient();
  LoginClient(std::vector<std::string>());
  PumpLoop();
  EXPECT_EQ("X", sent_message_id());
  EXPECT_EQ(MCSClient::TTL_EXCEEDED, message_send_status());
  EXPECT_TRUE(GetFakeHandler()->AllOutgoingMessagesReceived());
}

// Sending two messages with the same collapse key and same app id while
// disconnected should only send the latter of the two on reconnection.
TEST_F(MCSClientTest, CollapseKeysSameApp) {
  BuildMCSClient();
  InitializeClient();
  MCSMessage message(BuildDataMessage("from", "app", "message id 1", 1, "1",
                                      kTTLValue, 1, 0, "token", 0,
                                      IMMEDIATE_ACK_NO));
  mcs_client()->SendMessage(message);

  MCSMessage message2(BuildDataMessage("from", "app", "message id 2", 1, "1",
                                       kTTLValue, 1, 0, "token", 0,
                                       IMMEDIATE_ACK_NO));
  mcs_client()->SendMessage(message2);

  LoginClient(std::vector<std::string>());
  GetFakeHandler()->ExpectOutgoingMessage(message2);
  PumpLoop();
}

// Sending two messages with the same collapse key and different app id while
// disconnected should not perform any collapsing.
TEST_F(MCSClientTest, CollapseKeysDifferentApp) {
  BuildMCSClient();
  InitializeClient();
  MCSMessage message(BuildDataMessage("from", "app", "message id 1", 1, "1",
                                      kTTLValue, 1, 0, "token", 0,
                                      IMMEDIATE_ACK_NO));
  mcs_client()->SendMessage(message);

  MCSMessage message2(BuildDataMessage("from", "app 2", "message id 2", 1, "2",
                                       kTTLValue, 1, 0, "token", 0,
                                       IMMEDIATE_ACK_NO));
  mcs_client()->SendMessage(message2);

  LoginClient(std::vector<std::string>());
  GetFakeHandler()->ExpectOutgoingMessage(message);
  GetFakeHandler()->ExpectOutgoingMessage(message2);
  PumpLoop();
}

// Sending two messages with the same collapse key and app id, but different
// user, while disconnected, should not perform any collapsing.
TEST_F(MCSClientTest, CollapseKeysDifferentUser) {
  BuildMCSClient();
  InitializeClient();
  MCSMessage message(BuildDataMessage("from", "app", "message id 1", 1, "1",
                                      kTTLValue, 1, 0, "token", 0,
                                      IMMEDIATE_ACK_NO));
  mcs_client()->SendMessage(message);

  MCSMessage message2(BuildDataMessage("from", "app", "message id 2", 1, "2",
                                       kTTLValue, 1, 0, "token", 1,
                                       IMMEDIATE_ACK_NO));
  mcs_client()->SendMessage(message2);

  LoginClient(std::vector<std::string>());
  GetFakeHandler()->ExpectOutgoingMessage(message);
  GetFakeHandler()->ExpectOutgoingMessage(message2);
  PumpLoop();
}

// Test case for setting a custom heartbeat interval, when it is too short.
// Covers both connection restart and storing of custom intervals.
TEST_F(MCSClientTest, CustomHeartbeatIntervalTooShort) {
  BuildMCSClient();
  InitializeClient();
  LoginClient(std::vector<std::string>());
  PumpLoop();
  StoreCredentials();

  HeartbeatManager* hb_manager = mcs_client()->GetHeartbeatManagerForTesting();
  // By default custom client interval is not set.
  EXPECT_FALSE(hb_manager->HasClientHeartbeatInterval());

  const std::string component_1 = "component1";
  int interval_ms = 15 * 1000;  // 15 seconds, too low.
  mcs_client()->AddHeartbeatInterval(component_1, interval_ms);
  // Setting was too low so it was ignored.
  EXPECT_FALSE(hb_manager->HasClientHeartbeatInterval());

  // Restore and check again to make sure that nothing was set in store.
  BuildMCSClient();
  InitializeClient();
  LoginClientWithHeartbeat(std::vector<std::string>(), 0);
  PumpLoop();

  hb_manager = mcs_client()->GetHeartbeatManagerForTesting();
  EXPECT_FALSE(hb_manager->HasClientHeartbeatInterval());
}

// Test case for setting a custom heartbeat interval, when it is too long.
// Covers both connection restart and storing of custom intervals.
TEST_F(MCSClientTest, CustomHeartbeatIntervalTooLong) {
  BuildMCSClient();
  InitializeClient();
  LoginClient(std::vector<std::string>());
  PumpLoop();
  StoreCredentials();

  HeartbeatManager* hb_manager = mcs_client()->GetHeartbeatManagerForTesting();

  const std::string component_1 = "component1";
  int interval_ms = 60 * 60 * 1000;  // 1 hour, too high.
  mcs_client()->AddHeartbeatInterval(component_1, interval_ms);
  // Setting was too high, again it was ignored.
  EXPECT_FALSE(hb_manager->HasClientHeartbeatInterval());

  // Restore and check again to make sure that nothing was set in store.
  BuildMCSClient();
  InitializeClient();
  LoginClientWithHeartbeat(std::vector<std::string>(), 0);
  PumpLoop();

  // Setting was too high, again it was ignored.
  hb_manager = mcs_client()->GetHeartbeatManagerForTesting();
  EXPECT_FALSE(hb_manager->HasClientHeartbeatInterval());
}

// Tests adding and removing custom heartbeat interval.
// Covers both connection restart and storing of custom intervals.
TEST_F(MCSClientTest, CustomHeartbeatIntervalSingleInterval) {
  BuildMCSClient();
  InitializeClient();
  LoginClient(std::vector<std::string>());
  PumpLoop();
  StoreCredentials();

  TestConnectionListener test_connection_listener;
  connection_factory()->SetConnectionListener(&test_connection_listener);

  HeartbeatManager* hb_manager = mcs_client()->GetHeartbeatManagerForTesting();

  const std::string component_1 = "component1";
  int interval_ms = 5 * 60 * 1000;  // 5 minutes. A valid setting.

  AddExpectedLoginRequest(std::vector<std::string>(), interval_ms);
  mcs_client()->AddHeartbeatInterval(component_1, interval_ms);
  PumpLoop();

  // Interval was OK. HearbeatManager should get that setting now.
  EXPECT_TRUE(hb_manager->HasClientHeartbeatInterval());
  EXPECT_EQ(interval_ms, hb_manager->GetClientHeartbeatIntervalMs());
  EXPECT_EQ(1, test_connection_listener.get_disconnect_counter());

  // Check that setting was persisted and will take effect upon restart.
  BuildMCSClient();
  InitializeClient();
  LoginClientWithHeartbeat(std::vector<std::string>(), interval_ms);
  PumpLoop();

  // HB manger uses the shortest persisted interval after restart.
  hb_manager = mcs_client()->GetHeartbeatManagerForTesting();
  EXPECT_TRUE(hb_manager->HasClientHeartbeatInterval());
  EXPECT_EQ(interval_ms, hb_manager->GetClientHeartbeatIntervalMs());

  mcs_client()->RemoveHeartbeatInterval(component_1);
  PumpLoop();

  // Check that setting was persisted and will take effect upon restart.
  BuildMCSClient();
  InitializeClient();
  LoginClientWithHeartbeat(std::vector<std::string>(), 0);
  PumpLoop();

  hb_manager = mcs_client()->GetHeartbeatManagerForTesting();
  EXPECT_FALSE(hb_manager->HasClientHeartbeatInterval());
}

// Tests adding custom heartbeat interval before connection is initialized.
TEST_F(MCSClientTest, CustomHeartbeatIntervalSetBeforeInitialize) {
  BuildMCSClient();

  const std::string component_1 = "component1";
  int interval_ms = 5 * 60 * 1000;  // 5 minutes. A valid setting.
  mcs_client()->AddHeartbeatInterval(component_1, interval_ms);
  InitializeClient();
  LoginClientWithHeartbeat(std::vector<std::string>(), interval_ms);
  HeartbeatManager* hb_manager = mcs_client()->GetHeartbeatManagerForTesting();
  EXPECT_TRUE(hb_manager->HasClientHeartbeatInterval());
}

// Tests adding custom heartbeat interval after connection is initialized, but
// but before login is sent.
TEST_F(MCSClientTest, CustomHeartbeatIntervalSetBeforeLogin) {
  BuildMCSClient();

  const std::string component_1 = "component1";
  int interval_ms = 5 * 60 * 1000;  // 5 minutes. A valid setting.
  InitializeClient();
  mcs_client()->AddHeartbeatInterval(component_1, interval_ms);
  LoginClientWithHeartbeat(std::vector<std::string>(), interval_ms);
  HeartbeatManager* hb_manager = mcs_client()->GetHeartbeatManagerForTesting();
  EXPECT_TRUE(hb_manager->HasClientHeartbeatInterval());
}

// Tests situation when two heartbeat intervals are set and second is longer.
// Covers both connection restart and storing of custom intervals.
TEST_F(MCSClientTest, CustomHeartbeatIntervalSecondIntervalLonger) {
  BuildMCSClient();
  InitializeClient();
  LoginClient(std::vector<std::string>());
  PumpLoop();
  StoreCredentials();

  TestConnectionListener test_connection_listener;
  connection_factory()->SetConnectionListener(&test_connection_listener);

  HeartbeatManager* hb_manager = mcs_client()->GetHeartbeatManagerForTesting();

  const std::string component_1 = "component1";
  int interval_ms = 5 * 60 * 1000;  // 5 minutes. A valid setting.

  AddExpectedLoginRequest(std::vector<std::string>(), interval_ms);
  mcs_client()->AddHeartbeatInterval(component_1, interval_ms);
  PumpLoop();

  const std::string component_2 = "component2";
  int other_interval_ms = 10 * 60 * 1000;  // 10 minutes. A valid setting.
  mcs_client()->AddHeartbeatInterval(component_2, other_interval_ms);
  PumpLoop();

  // Interval was OK, but longer. HearbeatManager will use the first one.
  EXPECT_TRUE(hb_manager->HasClientHeartbeatInterval());
  EXPECT_EQ(interval_ms, hb_manager->GetClientHeartbeatIntervalMs());
  EXPECT_EQ(1, test_connection_listener.get_disconnect_counter());

  // Check that setting was persisted and will take effect upon restart.
  BuildMCSClient();
  InitializeClient();
  LoginClientWithHeartbeat(std::vector<std::string>(), interval_ms);
  PumpLoop();

  // HB manger uses the shortest persisted interval after restart.
  hb_manager = mcs_client()->GetHeartbeatManagerForTesting();
  EXPECT_TRUE(hb_manager->HasClientHeartbeatInterval());
  EXPECT_EQ(interval_ms, hb_manager->GetClientHeartbeatIntervalMs());
}

// Tests situation when two heartbeat intervals are set and second is shorter.
// Covers both connection restart and storing of custom intervals.
TEST_F(MCSClientTest, CustomHeartbeatIntervalSecondIntervalShorter) {
  BuildMCSClient();
  InitializeClient();
  LoginClient(std::vector<std::string>());
  PumpLoop();
  StoreCredentials();

  TestConnectionListener test_connection_listener;
  connection_factory()->SetConnectionListener(&test_connection_listener);

  HeartbeatManager* hb_manager = mcs_client()->GetHeartbeatManagerForTesting();

  const std::string component_1 = "component1";
  int interval_ms = 5 * 60 * 1000;  // 5 minutes. A valid setting.

  AddExpectedLoginRequest(std::vector<std::string>(), interval_ms);
  mcs_client()->AddHeartbeatInterval(component_1, interval_ms);
  PumpLoop();

  const std::string component_2 = "component2";
  int other_interval_ms = 3 * 60 * 1000;  // 3 minutes. A valid setting.
  AddExpectedLoginRequest(std::vector<std::string>(), other_interval_ms);
  mcs_client()->AddHeartbeatInterval(component_2, other_interval_ms);
  PumpLoop();
  // Interval was OK. HearbeatManager should get that setting now.
  EXPECT_TRUE(hb_manager->HasClientHeartbeatInterval());
  EXPECT_EQ(other_interval_ms, hb_manager->GetClientHeartbeatIntervalMs());
  EXPECT_EQ(2, test_connection_listener.get_disconnect_counter());

  // Check that setting was persisted and will take effect upon restart.
  BuildMCSClient();
  InitializeClient();
  LoginClientWithHeartbeat(std::vector<std::string>(), other_interval_ms);
  PumpLoop();

  // HB manger uses the shortest persisted interval after restart.
  hb_manager = mcs_client()->GetHeartbeatManagerForTesting();
  EXPECT_TRUE(hb_manager->HasClientHeartbeatInterval());
  EXPECT_EQ(other_interval_ms, hb_manager->GetClientHeartbeatIntervalMs());
}

// Tests situation shorter of two intervals is removed.
// Covers both connection restart and storing of custom intervals.
TEST_F(MCSClientTest, CustomHeartbeatIntervalRemoveShorterInterval) {
  BuildMCSClient();
  InitializeClient();
  LoginClient(std::vector<std::string>());
  PumpLoop();
  StoreCredentials();

  TestConnectionListener test_connection_listener;
  connection_factory()->SetConnectionListener(&test_connection_listener);

  HeartbeatManager* hb_manager = mcs_client()->GetHeartbeatManagerForTesting();

  const std::string component_1 = "component1";
  int interval_ms = 5 * 60 * 1000;  // 5 minutes. A valid setting.

  AddExpectedLoginRequest(std::vector<std::string>(), interval_ms);
  mcs_client()->AddHeartbeatInterval(component_1, interval_ms);
  PumpLoop();

  const std::string component_2 = "component2";
  int other_interval_ms = 3 * 60 * 1000;  // 3 minutes. A valid setting.
  AddExpectedLoginRequest(std::vector<std::string>(), other_interval_ms);
  mcs_client()->AddHeartbeatInterval(component_2, other_interval_ms);
  PumpLoop();

  mcs_client()->RemoveHeartbeatInterval(component_2);
  PumpLoop();

  // Removing the lowest setting reverts to second lowest.
  EXPECT_TRUE(hb_manager->HasClientHeartbeatInterval());
  EXPECT_EQ(interval_ms, hb_manager->GetClientHeartbeatIntervalMs());
  // No connection reset expected.
  EXPECT_EQ(2, test_connection_listener.get_disconnect_counter());

  // Check that setting was persisted and will take effect upon restart.
  BuildMCSClient();
  InitializeClient();
  LoginClientWithHeartbeat(std::vector<std::string>(), interval_ms);
  PumpLoop();

  // HB manger uses the shortest persisted interval after restart.
  hb_manager = mcs_client()->GetHeartbeatManagerForTesting();
  EXPECT_TRUE(hb_manager->HasClientHeartbeatInterval());
  EXPECT_EQ(interval_ms, hb_manager->GetClientHeartbeatIntervalMs());
}

// Receive a message with immediate ack request, which should trigger an
// automatic stream ack.
TEST_F(MCSClientTest, AckWhenImmediateAckRequested) {
  BuildMCSClient();
  InitializeClient();
  LoginClient(std::vector<std::string>());

  // The stream ack.
  std::unique_ptr<mcs_proto::IqStanza> ack = BuildStreamAck();
  ack->set_last_stream_id_received(kAckLimitSize - 1);
  GetFakeHandler()->ExpectOutgoingMessage(
      MCSMessage(kIqStanzaTag, std::move(ack)));

  // Receive some messages.
  for (int i = 1; i < kAckLimitSize - 2; ++i) {
    std::string id(base::NumberToString(i));
    MCSMessage message(BuildDataMessage("from", "category", id, 1, id,
                                        kTTLValue, 1, 0, "", 0,
                                        IMMEDIATE_ACK_NO));
    GetFakeHandler()->ReceiveMessage(message);
    WaitForMCSEvent();
    PumpLoop();
  }
  // This message expects immediate ACK, which means it will happen before the
  // ACK limit size is reached. All of the preceding messages will be acked at
  // the same time.
  std::string ack_id(base::NumberToString(kAckLimitSize - 1));
  MCSMessage message(BuildDataMessage("from", "category", ack_id, 1, ack_id,
                                      kTTLValue, 1, 0, "", 0,
                                      IMMEDIATE_ACK_YES));
  GetFakeHandler()->ReceiveMessage(message);
  WaitForMCSEvent();
  PumpLoop();

  EXPECT_TRUE(GetFakeHandler()->AllOutgoingMessagesReceived());
}

} // namespace

}  // namespace gcm