• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 // Common utilities for Quic tests
6 
7 #ifndef QUICHE_QUIC_TEST_TOOLS_QUIC_TEST_UTILS_H_
8 #define QUICHE_QUIC_TEST_TOOLS_QUIC_TEST_UTILS_H_
9 
10 #include <cstdint>
11 #include <memory>
12 #include <string>
13 #include <utility>
14 #include <vector>
15 
16 #include "absl/container/flat_hash_map.h"
17 #include "absl/strings/ascii.h"
18 #include "absl/strings/str_cat.h"
19 #include "absl/strings/string_view.h"
20 #include "quiche/quic/core/congestion_control/loss_detection_interface.h"
21 #include "quiche/quic/core/congestion_control/send_algorithm_interface.h"
22 #include "quiche/quic/core/crypto/transport_parameters.h"
23 #include "quiche/quic/core/http/http_decoder.h"
24 #include "quiche/quic/core/http/quic_client_push_promise_index.h"
25 #include "quiche/quic/core/http/quic_server_session_base.h"
26 #include "quiche/quic/core/http/quic_spdy_session.h"
27 #include "quiche/quic/core/quic_connection.h"
28 #include "quiche/quic/core/quic_connection_id.h"
29 #include "quiche/quic/core/quic_error_codes.h"
30 #include "quiche/quic/core/quic_framer.h"
31 #include "quiche/quic/core/quic_packet_writer.h"
32 #include "quiche/quic/core/quic_path_validator.h"
33 #include "quiche/quic/core/quic_sent_packet_manager.h"
34 #include "quiche/quic/core/quic_server_id.h"
35 #include "quiche/quic/core/quic_types.h"
36 #include "quiche/quic/core/quic_utils.h"
37 #include "quiche/quic/platform/api/quic_socket_address.h"
38 #include "quiche/quic/test_tools/mock_clock.h"
39 #include "quiche/quic/test_tools/mock_connection_id_generator.h"
40 #include "quiche/quic/test_tools/mock_quic_session_visitor.h"
41 #include "quiche/quic/test_tools/mock_random.h"
42 #include "quiche/quic/test_tools/quic_framer_peer.h"
43 #include "quiche/quic/test_tools/simple_quic_framer.h"
44 #include "quiche/common/capsule.h"
45 #include "quiche/common/simple_buffer_allocator.h"
46 #include "quiche/spdy/core/http2_header_block.h"
47 
48 namespace quic {
49 
50 namespace test {
51 
52 // A generic predictable connection ID suited for testing.
53 QuicConnectionId TestConnectionId();
54 
55 // A generic predictable connection ID suited for testing, generated from a
56 // given number, such as an index.
57 QuicConnectionId TestConnectionId(uint64_t connection_number);
58 
59 // A generic predictable connection ID suited for testing, generated from a
60 // given number, such as an index. Guaranteed to be 9 bytes long.
61 QuicConnectionId TestConnectionIdNineBytesLong(uint64_t connection_number);
62 
63 // Extracts the connection number passed to TestConnectionId().
64 uint64_t TestConnectionIdToUInt64(QuicConnectionId connection_id);
65 
66 enum : uint16_t { kTestPort = 12345 };
67 enum : uint32_t {
68   kMaxDatagramFrameSizeForTest = 1333,
69   kMaxPacketSizeForTest = 9001,
70   kInitialStreamFlowControlWindowForTest = 1024 * 1024,   // 1 MB
71   kInitialSessionFlowControlWindowForTest = 1536 * 1024,  // 1.5 MB
72 };
73 
74 enum : uint64_t {
75   kAckDelayExponentForTest = 10,
76   kMaxAckDelayForTest = 51,  // ms
77   kActiveConnectionIdLimitForTest = 52,
78   kMinAckDelayUsForTest = 1000
79 };
80 
81 // Create an arbitrary stateless reset token, same across multiple calls.
82 std::vector<uint8_t> CreateStatelessResetTokenForTest();
83 
84 // A hostname useful for testing, returns "test.example.org".
85 std::string TestHostname();
86 
87 // A server ID useful for testing, returns test.example.org:12345.
88 QuicServerId TestServerId();
89 
90 // Returns the test peer IP address.
91 QuicIpAddress TestPeerIPAddress();
92 
93 // Upper limit on versions we support.
94 ParsedQuicVersion QuicVersionMax();
95 
96 // Lower limit on versions we support.
97 ParsedQuicVersion QuicVersionMin();
98 
99 // Disables all flags that enable QUIC versions that use TLS.
100 // This is only meant as a temporary measure to prevent some broken tests
101 // from running with TLS.
102 void DisableQuicVersionsWithTls();
103 
104 // Create an encrypted packet for testing.
105 // If versions == nullptr, uses &AllSupportedVersions().
106 // Note that the packet is encrypted with NullEncrypter, so to decrypt the
107 // constructed packet, the framer must be set to use NullDecrypter.
108 QuicEncryptedPacket* ConstructEncryptedPacket(
109     QuicConnectionId destination_connection_id,
110     QuicConnectionId source_connection_id, bool version_flag, bool reset_flag,
111     uint64_t packet_number, const std::string& data, bool full_padding,
112     QuicConnectionIdIncluded destination_connection_id_included,
113     QuicConnectionIdIncluded source_connection_id_included,
114     QuicPacketNumberLength packet_number_length,
115     ParsedQuicVersionVector* versions, Perspective perspective);
116 
117 QuicEncryptedPacket* ConstructEncryptedPacket(
118     QuicConnectionId destination_connection_id,
119     QuicConnectionId source_connection_id, bool version_flag, bool reset_flag,
120     uint64_t packet_number, const std::string& data, bool full_padding,
121     QuicConnectionIdIncluded destination_connection_id_included,
122     QuicConnectionIdIncluded source_connection_id_included,
123     QuicPacketNumberLength packet_number_length,
124     ParsedQuicVersionVector* versions);
125 
126 // Create an encrypted packet for testing.
127 // If versions == nullptr, uses &AllSupportedVersions().
128 // Note that the packet is encrypted with NullEncrypter, so to decrypt the
129 // constructed packet, the framer must be set to use NullDecrypter.
130 QuicEncryptedPacket* ConstructEncryptedPacket(
131     QuicConnectionId destination_connection_id,
132     QuicConnectionId source_connection_id, bool version_flag, bool reset_flag,
133     uint64_t packet_number, const std::string& data,
134     QuicConnectionIdIncluded destination_connection_id_included,
135     QuicConnectionIdIncluded source_connection_id_included,
136     QuicPacketNumberLength packet_number_length,
137     ParsedQuicVersionVector* versions);
138 
139 // This form assumes |versions| == nullptr.
140 QuicEncryptedPacket* ConstructEncryptedPacket(
141     QuicConnectionId destination_connection_id,
142     QuicConnectionId source_connection_id, bool version_flag, bool reset_flag,
143     uint64_t packet_number, const std::string& data,
144     QuicConnectionIdIncluded destination_connection_id_included,
145     QuicConnectionIdIncluded source_connection_id_included,
146     QuicPacketNumberLength packet_number_length);
147 
148 // This form assumes |connection_id_length| == PACKET_8BYTE_CONNECTION_ID,
149 // |packet_number_length| == PACKET_4BYTE_PACKET_NUMBER and
150 // |versions| == nullptr.
151 QuicEncryptedPacket* ConstructEncryptedPacket(
152     QuicConnectionId destination_connection_id,
153     QuicConnectionId source_connection_id, bool version_flag, bool reset_flag,
154     uint64_t packet_number, const std::string& data);
155 
156 // Creates a client-to-server ZERO-RTT packet that will fail to decrypt.
157 std::unique_ptr<QuicEncryptedPacket> GetUndecryptableEarlyPacket(
158     const ParsedQuicVersion& version,
159     const QuicConnectionId& server_connection_id);
160 
161 // Constructs a received packet for testing. The caller must take ownership
162 // of the returned pointer.
163 QuicReceivedPacket* ConstructReceivedPacket(
164     const QuicEncryptedPacket& encrypted_packet, QuicTime receipt_time);
165 
166 // Create an encrypted packet for testing whose data portion erroneous.
167 // The specific way the data portion is erroneous is not specified, but
168 // it is an error that QuicFramer detects.
169 // Note that the packet is encrypted with NullEncrypter, so to decrypt the
170 // constructed packet, the framer must be set to use NullDecrypter.
171 QuicEncryptedPacket* ConstructMisFramedEncryptedPacket(
172     QuicConnectionId destination_connection_id,
173     QuicConnectionId source_connection_id, bool version_flag, bool reset_flag,
174     uint64_t packet_number, const std::string& data,
175     QuicConnectionIdIncluded destination_connection_id_included,
176     QuicConnectionIdIncluded source_connection_id_included,
177     QuicPacketNumberLength packet_number_length, ParsedQuicVersion version,
178     Perspective perspective);
179 
180 // Returns QuicConfig set to default values.
181 QuicConfig DefaultQuicConfig();
182 
183 ParsedQuicVersionVector SupportedVersions(ParsedQuicVersion version);
184 
185 struct QuicAckBlock {
186   QuicPacketNumber start;  // Included
187   QuicPacketNumber limit;  // Excluded
188 };
189 
190 // Testing convenience method to construct a QuicAckFrame with arbitrary ack
191 // blocks. Each block is given by a (closed-open) range of packet numbers. e.g.:
192 // InitAckFrame({{1, 10}})
193 //   => 1 ack block acking packet numbers 1 to 9.
194 //
195 // InitAckFrame({{1, 2}, {3, 4}})
196 //   => 2 ack blocks acking packet 1 and 3. Packet 2 is missing.
197 QuicAckFrame InitAckFrame(const std::vector<QuicAckBlock>& ack_blocks);
198 
199 // Testing convenience method to construct a QuicAckFrame with 1 ack block which
200 // covers packet number range [1, |largest_acked| + 1).
201 // Equivalent to InitAckFrame({{1, largest_acked + 1}})
202 QuicAckFrame InitAckFrame(uint64_t largest_acked);
203 QuicAckFrame InitAckFrame(QuicPacketNumber largest_acked);
204 
205 // Testing convenience method to construct a QuicAckFrame with |num_ack_blocks|
206 // ack blocks of width 1 packet, starting from |least_unacked| + 2.
207 QuicAckFrame MakeAckFrameWithAckBlocks(size_t num_ack_blocks,
208                                        uint64_t least_unacked);
209 
210 // Testing convenice method to construct a QuicAckFrame with |largest_acked|,
211 // ack blocks of width 1 packet and |gap_size|.
212 QuicAckFrame MakeAckFrameWithGaps(uint64_t gap_size, size_t max_num_gaps,
213                                   uint64_t largest_acked);
214 
215 // Returns the encryption level that corresponds to the header type in
216 // |header|. If the header is for GOOGLE_QUIC_PACKET instead of an
217 // IETF-invariants packet, this function returns ENCRYPTION_INITIAL.
218 EncryptionLevel HeaderToEncryptionLevel(const QuicPacketHeader& header);
219 
220 // Returns a QuicPacket that is owned by the caller, and
221 // is populated with the fields in |header| and |frames|, or is nullptr if the
222 // packet could not be created.
223 std::unique_ptr<QuicPacket> BuildUnsizedDataPacket(
224     QuicFramer* framer, const QuicPacketHeader& header,
225     const QuicFrames& frames);
226 // Returns a QuicPacket that is owned by the caller, and of size |packet_size|.
227 std::unique_ptr<QuicPacket> BuildUnsizedDataPacket(
228     QuicFramer* framer, const QuicPacketHeader& header,
229     const QuicFrames& frames, size_t packet_size);
230 
231 // Compute SHA-1 hash of the supplied std::string.
232 std::string Sha1Hash(absl::string_view data);
233 
234 // Delete |frame| and return true.
235 bool ClearControlFrame(const QuicFrame& frame);
236 bool ClearControlFrameWithTransmissionType(const QuicFrame& frame,
237                                            TransmissionType type);
238 
239 // Simple random number generator used to compute random numbers suitable
240 // for pseudo-randomly dropping packets in tests.
241 class SimpleRandom : public QuicRandom {
242  public:
SimpleRandom()243   SimpleRandom() { set_seed(0); }
244   SimpleRandom(const SimpleRandom&) = delete;
245   SimpleRandom& operator=(const SimpleRandom&) = delete;
~SimpleRandom()246   ~SimpleRandom() override {}
247 
248   // Generates |len| random bytes in the |data| buffer.
249   void RandBytes(void* data, size_t len) override;
250   // Returns a random number in the range [0, kuint64max].
251   uint64_t RandUint64() override;
252 
253   // InsecureRandBytes behaves equivalently to RandBytes.
254   void InsecureRandBytes(void* data, size_t len) override;
255   // InsecureRandUint64 behaves equivalently to RandUint64.
256   uint64_t InsecureRandUint64() override;
257 
258   void set_seed(uint64_t seed);
259 
260  private:
261   uint8_t buffer_[4096];
262   size_t buffer_offset_ = 0;
263   uint8_t key_[32];
264 
265   void FillBuffer();
266 };
267 
268 class MockFramerVisitor : public QuicFramerVisitorInterface {
269  public:
270   MockFramerVisitor();
271   MockFramerVisitor(const MockFramerVisitor&) = delete;
272   MockFramerVisitor& operator=(const MockFramerVisitor&) = delete;
273   ~MockFramerVisitor() override;
274 
275   MOCK_METHOD(void, OnError, (QuicFramer*), (override));
276   // The constructor sets this up to return false by default.
277   MOCK_METHOD(bool, OnProtocolVersionMismatch, (ParsedQuicVersion version),
278               (override));
279   MOCK_METHOD(void, OnPacket, (), (override));
280   MOCK_METHOD(void, OnPublicResetPacket, (const QuicPublicResetPacket& header),
281               (override));
282   MOCK_METHOD(void, OnVersionNegotiationPacket,
283               (const QuicVersionNegotiationPacket& packet), (override));
284   MOCK_METHOD(void, OnRetryPacket,
285               (QuicConnectionId original_connection_id,
286                QuicConnectionId new_connection_id,
287                absl::string_view retry_token,
288                absl::string_view retry_integrity_tag,
289                absl::string_view retry_without_tag),
290               (override));
291   // The constructor sets this up to return true by default.
292   MOCK_METHOD(bool, OnUnauthenticatedHeader, (const QuicPacketHeader& header),
293               (override));
294   // The constructor sets this up to return true by default.
295   MOCK_METHOD(bool, OnUnauthenticatedPublicHeader,
296               (const QuicPacketHeader& header), (override));
297   MOCK_METHOD(void, OnDecryptedPacket, (size_t length, EncryptionLevel level),
298               (override));
299   MOCK_METHOD(bool, OnPacketHeader, (const QuicPacketHeader& header),
300               (override));
301   MOCK_METHOD(void, OnCoalescedPacket, (const QuicEncryptedPacket& packet),
302               (override));
303   MOCK_METHOD(void, OnUndecryptablePacket,
304               (const QuicEncryptedPacket& packet,
305                EncryptionLevel decryption_level, bool has_decryption_key),
306               (override));
307   MOCK_METHOD(bool, OnStreamFrame, (const QuicStreamFrame& frame), (override));
308   MOCK_METHOD(bool, OnCryptoFrame, (const QuicCryptoFrame& frame), (override));
309   MOCK_METHOD(bool, OnAckFrameStart, (QuicPacketNumber, QuicTime::Delta),
310               (override));
311   MOCK_METHOD(bool, OnAckRange, (QuicPacketNumber, QuicPacketNumber),
312               (override));
313   MOCK_METHOD(bool, OnAckTimestamp, (QuicPacketNumber, QuicTime), (override));
314   MOCK_METHOD(bool, OnAckFrameEnd,
315               (QuicPacketNumber, const absl::optional<QuicEcnCounts>&),
316               (override));
317   MOCK_METHOD(bool, OnStopWaitingFrame, (const QuicStopWaitingFrame& frame),
318               (override));
319   MOCK_METHOD(bool, OnPaddingFrame, (const QuicPaddingFrame& frame),
320               (override));
321   MOCK_METHOD(bool, OnPingFrame, (const QuicPingFrame& frame), (override));
322   MOCK_METHOD(bool, OnRstStreamFrame, (const QuicRstStreamFrame& frame),
323               (override));
324   MOCK_METHOD(bool, OnConnectionCloseFrame,
325               (const QuicConnectionCloseFrame& frame), (override));
326   MOCK_METHOD(bool, OnNewConnectionIdFrame,
327               (const QuicNewConnectionIdFrame& frame), (override));
328   MOCK_METHOD(bool, OnRetireConnectionIdFrame,
329               (const QuicRetireConnectionIdFrame& frame), (override));
330   MOCK_METHOD(bool, OnNewTokenFrame, (const QuicNewTokenFrame& frame),
331               (override));
332   MOCK_METHOD(bool, OnStopSendingFrame, (const QuicStopSendingFrame& frame),
333               (override));
334   MOCK_METHOD(bool, OnPathChallengeFrame, (const QuicPathChallengeFrame& frame),
335               (override));
336   MOCK_METHOD(bool, OnPathResponseFrame, (const QuicPathResponseFrame& frame),
337               (override));
338   MOCK_METHOD(bool, OnGoAwayFrame, (const QuicGoAwayFrame& frame), (override));
339   MOCK_METHOD(bool, OnMaxStreamsFrame, (const QuicMaxStreamsFrame& frame),
340               (override));
341   MOCK_METHOD(bool, OnStreamsBlockedFrame,
342               (const QuicStreamsBlockedFrame& frame), (override));
343   MOCK_METHOD(bool, OnWindowUpdateFrame, (const QuicWindowUpdateFrame& frame),
344               (override));
345   MOCK_METHOD(bool, OnBlockedFrame, (const QuicBlockedFrame& frame),
346               (override));
347   MOCK_METHOD(bool, OnMessageFrame, (const QuicMessageFrame& frame),
348               (override));
349   MOCK_METHOD(bool, OnHandshakeDoneFrame, (const QuicHandshakeDoneFrame& frame),
350               (override));
351   MOCK_METHOD(bool, OnAckFrequencyFrame, (const QuicAckFrequencyFrame& frame),
352               (override));
353   MOCK_METHOD(void, OnPacketComplete, (), (override));
354   MOCK_METHOD(bool, IsValidStatelessResetToken, (const StatelessResetToken&),
355               (const, override));
356   MOCK_METHOD(void, OnAuthenticatedIetfStatelessResetPacket,
357               (const QuicIetfStatelessResetPacket&), (override));
358   MOCK_METHOD(void, OnKeyUpdate, (KeyUpdateReason), (override));
359   MOCK_METHOD(void, OnDecryptedFirstPacketInKeyPhase, (), (override));
360   MOCK_METHOD(std::unique_ptr<QuicDecrypter>,
361               AdvanceKeysAndCreateCurrentOneRttDecrypter, (), (override));
362   MOCK_METHOD(std::unique_ptr<QuicEncrypter>, CreateCurrentOneRttEncrypter, (),
363               (override));
364 };
365 
366 class NoOpFramerVisitor : public QuicFramerVisitorInterface {
367  public:
NoOpFramerVisitor()368   NoOpFramerVisitor() {}
369   NoOpFramerVisitor(const NoOpFramerVisitor&) = delete;
370   NoOpFramerVisitor& operator=(const NoOpFramerVisitor&) = delete;
371 
OnError(QuicFramer *)372   void OnError(QuicFramer* /*framer*/) override {}
OnPacket()373   void OnPacket() override {}
OnPublicResetPacket(const QuicPublicResetPacket &)374   void OnPublicResetPacket(const QuicPublicResetPacket& /*packet*/) override {}
OnVersionNegotiationPacket(const QuicVersionNegotiationPacket &)375   void OnVersionNegotiationPacket(
376       const QuicVersionNegotiationPacket& /*packet*/) override {}
OnRetryPacket(QuicConnectionId,QuicConnectionId,absl::string_view,absl::string_view,absl::string_view)377   void OnRetryPacket(QuicConnectionId /*original_connection_id*/,
378                      QuicConnectionId /*new_connection_id*/,
379                      absl::string_view /*retry_token*/,
380                      absl::string_view /*retry_integrity_tag*/,
381                      absl::string_view /*retry_without_tag*/) override {}
382   bool OnProtocolVersionMismatch(ParsedQuicVersion version) override;
383   bool OnUnauthenticatedHeader(const QuicPacketHeader& header) override;
384   bool OnUnauthenticatedPublicHeader(const QuicPacketHeader& header) override;
OnDecryptedPacket(size_t,EncryptionLevel)385   void OnDecryptedPacket(size_t /*length*/,
386                          EncryptionLevel /*level*/) override {}
387   bool OnPacketHeader(const QuicPacketHeader& header) override;
388   void OnCoalescedPacket(const QuicEncryptedPacket& packet) override;
389   void OnUndecryptablePacket(const QuicEncryptedPacket& packet,
390                              EncryptionLevel decryption_level,
391                              bool has_decryption_key) override;
392   bool OnStreamFrame(const QuicStreamFrame& frame) override;
393   bool OnCryptoFrame(const QuicCryptoFrame& frame) override;
394   bool OnAckFrameStart(QuicPacketNumber largest_acked,
395                        QuicTime::Delta ack_delay_time) override;
396   bool OnAckRange(QuicPacketNumber start, QuicPacketNumber end) override;
397   bool OnAckTimestamp(QuicPacketNumber packet_number,
398                       QuicTime timestamp) override;
399   bool OnAckFrameEnd(QuicPacketNumber start,
400                      const absl::optional<QuicEcnCounts>& ecn_counts) override;
401   bool OnStopWaitingFrame(const QuicStopWaitingFrame& frame) override;
402   bool OnPaddingFrame(const QuicPaddingFrame& frame) override;
403   bool OnPingFrame(const QuicPingFrame& frame) override;
404   bool OnRstStreamFrame(const QuicRstStreamFrame& frame) override;
405   bool OnConnectionCloseFrame(const QuicConnectionCloseFrame& frame) override;
406   bool OnNewConnectionIdFrame(const QuicNewConnectionIdFrame& frame) override;
407   bool OnRetireConnectionIdFrame(
408       const QuicRetireConnectionIdFrame& frame) override;
409   bool OnNewTokenFrame(const QuicNewTokenFrame& frame) override;
410   bool OnStopSendingFrame(const QuicStopSendingFrame& frame) override;
411   bool OnPathChallengeFrame(const QuicPathChallengeFrame& frame) override;
412   bool OnPathResponseFrame(const QuicPathResponseFrame& frame) override;
413   bool OnGoAwayFrame(const QuicGoAwayFrame& frame) override;
414   bool OnMaxStreamsFrame(const QuicMaxStreamsFrame& frame) override;
415   bool OnStreamsBlockedFrame(const QuicStreamsBlockedFrame& frame) override;
416   bool OnWindowUpdateFrame(const QuicWindowUpdateFrame& frame) override;
417   bool OnBlockedFrame(const QuicBlockedFrame& frame) override;
418   bool OnMessageFrame(const QuicMessageFrame& frame) override;
419   bool OnHandshakeDoneFrame(const QuicHandshakeDoneFrame& frame) override;
420   bool OnAckFrequencyFrame(const QuicAckFrequencyFrame& frame) override;
OnPacketComplete()421   void OnPacketComplete() override {}
422   bool IsValidStatelessResetToken(
423       const StatelessResetToken& token) const override;
OnAuthenticatedIetfStatelessResetPacket(const QuicIetfStatelessResetPacket &)424   void OnAuthenticatedIetfStatelessResetPacket(
425       const QuicIetfStatelessResetPacket& /*packet*/) override {}
OnKeyUpdate(KeyUpdateReason)426   void OnKeyUpdate(KeyUpdateReason /*reason*/) override {}
OnDecryptedFirstPacketInKeyPhase()427   void OnDecryptedFirstPacketInKeyPhase() override {}
AdvanceKeysAndCreateCurrentOneRttDecrypter()428   std::unique_ptr<QuicDecrypter> AdvanceKeysAndCreateCurrentOneRttDecrypter()
429       override {
430     return nullptr;
431   }
CreateCurrentOneRttEncrypter()432   std::unique_ptr<QuicEncrypter> CreateCurrentOneRttEncrypter() override {
433     return nullptr;
434   }
435 };
436 
437 class MockQuicConnectionVisitor : public QuicConnectionVisitorInterface {
438  public:
439   MockQuicConnectionVisitor();
440   MockQuicConnectionVisitor(const MockQuicConnectionVisitor&) = delete;
441   MockQuicConnectionVisitor& operator=(const MockQuicConnectionVisitor&) =
442       delete;
443   ~MockQuicConnectionVisitor() override;
444 
445   MOCK_METHOD(void, OnStreamFrame, (const QuicStreamFrame& frame), (override));
446   MOCK_METHOD(void, OnCryptoFrame, (const QuicCryptoFrame& frame), (override));
447   MOCK_METHOD(void, OnWindowUpdateFrame, (const QuicWindowUpdateFrame& frame),
448               (override));
449   MOCK_METHOD(void, OnBlockedFrame, (const QuicBlockedFrame& frame),
450               (override));
451   MOCK_METHOD(void, OnRstStream, (const QuicRstStreamFrame& frame), (override));
452   MOCK_METHOD(void, OnGoAway, (const QuicGoAwayFrame& frame), (override));
453   MOCK_METHOD(void, OnMessageReceived, (absl::string_view message), (override));
454   MOCK_METHOD(void, OnHandshakeDoneReceived, (), (override));
455   MOCK_METHOD(void, OnNewTokenReceived, (absl::string_view token), (override));
456   MOCK_METHOD(void, OnConnectionClosed,
457               (const QuicConnectionCloseFrame& frame,
458                ConnectionCloseSource source),
459               (override));
460   MOCK_METHOD(void, OnWriteBlocked, (), (override));
461   MOCK_METHOD(void, OnCanWrite, (), (override));
462   MOCK_METHOD(void, OnCongestionWindowChange, (QuicTime now), (override));
463   MOCK_METHOD(void, OnConnectionMigration, (AddressChangeType type),
464               (override));
465   MOCK_METHOD(void, OnPathDegrading, (), (override));
466   MOCK_METHOD(void, OnForwardProgressMadeAfterPathDegrading, (), (override));
467   MOCK_METHOD(bool, WillingAndAbleToWrite, (), (const, override));
468   MOCK_METHOD(bool, ShouldKeepConnectionAlive, (), (const, override));
469   MOCK_METHOD(std::string, GetStreamsInfoForLogging, (), (const, override));
470   MOCK_METHOD(void, OnSuccessfulVersionNegotiation,
471               (const ParsedQuicVersion& version), (override));
472   MOCK_METHOD(void, OnPacketReceived,
473               (const QuicSocketAddress& self_address,
474                const QuicSocketAddress& peer_address,
475                bool is_connectivity_probe),
476               (override));
477   MOCK_METHOD(void, OnAckNeedsRetransmittableFrame, (), (override));
478   MOCK_METHOD(void, SendAckFrequency, (const QuicAckFrequencyFrame& frame),
479               (override));
480   MOCK_METHOD(void, SendNewConnectionId,
481               (const QuicNewConnectionIdFrame& frame), (override));
482   MOCK_METHOD(void, SendRetireConnectionId, (uint64_t sequence_number),
483               (override));
484   MOCK_METHOD(bool, MaybeReserveConnectionId,
485               (const QuicConnectionId& server_connection_id), (override));
486   MOCK_METHOD(void, OnServerConnectionIdRetired,
487               (const QuicConnectionId& server_connection_id), (override));
488   MOCK_METHOD(bool, AllowSelfAddressChange, (), (const, override));
489   MOCK_METHOD(HandshakeState, GetHandshakeState, (), (const, override));
490   MOCK_METHOD(bool, OnMaxStreamsFrame, (const QuicMaxStreamsFrame& frame),
491               (override));
492   MOCK_METHOD(bool, OnStreamsBlockedFrame,
493               (const QuicStreamsBlockedFrame& frame), (override));
494   MOCK_METHOD(void, OnStopSendingFrame, (const QuicStopSendingFrame& frame),
495               (override));
496   MOCK_METHOD(void, OnPacketDecrypted, (EncryptionLevel), (override));
497   MOCK_METHOD(void, OnOneRttPacketAcknowledged, (), (override));
498   MOCK_METHOD(void, OnHandshakePacketSent, (), (override));
499   MOCK_METHOD(void, OnKeyUpdate, (KeyUpdateReason), (override));
500   MOCK_METHOD(std::unique_ptr<QuicDecrypter>,
501               AdvanceKeysAndCreateCurrentOneRttDecrypter, (), (override));
502   MOCK_METHOD(std::unique_ptr<QuicEncrypter>, CreateCurrentOneRttEncrypter, (),
503               (override));
504   MOCK_METHOD(void, BeforeConnectionCloseSent, (), (override));
505   MOCK_METHOD(bool, ValidateToken, (absl::string_view), (override));
506   MOCK_METHOD(bool, MaybeSendAddressToken, (), (override));
507   MOCK_METHOD(std::unique_ptr<QuicPathValidationContext>,
508               CreateContextForMultiPortPath, (), (override));
509   MOCK_METHOD(void, MigrateToMultiPortPath,
510               (std::unique_ptr<QuicPathValidationContext>), (override));
511   MOCK_METHOD(void, OnServerPreferredAddressAvailable,
512               (const QuicSocketAddress&), (override));
OnBandwidthUpdateTimeout()513   void OnBandwidthUpdateTimeout() override {}
514 };
515 
516 class MockQuicConnectionHelper : public QuicConnectionHelperInterface {
517  public:
518   MockQuicConnectionHelper();
519   MockQuicConnectionHelper(const MockQuicConnectionHelper&) = delete;
520   MockQuicConnectionHelper& operator=(const MockQuicConnectionHelper&) = delete;
521   ~MockQuicConnectionHelper() override;
522   const QuicClock* GetClock() const override;
523   QuicClock* GetClock();
524   QuicRandom* GetRandomGenerator() override;
525   quiche::QuicheBufferAllocator* GetStreamSendBufferAllocator() override;
526   void AdvanceTime(QuicTime::Delta delta);
527 
528  private:
529   MockClock clock_;
530   testing::NiceMock<MockRandom> random_generator_;
531   quiche::SimpleBufferAllocator buffer_allocator_;
532 };
533 
534 class MockAlarmFactory : public QuicAlarmFactory {
535  public:
536   QuicAlarm* CreateAlarm(QuicAlarm::Delegate* delegate) override;
537   QuicArenaScopedPtr<QuicAlarm> CreateAlarm(
538       QuicArenaScopedPtr<QuicAlarm::Delegate> delegate,
539       QuicConnectionArena* arena) override;
540 
541   // No-op alarm implementation
542   class TestAlarm : public QuicAlarm {
543    public:
TestAlarm(QuicArenaScopedPtr<QuicAlarm::Delegate> delegate)544     explicit TestAlarm(QuicArenaScopedPtr<QuicAlarm::Delegate> delegate)
545         : QuicAlarm(std::move(delegate)) {}
546 
SetImpl()547     void SetImpl() override {}
CancelImpl()548     void CancelImpl() override {}
549 
550     using QuicAlarm::Fire;
551   };
552 
FireAlarm(QuicAlarm * alarm)553   void FireAlarm(QuicAlarm* alarm) {
554     reinterpret_cast<TestAlarm*>(alarm)->Fire();
555   }
556 };
557 
558 class TestAlarmFactory : public QuicAlarmFactory {
559  public:
560   class TestAlarm : public QuicAlarm {
561    public:
TestAlarm(QuicArenaScopedPtr<QuicAlarm::Delegate> delegate)562     explicit TestAlarm(QuicArenaScopedPtr<QuicAlarm::Delegate> delegate)
563         : QuicAlarm(std::move(delegate)) {}
564 
SetImpl()565     void SetImpl() override {}
CancelImpl()566     void CancelImpl() override {}
567     using QuicAlarm::Fire;
568   };
569 
TestAlarmFactory()570   TestAlarmFactory() {}
571   TestAlarmFactory(const TestAlarmFactory&) = delete;
572   TestAlarmFactory& operator=(const TestAlarmFactory&) = delete;
573 
CreateAlarm(QuicAlarm::Delegate * delegate)574   QuicAlarm* CreateAlarm(QuicAlarm::Delegate* delegate) override {
575     return new TestAlarm(QuicArenaScopedPtr<QuicAlarm::Delegate>(delegate));
576   }
577 
CreateAlarm(QuicArenaScopedPtr<QuicAlarm::Delegate> delegate,QuicConnectionArena * arena)578   QuicArenaScopedPtr<QuicAlarm> CreateAlarm(
579       QuicArenaScopedPtr<QuicAlarm::Delegate> delegate,
580       QuicConnectionArena* arena) override {
581     return arena->New<TestAlarm>(std::move(delegate));
582   }
583 };
584 
585 class MockQuicConnection : public QuicConnection {
586  public:
587   // Uses a ConnectionId of 42 and 127.0.0.1:123.
588   MockQuicConnection(QuicConnectionHelperInterface* helper,
589                      QuicAlarmFactory* alarm_factory, Perspective perspective);
590 
591   // Uses a ConnectionId of 42.
592   MockQuicConnection(QuicSocketAddress address,
593                      QuicConnectionHelperInterface* helper,
594                      QuicAlarmFactory* alarm_factory, Perspective perspective);
595 
596   // Uses 127.0.0.1:123.
597   MockQuicConnection(QuicConnectionId connection_id,
598                      QuicConnectionHelperInterface* helper,
599                      QuicAlarmFactory* alarm_factory, Perspective perspective);
600 
601   // Uses a ConnectionId of 42, and 127.0.0.1:123.
602   MockQuicConnection(QuicConnectionHelperInterface* helper,
603                      QuicAlarmFactory* alarm_factory, Perspective perspective,
604                      const ParsedQuicVersionVector& supported_versions);
605 
606   MockQuicConnection(QuicConnectionId connection_id, QuicSocketAddress address,
607                      QuicConnectionHelperInterface* helper,
608                      QuicAlarmFactory* alarm_factory, Perspective perspective,
609                      const ParsedQuicVersionVector& supported_versions);
610   MockQuicConnection(const MockQuicConnection&) = delete;
611   MockQuicConnection& operator=(const MockQuicConnection&) = delete;
612 
613   ~MockQuicConnection() override;
614 
615   // If the constructor that uses a QuicConnectionHelperInterface has been used
616   // then this method will advance the time of the MockClock.
617   void AdvanceTime(QuicTime::Delta delta);
618 
619   MOCK_METHOD(void, ProcessUdpPacket,
620               (const QuicSocketAddress& self_address,
621                const QuicSocketAddress& peer_address,
622                const QuicReceivedPacket& packet),
623               (override));
624   MOCK_METHOD(void, CloseConnection,
625               (QuicErrorCode error, const std::string& details,
626                ConnectionCloseBehavior connection_close_behavior),
627               (override));
628   MOCK_METHOD(void, CloseConnection,
629               (QuicErrorCode error, QuicIetfTransportErrorCodes ietf_error,
630                const std::string& details,
631                ConnectionCloseBehavior connection_close_behavior),
632               (override));
633   MOCK_METHOD(void, SendConnectionClosePacket,
634               (QuicErrorCode error, QuicIetfTransportErrorCodes ietf_error,
635                const std::string& details),
636               (override));
637   MOCK_METHOD(void, OnCanWrite, (), (override));
638   MOCK_METHOD(bool, SendConnectivityProbingPacket,
639               (QuicPacketWriter*, const QuicSocketAddress& peer_address),
640               (override));
641   MOCK_METHOD(void, MaybeProbeMultiPortPath, (), (override));
642 
643   MOCK_METHOD(void, OnSendConnectionState, (const CachedNetworkParameters&),
644               (override));
645   MOCK_METHOD(void, ResumeConnectionState,
646               (const CachedNetworkParameters&, bool), (override));
647   MOCK_METHOD(void, SetMaxPacingRate, (QuicBandwidth), (override));
648 
649   MOCK_METHOD(void, OnStreamReset, (QuicStreamId, QuicRstStreamErrorCode),
650               (override));
651   MOCK_METHOD(bool, SendControlFrame, (const QuicFrame& frame), (override));
652   MOCK_METHOD(MessageStatus, SendMessage,
653               (QuicMessageId, absl::Span<quiche::QuicheMemSlice>, bool),
654               (override));
655   MOCK_METHOD(bool, SendPathChallenge,
656               (const QuicPathFrameBuffer&, const QuicSocketAddress&,
657                const QuicSocketAddress&, const QuicSocketAddress&,
658                QuicPacketWriter*),
659               (override));
660 
661   MOCK_METHOD(void, OnError, (QuicFramer*), (override));
QuicConnection_OnError(QuicFramer * framer)662   void QuicConnection_OnError(QuicFramer* framer) {
663     QuicConnection::OnError(framer);
664   }
665 
ReallyOnCanWrite()666   void ReallyOnCanWrite() { QuicConnection::OnCanWrite(); }
667 
ReallyCloseConnection(QuicErrorCode error,const std::string & details,ConnectionCloseBehavior connection_close_behavior)668   void ReallyCloseConnection(
669       QuicErrorCode error, const std::string& details,
670       ConnectionCloseBehavior connection_close_behavior) {
671     // Call the 4-param method directly instead of the 3-param method, so that
672     // it doesn't invoke the virtual 4-param method causing the mock 4-param
673     // method to trigger.
674     QuicConnection::CloseConnection(error, NO_IETF_QUIC_ERROR, details,
675                                     connection_close_behavior);
676   }
677 
ReallyCloseConnection4(QuicErrorCode error,QuicIetfTransportErrorCodes ietf_error,const std::string & details,ConnectionCloseBehavior connection_close_behavior)678   void ReallyCloseConnection4(
679       QuicErrorCode error, QuicIetfTransportErrorCodes ietf_error,
680       const std::string& details,
681       ConnectionCloseBehavior connection_close_behavior) {
682     QuicConnection::CloseConnection(error, ietf_error, details,
683                                     connection_close_behavior);
684   }
685 
ReallySendConnectionClosePacket(QuicErrorCode error,QuicIetfTransportErrorCodes ietf_error,const std::string & details)686   void ReallySendConnectionClosePacket(QuicErrorCode error,
687                                        QuicIetfTransportErrorCodes ietf_error,
688                                        const std::string& details) {
689     QuicConnection::SendConnectionClosePacket(error, ietf_error, details);
690   }
691 
ReallyProcessUdpPacket(const QuicSocketAddress & self_address,const QuicSocketAddress & peer_address,const QuicReceivedPacket & packet)692   void ReallyProcessUdpPacket(const QuicSocketAddress& self_address,
693                               const QuicSocketAddress& peer_address,
694                               const QuicReceivedPacket& packet) {
695     QuicConnection::ProcessUdpPacket(self_address, peer_address, packet);
696   }
697 
698   bool OnProtocolVersionMismatch(ParsedQuicVersion version) override;
OnIdleNetworkDetected()699   void OnIdleNetworkDetected() override {}
700 
ReallySendControlFrame(const QuicFrame & frame)701   bool ReallySendControlFrame(const QuicFrame& frame) {
702     return QuicConnection::SendControlFrame(frame);
703   }
704 
ReallySendConnectivityProbingPacket(QuicPacketWriter * probing_writer,const QuicSocketAddress & peer_address)705   bool ReallySendConnectivityProbingPacket(
706       QuicPacketWriter* probing_writer, const QuicSocketAddress& peer_address) {
707     return QuicConnection::SendConnectivityProbingPacket(probing_writer,
708                                                          peer_address);
709   }
710 
ReallyOnPathResponseFrame(const QuicPathResponseFrame & frame)711   bool ReallyOnPathResponseFrame(const QuicPathResponseFrame& frame) {
712     return QuicConnection::OnPathResponseFrame(frame);
713   }
714 
715   MOCK_METHOD(bool, OnPathResponseFrame, (const QuicPathResponseFrame&),
716               (override));
717   MOCK_METHOD(bool, OnStopSendingFrame, (const QuicStopSendingFrame& frame),
718               (override));
719   MOCK_METHOD(size_t, SendCryptoData,
720               (EncryptionLevel, size_t, QuicStreamOffset), (override));
QuicConnection_SendCryptoData(EncryptionLevel level,size_t write_length,QuicStreamOffset offset)721   size_t QuicConnection_SendCryptoData(EncryptionLevel level,
722                                        size_t write_length,
723                                        QuicStreamOffset offset) {
724     return QuicConnection::SendCryptoData(level, write_length, offset);
725   }
726 
connection_id_generator()727   MockConnectionIdGenerator& connection_id_generator() {
728     return connection_id_generator_;
729   }
730 
731  private:
732   // It would be more correct to pass the generator as an argument to the
733   // constructor, particularly in dispatcher tests that keep their own
734   // reference to a generator. But there are many, many instances of derived
735   // test classes that would have to declare a generator. As this object is
736   // public, it is straightforward for the caller to use it as an argument to
737   // EXPECT_CALL.
738   MockConnectionIdGenerator connection_id_generator_;
739 };
740 
741 class PacketSavingConnection : public MockQuicConnection {
742  public:
743   PacketSavingConnection(QuicConnectionHelperInterface* helper,
744                          QuicAlarmFactory* alarm_factory,
745                          Perspective perspective);
746 
747   PacketSavingConnection(QuicConnectionHelperInterface* helper,
748                          QuicAlarmFactory* alarm_factory,
749                          Perspective perspective,
750                          const ParsedQuicVersionVector& supported_versions);
751   PacketSavingConnection(const PacketSavingConnection&) = delete;
752   PacketSavingConnection& operator=(const PacketSavingConnection&) = delete;
753 
754   ~PacketSavingConnection() override;
755 
756   SerializedPacketFate GetSerializedPacketFate(
757       bool is_mtu_discovery, EncryptionLevel encryption_level) override;
758 
759   void SendOrQueuePacket(SerializedPacket packet) override;
760 
761   MOCK_METHOD(void, OnPacketSent, (EncryptionLevel, TransmissionType));
762 
763   std::vector<std::unique_ptr<QuicEncryptedPacket>> encrypted_packets_;
764   // Number of packets in encrypted_packets that has been delivered to the peer
765   // connection.
766   size_t number_of_packets_delivered_ = 0;
767   MockClock clock_;
768 };
769 
770 class MockQuicSession : public QuicSession {
771  public:
772   // Takes ownership of |connection|.
773   MockQuicSession(QuicConnection* connection, bool create_mock_crypto_stream);
774 
775   // Takes ownership of |connection|.
776   explicit MockQuicSession(QuicConnection* connection);
777   MockQuicSession(const MockQuicSession&) = delete;
778   MockQuicSession& operator=(const MockQuicSession&) = delete;
779   ~MockQuicSession() override;
780 
781   QuicCryptoStream* GetMutableCryptoStream() override;
782   const QuicCryptoStream* GetCryptoStream() const override;
783   void SetCryptoStream(QuicCryptoStream* crypto_stream);
784 
785   MOCK_METHOD(void, OnConnectionClosed,
786               (const QuicConnectionCloseFrame& frame,
787                ConnectionCloseSource source),
788               (override));
789   MOCK_METHOD(QuicStream*, CreateIncomingStream, (QuicStreamId id), (override));
790   MOCK_METHOD(QuicSpdyStream*, CreateIncomingStream, (PendingStream*),
791               (override));
792   MOCK_METHOD(QuicConsumedData, WritevData,
793               (QuicStreamId id, size_t write_length, QuicStreamOffset offset,
794                StreamSendingState state, TransmissionType type,
795                EncryptionLevel level),
796               (override));
797   MOCK_METHOD(bool, WriteControlFrame,
798               (const QuicFrame& frame, TransmissionType type), (override));
799   MOCK_METHOD(void, MaybeSendRstStreamFrame,
800               (QuicStreamId stream_id, QuicResetStreamError error,
801                QuicStreamOffset bytes_written),
802               (override));
803   MOCK_METHOD(void, MaybeSendStopSendingFrame,
804               (QuicStreamId stream_id, QuicResetStreamError error), (override));
805   MOCK_METHOD(void, SendBlocked,
806               (QuicStreamId stream_id, QuicStreamOffset offset), (override));
807 
808   MOCK_METHOD(bool, ShouldKeepConnectionAlive, (), (const, override));
809   MOCK_METHOD(std::vector<std::string>, GetAlpnsToOffer, (), (const, override));
810   MOCK_METHOD(std::vector<absl::string_view>::const_iterator, SelectAlpn,
811               (const std::vector<absl::string_view>&), (const, override));
812   MOCK_METHOD(void, OnAlpnSelected, (absl::string_view), (override));
813 
814   using QuicSession::ActivateStream;
815 
816   // Returns a QuicConsumedData that indicates all of |write_length| (and |fin|
817   // if set) has been consumed.
818   QuicConsumedData ConsumeData(QuicStreamId id, size_t write_length,
819                                QuicStreamOffset offset,
820                                StreamSendingState state, TransmissionType type,
821                                absl::optional<EncryptionLevel> level);
822 
ReallyMaybeSendRstStreamFrame(QuicStreamId id,QuicRstStreamErrorCode error,QuicStreamOffset bytes_written)823   void ReallyMaybeSendRstStreamFrame(QuicStreamId id,
824                                      QuicRstStreamErrorCode error,
825                                      QuicStreamOffset bytes_written) {
826     QuicSession::MaybeSendRstStreamFrame(
827         id, QuicResetStreamError::FromInternal(error), bytes_written);
828   }
829 
830  private:
831   std::unique_ptr<QuicCryptoStream> crypto_stream_;
832 };
833 
834 class MockQuicCryptoStream : public QuicCryptoStream {
835  public:
836   explicit MockQuicCryptoStream(QuicSession* session);
837 
838   ~MockQuicCryptoStream() override;
839 
840   ssl_early_data_reason_t EarlyDataReason() const override;
841   bool encryption_established() const override;
842   bool one_rtt_keys_available() const override;
843   const QuicCryptoNegotiatedParameters& crypto_negotiated_params()
844       const override;
845   CryptoMessageParser* crypto_message_parser() override;
OnPacketDecrypted(EncryptionLevel)846   void OnPacketDecrypted(EncryptionLevel /*level*/) override {}
OnOneRttPacketAcknowledged()847   void OnOneRttPacketAcknowledged() override {}
OnHandshakePacketSent()848   void OnHandshakePacketSent() override {}
OnHandshakeDoneReceived()849   void OnHandshakeDoneReceived() override {}
OnNewTokenReceived(absl::string_view)850   void OnNewTokenReceived(absl::string_view /*token*/) override {}
GetAddressToken(const CachedNetworkParameters *)851   std::string GetAddressToken(
852       const CachedNetworkParameters* /*cached_network_parameters*/)
853       const override {
854     return "";
855   }
ValidateAddressToken(absl::string_view)856   bool ValidateAddressToken(absl::string_view /*token*/) const override {
857     return true;
858   }
PreviousCachedNetworkParams()859   const CachedNetworkParameters* PreviousCachedNetworkParams() const override {
860     return nullptr;
861   }
SetPreviousCachedNetworkParams(CachedNetworkParameters)862   void SetPreviousCachedNetworkParams(
863       CachedNetworkParameters /*cached_network_params*/) override {}
OnConnectionClosed(QuicErrorCode,ConnectionCloseSource)864   void OnConnectionClosed(QuicErrorCode /*error*/,
865                           ConnectionCloseSource /*source*/) override {}
GetHandshakeState()866   HandshakeState GetHandshakeState() const override { return HANDSHAKE_START; }
SetServerApplicationStateForResumption(std::unique_ptr<ApplicationState>)867   void SetServerApplicationStateForResumption(
868       std::unique_ptr<ApplicationState> /*application_state*/) override {}
AdvanceKeysAndCreateCurrentOneRttDecrypter()869   std::unique_ptr<QuicDecrypter> AdvanceKeysAndCreateCurrentOneRttDecrypter()
870       override {
871     return nullptr;
872   }
CreateCurrentOneRttEncrypter()873   std::unique_ptr<QuicEncrypter> CreateCurrentOneRttEncrypter() override {
874     return nullptr;
875   }
ExportKeyingMaterial(absl::string_view,absl::string_view,size_t,std::string *)876   bool ExportKeyingMaterial(absl::string_view /*label*/,
877                             absl::string_view /*context*/,
878                             size_t /*result_len*/,
879                             std::string* /*result*/) override {
880     return false;
881   }
GetSsl()882   SSL* GetSsl() const override { return nullptr; }
IsCryptoFrameExpectedForEncryptionLevel(quic::EncryptionLevel level)883   bool IsCryptoFrameExpectedForEncryptionLevel(
884       quic::EncryptionLevel level) const override {
885     return level != ENCRYPTION_ZERO_RTT;
886   }
GetEncryptionLevelToSendCryptoDataOfSpace(PacketNumberSpace space)887   EncryptionLevel GetEncryptionLevelToSendCryptoDataOfSpace(
888       PacketNumberSpace space) const override {
889     switch (space) {
890       case INITIAL_DATA:
891         return ENCRYPTION_INITIAL;
892       case HANDSHAKE_DATA:
893         return ENCRYPTION_HANDSHAKE;
894       case APPLICATION_DATA:
895         return ENCRYPTION_FORWARD_SECURE;
896       default:
897         QUICHE_DCHECK(false);
898         return NUM_ENCRYPTION_LEVELS;
899     }
900   }
901 
902  private:
903   quiche::QuicheReferenceCountedPointer<QuicCryptoNegotiatedParameters> params_;
904   CryptoFramer crypto_framer_;
905 };
906 
907 class MockQuicSpdySession : public QuicSpdySession {
908  public:
909   // Takes ownership of |connection|.
910   explicit MockQuicSpdySession(QuicConnection* connection);
911   // Takes ownership of |connection|.
912   MockQuicSpdySession(QuicConnection* connection,
913                       bool create_mock_crypto_stream);
914   MockQuicSpdySession(const MockQuicSpdySession&) = delete;
915   MockQuicSpdySession& operator=(const MockQuicSpdySession&) = delete;
916   ~MockQuicSpdySession() override;
917 
918   QuicCryptoStream* GetMutableCryptoStream() override;
919   const QuicCryptoStream* GetCryptoStream() const override;
920   void SetCryptoStream(QuicCryptoStream* crypto_stream);
921 
ReallyOnConnectionClosed(const QuicConnectionCloseFrame & frame,ConnectionCloseSource source)922   void ReallyOnConnectionClosed(const QuicConnectionCloseFrame& frame,
923                                 ConnectionCloseSource source) {
924     QuicSession::OnConnectionClosed(frame, source);
925   }
926 
927   // From QuicSession.
928   MOCK_METHOD(void, OnConnectionClosed,
929               (const QuicConnectionCloseFrame& frame,
930                ConnectionCloseSource source),
931               (override));
932   MOCK_METHOD(QuicSpdyStream*, CreateIncomingStream, (QuicStreamId id),
933               (override));
934   MOCK_METHOD(QuicSpdyStream*, CreateIncomingStream, (PendingStream*),
935               (override));
936   MOCK_METHOD(QuicSpdyStream*, CreateOutgoingBidirectionalStream, (),
937               (override));
938   MOCK_METHOD(QuicSpdyStream*, CreateOutgoingUnidirectionalStream, (),
939               (override));
940   MOCK_METHOD(bool, ShouldCreateIncomingStream, (QuicStreamId id), (override));
941   MOCK_METHOD(bool, ShouldCreateOutgoingBidirectionalStream, (), (override));
942   MOCK_METHOD(bool, ShouldCreateOutgoingUnidirectionalStream, (), (override));
943   MOCK_METHOD(QuicConsumedData, WritevData,
944               (QuicStreamId id, size_t write_length, QuicStreamOffset offset,
945                StreamSendingState state, TransmissionType type,
946                EncryptionLevel level),
947               (override));
948   MOCK_METHOD(void, MaybeSendRstStreamFrame,
949               (QuicStreamId stream_id, QuicResetStreamError error,
950                QuicStreamOffset bytes_written),
951               (override));
952   MOCK_METHOD(void, MaybeSendStopSendingFrame,
953               (QuicStreamId stream_id, QuicResetStreamError error), (override));
954   MOCK_METHOD(void, SendWindowUpdate,
955               (QuicStreamId id, QuicStreamOffset byte_offset), (override));
956   MOCK_METHOD(void, SendBlocked,
957               (QuicStreamId id, QuicStreamOffset byte_offset), (override));
958   MOCK_METHOD(void, OnStreamHeadersPriority,
959               (QuicStreamId stream_id,
960                const spdy::SpdyStreamPrecedence& precedence),
961               (override));
962   MOCK_METHOD(void, OnStreamHeaderList,
963               (QuicStreamId stream_id, bool fin, size_t frame_len,
964                const QuicHeaderList& header_list),
965               (override));
966   MOCK_METHOD(void, OnPromiseHeaderList,
967               (QuicStreamId stream_id, QuicStreamId promised_stream_id,
968                size_t frame_len, const QuicHeaderList& header_list),
969               (override));
970   MOCK_METHOD(void, OnPriorityFrame,
971               (QuicStreamId id, const spdy::SpdyStreamPrecedence& precedence),
972               (override));
973   MOCK_METHOD(void, OnCongestionWindowChange, (QuicTime now), (override));
974 
975   // Returns a QuicConsumedData that indicates all of |write_length| (and |fin|
976   // if set) has been consumed.
977   QuicConsumedData ConsumeData(QuicStreamId id, size_t write_length,
978                                QuicStreamOffset offset,
979                                StreamSendingState state, TransmissionType type,
980                                absl::optional<EncryptionLevel> level);
981 
982   using QuicSession::ActivateStream;
983 
984  private:
985   std::unique_ptr<QuicCryptoStream> crypto_stream_;
986 };
987 
988 class MockHttp3DebugVisitor : public Http3DebugVisitor {
989  public:
990   MOCK_METHOD(void, OnControlStreamCreated, (QuicStreamId), (override));
991   MOCK_METHOD(void, OnQpackEncoderStreamCreated, (QuicStreamId), (override));
992   MOCK_METHOD(void, OnQpackDecoderStreamCreated, (QuicStreamId), (override));
993   MOCK_METHOD(void, OnPeerControlStreamCreated, (QuicStreamId), (override));
994   MOCK_METHOD(void, OnPeerQpackEncoderStreamCreated, (QuicStreamId),
995               (override));
996   MOCK_METHOD(void, OnPeerQpackDecoderStreamCreated, (QuicStreamId),
997               (override));
998 
999   MOCK_METHOD(void, OnSettingsFrameReceivedViaAlps, (const SettingsFrame&),
1000               (override));
1001 
1002   MOCK_METHOD(void, OnAcceptChFrameReceivedViaAlps, (const AcceptChFrame&),
1003               (override));
1004 
1005   MOCK_METHOD(void, OnSettingsFrameReceived, (const SettingsFrame&),
1006               (override));
1007   MOCK_METHOD(void, OnGoAwayFrameReceived, (const GoAwayFrame&), (override));
1008   MOCK_METHOD(void, OnPriorityUpdateFrameReceived, (const PriorityUpdateFrame&),
1009               (override));
1010   MOCK_METHOD(void, OnAcceptChFrameReceived, (const AcceptChFrame&),
1011               (override));
1012 
1013   MOCK_METHOD(void, OnDataFrameReceived, (QuicStreamId, QuicByteCount),
1014               (override));
1015   MOCK_METHOD(void, OnHeadersFrameReceived, (QuicStreamId, QuicByteCount),
1016               (override));
1017   MOCK_METHOD(void, OnHeadersDecoded, (QuicStreamId, QuicHeaderList),
1018               (override));
1019   MOCK_METHOD(void, OnUnknownFrameReceived,
1020               (QuicStreamId, uint64_t, QuicByteCount), (override));
1021 
1022   MOCK_METHOD(void, OnSettingsFrameSent, (const SettingsFrame&), (override));
1023   MOCK_METHOD(void, OnGoAwayFrameSent, (QuicStreamId), (override));
1024   MOCK_METHOD(void, OnPriorityUpdateFrameSent, (const PriorityUpdateFrame&),
1025               (override));
1026 
1027   MOCK_METHOD(void, OnDataFrameSent, (QuicStreamId, QuicByteCount), (override));
1028   MOCK_METHOD(void, OnHeadersFrameSent,
1029               (QuicStreamId, const spdy::Http2HeaderBlock&), (override));
1030   MOCK_METHOD(void, OnSettingsFrameResumed, (const SettingsFrame&), (override));
1031 };
1032 
1033 class TestQuicSpdyServerSession : public QuicServerSessionBase {
1034  public:
1035   // Takes ownership of |connection|.
1036   TestQuicSpdyServerSession(QuicConnection* connection,
1037                             const QuicConfig& config,
1038                             const ParsedQuicVersionVector& supported_versions,
1039                             const QuicCryptoServerConfig* crypto_config,
1040                             QuicCompressedCertsCache* compressed_certs_cache);
1041   TestQuicSpdyServerSession(const TestQuicSpdyServerSession&) = delete;
1042   TestQuicSpdyServerSession& operator=(const TestQuicSpdyServerSession&) =
1043       delete;
1044   ~TestQuicSpdyServerSession() override;
1045 
1046   MOCK_METHOD(QuicSpdyStream*, CreateIncomingStream, (QuicStreamId id),
1047               (override));
1048   MOCK_METHOD(QuicSpdyStream*, CreateIncomingStream, (PendingStream*),
1049               (override));
1050   MOCK_METHOD(QuicSpdyStream*, CreateOutgoingBidirectionalStream, (),
1051               (override));
1052   MOCK_METHOD(QuicSpdyStream*, CreateOutgoingUnidirectionalStream, (),
1053               (override));
1054   MOCK_METHOD(std::vector<absl::string_view>::const_iterator, SelectAlpn,
1055               (const std::vector<absl::string_view>&), (const, override));
1056   MOCK_METHOD(void, OnAlpnSelected, (absl::string_view), (override));
1057   std::unique_ptr<QuicCryptoServerStreamBase> CreateQuicCryptoServerStream(
1058       const QuicCryptoServerConfig* crypto_config,
1059       QuicCompressedCertsCache* compressed_certs_cache) override;
1060 
1061   QuicCryptoServerStreamBase* GetMutableCryptoStream() override;
1062 
1063   const QuicCryptoServerStreamBase* GetCryptoStream() const override;
1064 
helper()1065   MockQuicCryptoServerStreamHelper* helper() { return &helper_; }
1066 
GetSSLConfig()1067   QuicSSLConfig GetSSLConfig() const override {
1068     QuicSSLConfig ssl_config = QuicServerSessionBase::GetSSLConfig();
1069     if (early_data_enabled_.has_value()) {
1070       ssl_config.early_data_enabled = *early_data_enabled_;
1071     }
1072     if (client_cert_mode_.has_value()) {
1073       ssl_config.client_cert_mode = *client_cert_mode_;
1074     }
1075 
1076     return ssl_config;
1077   }
1078 
set_early_data_enabled(bool enabled)1079   void set_early_data_enabled(bool enabled) { early_data_enabled_ = enabled; }
1080 
set_client_cert_mode(ClientCertMode mode)1081   void set_client_cert_mode(ClientCertMode mode) { client_cert_mode_ = mode; }
1082 
1083  private:
1084   MockQuicSessionVisitor visitor_;
1085   MockQuicCryptoServerStreamHelper helper_;
1086   // If not nullopt, override the early_data_enabled value from base class'
1087   // ssl_config.
1088   absl::optional<bool> early_data_enabled_;
1089   // If not nullopt, override the client_cert_mode value from base class'
1090   // ssl_config.
1091   absl::optional<ClientCertMode> client_cert_mode_;
1092 };
1093 
1094 // A test implementation of QuicClientPushPromiseIndex::Delegate.
1095 class TestPushPromiseDelegate : public QuicClientPushPromiseIndex::Delegate {
1096  public:
1097   // |match| sets the validation result for checking whether designated header
1098   // fields match for promise request and client request.
1099   explicit TestPushPromiseDelegate(bool match);
1100 
1101   bool CheckVary(const spdy::Http2HeaderBlock& client_request,
1102                  const spdy::Http2HeaderBlock& promise_request,
1103                  const spdy::Http2HeaderBlock& promise_response) override;
1104 
1105   void OnRendezvousResult(QuicSpdyStream* stream) override;
1106 
rendezvous_stream()1107   QuicSpdyStream* rendezvous_stream() { return rendezvous_stream_; }
rendezvous_fired()1108   bool rendezvous_fired() { return rendezvous_fired_; }
1109 
1110  private:
1111   bool match_;
1112   bool rendezvous_fired_;
1113   QuicSpdyStream* rendezvous_stream_;
1114 };
1115 
1116 class TestQuicSpdyClientSession : public QuicSpdyClientSessionBase {
1117  public:
1118   TestQuicSpdyClientSession(
1119       QuicConnection* connection, const QuicConfig& config,
1120       const ParsedQuicVersionVector& supported_versions,
1121       const QuicServerId& server_id, QuicCryptoClientConfig* crypto_config,
1122       absl::optional<QuicSSLConfig> ssl_config = absl::nullopt);
1123   TestQuicSpdyClientSession(const TestQuicSpdyClientSession&) = delete;
1124   TestQuicSpdyClientSession& operator=(const TestQuicSpdyClientSession&) =
1125       delete;
1126   ~TestQuicSpdyClientSession() override;
1127 
1128   bool IsAuthorized(const std::string& authority) override;
1129 
1130   // QuicSpdyClientSessionBase
1131   MOCK_METHOD(void, OnProofValid,
1132               (const QuicCryptoClientConfig::CachedState& cached), (override));
1133   MOCK_METHOD(void, OnProofVerifyDetailsAvailable,
1134               (const ProofVerifyDetails& verify_details), (override));
1135 
1136   // TestQuicSpdyClientSession
1137   MOCK_METHOD(QuicSpdyStream*, CreateIncomingStream, (QuicStreamId id),
1138               (override));
1139   MOCK_METHOD(QuicSpdyStream*, CreateIncomingStream, (PendingStream*),
1140               (override));
1141   MOCK_METHOD(QuicSpdyStream*, CreateOutgoingBidirectionalStream, (),
1142               (override));
1143   MOCK_METHOD(QuicSpdyStream*, CreateOutgoingUnidirectionalStream, (),
1144               (override));
1145   MOCK_METHOD(bool, ShouldCreateIncomingStream, (QuicStreamId id), (override));
1146   MOCK_METHOD(bool, ShouldCreateOutgoingBidirectionalStream, (), (override));
1147   MOCK_METHOD(bool, ShouldCreateOutgoingUnidirectionalStream, (), (override));
1148   MOCK_METHOD(std::vector<std::string>, GetAlpnsToOffer, (), (const, override));
1149   MOCK_METHOD(void, OnAlpnSelected, (absl::string_view), (override));
1150   MOCK_METHOD(void, OnConfigNegotiated, (), (override));
1151 
1152   QuicCryptoClientStream* GetMutableCryptoStream() override;
1153   const QuicCryptoClientStream* GetCryptoStream() const override;
1154 
GetSSLConfig()1155   QuicSSLConfig GetSSLConfig() const override {
1156     return ssl_config_.has_value() ? *ssl_config_
1157                                    : QuicSpdyClientSessionBase::GetSSLConfig();
1158   }
1159 
1160   // Override to save sent crypto handshake messages.
OnCryptoHandshakeMessageSent(const CryptoHandshakeMessage & message)1161   void OnCryptoHandshakeMessageSent(
1162       const CryptoHandshakeMessage& message) override {
1163     sent_crypto_handshake_messages_.push_back(message);
1164   }
1165 
sent_crypto_handshake_messages()1166   const std::vector<CryptoHandshakeMessage>& sent_crypto_handshake_messages()
1167       const {
1168     return sent_crypto_handshake_messages_;
1169   }
1170 
1171  private:
1172   // Calls the parent class's OnConfigNegotiated method. Used to set the default
1173   // mock behavior for OnConfigNegotiated.
1174   void RealOnConfigNegotiated();
1175 
1176   std::unique_ptr<QuicCryptoClientStream> crypto_stream_;
1177   QuicClientPushPromiseIndex push_promise_index_;
1178   std::vector<CryptoHandshakeMessage> sent_crypto_handshake_messages_;
1179   absl::optional<QuicSSLConfig> ssl_config_;
1180 };
1181 
1182 class MockPacketWriter : public QuicPacketWriter {
1183  public:
1184   MockPacketWriter();
1185   MockPacketWriter(const MockPacketWriter&) = delete;
1186   MockPacketWriter& operator=(const MockPacketWriter&) = delete;
1187   ~MockPacketWriter() override;
1188 
1189   MOCK_METHOD(WriteResult, WritePacket,
1190               (const char*, size_t buf_len, const QuicIpAddress& self_address,
1191                const QuicSocketAddress& peer_address, PerPacketOptions*),
1192               (override));
1193   MOCK_METHOD(bool, IsWriteBlocked, (), (const, override));
1194   MOCK_METHOD(void, SetWritable, (), (override));
1195   MOCK_METHOD(absl::optional<int>, MessageTooBigErrorCode, (),
1196               (const, override));
1197   MOCK_METHOD(QuicByteCount, GetMaxPacketSize,
1198               (const QuicSocketAddress& peer_address), (const, override));
1199   MOCK_METHOD(bool, SupportsReleaseTime, (), (const, override));
1200   MOCK_METHOD(bool, IsBatchMode, (), (const, override));
1201   MOCK_METHOD(QuicPacketBuffer, GetNextWriteLocation,
1202               (const QuicIpAddress& self_address,
1203                const QuicSocketAddress& peer_address),
1204               (override));
1205   MOCK_METHOD(WriteResult, Flush, (), (override));
1206 };
1207 
1208 class MockSendAlgorithm : public SendAlgorithmInterface {
1209  public:
1210   MockSendAlgorithm();
1211   MockSendAlgorithm(const MockSendAlgorithm&) = delete;
1212   MockSendAlgorithm& operator=(const MockSendAlgorithm&) = delete;
1213   ~MockSendAlgorithm() override;
1214 
1215   MOCK_METHOD(void, SetFromConfig,
1216               (const QuicConfig& config, Perspective perspective), (override));
1217   MOCK_METHOD(void, ApplyConnectionOptions,
1218               (const QuicTagVector& connection_options), (override));
1219   MOCK_METHOD(void, SetInitialCongestionWindowInPackets,
1220               (QuicPacketCount packets), (override));
1221   MOCK_METHOD(void, OnCongestionEvent,
1222               (bool rtt_updated, QuicByteCount bytes_in_flight,
1223                QuicTime event_time, const AckedPacketVector& acked_packets,
1224                const LostPacketVector& lost_packets, QuicPacketCount num_ect,
1225                QuicPacketCount num_ce),
1226               (override));
1227   MOCK_METHOD(void, OnPacketSent,
1228               (QuicTime, QuicByteCount, QuicPacketNumber, QuicByteCount,
1229                HasRetransmittableData),
1230               (override));
1231   MOCK_METHOD(void, OnPacketNeutered, (QuicPacketNumber), (override));
1232   MOCK_METHOD(void, OnRetransmissionTimeout, (bool), (override));
1233   MOCK_METHOD(void, OnConnectionMigration, (), (override));
1234   MOCK_METHOD(bool, CanSend, (QuicByteCount), (override));
1235   MOCK_METHOD(QuicBandwidth, PacingRate, (QuicByteCount), (const, override));
1236   MOCK_METHOD(QuicBandwidth, BandwidthEstimate, (), (const, override));
1237   MOCK_METHOD(bool, HasGoodBandwidthEstimateForResumption, (),
1238               (const, override));
1239   MOCK_METHOD(QuicByteCount, GetCongestionWindow, (), (const, override));
1240   MOCK_METHOD(std::string, GetDebugState, (), (const, override));
1241   MOCK_METHOD(bool, InSlowStart, (), (const, override));
1242   MOCK_METHOD(bool, InRecovery, (), (const, override));
1243   MOCK_METHOD(QuicByteCount, GetSlowStartThreshold, (), (const, override));
1244   MOCK_METHOD(CongestionControlType, GetCongestionControlType, (),
1245               (const, override));
1246   MOCK_METHOD(void, AdjustNetworkParameters, (const NetworkParams&),
1247               (override));
1248   MOCK_METHOD(void, OnApplicationLimited, (QuicByteCount), (override));
1249   MOCK_METHOD(void, PopulateConnectionStats, (QuicConnectionStats*),
1250               (const, override));
1251   MOCK_METHOD(bool, SupportsECT0, (), (const, override));
1252   MOCK_METHOD(bool, SupportsECT1, (), (const, override));
1253 };
1254 
1255 class MockLossAlgorithm : public LossDetectionInterface {
1256  public:
1257   MockLossAlgorithm();
1258   MockLossAlgorithm(const MockLossAlgorithm&) = delete;
1259   MockLossAlgorithm& operator=(const MockLossAlgorithm&) = delete;
1260   ~MockLossAlgorithm() override;
1261 
1262   MOCK_METHOD(void, SetFromConfig,
1263               (const QuicConfig& config, Perspective perspective), (override));
1264 
1265   MOCK_METHOD(DetectionStats, DetectLosses,
1266               (const QuicUnackedPacketMap& unacked_packets, QuicTime time,
1267                const RttStats& rtt_stats,
1268                QuicPacketNumber largest_recently_acked,
1269                const AckedPacketVector& packets_acked, LostPacketVector*),
1270               (override));
1271   MOCK_METHOD(QuicTime, GetLossTimeout, (), (const, override));
1272   MOCK_METHOD(void, SpuriousLossDetected,
1273               (const QuicUnackedPacketMap&, const RttStats&, QuicTime,
1274                QuicPacketNumber, QuicPacketNumber),
1275               (override));
1276 
1277   MOCK_METHOD(void, OnConfigNegotiated, (), (override));
1278   MOCK_METHOD(void, OnMinRttAvailable, (), (override));
1279   MOCK_METHOD(void, OnUserAgentIdKnown, (), (override));
1280   MOCK_METHOD(void, OnConnectionClosed, (), (override));
1281   MOCK_METHOD(void, OnReorderingDetected, (), (override));
1282 };
1283 
1284 class MockAckListener : public QuicAckListenerInterface {
1285  public:
1286   MockAckListener();
1287   MockAckListener(const MockAckListener&) = delete;
1288   MockAckListener& operator=(const MockAckListener&) = delete;
1289 
1290   MOCK_METHOD(void, OnPacketAcked,
1291               (int acked_bytes, QuicTime::Delta ack_delay_time), (override));
1292 
1293   MOCK_METHOD(void, OnPacketRetransmitted, (int retransmitted_bytes),
1294               (override));
1295 
1296  protected:
1297   // Object is ref counted.
1298   ~MockAckListener() override;
1299 };
1300 
1301 class MockNetworkChangeVisitor
1302     : public QuicSentPacketManager::NetworkChangeVisitor {
1303  public:
1304   MockNetworkChangeVisitor();
1305   MockNetworkChangeVisitor(const MockNetworkChangeVisitor&) = delete;
1306   MockNetworkChangeVisitor& operator=(const MockNetworkChangeVisitor&) = delete;
1307   ~MockNetworkChangeVisitor() override;
1308 
1309   MOCK_METHOD(void, OnCongestionChange, (), (override));
1310   MOCK_METHOD(void, OnPathMtuIncreased, (QuicPacketLength), (override));
1311 };
1312 
1313 class MockQuicConnectionDebugVisitor : public QuicConnectionDebugVisitor {
1314  public:
1315   MockQuicConnectionDebugVisitor();
1316   ~MockQuicConnectionDebugVisitor() override;
1317 
1318   MOCK_METHOD(void, OnPacketSent,
1319               (QuicPacketNumber, QuicPacketLength, bool, TransmissionType,
1320                EncryptionLevel, const QuicFrames&, const QuicFrames&, QuicTime),
1321               (override));
1322 
1323   MOCK_METHOD(void, OnCoalescedPacketSent, (const QuicCoalescedPacket&, size_t),
1324               (override));
1325 
1326   MOCK_METHOD(void, OnPingSent, (), (override));
1327 
1328   MOCK_METHOD(void, OnPacketReceived,
1329               (const QuicSocketAddress&, const QuicSocketAddress&,
1330                const QuicEncryptedPacket&),
1331               (override));
1332 
1333   MOCK_METHOD(void, OnIncorrectConnectionId, (QuicConnectionId), (override));
1334 
1335   MOCK_METHOD(void, OnProtocolVersionMismatch, (ParsedQuicVersion), (override));
1336 
1337   MOCK_METHOD(void, OnPacketHeader,
1338               (const QuicPacketHeader& header, QuicTime receive_time,
1339                EncryptionLevel level),
1340               (override));
1341 
1342   MOCK_METHOD(void, OnSuccessfulVersionNegotiation, (const ParsedQuicVersion&),
1343               (override));
1344 
1345   MOCK_METHOD(void, OnStreamFrame, (const QuicStreamFrame&), (override));
1346 
1347   MOCK_METHOD(void, OnCryptoFrame, (const QuicCryptoFrame&), (override));
1348 
1349   MOCK_METHOD(void, OnStopWaitingFrame, (const QuicStopWaitingFrame&),
1350               (override));
1351 
1352   MOCK_METHOD(void, OnRstStreamFrame, (const QuicRstStreamFrame&), (override));
1353 
1354   MOCK_METHOD(void, OnConnectionCloseFrame, (const QuicConnectionCloseFrame&),
1355               (override));
1356 
1357   MOCK_METHOD(void, OnBlockedFrame, (const QuicBlockedFrame&), (override));
1358 
1359   MOCK_METHOD(void, OnNewConnectionIdFrame, (const QuicNewConnectionIdFrame&),
1360               (override));
1361 
1362   MOCK_METHOD(void, OnRetireConnectionIdFrame,
1363               (const QuicRetireConnectionIdFrame&), (override));
1364 
1365   MOCK_METHOD(void, OnNewTokenFrame, (const QuicNewTokenFrame&), (override));
1366 
1367   MOCK_METHOD(void, OnMessageFrame, (const QuicMessageFrame&), (override));
1368 
1369   MOCK_METHOD(void, OnStopSendingFrame, (const QuicStopSendingFrame&),
1370               (override));
1371 
1372   MOCK_METHOD(void, OnPathChallengeFrame, (const QuicPathChallengeFrame&),
1373               (override));
1374 
1375   MOCK_METHOD(void, OnPathResponseFrame, (const QuicPathResponseFrame&),
1376               (override));
1377 
1378   MOCK_METHOD(void, OnPublicResetPacket, (const QuicPublicResetPacket&),
1379               (override));
1380 
1381   MOCK_METHOD(void, OnVersionNegotiationPacket,
1382               (const QuicVersionNegotiationPacket&), (override));
1383 
1384   MOCK_METHOD(void, OnTransportParametersSent, (const TransportParameters&),
1385               (override));
1386 
1387   MOCK_METHOD(void, OnTransportParametersReceived, (const TransportParameters&),
1388               (override));
1389 
1390   MOCK_METHOD(void, OnZeroRttRejected, (int), (override));
1391   MOCK_METHOD(void, OnZeroRttPacketAcked, (), (override));
1392 };
1393 
1394 class MockReceivedPacketManager : public QuicReceivedPacketManager {
1395  public:
1396   explicit MockReceivedPacketManager(QuicConnectionStats* stats);
1397   ~MockReceivedPacketManager() override;
1398 
1399   MOCK_METHOD(void, RecordPacketReceived,
1400               (const QuicPacketHeader& header, QuicTime receipt_time,
1401                const QuicEcnCodepoint ecn),
1402               (override));
1403   MOCK_METHOD(bool, IsMissing, (QuicPacketNumber packet_number), (override));
1404   MOCK_METHOD(bool, IsAwaitingPacket, (QuicPacketNumber packet_number),
1405               (const, override));
1406   MOCK_METHOD(bool, HasNewMissingPackets, (), (const, override));
1407   MOCK_METHOD(bool, ack_frame_updated, (), (const, override));
1408 };
1409 
1410 class MockPacketCreatorDelegate : public QuicPacketCreator::DelegateInterface {
1411  public:
1412   MockPacketCreatorDelegate();
1413   MockPacketCreatorDelegate(const MockPacketCreatorDelegate&) = delete;
1414   MockPacketCreatorDelegate& operator=(const MockPacketCreatorDelegate&) =
1415       delete;
1416   ~MockPacketCreatorDelegate() override;
1417 
1418   MOCK_METHOD(QuicPacketBuffer, GetPacketBuffer, (), (override));
1419   MOCK_METHOD(void, OnSerializedPacket, (SerializedPacket), (override));
1420   MOCK_METHOD(void, OnUnrecoverableError, (QuicErrorCode, const std::string&),
1421               (override));
1422   MOCK_METHOD(bool, ShouldGeneratePacket,
1423               (HasRetransmittableData retransmittable, IsHandshake handshake),
1424               (override));
1425   MOCK_METHOD(const QuicFrames, MaybeBundleAckOpportunistically, (),
1426               (override));
1427   MOCK_METHOD(SerializedPacketFate, GetSerializedPacketFate,
1428               (bool, EncryptionLevel), (override));
1429 };
1430 
1431 class MockSessionNotifier : public SessionNotifierInterface {
1432  public:
1433   MockSessionNotifier();
1434   ~MockSessionNotifier() override;
1435 
1436   MOCK_METHOD(bool, OnFrameAcked, (const QuicFrame&, QuicTime::Delta, QuicTime),
1437               (override));
1438   MOCK_METHOD(void, OnStreamFrameRetransmitted, (const QuicStreamFrame&),
1439               (override));
1440   MOCK_METHOD(void, OnFrameLost, (const QuicFrame&), (override));
1441   MOCK_METHOD(bool, RetransmitFrames,
1442               (const QuicFrames&, TransmissionType type), (override));
1443   MOCK_METHOD(bool, IsFrameOutstanding, (const QuicFrame&), (const, override));
1444   MOCK_METHOD(bool, HasUnackedCryptoData, (), (const, override));
1445   MOCK_METHOD(bool, HasUnackedStreamData, (), (const, override));
1446 };
1447 
1448 class MockQuicPathValidationContext : public QuicPathValidationContext {
1449  public:
MockQuicPathValidationContext(const QuicSocketAddress & self_address,const QuicSocketAddress & peer_address,const QuicSocketAddress & effective_peer_address,QuicPacketWriter * writer)1450   MockQuicPathValidationContext(const QuicSocketAddress& self_address,
1451                                 const QuicSocketAddress& peer_address,
1452                                 const QuicSocketAddress& effective_peer_address,
1453                                 QuicPacketWriter* writer)
1454       : QuicPathValidationContext(self_address, peer_address,
1455                                   effective_peer_address),
1456         writer_(writer) {}
WriterToUse()1457   QuicPacketWriter* WriterToUse() override { return writer_; }
1458 
1459  private:
1460   QuicPacketWriter* writer_;
1461 };
1462 
1463 class MockQuicPathValidationResultDelegate
1464     : public QuicPathValidator::ResultDelegate {
1465  public:
1466   MOCK_METHOD(void, OnPathValidationSuccess,
1467               (std::unique_ptr<QuicPathValidationContext>, QuicTime),
1468               (override));
1469 
1470   MOCK_METHOD(void, OnPathValidationFailure,
1471               (std::unique_ptr<QuicPathValidationContext>), (override));
1472 };
1473 
1474 class MockHttpDecoderVisitor : public HttpDecoder::Visitor {
1475  public:
1476   ~MockHttpDecoderVisitor() override = default;
1477 
1478   // Called if an error is detected.
1479   MOCK_METHOD(void, OnError, (HttpDecoder*), (override));
1480 
1481   MOCK_METHOD(bool, OnMaxPushIdFrame, (), (override));
1482   MOCK_METHOD(bool, OnGoAwayFrame, (const GoAwayFrame& frame), (override));
1483   MOCK_METHOD(bool, OnSettingsFrameStart, (QuicByteCount header_length),
1484               (override));
1485   MOCK_METHOD(bool, OnSettingsFrame, (const SettingsFrame& frame), (override));
1486 
1487   MOCK_METHOD(bool, OnDataFrameStart,
1488               (QuicByteCount header_length, QuicByteCount payload_length),
1489               (override));
1490   MOCK_METHOD(bool, OnDataFramePayload, (absl::string_view payload),
1491               (override));
1492   MOCK_METHOD(bool, OnDataFrameEnd, (), (override));
1493 
1494   MOCK_METHOD(bool, OnHeadersFrameStart,
1495               (QuicByteCount header_length, QuicByteCount payload_length),
1496               (override));
1497   MOCK_METHOD(bool, OnHeadersFramePayload, (absl::string_view payload),
1498               (override));
1499   MOCK_METHOD(bool, OnHeadersFrameEnd, (), (override));
1500 
1501   MOCK_METHOD(bool, OnPriorityUpdateFrameStart, (QuicByteCount header_length),
1502               (override));
1503   MOCK_METHOD(bool, OnPriorityUpdateFrame, (const PriorityUpdateFrame& frame),
1504               (override));
1505 
1506   MOCK_METHOD(bool, OnAcceptChFrameStart, (QuicByteCount header_length),
1507               (override));
1508   MOCK_METHOD(bool, OnAcceptChFrame, (const AcceptChFrame& frame), (override));
1509   MOCK_METHOD(void, OnWebTransportStreamFrameType,
1510               (QuicByteCount header_length, WebTransportSessionId session_id),
1511               (override));
1512 
1513   MOCK_METHOD(bool, OnUnknownFrameStart,
1514               (uint64_t frame_type, QuicByteCount header_length,
1515                QuicByteCount payload_length),
1516               (override));
1517   MOCK_METHOD(bool, OnUnknownFramePayload, (absl::string_view payload),
1518               (override));
1519   MOCK_METHOD(bool, OnUnknownFrameEnd, (), (override));
1520 };
1521 
1522 class QuicCryptoClientStreamPeer {
1523  public:
1524   QuicCryptoClientStreamPeer() = delete;
1525 
1526   static QuicCryptoClientStream::HandshakerInterface* GetHandshaker(
1527       QuicCryptoClientStream* stream);
1528 };
1529 
1530 // Creates a client session for testing.
1531 //
1532 // server_id: The server id associated with this stream.
1533 // connection_start_time: The time to set for the connection clock.
1534 //   Needed for strike-register nonce verification.  The client
1535 //   connection_start_time should be synchronized witht the server
1536 //   start time, otherwise nonce verification will fail.
1537 // supported_versions: Set of QUIC versions this client supports.
1538 // helper: Pointer to the MockQuicConnectionHelper to use for the session.
1539 // crypto_client_config: Pointer to the crypto client config.
1540 // client_connection: Pointer reference for newly created
1541 //   connection.  This object will be owned by the
1542 //   client_session.
1543 // client_session: Pointer reference for the newly created client
1544 //   session.  The new object will be owned by the caller.
1545 void CreateClientSessionForTest(
1546     QuicServerId server_id, QuicTime::Delta connection_start_time,
1547     const ParsedQuicVersionVector& supported_versions,
1548     QuicConnectionHelperInterface* helper, QuicAlarmFactory* alarm_factory,
1549     QuicCryptoClientConfig* crypto_client_config,
1550     PacketSavingConnection** client_connection,
1551     TestQuicSpdyClientSession** client_session);
1552 
1553 // Creates a server session for testing.
1554 //
1555 // server_id: The server id associated with this stream.
1556 // connection_start_time: The time to set for the connection clock.
1557 //   Needed for strike-register nonce verification.  The server
1558 //   connection_start_time should be synchronized witht the client
1559 //   start time, otherwise nonce verification will fail.
1560 // supported_versions: Set of QUIC versions this server supports.
1561 // helper: Pointer to the MockQuicConnectionHelper to use for the session.
1562 // server_crypto_config: Pointer to the crypto server config.
1563 // server_connection: Pointer reference for newly created
1564 //   connection.  This object will be owned by the
1565 //   server_session.
1566 // server_session: Pointer reference for the newly created server
1567 //   session.  The new object will be owned by the caller.
1568 void CreateServerSessionForTest(
1569     QuicServerId server_id, QuicTime::Delta connection_start_time,
1570     ParsedQuicVersionVector supported_versions,
1571     QuicConnectionHelperInterface* helper, QuicAlarmFactory* alarm_factory,
1572     QuicCryptoServerConfig* server_crypto_config,
1573     QuicCompressedCertsCache* compressed_certs_cache,
1574     PacketSavingConnection** server_connection,
1575     TestQuicSpdyServerSession** server_session);
1576 
1577 // Verifies that the relative error of |actual| with respect to |expected| is
1578 // no more than |margin|.
1579 // Please use EXPECT_APPROX_EQ, a wrapper around this function, for better error
1580 // report.
1581 template <typename T>
ExpectApproxEq(T expected,T actual,float relative_margin)1582 void ExpectApproxEq(T expected, T actual, float relative_margin) {
1583   // If |relative_margin| > 1 and T is an unsigned type, the comparison will
1584   // underflow.
1585   ASSERT_LE(relative_margin, 1);
1586   ASSERT_GE(relative_margin, 0);
1587 
1588   T absolute_margin = expected * relative_margin;
1589 
1590   EXPECT_GE(expected + absolute_margin, actual) << "actual value too big";
1591   EXPECT_LE(expected - absolute_margin, actual) << "actual value too small";
1592 }
1593 
1594 #define EXPECT_APPROX_EQ(expected, actual, relative_margin)                    \
1595   do {                                                                         \
1596     SCOPED_TRACE(testing::Message() << "relative_margin:" << relative_margin); \
1597     quic::test::ExpectApproxEq(expected, actual, relative_margin);             \
1598   } while (0)
1599 
1600 template <typename T>
AsHeaderList(const T & container)1601 QuicHeaderList AsHeaderList(const T& container) {
1602   QuicHeaderList l;
1603   l.OnHeaderBlockStart();
1604   size_t total_size = 0;
1605   for (auto p : container) {
1606     total_size += p.first.size() + p.second.size();
1607     l.OnHeader(p.first, p.second);
1608   }
1609   l.OnHeaderBlockEnd(total_size, total_size);
1610   return l;
1611 }
1612 
1613 // Helper functions for stream ids, to allow test logic to abstract over the
1614 // HTTP stream numbering scheme (i.e. whether one or two QUIC streams are used
1615 // per HTTP transaction).
1616 QuicStreamId GetNthClientInitiatedBidirectionalStreamId(
1617     QuicTransportVersion version, int n);
1618 QuicStreamId GetNthServerInitiatedBidirectionalStreamId(
1619     QuicTransportVersion version, int n);
1620 QuicStreamId GetNthServerInitiatedUnidirectionalStreamId(
1621     QuicTransportVersion version, int n);
1622 QuicStreamId GetNthClientInitiatedUnidirectionalStreamId(
1623     QuicTransportVersion version, int n);
1624 
1625 StreamType DetermineStreamType(QuicStreamId id, ParsedQuicVersion version,
1626                                Perspective perspective, bool is_incoming,
1627                                StreamType default_type);
1628 
1629 // Creates a MemSlice using a singleton trivial buffer allocator.  Performs a
1630 // copy.
1631 quiche::QuicheMemSlice MemSliceFromString(absl::string_view data);
1632 
1633 // Used to compare ReceivedPacketInfo.
1634 MATCHER_P(ReceivedPacketInfoEquals, info, "") {
1635   return info.ToString() == arg.ToString();
1636 }
1637 
1638 MATCHER_P(ReceivedPacketInfoConnectionIdEquals, destination_connection_id, "") {
1639   return arg.destination_connection_id == destination_connection_id;
1640 }
1641 
1642 MATCHER_P2(InRange, min, max, "") { return arg >= min && arg <= max; }
1643 
1644 // A GMock matcher that prints expected and actual QuicErrorCode strings
1645 // upon failure.  Example usage:
1646 // EXPECT_THAT(stream_->connection_error(), IsError(QUIC_INTERNAL_ERROR));
1647 MATCHER_P(IsError, expected,
1648           absl::StrCat(negation ? "isn't equal to " : "is equal to ",
1649                        QuicErrorCodeToString(expected))) {
1650   *result_listener << QuicErrorCodeToString(static_cast<QuicErrorCode>(arg));
1651   return arg == expected;
1652 }
1653 
1654 // Shorthand for IsError(QUIC_NO_ERROR).
1655 // Example usage: EXPECT_THAT(stream_->connection_error(), IsQuicNoError());
1656 MATCHER(IsQuicNoError,
1657         absl::StrCat(negation ? "isn't equal to " : "is equal to ",
1658                      QuicErrorCodeToString(QUIC_NO_ERROR))) {
1659   *result_listener << QuicErrorCodeToString(arg);
1660   return arg == QUIC_NO_ERROR;
1661 }
1662 
1663 // A GMock matcher that prints expected and actual QuicRstStreamErrorCode
1664 // strings upon failure.  Example usage:
1665 // EXPECT_THAT(stream_->stream_error(), IsStreamError(QUIC_INTERNAL_ERROR));
1666 MATCHER_P(IsStreamError, expected,
1667           absl::StrCat(negation ? "isn't equal to " : "is equal to ",
1668                        QuicRstStreamErrorCodeToString(expected))) {
1669   *result_listener << QuicRstStreamErrorCodeToString(arg);
1670   return arg == expected;
1671 }
1672 
1673 // Shorthand for IsStreamError(QUIC_STREAM_NO_ERROR).  Example usage:
1674 // EXPECT_THAT(stream_->stream_error(), IsQuicStreamNoError());
1675 MATCHER(IsQuicStreamNoError,
1676         absl::StrCat(negation ? "isn't equal to " : "is equal to ",
1677                      QuicRstStreamErrorCodeToString(QUIC_STREAM_NO_ERROR))) {
1678   *result_listener << QuicRstStreamErrorCodeToString(arg);
1679   return arg == QUIC_STREAM_NO_ERROR;
1680 }
1681 
1682 // TaggingEncrypter appends kTagSize bytes of |tag| to the end of each message.
1683 class TaggingEncrypter : public QuicEncrypter {
1684  public:
TaggingEncrypter(uint8_t tag)1685   explicit TaggingEncrypter(uint8_t tag) : tag_(tag) {}
1686   TaggingEncrypter(const TaggingEncrypter&) = delete;
1687   TaggingEncrypter& operator=(const TaggingEncrypter&) = delete;
1688 
~TaggingEncrypter()1689   ~TaggingEncrypter() override {}
1690 
1691   // QuicEncrypter interface.
SetKey(absl::string_view)1692   bool SetKey(absl::string_view /*key*/) override { return true; }
1693 
SetNoncePrefix(absl::string_view)1694   bool SetNoncePrefix(absl::string_view /*nonce_prefix*/) override {
1695     return true;
1696   }
1697 
SetIV(absl::string_view)1698   bool SetIV(absl::string_view /*iv*/) override { return true; }
1699 
SetHeaderProtectionKey(absl::string_view)1700   bool SetHeaderProtectionKey(absl::string_view /*key*/) override {
1701     return true;
1702   }
1703 
1704   bool EncryptPacket(uint64_t packet_number, absl::string_view associated_data,
1705                      absl::string_view plaintext, char* output,
1706                      size_t* output_length, size_t max_output_length) override;
1707 
GenerateHeaderProtectionMask(absl::string_view)1708   std::string GenerateHeaderProtectionMask(
1709       absl::string_view /*sample*/) override {
1710     return std::string(5, 0);
1711   }
1712 
GetKeySize()1713   size_t GetKeySize() const override { return 0; }
GetNoncePrefixSize()1714   size_t GetNoncePrefixSize() const override { return 0; }
GetIVSize()1715   size_t GetIVSize() const override { return 0; }
1716 
GetMaxPlaintextSize(size_t ciphertext_size)1717   size_t GetMaxPlaintextSize(size_t ciphertext_size) const override {
1718     return ciphertext_size - kTagSize;
1719   }
1720 
GetCiphertextSize(size_t plaintext_size)1721   size_t GetCiphertextSize(size_t plaintext_size) const override {
1722     return plaintext_size + kTagSize;
1723   }
1724 
GetConfidentialityLimit()1725   QuicPacketCount GetConfidentialityLimit() const override {
1726     return std::numeric_limits<QuicPacketCount>::max();
1727   }
1728 
GetKey()1729   absl::string_view GetKey() const override { return absl::string_view(); }
1730 
GetNoncePrefix()1731   absl::string_view GetNoncePrefix() const override {
1732     return absl::string_view();
1733   }
1734 
1735  private:
1736   enum {
1737     kTagSize = 16,
1738   };
1739 
1740   const uint8_t tag_;
1741 };
1742 
1743 // TaggingDecrypter ensures that the final kTagSize bytes of the message all
1744 // have the same value and then removes them.
1745 class TaggingDecrypter : public QuicDecrypter {
1746  public:
~TaggingDecrypter()1747   ~TaggingDecrypter() override {}
1748 
1749   // QuicDecrypter interface
SetKey(absl::string_view)1750   bool SetKey(absl::string_view /*key*/) override { return true; }
1751 
SetNoncePrefix(absl::string_view)1752   bool SetNoncePrefix(absl::string_view /*nonce_prefix*/) override {
1753     return true;
1754   }
1755 
SetIV(absl::string_view)1756   bool SetIV(absl::string_view /*iv*/) override { return true; }
1757 
SetHeaderProtectionKey(absl::string_view)1758   bool SetHeaderProtectionKey(absl::string_view /*key*/) override {
1759     return true;
1760   }
1761 
SetPreliminaryKey(absl::string_view)1762   bool SetPreliminaryKey(absl::string_view /*key*/) override {
1763     QUIC_BUG(quic_bug_10230_1) << "should not be called";
1764     return false;
1765   }
1766 
SetDiversificationNonce(const DiversificationNonce &)1767   bool SetDiversificationNonce(const DiversificationNonce& /*key*/) override {
1768     return true;
1769   }
1770 
1771   bool DecryptPacket(uint64_t packet_number, absl::string_view associated_data,
1772                      absl::string_view ciphertext, char* output,
1773                      size_t* output_length, size_t max_output_length) override;
1774 
GenerateHeaderProtectionMask(QuicDataReader *)1775   std::string GenerateHeaderProtectionMask(
1776       QuicDataReader* /*sample_reader*/) override {
1777     return std::string(5, 0);
1778   }
1779 
GetKeySize()1780   size_t GetKeySize() const override { return 0; }
GetNoncePrefixSize()1781   size_t GetNoncePrefixSize() const override { return 0; }
GetIVSize()1782   size_t GetIVSize() const override { return 0; }
GetKey()1783   absl::string_view GetKey() const override { return absl::string_view(); }
GetNoncePrefix()1784   absl::string_view GetNoncePrefix() const override {
1785     return absl::string_view();
1786   }
1787   // Use a distinct value starting with 0xFFFFFF, which is never used by TLS.
cipher_id()1788   uint32_t cipher_id() const override { return 0xFFFFFFF0; }
GetIntegrityLimit()1789   QuicPacketCount GetIntegrityLimit() const override {
1790     return std::numeric_limits<QuicPacketCount>::max();
1791   }
1792 
1793  protected:
GetTag(absl::string_view ciphertext)1794   virtual uint8_t GetTag(absl::string_view ciphertext) {
1795     return ciphertext.data()[ciphertext.size() - 1];
1796   }
1797 
1798  private:
1799   enum {
1800     kTagSize = 16,
1801   };
1802 
1803   bool CheckTag(absl::string_view ciphertext, uint8_t tag);
1804 };
1805 
1806 // StringTaggingDecrypter ensures that the final kTagSize bytes of the message
1807 // match the expected value.
1808 class StrictTaggingDecrypter : public TaggingDecrypter {
1809  public:
StrictTaggingDecrypter(uint8_t tag)1810   explicit StrictTaggingDecrypter(uint8_t tag) : tag_(tag) {}
~StrictTaggingDecrypter()1811   ~StrictTaggingDecrypter() override {}
1812 
1813   // TaggingQuicDecrypter
GetTag(absl::string_view)1814   uint8_t GetTag(absl::string_view /*ciphertext*/) override { return tag_; }
1815 
1816   // Use a distinct value starting with 0xFFFFFF, which is never used by TLS.
cipher_id()1817   uint32_t cipher_id() const override { return 0xFFFFFFF1; }
1818 
1819  private:
1820   const uint8_t tag_;
1821 };
1822 
1823 class TestPacketWriter : public QuicPacketWriter {
1824   struct PacketBuffer {
1825     ABSL_CACHELINE_ALIGNED char buffer[1500];
1826     bool in_use = false;
1827   };
1828 
1829  public:
1830   TestPacketWriter(ParsedQuicVersion version, MockClock* clock,
1831                    Perspective perspective);
1832 
1833   TestPacketWriter(const TestPacketWriter&) = delete;
1834   TestPacketWriter& operator=(const TestPacketWriter&) = delete;
1835 
1836   ~TestPacketWriter() override;
1837 
1838   // QuicPacketWriter interface
1839   WriteResult WritePacket(const char* buffer, size_t buf_len,
1840                           const QuicIpAddress& self_address,
1841                           const QuicSocketAddress& peer_address,
1842                           PerPacketOptions* options) override;
1843 
ShouldWriteFail()1844   bool ShouldWriteFail() { return write_should_fail_; }
1845 
IsWriteBlocked()1846   bool IsWriteBlocked() const override { return write_blocked_; }
1847 
MessageTooBigErrorCode()1848   absl::optional<int> MessageTooBigErrorCode() const override { return 0x1234; }
1849 
SetWriteBlocked()1850   void SetWriteBlocked() { write_blocked_ = true; }
1851 
SetWritable()1852   void SetWritable() override { write_blocked_ = false; }
1853 
SetShouldWriteFail()1854   void SetShouldWriteFail() { write_should_fail_ = true; }
1855 
SetWriteError(int error_code)1856   void SetWriteError(int error_code) { write_error_code_ = error_code; }
1857 
GetMaxPacketSize(const QuicSocketAddress &)1858   QuicByteCount GetMaxPacketSize(
1859       const QuicSocketAddress& /*peer_address*/) const override {
1860     return max_packet_size_;
1861   }
1862 
SupportsReleaseTime()1863   bool SupportsReleaseTime() const override { return supports_release_time_; }
1864 
IsBatchMode()1865   bool IsBatchMode() const override { return is_batch_mode_; }
1866 
1867   QuicPacketBuffer GetNextWriteLocation(
1868       const QuicIpAddress& /*self_address*/,
1869       const QuicSocketAddress& /*peer_address*/) override;
1870 
1871   WriteResult Flush() override;
1872 
BlockOnNextFlush()1873   void BlockOnNextFlush() { block_on_next_flush_ = true; }
1874 
BlockOnNextWrite()1875   void BlockOnNextWrite() { block_on_next_write_ = true; }
1876 
SimulateNextPacketTooLarge()1877   void SimulateNextPacketTooLarge() { next_packet_too_large_ = true; }
1878 
ExpectNextPacketUnprocessable()1879   void ExpectNextPacketUnprocessable() { next_packet_processable_ = false; }
1880 
AlwaysGetPacketTooLarge()1881   void AlwaysGetPacketTooLarge() { always_get_packet_too_large_ = true; }
1882 
1883   // Sets the amount of time that the writer should before the actual write.
SetWritePauseTimeDelta(QuicTime::Delta delta)1884   void SetWritePauseTimeDelta(QuicTime::Delta delta) {
1885     write_pause_time_delta_ = delta;
1886   }
1887 
SetBatchMode(bool new_value)1888   void SetBatchMode(bool new_value) { is_batch_mode_ = new_value; }
1889 
header()1890   const QuicPacketHeader& header() { return framer_.header(); }
1891 
frame_count()1892   size_t frame_count() const { return framer_.num_frames(); }
1893 
ack_frames()1894   const std::vector<QuicAckFrame>& ack_frames() const {
1895     return framer_.ack_frames();
1896   }
1897 
stop_waiting_frames()1898   const std::vector<QuicStopWaitingFrame>& stop_waiting_frames() const {
1899     return framer_.stop_waiting_frames();
1900   }
1901 
connection_close_frames()1902   const std::vector<QuicConnectionCloseFrame>& connection_close_frames() const {
1903     return framer_.connection_close_frames();
1904   }
1905 
rst_stream_frames()1906   const std::vector<QuicRstStreamFrame>& rst_stream_frames() const {
1907     return framer_.rst_stream_frames();
1908   }
1909 
stream_frames()1910   const std::vector<std::unique_ptr<QuicStreamFrame>>& stream_frames() const {
1911     return framer_.stream_frames();
1912   }
1913 
crypto_frames()1914   const std::vector<std::unique_ptr<QuicCryptoFrame>>& crypto_frames() const {
1915     return framer_.crypto_frames();
1916   }
1917 
ping_frames()1918   const std::vector<QuicPingFrame>& ping_frames() const {
1919     return framer_.ping_frames();
1920   }
1921 
message_frames()1922   const std::vector<QuicMessageFrame>& message_frames() const {
1923     return framer_.message_frames();
1924   }
1925 
window_update_frames()1926   const std::vector<QuicWindowUpdateFrame>& window_update_frames() const {
1927     return framer_.window_update_frames();
1928   }
1929 
padding_frames()1930   const std::vector<QuicPaddingFrame>& padding_frames() const {
1931     return framer_.padding_frames();
1932   }
1933 
path_challenge_frames()1934   const std::vector<QuicPathChallengeFrame>& path_challenge_frames() const {
1935     return framer_.path_challenge_frames();
1936   }
1937 
path_response_frames()1938   const std::vector<QuicPathResponseFrame>& path_response_frames() const {
1939     return framer_.path_response_frames();
1940   }
1941 
coalesced_packet()1942   const QuicEncryptedPacket* coalesced_packet() const {
1943     return framer_.coalesced_packet();
1944   }
1945 
last_packet_size()1946   size_t last_packet_size() const { return last_packet_size_; }
1947 
total_bytes_written()1948   size_t total_bytes_written() const { return total_bytes_written_; }
1949 
last_packet_header()1950   const QuicPacketHeader& last_packet_header() const {
1951     return last_packet_header_;
1952   }
1953 
version_negotiation_packet()1954   const QuicVersionNegotiationPacket* version_negotiation_packet() {
1955     return framer_.version_negotiation_packet();
1956   }
1957 
set_is_write_blocked_data_buffered(bool buffered)1958   void set_is_write_blocked_data_buffered(bool buffered) {
1959     is_write_blocked_data_buffered_ = buffered;
1960   }
1961 
set_perspective(Perspective perspective)1962   void set_perspective(Perspective perspective) {
1963     // We invert perspective here, because the framer needs to parse packets
1964     // we send.
1965     QuicFramerPeer::SetPerspective(framer_.framer(),
1966                                    QuicUtils::InvertPerspective(perspective));
1967     framer_.framer()->SetInitialObfuscators(TestConnectionId());
1968   }
1969 
1970   // final_bytes_of_last_packet_ returns the last four bytes of the previous
1971   // packet as a little-endian, uint32_t. This is intended to be used with a
1972   // TaggingEncrypter so that tests can determine which encrypter was used for
1973   // a given packet.
final_bytes_of_last_packet()1974   uint32_t final_bytes_of_last_packet() { return final_bytes_of_last_packet_; }
1975 
1976   // Returns the final bytes of the second to last packet.
final_bytes_of_previous_packet()1977   uint32_t final_bytes_of_previous_packet() {
1978     return final_bytes_of_previous_packet_;
1979   }
1980 
packets_write_attempts()1981   uint32_t packets_write_attempts() const { return packets_write_attempts_; }
1982 
flush_attempts()1983   uint32_t flush_attempts() const { return flush_attempts_; }
1984 
connection_close_packets()1985   uint32_t connection_close_packets() const {
1986     return connection_close_packets_;
1987   }
1988 
Reset()1989   void Reset() { framer_.Reset(); }
1990 
SetSupportedVersions(const ParsedQuicVersionVector & versions)1991   void SetSupportedVersions(const ParsedQuicVersionVector& versions) {
1992     framer_.SetSupportedVersions(versions);
1993   }
1994 
set_max_packet_size(QuicByteCount max_packet_size)1995   void set_max_packet_size(QuicByteCount max_packet_size) {
1996     max_packet_size_ = max_packet_size;
1997   }
1998 
set_supports_release_time(bool supports_release_time)1999   void set_supports_release_time(bool supports_release_time) {
2000     supports_release_time_ = supports_release_time;
2001   }
2002 
framer()2003   SimpleQuicFramer* framer() { return &framer_; }
2004 
last_write_source_address()2005   const QuicIpAddress& last_write_source_address() const {
2006     return last_write_source_address_;
2007   }
2008 
last_write_peer_address()2009   const QuicSocketAddress& last_write_peer_address() const {
2010     return last_write_peer_address_;
2011   }
2012 
last_ecn_sent()2013   QuicEcnCodepoint last_ecn_sent() const { return last_ecn_sent_; }
2014 
2015  private:
2016   char* AllocPacketBuffer();
2017 
2018   void FreePacketBuffer(const char* buffer);
2019 
2020   ParsedQuicVersion version_;
2021   SimpleQuicFramer framer_;
2022   size_t last_packet_size_ = 0;
2023   size_t total_bytes_written_ = 0;
2024   QuicPacketHeader last_packet_header_;
2025   bool write_blocked_ = false;
2026   bool write_should_fail_ = false;
2027   bool block_on_next_flush_ = false;
2028   bool block_on_next_write_ = false;
2029   bool next_packet_too_large_ = false;
2030   bool next_packet_processable_ = true;
2031   bool always_get_packet_too_large_ = false;
2032   bool is_write_blocked_data_buffered_ = false;
2033   bool is_batch_mode_ = false;
2034   // Number of times Flush() was called.
2035   uint32_t flush_attempts_ = 0;
2036   // (Batch mode only) Number of bytes buffered in writer. It is used as the
2037   // return value of a successful Flush().
2038   uint32_t bytes_buffered_ = 0;
2039   uint32_t final_bytes_of_last_packet_ = 0;
2040   uint32_t final_bytes_of_previous_packet_ = 0;
2041   uint32_t packets_write_attempts_ = 0;
2042   uint32_t connection_close_packets_ = 0;
2043   MockClock* clock_ = nullptr;
2044   // If non-zero, the clock will pause during WritePacket for this amount of
2045   // time.
2046   QuicTime::Delta write_pause_time_delta_ = QuicTime::Delta::Zero();
2047   QuicByteCount max_packet_size_ = kMaxOutgoingPacketSize;
2048   bool supports_release_time_ = false;
2049   // Used to verify writer-allocated packet buffers are properly released.
2050   std::vector<PacketBuffer*> packet_buffer_pool_;
2051   // Buffer address => Address of the owning PacketBuffer.
2052   absl::flat_hash_map<char*, PacketBuffer*, absl::Hash<char*>>
2053       packet_buffer_pool_index_;
2054   // Indices in packet_buffer_pool_ that are not allocated.
2055   std::list<PacketBuffer*> packet_buffer_free_list_;
2056   // The soruce/peer address passed into WritePacket().
2057   QuicIpAddress last_write_source_address_;
2058   QuicSocketAddress last_write_peer_address_;
2059   int write_error_code_{0};
2060   QuicEcnCodepoint last_ecn_sent_ = ECN_NOT_ECT;
2061 };
2062 
2063 // Parses a packet generated by
2064 // QuicFramer::WriteClientVersionNegotiationProbePacket.
2065 // |packet_bytes| must point to |packet_length| bytes in memory which represent
2066 // the packet. This method will fill in |destination_connection_id_bytes|
2067 // which must point to at least |*destination_connection_id_length_out| bytes in
2068 // memory. |*destination_connection_id_length_out| will contain the length of
2069 // the received destination connection ID, which on success will match the
2070 // contents of the destination connection ID passed in to
2071 // WriteClientVersionNegotiationProbePacket.
2072 bool ParseClientVersionNegotiationProbePacket(
2073     const char* packet_bytes, size_t packet_length,
2074     char* destination_connection_id_bytes,
2075     uint8_t* destination_connection_id_length_out);
2076 
2077 // Writes an array of bytes that correspond to a QUIC version negotiation packet
2078 // that a QUIC server would send in response to a probe created by
2079 // QuicFramer::WriteClientVersionNegotiationProbePacket.
2080 // The bytes will be written to |packet_bytes|, which must point to
2081 // |*packet_length_out| bytes of memory. |*packet_length_out| will contain the
2082 // length of the created packet. |source_connection_id_bytes| will be sent as
2083 // the source connection ID, and must point to |source_connection_id_length|
2084 // bytes of memory.
2085 bool WriteServerVersionNegotiationProbeResponse(
2086     char* packet_bytes, size_t* packet_length_out,
2087     const char* source_connection_id_bytes,
2088     uint8_t source_connection_id_length);
2089 
2090 // Implementation of Http3DatagramVisitor which saves all received datagrams.
2091 class SavingHttp3DatagramVisitor : public QuicSpdyStream::Http3DatagramVisitor {
2092  public:
2093   struct SavedHttp3Datagram {
2094     QuicStreamId stream_id;
2095     std::string payload;
2096     bool operator==(const SavedHttp3Datagram& o) const {
2097       return stream_id == o.stream_id && payload == o.payload;
2098     }
2099   };
2100   struct SavedUnknownCapsule {
2101     QuicStreamId stream_id;
2102     uint64_t type;
2103     std::string payload;
2104     bool operator==(const SavedUnknownCapsule& o) const {
2105       return stream_id == o.stream_id && type == o.type && payload == o.payload;
2106     }
2107   };
received_h3_datagrams()2108   const std::vector<SavedHttp3Datagram>& received_h3_datagrams() const {
2109     return received_h3_datagrams_;
2110   }
received_unknown_capsules()2111   const std::vector<SavedUnknownCapsule>& received_unknown_capsules() const {
2112     return received_unknown_capsules_;
2113   }
2114 
2115   // Override from QuicSpdyStream::Http3DatagramVisitor.
OnHttp3Datagram(QuicStreamId stream_id,absl::string_view payload)2116   void OnHttp3Datagram(QuicStreamId stream_id,
2117                        absl::string_view payload) override {
2118     received_h3_datagrams_.push_back(
2119         SavedHttp3Datagram{stream_id, std::string(payload)});
2120   }
OnUnknownCapsule(QuicStreamId stream_id,const quiche::UnknownCapsule & capsule)2121   void OnUnknownCapsule(QuicStreamId stream_id,
2122                         const quiche::UnknownCapsule& capsule) override {
2123     received_unknown_capsules_.push_back(SavedUnknownCapsule{
2124         stream_id, capsule.type, std::string(capsule.payload)});
2125   }
2126 
2127  private:
2128   std::vector<SavedHttp3Datagram> received_h3_datagrams_;
2129   std::vector<SavedUnknownCapsule> received_unknown_capsules_;
2130 };
2131 
2132 // Implementation of ConnectIpVisitor which saves all received capsules.
2133 class SavingConnectIpVisitor : public QuicSpdyStream::ConnectIpVisitor {
2134  public:
2135   const std::vector<quiche::AddressAssignCapsule>&
received_address_assign_capsules()2136   received_address_assign_capsules() const {
2137     return received_address_assign_capsules_;
2138   }
2139   const std::vector<quiche::AddressRequestCapsule>&
received_address_request_capsules()2140   received_address_request_capsules() const {
2141     return received_address_request_capsules_;
2142   }
2143   const std::vector<quiche::RouteAdvertisementCapsule>&
received_route_advertisement_capsules()2144   received_route_advertisement_capsules() const {
2145     return received_route_advertisement_capsules_;
2146   }
headers_written()2147   bool headers_written() const { return headers_written_; }
2148 
2149   // From QuicSpdyStream::ConnectIpVisitor.
OnAddressAssignCapsule(const quiche::AddressAssignCapsule & capsule)2150   bool OnAddressAssignCapsule(
2151       const quiche::AddressAssignCapsule& capsule) override {
2152     received_address_assign_capsules_.push_back(capsule);
2153     return true;
2154   }
OnAddressRequestCapsule(const quiche::AddressRequestCapsule & capsule)2155   bool OnAddressRequestCapsule(
2156       const quiche::AddressRequestCapsule& capsule) override {
2157     received_address_request_capsules_.push_back(capsule);
2158     return true;
2159   }
OnRouteAdvertisementCapsule(const quiche::RouteAdvertisementCapsule & capsule)2160   bool OnRouteAdvertisementCapsule(
2161       const quiche::RouteAdvertisementCapsule& capsule) override {
2162     received_route_advertisement_capsules_.push_back(capsule);
2163     return true;
2164   }
OnHeadersWritten()2165   void OnHeadersWritten() override { headers_written_ = true; }
2166 
2167  private:
2168   std::vector<quiche::AddressAssignCapsule> received_address_assign_capsules_;
2169   std::vector<quiche::AddressRequestCapsule> received_address_request_capsules_;
2170   std::vector<quiche::RouteAdvertisementCapsule>
2171       received_route_advertisement_capsules_;
2172   bool headers_written_ = false;
2173 };
2174 
EscapeTestParamName(absl::string_view name)2175 inline std::string EscapeTestParamName(absl::string_view name) {
2176   std::string result(name);
2177   // Escape all characters that are not allowed by gtest ([a-zA-Z0-9_]).
2178   for (char& c : result) {
2179     bool valid = absl::ascii_isalnum(c) || c == '_';
2180     if (!valid) {
2181       c = '_';
2182     }
2183   }
2184   return result;
2185 }
2186 
2187 struct TestPerPacketOptions : PerPacketOptions {
2188  public:
CloneTestPerPacketOptions2189   std::unique_ptr<quic::PerPacketOptions> Clone() const override {
2190     return std::make_unique<TestPerPacketOptions>(*this);
2191   }
2192 };
2193 
2194 }  // namespace test
2195 }  // namespace quic
2196 
2197 #endif  // QUICHE_QUIC_TEST_TOOLS_QUIC_TEST_UTILS_H_
2198