Roll src/third_party/WebKit d9c6159:8139f33 (svn 201974:201975)
[chromium-blink-merge.git] / net / quic / test_tools / quic_test_utils.cc
blobcab2bf72098cafece9b708034a1e5e9729747cbd
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.
5 #include "net/quic/test_tools/quic_test_utils.h"
7 #include "base/sha1.h"
8 #include "base/stl_util.h"
9 #include "base/strings/string_number_conversions.h"
10 #include "net/quic/crypto/crypto_framer.h"
11 #include "net/quic/crypto/crypto_handshake.h"
12 #include "net/quic/crypto/crypto_utils.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/quic_data_writer.h"
17 #include "net/quic/quic_framer.h"
18 #include "net/quic/quic_packet_creator.h"
19 #include "net/quic/quic_utils.h"
20 #include "net/quic/test_tools/crypto_test_utils.h"
21 #include "net/quic/test_tools/quic_connection_peer.h"
22 #include "net/spdy/spdy_frame_builder.h"
23 #include "net/tools/quic/quic_per_connection_packet_writer.h"
25 using base::StringPiece;
26 using std::max;
27 using std::min;
28 using std::string;
29 using testing::Invoke;
30 using testing::_;
32 namespace net {
33 namespace test {
34 namespace {
36 // No-op alarm implementation used by MockHelper.
37 class TestAlarm : public QuicAlarm {
38 public:
39 explicit TestAlarm(QuicAlarm::Delegate* delegate)
40 : QuicAlarm(delegate) {
43 void SetImpl() override {}
44 void CancelImpl() override {}
47 } // namespace
49 QuicAckFrame MakeAckFrame(QuicPacketNumber largest_observed) {
50 QuicAckFrame ack;
51 ack.largest_observed = largest_observed;
52 ack.entropy_hash = 0;
53 return ack;
56 QuicAckFrame MakeAckFrameWithNackRanges(size_t num_nack_ranges,
57 QuicPacketNumber least_unacked) {
58 QuicAckFrame ack = MakeAckFrame(2 * num_nack_ranges + least_unacked);
59 // Add enough missing packets to get num_nack_ranges nack ranges.
60 for (QuicPacketNumber i = 1; i < 2 * num_nack_ranges; i += 2) {
61 ack.missing_packets.insert(least_unacked + i);
63 return ack;
66 QuicPacket* BuildUnsizedDataPacket(QuicFramer* framer,
67 const QuicPacketHeader& header,
68 const QuicFrames& frames) {
69 const size_t max_plaintext_size = framer->GetMaxPlaintextSize(kMaxPacketSize);
70 size_t packet_size = GetPacketHeaderSize(header);
71 for (size_t i = 0; i < frames.size(); ++i) {
72 DCHECK_LE(packet_size, max_plaintext_size);
73 bool first_frame = i == 0;
74 bool last_frame = i == frames.size() - 1;
75 const size_t frame_size = framer->GetSerializedFrameLength(
76 frames[i], max_plaintext_size - packet_size, first_frame, last_frame,
77 header.is_in_fec_group, header.public_header.packet_number_length);
78 DCHECK(frame_size);
79 packet_size += frame_size;
81 return BuildUnsizedDataPacket(framer, header, frames, packet_size);
84 QuicPacket* BuildUnsizedDataPacket(QuicFramer* framer,
85 const QuicPacketHeader& header,
86 const QuicFrames& frames,
87 size_t packet_size) {
88 char* buffer = new char[packet_size];
89 scoped_ptr<QuicPacket> packet(
90 framer->BuildDataPacket(header, frames, buffer, packet_size));
91 DCHECK(packet.get() != nullptr);
92 // Now I have to re-construct the data packet with data ownership.
93 return new QuicPacket(buffer, packet->length(), true,
94 header.public_header.connection_id_length,
95 header.public_header.version_flag,
96 header.public_header.packet_number_length);
99 uint64 SimpleRandom::RandUint64() {
100 unsigned char hash[base::kSHA1Length];
101 base::SHA1HashBytes(reinterpret_cast<unsigned char*>(&seed_), sizeof(seed_),
102 hash);
103 memcpy(&seed_, hash, sizeof(seed_));
104 return seed_;
107 MockFramerVisitor::MockFramerVisitor() {
108 // By default, we want to accept packets.
109 ON_CALL(*this, OnProtocolVersionMismatch(_))
110 .WillByDefault(testing::Return(false));
112 // By default, we want to accept packets.
113 ON_CALL(*this, OnUnauthenticatedHeader(_))
114 .WillByDefault(testing::Return(true));
116 ON_CALL(*this, OnUnauthenticatedPublicHeader(_))
117 .WillByDefault(testing::Return(true));
119 ON_CALL(*this, OnPacketHeader(_))
120 .WillByDefault(testing::Return(true));
122 ON_CALL(*this, OnStreamFrame(_))
123 .WillByDefault(testing::Return(true));
125 ON_CALL(*this, OnAckFrame(_))
126 .WillByDefault(testing::Return(true));
128 ON_CALL(*this, OnStopWaitingFrame(_))
129 .WillByDefault(testing::Return(true));
131 ON_CALL(*this, OnPingFrame(_))
132 .WillByDefault(testing::Return(true));
134 ON_CALL(*this, OnRstStreamFrame(_))
135 .WillByDefault(testing::Return(true));
137 ON_CALL(*this, OnConnectionCloseFrame(_))
138 .WillByDefault(testing::Return(true));
140 ON_CALL(*this, OnGoAwayFrame(_))
141 .WillByDefault(testing::Return(true));
144 MockFramerVisitor::~MockFramerVisitor() {
147 bool NoOpFramerVisitor::OnProtocolVersionMismatch(QuicVersion version) {
148 return false;
151 bool NoOpFramerVisitor::OnUnauthenticatedPublicHeader(
152 const QuicPacketPublicHeader& header) {
153 return true;
156 bool NoOpFramerVisitor::OnUnauthenticatedHeader(
157 const QuicPacketHeader& header) {
158 return true;
161 bool NoOpFramerVisitor::OnPacketHeader(const QuicPacketHeader& header) {
162 return true;
165 bool NoOpFramerVisitor::OnStreamFrame(const QuicStreamFrame& frame) {
166 return true;
169 bool NoOpFramerVisitor::OnAckFrame(const QuicAckFrame& frame) {
170 return true;
173 bool NoOpFramerVisitor::OnStopWaitingFrame(
174 const QuicStopWaitingFrame& frame) {
175 return true;
178 bool NoOpFramerVisitor::OnPingFrame(const QuicPingFrame& frame) {
179 return true;
182 bool NoOpFramerVisitor::OnRstStreamFrame(
183 const QuicRstStreamFrame& frame) {
184 return true;
187 bool NoOpFramerVisitor::OnConnectionCloseFrame(
188 const QuicConnectionCloseFrame& frame) {
189 return true;
192 bool NoOpFramerVisitor::OnGoAwayFrame(const QuicGoAwayFrame& frame) {
193 return true;
196 bool NoOpFramerVisitor::OnWindowUpdateFrame(
197 const QuicWindowUpdateFrame& frame) {
198 return true;
201 bool NoOpFramerVisitor::OnBlockedFrame(const QuicBlockedFrame& frame) {
202 return true;
205 MockConnectionVisitor::MockConnectionVisitor() {
208 MockConnectionVisitor::~MockConnectionVisitor() {
211 MockHelper::MockHelper() {
214 MockHelper::~MockHelper() {
217 const QuicClock* MockHelper::GetClock() const {
218 return &clock_;
221 QuicRandom* MockHelper::GetRandomGenerator() {
222 return &random_generator_;
225 QuicAlarm* MockHelper::CreateAlarm(QuicAlarm::Delegate* delegate) {
226 return new TestAlarm(delegate);
229 void MockHelper::AdvanceTime(QuicTime::Delta delta) {
230 clock_.AdvanceTime(delta);
233 QuicPacketWriter* NiceMockPacketWriterFactory::Create(
234 QuicConnection* /*connection*/) const {
235 return new testing::NiceMock<MockPacketWriter>();
238 MockConnection::MockConnection(Perspective perspective)
239 : MockConnection(perspective,
240 /* is_secure= */ false) {
243 MockConnection::MockConnection(Perspective perspective, bool is_secure)
244 : MockConnection(kTestConnectionId,
245 IPEndPoint(TestPeerIPAddress(), kTestPort),
246 perspective,
247 is_secure,
248 QuicSupportedVersions()) {
251 MockConnection::MockConnection(IPEndPoint address, Perspective perspective)
252 : MockConnection(kTestConnectionId,
253 address,
254 perspective,
255 /* is_secure= */ false,
256 QuicSupportedVersions()) {
259 MockConnection::MockConnection(QuicConnectionId connection_id,
260 Perspective perspective)
261 : MockConnection(connection_id,
262 perspective,
263 /* is_secure= */ false) {
266 MockConnection::MockConnection(QuicConnectionId connection_id,
267 Perspective perspective,
268 bool is_secure)
269 : MockConnection(connection_id,
270 IPEndPoint(TestPeerIPAddress(), kTestPort),
271 perspective,
272 is_secure,
273 QuicSupportedVersions()) {
276 MockConnection::MockConnection(Perspective perspective,
277 const QuicVersionVector& supported_versions)
278 : MockConnection(kTestConnectionId,
279 IPEndPoint(TestPeerIPAddress(), kTestPort),
280 perspective,
281 /* is_secure= */ false,
282 supported_versions) {
285 MockConnection::MockConnection(QuicConnectionId connection_id,
286 IPEndPoint address,
287 Perspective perspective,
288 bool is_secure,
289 const QuicVersionVector& supported_versions)
290 : QuicConnection(connection_id,
291 address,
292 new testing::NiceMock<MockHelper>(),
293 NiceMockPacketWriterFactory(),
294 /* owns_writer= */ true,
295 perspective,
296 is_secure,
297 supported_versions),
298 helper_(helper()) {
299 ON_CALL(*this, OnError(_))
300 .WillByDefault(
301 Invoke(this, &PacketSavingConnection::QuicConnection_OnError));
304 MockConnection::~MockConnection() {
307 void MockConnection::AdvanceTime(QuicTime::Delta delta) {
308 static_cast<MockHelper*>(helper())->AdvanceTime(delta);
311 PacketSavingConnection::PacketSavingConnection(Perspective perspective)
312 : MockConnection(perspective) {
315 PacketSavingConnection::PacketSavingConnection(
316 Perspective perspective,
317 const QuicVersionVector& supported_versions)
318 : MockConnection(perspective, supported_versions) {
321 PacketSavingConnection::~PacketSavingConnection() {
322 STLDeleteElements(&encrypted_packets_);
325 void PacketSavingConnection::SendOrQueuePacket(QueuedPacket packet) {
326 if (!packet.serialized_packet.packet->owns_buffer()) {
327 scoped_ptr<QuicEncryptedPacket> encrypted_deleter(
328 packet.serialized_packet.packet);
329 packet.serialized_packet.packet = packet.serialized_packet.packet->Clone();
331 encrypted_packets_.push_back(packet.serialized_packet.packet);
332 // Transfer ownership of the packet to the SentPacketManager and the
333 // ack notifier to the AckNotifierManager.
334 sent_packet_manager_.OnPacketSent(
335 &packet.serialized_packet, 0, QuicTime::Zero(), 1000,
336 NOT_RETRANSMISSION, HAS_RETRANSMITTABLE_DATA);
339 MockQuicSpdySession::MockQuicSpdySession(QuicConnection* connection)
340 : QuicSpdySession(connection, DefaultQuicConfig()) {
341 crypto_stream_.reset(new QuicCryptoStream(this));
342 Initialize();
343 ON_CALL(*this, WritevData(_, _, _, _, _, _))
344 .WillByDefault(testing::Return(QuicConsumedData(0, false)));
347 MockQuicSpdySession::~MockQuicSpdySession() {
350 TestQuicSpdyServerSession::TestQuicSpdyServerSession(
351 QuicConnection* connection,
352 const QuicConfig& config,
353 const QuicCryptoServerConfig* crypto_config)
354 : QuicSpdySession(connection, config) {
355 crypto_stream_.reset(new QuicCryptoServerStream(crypto_config, this));
356 Initialize();
359 TestQuicSpdyServerSession::~TestQuicSpdyServerSession() {
362 QuicCryptoServerStream* TestQuicSpdyServerSession::GetCryptoStream() {
363 return crypto_stream_.get();
366 TestQuicSpdyClientSession::TestQuicSpdyClientSession(
367 QuicConnection* connection,
368 const QuicConfig& config,
369 const QuicServerId& server_id,
370 QuicCryptoClientConfig* crypto_config)
371 : QuicClientSessionBase(connection, config) {
372 crypto_stream_.reset(new QuicCryptoClientStream(
373 server_id, this, CryptoTestUtils::ProofVerifyContextForTesting(),
374 crypto_config));
375 Initialize();
378 TestQuicSpdyClientSession::~TestQuicSpdyClientSession() {
381 QuicCryptoClientStream* TestQuicSpdyClientSession::GetCryptoStream() {
382 return crypto_stream_.get();
385 MockPacketWriter::MockPacketWriter() {
388 MockPacketWriter::~MockPacketWriter() {
391 MockSendAlgorithm::MockSendAlgorithm() {
394 MockSendAlgorithm::~MockSendAlgorithm() {
397 MockLossAlgorithm::MockLossAlgorithm() {
400 MockLossAlgorithm::~MockLossAlgorithm() {
403 MockAckNotifierDelegate::MockAckNotifierDelegate() {
406 MockAckNotifierDelegate::~MockAckNotifierDelegate() {
409 MockNetworkChangeVisitor::MockNetworkChangeVisitor() {
412 MockNetworkChangeVisitor::~MockNetworkChangeVisitor() {
415 namespace {
417 string HexDumpWithMarks(const char* data, int length,
418 const bool* marks, int mark_length) {
419 static const char kHexChars[] = "0123456789abcdef";
420 static const int kColumns = 4;
422 const int kSizeLimit = 1024;
423 if (length > kSizeLimit || mark_length > kSizeLimit) {
424 LOG(ERROR) << "Only dumping first " << kSizeLimit << " bytes.";
425 length = min(length, kSizeLimit);
426 mark_length = min(mark_length, kSizeLimit);
429 string hex;
430 for (const char* row = data; length > 0;
431 row += kColumns, length -= kColumns) {
432 for (const char *p = row; p < row + 4; ++p) {
433 if (p < row + length) {
434 const bool mark =
435 (marks && (p - data) < mark_length && marks[p - data]);
436 hex += mark ? '*' : ' ';
437 hex += kHexChars[(*p & 0xf0) >> 4];
438 hex += kHexChars[*p & 0x0f];
439 hex += mark ? '*' : ' ';
440 } else {
441 hex += " ";
444 hex = hex + " ";
446 for (const char* p = row; p < row + 4 && p < row + length; ++p) {
447 hex += (*p >= 0x20 && *p <= 0x7f) ? (*p) : '.';
450 hex = hex + '\n';
452 return hex;
455 } // namespace
457 IPAddressNumber TestPeerIPAddress() { return Loopback4(); }
459 QuicVersion QuicVersionMax() { return QuicSupportedVersions().front(); }
461 QuicVersion QuicVersionMin() { return QuicSupportedVersions().back(); }
463 IPAddressNumber Loopback4() {
464 IPAddressNumber addr;
465 CHECK(ParseIPLiteralToNumber("127.0.0.1", &addr));
466 return addr;
469 IPAddressNumber Loopback6() {
470 IPAddressNumber addr;
471 CHECK(ParseIPLiteralToNumber("::1", &addr));
472 return addr;
475 IPAddressNumber Any4() {
476 IPAddressNumber any4;
477 CHECK(net::ParseIPLiteralToNumber("0.0.0.0", &any4));
478 return any4;
481 void GenerateBody(string* body, int length) {
482 body->clear();
483 body->reserve(length);
484 for (int i = 0; i < length; ++i) {
485 body->append(1, static_cast<char>(32 + i % (126 - 32)));
489 QuicEncryptedPacket* ConstructEncryptedPacket(QuicConnectionId connection_id,
490 bool version_flag,
491 bool reset_flag,
492 QuicPacketNumber packet_number,
493 const string& data) {
494 return ConstructEncryptedPacket(
495 connection_id, version_flag, reset_flag, packet_number, data,
496 PACKET_8BYTE_CONNECTION_ID, PACKET_6BYTE_PACKET_NUMBER);
499 QuicEncryptedPacket* ConstructEncryptedPacket(
500 QuicConnectionId connection_id,
501 bool version_flag,
502 bool reset_flag,
503 QuicPacketNumber packet_number,
504 const string& data,
505 QuicConnectionIdLength connection_id_length,
506 QuicPacketNumberLength packet_number_length) {
507 return ConstructEncryptedPacket(connection_id, version_flag, reset_flag,
508 packet_number, data, connection_id_length,
509 packet_number_length, nullptr);
512 QuicEncryptedPacket* ConstructEncryptedPacket(
513 QuicConnectionId connection_id,
514 bool version_flag,
515 bool reset_flag,
516 QuicPacketNumber packet_number,
517 const string& data,
518 QuicConnectionIdLength connection_id_length,
519 QuicPacketNumberLength packet_number_length,
520 QuicVersionVector* versions) {
521 QuicPacketHeader header;
522 header.public_header.connection_id = connection_id;
523 header.public_header.connection_id_length = connection_id_length;
524 header.public_header.version_flag = version_flag;
525 header.public_header.reset_flag = reset_flag;
526 header.public_header.packet_number_length = packet_number_length;
527 header.packet_packet_number = packet_number;
528 header.entropy_flag = false;
529 header.entropy_hash = 0;
530 header.fec_flag = false;
531 header.is_in_fec_group = NOT_IN_FEC_GROUP;
532 header.fec_group = 0;
533 QuicStreamFrame stream_frame(1, false, 0, StringPiece(data));
534 QuicFrame frame(&stream_frame);
535 QuicFrames frames;
536 frames.push_back(frame);
537 QuicFramer framer(versions != nullptr ? *versions : QuicSupportedVersions(),
538 QuicTime::Zero(), Perspective::IS_CLIENT);
540 scoped_ptr<QuicPacket> packet(
541 BuildUnsizedDataPacket(&framer, header, frames));
542 EXPECT_TRUE(packet != nullptr);
543 char buffer[kMaxPacketSize];
544 scoped_ptr<QuicEncryptedPacket> encrypted(framer.EncryptPayload(
545 ENCRYPTION_NONE, packet_number, *packet, buffer, kMaxPacketSize));
546 EXPECT_TRUE(encrypted != nullptr);
547 return encrypted->Clone();
550 QuicEncryptedPacket* ConstructMisFramedEncryptedPacket(
551 QuicConnectionId connection_id,
552 bool version_flag,
553 bool reset_flag,
554 QuicPacketNumber packet_number,
555 const string& data,
556 QuicConnectionIdLength connection_id_length,
557 QuicPacketNumberLength packet_number_length,
558 QuicVersionVector* versions) {
559 QuicPacketHeader header;
560 header.public_header.connection_id = connection_id;
561 header.public_header.connection_id_length = connection_id_length;
562 header.public_header.version_flag = version_flag;
563 header.public_header.reset_flag = reset_flag;
564 header.public_header.packet_number_length = packet_number_length;
565 header.packet_packet_number = packet_number;
566 header.entropy_flag = false;
567 header.entropy_hash = 0;
568 header.fec_flag = false;
569 header.is_in_fec_group = NOT_IN_FEC_GROUP;
570 header.fec_group = 0;
571 QuicStreamFrame stream_frame(1, false, 0, StringPiece(data));
572 QuicFrame frame(&stream_frame);
573 QuicFrames frames;
574 frames.push_back(frame);
575 QuicFramer framer(versions != nullptr ? *versions : QuicSupportedVersions(),
576 QuicTime::Zero(), Perspective::IS_CLIENT);
578 scoped_ptr<QuicPacket> packet(
579 BuildUnsizedDataPacket(&framer, header, frames));
580 EXPECT_TRUE(packet != nullptr);
582 // Now set the packet's private flags byte to 0xFF, which is an invalid value.
583 reinterpret_cast<unsigned char*>(
584 packet->mutable_data())[GetStartOfEncryptedData(
585 connection_id_length, version_flag, packet_number_length)] = 0xFF;
587 char buffer[kMaxPacketSize];
588 scoped_ptr<QuicEncryptedPacket> encrypted(framer.EncryptPayload(
589 ENCRYPTION_NONE, packet_number, *packet, buffer, kMaxPacketSize));
590 EXPECT_TRUE(encrypted != nullptr);
591 return encrypted->Clone();
594 void CompareCharArraysWithHexError(
595 const string& description,
596 const char* actual,
597 const int actual_len,
598 const char* expected,
599 const int expected_len) {
600 EXPECT_EQ(actual_len, expected_len);
601 const int min_len = min(actual_len, expected_len);
602 const int max_len = max(actual_len, expected_len);
603 scoped_ptr<bool[]> marks(new bool[max_len]);
604 bool identical = (actual_len == expected_len);
605 for (int i = 0; i < min_len; ++i) {
606 if (actual[i] != expected[i]) {
607 marks[i] = true;
608 identical = false;
609 } else {
610 marks[i] = false;
613 for (int i = min_len; i < max_len; ++i) {
614 marks[i] = true;
616 if (identical) return;
617 ADD_FAILURE()
618 << "Description:\n"
619 << description
620 << "\n\nExpected:\n"
621 << HexDumpWithMarks(expected, expected_len, marks.get(), max_len)
622 << "\nActual:\n"
623 << HexDumpWithMarks(actual, actual_len, marks.get(), max_len);
626 bool DecodeHexString(const base::StringPiece& hex, std::string* bytes) {
627 bytes->clear();
628 if (hex.empty())
629 return true;
630 std::vector<uint8> v;
631 if (!base::HexStringToBytes(hex.as_string(), &v))
632 return false;
633 if (!v.empty())
634 bytes->assign(reinterpret_cast<const char*>(&v[0]), v.size());
635 return true;
638 static QuicPacket* ConstructPacketFromHandshakeMessage(
639 QuicConnectionId connection_id,
640 const CryptoHandshakeMessage& message,
641 bool should_include_version) {
642 CryptoFramer crypto_framer;
643 scoped_ptr<QuicData> data(crypto_framer.ConstructHandshakeMessage(message));
644 QuicFramer quic_framer(QuicSupportedVersions(), QuicTime::Zero(),
645 Perspective::IS_CLIENT);
647 QuicPacketHeader header;
648 header.public_header.connection_id = connection_id;
649 header.public_header.reset_flag = false;
650 header.public_header.version_flag = should_include_version;
651 header.packet_packet_number = 1;
652 header.entropy_flag = false;
653 header.entropy_hash = 0;
654 header.fec_flag = false;
655 header.fec_group = 0;
657 QuicStreamFrame stream_frame(kCryptoStreamId, false, 0,
658 data->AsStringPiece());
660 QuicFrame frame(&stream_frame);
661 QuicFrames frames;
662 frames.push_back(frame);
663 return BuildUnsizedDataPacket(&quic_framer, header, frames);
666 QuicPacket* ConstructHandshakePacket(QuicConnectionId connection_id,
667 QuicTag tag) {
668 CryptoHandshakeMessage message;
669 message.set_tag(tag);
670 return ConstructPacketFromHandshakeMessage(connection_id, message, false);
673 size_t GetPacketLengthForOneStream(QuicVersion version,
674 bool include_version,
675 QuicConnectionIdLength connection_id_length,
676 QuicPacketNumberLength packet_number_length,
677 InFecGroup is_in_fec_group,
678 size_t* payload_length) {
679 *payload_length = 1;
680 const size_t stream_length =
681 NullEncrypter().GetCiphertextSize(*payload_length) +
682 QuicPacketCreator::StreamFramePacketOverhead(
683 PACKET_8BYTE_CONNECTION_ID, include_version, packet_number_length, 0u,
684 is_in_fec_group);
685 const size_t ack_length =
686 NullEncrypter().GetCiphertextSize(
687 QuicFramer::GetMinAckFrameSize(PACKET_1BYTE_PACKET_NUMBER)) +
688 GetPacketHeaderSize(connection_id_length, include_version,
689 packet_number_length, is_in_fec_group);
690 if (stream_length < ack_length) {
691 *payload_length = 1 + ack_length - stream_length;
694 return NullEncrypter().GetCiphertextSize(*payload_length) +
695 QuicPacketCreator::StreamFramePacketOverhead(
696 connection_id_length, include_version, packet_number_length, 0u,
697 is_in_fec_group);
700 TestEntropyCalculator::TestEntropyCalculator() {}
702 TestEntropyCalculator::~TestEntropyCalculator() {}
704 QuicPacketEntropyHash TestEntropyCalculator::EntropyHash(
705 QuicPacketNumber packet_number) const {
706 return 1u;
709 MockEntropyCalculator::MockEntropyCalculator() {}
711 MockEntropyCalculator::~MockEntropyCalculator() {}
713 QuicConfig DefaultQuicConfig() {
714 QuicConfig config;
715 config.SetInitialStreamFlowControlWindowToSend(
716 kInitialStreamFlowControlWindowForTest);
717 config.SetInitialSessionFlowControlWindowToSend(
718 kInitialSessionFlowControlWindowForTest);
719 return config;
722 QuicConfig DefaultQuicConfigStatelessRejects() {
723 QuicConfig config = DefaultQuicConfig();
724 QuicTagVector copt;
725 copt.push_back(kSREJ);
726 config.SetConnectionOptionsToSend(copt);
727 return config;
730 QuicVersionVector SupportedVersions(QuicVersion version) {
731 QuicVersionVector versions;
732 versions.push_back(version);
733 return versions;
736 TestWriterFactory::TestWriterFactory() : current_writer_(nullptr) {}
737 TestWriterFactory::~TestWriterFactory() {}
739 QuicPacketWriter* TestWriterFactory::Create(QuicPacketWriter* writer,
740 QuicConnection* connection) {
741 return new PerConnectionPacketWriter(this, writer, connection);
744 void TestWriterFactory::OnPacketSent(WriteResult result) {
745 if (current_writer_ != nullptr && result.status == WRITE_STATUS_ERROR) {
746 current_writer_->connection()->OnWriteError(result.error_code);
747 current_writer_ = nullptr;
751 void TestWriterFactory::Unregister(PerConnectionPacketWriter* writer) {
752 if (current_writer_ == writer) {
753 current_writer_ = nullptr;
757 TestWriterFactory::PerConnectionPacketWriter::PerConnectionPacketWriter(
758 TestWriterFactory* factory,
759 QuicPacketWriter* writer,
760 QuicConnection* connection)
761 : QuicPerConnectionPacketWriter(writer, connection),
762 factory_(factory) {
765 TestWriterFactory::PerConnectionPacketWriter::~PerConnectionPacketWriter() {
766 factory_->Unregister(this);
769 WriteResult TestWriterFactory::PerConnectionPacketWriter::WritePacket(
770 const char* buffer,
771 size_t buf_len,
772 const IPAddressNumber& self_address,
773 const IPEndPoint& peer_address) {
774 // A DCHECK(factory_current_writer_ == nullptr) would be wrong here -- this
775 // class may be used in a setting where connection()->OnPacketSent() is called
776 // in a different way, so TestWriterFactory::OnPacketSent might never be
777 // called.
778 factory_->current_writer_ = this;
779 return tools::QuicPerConnectionPacketWriter::WritePacket(
780 buffer, buf_len, self_address, peer_address);
783 MockQuicConnectionDebugVisitor::MockQuicConnectionDebugVisitor() {
786 MockQuicConnectionDebugVisitor::~MockQuicConnectionDebugVisitor() {
789 void CreateClientSessionForTest(QuicServerId server_id,
790 bool supports_stateless_rejects,
791 QuicTime::Delta connection_start_time,
792 QuicCryptoClientConfig* crypto_client_config,
793 PacketSavingConnection** client_connection,
794 TestQuicSpdyClientSession** client_session) {
795 CHECK(crypto_client_config);
796 CHECK(client_connection);
797 CHECK(client_session);
798 CHECK(!connection_start_time.IsZero())
799 << "Connections must start at non-zero times, otherwise the "
800 << "strike-register will be unhappy.";
802 QuicConfig config = supports_stateless_rejects
803 ? DefaultQuicConfigStatelessRejects()
804 : DefaultQuicConfig();
805 *client_connection = new PacketSavingConnection(Perspective::IS_CLIENT);
806 *client_session = new TestQuicSpdyClientSession(
807 *client_connection, config, server_id, crypto_client_config);
808 (*client_connection)->AdvanceTime(connection_start_time);
811 void CreateServerSessionForTest(QuicServerId server_id,
812 QuicTime::Delta connection_start_time,
813 QuicCryptoServerConfig* server_crypto_config,
814 PacketSavingConnection** server_connection,
815 TestQuicSpdyServerSession** server_session) {
816 CHECK(server_crypto_config);
817 CHECK(server_connection);
818 CHECK(server_session);
819 CHECK(!connection_start_time.IsZero())
820 << "Connections must start at non-zero times, otherwise the "
821 << "strike-register will be unhappy.";
823 *server_connection = new PacketSavingConnection(Perspective::IS_SERVER);
824 *server_session = new TestQuicSpdyServerSession(
825 *server_connection, DefaultQuicConfig(), server_crypto_config);
827 // We advance the clock initially because the default time is zero and the
828 // strike register worries that we've just overflowed a uint32 time.
829 (*server_connection)->AdvanceTime(connection_start_time);
832 } // namespace test
833 } // namespace net