485d48b6ff5b861500cf5af04ea0aecd05d9ff94
[platform/framework/web/crosswalk.git] / src / net / quic / quic_connection_test.cc
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "net/quic/quic_connection.h"
6
7 #include "base/basictypes.h"
8 #include "base/bind.h"
9 #include "base/stl_util.h"
10 #include "net/base/net_errors.h"
11 #include "net/quic/congestion_control/loss_detection_interface.h"
12 #include "net/quic/congestion_control/receive_algorithm_interface.h"
13 #include "net/quic/congestion_control/send_algorithm_interface.h"
14 #include "net/quic/crypto/null_encrypter.h"
15 #include "net/quic/crypto/quic_decrypter.h"
16 #include "net/quic/crypto/quic_encrypter.h"
17 #include "net/quic/quic_protocol.h"
18 #include "net/quic/quic_sent_packet_manager.h"
19 #include "net/quic/quic_utils.h"
20 #include "net/quic/test_tools/mock_clock.h"
21 #include "net/quic/test_tools/mock_random.h"
22 #include "net/quic/test_tools/quic_connection_peer.h"
23 #include "net/quic/test_tools/quic_framer_peer.h"
24 #include "net/quic/test_tools/quic_packet_creator_peer.h"
25 #include "net/quic/test_tools/quic_sent_packet_manager_peer.h"
26 #include "net/quic/test_tools/quic_test_utils.h"
27 #include "testing/gmock/include/gmock/gmock.h"
28 #include "testing/gtest/include/gtest/gtest.h"
29
30 using base::StringPiece;
31 using std::map;
32 using std::vector;
33 using testing::_;
34 using testing::AnyNumber;
35 using testing::AtLeast;
36 using testing::ContainerEq;
37 using testing::Contains;
38 using testing::DoAll;
39 using testing::InSequence;
40 using testing::InvokeWithoutArgs;
41 using testing::Ref;
42 using testing::Return;
43 using testing::SaveArg;
44 using testing::StrictMock;
45
46 namespace net {
47 namespace test {
48 namespace {
49
50 const char data1[] = "foo";
51 const char data2[] = "bar";
52
53 const bool kFin = true;
54 const bool kEntropyFlag = true;
55
56 const QuicPacketEntropyHash kTestEntropyHash = 76;
57
58 const int kDefaultRetransmissionTimeMs = 500;
59 const int kMinRetransmissionTimeMs = 200;
60
61 // Used by TestConnection::SendStreamData3.
62 const QuicStreamId kStreamId3 = 3;
63 // Used by TestConnection::SendStreamData5.
64 const QuicStreamId kStreamId5 = 5;
65
66 class TestReceiveAlgorithm : public ReceiveAlgorithmInterface {
67  public:
68   explicit TestReceiveAlgorithm(QuicCongestionFeedbackFrame* feedback)
69       : feedback_(feedback) {
70   }
71
72   bool GenerateCongestionFeedback(
73       QuicCongestionFeedbackFrame* congestion_feedback) {
74     if (feedback_ == NULL) {
75       return false;
76     }
77     *congestion_feedback = *feedback_;
78     return true;
79   }
80
81   MOCK_METHOD3(RecordIncomingPacket,
82                void(QuicByteCount, QuicPacketSequenceNumber, QuicTime));
83
84  private:
85   QuicCongestionFeedbackFrame* feedback_;
86
87   DISALLOW_COPY_AND_ASSIGN(TestReceiveAlgorithm);
88 };
89
90 // TaggingEncrypter appends kTagSize bytes of |tag| to the end of each message.
91 class TaggingEncrypter : public QuicEncrypter {
92  public:
93   explicit TaggingEncrypter(uint8 tag)
94       : tag_(tag) {
95   }
96
97   virtual ~TaggingEncrypter() {}
98
99   // QuicEncrypter interface.
100   virtual bool SetKey(StringPiece key) OVERRIDE { return true; }
101   virtual bool SetNoncePrefix(StringPiece nonce_prefix) OVERRIDE {
102     return true;
103   }
104
105   virtual bool Encrypt(StringPiece nonce,
106                        StringPiece associated_data,
107                        StringPiece plaintext,
108                        unsigned char* output) OVERRIDE {
109     memcpy(output, plaintext.data(), plaintext.size());
110     output += plaintext.size();
111     memset(output, tag_, kTagSize);
112     return true;
113   }
114
115   virtual QuicData* EncryptPacket(QuicPacketSequenceNumber sequence_number,
116                                   StringPiece associated_data,
117                                   StringPiece plaintext) OVERRIDE {
118     const size_t len = plaintext.size() + kTagSize;
119     uint8* buffer = new uint8[len];
120     Encrypt(StringPiece(), associated_data, plaintext, buffer);
121     return new QuicData(reinterpret_cast<char*>(buffer), len, true);
122   }
123
124   virtual size_t GetKeySize() const OVERRIDE { return 0; }
125   virtual size_t GetNoncePrefixSize() const OVERRIDE { return 0; }
126
127   virtual size_t GetMaxPlaintextSize(size_t ciphertext_size) const OVERRIDE {
128     return ciphertext_size - kTagSize;
129   }
130
131   virtual size_t GetCiphertextSize(size_t plaintext_size) const OVERRIDE {
132     return plaintext_size + kTagSize;
133   }
134
135   virtual StringPiece GetKey() const OVERRIDE {
136     return StringPiece();
137   }
138
139   virtual StringPiece GetNoncePrefix() const OVERRIDE {
140     return StringPiece();
141   }
142
143  private:
144   enum {
145     kTagSize = 12,
146   };
147
148   const uint8 tag_;
149 };
150
151 // TaggingDecrypter ensures that the final kTagSize bytes of the message all
152 // have the same value and then removes them.
153 class TaggingDecrypter : public QuicDecrypter {
154  public:
155   virtual ~TaggingDecrypter() {}
156
157   // QuicDecrypter interface
158   virtual bool SetKey(StringPiece key) OVERRIDE { return true; }
159   virtual bool SetNoncePrefix(StringPiece nonce_prefix) OVERRIDE {
160     return true;
161   }
162
163   virtual bool Decrypt(StringPiece nonce,
164                        StringPiece associated_data,
165                        StringPiece ciphertext,
166                        unsigned char* output,
167                        size_t* output_length) OVERRIDE {
168     if (ciphertext.size() < kTagSize) {
169       return false;
170     }
171     if (!CheckTag(ciphertext, GetTag(ciphertext))) {
172       return false;
173     }
174     *output_length = ciphertext.size() - kTagSize;
175     memcpy(output, ciphertext.data(), *output_length);
176     return true;
177   }
178
179   virtual QuicData* DecryptPacket(QuicPacketSequenceNumber sequence_number,
180                                   StringPiece associated_data,
181                                   StringPiece ciphertext) OVERRIDE {
182     if (ciphertext.size() < kTagSize) {
183       return NULL;
184     }
185     if (!CheckTag(ciphertext, GetTag(ciphertext))) {
186       return NULL;
187     }
188     const size_t len = ciphertext.size() - kTagSize;
189     uint8* buf = new uint8[len];
190     memcpy(buf, ciphertext.data(), len);
191     return new QuicData(reinterpret_cast<char*>(buf), len,
192                         true /* owns buffer */);
193   }
194
195   virtual StringPiece GetKey() const OVERRIDE { return StringPiece(); }
196   virtual StringPiece GetNoncePrefix() const OVERRIDE { return StringPiece(); }
197
198  protected:
199   virtual uint8 GetTag(StringPiece ciphertext) {
200     return ciphertext.data()[ciphertext.size()-1];
201   }
202
203  private:
204   enum {
205     kTagSize = 12,
206   };
207
208   bool CheckTag(StringPiece ciphertext, uint8 tag) {
209     for (size_t i = ciphertext.size() - kTagSize; i < ciphertext.size(); i++) {
210       if (ciphertext.data()[i] != tag) {
211         return false;
212       }
213     }
214
215     return true;
216   }
217 };
218
219 // StringTaggingDecrypter ensures that the final kTagSize bytes of the message
220 // match the expected value.
221 class StrictTaggingDecrypter : public TaggingDecrypter {
222  public:
223   explicit StrictTaggingDecrypter(uint8 tag) : tag_(tag) {}
224   virtual ~StrictTaggingDecrypter() {}
225
226   // TaggingQuicDecrypter
227   virtual uint8 GetTag(StringPiece ciphertext) OVERRIDE {
228     return tag_;
229   }
230
231  private:
232   const uint8 tag_;
233 };
234
235 class TestConnectionHelper : public QuicConnectionHelperInterface {
236  public:
237   class TestAlarm : public QuicAlarm {
238    public:
239     explicit TestAlarm(QuicAlarm::Delegate* delegate)
240         : QuicAlarm(delegate) {
241     }
242
243     virtual void SetImpl() OVERRIDE {}
244     virtual void CancelImpl() OVERRIDE {}
245     using QuicAlarm::Fire;
246   };
247
248   TestConnectionHelper(MockClock* clock, MockRandom* random_generator)
249       : clock_(clock),
250         random_generator_(random_generator) {
251     clock_->AdvanceTime(QuicTime::Delta::FromSeconds(1));
252   }
253
254   // QuicConnectionHelperInterface
255   virtual const QuicClock* GetClock() const OVERRIDE {
256     return clock_;
257   }
258
259   virtual QuicRandom* GetRandomGenerator() OVERRIDE {
260     return random_generator_;
261   }
262
263   virtual QuicAlarm* CreateAlarm(QuicAlarm::Delegate* delegate) OVERRIDE {
264     return new TestAlarm(delegate);
265   }
266
267  private:
268   MockClock* clock_;
269   MockRandom* random_generator_;
270
271   DISALLOW_COPY_AND_ASSIGN(TestConnectionHelper);
272 };
273
274 class TestPacketWriter : public QuicPacketWriter {
275  public:
276   explicit TestPacketWriter(QuicVersion version)
277       : version_(version),
278         last_packet_size_(0),
279         write_blocked_(false),
280         block_on_next_write_(false),
281         is_write_blocked_data_buffered_(false),
282         is_server_(true),
283         final_bytes_of_last_packet_(0),
284         final_bytes_of_previous_packet_(0),
285         use_tagging_decrypter_(false),
286         packets_write_attempts_(0) {
287   }
288
289   // QuicPacketWriter interface
290   virtual WriteResult WritePacket(
291       const char* buffer, size_t buf_len,
292       const IPAddressNumber& self_address,
293       const IPEndPoint& peer_address) OVERRIDE {
294     QuicEncryptedPacket packet(buffer, buf_len);
295     ++packets_write_attempts_;
296
297     if (packet.length() >= sizeof(final_bytes_of_last_packet_)) {
298       final_bytes_of_previous_packet_ = final_bytes_of_last_packet_;
299       memcpy(&final_bytes_of_last_packet_, packet.data() + packet.length() - 4,
300              sizeof(final_bytes_of_last_packet_));
301     }
302
303     QuicFramer framer(SupportedVersions(version_),
304                       QuicTime::Zero(), !is_server_);
305     if (use_tagging_decrypter_) {
306       framer.SetDecrypter(new TaggingDecrypter);
307     }
308     visitor_.Reset();
309     framer.set_visitor(&visitor_);
310     EXPECT_TRUE(framer.ProcessPacket(packet));
311     if (block_on_next_write_) {
312       write_blocked_ = true;
313       block_on_next_write_ = false;
314     }
315     if (IsWriteBlocked()) {
316       return WriteResult(WRITE_STATUS_BLOCKED, -1);
317     }
318     last_packet_size_ = packet.length();
319     return WriteResult(WRITE_STATUS_OK, last_packet_size_);
320   }
321
322   virtual bool IsWriteBlockedDataBuffered() const OVERRIDE {
323     return is_write_blocked_data_buffered_;
324   }
325
326   virtual bool IsWriteBlocked() const OVERRIDE { return write_blocked_; }
327
328   virtual void SetWritable() OVERRIDE { write_blocked_ = false; }
329
330   void BlockOnNextWrite() { block_on_next_write_ = true; }
331
332   // Resets the visitor's state by clearing out the headers and frames.
333   void Reset() {
334     visitor_.Reset();
335   }
336
337   QuicPacketHeader* header() { return visitor_.header(); }
338
339   size_t frame_count() const { return visitor_.frame_count(); }
340
341   QuicAckFrame* ack() { return visitor_.ack(); }
342
343   QuicCongestionFeedbackFrame* feedback() { return visitor_.feedback(); }
344
345   QuicStopWaitingFrame* stop_waiting() { return visitor_.stop_waiting(); }
346
347   QuicConnectionCloseFrame* close() { return visitor_.close(); }
348
349   const vector<QuicStreamFrame>* stream_frames() const {
350     return visitor_.stream_frames();
351   }
352
353   size_t last_packet_size() {
354     return last_packet_size_;
355   }
356
357   QuicVersionNegotiationPacket* version_negotiation_packet() {
358     return visitor_.version_negotiation_packet();
359   }
360
361   void set_is_write_blocked_data_buffered(bool buffered) {
362     is_write_blocked_data_buffered_ = buffered;
363   }
364
365   void set_is_server(bool is_server) { is_server_ = is_server; }
366
367   // final_bytes_of_last_packet_ returns the last four bytes of the previous
368   // packet as a little-endian, uint32. This is intended to be used with a
369   // TaggingEncrypter so that tests can determine which encrypter was used for
370   // a given packet.
371   uint32 final_bytes_of_last_packet() { return final_bytes_of_last_packet_; }
372
373   // Returns the final bytes of the second to last packet.
374   uint32 final_bytes_of_previous_packet() {
375     return final_bytes_of_previous_packet_;
376   }
377
378   void use_tagging_decrypter() {
379     use_tagging_decrypter_ = true;
380   }
381
382   uint32 packets_write_attempts() { return packets_write_attempts_; }
383
384  private:
385   QuicVersion version_;
386   FramerVisitorCapturingFrames visitor_;
387   size_t last_packet_size_;
388   bool write_blocked_;
389   bool block_on_next_write_;
390   bool is_write_blocked_data_buffered_;
391   bool is_server_;
392   uint32 final_bytes_of_last_packet_;
393   uint32 final_bytes_of_previous_packet_;
394   bool use_tagging_decrypter_;
395   uint32 packets_write_attempts_;
396
397   DISALLOW_COPY_AND_ASSIGN(TestPacketWriter);
398 };
399
400 class TestConnection : public QuicConnection {
401  public:
402   TestConnection(QuicConnectionId connection_id,
403                  IPEndPoint address,
404                  TestConnectionHelper* helper,
405                  TestPacketWriter* writer,
406                  bool is_server,
407                  QuicVersion version)
408       : QuicConnection(connection_id, address, helper, writer, is_server,
409                        SupportedVersions(version)),
410         writer_(writer) {
411     // Disable tail loss probes for most tests.
412     QuicSentPacketManagerPeer::SetMaxTailLossProbes(
413         QuicConnectionPeer::GetSentPacketManager(this), 0);
414     writer_->set_is_server(is_server);
415   }
416
417   void SendAck() {
418     QuicConnectionPeer::SendAck(this);
419   }
420
421   void SetReceiveAlgorithm(TestReceiveAlgorithm* receive_algorithm) {
422      QuicConnectionPeer::SetReceiveAlgorithm(this, receive_algorithm);
423   }
424
425   void SetSendAlgorithm(SendAlgorithmInterface* send_algorithm) {
426     QuicConnectionPeer::SetSendAlgorithm(this, send_algorithm);
427   }
428
429   void SetLossAlgorithm(LossDetectionInterface* loss_algorithm) {
430     QuicSentPacketManagerPeer::SetLossAlgorithm(
431         QuicConnectionPeer::GetSentPacketManager(this), loss_algorithm);
432   }
433
434   void SendPacket(EncryptionLevel level,
435                   QuicPacketSequenceNumber sequence_number,
436                   QuicPacket* packet,
437                   QuicPacketEntropyHash entropy_hash,
438                   HasRetransmittableData retransmittable) {
439     RetransmittableFrames* retransmittable_frames =
440         retransmittable == HAS_RETRANSMITTABLE_DATA ?
441             new RetransmittableFrames() : NULL;
442     OnSerializedPacket(
443         SerializedPacket(sequence_number, PACKET_6BYTE_SEQUENCE_NUMBER,
444                          packet, entropy_hash, retransmittable_frames));
445   }
446
447   QuicConsumedData SendStreamDataWithString(
448       QuicStreamId id,
449       StringPiece data,
450       QuicStreamOffset offset,
451       bool fin,
452       QuicAckNotifier::DelegateInterface* delegate) {
453     IOVector data_iov;
454     if (!data.empty()) {
455       data_iov.Append(const_cast<char*>(data.data()), data.size());
456     }
457     return QuicConnection::SendStreamData(id, data_iov, offset, fin, delegate);
458   }
459
460   QuicConsumedData SendStreamData3() {
461     return SendStreamDataWithString(kStreamId3, "food", 0, !kFin, NULL);
462   }
463
464   QuicConsumedData SendStreamData5() {
465     return SendStreamDataWithString(kStreamId5, "food2", 0, !kFin, NULL);
466   }
467
468   // Ensures the connection can write stream data before writing.
469   QuicConsumedData EnsureWritableAndSendStreamData5() {
470     EXPECT_TRUE(CanWriteStreamData());
471     return SendStreamData5();
472   }
473
474   // The crypto stream has special semantics so that it is not blocked by a
475   // congestion window limitation, and also so that it gets put into a separate
476   // packet (so that it is easier to reason about a crypto frame not being
477   // split needlessly across packet boundaries).  As a result, we have separate
478   // tests for some cases for this stream.
479   QuicConsumedData SendCryptoStreamData() {
480     this->Flush();
481     QuicConsumedData consumed =
482         SendStreamDataWithString(kCryptoStreamId, "chlo", 0, !kFin, NULL);
483     this->Flush();
484     return consumed;
485   }
486
487   bool is_server() {
488     return QuicConnectionPeer::IsServer(this);
489   }
490
491   void set_version(QuicVersion version) {
492     QuicConnectionPeer::GetFramer(this)->set_version(version);
493   }
494
495   void SetSupportedVersions(const QuicVersionVector& versions) {
496     QuicConnectionPeer::GetFramer(this)->SetSupportedVersions(versions);
497   }
498
499   void set_is_server(bool is_server) {
500     writer_->set_is_server(is_server);
501     QuicPacketCreatorPeer::SetIsServer(
502         QuicConnectionPeer::GetPacketCreator(this), is_server);
503     QuicConnectionPeer::SetIsServer(this, is_server);
504   }
505
506   TestConnectionHelper::TestAlarm* GetAckAlarm() {
507     return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
508         QuicConnectionPeer::GetAckAlarm(this));
509   }
510
511   TestConnectionHelper::TestAlarm* GetRetransmissionAlarm() {
512     return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
513         QuicConnectionPeer::GetRetransmissionAlarm(this));
514   }
515
516   TestConnectionHelper::TestAlarm* GetSendAlarm() {
517     return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
518         QuicConnectionPeer::GetSendAlarm(this));
519   }
520
521   TestConnectionHelper::TestAlarm* GetResumeWritesAlarm() {
522     return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
523         QuicConnectionPeer::GetResumeWritesAlarm(this));
524   }
525
526   TestConnectionHelper::TestAlarm* GetTimeoutAlarm() {
527     return reinterpret_cast<TestConnectionHelper::TestAlarm*>(
528         QuicConnectionPeer::GetTimeoutAlarm(this));
529   }
530
531   using QuicConnection::SelectMutualVersion;
532
533  private:
534   TestPacketWriter* writer_;
535
536   DISALLOW_COPY_AND_ASSIGN(TestConnection);
537 };
538
539 class QuicConnectionTest : public ::testing::TestWithParam<QuicVersion> {
540  protected:
541   QuicConnectionTest()
542       : connection_id_(42),
543         framer_(SupportedVersions(version()), QuicTime::Zero(), false),
544         creator_(connection_id_, &framer_, &random_generator_, false),
545         send_algorithm_(new StrictMock<MockSendAlgorithm>),
546         loss_algorithm_(new MockLossAlgorithm()),
547         helper_(new TestConnectionHelper(&clock_, &random_generator_)),
548         writer_(new TestPacketWriter(version())),
549         connection_(connection_id_, IPEndPoint(), helper_.get(),
550                     writer_.get(), false, version()),
551         frame1_(1, false, 0, MakeIOVector(data1)),
552         frame2_(1, false, 3, MakeIOVector(data2)),
553         accept_packet_(true) {
554     connection_.set_visitor(&visitor_);
555     connection_.SetSendAlgorithm(send_algorithm_);
556     connection_.SetLossAlgorithm(loss_algorithm_);
557     framer_.set_received_entropy_calculator(&entropy_calculator_);
558     // Simplify tests by not sending feedback unless specifically configured.
559     SetFeedback(NULL);
560     EXPECT_CALL(
561         *send_algorithm_, TimeUntilSend(_, _, _, _)).WillRepeatedly(Return(
562             QuicTime::Delta::Zero()));
563     EXPECT_CALL(*receive_algorithm_,
564                 RecordIncomingPacket(_, _, _)).Times(AnyNumber());
565     EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
566         .Times(AnyNumber());
567     EXPECT_CALL(*send_algorithm_, RetransmissionDelay()).WillRepeatedly(
568         Return(QuicTime::Delta::Zero()));
569     EXPECT_CALL(*send_algorithm_, BandwidthEstimate()).WillRepeatedly(Return(
570         QuicBandwidth::FromKBitsPerSecond(100)));
571     ON_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
572         .WillByDefault(Return(true));
573     EXPECT_CALL(visitor_, HasPendingWrites()).Times(AnyNumber());
574     EXPECT_CALL(visitor_, HasPendingHandshake()).Times(AnyNumber());
575     EXPECT_CALL(visitor_, OnCanWrite()).Times(AnyNumber());
576
577     EXPECT_CALL(*loss_algorithm_, GetLossTimeout())
578         .WillRepeatedly(Return(QuicTime::Zero()));
579     EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
580         .WillRepeatedly(Return(SequenceNumberSet()));
581   }
582
583   QuicVersion version() {
584     return GetParam();
585   }
586
587   QuicAckFrame* outgoing_ack() {
588     outgoing_ack_.reset(QuicConnectionPeer::CreateAckFrame(&connection_));
589     return outgoing_ack_.get();
590   }
591
592   QuicPacketSequenceNumber least_unacked() {
593     if (version() <= QUIC_VERSION_15) {
594       QuicAckFrame* ack = last_ack();
595       if (ack == NULL) {
596         return 0;
597       }
598       return ack->sent_info.least_unacked;
599     }
600     QuicStopWaitingFrame* stop_waiting = last_stop_waiting();
601     if (stop_waiting == NULL) {
602       return 0;
603     }
604     return stop_waiting->least_unacked;
605   }
606
607   QuicAckFrame* last_ack() {
608     return writer_->ack();
609   }
610
611   QuicCongestionFeedbackFrame* last_feedback() {
612     return writer_->feedback();
613   }
614
615   QuicStopWaitingFrame* last_stop_waiting() {
616     return writer_->stop_waiting();
617   }
618
619   QuicConnectionCloseFrame* last_close() {
620     return writer_->close();
621   }
622
623   QuicPacketHeader* last_header() {
624     return writer_->header();
625   }
626
627   size_t last_sent_packet_size() {
628     return writer_->last_packet_size();
629   }
630
631   uint32 final_bytes_of_last_packet() {
632     return writer_->final_bytes_of_last_packet();
633   }
634
635   uint32 final_bytes_of_previous_packet() {
636     return writer_->final_bytes_of_previous_packet();
637   }
638
639   void use_tagging_decrypter() {
640     writer_->use_tagging_decrypter();
641   }
642
643   void ProcessPacket(QuicPacketSequenceNumber number) {
644     EXPECT_CALL(visitor_, OnStreamFrames(_)).WillOnce(Return(accept_packet_));
645     ProcessDataPacket(number, 0, !kEntropyFlag);
646   }
647
648   QuicPacketEntropyHash ProcessFramePacket(QuicFrame frame) {
649     QuicFrames frames;
650     frames.push_back(QuicFrame(frame));
651     QuicPacketCreatorPeer::SetSendVersionInPacket(&creator_,
652                                                   connection_.is_server());
653     SerializedPacket serialized_packet = creator_.SerializeAllFrames(frames);
654     scoped_ptr<QuicPacket> packet(serialized_packet.packet);
655     scoped_ptr<QuicEncryptedPacket> encrypted(
656         framer_.EncryptPacket(ENCRYPTION_NONE,
657                               serialized_packet.sequence_number, *packet));
658     connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
659     return serialized_packet.entropy_hash;
660   }
661
662   size_t ProcessDataPacket(QuicPacketSequenceNumber number,
663                            QuicFecGroupNumber fec_group,
664                            bool entropy_flag) {
665     return ProcessDataPacketAtLevel(number, fec_group, entropy_flag,
666                                     ENCRYPTION_NONE);
667   }
668
669   size_t ProcessDataPacketAtLevel(QuicPacketSequenceNumber number,
670                                   QuicFecGroupNumber fec_group,
671                                   bool entropy_flag,
672                                   EncryptionLevel level) {
673     scoped_ptr<QuicPacket> packet(ConstructDataPacket(number, fec_group,
674                                                       entropy_flag));
675     scoped_ptr<QuicEncryptedPacket> encrypted(framer_.EncryptPacket(
676         level, number, *packet));
677     connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
678     return encrypted->length();
679   }
680
681   void ProcessClosePacket(QuicPacketSequenceNumber number,
682                           QuicFecGroupNumber fec_group) {
683     scoped_ptr<QuicPacket> packet(ConstructClosePacket(number, fec_group));
684     scoped_ptr<QuicEncryptedPacket> encrypted(framer_.EncryptPacket(
685         ENCRYPTION_NONE, number, *packet));
686     connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
687   }
688
689   size_t ProcessFecProtectedPacket(QuicPacketSequenceNumber number,
690                                    bool expect_revival, bool entropy_flag) {
691     if (expect_revival) {
692       EXPECT_CALL(visitor_, OnStreamFrames(_)).WillOnce(Return(accept_packet_));
693     }
694     EXPECT_CALL(visitor_, OnStreamFrames(_)).WillOnce(Return(accept_packet_))
695         .RetiresOnSaturation();
696     return ProcessDataPacket(number, 1, entropy_flag);
697   }
698
699   // Processes an FEC packet that covers the packets that would have been
700   // received.
701   size_t ProcessFecPacket(QuicPacketSequenceNumber number,
702                           QuicPacketSequenceNumber min_protected_packet,
703                           bool expect_revival,
704                           bool entropy_flag,
705                           QuicPacket* packet) {
706     if (expect_revival) {
707       EXPECT_CALL(visitor_, OnStreamFrames(_)).WillOnce(Return(accept_packet_));
708     }
709
710     // Construct the decrypted data packet so we can compute the correct
711     // redundancy. If |packet| has been provided then use that, otherwise
712     // construct a default data packet.
713     scoped_ptr<QuicPacket> data_packet;
714     if (packet) {
715       data_packet.reset(packet);
716     } else {
717       data_packet.reset(ConstructDataPacket(number, 1, !kEntropyFlag));
718     }
719
720     header_.public_header.connection_id = connection_id_;
721     header_.public_header.reset_flag = false;
722     header_.public_header.version_flag = false;
723     header_.entropy_flag = entropy_flag;
724     header_.fec_flag = true;
725     header_.packet_sequence_number = number;
726     header_.is_in_fec_group = IN_FEC_GROUP;
727     header_.fec_group = min_protected_packet;
728     QuicFecData fec_data;
729     fec_data.fec_group = header_.fec_group;
730
731     // Since all data packets in this test have the same payload, the
732     // redundancy is either equal to that payload or the xor of that payload
733     // with itself, depending on the number of packets.
734     if (((number - min_protected_packet) % 2) == 0) {
735       for (size_t i = GetStartOfFecProtectedData(
736                header_.public_header.connection_id_length,
737                header_.public_header.version_flag,
738                header_.public_header.sequence_number_length);
739            i < data_packet->length(); ++i) {
740         data_packet->mutable_data()[i] ^= data_packet->data()[i];
741       }
742     }
743     fec_data.redundancy = data_packet->FecProtectedData();
744
745     scoped_ptr<QuicPacket> fec_packet(
746         framer_.BuildFecPacket(header_, fec_data).packet);
747     scoped_ptr<QuicEncryptedPacket> encrypted(
748         framer_.EncryptPacket(ENCRYPTION_NONE, number, *fec_packet));
749
750     connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
751     return encrypted->length();
752   }
753
754   QuicByteCount SendStreamDataToPeer(QuicStreamId id,
755                                      StringPiece data,
756                                      QuicStreamOffset offset,
757                                      bool fin,
758                                      QuicPacketSequenceNumber* last_packet) {
759     QuicByteCount packet_size;
760     EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
761         .WillOnce(DoAll(SaveArg<2>(&packet_size), Return(true)));
762     connection_.SendStreamDataWithString(id, data, offset, fin, NULL);
763     if (last_packet != NULL) {
764       *last_packet =
765           QuicConnectionPeer::GetPacketCreator(&connection_)->sequence_number();
766     }
767     EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
768         .Times(AnyNumber());
769     return packet_size;
770   }
771
772   void SendAckPacketToPeer() {
773     EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
774     connection_.SendAck();
775     EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
776         .Times(AnyNumber());
777   }
778
779   QuicPacketEntropyHash ProcessAckPacket(QuicAckFrame* frame) {
780     return ProcessFramePacket(QuicFrame(frame));
781   }
782
783   QuicPacketEntropyHash ProcessStopWaitingPacket(QuicStopWaitingFrame* frame) {
784     return ProcessFramePacket(QuicFrame(frame));
785   }
786
787   QuicPacketEntropyHash ProcessGoAwayPacket(QuicGoAwayFrame* frame) {
788     return ProcessFramePacket(QuicFrame(frame));
789   }
790
791   bool IsMissing(QuicPacketSequenceNumber number) {
792     return IsAwaitingPacket(outgoing_ack()->received_info, number);
793   }
794
795   QuicPacket* ConstructDataPacket(QuicPacketSequenceNumber number,
796                                   QuicFecGroupNumber fec_group,
797                                   bool entropy_flag) {
798     header_.public_header.connection_id = connection_id_;
799     header_.public_header.reset_flag = false;
800     header_.public_header.version_flag = false;
801     header_.entropy_flag = entropy_flag;
802     header_.fec_flag = false;
803     header_.packet_sequence_number = number;
804     header_.is_in_fec_group = fec_group == 0u ? NOT_IN_FEC_GROUP : IN_FEC_GROUP;
805     header_.fec_group = fec_group;
806
807     QuicFrames frames;
808     QuicFrame frame(&frame1_);
809     frames.push_back(frame);
810     QuicPacket* packet =
811         framer_.BuildUnsizedDataPacket(header_, frames).packet;
812     EXPECT_TRUE(packet != NULL);
813     return packet;
814   }
815
816   QuicPacket* ConstructClosePacket(QuicPacketSequenceNumber number,
817                                    QuicFecGroupNumber fec_group) {
818     header_.public_header.connection_id = connection_id_;
819     header_.packet_sequence_number = number;
820     header_.public_header.reset_flag = false;
821     header_.public_header.version_flag = false;
822     header_.entropy_flag = false;
823     header_.fec_flag = false;
824     header_.is_in_fec_group = fec_group == 0u ? NOT_IN_FEC_GROUP : IN_FEC_GROUP;
825     header_.fec_group = fec_group;
826
827     QuicConnectionCloseFrame qccf;
828     qccf.error_code = QUIC_PEER_GOING_AWAY;
829
830     QuicFrames frames;
831     QuicFrame frame(&qccf);
832     frames.push_back(frame);
833     QuicPacket* packet =
834         framer_.BuildUnsizedDataPacket(header_, frames).packet;
835     EXPECT_TRUE(packet != NULL);
836     return packet;
837   }
838
839   void SetFeedback(QuicCongestionFeedbackFrame* feedback) {
840     receive_algorithm_ = new TestReceiveAlgorithm(feedback);
841     connection_.SetReceiveAlgorithm(receive_algorithm_);
842   }
843
844   QuicTime::Delta DefaultRetransmissionTime() {
845     return QuicTime::Delta::FromMilliseconds(kDefaultRetransmissionTimeMs);
846   }
847
848   QuicTime::Delta DefaultDelayedAckTime() {
849     return QuicTime::Delta::FromMilliseconds(kMinRetransmissionTimeMs/2);
850   }
851
852   // Initialize a frame acknowledging all packets up to largest_observed.
853   const QuicAckFrame InitAckFrame(QuicPacketSequenceNumber largest_observed,
854                                   QuicPacketSequenceNumber least_unacked) {
855     QuicAckFrame frame(largest_observed, QuicTime::Zero(), least_unacked);
856     if (largest_observed > 0) {
857       frame.received_info.entropy_hash =
858         QuicConnectionPeer::GetSentEntropyHash(&connection_, largest_observed);
859     }
860     return frame;
861   }
862
863   const QuicStopWaitingFrame InitStopWaitingFrame(
864       QuicPacketSequenceNumber least_unacked) {
865     QuicStopWaitingFrame frame;
866     frame.least_unacked = least_unacked;
867     return frame;
868   }
869   // Explicitly nack a packet.
870   void NackPacket(QuicPacketSequenceNumber missing, QuicAckFrame* frame) {
871     frame->received_info.missing_packets.insert(missing);
872     frame->received_info.entropy_hash ^=
873       QuicConnectionPeer::GetSentEntropyHash(&connection_, missing);
874     if (missing > 1) {
875       frame->received_info.entropy_hash ^=
876         QuicConnectionPeer::GetSentEntropyHash(&connection_, missing - 1);
877     }
878   }
879
880   // Undo nacking a packet within the frame.
881   void AckPacket(QuicPacketSequenceNumber arrived, QuicAckFrame* frame) {
882     EXPECT_THAT(frame->received_info.missing_packets, Contains(arrived));
883     frame->received_info.missing_packets.erase(arrived);
884     frame->received_info.entropy_hash ^=
885       QuicConnectionPeer::GetSentEntropyHash(&connection_, arrived);
886     if (arrived > 1) {
887       frame->received_info.entropy_hash ^=
888         QuicConnectionPeer::GetSentEntropyHash(&connection_, arrived - 1);
889     }
890   }
891
892   void TriggerConnectionClose() {
893     // Send an erroneous packet to close the connection.
894     EXPECT_CALL(visitor_,
895                 OnConnectionClosed(QUIC_INVALID_PACKET_HEADER, false));
896     // Call ProcessDataPacket rather than ProcessPacket, as we should not get a
897     // packet call to the visitor.
898     ProcessDataPacket(6000, 0, !kEntropyFlag);
899     EXPECT_FALSE(
900         QuicConnectionPeer::GetConnectionClosePacket(&connection_) == NULL);
901   }
902
903   void BlockOnNextWrite() {
904     writer_->BlockOnNextWrite();
905     EXPECT_CALL(visitor_, OnWriteBlocked()).Times(AtLeast(1));
906   }
907
908   QuicConnectionId connection_id_;
909   QuicFramer framer_;
910   QuicPacketCreator creator_;
911   MockEntropyCalculator entropy_calculator_;
912
913   MockSendAlgorithm* send_algorithm_;
914   MockLossAlgorithm* loss_algorithm_;
915   TestReceiveAlgorithm* receive_algorithm_;
916   MockClock clock_;
917   MockRandom random_generator_;
918   scoped_ptr<TestConnectionHelper> helper_;
919   scoped_ptr<TestPacketWriter> writer_;
920   TestConnection connection_;
921   StrictMock<MockConnectionVisitor> visitor_;
922
923   QuicPacketHeader header_;
924   QuicStreamFrame frame1_;
925   QuicStreamFrame frame2_;
926   scoped_ptr<QuicAckFrame> outgoing_ack_;
927   bool accept_packet_;
928
929  private:
930   DISALLOW_COPY_AND_ASSIGN(QuicConnectionTest);
931 };
932
933 // Run all end to end tests with all supported versions.
934 INSTANTIATE_TEST_CASE_P(SupportedVersion,
935                         QuicConnectionTest,
936                         ::testing::ValuesIn(QuicSupportedVersions()));
937
938 TEST_P(QuicConnectionTest, PacketsInOrder) {
939   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
940
941   ProcessPacket(1);
942   EXPECT_EQ(1u, outgoing_ack()->received_info.largest_observed);
943   EXPECT_EQ(0u, outgoing_ack()->received_info.missing_packets.size());
944
945   ProcessPacket(2);
946   EXPECT_EQ(2u, outgoing_ack()->received_info.largest_observed);
947   EXPECT_EQ(0u, outgoing_ack()->received_info.missing_packets.size());
948
949   ProcessPacket(3);
950   EXPECT_EQ(3u, outgoing_ack()->received_info.largest_observed);
951   EXPECT_EQ(0u, outgoing_ack()->received_info.missing_packets.size());
952 }
953
954 TEST_P(QuicConnectionTest, PacketsRejected) {
955   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
956
957   ProcessPacket(1);
958   EXPECT_EQ(1u, outgoing_ack()->received_info.largest_observed);
959   EXPECT_EQ(0u, outgoing_ack()->received_info.missing_packets.size());
960
961   accept_packet_ = false;
962   ProcessPacket(2);
963   // We should not have an ack for two.
964   EXPECT_EQ(1u, outgoing_ack()->received_info.largest_observed);
965   EXPECT_EQ(0u, outgoing_ack()->received_info.missing_packets.size());
966 }
967
968 TEST_P(QuicConnectionTest, PacketsOutOfOrder) {
969   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
970
971   ProcessPacket(3);
972   EXPECT_EQ(3u, outgoing_ack()->received_info.largest_observed);
973   EXPECT_TRUE(IsMissing(2));
974   EXPECT_TRUE(IsMissing(1));
975
976   ProcessPacket(2);
977   EXPECT_EQ(3u, outgoing_ack()->received_info.largest_observed);
978   EXPECT_FALSE(IsMissing(2));
979   EXPECT_TRUE(IsMissing(1));
980
981   ProcessPacket(1);
982   EXPECT_EQ(3u, outgoing_ack()->received_info.largest_observed);
983   EXPECT_FALSE(IsMissing(2));
984   EXPECT_FALSE(IsMissing(1));
985 }
986
987 TEST_P(QuicConnectionTest, DuplicatePacket) {
988   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
989
990   ProcessPacket(3);
991   EXPECT_EQ(3u, outgoing_ack()->received_info.largest_observed);
992   EXPECT_TRUE(IsMissing(2));
993   EXPECT_TRUE(IsMissing(1));
994
995   // Send packet 3 again, but do not set the expectation that
996   // the visitor OnStreamFrames() will be called.
997   ProcessDataPacket(3, 0, !kEntropyFlag);
998   EXPECT_EQ(3u, outgoing_ack()->received_info.largest_observed);
999   EXPECT_TRUE(IsMissing(2));
1000   EXPECT_TRUE(IsMissing(1));
1001 }
1002
1003 TEST_P(QuicConnectionTest, PacketsOutOfOrderWithAdditionsAndLeastAwaiting) {
1004   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1005
1006   ProcessPacket(3);
1007   EXPECT_EQ(3u, outgoing_ack()->received_info.largest_observed);
1008   EXPECT_TRUE(IsMissing(2));
1009   EXPECT_TRUE(IsMissing(1));
1010
1011   ProcessPacket(2);
1012   EXPECT_EQ(3u, outgoing_ack()->received_info.largest_observed);
1013   EXPECT_TRUE(IsMissing(1));
1014
1015   ProcessPacket(5);
1016   EXPECT_EQ(5u, outgoing_ack()->received_info.largest_observed);
1017   EXPECT_TRUE(IsMissing(1));
1018   EXPECT_TRUE(IsMissing(4));
1019
1020   // Pretend at this point the client has gotten acks for 2 and 3 and 1 is a
1021   // packet the peer will not retransmit.  It indicates this by sending 'least
1022   // awaiting' is 4.  The connection should then realize 1 will not be
1023   // retransmitted, and will remove it from the missing list.
1024   creator_.set_sequence_number(5);
1025   QuicAckFrame frame = InitAckFrame(0, 4);
1026   ProcessAckPacket(&frame);
1027
1028   // Force an ack to be sent.
1029   SendAckPacketToPeer();
1030   EXPECT_TRUE(IsMissing(4));
1031 }
1032
1033 TEST_P(QuicConnectionTest, RejectPacketTooFarOut) {
1034   EXPECT_CALL(visitor_,
1035               OnConnectionClosed(QUIC_INVALID_PACKET_HEADER, false));
1036   // Call ProcessDataPacket rather than ProcessPacket, as we should not get a
1037   // packet call to the visitor.
1038   ProcessDataPacket(6000, 0, !kEntropyFlag);
1039   EXPECT_FALSE(
1040       QuicConnectionPeer::GetConnectionClosePacket(&connection_) == NULL);
1041 }
1042
1043 TEST_P(QuicConnectionTest, TruncatedAck) {
1044   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1045   QuicPacketSequenceNumber num_packets = 256 * 2 + 1;
1046   for (QuicPacketSequenceNumber i = 0; i < num_packets; ++i) {
1047     SendStreamDataToPeer(3, "foo", i * 3, !kFin, NULL);
1048   }
1049
1050   QuicAckFrame frame = InitAckFrame(num_packets, 1);
1051   SequenceNumberSet lost_packets;
1052   // Create an ack with 256 nacks, none adjacent to one another.
1053   for (QuicPacketSequenceNumber i = 1; i <= 256; ++i) {
1054     NackPacket(i * 2, &frame);
1055     if (i < 256) {  // Last packet is nacked, but not lost.
1056       lost_packets.insert(i * 2);
1057     }
1058   }
1059   EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1060       .WillOnce(Return(lost_packets));
1061   EXPECT_CALL(entropy_calculator_,
1062               EntropyHash(511)).WillOnce(testing::Return(0));
1063   EXPECT_CALL(*send_algorithm_, UpdateRtt(_));
1064   EXPECT_CALL(*send_algorithm_, OnPacketAcked(_, _)).Times(256);
1065   EXPECT_CALL(*send_algorithm_, OnPacketLost(_, _)).Times(255);
1066   EXPECT_CALL(*send_algorithm_, OnPacketAbandoned(_, _)).Times(255);
1067   ProcessAckPacket(&frame);
1068
1069   QuicReceivedPacketManager* received_packet_manager =
1070       QuicConnectionPeer::GetReceivedPacketManager(&connection_);
1071   // A truncated ack will not have the true largest observed.
1072   EXPECT_GT(num_packets,
1073             received_packet_manager->peer_largest_observed_packet());
1074
1075   AckPacket(192, &frame);
1076
1077   // Removing one missing packet allows us to ack 192 and one more range, but
1078   // 192 has already been declared lost, so it doesn't register as an ack.
1079   EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1080       .WillOnce(Return(SequenceNumberSet()));
1081   EXPECT_CALL(*send_algorithm_, UpdateRtt(_));
1082   EXPECT_CALL(*send_algorithm_, OnPacketAcked(_, _)).Times(1);
1083   ProcessAckPacket(&frame);
1084   EXPECT_EQ(num_packets,
1085             received_packet_manager->peer_largest_observed_packet());
1086 }
1087
1088 TEST_P(QuicConnectionTest, AckReceiptCausesAckSendBadEntropy) {
1089   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1090
1091   ProcessPacket(1);
1092   // Delay sending, then queue up an ack.
1093   EXPECT_CALL(*send_algorithm_,
1094               TimeUntilSend(_, NOT_RETRANSMISSION, _, _)).WillOnce(
1095                   testing::Return(QuicTime::Delta::FromMicroseconds(1)));
1096   QuicConnectionPeer::SendAck(&connection_);
1097
1098   // Process an ack with a least unacked of the received ack.
1099   // This causes an ack to be sent when TimeUntilSend returns 0.
1100   EXPECT_CALL(*send_algorithm_,
1101               TimeUntilSend(_, NOT_RETRANSMISSION, _, _)).WillRepeatedly(
1102                   testing::Return(QuicTime::Delta::Zero()));
1103   // Skip a packet and then record an ack.
1104   creator_.set_sequence_number(2);
1105   QuicAckFrame frame = InitAckFrame(0, 3);
1106   ProcessAckPacket(&frame);
1107 }
1108
1109 TEST_P(QuicConnectionTest, OutOfOrderReceiptCausesAckSend) {
1110   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1111
1112   ProcessPacket(3);
1113   // Should ack immediately since we have missing packets.
1114   EXPECT_EQ(1u, writer_->packets_write_attempts());
1115
1116   ProcessPacket(2);
1117   // Should ack immediately since we have missing packets.
1118   EXPECT_EQ(2u, writer_->packets_write_attempts());
1119
1120   ProcessPacket(1);
1121   // Should ack immediately, since this fills the last hole.
1122   EXPECT_EQ(3u, writer_->packets_write_attempts());
1123
1124   ProcessPacket(4);
1125   // Should not cause an ack.
1126   EXPECT_EQ(3u, writer_->packets_write_attempts());
1127 }
1128
1129 TEST_P(QuicConnectionTest, AckReceiptCausesAckSend) {
1130   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1131
1132   QuicPacketSequenceNumber original;
1133   QuicByteCount packet_size;
1134   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, NOT_RETRANSMISSION, _))
1135       .WillOnce(DoAll(SaveArg<1>(&original), SaveArg<2>(&packet_size),
1136                       Return(true)));
1137   connection_.SendStreamDataWithString(3, "foo", 0, !kFin, NULL);
1138   QuicAckFrame frame = InitAckFrame(original, 1);
1139   NackPacket(original, &frame);
1140   // First nack triggers early retransmit.
1141   SequenceNumberSet lost_packets;
1142   lost_packets.insert(1);
1143   EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1144       .WillOnce(Return(lost_packets));
1145   EXPECT_CALL(*send_algorithm_, UpdateRtt(_));
1146   EXPECT_CALL(*send_algorithm_, OnPacketLost(1, _)).Times(1);
1147   EXPECT_CALL(*send_algorithm_, OnPacketAbandoned(1, _)).Times(1);
1148   QuicPacketSequenceNumber retransmission;
1149   EXPECT_CALL(*send_algorithm_,
1150               OnPacketSent(_, _, packet_size - kQuicVersionSize,
1151                            LOSS_RETRANSMISSION, _))
1152       .WillOnce(DoAll(SaveArg<1>(&retransmission), Return(true)));
1153
1154   ProcessAckPacket(&frame);
1155
1156   QuicAckFrame frame2 = InitAckFrame(retransmission, 1);
1157   NackPacket(original, &frame2);
1158   EXPECT_CALL(*send_algorithm_, UpdateRtt(_));
1159   EXPECT_CALL(*send_algorithm_, OnPacketAcked(_, _));
1160   EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1161       .WillOnce(Return(SequenceNumberSet()));
1162   ProcessAckPacket(&frame2);
1163
1164   // Now if the peer sends an ack which still reports the retransmitted packet
1165   // as missing, that will bundle an ack with data after two acks in a row
1166   // indicate the high water mark needs to be raised.
1167   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, NOT_RETRANSMISSION,
1168                                              HAS_RETRANSMITTABLE_DATA));
1169   connection_.SendStreamDataWithString(3, "foo", 3, !kFin, NULL);
1170   // No ack sent.
1171   EXPECT_EQ(1u, writer_->frame_count());
1172   EXPECT_EQ(1u, writer_->stream_frames()->size());
1173   writer_->Reset();
1174
1175   // No more packet loss for the rest of the test.
1176   EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1177       .WillRepeatedly(Return(SequenceNumberSet()));
1178   ProcessAckPacket(&frame2);
1179   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, NOT_RETRANSMISSION,
1180                                              HAS_RETRANSMITTABLE_DATA));
1181   connection_.SendStreamDataWithString(3, "foo", 3, !kFin, NULL);
1182   // Ack bundled.
1183   if (version() > QUIC_VERSION_15) {
1184     EXPECT_EQ(3u, writer_->frame_count());
1185   } else {
1186     EXPECT_EQ(2u, writer_->frame_count());
1187   }
1188   EXPECT_EQ(1u, writer_->stream_frames()->size());
1189   EXPECT_TRUE(writer_->ack());
1190
1191   // But an ack with no missing packets will not send an ack.
1192   AckPacket(original, &frame2);
1193   ProcessAckPacket(&frame2);
1194   ProcessAckPacket(&frame2);
1195 }
1196
1197 TEST_P(QuicConnectionTest, LeastUnackedLower) {
1198   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1199
1200   SendStreamDataToPeer(1, "foo", 0, !kFin, NULL);
1201   SendStreamDataToPeer(1, "bar", 3, !kFin, NULL);
1202   SendStreamDataToPeer(1, "eep", 6, !kFin, NULL);
1203
1204   // Start out saying the least unacked is 2.
1205   creator_.set_sequence_number(5);
1206   if (version() > QUIC_VERSION_15) {
1207     QuicStopWaitingFrame frame = InitStopWaitingFrame(2);
1208     ProcessStopWaitingPacket(&frame);
1209   } else {
1210     QuicAckFrame frame = InitAckFrame(0, 2);
1211     ProcessAckPacket(&frame);
1212   }
1213
1214   // Change it to 1, but lower the sequence number to fake out-of-order packets.
1215   // This should be fine.
1216   creator_.set_sequence_number(1);
1217   // The scheduler will not process out of order acks, but all packet processing
1218   // causes the connection to try to write.
1219   EXPECT_CALL(visitor_, OnCanWrite());
1220   if (version() > QUIC_VERSION_15) {
1221     QuicStopWaitingFrame frame2 = InitStopWaitingFrame(1);
1222     ProcessStopWaitingPacket(&frame2);
1223   } else {
1224     QuicAckFrame frame2 = InitAckFrame(0, 1);
1225     ProcessAckPacket(&frame2);
1226   }
1227
1228   // Now claim it's one, but set the ordering so it was sent "after" the first
1229   // one.  This should cause a connection error.
1230   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
1231   creator_.set_sequence_number(7);
1232   if (version() > QUIC_VERSION_15) {
1233     EXPECT_CALL(visitor_,
1234                 OnConnectionClosed(QUIC_INVALID_STOP_WAITING_DATA, false));
1235     QuicStopWaitingFrame frame2 = InitStopWaitingFrame(1);
1236     ProcessStopWaitingPacket(&frame2);
1237   } else {
1238     EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_INVALID_ACK_DATA, false));
1239     QuicAckFrame frame2 = InitAckFrame(0, 1);
1240     ProcessAckPacket(&frame2);
1241   }
1242 }
1243
1244 TEST_P(QuicConnectionTest, LargestObservedLower) {
1245   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1246
1247   SendStreamDataToPeer(1, "foo", 0, !kFin, NULL);
1248   SendStreamDataToPeer(1, "bar", 3, !kFin, NULL);
1249   SendStreamDataToPeer(1, "eep", 6, !kFin, NULL);
1250   EXPECT_CALL(*send_algorithm_, UpdateRtt(_));
1251   EXPECT_CALL(*send_algorithm_, OnPacketAcked(_, _)).Times(2);
1252
1253   // Start out saying the largest observed is 2.
1254   QuicAckFrame frame1 = InitAckFrame(1, 0);
1255   QuicAckFrame frame2 = InitAckFrame(2, 0);
1256   ProcessAckPacket(&frame2);
1257
1258   // Now change it to 1, and it should cause a connection error.
1259   EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_INVALID_ACK_DATA, false));
1260   EXPECT_CALL(visitor_, OnCanWrite()).Times(0);
1261   ProcessAckPacket(&frame1);
1262 }
1263
1264 TEST_P(QuicConnectionTest, AckUnsentData) {
1265   // Ack a packet which has not been sent.
1266   EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_INVALID_ACK_DATA, false));
1267   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1268   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
1269   QuicAckFrame frame(1, QuicTime::Zero(), 0);
1270   EXPECT_CALL(visitor_, OnCanWrite()).Times(0);
1271   ProcessAckPacket(&frame);
1272 }
1273
1274 TEST_P(QuicConnectionTest, AckAll) {
1275   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1276   ProcessPacket(1);
1277
1278   creator_.set_sequence_number(1);
1279   QuicAckFrame frame1 = InitAckFrame(0, 1);
1280   ProcessAckPacket(&frame1);
1281 }
1282
1283 TEST_P(QuicConnectionTest, SendingDifferentSequenceNumberLengthsBandwidth) {
1284   EXPECT_CALL(*send_algorithm_, BandwidthEstimate()).WillOnce(Return(
1285        QuicBandwidth::FromKBitsPerSecond(1000)));
1286
1287   QuicPacketSequenceNumber last_packet;
1288   SendStreamDataToPeer(1, "foo", 0, !kFin, &last_packet);
1289   EXPECT_EQ(1u, last_packet);
1290   EXPECT_EQ(PACKET_1BYTE_SEQUENCE_NUMBER,
1291             connection_.options()->send_sequence_number_length);
1292   EXPECT_EQ(PACKET_1BYTE_SEQUENCE_NUMBER,
1293             last_header()->public_header.sequence_number_length);
1294
1295   EXPECT_CALL(*send_algorithm_, BandwidthEstimate()).WillOnce(Return(
1296        QuicBandwidth::FromKBitsPerSecond(1000 * 256)));
1297
1298   SendStreamDataToPeer(1, "bar", 3, !kFin, &last_packet);
1299   EXPECT_EQ(2u, last_packet);
1300   EXPECT_EQ(PACKET_2BYTE_SEQUENCE_NUMBER,
1301             connection_.options()->send_sequence_number_length);
1302   // The 1 packet lag is due to the sequence number length being recalculated in
1303   // QuicConnection after a packet is sent.
1304   EXPECT_EQ(PACKET_1BYTE_SEQUENCE_NUMBER,
1305             last_header()->public_header.sequence_number_length);
1306
1307   EXPECT_CALL(*send_algorithm_, BandwidthEstimate()).WillOnce(Return(
1308        QuicBandwidth::FromKBitsPerSecond(1000 * 256 * 256)));
1309
1310   SendStreamDataToPeer(1, "foo", 6, !kFin, &last_packet);
1311   EXPECT_EQ(3u, last_packet);
1312   EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1313             connection_.options()->send_sequence_number_length);
1314   EXPECT_EQ(PACKET_2BYTE_SEQUENCE_NUMBER,
1315             last_header()->public_header.sequence_number_length);
1316
1317   EXPECT_CALL(*send_algorithm_, BandwidthEstimate()).WillOnce(Return(
1318        QuicBandwidth::FromKBitsPerSecond(1000ll * 256 * 256 * 256)));
1319
1320   SendStreamDataToPeer(1, "bar", 9, !kFin, &last_packet);
1321   EXPECT_EQ(4u, last_packet);
1322   EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1323             connection_.options()->send_sequence_number_length);
1324   EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1325             last_header()->public_header.sequence_number_length);
1326
1327   EXPECT_CALL(*send_algorithm_, BandwidthEstimate()).WillOnce(Return(
1328       QuicBandwidth::FromKBitsPerSecond(1000ll * 256 * 256 * 256 * 256)));
1329
1330   SendStreamDataToPeer(1, "foo", 12, !kFin, &last_packet);
1331   EXPECT_EQ(5u, last_packet);
1332   EXPECT_EQ(PACKET_6BYTE_SEQUENCE_NUMBER,
1333             connection_.options()->send_sequence_number_length);
1334   EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1335             last_header()->public_header.sequence_number_length);
1336 }
1337
1338 TEST_P(QuicConnectionTest, SendingDifferentSequenceNumberLengthsUnackedDelta) {
1339   QuicPacketSequenceNumber last_packet;
1340   SendStreamDataToPeer(1, "foo", 0, !kFin, &last_packet);
1341   EXPECT_EQ(1u, last_packet);
1342   EXPECT_EQ(PACKET_1BYTE_SEQUENCE_NUMBER,
1343             connection_.options()->send_sequence_number_length);
1344   EXPECT_EQ(PACKET_1BYTE_SEQUENCE_NUMBER,
1345             last_header()->public_header.sequence_number_length);
1346
1347   QuicConnectionPeer::GetPacketCreator(&connection_)->set_sequence_number(100);
1348
1349   SendStreamDataToPeer(1, "bar", 3, !kFin, &last_packet);
1350   EXPECT_EQ(PACKET_2BYTE_SEQUENCE_NUMBER,
1351             connection_.options()->send_sequence_number_length);
1352   EXPECT_EQ(PACKET_1BYTE_SEQUENCE_NUMBER,
1353             last_header()->public_header.sequence_number_length);
1354
1355   QuicConnectionPeer::GetPacketCreator(&connection_)->set_sequence_number(
1356       100 * 256);
1357
1358   SendStreamDataToPeer(1, "foo", 6, !kFin, &last_packet);
1359   EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1360             connection_.options()->send_sequence_number_length);
1361   EXPECT_EQ(PACKET_2BYTE_SEQUENCE_NUMBER,
1362             last_header()->public_header.sequence_number_length);
1363
1364   QuicConnectionPeer::GetPacketCreator(&connection_)->set_sequence_number(
1365       100 * 256 * 256);
1366
1367   SendStreamDataToPeer(1, "bar", 9, !kFin, &last_packet);
1368   EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1369             connection_.options()->send_sequence_number_length);
1370   EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1371             last_header()->public_header.sequence_number_length);
1372
1373   QuicConnectionPeer::GetPacketCreator(&connection_)->set_sequence_number(
1374       100 * 256 * 256 * 256);
1375
1376   SendStreamDataToPeer(1, "foo", 12, !kFin, &last_packet);
1377   EXPECT_EQ(PACKET_6BYTE_SEQUENCE_NUMBER,
1378             connection_.options()->send_sequence_number_length);
1379   EXPECT_EQ(PACKET_4BYTE_SEQUENCE_NUMBER,
1380             last_header()->public_header.sequence_number_length);
1381 }
1382
1383 TEST_P(QuicConnectionTest, BasicSending) {
1384   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1385   QuicPacketSequenceNumber last_packet;
1386   SendStreamDataToPeer(1, "foo", 0, !kFin, &last_packet);  // Packet 1
1387   EXPECT_EQ(1u, last_packet);
1388   SendAckPacketToPeer();  // Packet 2
1389
1390   EXPECT_EQ(1u, least_unacked());
1391
1392   SendAckPacketToPeer();  // Packet 3
1393   EXPECT_EQ(1u, least_unacked());
1394
1395   SendStreamDataToPeer(1, "bar", 3, !kFin, &last_packet);  // Packet 4
1396   EXPECT_EQ(4u, last_packet);
1397   SendAckPacketToPeer();  // Packet 5
1398   EXPECT_EQ(1u, least_unacked());
1399
1400   EXPECT_CALL(*send_algorithm_, UpdateRtt(_));
1401   EXPECT_CALL(*send_algorithm_, OnPacketAcked(_, _)).Times(3);
1402
1403   // Peer acks up to packet 3.
1404   QuicAckFrame frame = InitAckFrame(3, 0);
1405   ProcessAckPacket(&frame);
1406   SendAckPacketToPeer();  // Packet 6
1407
1408   // As soon as we've acked one, we skip ack packets 2 and 3 and note lack of
1409   // ack for 4.
1410   EXPECT_EQ(4u, least_unacked());
1411
1412   EXPECT_CALL(*send_algorithm_, UpdateRtt(_));
1413   EXPECT_CALL(*send_algorithm_, OnPacketAcked(_, _)).Times(3);
1414
1415   // Peer acks up to packet 4, the last packet.
1416   QuicAckFrame frame2 = InitAckFrame(6, 0);
1417   ProcessAckPacket(&frame2);  // Acks don't instigate acks.
1418
1419   // Verify that we did not send an ack.
1420   EXPECT_EQ(6u, last_header()->packet_sequence_number);
1421
1422   // So the last ack has not changed.
1423   EXPECT_EQ(4u, least_unacked());
1424
1425   // If we force an ack, we shouldn't change our retransmit state.
1426   SendAckPacketToPeer();  // Packet 7
1427   EXPECT_EQ(7u, least_unacked());
1428
1429   // But if we send more data it should.
1430   SendStreamDataToPeer(1, "eep", 6, !kFin, &last_packet);  // Packet 8
1431   EXPECT_EQ(8u, last_packet);
1432   SendAckPacketToPeer();  // Packet 9
1433   EXPECT_EQ(7u, least_unacked());
1434 }
1435
1436 TEST_P(QuicConnectionTest, FECSending) {
1437   if (version() < QUIC_VERSION_15) {
1438     return;
1439   }
1440   // All packets carry version info till version is negotiated.
1441   size_t payload_length;
1442   connection_.options()->max_packet_length =
1443       GetPacketLengthForOneStream(
1444           connection_.version(), kIncludeVersion, PACKET_1BYTE_SEQUENCE_NUMBER,
1445           IN_FEC_GROUP, &payload_length);
1446   // And send FEC every two packets.
1447   connection_.options()->max_packets_per_fec_group = 2;
1448
1449   // Send 4 data packets and 2 FEC packets.
1450   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(6);
1451   // The first stream frame will consume 2 fewer bytes than the other three.
1452   const string payload(payload_length * 4 - 6, 'a');
1453   connection_.SendStreamDataWithString(1, payload, 0, !kFin, NULL);
1454   // Expect the FEC group to be closed after SendStreamDataWithString.
1455   EXPECT_FALSE(creator_.ShouldSendFec(true));
1456 }
1457
1458 TEST_P(QuicConnectionTest, FECQueueing) {
1459   if (version() < QUIC_VERSION_15) {
1460     return;
1461   }
1462   // All packets carry version info till version is negotiated.
1463   size_t payload_length;
1464   connection_.options()->max_packet_length =
1465       GetPacketLengthForOneStream(
1466           connection_.version(), kIncludeVersion, PACKET_1BYTE_SEQUENCE_NUMBER,
1467           IN_FEC_GROUP, &payload_length);
1468   // And send FEC every two packets.
1469   connection_.options()->max_packets_per_fec_group = 2;
1470
1471   EXPECT_EQ(0u, connection_.NumQueuedPackets());
1472   BlockOnNextWrite();
1473   const string payload(payload_length, 'a');
1474   connection_.SendStreamDataWithString(1, payload, 0, !kFin, NULL);
1475   EXPECT_FALSE(creator_.ShouldSendFec(true));
1476   // Expect the first data packet and the fec packet to be queued.
1477   EXPECT_EQ(2u, connection_.NumQueuedPackets());
1478 }
1479
1480 TEST_P(QuicConnectionTest, AbandonFECFromCongestionWindow) {
1481   if (version() < QUIC_VERSION_15) {
1482     return;
1483   }
1484   connection_.options()->max_packets_per_fec_group = 1;
1485   // 1 Data and 1 FEC packet.
1486   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(2);
1487   connection_.SendStreamDataWithString(3, "foo", 0, !kFin, NULL);
1488
1489   const QuicTime::Delta retransmission_time =
1490       QuicTime::Delta::FromMilliseconds(5000);
1491   clock_.AdvanceTime(retransmission_time);
1492
1493   // Abandon FEC packet and data packet.
1494   EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
1495   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
1496   EXPECT_CALL(visitor_, OnCanWrite());
1497   connection_.OnRetransmissionTimeout();
1498 }
1499
1500 TEST_P(QuicConnectionTest, DontAbandonAckedFEC) {
1501   if (version() < QUIC_VERSION_15) {
1502     return;
1503   }
1504   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1505   connection_.options()->max_packets_per_fec_group = 1;
1506
1507   // 1 Data and 1 FEC packet.
1508   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(6);
1509   connection_.SendStreamDataWithString(3, "foo", 0, !kFin, NULL);
1510   // Send some more data afterwards to ensure early retransmit doesn't trigger.
1511   connection_.SendStreamDataWithString(3, "foo", 3, !kFin, NULL);
1512   connection_.SendStreamDataWithString(3, "foo", 6, !kFin, NULL);
1513
1514   QuicAckFrame ack_fec = InitAckFrame(2, 1);
1515   // Data packet missing.
1516   // TODO(ianswett): Note that this is not a sensible ack, since if the FEC was
1517   // received, it would cause the covered packet to be acked as well.
1518   NackPacket(1, &ack_fec);
1519
1520   EXPECT_CALL(*send_algorithm_, UpdateRtt(_));
1521   EXPECT_CALL(*send_algorithm_, OnPacketAcked(_, _)).Times(1);
1522   ProcessAckPacket(&ack_fec);
1523   clock_.AdvanceTime(DefaultRetransmissionTime());
1524
1525   // Don't abandon the acked FEC packet, but it will abandon 2 the subsequent
1526   // FEC packets.
1527   EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
1528   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(3);
1529   connection_.GetRetransmissionAlarm()->Fire();
1530 }
1531
1532 TEST_P(QuicConnectionTest, AbandonAllFEC) {
1533   if (version() < QUIC_VERSION_15) {
1534     return;
1535   }
1536   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1537   connection_.options()->max_packets_per_fec_group = 1;
1538
1539   // 1 Data and 1 FEC packet.
1540   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(6);
1541   connection_.SendStreamDataWithString(3, "foo", 0, !kFin, NULL);
1542   // Send some more data afterwards to ensure early retransmit doesn't trigger.
1543   connection_.SendStreamDataWithString(3, "foo", 3, !kFin, NULL);
1544   // Advance the time so not all the FEC packets are abandoned.
1545   clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(1));
1546   connection_.SendStreamDataWithString(3, "foo", 6, !kFin, NULL);
1547
1548   QuicAckFrame ack_fec = InitAckFrame(5, 1);
1549   // Ack all data packets, but no fec packets.
1550   NackPacket(2, &ack_fec);
1551   NackPacket(4, &ack_fec);
1552
1553   // Lose the first FEC packet and ack the three data packets.
1554   SequenceNumberSet lost_packets;
1555   lost_packets.insert(2);
1556   EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1557       .WillOnce(Return(lost_packets));
1558   EXPECT_CALL(*send_algorithm_, UpdateRtt(_));
1559   EXPECT_CALL(*send_algorithm_, OnPacketAcked(_, _)).Times(3);
1560   EXPECT_CALL(*send_algorithm_, OnPacketAbandoned(2, _));
1561   EXPECT_CALL(*send_algorithm_, OnPacketLost(2, _));
1562   ProcessAckPacket(&ack_fec);
1563
1564   clock_.AdvanceTime(DefaultRetransmissionTime().Subtract(
1565       QuicTime::Delta::FromMilliseconds(1)));
1566
1567   // Abandon all packets
1568   EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(false));
1569   connection_.GetRetransmissionAlarm()->Fire();
1570
1571   // Ensure the alarm is not set since all packets have been abandoned.
1572   EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
1573 }
1574
1575 TEST_P(QuicConnectionTest, FramePacking) {
1576   // Block the connection.
1577   connection_.GetSendAlarm()->Set(
1578       clock_.ApproximateNow().Add(QuicTime::Delta::FromSeconds(1)));
1579
1580   // Send an ack and two stream frames in 1 packet by queueing them.
1581   connection_.SendAck();
1582   EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll(
1583       IgnoreResult(InvokeWithoutArgs(&connection_,
1584                                      &TestConnection::SendStreamData3)),
1585       IgnoreResult(InvokeWithoutArgs(&connection_,
1586                                      &TestConnection::SendStreamData5))));
1587
1588   EXPECT_CALL(*send_algorithm_,
1589               OnPacketSent(_, _, _, NOT_RETRANSMISSION, _))
1590       .Times(1);
1591   // Unblock the connection.
1592   connection_.GetSendAlarm()->Fire();
1593   EXPECT_EQ(0u, connection_.NumQueuedPackets());
1594   EXPECT_FALSE(connection_.HasQueuedData());
1595
1596   // Parse the last packet and ensure it's an ack and two stream frames from
1597   // two different streams.
1598   if (version() > QUIC_VERSION_15) {
1599     EXPECT_EQ(4u, writer_->frame_count());
1600     EXPECT_TRUE(writer_->stop_waiting());
1601   } else {
1602     EXPECT_EQ(3u, writer_->frame_count());
1603   }
1604   EXPECT_TRUE(writer_->ack());
1605   EXPECT_EQ(2u, writer_->stream_frames()->size());
1606   EXPECT_EQ(kStreamId3, (*writer_->stream_frames())[0].stream_id);
1607   EXPECT_EQ(kStreamId5, (*writer_->stream_frames())[1].stream_id);
1608 }
1609
1610 TEST_P(QuicConnectionTest, FramePackingNonCryptoThenCrypto) {
1611   // Block the connection.
1612   connection_.GetSendAlarm()->Set(
1613       clock_.ApproximateNow().Add(QuicTime::Delta::FromSeconds(1)));
1614
1615   // Send an ack and two stream frames (one non-crypto, then one crypto) in 2
1616   // packets by queueing them.
1617   connection_.SendAck();
1618   EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll(
1619       IgnoreResult(InvokeWithoutArgs(&connection_,
1620                                      &TestConnection::SendStreamData3)),
1621       IgnoreResult(InvokeWithoutArgs(&connection_,
1622                                      &TestConnection::SendCryptoStreamData))));
1623
1624   EXPECT_CALL(*send_algorithm_,
1625               OnPacketSent(_, _, _, NOT_RETRANSMISSION, _))
1626       .Times(2);
1627   // Unblock the connection.
1628   connection_.GetSendAlarm()->Fire();
1629   EXPECT_EQ(0u, connection_.NumQueuedPackets());
1630   EXPECT_FALSE(connection_.HasQueuedData());
1631
1632   // Parse the last packet and ensure it's the crypto stream frame.
1633   EXPECT_EQ(1u, writer_->frame_count());
1634   EXPECT_EQ(1u, writer_->stream_frames()->size());
1635   EXPECT_EQ(kCryptoStreamId, (*writer_->stream_frames())[0].stream_id);
1636 }
1637
1638 TEST_P(QuicConnectionTest, FramePackingCryptoThenNonCrypto) {
1639   // Block the connection.
1640   connection_.GetSendAlarm()->Set(
1641       clock_.ApproximateNow().Add(QuicTime::Delta::FromSeconds(1)));
1642
1643   // Send an ack and two stream frames (one crypto, then one non-crypto) in 3
1644   // packets by queueing them.
1645   connection_.SendAck();
1646   EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll(
1647       IgnoreResult(InvokeWithoutArgs(&connection_,
1648                                      &TestConnection::SendCryptoStreamData)),
1649       IgnoreResult(InvokeWithoutArgs(&connection_,
1650                                      &TestConnection::SendStreamData3))));
1651
1652   EXPECT_CALL(*send_algorithm_,
1653               OnPacketSent(_, _, _, NOT_RETRANSMISSION, _))
1654       .Times(3);
1655   // Unblock the connection.
1656   connection_.GetSendAlarm()->Fire();
1657   EXPECT_EQ(0u, connection_.NumQueuedPackets());
1658   EXPECT_FALSE(connection_.HasQueuedData());
1659
1660   // Parse the last packet and ensure it's the stream frame from stream 3.
1661   EXPECT_EQ(1u, writer_->frame_count());
1662   EXPECT_EQ(1u, writer_->stream_frames()->size());
1663   EXPECT_EQ(kStreamId3, (*writer_->stream_frames())[0].stream_id);
1664 }
1665
1666 TEST_P(QuicConnectionTest, FramePackingFEC) {
1667   if (version() < QUIC_VERSION_15) {
1668     return;
1669   }
1670   // Enable fec.
1671   connection_.options()->max_packets_per_fec_group = 6;
1672   // Block the connection.
1673   connection_.GetSendAlarm()->Set(
1674       clock_.ApproximateNow().Add(QuicTime::Delta::FromSeconds(1)));
1675
1676   // Send an ack and two stream frames in 1 packet by queueing them.
1677   connection_.SendAck();
1678   EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll(
1679       IgnoreResult(InvokeWithoutArgs(&connection_,
1680                                      &TestConnection::SendStreamData3)),
1681       IgnoreResult(InvokeWithoutArgs(&connection_,
1682                                      &TestConnection::SendStreamData5))));
1683
1684   EXPECT_CALL(*send_algorithm_,
1685               OnPacketSent(_, _, _, NOT_RETRANSMISSION, _)).Times(2);
1686   // Unblock the connection.
1687   connection_.GetSendAlarm()->Fire();
1688   EXPECT_EQ(0u, connection_.NumQueuedPackets());
1689   EXPECT_FALSE(connection_.HasQueuedData());
1690
1691   // Parse the last packet and ensure it's in an fec group.
1692   EXPECT_EQ(1u, writer_->header()->fec_group);
1693   EXPECT_EQ(0u, writer_->frame_count());
1694 }
1695
1696 TEST_P(QuicConnectionTest, FramePackingAckResponse) {
1697   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1698   // Process a data packet to queue up a pending ack.
1699   EXPECT_CALL(visitor_, OnStreamFrames(_)).WillOnce(Return(true));
1700   ProcessDataPacket(1, 1, kEntropyFlag);
1701
1702   EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll(
1703       IgnoreResult(InvokeWithoutArgs(&connection_,
1704                                      &TestConnection::SendStreamData3)),
1705       IgnoreResult(InvokeWithoutArgs(&connection_,
1706                                      &TestConnection::SendStreamData5))));
1707
1708   EXPECT_CALL(*send_algorithm_,
1709               OnPacketSent(_, _, _, NOT_RETRANSMISSION, _))
1710       .Times(1);
1711
1712   // Process an ack to cause the visitor's OnCanWrite to be invoked.
1713   creator_.set_sequence_number(2);
1714   QuicAckFrame ack_one = InitAckFrame(0, 0);
1715   ProcessAckPacket(&ack_one);
1716
1717   EXPECT_EQ(0u, connection_.NumQueuedPackets());
1718   EXPECT_FALSE(connection_.HasQueuedData());
1719
1720   // Parse the last packet and ensure it's an ack and two stream frames from
1721   // two different streams.
1722   if (version() > QUIC_VERSION_15) {
1723     EXPECT_EQ(4u, writer_->frame_count());
1724     EXPECT_TRUE(writer_->stop_waiting());
1725   } else {
1726     EXPECT_EQ(3u, writer_->frame_count());
1727   }
1728   EXPECT_TRUE(writer_->ack());
1729   ASSERT_EQ(2u, writer_->stream_frames()->size());
1730   EXPECT_EQ(kStreamId3, (*writer_->stream_frames())[0].stream_id);
1731   EXPECT_EQ(kStreamId5, (*writer_->stream_frames())[1].stream_id);
1732 }
1733
1734 TEST_P(QuicConnectionTest, FramePackingSendv) {
1735   // Send data in 1 packet by writing multiple blocks in a single iovector
1736   // using writev.
1737   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, NOT_RETRANSMISSION, _));
1738
1739   char data[] = "ABCD";
1740   IOVector data_iov;
1741   data_iov.AppendNoCoalesce(data, 2);
1742   data_iov.AppendNoCoalesce(data + 2, 2);
1743   connection_.SendStreamData(1, data_iov, 0, !kFin, NULL);
1744
1745   EXPECT_EQ(0u, connection_.NumQueuedPackets());
1746   EXPECT_FALSE(connection_.HasQueuedData());
1747
1748   // Parse the last packet and ensure multiple iovector blocks have
1749   // been packed into a single stream frame from one stream.
1750   EXPECT_EQ(1u, writer_->frame_count());
1751   EXPECT_EQ(1u, writer_->stream_frames()->size());
1752   QuicStreamFrame frame = (*writer_->stream_frames())[0];
1753   EXPECT_EQ(1u, frame.stream_id);
1754   EXPECT_EQ("ABCD", string(static_cast<char*>
1755                            (frame.data.iovec()[0].iov_base),
1756                            (frame.data.iovec()[0].iov_len)));
1757 }
1758
1759 TEST_P(QuicConnectionTest, FramePackingSendvQueued) {
1760   // Try to send two stream frames in 1 packet by using writev.
1761   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, NOT_RETRANSMISSION, _));
1762
1763   BlockOnNextWrite();
1764   char data[] = "ABCD";
1765   IOVector data_iov;
1766   data_iov.AppendNoCoalesce(data, 2);
1767   data_iov.AppendNoCoalesce(data + 2, 2);
1768   connection_.SendStreamData(1, data_iov, 0, !kFin, NULL);
1769
1770   EXPECT_EQ(1u, connection_.NumQueuedPackets());
1771   EXPECT_TRUE(connection_.HasQueuedData());
1772
1773   // Unblock the writes and actually send.
1774   writer_->SetWritable();
1775   connection_.OnCanWrite();
1776   EXPECT_EQ(0u, connection_.NumQueuedPackets());
1777
1778   // Parse the last packet and ensure it's one stream frame from one stream.
1779   EXPECT_EQ(1u, writer_->frame_count());
1780   EXPECT_EQ(1u, writer_->stream_frames()->size());
1781   EXPECT_EQ(1u, (*writer_->stream_frames())[0].stream_id);
1782 }
1783
1784 TEST_P(QuicConnectionTest, SendingZeroBytes) {
1785   // Send a zero byte write with a fin using writev.
1786   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, NOT_RETRANSMISSION, _));
1787   IOVector empty_iov;
1788   connection_.SendStreamData(1, empty_iov, 0, kFin, NULL);
1789
1790   EXPECT_EQ(0u, connection_.NumQueuedPackets());
1791   EXPECT_FALSE(connection_.HasQueuedData());
1792
1793   // Parse the last packet and ensure it's one stream frame from one stream.
1794   EXPECT_EQ(1u, writer_->frame_count());
1795   EXPECT_EQ(1u, writer_->stream_frames()->size());
1796   EXPECT_EQ(1u, (*writer_->stream_frames())[0].stream_id);
1797   EXPECT_TRUE((*writer_->stream_frames())[0].fin);
1798 }
1799
1800 TEST_P(QuicConnectionTest, OnCanWrite) {
1801   // Visitor's OnCanWrite will send data, but will have more pending writes.
1802   EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(DoAll(
1803       IgnoreResult(InvokeWithoutArgs(&connection_,
1804                                      &TestConnection::SendStreamData3)),
1805       IgnoreResult(InvokeWithoutArgs(&connection_,
1806                                      &TestConnection::SendStreamData5))));
1807   EXPECT_CALL(visitor_, HasPendingWrites()).WillOnce(Return(true));
1808   EXPECT_CALL(*send_algorithm_,
1809               TimeUntilSend(_, NOT_RETRANSMISSION, _, _)).WillRepeatedly(
1810                   testing::Return(QuicTime::Delta::Zero()));
1811
1812   connection_.OnCanWrite();
1813
1814   // Parse the last packet and ensure it's the two stream frames from
1815   // two different streams.
1816   EXPECT_EQ(2u, writer_->frame_count());
1817   EXPECT_EQ(2u, writer_->stream_frames()->size());
1818   EXPECT_EQ(kStreamId3, (*writer_->stream_frames())[0].stream_id);
1819   EXPECT_EQ(kStreamId5, (*writer_->stream_frames())[1].stream_id);
1820 }
1821
1822 TEST_P(QuicConnectionTest, RetransmitOnNack) {
1823   QuicPacketSequenceNumber last_packet;
1824   QuicByteCount second_packet_size;
1825   SendStreamDataToPeer(3, "foo", 0, !kFin, &last_packet);  // Packet 1
1826   second_packet_size =
1827       SendStreamDataToPeer(3, "foos", 3, !kFin, &last_packet);  // Packet 2
1828   SendStreamDataToPeer(3, "fooos", 7, !kFin, &last_packet);  // Packet 3
1829
1830   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1831
1832   // Don't lose a packet on an ack, and nothing is retransmitted.
1833   EXPECT_CALL(*send_algorithm_, UpdateRtt(_));
1834   EXPECT_CALL(*send_algorithm_, OnPacketAcked(1, _));
1835   QuicAckFrame ack_one = InitAckFrame(1, 0);
1836   ProcessAckPacket(&ack_one);
1837
1838   // Lose a packet and ensure it triggers retransmission.
1839   QuicAckFrame nack_two = InitAckFrame(3, 0);
1840   NackPacket(2, &nack_two);
1841   SequenceNumberSet lost_packets;
1842   lost_packets.insert(2);
1843   EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1844       .WillOnce(Return(lost_packets));
1845   EXPECT_CALL(*send_algorithm_, UpdateRtt(_));
1846   EXPECT_CALL(*send_algorithm_, OnPacketAcked(3, _));
1847   EXPECT_CALL(*send_algorithm_, OnPacketLost(2, _)).Times(1);
1848   EXPECT_CALL(*send_algorithm_, OnPacketAbandoned(2, _)).Times(1);
1849   EXPECT_CALL(*send_algorithm_,
1850               OnPacketSent(_, _, second_packet_size - kQuicVersionSize,
1851                            LOSS_RETRANSMISSION, _)).Times(1);
1852   ProcessAckPacket(&nack_two);
1853 }
1854
1855 TEST_P(QuicConnectionTest, DiscardRetransmit) {
1856   QuicPacketSequenceNumber last_packet;
1857   SendStreamDataToPeer(1, "foo", 0, !kFin, &last_packet);  // Packet 1
1858   SendStreamDataToPeer(1, "foos", 3, !kFin, &last_packet);  // Packet 2
1859   SendStreamDataToPeer(1, "fooos", 7, !kFin, &last_packet);  // Packet 3
1860
1861   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1862
1863   // Instigate a loss with an ack.
1864   QuicAckFrame nack_two = InitAckFrame(3, 0);
1865   NackPacket(2, &nack_two);
1866   // The first nack should trigger a fast retransmission, but we'll be
1867   // write blocked, so the packet will be queued.
1868   BlockOnNextWrite();
1869   SequenceNumberSet lost_packets;
1870   lost_packets.insert(2);
1871   EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1872       .WillOnce(Return(lost_packets));
1873   EXPECT_CALL(*send_algorithm_, UpdateRtt(_));
1874   EXPECT_CALL(*send_algorithm_, OnPacketAcked(_, _)).Times(2);
1875   EXPECT_CALL(*send_algorithm_, OnPacketLost(2, _));
1876   EXPECT_CALL(*send_algorithm_, OnPacketAbandoned(2, _));
1877   ProcessAckPacket(&nack_two);
1878   EXPECT_EQ(1u, connection_.NumQueuedPackets());
1879
1880   // Now, ack the previous transmission.
1881   EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1882       .WillOnce(Return(SequenceNumberSet()));
1883   QuicAckFrame ack_all = InitAckFrame(3, 0);
1884   ProcessAckPacket(&ack_all);
1885
1886   // Unblock the socket and attempt to send the queued packets.  However,
1887   // since the previous transmission has been acked, we will not
1888   // send the retransmission.
1889   EXPECT_CALL(*send_algorithm_,
1890               OnPacketSent(_, _, _, _, _)).Times(0);
1891
1892   writer_->SetWritable();
1893   connection_.OnCanWrite();
1894
1895   EXPECT_EQ(0u, connection_.NumQueuedPackets());
1896 }
1897
1898 TEST_P(QuicConnectionTest, RetransmitNackedLargestObserved) {
1899   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1900   QuicPacketSequenceNumber largest_observed;
1901   QuicByteCount packet_size;
1902   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, NOT_RETRANSMISSION, _))
1903       .WillOnce(DoAll(SaveArg<1>(&largest_observed), SaveArg<2>(&packet_size),
1904                       Return(true)));
1905   connection_.SendStreamDataWithString(3, "foo", 0, !kFin, NULL);
1906
1907   QuicAckFrame frame = InitAckFrame(1, largest_observed);
1908   NackPacket(largest_observed, &frame);
1909   // The first nack should retransmit the largest observed packet.
1910   SequenceNumberSet lost_packets;
1911   lost_packets.insert(1);
1912   EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
1913       .WillOnce(Return(lost_packets));
1914   EXPECT_CALL(*send_algorithm_, UpdateRtt(_));
1915   EXPECT_CALL(*send_algorithm_, OnPacketLost(1, _)).Times(1);
1916   EXPECT_CALL(*send_algorithm_, OnPacketAbandoned(1, _)).Times(1);
1917   EXPECT_CALL(*send_algorithm_,
1918               OnPacketSent(_, _, packet_size - kQuicVersionSize,
1919                            LOSS_RETRANSMISSION, _));
1920   ProcessAckPacket(&frame);
1921 }
1922
1923 TEST_P(QuicConnectionTest, QueueAfterTwoRTOs) {
1924   for (int i = 0; i < 10; ++i) {
1925     EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
1926     connection_.SendStreamDataWithString(3, "foo", i * 3, !kFin, NULL);
1927   }
1928
1929   // Block the congestion window and ensure they're queued.
1930   BlockOnNextWrite();
1931   clock_.AdvanceTime(DefaultRetransmissionTime());
1932   // Only one packet should be retransmitted.
1933   EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
1934   connection_.GetRetransmissionAlarm()->Fire();
1935   EXPECT_TRUE(connection_.HasQueuedData());
1936
1937   // Unblock the congestion window.
1938   writer_->SetWritable();
1939   clock_.AdvanceTime(QuicTime::Delta::FromMicroseconds(
1940       2 * DefaultRetransmissionTime().ToMicroseconds()));
1941   // Retransmit already retransmitted packets event though the sequence number
1942   // greater than the largest observed.
1943   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(10);
1944   connection_.GetRetransmissionAlarm()->Fire();
1945   connection_.OnCanWrite();
1946 }
1947
1948 TEST_P(QuicConnectionTest, WriteBlockedThenSent) {
1949   BlockOnNextWrite();
1950   writer_->set_is_write_blocked_data_buffered(true);
1951   connection_.SendStreamDataWithString(1, "foo", 0, !kFin, NULL);
1952   EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
1953
1954   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
1955   connection_.OnPacketSent(WriteResult(WRITE_STATUS_OK, 0));
1956   EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
1957 }
1958
1959 TEST_P(QuicConnectionTest, WriteBlockedAckedThenSent) {
1960   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1961   BlockOnNextWrite();
1962   writer_->set_is_write_blocked_data_buffered(true);
1963   connection_.SendStreamDataWithString(1, "foo", 0, !kFin, NULL);
1964   EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
1965
1966   // Ack the sent packet before the callback returns, which happens in
1967   // rare circumstances with write blocked sockets.
1968   QuicAckFrame ack = InitAckFrame(1, 0);
1969   ProcessAckPacket(&ack);
1970
1971   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
1972   connection_.OnPacketSent(WriteResult(WRITE_STATUS_OK, 0));
1973   EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
1974 }
1975
1976 TEST_P(QuicConnectionTest, RetransmitWriteBlockedAckedOriginalThenSent) {
1977   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
1978   connection_.SendStreamDataWithString(3, "foo", 0, !kFin, NULL);
1979   EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
1980
1981   BlockOnNextWrite();
1982   writer_->set_is_write_blocked_data_buffered(true);
1983   // Simulate the retransmission alarm firing.
1984   EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(_));
1985   clock_.AdvanceTime(DefaultRetransmissionTime());
1986   connection_.GetRetransmissionAlarm()->Fire();
1987
1988   // Ack the sent packet before the callback returns, which happens in
1989   // rare circumstances with write blocked sockets.
1990   EXPECT_CALL(*send_algorithm_, UpdateRtt(_));
1991   QuicAckFrame ack = InitAckFrame(1, 0);
1992   ProcessAckPacket(&ack);
1993
1994   connection_.OnPacketSent(WriteResult(WRITE_STATUS_OK, 0));
1995   // The retransmission alarm should not be set because there are
1996   // no unacked packets.
1997   EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
1998 }
1999
2000 TEST_P(QuicConnectionTest, AlarmsWhenWriteBlocked) {
2001   // Block the connection.
2002   BlockOnNextWrite();
2003   connection_.SendStreamDataWithString(3, "foo", 0, !kFin, NULL);
2004   EXPECT_EQ(1u, writer_->packets_write_attempts());
2005   EXPECT_TRUE(writer_->IsWriteBlocked());
2006
2007   // Set the send and resumption alarms. Fire the alarms and ensure they don't
2008   // attempt to write.
2009   connection_.GetResumeWritesAlarm()->Set(clock_.ApproximateNow());
2010   connection_.GetSendAlarm()->Set(clock_.ApproximateNow());
2011   connection_.GetResumeWritesAlarm()->Fire();
2012   connection_.GetSendAlarm()->Fire();
2013   EXPECT_TRUE(writer_->IsWriteBlocked());
2014   EXPECT_EQ(1u, writer_->packets_write_attempts());
2015 }
2016
2017 TEST_P(QuicConnectionTest, NoLimitPacketsPerNack) {
2018   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2019   int offset = 0;
2020   // Send packets 1 to 15.
2021   for (int i = 0; i < 15; ++i) {
2022     SendStreamDataToPeer(1, "foo", offset, !kFin, NULL);
2023     offset += 3;
2024   }
2025
2026   // Ack 15, nack 1-14.
2027   SequenceNumberSet lost_packets;
2028   QuicAckFrame nack = InitAckFrame(15, 0);
2029   for (int i = 1; i < 15; ++i) {
2030     NackPacket(i, &nack);
2031     lost_packets.insert(i);
2032   }
2033
2034   // 14 packets have been NACK'd and lost.  In TCP cubic, PRR limits
2035   // the retransmission rate in the case of burst losses.
2036   EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
2037       .WillOnce(Return(lost_packets));
2038   EXPECT_CALL(*send_algorithm_, UpdateRtt(_));
2039   EXPECT_CALL(*send_algorithm_, OnPacketAcked(15, _)).Times(1);
2040   EXPECT_CALL(*send_algorithm_, OnPacketAbandoned(_, _)).Times(14);
2041   EXPECT_CALL(*send_algorithm_, OnPacketLost(_, _)).Times(14);
2042   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(14);
2043   ProcessAckPacket(&nack);
2044 }
2045
2046 // Test sending multiple acks from the connection to the session.
2047 TEST_P(QuicConnectionTest, MultipleAcks) {
2048   QuicPacketSequenceNumber last_packet;
2049   SendStreamDataToPeer(1, "foo", 0, !kFin, &last_packet);  // Packet 1
2050   EXPECT_EQ(1u, last_packet);
2051   SendStreamDataToPeer(3, "foo", 0, !kFin, &last_packet);  // Packet 2
2052   EXPECT_EQ(2u, last_packet);
2053   SendAckPacketToPeer();  // Packet 3
2054   SendStreamDataToPeer(5, "foo", 0, !kFin, &last_packet);  // Packet 4
2055   EXPECT_EQ(4u, last_packet);
2056   SendStreamDataToPeer(1, "foo", 3, !kFin, &last_packet);  // Packet 5
2057   EXPECT_EQ(5u, last_packet);
2058   SendStreamDataToPeer(3, "foo", 3, !kFin, &last_packet);  // Packet 6
2059   EXPECT_EQ(6u, last_packet);
2060
2061   // Client will ack packets 1, 2, [!3], 4, 5.
2062   EXPECT_CALL(*send_algorithm_, UpdateRtt(_));
2063   EXPECT_CALL(*send_algorithm_, OnPacketAcked(_, _)).Times(4);
2064   QuicAckFrame frame1 = InitAckFrame(5, 0);
2065   NackPacket(3, &frame1);
2066   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2067   ProcessAckPacket(&frame1);
2068
2069   // Now the client implicitly acks 3, and explicitly acks 6.
2070   EXPECT_CALL(*send_algorithm_, UpdateRtt(_));
2071   EXPECT_CALL(*send_algorithm_, OnPacketAcked(_, _)).Times(2);
2072   QuicAckFrame frame2 = InitAckFrame(6, 0);
2073   ProcessAckPacket(&frame2);
2074 }
2075
2076 TEST_P(QuicConnectionTest, DontLatchUnackedPacket) {
2077   EXPECT_CALL(*send_algorithm_, UpdateRtt(_));
2078   EXPECT_CALL(*send_algorithm_, OnPacketAcked(_, _)).Times(1);
2079   SendStreamDataToPeer(1, "foo", 0, !kFin, NULL);  // Packet 1;
2080   // From now on, we send acks, so the send algorithm won't save them.
2081   ON_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2082               .WillByDefault(Return(false));
2083   SendAckPacketToPeer();  // Packet 2
2084
2085   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2086   QuicAckFrame frame = InitAckFrame(1, 0);
2087   ProcessAckPacket(&frame);
2088
2089   // Verify that our internal state has least-unacked as 3.
2090   EXPECT_EQ(3u, outgoing_ack()->sent_info.least_unacked);
2091
2092   // When we send an ack, we make sure our least-unacked makes sense.  In this
2093   // case since we're not waiting on an ack for 2 and all packets are acked, we
2094   // set it to 3.
2095   SendAckPacketToPeer();  // Packet 3
2096   // Since this was an ack packet, we set least_unacked to 4.
2097   EXPECT_EQ(4u, outgoing_ack()->sent_info.least_unacked);
2098   // Check that the outgoing ack had its sequence number as least_unacked.
2099   EXPECT_EQ(3u, least_unacked());
2100
2101   ON_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2102               .WillByDefault(Return(true));
2103   SendStreamDataToPeer(1, "bar", 3, false, NULL);  // Packet 4
2104   EXPECT_EQ(4u, outgoing_ack()->sent_info.least_unacked);
2105   ON_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _))
2106               .WillByDefault(Return(false));
2107   SendAckPacketToPeer();  // Packet 5
2108   EXPECT_EQ(4u, least_unacked());
2109 }
2110
2111 TEST_P(QuicConnectionTest, ReviveMissingPacketAfterFecPacket) {
2112   if (version() < QUIC_VERSION_15) {
2113     return;
2114   }
2115   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2116
2117   // Don't send missing packet 1.
2118   ProcessFecPacket(2, 1, true, !kEntropyFlag, NULL);
2119   // Entropy flag should be false, so entropy should be 0.
2120   EXPECT_EQ(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 2));
2121 }
2122
2123 TEST_P(QuicConnectionTest, ReviveMissingPacketAfterDataPacketThenFecPacket) {
2124   if (version() < QUIC_VERSION_15) {
2125     return;
2126   }
2127   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2128
2129   ProcessFecProtectedPacket(1, false, kEntropyFlag);
2130   // Don't send missing packet 2.
2131   ProcessFecPacket(3, 1, true, !kEntropyFlag, NULL);
2132   // Entropy flag should be true, so entropy should not be 0.
2133   EXPECT_NE(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 2));
2134 }
2135
2136 TEST_P(QuicConnectionTest, ReviveMissingPacketAfterDataPacketsThenFecPacket) {
2137   if (version() < QUIC_VERSION_15) {
2138     return;
2139   }
2140   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2141
2142   ProcessFecProtectedPacket(1, false, !kEntropyFlag);
2143   // Don't send missing packet 2.
2144   ProcessFecProtectedPacket(3, false, !kEntropyFlag);
2145   ProcessFecPacket(4, 1, true, kEntropyFlag, NULL);
2146   // Ensure QUIC no longer revives entropy for lost packets.
2147   EXPECT_EQ(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 2));
2148   EXPECT_NE(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 4));
2149 }
2150
2151 TEST_P(QuicConnectionTest, ReviveMissingPacketAfterDataPacket) {
2152   if (version() < QUIC_VERSION_15) {
2153     return;
2154   }
2155   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2156
2157   // Don't send missing packet 1.
2158   ProcessFecPacket(3, 1, false, !kEntropyFlag, NULL);
2159   // Out of order.
2160   ProcessFecProtectedPacket(2, true, !kEntropyFlag);
2161   // Entropy flag should be false, so entropy should be 0.
2162   EXPECT_EQ(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 2));
2163 }
2164
2165 TEST_P(QuicConnectionTest, ReviveMissingPacketAfterDataPackets) {
2166   if (version() < QUIC_VERSION_15) {
2167     return;
2168   }
2169   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2170
2171   ProcessFecProtectedPacket(1, false, !kEntropyFlag);
2172   // Don't send missing packet 2.
2173   ProcessFecPacket(6, 1, false, kEntropyFlag, NULL);
2174   ProcessFecProtectedPacket(3, false, kEntropyFlag);
2175   ProcessFecProtectedPacket(4, false, kEntropyFlag);
2176   ProcessFecProtectedPacket(5, true, !kEntropyFlag);
2177   // Ensure entropy is not revived for the missing packet.
2178   EXPECT_EQ(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 2));
2179   EXPECT_NE(0u, QuicConnectionPeer::ReceivedEntropyHash(&connection_, 3));
2180 }
2181
2182 TEST_P(QuicConnectionTest, RTO) {
2183   QuicTime default_retransmission_time = clock_.ApproximateNow().Add(
2184       DefaultRetransmissionTime());
2185   SendStreamDataToPeer(3, "foo", 0, !kFin, NULL);
2186   EXPECT_EQ(1u, outgoing_ack()->sent_info.least_unacked);
2187
2188   EXPECT_EQ(1u, last_header()->packet_sequence_number);
2189   EXPECT_EQ(default_retransmission_time,
2190             connection_.GetRetransmissionAlarm()->deadline());
2191   // Simulate the retransmission alarm firing.
2192   clock_.AdvanceTime(DefaultRetransmissionTime());
2193   EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
2194   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, 2u, _, _, _));
2195   connection_.GetRetransmissionAlarm()->Fire();
2196   EXPECT_EQ(2u, last_header()->packet_sequence_number);
2197   // We do not raise the high water mark yet.
2198   EXPECT_EQ(1u, outgoing_ack()->sent_info.least_unacked);
2199 }
2200
2201 TEST_P(QuicConnectionTest, RTOWithSameEncryptionLevel) {
2202   QuicTime default_retransmission_time = clock_.ApproximateNow().Add(
2203       DefaultRetransmissionTime());
2204   use_tagging_decrypter();
2205
2206   // A TaggingEncrypter puts kTagSize copies of the given byte (0x01 here) at
2207   // the end of the packet. We can test this to check which encrypter was used.
2208   connection_.SetEncrypter(ENCRYPTION_NONE, new TaggingEncrypter(0x01));
2209   SendStreamDataToPeer(3, "foo", 0, !kFin, NULL);
2210   EXPECT_EQ(0x01010101u, final_bytes_of_last_packet());
2211
2212   connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(0x02));
2213   connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2214   SendStreamDataToPeer(3, "foo", 0, !kFin, NULL);
2215   EXPECT_EQ(0x02020202u, final_bytes_of_last_packet());
2216
2217   EXPECT_EQ(default_retransmission_time,
2218             connection_.GetRetransmissionAlarm()->deadline());
2219   {
2220     InSequence s;
2221     EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
2222     EXPECT_CALL(*send_algorithm_, OnPacketSent(_, 3, _, RTO_RETRANSMISSION, _));
2223     EXPECT_CALL(*send_algorithm_, OnPacketSent(_, 4, _, RTO_RETRANSMISSION, _));
2224   }
2225
2226   // Simulate the retransmission alarm firing.
2227   clock_.AdvanceTime(DefaultRetransmissionTime());
2228   connection_.GetRetransmissionAlarm()->Fire();
2229
2230   // Packet should have been sent with ENCRYPTION_NONE.
2231   EXPECT_EQ(0x01010101u, final_bytes_of_previous_packet());
2232
2233   // Packet should have been sent with ENCRYPTION_INITIAL.
2234   EXPECT_EQ(0x02020202u, final_bytes_of_last_packet());
2235 }
2236
2237 TEST_P(QuicConnectionTest, SendHandshakeMessages) {
2238   use_tagging_decrypter();
2239   // A TaggingEncrypter puts kTagSize copies of the given byte (0x01 here) at
2240   // the end of the packet. We can test this to check which encrypter was used.
2241   connection_.SetEncrypter(ENCRYPTION_NONE, new TaggingEncrypter(0x01));
2242
2243   // Attempt to send a handshake message while the congestion manager
2244   // does not permit sending.
2245   EXPECT_CALL(*send_algorithm_,
2246               TimeUntilSend(_, _, _, IS_HANDSHAKE)).WillRepeatedly(
2247                   testing::Return(QuicTime::Delta::Infinite()));
2248   connection_.SendStreamDataWithString(1, "foo", 0, !kFin, NULL);
2249   // The packet should be serialized, but not queued.
2250   EXPECT_EQ(1u, connection_.NumQueuedPackets());
2251
2252   // Switch to the new encrypter.
2253   connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(0x02));
2254   connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2255
2256   // Now become writeable and flush the packets.
2257   EXPECT_CALL(*send_algorithm_,
2258               TimeUntilSend(_, _, _, IS_HANDSHAKE)).WillRepeatedly(
2259                   testing::Return(QuicTime::Delta::Zero()));
2260   EXPECT_CALL(visitor_, OnCanWrite());
2261   connection_.OnCanWrite();
2262   EXPECT_EQ(0u, connection_.NumQueuedPackets());
2263
2264   // Verify that the handshake packet went out at the null encryption.
2265   EXPECT_EQ(0x01010101u, final_bytes_of_last_packet());
2266 }
2267
2268 TEST_P(QuicConnectionTest,
2269        DropRetransmitsForNullEncryptedPacketAfterForwardSecure) {
2270   use_tagging_decrypter();
2271   connection_.SetEncrypter(ENCRYPTION_NONE, new TaggingEncrypter(0x01));
2272   QuicPacketSequenceNumber sequence_number;
2273   SendStreamDataToPeer(3, "foo", 0, !kFin, &sequence_number);
2274
2275   connection_.SetEncrypter(ENCRYPTION_FORWARD_SECURE,
2276                            new TaggingEncrypter(0x02));
2277   connection_.SetDefaultEncryptionLevel(ENCRYPTION_FORWARD_SECURE);
2278
2279   EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
2280   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
2281
2282   QuicTime default_retransmission_time = clock_.ApproximateNow().Add(
2283       DefaultRetransmissionTime());
2284
2285   EXPECT_EQ(default_retransmission_time,
2286             connection_.GetRetransmissionAlarm()->deadline());
2287   // Simulate the retransmission alarm firing.
2288   clock_.AdvanceTime(DefaultRetransmissionTime());
2289   connection_.GetRetransmissionAlarm()->Fire();
2290 }
2291
2292 TEST_P(QuicConnectionTest, RetransmitPacketsWithInitialEncryption) {
2293   use_tagging_decrypter();
2294   connection_.SetEncrypter(ENCRYPTION_NONE, new TaggingEncrypter(0x01));
2295   connection_.SetDefaultEncryptionLevel(ENCRYPTION_NONE);
2296
2297   SendStreamDataToPeer(1, "foo", 0, !kFin, NULL);
2298
2299   connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(0x02));
2300   connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2301
2302   SendStreamDataToPeer(2, "bar", 0, !kFin, NULL);
2303
2304   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(1);
2305   EXPECT_CALL(*send_algorithm_, OnPacketAbandoned(_, _)).Times(1);
2306
2307   connection_.RetransmitUnackedPackets(INITIAL_ENCRYPTION_ONLY);
2308 }
2309
2310 TEST_P(QuicConnectionTest, BufferNonDecryptablePackets) {
2311   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2312   use_tagging_decrypter();
2313
2314   const uint8 tag = 0x07;
2315   framer_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(tag));
2316
2317   // Process an encrypted packet which can not yet be decrypted
2318   // which should result in the packet being buffered.
2319   ProcessDataPacketAtLevel(1, false, kEntropyFlag, ENCRYPTION_INITIAL);
2320
2321   // Transition to the new encryption state and process another
2322   // encrypted packet which should result in the original packet being
2323   // processed.
2324   connection_.SetDecrypter(new StrictTaggingDecrypter(tag));
2325   connection_.SetDefaultEncryptionLevel(ENCRYPTION_INITIAL);
2326   connection_.SetEncrypter(ENCRYPTION_INITIAL, new TaggingEncrypter(tag));
2327   EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(2).WillRepeatedly(
2328       Return(true));
2329   ProcessDataPacketAtLevel(2, false, kEntropyFlag, ENCRYPTION_INITIAL);
2330
2331   // Finally, process a third packet and note that we do not
2332   // reprocess the buffered packet.
2333   EXPECT_CALL(visitor_, OnStreamFrames(_)).WillOnce(Return(true));
2334   ProcessDataPacketAtLevel(3, false, kEntropyFlag, ENCRYPTION_INITIAL);
2335 }
2336
2337 TEST_P(QuicConnectionTest, TestRetransmitOrder) {
2338   QuicByteCount first_packet_size;
2339   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).WillOnce(
2340       DoAll(SaveArg<2>(&first_packet_size), Return(true)));
2341
2342   connection_.SendStreamDataWithString(3, "first_packet", 0, !kFin, NULL);
2343   QuicByteCount second_packet_size;
2344   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).WillOnce(
2345       DoAll(SaveArg<2>(&second_packet_size), Return(true)));
2346   connection_.SendStreamDataWithString(3, "second_packet", 12, !kFin, NULL);
2347   EXPECT_NE(first_packet_size, second_packet_size);
2348   // Advance the clock by huge time to make sure packets will be retransmitted.
2349   clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
2350   EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
2351   {
2352     InSequence s;
2353     EXPECT_CALL(*send_algorithm_,
2354                 OnPacketSent(_, _, first_packet_size, _, _));
2355     EXPECT_CALL(*send_algorithm_,
2356                 OnPacketSent(_, _, second_packet_size, _, _));
2357   }
2358   connection_.GetRetransmissionAlarm()->Fire();
2359
2360   // Advance again and expect the packets to be sent again in the same order.
2361   clock_.AdvanceTime(QuicTime::Delta::FromSeconds(20));
2362   EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
2363   {
2364     InSequence s;
2365     EXPECT_CALL(*send_algorithm_,
2366                 OnPacketSent(_, _, first_packet_size, _, _));
2367     EXPECT_CALL(*send_algorithm_,
2368                 OnPacketSent(_, _, second_packet_size, _, _));
2369   }
2370   connection_.GetRetransmissionAlarm()->Fire();
2371 }
2372
2373 TEST_P(QuicConnectionTest, RetransmissionCountCalculation) {
2374   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2375   QuicPacketSequenceNumber original_sequence_number;
2376   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, NOT_RETRANSMISSION, _))
2377       .WillOnce(DoAll(SaveArg<1>(&original_sequence_number), Return(true)));
2378   connection_.SendStreamDataWithString(3, "foo", 0, !kFin, NULL);
2379
2380   EXPECT_TRUE(QuicConnectionPeer::IsSavedForRetransmission(
2381       &connection_, original_sequence_number));
2382   EXPECT_FALSE(QuicConnectionPeer::IsRetransmission(
2383       &connection_, original_sequence_number));
2384   // Force retransmission due to RTO.
2385   clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
2386   EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
2387   QuicPacketSequenceNumber rto_sequence_number;
2388   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, RTO_RETRANSMISSION, _))
2389       .WillOnce(DoAll(SaveArg<1>(&rto_sequence_number), Return(true)));
2390   connection_.GetRetransmissionAlarm()->Fire();
2391   EXPECT_FALSE(QuicConnectionPeer::IsSavedForRetransmission(
2392       &connection_, original_sequence_number));
2393   ASSERT_TRUE(QuicConnectionPeer::IsSavedForRetransmission(
2394       &connection_, rto_sequence_number));
2395   EXPECT_TRUE(QuicConnectionPeer::IsRetransmission(
2396       &connection_, rto_sequence_number));
2397   // Once by explicit nack.
2398   SequenceNumberSet lost_packets;
2399   lost_packets.insert(rto_sequence_number);
2400   EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
2401       .WillOnce(Return(lost_packets));
2402   EXPECT_CALL(*send_algorithm_, UpdateRtt(_)).Times(1);
2403   EXPECT_CALL(*send_algorithm_, OnPacketLost(rto_sequence_number, _)).Times(1);
2404   EXPECT_CALL(*send_algorithm_,
2405               OnPacketAbandoned(rto_sequence_number, _)).Times(1);
2406   QuicPacketSequenceNumber nack_sequence_number = 0;
2407   // Ack packets might generate some other packets, which are not
2408   // retransmissions. (More ack packets).
2409   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, NOT_RETRANSMISSION, _))
2410       .Times(AnyNumber());
2411   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, LOSS_RETRANSMISSION, _))
2412       .WillOnce(DoAll(SaveArg<1>(&nack_sequence_number), Return(true)));
2413   QuicAckFrame ack = InitAckFrame(rto_sequence_number, 0);
2414   // Nack the retransmitted packet.
2415   NackPacket(original_sequence_number, &ack);
2416   NackPacket(rto_sequence_number, &ack);
2417   ProcessAckPacket(&ack);
2418
2419   ASSERT_NE(0u, nack_sequence_number);
2420   EXPECT_FALSE(QuicConnectionPeer::IsSavedForRetransmission(
2421       &connection_, rto_sequence_number));
2422   ASSERT_TRUE(QuicConnectionPeer::IsSavedForRetransmission(
2423       &connection_, nack_sequence_number));
2424   EXPECT_TRUE(QuicConnectionPeer::IsRetransmission(
2425       &connection_, nack_sequence_number));
2426 }
2427
2428 TEST_P(QuicConnectionTest, SetRTOAfterWritingToSocket) {
2429   BlockOnNextWrite();
2430   connection_.SendStreamDataWithString(1, "foo", 0, !kFin, NULL);
2431   // Make sure that RTO is not started when the packet is queued.
2432   EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
2433
2434   // Test that RTO is started once we write to the socket.
2435   writer_->SetWritable();
2436   connection_.OnCanWrite();
2437   EXPECT_TRUE(connection_.GetRetransmissionAlarm()->IsSet());
2438 }
2439
2440 TEST_P(QuicConnectionTest, DelayRTOWithAckReceipt) {
2441   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2442   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, NOT_RETRANSMISSION, _))
2443       .Times(2);
2444   connection_.SendStreamDataWithString(2, "foo", 0, !kFin, NULL);
2445   connection_.SendStreamDataWithString(3, "bar", 0, !kFin, NULL);
2446   QuicAlarm* retransmission_alarm = connection_.GetRetransmissionAlarm();
2447   EXPECT_TRUE(retransmission_alarm->IsSet());
2448   EXPECT_EQ(clock_.Now().Add(DefaultRetransmissionTime()),
2449             retransmission_alarm->deadline());
2450
2451   // Advance the time right before the RTO, then receive an ack for the first
2452   // packet to delay the RTO.
2453   clock_.AdvanceTime(DefaultRetransmissionTime());
2454   EXPECT_CALL(*send_algorithm_, UpdateRtt(_));
2455   EXPECT_CALL(*send_algorithm_, OnPacketAcked(_, _)).Times(1);
2456   QuicAckFrame ack = InitAckFrame(1, 0);
2457   ProcessAckPacket(&ack);
2458   EXPECT_TRUE(retransmission_alarm->IsSet());
2459   EXPECT_GT(retransmission_alarm->deadline(), clock_.Now());
2460
2461   // Move forward past the original RTO and ensure the RTO is still pending.
2462   clock_.AdvanceTime(DefaultRetransmissionTime().Multiply(2));
2463
2464   // Ensure the second packet gets retransmitted when it finally fires.
2465   EXPECT_TRUE(retransmission_alarm->IsSet());
2466   EXPECT_LT(retransmission_alarm->deadline(), clock_.ApproximateNow());
2467   EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
2468   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, RTO_RETRANSMISSION, _));
2469   // Manually cancel the alarm to simulate a real test.
2470   connection_.GetRetransmissionAlarm()->Fire();
2471
2472   // The new retransmitted sequence number should set the RTO to a larger value
2473   // than previously.
2474   EXPECT_TRUE(retransmission_alarm->IsSet());
2475   QuicTime next_rto_time = retransmission_alarm->deadline();
2476   QuicTime expected_rto_time =
2477       connection_.sent_packet_manager().GetRetransmissionTime();
2478   EXPECT_EQ(next_rto_time, expected_rto_time);
2479 }
2480
2481 TEST_P(QuicConnectionTest, TestQueued) {
2482   EXPECT_EQ(0u, connection_.NumQueuedPackets());
2483   BlockOnNextWrite();
2484   connection_.SendStreamDataWithString(1, "foo", 0, !kFin, NULL);
2485   EXPECT_EQ(1u, connection_.NumQueuedPackets());
2486
2487   // Unblock the writes and actually send.
2488   writer_->SetWritable();
2489   connection_.OnCanWrite();
2490   EXPECT_EQ(0u, connection_.NumQueuedPackets());
2491 }
2492
2493 TEST_P(QuicConnectionTest, CloseFecGroup) {
2494   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2495   // Don't send missing packet 1.
2496   // Don't send missing packet 2.
2497   ProcessFecProtectedPacket(3, false, !kEntropyFlag);
2498   // Don't send missing FEC packet 3.
2499   ASSERT_EQ(1u, connection_.NumFecGroups());
2500
2501   // Now send non-fec protected ack packet and close the group.
2502   creator_.set_sequence_number(4);
2503   if (version() > QUIC_VERSION_15) {
2504     QuicStopWaitingFrame frame = InitStopWaitingFrame(5);
2505     ProcessStopWaitingPacket(&frame);
2506   } else {
2507     QuicAckFrame frame = InitAckFrame(0, 5);
2508     ProcessAckPacket(&frame);
2509   }
2510   ASSERT_EQ(0u, connection_.NumFecGroups());
2511 }
2512
2513 TEST_P(QuicConnectionTest, NoQuicCongestionFeedbackFrame) {
2514   SendAckPacketToPeer();
2515   EXPECT_TRUE(last_feedback() == NULL);
2516 }
2517
2518 TEST_P(QuicConnectionTest, WithQuicCongestionFeedbackFrame) {
2519   QuicCongestionFeedbackFrame info;
2520   info.type = kFixRate;
2521   info.fix_rate.bitrate = QuicBandwidth::FromBytesPerSecond(123);
2522   SetFeedback(&info);
2523
2524   SendAckPacketToPeer();
2525   EXPECT_EQ(kFixRate, last_feedback()->type);
2526   EXPECT_EQ(info.fix_rate.bitrate, last_feedback()->fix_rate.bitrate);
2527 }
2528
2529 TEST_P(QuicConnectionTest, UpdateQuicCongestionFeedbackFrame) {
2530   SendAckPacketToPeer();
2531   EXPECT_CALL(*receive_algorithm_, RecordIncomingPacket(_, _, _));
2532   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2533   ProcessPacket(1);
2534 }
2535
2536 TEST_P(QuicConnectionTest, DontUpdateQuicCongestionFeedbackFrameForRevived) {
2537   if (version() < QUIC_VERSION_15) {
2538     return;
2539   }
2540   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2541   SendAckPacketToPeer();
2542   // Process an FEC packet, and revive the missing data packet
2543   // but only contact the receive_algorithm once.
2544   EXPECT_CALL(*receive_algorithm_, RecordIncomingPacket(_, _, _));
2545   ProcessFecPacket(2, 1, true, !kEntropyFlag, NULL);
2546 }
2547
2548 TEST_P(QuicConnectionTest, InitialTimeout) {
2549   EXPECT_TRUE(connection_.connected());
2550   EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_CONNECTION_TIMED_OUT, false));
2551   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
2552
2553   QuicTime default_timeout = clock_.ApproximateNow().Add(
2554       QuicTime::Delta::FromSeconds(kDefaultInitialTimeoutSecs));
2555   EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
2556
2557   // Simulate the timeout alarm firing.
2558   clock_.AdvanceTime(
2559       QuicTime::Delta::FromSeconds(kDefaultInitialTimeoutSecs));
2560   connection_.GetTimeoutAlarm()->Fire();
2561   EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
2562   EXPECT_FALSE(connection_.connected());
2563
2564   EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
2565   EXPECT_FALSE(connection_.GetResumeWritesAlarm()->IsSet());
2566   EXPECT_FALSE(connection_.GetRetransmissionAlarm()->IsSet());
2567   EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
2568   EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
2569 }
2570
2571 TEST_P(QuicConnectionTest, TimeoutAfterSend) {
2572   EXPECT_TRUE(connection_.connected());
2573
2574   QuicTime default_timeout = clock_.ApproximateNow().Add(
2575       QuicTime::Delta::FromSeconds(kDefaultInitialTimeoutSecs));
2576
2577   // When we send a packet, the timeout will change to 5000 +
2578   // kDefaultInitialTimeoutSecs.
2579   clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
2580
2581   // Send an ack so we don't set the retransmission alarm.
2582   SendAckPacketToPeer();
2583   EXPECT_EQ(default_timeout, connection_.GetTimeoutAlarm()->deadline());
2584
2585   // The original alarm will fire.  We should not time out because we had a
2586   // network event at t=5000.  The alarm will reregister.
2587   clock_.AdvanceTime(QuicTime::Delta::FromMicroseconds(
2588       kDefaultInitialTimeoutSecs * 1000000 - 5000));
2589   EXPECT_EQ(default_timeout, clock_.ApproximateNow());
2590   connection_.GetTimeoutAlarm()->Fire();
2591   EXPECT_TRUE(connection_.GetTimeoutAlarm()->IsSet());
2592   EXPECT_TRUE(connection_.connected());
2593   EXPECT_EQ(default_timeout.Add(QuicTime::Delta::FromMilliseconds(5)),
2594             connection_.GetTimeoutAlarm()->deadline());
2595
2596   // This time, we should time out.
2597   EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_CONNECTION_TIMED_OUT, false));
2598   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
2599   clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(5));
2600   EXPECT_EQ(default_timeout.Add(QuicTime::Delta::FromMilliseconds(5)),
2601             clock_.ApproximateNow());
2602   connection_.GetTimeoutAlarm()->Fire();
2603   EXPECT_FALSE(connection_.GetTimeoutAlarm()->IsSet());
2604   EXPECT_FALSE(connection_.connected());
2605 }
2606
2607 TEST_P(QuicConnectionTest, SendScheduler) {
2608   // Test that if we send a packet without delay, it is not queued.
2609   QuicPacket* packet = ConstructDataPacket(1, 0, !kEntropyFlag);
2610   EXPECT_CALL(*send_algorithm_,
2611               TimeUntilSend(_, NOT_RETRANSMISSION, _, _)).WillOnce(
2612                   testing::Return(QuicTime::Delta::Zero()));
2613   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
2614   connection_.SendPacket(
2615       ENCRYPTION_NONE, 1, packet, kTestEntropyHash, HAS_RETRANSMITTABLE_DATA);
2616   EXPECT_EQ(0u, connection_.NumQueuedPackets());
2617 }
2618
2619 TEST_P(QuicConnectionTest, SendSchedulerDelay) {
2620   // Test that if we send a packet with a delay, it ends up queued.
2621   QuicPacket* packet = ConstructDataPacket(1, 0, !kEntropyFlag);
2622   EXPECT_CALL(*send_algorithm_,
2623               TimeUntilSend(_, NOT_RETRANSMISSION, _, _)).WillOnce(
2624                   testing::Return(QuicTime::Delta::FromMicroseconds(1)));
2625   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, 1, _, _, _)).Times(0);
2626   connection_.SendPacket(
2627       ENCRYPTION_NONE, 1, packet, kTestEntropyHash, HAS_RETRANSMITTABLE_DATA);
2628   EXPECT_EQ(1u, connection_.NumQueuedPackets());
2629 }
2630
2631 TEST_P(QuicConnectionTest, SendSchedulerForce) {
2632   // Test that if we force send a packet, it is not queued.
2633   QuicPacket* packet = ConstructDataPacket(1, 0, !kEntropyFlag);
2634   EXPECT_CALL(*send_algorithm_,
2635               TimeUntilSend(_, LOSS_RETRANSMISSION, _, _)).Times(0);
2636   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
2637   connection_.SendPacket(
2638       ENCRYPTION_NONE, 1, packet, kTestEntropyHash, HAS_RETRANSMITTABLE_DATA);
2639   // XXX: fixme.  was:  connection_.SendPacket(1, packet, kForce);
2640   EXPECT_EQ(0u, connection_.NumQueuedPackets());
2641 }
2642
2643 TEST_P(QuicConnectionTest, SendSchedulerEAGAIN) {
2644   QuicPacket* packet = ConstructDataPacket(1, 0, !kEntropyFlag);
2645   BlockOnNextWrite();
2646   EXPECT_CALL(*send_algorithm_,
2647               TimeUntilSend(_, NOT_RETRANSMISSION, _, _)).WillOnce(
2648                   testing::Return(QuicTime::Delta::Zero()));
2649   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, 1, _, _, _)).Times(0);
2650   connection_.SendPacket(
2651       ENCRYPTION_NONE, 1, packet, kTestEntropyHash, HAS_RETRANSMITTABLE_DATA);
2652   EXPECT_EQ(1u, connection_.NumQueuedPackets());
2653 }
2654
2655 TEST_P(QuicConnectionTest, SendSchedulerDelayThenSend) {
2656   // Test that if we send a packet with a delay, it ends up queued.
2657   QuicPacket* packet = ConstructDataPacket(1, 0, !kEntropyFlag);
2658   EXPECT_CALL(*send_algorithm_,
2659               TimeUntilSend(_, NOT_RETRANSMISSION, _, _)).WillOnce(
2660                   testing::Return(QuicTime::Delta::FromMicroseconds(1)));
2661   connection_.SendPacket(
2662        ENCRYPTION_NONE, 1, packet, kTestEntropyHash, HAS_RETRANSMITTABLE_DATA);
2663   EXPECT_EQ(1u, connection_.NumQueuedPackets());
2664
2665   // Advance the clock to fire the alarm, and configure the scheduler
2666   // to permit the packet to be sent.
2667   EXPECT_CALL(*send_algorithm_,
2668               TimeUntilSend(_, NOT_RETRANSMISSION, _, _)).WillRepeatedly(
2669                   testing::Return(QuicTime::Delta::Zero()));
2670   clock_.AdvanceTime(QuicTime::Delta::FromMicroseconds(1));
2671   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
2672   connection_.GetSendAlarm()->Fire();
2673   EXPECT_EQ(0u, connection_.NumQueuedPackets());
2674 }
2675
2676 TEST_P(QuicConnectionTest, SendSchedulerDelayThenRetransmit) {
2677   EXPECT_CALL(*send_algorithm_, TimeUntilSend(_, NOT_RETRANSMISSION, _, _))
2678       .WillRepeatedly(testing::Return(QuicTime::Delta::Zero()));
2679   EXPECT_CALL(*send_algorithm_,
2680               OnPacketSent(_, 1, _, NOT_RETRANSMISSION, _));
2681   connection_.SendStreamDataWithString(3, "foo", 0, !kFin, NULL);
2682   EXPECT_EQ(0u, connection_.NumQueuedPackets());
2683   // Advance the time for retransmission of lost packet.
2684   clock_.AdvanceTime(QuicTime::Delta::FromMilliseconds(501));
2685   // Test that if we send a retransmit with a delay, it ends up queued in the
2686   // sent packet manager, but not yet serialized.
2687   EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
2688   EXPECT_CALL(*send_algorithm_,
2689               TimeUntilSend(_, RTO_RETRANSMISSION, _, _)).WillOnce(
2690                   testing::Return(QuicTime::Delta::FromMicroseconds(1)));
2691   connection_.GetRetransmissionAlarm()->Fire();
2692   EXPECT_EQ(0u, connection_.NumQueuedPackets());
2693
2694   // Advance the clock to fire the alarm, and configure the scheduler
2695   // to permit the packet to be sent.
2696   EXPECT_CALL(*send_algorithm_,
2697               TimeUntilSend(_, RTO_RETRANSMISSION, _, _)).Times(2).
2698                   WillRepeatedly(testing::Return(QuicTime::Delta::Zero()));
2699
2700   // Ensure the scheduler is notified this is a retransmit.
2701   EXPECT_CALL(*send_algorithm_,
2702               OnPacketSent(_, _, _, RTO_RETRANSMISSION, _));
2703   clock_.AdvanceTime(QuicTime::Delta::FromMicroseconds(1));
2704   connection_.GetSendAlarm()->Fire();
2705   EXPECT_EQ(0u, connection_.NumQueuedPackets());
2706 }
2707
2708 TEST_P(QuicConnectionTest, SendSchedulerDelayAndQueue) {
2709   QuicPacket* packet = ConstructDataPacket(1, 0, !kEntropyFlag);
2710   EXPECT_CALL(*send_algorithm_,
2711               TimeUntilSend(_, NOT_RETRANSMISSION, _, _)).WillOnce(
2712                   testing::Return(QuicTime::Delta::FromMicroseconds(1)));
2713   connection_.SendPacket(
2714       ENCRYPTION_NONE, 1, packet, kTestEntropyHash, HAS_RETRANSMITTABLE_DATA);
2715   EXPECT_EQ(1u, connection_.NumQueuedPackets());
2716
2717   // Attempt to send another packet and make sure that it gets queued.
2718   packet = ConstructDataPacket(2, 0, !kEntropyFlag);
2719   connection_.SendPacket(
2720       ENCRYPTION_NONE, 2, packet, kTestEntropyHash, HAS_RETRANSMITTABLE_DATA);
2721   EXPECT_EQ(2u, connection_.NumQueuedPackets());
2722 }
2723
2724 TEST_P(QuicConnectionTest, SendSchedulerDelayThenAckAndSend) {
2725   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2726   QuicPacket* packet = ConstructDataPacket(1, 0, !kEntropyFlag);
2727   EXPECT_CALL(*send_algorithm_,
2728               TimeUntilSend(_, NOT_RETRANSMISSION, _, _)).WillOnce(
2729                   testing::Return(QuicTime::Delta::FromMicroseconds(10)));
2730   connection_.SendPacket(
2731       ENCRYPTION_NONE, 1, packet, kTestEntropyHash, HAS_RETRANSMITTABLE_DATA);
2732   EXPECT_EQ(1u, connection_.NumQueuedPackets());
2733
2734   // Now send non-retransmitting information, that we're not going to
2735   // retransmit 3. The far end should stop waiting for it.
2736   QuicAckFrame frame = InitAckFrame(0, 1);
2737   EXPECT_CALL(*send_algorithm_,
2738               TimeUntilSend(_, NOT_RETRANSMISSION, _, _)).WillRepeatedly(
2739                   testing::Return(QuicTime::Delta::Zero()));
2740   EXPECT_CALL(*send_algorithm_,
2741               OnPacketSent(_, _, _, _, _));
2742   ProcessAckPacket(&frame);
2743
2744   EXPECT_EQ(0u, connection_.NumQueuedPackets());
2745   // Ensure alarm is not set
2746   EXPECT_FALSE(connection_.GetSendAlarm()->IsSet());
2747 }
2748
2749 TEST_P(QuicConnectionTest, SendSchedulerDelayThenAckAndHold) {
2750   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2751   QuicPacket* packet = ConstructDataPacket(1, 0, !kEntropyFlag);
2752   EXPECT_CALL(*send_algorithm_,
2753               TimeUntilSend(_, NOT_RETRANSMISSION, _, _)).WillOnce(
2754                   testing::Return(QuicTime::Delta::FromMicroseconds(10)));
2755   connection_.SendPacket(
2756       ENCRYPTION_NONE, 1, packet, kTestEntropyHash, HAS_RETRANSMITTABLE_DATA);
2757   EXPECT_EQ(1u, connection_.NumQueuedPackets());
2758
2759   // Now send non-retransmitting information, that we're not going to
2760   // retransmit 3.  The far end should stop waiting for it.
2761   QuicAckFrame frame = InitAckFrame(0, 1);
2762   EXPECT_CALL(*send_algorithm_,
2763               TimeUntilSend(_, NOT_RETRANSMISSION, _, _)).WillOnce(
2764                   testing::Return(QuicTime::Delta::FromMicroseconds(1)));
2765   ProcessAckPacket(&frame);
2766
2767   EXPECT_EQ(1u, connection_.NumQueuedPackets());
2768 }
2769
2770 TEST_P(QuicConnectionTest, SendSchedulerDelayThenOnCanWrite) {
2771   // TODO(ianswett): This test is unrealistic, because we would not serialize
2772   // new data if the send algorithm said not to.
2773   QuicPacket* packet = ConstructDataPacket(1, 0, !kEntropyFlag);
2774   EXPECT_CALL(*send_algorithm_,
2775               TimeUntilSend(_, NOT_RETRANSMISSION, _, _)).WillOnce(
2776                   testing::Return(QuicTime::Delta::FromMicroseconds(10)));
2777   connection_.SendPacket(
2778       ENCRYPTION_NONE, 1, packet, kTestEntropyHash, HAS_RETRANSMITTABLE_DATA);
2779   EXPECT_EQ(1u, connection_.NumQueuedPackets());
2780
2781   // OnCanWrite should send the packet, because it won't consult the send
2782   // algorithm for queued packets.
2783   connection_.OnCanWrite();
2784   EXPECT_EQ(0u, connection_.NumQueuedPackets());
2785 }
2786
2787 TEST_P(QuicConnectionTest, TestQueueLimitsOnSendStreamData) {
2788   // All packets carry version info till version is negotiated.
2789   size_t payload_length;
2790   connection_.options()->max_packet_length =
2791       GetPacketLengthForOneStream(
2792           connection_.version(), kIncludeVersion, PACKET_1BYTE_SEQUENCE_NUMBER,
2793           NOT_IN_FEC_GROUP, &payload_length);
2794
2795   // Queue the first packet.
2796   EXPECT_CALL(*send_algorithm_,
2797               TimeUntilSend(_, NOT_RETRANSMISSION, _, _)).WillOnce(
2798                   testing::Return(QuicTime::Delta::FromMicroseconds(10)));
2799   const string payload(payload_length, 'a');
2800   EXPECT_EQ(0u,
2801             connection_.SendStreamDataWithString(3, payload, 0,
2802                                                  !kFin, NULL).bytes_consumed);
2803   EXPECT_EQ(0u, connection_.NumQueuedPackets());
2804 }
2805
2806 TEST_P(QuicConnectionTest, LoopThroughSendingPackets) {
2807   // All packets carry version info till version is negotiated.
2808   size_t payload_length;
2809   connection_.options()->max_packet_length =
2810       GetPacketLengthForOneStream(
2811           connection_.version(), kIncludeVersion, PACKET_1BYTE_SEQUENCE_NUMBER,
2812           NOT_IN_FEC_GROUP, &payload_length);
2813
2814   // Queue the first packet.
2815   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(7);
2816   // The first stream frame will consume 2 fewer bytes than the other six.
2817   const string payload(payload_length * 7 - 12, 'a');
2818   EXPECT_EQ(payload.size(),
2819             connection_.SendStreamDataWithString(1, payload, 0,
2820                                                  !kFin, NULL).bytes_consumed);
2821 }
2822
2823 TEST_P(QuicConnectionTest, SendDelayedAckOnTimer) {
2824   QuicTime ack_time = clock_.ApproximateNow().Add(DefaultDelayedAckTime());
2825   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2826   EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
2827   ProcessPacket(1);
2828   // Check if delayed ack timer is running for the expected interval.
2829   EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
2830   EXPECT_EQ(ack_time, connection_.GetAckAlarm()->deadline());
2831   // Simulate delayed ack alarm firing.
2832   connection_.GetAckAlarm()->Fire();
2833   // Check that ack is sent and that delayed ack alarm is reset.
2834   if (version() > QUIC_VERSION_15) {
2835     EXPECT_EQ(2u, writer_->frame_count());
2836     EXPECT_TRUE(writer_->stop_waiting());
2837   } else {
2838     EXPECT_EQ(1u, writer_->frame_count());
2839   }
2840   EXPECT_TRUE(writer_->ack());
2841   EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
2842 }
2843
2844 TEST_P(QuicConnectionTest, SendDelayedAckOnSecondPacket) {
2845   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2846   ProcessPacket(1);
2847   ProcessPacket(2);
2848   // Check that ack is sent and that delayed ack alarm is reset.
2849   if (version() > QUIC_VERSION_15) {
2850     EXPECT_EQ(2u, writer_->frame_count());
2851     EXPECT_TRUE(writer_->stop_waiting());
2852   } else {
2853     EXPECT_EQ(1u, writer_->frame_count());
2854   }
2855   EXPECT_TRUE(writer_->ack());
2856   EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
2857 }
2858
2859 TEST_P(QuicConnectionTest, NoAckOnOldNacks) {
2860   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2861   // Drop one packet, triggering a sequence of acks.
2862   ProcessPacket(2);
2863   size_t frames_per_ack = version() > QUIC_VERSION_15 ? 2 : 1;
2864   EXPECT_EQ(frames_per_ack, writer_->frame_count());
2865   EXPECT_TRUE(writer_->ack());
2866   writer_->Reset();
2867   ProcessPacket(3);
2868   EXPECT_EQ(frames_per_ack, writer_->frame_count());
2869   EXPECT_TRUE(writer_->ack());
2870   writer_->Reset();
2871   ProcessPacket(4);
2872   EXPECT_EQ(frames_per_ack, writer_->frame_count());
2873   EXPECT_TRUE(writer_->ack());
2874   writer_->Reset();
2875   ProcessPacket(5);
2876   EXPECT_EQ(frames_per_ack, writer_->frame_count());
2877   EXPECT_TRUE(writer_->ack());
2878   // Now only set the timer on the 6th packet, instead of sending another ack.
2879   writer_->Reset();
2880   ProcessPacket(6);
2881   EXPECT_EQ(0u, writer_->frame_count());
2882   EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
2883 }
2884
2885 TEST_P(QuicConnectionTest, SendDelayedAckOnOutgoingPacket) {
2886   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2887   ProcessPacket(1);
2888   connection_.SendStreamDataWithString(kStreamId3, "foo", 0, !kFin, NULL);
2889   // Check that ack is bundled with outgoing data and that delayed ack
2890   // alarm is reset.
2891   if (version() > QUIC_VERSION_15) {
2892     EXPECT_EQ(3u, writer_->frame_count());
2893     EXPECT_TRUE(writer_->stop_waiting());
2894   } else {
2895     EXPECT_EQ(2u, writer_->frame_count());
2896   }
2897   EXPECT_TRUE(writer_->ack());
2898   EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
2899 }
2900
2901 TEST_P(QuicConnectionTest, DontSendDelayedAckOnOutgoingCryptoPacket) {
2902   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2903   ProcessPacket(1);
2904   connection_.SendStreamDataWithString(kCryptoStreamId, "foo", 0, !kFin, NULL);
2905   // Check that ack is not bundled with outgoing data.
2906   EXPECT_EQ(1u, writer_->frame_count());
2907   EXPECT_FALSE(writer_->ack());
2908   EXPECT_TRUE(connection_.GetAckAlarm()->IsSet());
2909 }
2910
2911 TEST_P(QuicConnectionTest, BundleAckWithDataOnIncomingAck) {
2912   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2913   connection_.SendStreamDataWithString(kStreamId3, "foo", 0, !kFin, NULL);
2914   connection_.SendStreamDataWithString(kStreamId3, "foo", 3, !kFin, NULL);
2915   // Ack the second packet, which will retransmit the first packet.
2916   QuicAckFrame ack = InitAckFrame(2, 0);
2917   NackPacket(1, &ack);
2918   SequenceNumberSet lost_packets;
2919   lost_packets.insert(1);
2920   EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
2921       .WillOnce(Return(lost_packets));
2922   EXPECT_CALL(*send_algorithm_, UpdateRtt(_));
2923   EXPECT_CALL(*send_algorithm_, OnPacketAcked(2, _)).Times(1);
2924   EXPECT_CALL(*send_algorithm_, OnPacketLost(1, _)).Times(1);
2925   EXPECT_CALL(*send_algorithm_, OnPacketAbandoned(1, _)).Times(1);
2926   ProcessAckPacket(&ack);
2927   EXPECT_EQ(1u, writer_->frame_count());
2928   EXPECT_EQ(1u, writer_->stream_frames()->size());
2929   writer_->Reset();
2930
2931   // Now ack the retransmission, which will both raise the high water mark
2932   // and see if there is more data to send.
2933   ack = InitAckFrame(3, 0);
2934   NackPacket(1, &ack);
2935   EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
2936       .WillOnce(Return(SequenceNumberSet()));
2937   EXPECT_CALL(*send_algorithm_, UpdateRtt(_));
2938   EXPECT_CALL(*send_algorithm_, OnPacketAcked(3, _)).Times(1);
2939   ProcessAckPacket(&ack);
2940
2941   // Check that no packet is sent and the ack alarm isn't set.
2942   EXPECT_EQ(0u, writer_->frame_count());
2943   EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
2944   writer_->Reset();
2945
2946   // Send the same ack, but send both data and an ack together.
2947   ack = InitAckFrame(3, 0);
2948   NackPacket(1, &ack);
2949   EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
2950       .WillOnce(Return(SequenceNumberSet()));
2951   EXPECT_CALL(visitor_, OnCanWrite()).WillOnce(
2952       IgnoreResult(InvokeWithoutArgs(
2953           &connection_,
2954           &TestConnection::EnsureWritableAndSendStreamData5)));
2955   ProcessAckPacket(&ack);
2956
2957   // Check that ack is bundled with outgoing data and the delayed ack
2958   // alarm is reset.
2959   if (version() > QUIC_VERSION_15) {
2960     EXPECT_EQ(3u, writer_->frame_count());
2961     EXPECT_TRUE(writer_->stop_waiting());
2962   } else {
2963     EXPECT_EQ(2u, writer_->frame_count());
2964   }
2965   EXPECT_TRUE(writer_->ack());
2966   EXPECT_EQ(1u, writer_->stream_frames()->size());
2967   EXPECT_FALSE(connection_.GetAckAlarm()->IsSet());
2968 }
2969
2970 TEST_P(QuicConnectionTest, NoAckForClose) {
2971   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
2972   ProcessPacket(1);
2973   EXPECT_CALL(*send_algorithm_, OnPacketAcked(_, _)).Times(0);
2974   EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PEER_GOING_AWAY, true));
2975   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _)).Times(0);
2976   ProcessClosePacket(2, 0);
2977 }
2978
2979 TEST_P(QuicConnectionTest, SendWhenDisconnected) {
2980   EXPECT_TRUE(connection_.connected());
2981   EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PEER_GOING_AWAY, false));
2982   connection_.CloseConnection(QUIC_PEER_GOING_AWAY, false);
2983   EXPECT_FALSE(connection_.connected());
2984   QuicPacket* packet = ConstructDataPacket(1, 0, !kEntropyFlag);
2985   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, 1, _, _, _)).Times(0);
2986   connection_.SendPacket(
2987       ENCRYPTION_NONE, 1, packet, kTestEntropyHash, HAS_RETRANSMITTABLE_DATA);
2988 }
2989
2990 TEST_P(QuicConnectionTest, PublicReset) {
2991   QuicPublicResetPacket header;
2992   header.public_header.connection_id = connection_id_;
2993   header.public_header.reset_flag = true;
2994   header.public_header.version_flag = false;
2995   header.rejected_sequence_number = 10101;
2996   scoped_ptr<QuicEncryptedPacket> packet(
2997       framer_.BuildPublicResetPacket(header));
2998   EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PUBLIC_RESET, true));
2999   connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *packet);
3000 }
3001
3002 TEST_P(QuicConnectionTest, GoAway) {
3003   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3004
3005   QuicGoAwayFrame goaway;
3006   goaway.last_good_stream_id = 1;
3007   goaway.error_code = QUIC_PEER_GOING_AWAY;
3008   goaway.reason_phrase = "Going away.";
3009   EXPECT_CALL(visitor_, OnGoAway(_));
3010   ProcessGoAwayPacket(&goaway);
3011 }
3012
3013 TEST_P(QuicConnectionTest, WindowUpdate) {
3014   if (version() == QUIC_VERSION_13) {
3015     return;
3016   }
3017   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3018
3019   QuicWindowUpdateFrame window_update;
3020   window_update.stream_id = 3;
3021   window_update.byte_offset = 1234;
3022   EXPECT_CALL(visitor_, OnWindowUpdateFrames(_));
3023   ProcessFramePacket(QuicFrame(&window_update));
3024 }
3025
3026 TEST_P(QuicConnectionTest, Blocked) {
3027   if (version() == QUIC_VERSION_13) {
3028     return;
3029   }
3030   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3031
3032   QuicBlockedFrame blocked;
3033   blocked.stream_id = 3;
3034   EXPECT_CALL(visitor_, OnBlockedFrames(_));
3035   ProcessFramePacket(QuicFrame(&blocked));
3036 }
3037
3038 TEST_P(QuicConnectionTest, InvalidPacket) {
3039   EXPECT_CALL(visitor_,
3040               OnConnectionClosed(QUIC_INVALID_PACKET_HEADER, false));
3041   QuicEncryptedPacket encrypted(NULL, 0);
3042   connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), encrypted);
3043   // The connection close packet should have error details.
3044   ASSERT_TRUE(last_close() != NULL);
3045   EXPECT_EQ("Unable to read public flags.", last_close()->error_details);
3046 }
3047
3048 TEST_P(QuicConnectionTest, MissingPacketsBeforeLeastUnacked) {
3049   // Set the sequence number of the ack packet to be least unacked (4).
3050   creator_.set_sequence_number(3);
3051   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3052   if (version() > QUIC_VERSION_15) {
3053     QuicStopWaitingFrame frame = InitStopWaitingFrame(4);
3054     ProcessStopWaitingPacket(&frame);
3055   } else {
3056     QuicAckFrame ack = InitAckFrame(0, 4);
3057     ProcessAckPacket(&ack);
3058   }
3059   EXPECT_TRUE(outgoing_ack()->received_info.missing_packets.empty());
3060 }
3061
3062 TEST_P(QuicConnectionTest, ReceivedEntropyHashCalculation) {
3063   EXPECT_CALL(visitor_, OnStreamFrames(_)).WillRepeatedly(Return(true));
3064   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3065   ProcessDataPacket(1, 1, kEntropyFlag);
3066   ProcessDataPacket(4, 1, kEntropyFlag);
3067   ProcessDataPacket(3, 1, !kEntropyFlag);
3068   ProcessDataPacket(7, 1, kEntropyFlag);
3069   EXPECT_EQ(146u, outgoing_ack()->received_info.entropy_hash);
3070 }
3071
3072 TEST_P(QuicConnectionTest, ReceivedEntropyHashCalculationHalfFEC) {
3073   if (version() < QUIC_VERSION_15) {
3074     return;
3075   }
3076   // FEC packets should not change the entropy hash calculation.
3077   EXPECT_CALL(visitor_, OnStreamFrames(_)).WillRepeatedly(Return(true));
3078   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3079   ProcessDataPacket(1, 1, kEntropyFlag);
3080   ProcessFecPacket(4, 1, false, kEntropyFlag, NULL);
3081   ProcessDataPacket(3, 3, !kEntropyFlag);
3082   ProcessFecPacket(7, 3, false, kEntropyFlag, NULL);
3083   EXPECT_EQ(146u, outgoing_ack()->received_info.entropy_hash);
3084 }
3085
3086 TEST_P(QuicConnectionTest, UpdateEntropyForReceivedPackets) {
3087   EXPECT_CALL(visitor_, OnStreamFrames(_)).WillRepeatedly(Return(true));
3088   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3089   ProcessDataPacket(1, 1, kEntropyFlag);
3090   ProcessDataPacket(5, 1, kEntropyFlag);
3091   ProcessDataPacket(4, 1, !kEntropyFlag);
3092   EXPECT_EQ(34u, outgoing_ack()->received_info.entropy_hash);
3093   // Make 4th packet my least unacked, and update entropy for 2, 3 packets.
3094   creator_.set_sequence_number(5);
3095   QuicPacketEntropyHash six_packet_entropy_hash = 0;
3096   QuicPacketEntropyHash kRandomEntropyHash = 129u;
3097   if (version() > QUIC_VERSION_15) {
3098     QuicStopWaitingFrame frame = InitStopWaitingFrame(4);
3099     frame.entropy_hash = kRandomEntropyHash;
3100     if (ProcessStopWaitingPacket(&frame)) {
3101       six_packet_entropy_hash = 1 << 6;
3102     }
3103   } else {
3104     QuicAckFrame ack = InitAckFrame(0, 4);
3105     ack.sent_info.entropy_hash = kRandomEntropyHash;
3106     if (ProcessAckPacket(&ack)) {
3107       six_packet_entropy_hash = 1 << 6;
3108     }
3109   }
3110
3111   EXPECT_EQ((kRandomEntropyHash + (1 << 5) + six_packet_entropy_hash),
3112             outgoing_ack()->received_info.entropy_hash);
3113 }
3114
3115 TEST_P(QuicConnectionTest, UpdateEntropyHashUptoCurrentPacket) {
3116   EXPECT_CALL(visitor_, OnStreamFrames(_)).WillRepeatedly(Return(true));
3117   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3118   ProcessDataPacket(1, 1, kEntropyFlag);
3119   ProcessDataPacket(5, 1, !kEntropyFlag);
3120   ProcessDataPacket(22, 1, kEntropyFlag);
3121   EXPECT_EQ(66u, outgoing_ack()->received_info.entropy_hash);
3122   creator_.set_sequence_number(22);
3123   QuicPacketEntropyHash kRandomEntropyHash = 85u;
3124   // Current packet is the least unacked packet.
3125   QuicPacketEntropyHash ack_entropy_hash;
3126   if (version() > QUIC_VERSION_15) {
3127     QuicStopWaitingFrame frame = InitStopWaitingFrame(23);
3128     frame.entropy_hash = kRandomEntropyHash;
3129     ack_entropy_hash = ProcessStopWaitingPacket(&frame);
3130   } else {
3131     QuicAckFrame ack = InitAckFrame(0, 23);
3132     ack.sent_info.entropy_hash = kRandomEntropyHash;
3133     ack_entropy_hash = ProcessAckPacket(&ack);
3134   }
3135   EXPECT_EQ((kRandomEntropyHash + ack_entropy_hash),
3136             outgoing_ack()->received_info.entropy_hash);
3137   ProcessDataPacket(25, 1, kEntropyFlag);
3138   EXPECT_EQ((kRandomEntropyHash + ack_entropy_hash + (1 << (25 % 8))),
3139             outgoing_ack()->received_info.entropy_hash);
3140 }
3141
3142 TEST_P(QuicConnectionTest, EntropyCalculationForTruncatedAck) {
3143   EXPECT_CALL(visitor_, OnStreamFrames(_)).WillRepeatedly(Return(true));
3144   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3145   QuicPacketEntropyHash entropy[51];
3146   entropy[0] = 0;
3147   for (int i = 1; i < 51; ++i) {
3148     bool should_send = i % 10 != 0;
3149     bool entropy_flag = (i & (i - 1)) != 0;
3150     if (!should_send) {
3151       entropy[i] = entropy[i - 1];
3152       continue;
3153     }
3154     if (entropy_flag) {
3155       entropy[i] = entropy[i - 1] ^ (1 << (i % 8));
3156     } else {
3157       entropy[i] = entropy[i - 1];
3158     }
3159     ProcessDataPacket(i, 1, entropy_flag);
3160   }
3161   // Till 50 since 50th packet is not sent.
3162   for (int i = 1; i < 50; ++i) {
3163     EXPECT_EQ(entropy[i], QuicConnectionPeer::ReceivedEntropyHash(
3164         &connection_, i));
3165   }
3166 }
3167
3168 TEST_P(QuicConnectionTest, CheckSentEntropyHash) {
3169   creator_.set_sequence_number(1);
3170   SequenceNumberSet missing_packets;
3171   QuicPacketEntropyHash entropy_hash = 0;
3172   QuicPacketSequenceNumber max_sequence_number = 51;
3173   for (QuicPacketSequenceNumber i = 1; i <= max_sequence_number; ++i) {
3174     bool is_missing = i % 10 != 0;
3175     bool entropy_flag = (i & (i - 1)) != 0;
3176     QuicPacketEntropyHash packet_entropy_hash = 0;
3177     if (entropy_flag) {
3178       packet_entropy_hash = 1 << (i % 8);
3179     }
3180     QuicPacket* packet = ConstructDataPacket(i, 0, entropy_flag);
3181     connection_.SendPacket(
3182         ENCRYPTION_NONE, i, packet, packet_entropy_hash,
3183         HAS_RETRANSMITTABLE_DATA);
3184
3185     if (is_missing)  {
3186       missing_packets.insert(i);
3187       continue;
3188     }
3189
3190     entropy_hash ^= packet_entropy_hash;
3191   }
3192   EXPECT_TRUE(QuicConnectionPeer::IsValidEntropy(
3193       &connection_, max_sequence_number, missing_packets, entropy_hash))
3194       << "";
3195 }
3196
3197 TEST_P(QuicConnectionTest, ServerSendsVersionNegotiationPacket) {
3198   connection_.SetSupportedVersions(QuicSupportedVersions());
3199   framer_.set_version_for_tests(QUIC_VERSION_UNSUPPORTED);
3200
3201   QuicPacketHeader header;
3202   header.public_header.connection_id = connection_id_;
3203   header.public_header.reset_flag = false;
3204   header.public_header.version_flag = true;
3205   header.entropy_flag = false;
3206   header.fec_flag = false;
3207   header.packet_sequence_number = 12;
3208   header.fec_group = 0;
3209
3210   QuicFrames frames;
3211   QuicFrame frame(&frame1_);
3212   frames.push_back(frame);
3213   scoped_ptr<QuicPacket> packet(
3214       framer_.BuildUnsizedDataPacket(header, frames).packet);
3215   scoped_ptr<QuicEncryptedPacket> encrypted(
3216       framer_.EncryptPacket(ENCRYPTION_NONE, 12, *packet));
3217
3218   framer_.set_version(version());
3219   connection_.set_is_server(true);
3220   connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
3221   EXPECT_TRUE(writer_->version_negotiation_packet() != NULL);
3222
3223   size_t num_versions = arraysize(kSupportedQuicVersions);
3224   ASSERT_EQ(num_versions,
3225             writer_->version_negotiation_packet()->versions.size());
3226
3227   // We expect all versions in kSupportedQuicVersions to be
3228   // included in the packet.
3229   for (size_t i = 0; i < num_versions; ++i) {
3230     EXPECT_EQ(kSupportedQuicVersions[i],
3231               writer_->version_negotiation_packet()->versions[i]);
3232   }
3233 }
3234
3235 TEST_P(QuicConnectionTest, ServerSendsVersionNegotiationPacketSocketBlocked) {
3236   connection_.SetSupportedVersions(QuicSupportedVersions());
3237   framer_.set_version_for_tests(QUIC_VERSION_UNSUPPORTED);
3238
3239   QuicPacketHeader header;
3240   header.public_header.connection_id = connection_id_;
3241   header.public_header.reset_flag = false;
3242   header.public_header.version_flag = true;
3243   header.entropy_flag = false;
3244   header.fec_flag = false;
3245   header.packet_sequence_number = 12;
3246   header.fec_group = 0;
3247
3248   QuicFrames frames;
3249   QuicFrame frame(&frame1_);
3250   frames.push_back(frame);
3251   scoped_ptr<QuicPacket> packet(
3252       framer_.BuildUnsizedDataPacket(header, frames).packet);
3253   scoped_ptr<QuicEncryptedPacket> encrypted(
3254       framer_.EncryptPacket(ENCRYPTION_NONE, 12, *packet));
3255
3256   framer_.set_version(version());
3257   connection_.set_is_server(true);
3258   BlockOnNextWrite();
3259   connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
3260   EXPECT_EQ(0u, writer_->last_packet_size());
3261   EXPECT_TRUE(connection_.HasQueuedData());
3262
3263   writer_->SetWritable();
3264   connection_.OnCanWrite();
3265   EXPECT_TRUE(writer_->version_negotiation_packet() != NULL);
3266
3267   size_t num_versions = arraysize(kSupportedQuicVersions);
3268   ASSERT_EQ(num_versions,
3269             writer_->version_negotiation_packet()->versions.size());
3270
3271   // We expect all versions in kSupportedQuicVersions to be
3272   // included in the packet.
3273   for (size_t i = 0; i < num_versions; ++i) {
3274     EXPECT_EQ(kSupportedQuicVersions[i],
3275               writer_->version_negotiation_packet()->versions[i]);
3276   }
3277 }
3278
3279 TEST_P(QuicConnectionTest,
3280        ServerSendsVersionNegotiationPacketSocketBlockedDataBuffered) {
3281   connection_.SetSupportedVersions(QuicSupportedVersions());
3282   framer_.set_version_for_tests(QUIC_VERSION_UNSUPPORTED);
3283
3284   QuicPacketHeader header;
3285   header.public_header.connection_id = connection_id_;
3286   header.public_header.reset_flag = false;
3287   header.public_header.version_flag = true;
3288   header.entropy_flag = false;
3289   header.fec_flag = false;
3290   header.packet_sequence_number = 12;
3291   header.fec_group = 0;
3292
3293   QuicFrames frames;
3294   QuicFrame frame(&frame1_);
3295   frames.push_back(frame);
3296   scoped_ptr<QuicPacket> packet(
3297       framer_.BuildUnsizedDataPacket(header, frames).packet);
3298   scoped_ptr<QuicEncryptedPacket> encrypted(
3299       framer_.EncryptPacket(ENCRYPTION_NONE, 12, *packet));
3300
3301   framer_.set_version(version());
3302   connection_.set_is_server(true);
3303   BlockOnNextWrite();
3304   writer_->set_is_write_blocked_data_buffered(true);
3305   connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
3306   EXPECT_EQ(0u, writer_->last_packet_size());
3307   EXPECT_FALSE(connection_.HasQueuedData());
3308 }
3309
3310 TEST_P(QuicConnectionTest, ClientHandlesVersionNegotiation) {
3311   // Start out with some unsupported version.
3312   QuicConnectionPeer::GetFramer(&connection_)->set_version_for_tests(
3313       QUIC_VERSION_UNSUPPORTED);
3314
3315   QuicPacketHeader header;
3316   header.public_header.connection_id = connection_id_;
3317   header.public_header.reset_flag = false;
3318   header.public_header.version_flag = true;
3319   header.entropy_flag = false;
3320   header.fec_flag = false;
3321   header.packet_sequence_number = 12;
3322   header.fec_group = 0;
3323
3324   QuicVersionVector supported_versions;
3325   for (size_t i = 0; i < arraysize(kSupportedQuicVersions); ++i) {
3326     supported_versions.push_back(kSupportedQuicVersions[i]);
3327   }
3328
3329   // Send a version negotiation packet.
3330   scoped_ptr<QuicEncryptedPacket> encrypted(
3331       framer_.BuildVersionNegotiationPacket(
3332           header.public_header, supported_versions));
3333   connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
3334
3335   // Now force another packet.  The connection should transition into
3336   // NEGOTIATED_VERSION state and tell the packet creator to StopSendingVersion.
3337   header.public_header.version_flag = false;
3338   QuicFrames frames;
3339   QuicFrame frame(&frame1_);
3340   frames.push_back(frame);
3341   scoped_ptr<QuicPacket> packet(
3342       framer_.BuildUnsizedDataPacket(header, frames).packet);
3343   encrypted.reset(framer_.EncryptPacket(ENCRYPTION_NONE, 12, *packet));
3344   EXPECT_CALL(visitor_, OnStreamFrames(_)).Times(1);
3345   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3346   connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
3347
3348   ASSERT_FALSE(QuicPacketCreatorPeer::SendVersionInPacket(
3349       QuicConnectionPeer::GetPacketCreator(&connection_)));
3350 }
3351
3352 TEST_P(QuicConnectionTest, BadVersionNegotiation) {
3353   QuicPacketHeader header;
3354   header.public_header.connection_id = connection_id_;
3355   header.public_header.reset_flag = false;
3356   header.public_header.version_flag = true;
3357   header.entropy_flag = false;
3358   header.fec_flag = false;
3359   header.packet_sequence_number = 12;
3360   header.fec_group = 0;
3361
3362   QuicVersionVector supported_versions;
3363   for (size_t i = 0; i < arraysize(kSupportedQuicVersions); ++i) {
3364     supported_versions.push_back(kSupportedQuicVersions[i]);
3365   }
3366
3367   // Send a version negotiation packet with the version the client started with.
3368   // It should be rejected.
3369   EXPECT_CALL(visitor_,
3370               OnConnectionClosed(QUIC_INVALID_VERSION_NEGOTIATION_PACKET,
3371                                  false));
3372   scoped_ptr<QuicEncryptedPacket> encrypted(
3373       framer_.BuildVersionNegotiationPacket(
3374           header.public_header, supported_versions));
3375   connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
3376 }
3377
3378 TEST_P(QuicConnectionTest, CheckSendStats) {
3379   EXPECT_CALL(*send_algorithm_,
3380               OnPacketSent(_, _, _, NOT_RETRANSMISSION, _));
3381   connection_.SendStreamDataWithString(3, "first", 0, !kFin, NULL);
3382   size_t first_packet_size = last_sent_packet_size();
3383
3384   EXPECT_CALL(*send_algorithm_,
3385               OnPacketSent(_, _, _, NOT_RETRANSMISSION, _));
3386   connection_.SendStreamDataWithString(5, "second", 0, !kFin, NULL);
3387   size_t second_packet_size = last_sent_packet_size();
3388
3389   // 2 retransmissions due to rto, 1 due to explicit nack.
3390   EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
3391   EXPECT_CALL(*send_algorithm_,
3392               OnPacketSent(_, _, _, RTO_RETRANSMISSION, _)).Times(2);
3393   EXPECT_CALL(*send_algorithm_,
3394               OnPacketSent(_, _, _, LOSS_RETRANSMISSION, _));
3395   EXPECT_CALL(*send_algorithm_, OnPacketAbandoned(_, _)).Times(1);
3396
3397   // Retransmit due to RTO.
3398   clock_.AdvanceTime(QuicTime::Delta::FromSeconds(10));
3399   connection_.GetRetransmissionAlarm()->Fire();
3400
3401   // Retransmit due to explicit nacks.
3402   QuicAckFrame nack_three = InitAckFrame(4, 0);
3403   NackPacket(3, &nack_three);
3404   NackPacket(1, &nack_three);
3405   SequenceNumberSet lost_packets;
3406   lost_packets.insert(1);
3407   lost_packets.insert(3);
3408   EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
3409       .WillOnce(Return(lost_packets));
3410   EXPECT_CALL(*send_algorithm_, UpdateRtt(_));
3411   EXPECT_CALL(*send_algorithm_, OnPacketAcked(4, _)).Times(1);
3412   EXPECT_CALL(*send_algorithm_, OnPacketLost(_, _)).Times(2);
3413   EXPECT_CALL(visitor_, OnCanWrite()).Times(2);
3414   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3415   ProcessAckPacket(&nack_three);
3416
3417   EXPECT_CALL(*send_algorithm_, BandwidthEstimate()).WillOnce(
3418       Return(QuicBandwidth::Zero()));
3419
3420   const QuicConnectionStats& stats = connection_.GetStats();
3421   EXPECT_EQ(3 * first_packet_size + 2 * second_packet_size - kQuicVersionSize,
3422             stats.bytes_sent);
3423   EXPECT_EQ(5u, stats.packets_sent);
3424   EXPECT_EQ(2 * first_packet_size + second_packet_size - kQuicVersionSize,
3425             stats.bytes_retransmitted);
3426   EXPECT_EQ(3u, stats.packets_retransmitted);
3427   EXPECT_EQ(1u, stats.rto_count);
3428 }
3429
3430 TEST_P(QuicConnectionTest, CheckReceiveStats) {
3431   if (version() < QUIC_VERSION_15) {
3432     return;
3433   }
3434   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3435
3436   size_t received_bytes = 0;
3437   received_bytes += ProcessFecProtectedPacket(1, false, !kEntropyFlag);
3438   received_bytes += ProcessFecProtectedPacket(3, false, !kEntropyFlag);
3439   // Should be counted against dropped packets.
3440   received_bytes += ProcessDataPacket(3, 1, !kEntropyFlag);
3441   received_bytes += ProcessFecPacket(4, 1, true, !kEntropyFlag, NULL);
3442
3443   EXPECT_CALL(*send_algorithm_, BandwidthEstimate()).WillOnce(
3444       Return(QuicBandwidth::Zero()));
3445
3446   const QuicConnectionStats& stats = connection_.GetStats();
3447   EXPECT_EQ(received_bytes, stats.bytes_received);
3448   EXPECT_EQ(4u, stats.packets_received);
3449
3450   EXPECT_EQ(1u, stats.packets_revived);
3451   EXPECT_EQ(1u, stats.packets_dropped);
3452 }
3453
3454 TEST_P(QuicConnectionTest, TestFecGroupLimits) {
3455   // Create and return a group for 1.
3456   ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 1) != NULL);
3457
3458   // Create and return a group for 2.
3459   ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 2) != NULL);
3460
3461   // Create and return a group for 4.  This should remove 1 but not 2.
3462   ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 4) != NULL);
3463   ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 1) == NULL);
3464   ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 2) != NULL);
3465
3466   // Create and return a group for 3.  This will kill off 2.
3467   ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 3) != NULL);
3468   ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 2) == NULL);
3469
3470   // Verify that adding 5 kills off 3, despite 4 being created before 3.
3471   ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 5) != NULL);
3472   ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 4) != NULL);
3473   ASSERT_TRUE(QuicConnectionPeer::GetFecGroup(&connection_, 3) == NULL);
3474 }
3475
3476 TEST_P(QuicConnectionTest, ProcessFramesIfPacketClosedConnection) {
3477   // Construct a packet with stream frame and connection close frame.
3478   header_.public_header.connection_id = connection_id_;
3479   header_.packet_sequence_number = 1;
3480   header_.public_header.reset_flag = false;
3481   header_.public_header.version_flag = false;
3482   header_.entropy_flag = false;
3483   header_.fec_flag = false;
3484   header_.fec_group = 0;
3485
3486   QuicConnectionCloseFrame qccf;
3487   qccf.error_code = QUIC_PEER_GOING_AWAY;
3488   QuicFrame close_frame(&qccf);
3489   QuicFrame stream_frame(&frame1_);
3490
3491   QuicFrames frames;
3492   frames.push_back(stream_frame);
3493   frames.push_back(close_frame);
3494   scoped_ptr<QuicPacket> packet(
3495       framer_.BuildUnsizedDataPacket(header_, frames).packet);
3496   EXPECT_TRUE(NULL != packet.get());
3497   scoped_ptr<QuicEncryptedPacket> encrypted(framer_.EncryptPacket(
3498       ENCRYPTION_NONE, 1, *packet));
3499
3500   EXPECT_CALL(visitor_, OnConnectionClosed(QUIC_PEER_GOING_AWAY, true));
3501   EXPECT_CALL(visitor_, OnStreamFrames(_)).WillOnce(Return(true));
3502   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3503
3504   connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
3505 }
3506
3507 TEST_P(QuicConnectionTest, DontProcessStreamFrameAndIgnoreCloseFrame) {
3508   // Construct a packet with stream frame, ack frame,
3509   // and connection close frame.
3510   header_.public_header.connection_id = connection_id_;
3511   header_.packet_sequence_number = 1;
3512   header_.public_header.reset_flag = false;
3513   header_.public_header.version_flag = false;
3514   header_.entropy_flag = false;
3515   header_.fec_flag = false;
3516   header_.fec_group = 0;
3517
3518   QuicConnectionCloseFrame qccf;
3519   qccf.error_code = QUIC_PEER_GOING_AWAY;
3520   QuicFrame close_frame(&qccf);
3521   QuicFrame stream_frame(&frame1_);
3522
3523   QuicFrames frames;
3524   frames.push_back(stream_frame);
3525   frames.push_back(close_frame);
3526   scoped_ptr<QuicPacket> packet(
3527       framer_.BuildUnsizedDataPacket(header_, frames).packet);
3528   EXPECT_TRUE(NULL != packet.get());
3529   scoped_ptr<QuicEncryptedPacket> encrypted(framer_.EncryptPacket(
3530       ENCRYPTION_NONE, 1, *packet));
3531
3532   EXPECT_CALL(visitor_, OnStreamFrames(_)).WillOnce(Return(false));
3533   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3534
3535   connection_.ProcessUdpPacket(IPEndPoint(), IPEndPoint(), *encrypted);
3536 }
3537
3538 TEST_P(QuicConnectionTest, SelectMutualVersion) {
3539   connection_.SetSupportedVersions(QuicSupportedVersions());
3540   // Set the connection to speak the lowest quic version.
3541   connection_.set_version(QuicVersionMin());
3542   EXPECT_EQ(QuicVersionMin(), connection_.version());
3543
3544   // Pass in available versions which includes a higher mutually supported
3545   // version.  The higher mutually supported version should be selected.
3546   QuicVersionVector supported_versions;
3547   for (size_t i = 0; i < arraysize(kSupportedQuicVersions); ++i) {
3548     supported_versions.push_back(kSupportedQuicVersions[i]);
3549   }
3550   EXPECT_TRUE(connection_.SelectMutualVersion(supported_versions));
3551   EXPECT_EQ(QuicVersionMax(), connection_.version());
3552
3553   // Expect that the lowest version is selected.
3554   // Ensure the lowest supported version is less than the max, unless they're
3555   // the same.
3556   EXPECT_LE(QuicVersionMin(), QuicVersionMax());
3557   QuicVersionVector lowest_version_vector;
3558   lowest_version_vector.push_back(QuicVersionMin());
3559   EXPECT_TRUE(connection_.SelectMutualVersion(lowest_version_vector));
3560   EXPECT_EQ(QuicVersionMin(), connection_.version());
3561
3562   // Shouldn't be able to find a mutually supported version.
3563   QuicVersionVector unsupported_version;
3564   unsupported_version.push_back(QUIC_VERSION_UNSUPPORTED);
3565   EXPECT_FALSE(connection_.SelectMutualVersion(unsupported_version));
3566 }
3567
3568 TEST_P(QuicConnectionTest, ConnectionCloseWhenWritable) {
3569   EXPECT_FALSE(writer_->IsWriteBlocked());
3570
3571   // Send a packet.
3572   connection_.SendStreamDataWithString(1, "foo", 0, !kFin, NULL);
3573   EXPECT_EQ(0u, connection_.NumQueuedPackets());
3574   EXPECT_EQ(1u, writer_->packets_write_attempts());
3575
3576   TriggerConnectionClose();
3577   EXPECT_EQ(2u, writer_->packets_write_attempts());
3578 }
3579
3580 TEST_P(QuicConnectionTest, ConnectionCloseGettingWriteBlocked) {
3581   BlockOnNextWrite();
3582   TriggerConnectionClose();
3583   EXPECT_EQ(1u, writer_->packets_write_attempts());
3584   EXPECT_TRUE(writer_->IsWriteBlocked());
3585 }
3586
3587 TEST_P(QuicConnectionTest, ConnectionCloseWhenWriteBlocked) {
3588   BlockOnNextWrite();
3589   connection_.SendStreamDataWithString(1, "foo", 0, !kFin, NULL);
3590   EXPECT_EQ(1u, connection_.NumQueuedPackets());
3591   EXPECT_EQ(1u, writer_->packets_write_attempts());
3592   EXPECT_TRUE(writer_->IsWriteBlocked());
3593   TriggerConnectionClose();
3594   EXPECT_EQ(1u, writer_->packets_write_attempts());
3595 }
3596
3597 TEST_P(QuicConnectionTest, AckNotifierTriggerCallback) {
3598   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3599
3600   // Create a delegate which we expect to be called.
3601   scoped_refptr<MockAckNotifierDelegate> delegate(new MockAckNotifierDelegate);
3602   EXPECT_CALL(*delegate, OnAckNotification(_, _, _, _)).Times(1);
3603
3604   // Send some data, which will register the delegate to be notified.
3605   connection_.SendStreamDataWithString(1, "foo", 0, !kFin, delegate.get());
3606
3607   // Process an ACK from the server which should trigger the callback.
3608   EXPECT_CALL(*send_algorithm_, UpdateRtt(_));
3609   EXPECT_CALL(*send_algorithm_, OnPacketAcked(_, _)).Times(1);
3610   QuicAckFrame frame = InitAckFrame(1, 0);
3611   ProcessAckPacket(&frame);
3612 }
3613
3614 TEST_P(QuicConnectionTest, AckNotifierFailToTriggerCallback) {
3615   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3616
3617   // Create a delegate which we don't expect to be called.
3618   scoped_refptr<MockAckNotifierDelegate> delegate(new MockAckNotifierDelegate);
3619   EXPECT_CALL(*delegate, OnAckNotification(_, _, _, _)).Times(0);
3620
3621   EXPECT_CALL(*send_algorithm_, UpdateRtt(_));
3622   EXPECT_CALL(*send_algorithm_, OnPacketAcked(_, _)).Times(2);
3623
3624   // Send some data, which will register the delegate to be notified. This will
3625   // not be ACKed and so the delegate should never be called.
3626   connection_.SendStreamDataWithString(1, "foo", 0, !kFin, delegate.get());
3627
3628   // Send some other data which we will ACK.
3629   connection_.SendStreamDataWithString(1, "foo", 0, !kFin, NULL);
3630   connection_.SendStreamDataWithString(1, "bar", 0, !kFin, NULL);
3631
3632   // Now we receive ACK for packets 2 and 3, but importantly missing packet 1
3633   // which we registered to be notified about.
3634   QuicAckFrame frame = InitAckFrame(3, 0);
3635   NackPacket(1, &frame);
3636   SequenceNumberSet lost_packets;
3637   lost_packets.insert(1);
3638   EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
3639       .WillOnce(Return(lost_packets));
3640   EXPECT_CALL(*send_algorithm_, OnPacketLost(1, _));
3641   EXPECT_CALL(*send_algorithm_, OnPacketAbandoned(1, _));
3642   ProcessAckPacket(&frame);
3643 }
3644
3645 TEST_P(QuicConnectionTest, AckNotifierCallbackAfterRetransmission) {
3646   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3647
3648   // Create a delegate which we expect to be called.
3649   scoped_refptr<MockAckNotifierDelegate> delegate(new MockAckNotifierDelegate);
3650   EXPECT_CALL(*delegate, OnAckNotification(_, _, _, _)).Times(1);
3651
3652   // Send four packets, and register to be notified on ACK of packet 2.
3653   connection_.SendStreamDataWithString(3, "foo", 0, !kFin, NULL);
3654   connection_.SendStreamDataWithString(3, "bar", 0, !kFin, delegate.get());
3655   connection_.SendStreamDataWithString(3, "baz", 0, !kFin, NULL);
3656   connection_.SendStreamDataWithString(3, "qux", 0, !kFin, NULL);
3657
3658   // Now we receive ACK for packets 1, 3, and 4 and lose 2.
3659   QuicAckFrame frame = InitAckFrame(4, 0);
3660   NackPacket(2, &frame);
3661   SequenceNumberSet lost_packets;
3662   lost_packets.insert(2);
3663   EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
3664       .WillOnce(Return(lost_packets));
3665   EXPECT_CALL(*send_algorithm_, UpdateRtt(_));
3666   EXPECT_CALL(*send_algorithm_, OnPacketAcked(_, _)).Times(3);
3667   EXPECT_CALL(*send_algorithm_, OnPacketLost(2, _));
3668   EXPECT_CALL(*send_algorithm_, OnPacketAbandoned(2, _));
3669   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3670   ProcessAckPacket(&frame);
3671
3672   // Now we get an ACK for packet 5 (retransmitted packet 2), which should
3673   // trigger the callback.
3674   EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
3675       .WillRepeatedly(Return(SequenceNumberSet()));
3676   EXPECT_CALL(*send_algorithm_, UpdateRtt(_));
3677   EXPECT_CALL(*send_algorithm_, OnPacketAcked(5, _));
3678   QuicAckFrame second_ack_frame = InitAckFrame(5, 0);
3679   ProcessAckPacket(&second_ack_frame);
3680 }
3681
3682 // AckNotifierCallback is triggered by the ack of a packet that timed
3683 // out and was retransmitted, even though the retransmission has a
3684 // different sequence number.
3685 TEST_P(QuicConnectionTest, AckNotifierCallbackForAckAfterRTO) {
3686   InSequence s;
3687
3688   // Create a delegate which we expect to be called.
3689   scoped_refptr<MockAckNotifierDelegate> delegate(
3690       new StrictMock<MockAckNotifierDelegate>);
3691
3692   QuicTime default_retransmission_time = clock_.ApproximateNow().Add(
3693       DefaultRetransmissionTime());
3694   connection_.SendStreamDataWithString(3, "foo", 0, !kFin, delegate.get());
3695   EXPECT_EQ(1u, outgoing_ack()->sent_info.least_unacked);
3696
3697   EXPECT_EQ(1u, last_header()->packet_sequence_number);
3698   EXPECT_EQ(default_retransmission_time,
3699             connection_.GetRetransmissionAlarm()->deadline());
3700   // Simulate the retransmission alarm firing.
3701   clock_.AdvanceTime(DefaultRetransmissionTime());
3702   EXPECT_CALL(*send_algorithm_, OnRetransmissionTimeout(true));
3703   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, 2u, _, _, _));
3704   connection_.GetRetransmissionAlarm()->Fire();
3705   EXPECT_EQ(2u, last_header()->packet_sequence_number);
3706   // We do not raise the high water mark yet.
3707   EXPECT_EQ(1u, outgoing_ack()->sent_info.least_unacked);
3708
3709   // Ack the original packet.
3710   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3711   EXPECT_CALL(*send_algorithm_, UpdateRtt(_));
3712   EXPECT_CALL(*delegate, OnAckNotification(1, _, 1, _));
3713   QuicAckFrame ack_frame = InitAckFrame(1, 0);
3714   ProcessAckPacket(&ack_frame);
3715
3716   // Delegate is not notified again when the retransmit is acked.
3717   EXPECT_CALL(*send_algorithm_, UpdateRtt(_));
3718   EXPECT_CALL(*send_algorithm_, OnPacketAcked(2, _));
3719   QuicAckFrame second_ack_frame = InitAckFrame(2, 0);
3720   ProcessAckPacket(&second_ack_frame);
3721 }
3722
3723 // AckNotifierCallback is triggered by the ack of a packet that was
3724 // previously nacked, even though the retransmission has a different
3725 // sequence number.
3726 TEST_P(QuicConnectionTest, AckNotifierCallbackForAckOfNackedPacket) {
3727   InSequence s;
3728
3729   // Create a delegate which we expect to be called.
3730   scoped_refptr<MockAckNotifierDelegate> delegate(
3731       new StrictMock<MockAckNotifierDelegate>);
3732
3733   // Send four packets, and register to be notified on ACK of packet 2.
3734   connection_.SendStreamDataWithString(3, "foo", 0, !kFin, NULL);
3735   connection_.SendStreamDataWithString(3, "bar", 0, !kFin, delegate.get());
3736   connection_.SendStreamDataWithString(3, "baz", 0, !kFin, NULL);
3737   connection_.SendStreamDataWithString(3, "qux", 0, !kFin, NULL);
3738
3739   // Now we receive ACK for packets 1, 3, and 4 and lose 2.
3740   QuicAckFrame frame = InitAckFrame(4, 0);
3741   NackPacket(2, &frame);
3742   SequenceNumberSet lost_packets;
3743   lost_packets.insert(2);
3744   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3745   EXPECT_CALL(*send_algorithm_, UpdateRtt(_));
3746   EXPECT_CALL(*send_algorithm_, OnPacketAcked(1, _));
3747   EXPECT_CALL(*send_algorithm_, OnPacketAcked(3, _));
3748   EXPECT_CALL(*send_algorithm_, OnPacketAcked(4, _));
3749   EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
3750       .WillOnce(Return(lost_packets));
3751   EXPECT_CALL(*send_algorithm_, OnPacketLost(2, _));
3752   EXPECT_CALL(*send_algorithm_, OnPacketAbandoned(2, _));
3753   EXPECT_CALL(*send_algorithm_, OnPacketSent(_, _, _, _, _));
3754   ProcessAckPacket(&frame);
3755
3756   // Now we get an ACK for packet 2, which was previously nacked.
3757   SequenceNumberSet no_lost_packets;
3758   EXPECT_CALL(*delegate, OnAckNotification(1, _, 1, _));
3759   EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
3760       .WillOnce(Return(no_lost_packets));
3761   QuicAckFrame second_ack_frame = InitAckFrame(4, 0);
3762   ProcessAckPacket(&second_ack_frame);
3763
3764   // Verify that the delegate is not notified again when the
3765   // retransmit is acked.
3766   EXPECT_CALL(*send_algorithm_, UpdateRtt(_));
3767   EXPECT_CALL(*send_algorithm_, OnPacketAcked(5, _));
3768   EXPECT_CALL(*loss_algorithm_, DetectLostPackets(_, _, _, _))
3769       .WillOnce(Return(no_lost_packets));
3770   QuicAckFrame third_ack_frame = InitAckFrame(5, 0);
3771   ProcessAckPacket(&third_ack_frame);
3772 }
3773
3774 // TODO(rjshade): Add a similar test that FEC recovery on peer (and resulting
3775 //                ACK) triggers notification on our end.
3776 TEST_P(QuicConnectionTest, AckNotifierCallbackAfterFECRecovery) {
3777   if (version() < QUIC_VERSION_15) {
3778     return;
3779   }
3780   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3781   EXPECT_CALL(visitor_, OnCanWrite());
3782
3783   // Create a delegate which we expect to be called.
3784   scoped_refptr<MockAckNotifierDelegate> delegate(new MockAckNotifierDelegate);
3785   EXPECT_CALL(*delegate, OnAckNotification(_, _, _, _)).Times(1);
3786
3787   // Expect ACKs for 1 packet.
3788   EXPECT_CALL(*send_algorithm_, UpdateRtt(_));
3789   EXPECT_CALL(*send_algorithm_, OnPacketAcked(_, _)).Times(1);
3790
3791   // Send one packet, and register to be notified on ACK.
3792   connection_.SendStreamDataWithString(1, "foo", 0, !kFin, delegate.get());
3793
3794   // Ack packet gets dropped, but we receive an FEC packet that covers it.
3795   // Should recover the Ack packet and trigger the notification callback.
3796   QuicFrames frames;
3797
3798   QuicAckFrame ack_frame = InitAckFrame(1, 0);
3799   frames.push_back(QuicFrame(&ack_frame));
3800
3801   // Dummy stream frame to satisfy expectations set elsewhere.
3802   frames.push_back(QuicFrame(&frame1_));
3803
3804   QuicPacketHeader ack_header;
3805   ack_header.public_header.connection_id = connection_id_;
3806   ack_header.public_header.reset_flag = false;
3807   ack_header.public_header.version_flag = false;
3808   ack_header.entropy_flag = !kEntropyFlag;
3809   ack_header.fec_flag = true;
3810   ack_header.packet_sequence_number = 1;
3811   ack_header.is_in_fec_group = IN_FEC_GROUP;
3812   ack_header.fec_group = 1;
3813
3814   QuicPacket* packet =
3815       framer_.BuildUnsizedDataPacket(ack_header, frames).packet;
3816
3817   // Take the packet which contains the ACK frame, and construct and deliver an
3818   // FEC packet which allows the ACK packet to be recovered.
3819   ProcessFecPacket(2, 1, true, !kEntropyFlag, packet);
3820 }
3821
3822 class MockQuicConnectionDebugVisitor
3823     : public QuicConnectionDebugVisitorInterface {
3824  public:
3825   MOCK_METHOD1(OnFrameAddedToPacket,
3826                void(const QuicFrame&));
3827
3828   MOCK_METHOD5(OnPacketSent,
3829                void(QuicPacketSequenceNumber,
3830                     EncryptionLevel,
3831                     TransmissionType,
3832                     const QuicEncryptedPacket&,
3833                     WriteResult));
3834
3835   MOCK_METHOD2(OnPacketRetransmitted,
3836                void(QuicPacketSequenceNumber,
3837                     QuicPacketSequenceNumber));
3838
3839   MOCK_METHOD3(OnPacketReceived,
3840                void(const IPEndPoint&,
3841                     const IPEndPoint&,
3842                     const QuicEncryptedPacket&));
3843
3844   MOCK_METHOD1(OnProtocolVersionMismatch,
3845                void(QuicVersion));
3846
3847   MOCK_METHOD1(OnPacketHeader,
3848                void(const QuicPacketHeader& header));
3849
3850   MOCK_METHOD1(OnStreamFrame,
3851                void(const QuicStreamFrame&));
3852
3853   MOCK_METHOD1(OnAckFrame,
3854                void(const QuicAckFrame& frame));
3855
3856   MOCK_METHOD1(OnCongestionFeedbackFrame,
3857                void(const QuicCongestionFeedbackFrame&));
3858
3859   MOCK_METHOD1(OnStopWaitingFrame,
3860                void(const QuicStopWaitingFrame&));
3861
3862   MOCK_METHOD1(OnRstStreamFrame,
3863                void(const QuicRstStreamFrame&));
3864
3865   MOCK_METHOD1(OnConnectionCloseFrame,
3866                void(const QuicConnectionCloseFrame&));
3867
3868   MOCK_METHOD1(OnPublicResetPacket,
3869                void(const QuicPublicResetPacket&));
3870
3871   MOCK_METHOD1(OnVersionNegotiationPacket,
3872                void(const QuicVersionNegotiationPacket&));
3873
3874   MOCK_METHOD2(OnRevivedPacket,
3875                void(const QuicPacketHeader&, StringPiece payload));
3876 };
3877
3878 TEST_P(QuicConnectionTest, OnPacketHeaderDebugVisitor) {
3879   QuicPacketHeader header;
3880
3881   scoped_ptr<MockQuicConnectionDebugVisitor>
3882       debug_visitor(new StrictMock<MockQuicConnectionDebugVisitor>);
3883   connection_.set_debug_visitor(debug_visitor.get());
3884   EXPECT_CALL(*debug_visitor, OnPacketHeader(Ref(header))).Times(1);
3885   connection_.OnPacketHeader(header);
3886 }
3887
3888 TEST_P(QuicConnectionTest, Pacing) {
3889   ValueRestore<bool> old_flag(&FLAGS_enable_quic_pacing, true);
3890
3891   TestConnection server(connection_id_, IPEndPoint(), helper_.get(),
3892                         writer_.get(), true, version());
3893   TestConnection client(connection_id_, IPEndPoint(), helper_.get(),
3894                         writer_.get(), false, version());
3895   EXPECT_TRUE(client.sent_packet_manager().using_pacing());
3896   EXPECT_FALSE(server.sent_packet_manager().using_pacing());
3897 }
3898
3899 TEST_P(QuicConnectionTest, ControlFramesInstigateAcks) {
3900   if (version() == QUIC_VERSION_13) {
3901     return;
3902   }
3903   EXPECT_CALL(visitor_, OnSuccessfulVersionNegotiation(_));
3904
3905   // Send a WINDOW_UPDATE frame.
3906   QuicWindowUpdateFrame window_update;
3907   window_update.stream_id = 3;
3908   window_update.byte_offset = 1234;
3909   EXPECT_CALL(visitor_, OnWindowUpdateFrames(_));
3910   ProcessFramePacket(QuicFrame(&window_update));
3911
3912   // Ensure that this has caused the ACK alarm to be set.
3913   QuicAlarm* ack_alarm = QuicConnectionPeer::GetAckAlarm(&connection_);
3914   EXPECT_TRUE(ack_alarm->IsSet());
3915
3916   // Cancel alarm, and try again with BLOCKED frame.
3917   ack_alarm->Cancel();
3918   QuicBlockedFrame blocked;
3919   blocked.stream_id = 3;
3920   EXPECT_CALL(visitor_, OnBlockedFrames(_));
3921   ProcessFramePacket(QuicFrame(&blocked));
3922   EXPECT_TRUE(ack_alarm->IsSet());
3923 }
3924
3925 }  // namespace
3926 }  // namespace test
3927 }  // namespace net