Merge Chromium + Blink git repositories
[chromium-blink-merge.git] / net / spdy / spdy_test_util_common.cc
blob2b9b2b79299fe8a849da3da5210e8bf1549224a1
1 // Copyright (c) 2013 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "net/spdy/spdy_test_util_common.h"
7 #include <cstddef>
9 #include "base/compiler_specific.h"
10 #include "base/memory/scoped_ptr.h"
11 #include "base/strings/string_number_conversions.h"
12 #include "base/strings/string_split.h"
13 #include "net/cert/mock_cert_verifier.h"
14 #include "net/http/http_cache.h"
15 #include "net/http/http_network_session.h"
16 #include "net/http/http_network_transaction.h"
17 #include "net/http/http_server_properties_impl.h"
18 #include "net/socket/socket_test_util.h"
19 #include "net/socket/ssl_client_socket.h"
20 #include "net/socket/transport_client_socket_pool.h"
21 #include "net/spdy/buffered_spdy_framer.h"
22 #include "net/spdy/spdy_framer.h"
23 #include "net/spdy/spdy_http_utils.h"
24 #include "net/spdy/spdy_session.h"
25 #include "net/spdy/spdy_session_pool.h"
26 #include "net/spdy/spdy_stream.h"
27 #include "net/url_request/url_request_job_factory_impl.h"
29 namespace net {
31 namespace {
33 bool next_proto_is_spdy(NextProto next_proto) {
34 return next_proto >= kProtoSPDYMinimumVersion &&
35 next_proto <= kProtoSPDYMaximumVersion;
38 // Parses a URL into the scheme, host, and path components required for a
39 // SPDY request.
40 void ParseUrl(base::StringPiece url, std::string* scheme, std::string* host,
41 std::string* path) {
42 GURL gurl(url.as_string());
43 path->assign(gurl.PathForRequest());
44 scheme->assign(gurl.scheme());
45 host->assign(gurl.host());
46 if (gurl.has_port()) {
47 host->append(":");
48 host->append(gurl.port());
52 } // namespace
54 NextProtoVector SpdyNextProtos() {
55 NextProtoVector next_protos;
56 next_protos.push_back(kProtoHTTP11);
57 next_protos.push_back(kProtoSPDY31);
58 next_protos.push_back(kProtoHTTP2);
59 next_protos.push_back(kProtoQUIC1SPDY3);
60 return next_protos;
63 // Chop a frame into an array of MockWrites.
64 // |data| is the frame to chop.
65 // |length| is the length of the frame to chop.
66 // |num_chunks| is the number of chunks to create.
67 MockWrite* ChopWriteFrame(const char* data, int length, int num_chunks) {
68 MockWrite* chunks = new MockWrite[num_chunks];
69 int chunk_size = length / num_chunks;
70 for (int index = 0; index < num_chunks; index++) {
71 const char* ptr = data + (index * chunk_size);
72 if (index == num_chunks - 1)
73 chunk_size += length % chunk_size; // The last chunk takes the remainder.
74 chunks[index] = MockWrite(ASYNC, ptr, chunk_size);
76 return chunks;
79 // Chop a SpdyFrame into an array of MockWrites.
80 // |frame| is the frame to chop.
81 // |num_chunks| is the number of chunks to create.
82 MockWrite* ChopWriteFrame(const SpdyFrame& frame, int num_chunks) {
83 return ChopWriteFrame(frame.data(), frame.size(), num_chunks);
86 // Chop a frame into an array of MockReads.
87 // |data| is the frame to chop.
88 // |length| is the length of the frame to chop.
89 // |num_chunks| is the number of chunks to create.
90 MockRead* ChopReadFrame(const char* data, int length, int num_chunks) {
91 MockRead* chunks = new MockRead[num_chunks];
92 int chunk_size = length / num_chunks;
93 for (int index = 0; index < num_chunks; index++) {
94 const char* ptr = data + (index * chunk_size);
95 if (index == num_chunks - 1)
96 chunk_size += length % chunk_size; // The last chunk takes the remainder.
97 chunks[index] = MockRead(ASYNC, ptr, chunk_size);
99 return chunks;
102 // Chop a SpdyFrame into an array of MockReads.
103 // |frame| is the frame to chop.
104 // |num_chunks| is the number of chunks to create.
105 MockRead* ChopReadFrame(const SpdyFrame& frame, int num_chunks) {
106 return ChopReadFrame(frame.data(), frame.size(), num_chunks);
109 // Adds headers and values to a map.
110 // |extra_headers| is an array of { name, value } pairs, arranged as strings
111 // where the even entries are the header names, and the odd entries are the
112 // header values.
113 // |headers| gets filled in from |extra_headers|.
114 void AppendToHeaderBlock(const char* const extra_headers[],
115 int extra_header_count,
116 SpdyHeaderBlock* headers) {
117 std::string this_header;
118 std::string this_value;
120 if (!extra_header_count)
121 return;
123 // Sanity check: Non-NULL header list.
124 DCHECK(NULL != extra_headers) << "NULL header value pair list";
125 // Sanity check: Non-NULL header map.
126 DCHECK(NULL != headers) << "NULL header map";
127 // Copy in the headers.
128 for (int i = 0; i < extra_header_count; i++) {
129 // Sanity check: Non-empty header.
130 DCHECK_NE('\0', *extra_headers[i * 2]) << "Empty header value pair";
131 this_header = extra_headers[i * 2];
132 std::string::size_type header_len = this_header.length();
133 if (!header_len)
134 continue;
135 this_value = extra_headers[1 + (i * 2)];
136 std::string new_value;
137 if (headers->find(this_header) != headers->end()) {
138 // More than one entry in the header.
139 // Don't add the header again, just the append to the value,
140 // separated by a NULL character.
142 // Adjust the value.
143 new_value = (*headers)[this_header];
144 // Put in a NULL separator.
145 new_value.append(1, '\0');
146 // Append the new value.
147 new_value += this_value;
148 } else {
149 // Not a duplicate, just write the value.
150 new_value = this_value;
152 (*headers)[this_header] = new_value;
156 // Create a MockWrite from the given SpdyFrame.
157 MockWrite CreateMockWrite(const SpdyFrame& req) {
158 return MockWrite(ASYNC, req.data(), req.size());
161 // Create a MockWrite from the given SpdyFrame and sequence number.
162 MockWrite CreateMockWrite(const SpdyFrame& req, int seq) {
163 return CreateMockWrite(req, seq, ASYNC);
166 // Create a MockWrite from the given SpdyFrame and sequence number.
167 MockWrite CreateMockWrite(const SpdyFrame& req, int seq, IoMode mode) {
168 return MockWrite(mode, req.data(), req.size(), seq);
171 // Create a MockRead from the given SpdyFrame.
172 MockRead CreateMockRead(const SpdyFrame& resp) {
173 return MockRead(ASYNC, resp.data(), resp.size());
176 // Create a MockRead from the given SpdyFrame and sequence number.
177 MockRead CreateMockRead(const SpdyFrame& resp, int seq) {
178 return CreateMockRead(resp, seq, ASYNC);
181 // Create a MockRead from the given SpdyFrame and sequence number.
182 MockRead CreateMockRead(const SpdyFrame& resp, int seq, IoMode mode) {
183 return MockRead(mode, resp.data(), resp.size(), seq);
186 // Combines the given SpdyFrames into the given char array and returns
187 // the total length.
188 int CombineFrames(const SpdyFrame** frames, int num_frames,
189 char* buff, int buff_len) {
190 int total_len = 0;
191 for (int i = 0; i < num_frames; ++i) {
192 total_len += frames[i]->size();
194 DCHECK_LE(total_len, buff_len);
195 char* ptr = buff;
196 for (int i = 0; i < num_frames; ++i) {
197 int len = frames[i]->size();
198 memcpy(ptr, frames[i]->data(), len);
199 ptr += len;
201 return total_len;
204 namespace {
206 class PriorityGetter : public BufferedSpdyFramerVisitorInterface {
207 public:
208 PriorityGetter() : priority_(0) {}
209 ~PriorityGetter() override {}
211 SpdyPriority priority() const {
212 return priority_;
215 void OnError(SpdyFramer::SpdyError error_code) override {}
216 void OnStreamError(SpdyStreamId stream_id,
217 const std::string& description) override {}
218 void OnSynStream(SpdyStreamId stream_id,
219 SpdyStreamId associated_stream_id,
220 SpdyPriority priority,
221 bool fin,
222 bool unidirectional,
223 const SpdyHeaderBlock& headers) override {
224 priority_ = priority;
226 void OnSynReply(SpdyStreamId stream_id,
227 bool fin,
228 const SpdyHeaderBlock& headers) override {}
229 void OnHeaders(SpdyStreamId stream_id,
230 bool has_priority,
231 SpdyPriority priority,
232 SpdyStreamId parent_stream_id,
233 bool exclusive,
234 bool fin,
235 const SpdyHeaderBlock& headers) override {
236 if (has_priority) {
237 priority_ = priority;
240 void OnDataFrameHeader(SpdyStreamId stream_id,
241 size_t length,
242 bool fin) override {}
243 void OnStreamFrameData(SpdyStreamId stream_id,
244 const char* data,
245 size_t len,
246 bool fin) override {}
247 void OnStreamPadding(SpdyStreamId stream_id, size_t len) override {}
248 void OnSettings(bool clear_persisted) override {}
249 void OnSetting(SpdySettingsIds id, uint8 flags, uint32 value) override {}
250 void OnPing(SpdyPingId unique_id, bool is_ack) override {}
251 void OnRstStream(SpdyStreamId stream_id,
252 SpdyRstStreamStatus status) override {}
253 void OnGoAway(SpdyStreamId last_accepted_stream_id,
254 SpdyGoAwayStatus status) override {}
255 void OnWindowUpdate(SpdyStreamId stream_id, int delta_window_size) override {}
256 void OnPushPromise(SpdyStreamId stream_id,
257 SpdyStreamId promised_stream_id,
258 const SpdyHeaderBlock& headers) override {}
259 bool OnUnknownFrame(SpdyStreamId stream_id, int frame_type) override {
260 return false;
263 private:
264 SpdyPriority priority_;
267 } // namespace
269 bool GetSpdyPriority(SpdyMajorVersion version,
270 const SpdyFrame& frame,
271 SpdyPriority* priority) {
272 BufferedSpdyFramer framer(version, false);
273 PriorityGetter priority_getter;
274 framer.set_visitor(&priority_getter);
275 size_t frame_size = frame.size();
276 if (framer.ProcessInput(frame.data(), frame_size) != frame_size) {
277 return false;
279 *priority = priority_getter.priority();
280 return true;
283 base::WeakPtr<SpdyStream> CreateStreamSynchronously(
284 SpdyStreamType type,
285 const base::WeakPtr<SpdySession>& session,
286 const GURL& url,
287 RequestPriority priority,
288 const BoundNetLog& net_log) {
289 SpdyStreamRequest stream_request;
290 int rv = stream_request.StartRequest(type, session, url, priority, net_log,
291 CompletionCallback());
292 return
293 (rv == OK) ? stream_request.ReleaseStream() : base::WeakPtr<SpdyStream>();
296 StreamReleaserCallback::StreamReleaserCallback() {}
298 StreamReleaserCallback::~StreamReleaserCallback() {}
300 CompletionCallback StreamReleaserCallback::MakeCallback(
301 SpdyStreamRequest* request) {
302 return base::Bind(&StreamReleaserCallback::OnComplete,
303 base::Unretained(this),
304 request);
307 void StreamReleaserCallback::OnComplete(
308 SpdyStreamRequest* request, int result) {
309 if (result == OK)
310 request->ReleaseStream()->Cancel();
311 SetResult(result);
314 MockECSignatureCreator::MockECSignatureCreator(crypto::ECPrivateKey* key)
315 : key_(key) {
318 bool MockECSignatureCreator::Sign(const uint8* data,
319 int data_len,
320 std::vector<uint8>* signature) {
321 std::vector<uint8> private_key_value;
322 key_->ExportValue(&private_key_value);
323 std::string head = "fakesignature";
324 std::string tail = "/fakesignature";
326 signature->clear();
327 signature->insert(signature->end(), head.begin(), head.end());
328 signature->insert(signature->end(), private_key_value.begin(),
329 private_key_value.end());
330 signature->insert(signature->end(), '-');
331 signature->insert(signature->end(), data, data + data_len);
332 signature->insert(signature->end(), tail.begin(), tail.end());
333 return true;
336 bool MockECSignatureCreator::DecodeSignature(
337 const std::vector<uint8>& signature,
338 std::vector<uint8>* out_raw_sig) {
339 *out_raw_sig = signature;
340 return true;
343 MockECSignatureCreatorFactory::MockECSignatureCreatorFactory() {
344 crypto::ECSignatureCreator::SetFactoryForTesting(this);
347 MockECSignatureCreatorFactory::~MockECSignatureCreatorFactory() {
348 crypto::ECSignatureCreator::SetFactoryForTesting(NULL);
351 crypto::ECSignatureCreator* MockECSignatureCreatorFactory::Create(
352 crypto::ECPrivateKey* key) {
353 return new MockECSignatureCreator(key);
356 SpdySessionDependencies::SpdySessionDependencies(NextProto protocol)
357 : host_resolver(new MockCachingHostResolver),
358 cert_verifier(new MockCertVerifier),
359 transport_security_state(new TransportSecurityState),
360 proxy_service(ProxyService::CreateDirect()),
361 ssl_config_service(new SSLConfigServiceDefaults),
362 socket_factory(new MockClientSocketFactory),
363 deterministic_socket_factory(new DeterministicMockClientSocketFactory),
364 http_auth_handler_factory(
365 HttpAuthHandlerFactory::CreateDefault(host_resolver.get())),
366 enable_ip_pooling(true),
367 enable_compression(false),
368 enable_ping(false),
369 enable_user_alternate_protocol_ports(false),
370 protocol(protocol),
371 session_max_recv_window_size(
372 SpdySession::GetDefaultInitialWindowSize(protocol)),
373 stream_max_recv_window_size(
374 SpdySession::GetDefaultInitialWindowSize(protocol)),
375 time_func(&base::TimeTicks::Now),
376 use_alternative_services(false),
377 net_log(NULL) {
378 DCHECK(next_proto_is_spdy(protocol)) << "Invalid protocol: " << protocol;
380 // Note: The CancelledTransaction test does cleanup by running all
381 // tasks in the message loop (RunAllPending). Unfortunately, that
382 // doesn't clean up tasks on the host resolver thread; and
383 // TCPConnectJob is currently not cancellable. Using synchronous
384 // lookups allows the test to shutdown cleanly. Until we have
385 // cancellable TCPConnectJobs, use synchronous lookups.
386 host_resolver->set_synchronous_mode(true);
389 SpdySessionDependencies::SpdySessionDependencies(
390 NextProto protocol,
391 scoped_ptr<ProxyService> proxy_service)
392 : host_resolver(new MockHostResolver),
393 cert_verifier(new MockCertVerifier),
394 transport_security_state(new TransportSecurityState),
395 proxy_service(proxy_service.Pass()),
396 ssl_config_service(new SSLConfigServiceDefaults),
397 socket_factory(new MockClientSocketFactory),
398 deterministic_socket_factory(new DeterministicMockClientSocketFactory),
399 http_auth_handler_factory(
400 HttpAuthHandlerFactory::CreateDefault(host_resolver.get())),
401 enable_ip_pooling(true),
402 enable_compression(false),
403 enable_ping(false),
404 enable_user_alternate_protocol_ports(false),
405 protocol(protocol),
406 session_max_recv_window_size(
407 SpdySession::GetDefaultInitialWindowSize(protocol)),
408 stream_max_recv_window_size(
409 SpdySession::GetDefaultInitialWindowSize(protocol)),
410 time_func(&base::TimeTicks::Now),
411 use_alternative_services(true),
412 net_log(NULL) {
413 DCHECK(next_proto_is_spdy(protocol)) << "Invalid protocol: " << protocol;
416 SpdySessionDependencies::~SpdySessionDependencies() {}
418 // static
419 HttpNetworkSession* SpdySessionDependencies::SpdyCreateSession(
420 SpdySessionDependencies* session_deps) {
421 HttpNetworkSession::Params params = CreateSessionParams(session_deps);
422 params.client_socket_factory = session_deps->socket_factory.get();
423 HttpNetworkSession* http_session = new HttpNetworkSession(params);
424 SpdySessionPoolPeer pool_peer(http_session->spdy_session_pool());
425 pool_peer.SetEnableSendingInitialData(false);
426 return http_session;
429 // static
430 HttpNetworkSession* SpdySessionDependencies::SpdyCreateSessionDeterministic(
431 SpdySessionDependencies* session_deps) {
432 HttpNetworkSession::Params params = CreateSessionParams(session_deps);
433 params.client_socket_factory =
434 session_deps->deterministic_socket_factory.get();
435 HttpNetworkSession* http_session = new HttpNetworkSession(params);
436 SpdySessionPoolPeer pool_peer(http_session->spdy_session_pool());
437 pool_peer.SetEnableSendingInitialData(false);
438 return http_session;
441 // static
442 HttpNetworkSession::Params SpdySessionDependencies::CreateSessionParams(
443 SpdySessionDependencies* session_deps) {
444 DCHECK(next_proto_is_spdy(session_deps->protocol)) <<
445 "Invalid protocol: " << session_deps->protocol;
447 HttpNetworkSession::Params params;
448 params.host_resolver = session_deps->host_resolver.get();
449 params.cert_verifier = session_deps->cert_verifier.get();
450 params.transport_security_state =
451 session_deps->transport_security_state.get();
452 params.proxy_service = session_deps->proxy_service.get();
453 params.ssl_config_service = session_deps->ssl_config_service.get();
454 params.http_auth_handler_factory =
455 session_deps->http_auth_handler_factory.get();
456 params.http_server_properties =
457 session_deps->http_server_properties.GetWeakPtr();
458 params.enable_spdy_compression = session_deps->enable_compression;
459 params.enable_spdy_ping_based_connection_checking = session_deps->enable_ping;
460 params.enable_user_alternate_protocol_ports =
461 session_deps->enable_user_alternate_protocol_ports;
462 params.spdy_default_protocol = session_deps->protocol;
463 params.spdy_session_max_recv_window_size =
464 session_deps->session_max_recv_window_size;
465 params.spdy_stream_max_recv_window_size =
466 session_deps->stream_max_recv_window_size;
467 params.time_func = session_deps->time_func;
468 params.next_protos = session_deps->next_protos;
469 params.trusted_spdy_proxy = session_deps->trusted_spdy_proxy;
470 params.use_alternative_services = session_deps->use_alternative_services;
471 params.net_log = session_deps->net_log;
472 return params;
475 SpdyURLRequestContext::SpdyURLRequestContext(NextProto protocol)
476 : storage_(this) {
477 DCHECK(next_proto_is_spdy(protocol)) << "Invalid protocol: " << protocol;
479 storage_.set_host_resolver(scoped_ptr<HostResolver>(new MockHostResolver));
480 storage_.set_cert_verifier(make_scoped_ptr(new MockCertVerifier).Pass());
481 storage_.set_transport_security_state(
482 make_scoped_ptr(new TransportSecurityState));
483 storage_.set_proxy_service(ProxyService::CreateDirect());
484 storage_.set_ssl_config_service(new SSLConfigServiceDefaults);
485 storage_.set_http_auth_handler_factory(
486 HttpAuthHandlerFactory::CreateDefault(host_resolver()));
487 storage_.set_http_server_properties(
488 scoped_ptr<HttpServerProperties>(new HttpServerPropertiesImpl()));
489 storage_.set_job_factory(
490 make_scoped_ptr(new URLRequestJobFactoryImpl()).Pass());
491 HttpNetworkSession::Params params;
492 params.client_socket_factory = &socket_factory_;
493 params.host_resolver = host_resolver();
494 params.cert_verifier = cert_verifier();
495 params.transport_security_state = transport_security_state();
496 params.proxy_service = proxy_service();
497 params.ssl_config_service = ssl_config_service();
498 params.http_auth_handler_factory = http_auth_handler_factory();
499 params.network_delegate = network_delegate();
500 params.enable_spdy_compression = false;
501 params.enable_spdy_ping_based_connection_checking = false;
502 params.spdy_default_protocol = protocol;
503 params.http_server_properties = http_server_properties();
504 scoped_refptr<HttpNetworkSession> network_session(
505 new HttpNetworkSession(params));
506 SpdySessionPoolPeer pool_peer(network_session->spdy_session_pool());
507 pool_peer.SetEnableSendingInitialData(false);
508 storage_.set_http_transaction_factory(
509 make_scoped_ptr(new HttpCache(network_session.get(),
510 HttpCache::DefaultBackend::InMemory(0)))
511 .Pass());
514 SpdyURLRequestContext::~SpdyURLRequestContext() {
515 AssertNoURLRequests();
518 bool HasSpdySession(SpdySessionPool* pool, const SpdySessionKey& key) {
519 return pool->FindAvailableSession(key, BoundNetLog()) != NULL;
522 namespace {
524 base::WeakPtr<SpdySession> CreateSpdySessionHelper(
525 const scoped_refptr<HttpNetworkSession>& http_session,
526 const SpdySessionKey& key,
527 const BoundNetLog& net_log,
528 Error expected_status,
529 bool is_secure) {
530 EXPECT_FALSE(HasSpdySession(http_session->spdy_session_pool(), key));
532 scoped_refptr<TransportSocketParams> transport_params(
533 new TransportSocketParams(
534 key.host_port_pair(), false, false, OnHostResolutionCallback(),
535 TransportSocketParams::COMBINE_CONNECT_AND_WRITE_DEFAULT));
537 scoped_ptr<ClientSocketHandle> connection(new ClientSocketHandle);
538 TestCompletionCallback callback;
540 int rv = ERR_UNEXPECTED;
541 if (is_secure) {
542 SSLConfig ssl_config;
543 scoped_refptr<SSLSocketParams> ssl_params(
544 new SSLSocketParams(transport_params,
545 NULL,
546 NULL,
547 key.host_port_pair(),
548 ssl_config,
549 key.privacy_mode(),
551 false));
552 rv = connection->Init(key.host_port_pair().ToString(),
553 ssl_params,
554 MEDIUM,
555 callback.callback(),
556 http_session->GetSSLSocketPool(
557 HttpNetworkSession::NORMAL_SOCKET_POOL),
558 net_log);
559 } else {
560 rv = connection->Init(key.host_port_pair().ToString(),
561 transport_params,
562 MEDIUM,
563 callback.callback(),
564 http_session->GetTransportSocketPool(
565 HttpNetworkSession::NORMAL_SOCKET_POOL),
566 net_log);
569 if (rv == ERR_IO_PENDING)
570 rv = callback.WaitForResult();
572 EXPECT_EQ(OK, rv);
574 base::WeakPtr<SpdySession> spdy_session =
575 http_session->spdy_session_pool()->CreateAvailableSessionFromSocket(
576 key, connection.Pass(), net_log, OK, is_secure);
577 // Failure is reported asynchronously.
578 EXPECT_TRUE(spdy_session != NULL);
579 EXPECT_TRUE(HasSpdySession(http_session->spdy_session_pool(), key));
580 return spdy_session;
583 } // namespace
585 base::WeakPtr<SpdySession> CreateInsecureSpdySession(
586 const scoped_refptr<HttpNetworkSession>& http_session,
587 const SpdySessionKey& key,
588 const BoundNetLog& net_log) {
589 return CreateSpdySessionHelper(http_session, key, net_log,
590 OK, false /* is_secure */);
593 base::WeakPtr<SpdySession> TryCreateInsecureSpdySessionExpectingFailure(
594 const scoped_refptr<HttpNetworkSession>& http_session,
595 const SpdySessionKey& key,
596 Error expected_error,
597 const BoundNetLog& net_log) {
598 DCHECK_LT(expected_error, ERR_IO_PENDING);
599 return CreateSpdySessionHelper(http_session, key, net_log,
600 expected_error, false /* is_secure */);
603 base::WeakPtr<SpdySession> CreateSecureSpdySession(
604 const scoped_refptr<HttpNetworkSession>& http_session,
605 const SpdySessionKey& key,
606 const BoundNetLog& net_log) {
607 return CreateSpdySessionHelper(http_session, key, net_log,
608 OK, true /* is_secure */);
611 namespace {
613 // A ClientSocket used for CreateFakeSpdySession() below.
614 class FakeSpdySessionClientSocket : public MockClientSocket {
615 public:
616 explicit FakeSpdySessionClientSocket(int read_result)
617 : MockClientSocket(BoundNetLog()), read_result_(read_result) {}
619 ~FakeSpdySessionClientSocket() override {}
621 int Read(IOBuffer* buf,
622 int buf_len,
623 const CompletionCallback& callback) override {
624 return read_result_;
627 int Write(IOBuffer* buf,
628 int buf_len,
629 const CompletionCallback& callback) override {
630 return ERR_IO_PENDING;
633 // Return kProtoUnknown to use the pool's default protocol.
634 NextProto GetNegotiatedProtocol() const override { return kProtoUnknown; }
636 // The functions below are not expected to be called.
638 int Connect(const CompletionCallback& callback) override {
639 ADD_FAILURE();
640 return ERR_UNEXPECTED;
643 bool WasEverUsed() const override {
644 ADD_FAILURE();
645 return false;
648 bool UsingTCPFastOpen() const override {
649 ADD_FAILURE();
650 return false;
653 bool WasNpnNegotiated() const override {
654 ADD_FAILURE();
655 return false;
658 bool GetSSLInfo(SSLInfo* ssl_info) override {
659 ADD_FAILURE();
660 return false;
663 private:
664 int read_result_;
667 base::WeakPtr<SpdySession> CreateFakeSpdySessionHelper(
668 SpdySessionPool* pool,
669 const SpdySessionKey& key,
670 Error expected_status) {
671 EXPECT_NE(expected_status, ERR_IO_PENDING);
672 EXPECT_FALSE(HasSpdySession(pool, key));
673 scoped_ptr<ClientSocketHandle> handle(new ClientSocketHandle());
674 handle->SetSocket(scoped_ptr<StreamSocket>(new FakeSpdySessionClientSocket(
675 expected_status == OK ? ERR_IO_PENDING : expected_status)));
676 base::WeakPtr<SpdySession> spdy_session =
677 pool->CreateAvailableSessionFromSocket(
678 key, handle.Pass(), BoundNetLog(), OK, true /* is_secure */);
679 // Failure is reported asynchronously.
680 EXPECT_TRUE(spdy_session != NULL);
681 EXPECT_TRUE(HasSpdySession(pool, key));
682 return spdy_session;
685 } // namespace
687 base::WeakPtr<SpdySession> CreateFakeSpdySession(SpdySessionPool* pool,
688 const SpdySessionKey& key) {
689 return CreateFakeSpdySessionHelper(pool, key, OK);
692 base::WeakPtr<SpdySession> TryCreateFakeSpdySessionExpectingFailure(
693 SpdySessionPool* pool,
694 const SpdySessionKey& key,
695 Error expected_error) {
696 DCHECK_LT(expected_error, ERR_IO_PENDING);
697 return CreateFakeSpdySessionHelper(pool, key, expected_error);
700 SpdySessionPoolPeer::SpdySessionPoolPeer(SpdySessionPool* pool) : pool_(pool) {
703 void SpdySessionPoolPeer::RemoveAliases(const SpdySessionKey& key) {
704 pool_->RemoveAliases(key);
707 void SpdySessionPoolPeer::DisableDomainAuthenticationVerification() {
708 pool_->verify_domain_authentication_ = false;
711 void SpdySessionPoolPeer::SetEnableSendingInitialData(bool enabled) {
712 pool_->enable_sending_initial_data_ = enabled;
715 void SpdySessionPoolPeer::SetSessionMaxRecvWindowSize(size_t window) {
716 pool_->session_max_recv_window_size_ = window;
719 void SpdySessionPoolPeer::SetStreamInitialRecvWindowSize(size_t window) {
720 pool_->stream_max_recv_window_size_ = window;
723 SpdyTestUtil::SpdyTestUtil(NextProto protocol)
724 : protocol_(protocol),
725 spdy_version_(NextProtoToSpdyMajorVersion(protocol)),
726 default_url_(GURL(kDefaultURL)) {
727 DCHECK(next_proto_is_spdy(protocol)) << "Invalid protocol: " << protocol;
730 void SpdyTestUtil::AddUrlToHeaderBlock(base::StringPiece url,
731 SpdyHeaderBlock* headers) const {
732 std::string scheme, host, path;
733 ParseUrl(url, &scheme, &host, &path);
734 (*headers)[GetSchemeKey()] = scheme;
735 (*headers)[GetHostKey()] = host;
736 (*headers)[GetPathKey()] = path;
739 scoped_ptr<SpdyHeaderBlock> SpdyTestUtil::ConstructGetHeaderBlock(
740 base::StringPiece url) const {
741 return ConstructHeaderBlock("GET", url, NULL);
744 scoped_ptr<SpdyHeaderBlock> SpdyTestUtil::ConstructGetHeaderBlockForProxy(
745 base::StringPiece url) const {
746 scoped_ptr<SpdyHeaderBlock> headers(ConstructGetHeaderBlock(url));
747 return headers.Pass();
750 scoped_ptr<SpdyHeaderBlock> SpdyTestUtil::ConstructHeadHeaderBlock(
751 base::StringPiece url,
752 int64 content_length) const {
753 return ConstructHeaderBlock("HEAD", url, nullptr);
756 scoped_ptr<SpdyHeaderBlock> SpdyTestUtil::ConstructPostHeaderBlock(
757 base::StringPiece url,
758 int64 content_length) const {
759 return ConstructHeaderBlock("POST", url, &content_length);
762 scoped_ptr<SpdyHeaderBlock> SpdyTestUtil::ConstructPutHeaderBlock(
763 base::StringPiece url,
764 int64 content_length) const {
765 return ConstructHeaderBlock("PUT", url, &content_length);
768 SpdyFrame* SpdyTestUtil::ConstructSpdyFrame(
769 const SpdyHeaderInfo& header_info,
770 scoped_ptr<SpdyHeaderBlock> headers) const {
771 BufferedSpdyFramer framer(spdy_version_, header_info.compressed);
772 SpdyFrame* frame = NULL;
773 switch (header_info.kind) {
774 case DATA:
775 frame = framer.CreateDataFrame(header_info.id, header_info.data,
776 header_info.data_length,
777 header_info.data_flags);
778 break;
779 case SYN_STREAM:
781 frame = framer.CreateSynStream(header_info.id, header_info.assoc_id,
782 header_info.priority,
783 header_info.control_flags,
784 headers.get());
786 break;
787 case SYN_REPLY:
788 frame = framer.CreateSynReply(header_info.id, header_info.control_flags,
789 headers.get());
790 break;
791 case RST_STREAM:
792 frame = framer.CreateRstStream(header_info.id, header_info.status);
793 break;
794 case HEADERS:
795 frame = framer.CreateHeaders(header_info.id, header_info.control_flags,
796 header_info.priority,
797 headers.get());
798 break;
799 default:
800 ADD_FAILURE();
801 break;
803 return frame;
806 SpdyFrame* SpdyTestUtil::ConstructSpdyFrame(const SpdyHeaderInfo& header_info,
807 const char* const extra_headers[],
808 int extra_header_count,
809 const char* const tail_headers[],
810 int tail_header_count) const {
811 scoped_ptr<SpdyHeaderBlock> headers(new SpdyHeaderBlock());
812 AppendToHeaderBlock(extra_headers, extra_header_count, headers.get());
813 if (tail_headers && tail_header_count)
814 AppendToHeaderBlock(tail_headers, tail_header_count, headers.get());
815 return ConstructSpdyFrame(header_info, headers.Pass());
818 SpdyFrame* SpdyTestUtil::ConstructSpdyControlFrame(
819 scoped_ptr<SpdyHeaderBlock> headers,
820 bool compressed,
821 SpdyStreamId stream_id,
822 RequestPriority request_priority,
823 SpdyFrameType type,
824 SpdyControlFlags flags,
825 SpdyStreamId associated_stream_id) const {
826 EXPECT_GE(type, DATA);
827 EXPECT_LE(type, PRIORITY);
828 const SpdyHeaderInfo header_info = {
829 type,
830 stream_id,
831 associated_stream_id,
832 ConvertRequestPriorityToSpdyPriority(request_priority, spdy_version_),
833 0, // credential slot
834 flags,
835 compressed,
836 RST_STREAM_INVALID, // status
837 NULL, // data
838 0, // length
839 DATA_FLAG_NONE
841 return ConstructSpdyFrame(header_info, headers.Pass());
844 SpdyFrame* SpdyTestUtil::ConstructSpdyControlFrame(
845 const char* const extra_headers[],
846 int extra_header_count,
847 bool compressed,
848 SpdyStreamId stream_id,
849 RequestPriority request_priority,
850 SpdyFrameType type,
851 SpdyControlFlags flags,
852 const char* const* tail_headers,
853 int tail_header_size,
854 SpdyStreamId associated_stream_id) const {
855 scoped_ptr<SpdyHeaderBlock> headers(new SpdyHeaderBlock());
856 AppendToHeaderBlock(extra_headers, extra_header_count, headers.get());
857 if (tail_headers && tail_header_size)
858 AppendToHeaderBlock(tail_headers, tail_header_size / 2, headers.get());
859 return ConstructSpdyControlFrame(
860 headers.Pass(), compressed, stream_id,
861 request_priority, type, flags, associated_stream_id);
864 std::string SpdyTestUtil::ConstructSpdyReplyString(
865 const SpdyHeaderBlock& headers) const {
866 std::string reply_string;
867 for (SpdyHeaderBlock::const_iterator it = headers.begin();
868 it != headers.end(); ++it) {
869 std::string key = it->first;
870 // Remove leading colon from "special" headers (for SPDY3 and
871 // above).
872 if (spdy_version() >= SPDY3 && key[0] == ':')
873 key = key.substr(1);
874 for (const std::string& value :
875 base::SplitString(it->second, base::StringPiece("\0", 1),
876 base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL)) {
877 reply_string += key + ": " + value + "\n";
880 return reply_string;
883 // TODO(jgraettinger): Eliminate uses of this method in tests (prefer
884 // SpdySettingsIR).
885 SpdyFrame* SpdyTestUtil::ConstructSpdySettings(
886 const SettingsMap& settings) const {
887 SpdySettingsIR settings_ir;
888 for (SettingsMap::const_iterator it = settings.begin();
889 it != settings.end();
890 ++it) {
891 settings_ir.AddSetting(
892 it->first,
893 (it->second.first & SETTINGS_FLAG_PLEASE_PERSIST) != 0,
894 (it->second.first & SETTINGS_FLAG_PERSISTED) != 0,
895 it->second.second);
897 return CreateFramer(false)->SerializeFrame(settings_ir);
900 SpdyFrame* SpdyTestUtil::ConstructSpdySettingsAck() const {
901 char kEmptyWrite[] = "";
903 if (spdy_version() > SPDY3) {
904 SpdySettingsIR settings_ir;
905 settings_ir.set_is_ack(true);
906 return CreateFramer(false)->SerializeFrame(settings_ir);
908 // No settings ACK write occurs. Create an empty placeholder write.
909 return new SpdyFrame(kEmptyWrite, 0, false);
912 SpdyFrame* SpdyTestUtil::ConstructSpdyPing(uint32 ping_id, bool is_ack) const {
913 SpdyPingIR ping_ir(ping_id);
914 ping_ir.set_is_ack(is_ack);
915 return CreateFramer(false)->SerializeFrame(ping_ir);
918 SpdyFrame* SpdyTestUtil::ConstructSpdyGoAway() const {
919 return ConstructSpdyGoAway(0);
922 SpdyFrame* SpdyTestUtil::ConstructSpdyGoAway(
923 SpdyStreamId last_good_stream_id) const {
924 SpdyGoAwayIR go_ir(last_good_stream_id, GOAWAY_OK, "go away");
925 return CreateFramer(false)->SerializeFrame(go_ir);
928 SpdyFrame* SpdyTestUtil::ConstructSpdyGoAway(SpdyStreamId last_good_stream_id,
929 SpdyGoAwayStatus status,
930 const std::string& desc) const {
931 SpdyGoAwayIR go_ir(last_good_stream_id, status, desc);
932 return CreateFramer(false)->SerializeFrame(go_ir);
935 SpdyFrame* SpdyTestUtil::ConstructSpdyWindowUpdate(
936 const SpdyStreamId stream_id, uint32 delta_window_size) const {
937 SpdyWindowUpdateIR update_ir(stream_id, delta_window_size);
938 return CreateFramer(false)->SerializeFrame(update_ir);
941 // TODO(jgraettinger): Eliminate uses of this method in tests (prefer
942 // SpdyRstStreamIR).
943 SpdyFrame* SpdyTestUtil::ConstructSpdyRstStream(
944 SpdyStreamId stream_id,
945 SpdyRstStreamStatus status) const {
946 SpdyRstStreamIR rst_ir(stream_id, status, "");
947 return CreateFramer(false)->SerializeRstStream(rst_ir);
950 SpdyFrame* SpdyTestUtil::ConstructSpdyGet(
951 const char* const url,
952 bool compressed,
953 SpdyStreamId stream_id,
954 RequestPriority request_priority) const {
955 scoped_ptr<SpdyHeaderBlock> block(ConstructGetHeaderBlock(url));
956 return ConstructSpdySyn(
957 stream_id, *block, request_priority, compressed, true);
960 SpdyFrame* SpdyTestUtil::ConstructSpdyGet(const char* const extra_headers[],
961 int extra_header_count,
962 bool compressed,
963 int stream_id,
964 RequestPriority request_priority,
965 bool direct) const {
966 SpdyHeaderBlock block;
967 AddUrlToHeaderBlock(default_url_.spec(), &block);
968 block[GetMethodKey()] = "GET";
969 MaybeAddVersionHeader(&block);
970 AppendToHeaderBlock(extra_headers, extra_header_count, &block);
971 return ConstructSpdySyn(stream_id, block, request_priority, compressed, true);
974 SpdyFrame* SpdyTestUtil::ConstructSpdyConnect(
975 const char* const extra_headers[],
976 int extra_header_count,
977 int stream_id,
978 RequestPriority priority,
979 const HostPortPair& host_port_pair) const {
980 SpdyHeaderBlock block;
981 block[GetMethodKey()] = "CONNECT";
982 if (spdy_version() < HTTP2) {
983 block[GetPathKey()] = host_port_pair.ToString();
984 block[GetHostKey()] = (host_port_pair.port() == 443)
985 ? host_port_pair.host()
986 : host_port_pair.ToString();
987 } else {
988 block[GetHostKey()] = host_port_pair.ToString();
991 MaybeAddVersionHeader(&block);
992 AppendToHeaderBlock(extra_headers, extra_header_count, &block);
993 return ConstructSpdySyn(stream_id, block, priority, false, false);
996 SpdyFrame* SpdyTestUtil::ConstructSpdyPush(const char* const extra_headers[],
997 int extra_header_count,
998 int stream_id,
999 int associated_stream_id,
1000 const char* url) {
1001 if (spdy_version() < HTTP2) {
1002 SpdySynStreamIR syn_stream(stream_id);
1003 syn_stream.set_associated_to_stream_id(associated_stream_id);
1004 syn_stream.SetHeader("hello", "bye");
1005 syn_stream.SetHeader(GetStatusKey(), "200 OK");
1006 syn_stream.SetHeader(GetVersionKey(), "HTTP/1.1");
1007 AddUrlToHeaderBlock(url, syn_stream.mutable_header_block());
1008 AppendToHeaderBlock(extra_headers, extra_header_count,
1009 syn_stream.mutable_header_block());
1010 return CreateFramer(false)->SerializeFrame(syn_stream);
1011 } else {
1012 SpdyPushPromiseIR push_promise(associated_stream_id, stream_id);
1013 AddUrlToHeaderBlock(url, push_promise.mutable_header_block());
1014 scoped_ptr<SpdyFrame> push_promise_frame(
1015 CreateFramer(false)->SerializeFrame(push_promise));
1017 SpdyHeadersIR headers(stream_id);
1018 headers.SetHeader("hello", "bye");
1019 headers.SetHeader(GetStatusKey(), "200 OK");
1020 AppendToHeaderBlock(extra_headers, extra_header_count,
1021 headers.mutable_header_block());
1022 scoped_ptr<SpdyFrame> headers_frame(
1023 CreateFramer(false)->SerializeFrame(headers));
1025 int joint_data_size = push_promise_frame->size() + headers_frame->size();
1026 scoped_ptr<char[]> data(new char[joint_data_size]);
1027 const SpdyFrame* frames[2] = {
1028 push_promise_frame.get(), headers_frame.get(),
1030 int combined_size =
1031 CombineFrames(frames, arraysize(frames), data.get(), joint_data_size);
1032 DCHECK_EQ(combined_size, joint_data_size);
1033 return new SpdyFrame(data.release(), joint_data_size, true);
1037 SpdyFrame* SpdyTestUtil::ConstructSpdyPush(const char* const extra_headers[],
1038 int extra_header_count,
1039 int stream_id,
1040 int associated_stream_id,
1041 const char* url,
1042 const char* status,
1043 const char* location) {
1044 if (spdy_version() < HTTP2) {
1045 SpdySynStreamIR syn_stream(stream_id);
1046 syn_stream.set_associated_to_stream_id(associated_stream_id);
1047 syn_stream.SetHeader("hello", "bye");
1048 syn_stream.SetHeader(GetStatusKey(), status);
1049 syn_stream.SetHeader(GetVersionKey(), "HTTP/1.1");
1050 syn_stream.SetHeader("location", location);
1051 AddUrlToHeaderBlock(url, syn_stream.mutable_header_block());
1052 AppendToHeaderBlock(extra_headers, extra_header_count,
1053 syn_stream.mutable_header_block());
1054 return CreateFramer(false)->SerializeFrame(syn_stream);
1055 } else {
1056 SpdyPushPromiseIR push_promise(associated_stream_id, stream_id);
1057 AddUrlToHeaderBlock(url, push_promise.mutable_header_block());
1058 scoped_ptr<SpdyFrame> push_promise_frame(
1059 CreateFramer(false)->SerializeFrame(push_promise));
1061 SpdyHeadersIR headers(stream_id);
1062 headers.SetHeader("hello", "bye");
1063 headers.SetHeader(GetStatusKey(), status);
1064 headers.SetHeader("location", location);
1065 AppendToHeaderBlock(extra_headers, extra_header_count,
1066 headers.mutable_header_block());
1067 scoped_ptr<SpdyFrame> headers_frame(
1068 CreateFramer(false)->SerializeFrame(headers));
1070 int joint_data_size = push_promise_frame->size() + headers_frame->size();
1071 scoped_ptr<char[]> data(new char[joint_data_size]);
1072 const SpdyFrame* frames[2] = {
1073 push_promise_frame.get(), headers_frame.get(),
1075 int combined_size =
1076 CombineFrames(frames, arraysize(frames), data.get(), joint_data_size);
1077 DCHECK_EQ(combined_size, joint_data_size);
1078 return new SpdyFrame(data.release(), joint_data_size, true);
1082 SpdyFrame* SpdyTestUtil::ConstructInitialSpdyPushFrame(
1083 scoped_ptr<SpdyHeaderBlock> headers,
1084 int stream_id,
1085 int associated_stream_id) {
1086 if (spdy_version() < HTTP2) {
1087 SpdySynStreamIR syn_stream(stream_id);
1088 syn_stream.set_associated_to_stream_id(associated_stream_id);
1089 SetPriority(LOWEST, &syn_stream);
1090 syn_stream.set_header_block(*headers);
1091 return CreateFramer(false)->SerializeFrame(syn_stream);
1092 } else {
1093 SpdyPushPromiseIR push_promise(associated_stream_id, stream_id);
1094 push_promise.set_header_block(*headers);
1095 return CreateFramer(false)->SerializeFrame(push_promise);
1099 SpdyFrame* SpdyTestUtil::ConstructSpdyPushHeaders(
1100 int stream_id,
1101 const char* const extra_headers[],
1102 int extra_header_count) {
1103 SpdyHeadersIR headers(stream_id);
1104 headers.SetHeader(GetStatusKey(), "200 OK");
1105 MaybeAddVersionHeader(&headers);
1106 AppendToHeaderBlock(extra_headers, extra_header_count,
1107 headers.mutable_header_block());
1108 return CreateFramer(false)->SerializeFrame(headers);
1111 SpdyFrame* SpdyTestUtil::ConstructSpdyHeaderFrame(int stream_id,
1112 const char* const headers[],
1113 int header_count) {
1114 SpdyHeadersIR spdy_headers(stream_id);
1115 AppendToHeaderBlock(headers, header_count,
1116 spdy_headers.mutable_header_block());
1117 return CreateFramer(false)->SerializeFrame(spdy_headers);
1120 SpdyFrame* SpdyTestUtil::ConstructSpdySyn(int stream_id,
1121 const SpdyHeaderBlock& block,
1122 RequestPriority priority,
1123 bool compressed,
1124 bool fin) const {
1125 if (protocol_ < kProtoHTTP2) {
1126 SpdySynStreamIR syn_stream(stream_id);
1127 syn_stream.set_header_block(block);
1128 syn_stream.set_priority(
1129 ConvertRequestPriorityToSpdyPriority(priority, spdy_version()));
1130 syn_stream.set_fin(fin);
1131 return CreateFramer(compressed)->SerializeFrame(syn_stream);
1132 } else {
1133 SpdyHeadersIR headers(stream_id);
1134 headers.set_header_block(block);
1135 headers.set_has_priority(true);
1136 headers.set_priority(
1137 ConvertRequestPriorityToSpdyPriority(priority, spdy_version()));
1138 headers.set_fin(fin);
1139 return CreateFramer(compressed)->SerializeFrame(headers);
1143 SpdyFrame* SpdyTestUtil::ConstructSpdyReply(int stream_id,
1144 const SpdyHeaderBlock& headers) {
1145 if (protocol_ < kProtoHTTP2) {
1146 SpdySynReplyIR syn_reply(stream_id);
1147 syn_reply.set_header_block(headers);
1148 return CreateFramer(false)->SerializeFrame(syn_reply);
1149 } else {
1150 SpdyHeadersIR reply(stream_id);
1151 reply.set_header_block(headers);
1152 return CreateFramer(false)->SerializeFrame(reply);
1156 SpdyFrame* SpdyTestUtil::ConstructSpdySynReplyError(
1157 const char* const status,
1158 const char* const* const extra_headers,
1159 int extra_header_count,
1160 int stream_id) {
1161 SpdyHeaderBlock block;
1162 block["hello"] = "bye";
1163 block[GetStatusKey()] = status;
1164 MaybeAddVersionHeader(&block);
1165 AppendToHeaderBlock(extra_headers, extra_header_count, &block);
1167 return ConstructSpdyReply(stream_id, block);
1170 SpdyFrame* SpdyTestUtil::ConstructSpdyGetSynReplyRedirect(int stream_id) {
1171 static const char* const kExtraHeaders[] = {
1172 "location", "http://www.foo.com/index.php",
1174 return ConstructSpdySynReplyError("301 Moved Permanently", kExtraHeaders,
1175 arraysize(kExtraHeaders)/2, stream_id);
1178 SpdyFrame* SpdyTestUtil::ConstructSpdySynReplyError(int stream_id) {
1179 return ConstructSpdySynReplyError("500 Internal Server Error", NULL, 0, 1);
1182 SpdyFrame* SpdyTestUtil::ConstructSpdyGetSynReply(
1183 const char* const extra_headers[],
1184 int extra_header_count,
1185 int stream_id) {
1186 SpdyHeaderBlock block;
1187 block["hello"] = "bye";
1188 block[GetStatusKey()] = "200";
1189 MaybeAddVersionHeader(&block);
1190 AppendToHeaderBlock(extra_headers, extra_header_count, &block);
1192 return ConstructSpdyReply(stream_id, block);
1195 SpdyFrame* SpdyTestUtil::ConstructSpdyPost(const char* url,
1196 SpdyStreamId stream_id,
1197 int64 content_length,
1198 RequestPriority priority,
1199 const char* const extra_headers[],
1200 int extra_header_count) {
1201 scoped_ptr<SpdyHeaderBlock> block(
1202 ConstructPostHeaderBlock(url, content_length));
1203 AppendToHeaderBlock(extra_headers, extra_header_count, block.get());
1204 return ConstructSpdySyn(stream_id, *block, priority, false, false);
1207 SpdyFrame* SpdyTestUtil::ConstructChunkedSpdyPost(
1208 const char* const extra_headers[],
1209 int extra_header_count) {
1210 SpdyHeaderBlock block;
1211 block[GetMethodKey()] = "POST";
1212 AddUrlToHeaderBlock(default_url_.spec(), &block);
1213 MaybeAddVersionHeader(&block);
1214 AppendToHeaderBlock(extra_headers, extra_header_count, &block);
1215 return ConstructSpdySyn(1, block, LOWEST, false, false);
1218 SpdyFrame* SpdyTestUtil::ConstructSpdyPostSynReply(
1219 const char* const extra_headers[],
1220 int extra_header_count) {
1221 // TODO(jgraettinger): Remove this method.
1222 return ConstructSpdyGetSynReply(NULL, 0, 1);
1225 SpdyFrame* SpdyTestUtil::ConstructSpdyBodyFrame(int stream_id, bool fin) {
1226 SpdyFramer framer(spdy_version_);
1227 SpdyDataIR data_ir(stream_id,
1228 base::StringPiece(kUploadData, kUploadDataSize));
1229 data_ir.set_fin(fin);
1230 return framer.SerializeData(data_ir);
1233 SpdyFrame* SpdyTestUtil::ConstructSpdyBodyFrame(int stream_id,
1234 const char* data,
1235 uint32 len,
1236 bool fin) {
1237 SpdyFramer framer(spdy_version_);
1238 SpdyDataIR data_ir(stream_id, base::StringPiece(data, len));
1239 data_ir.set_fin(fin);
1240 return framer.SerializeData(data_ir);
1243 SpdyFrame* SpdyTestUtil::ConstructSpdyBodyFrame(int stream_id,
1244 const char* data,
1245 uint32 len,
1246 bool fin,
1247 int padding_length) {
1248 SpdyFramer framer(spdy_version_);
1249 SpdyDataIR data_ir(stream_id, base::StringPiece(data, len));
1250 data_ir.set_fin(fin);
1251 data_ir.set_padding_len(padding_length);
1252 return framer.SerializeData(data_ir);
1255 SpdyFrame* SpdyTestUtil::ConstructWrappedSpdyFrame(
1256 const scoped_ptr<SpdyFrame>& frame,
1257 int stream_id) {
1258 return ConstructSpdyBodyFrame(stream_id, frame->data(),
1259 frame->size(), false);
1262 const SpdyHeaderInfo SpdyTestUtil::MakeSpdyHeader(SpdyFrameType type) {
1263 const SpdyHeaderInfo kHeader = {
1264 type,
1265 1, // Stream ID
1266 0, // Associated stream ID
1267 ConvertRequestPriorityToSpdyPriority(LOWEST, spdy_version_),
1268 kSpdyCredentialSlotUnused,
1269 CONTROL_FLAG_FIN, // Control Flags
1270 false, // Compressed
1271 RST_STREAM_INVALID,
1272 NULL, // Data
1273 0, // Length
1274 DATA_FLAG_NONE
1276 return kHeader;
1279 scoped_ptr<SpdyFramer> SpdyTestUtil::CreateFramer(bool compressed) const {
1280 scoped_ptr<SpdyFramer> framer(new SpdyFramer(spdy_version_));
1281 framer->set_enable_compression(compressed);
1282 return framer.Pass();
1285 const char* SpdyTestUtil::GetMethodKey() const {
1286 return ":method";
1289 const char* SpdyTestUtil::GetStatusKey() const {
1290 return ":status";
1293 const char* SpdyTestUtil::GetHostKey() const {
1294 if (protocol_ < kProtoHTTP2)
1295 return ":host";
1296 else
1297 return ":authority";
1300 const char* SpdyTestUtil::GetSchemeKey() const {
1301 return ":scheme";
1304 const char* SpdyTestUtil::GetVersionKey() const {
1305 return ":version";
1308 const char* SpdyTestUtil::GetPathKey() const {
1309 return ":path";
1312 scoped_ptr<SpdyHeaderBlock> SpdyTestUtil::ConstructHeaderBlock(
1313 base::StringPiece method,
1314 base::StringPiece url,
1315 int64* content_length) const {
1316 std::string scheme, host, path;
1317 ParseUrl(url.data(), &scheme, &host, &path);
1318 scoped_ptr<SpdyHeaderBlock> headers(new SpdyHeaderBlock());
1319 (*headers)[GetMethodKey()] = method.as_string();
1320 (*headers)[GetPathKey()] = path.c_str();
1321 (*headers)[GetHostKey()] = host.c_str();
1322 (*headers)[GetSchemeKey()] = scheme.c_str();
1323 if (include_version_header()) {
1324 (*headers)[GetVersionKey()] = "HTTP/1.1";
1326 if (content_length) {
1327 std::string length_str = base::Int64ToString(*content_length);
1328 (*headers)["content-length"] = length_str;
1330 return headers.Pass();
1333 void SpdyTestUtil::MaybeAddVersionHeader(
1334 SpdyFrameWithHeaderBlockIR* frame_ir) const {
1335 if (include_version_header()) {
1336 frame_ir->SetHeader(GetVersionKey(), "HTTP/1.1");
1340 void SpdyTestUtil::MaybeAddVersionHeader(SpdyHeaderBlock* block) const {
1341 if (include_version_header()) {
1342 (*block)[GetVersionKey()] = "HTTP/1.1";
1346 void SpdyTestUtil::SetPriority(RequestPriority priority,
1347 SpdySynStreamIR* ir) const {
1348 ir->set_priority(ConvertRequestPriorityToSpdyPriority(
1349 priority, spdy_version()));
1352 } // namespace net