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