Explicitly add python-numpy dependency to install-build-deps.
[chromium-blink-merge.git] / net / spdy / spdy_test_util_common.cc
blob9543e64260b56c1363934a0d4d806834594c638b
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(kProtoSPDY4_14);
59 next_protos.push_back(kProtoSPDY4_15);
60 next_protos.push_back(kProtoQUIC1SPDY3);
61 return next_protos;
64 // Chop a frame into an array of MockWrites.
65 // |data| is the frame to chop.
66 // |length| is the length of the frame to chop.
67 // |num_chunks| is the number of chunks to create.
68 MockWrite* ChopWriteFrame(const char* data, int length, int num_chunks) {
69 MockWrite* chunks = new MockWrite[num_chunks];
70 int chunk_size = length / num_chunks;
71 for (int index = 0; index < num_chunks; index++) {
72 const char* ptr = data + (index * chunk_size);
73 if (index == num_chunks - 1)
74 chunk_size += length % chunk_size; // The last chunk takes the remainder.
75 chunks[index] = MockWrite(ASYNC, ptr, chunk_size);
77 return chunks;
80 // Chop a SpdyFrame into an array of MockWrites.
81 // |frame| is the frame to chop.
82 // |num_chunks| is the number of chunks to create.
83 MockWrite* ChopWriteFrame(const SpdyFrame& frame, int num_chunks) {
84 return ChopWriteFrame(frame.data(), frame.size(), num_chunks);
87 // Chop a frame into an array of MockReads.
88 // |data| is the frame to chop.
89 // |length| is the length of the frame to chop.
90 // |num_chunks| is the number of chunks to create.
91 MockRead* ChopReadFrame(const char* data, int length, int num_chunks) {
92 MockRead* chunks = new MockRead[num_chunks];
93 int chunk_size = length / num_chunks;
94 for (int index = 0; index < num_chunks; index++) {
95 const char* ptr = data + (index * chunk_size);
96 if (index == num_chunks - 1)
97 chunk_size += length % chunk_size; // The last chunk takes the remainder.
98 chunks[index] = MockRead(ASYNC, ptr, chunk_size);
100 return chunks;
103 // Chop a SpdyFrame into an array of MockReads.
104 // |frame| is the frame to chop.
105 // |num_chunks| is the number of chunks to create.
106 MockRead* ChopReadFrame(const SpdyFrame& frame, int num_chunks) {
107 return ChopReadFrame(frame.data(), frame.size(), num_chunks);
110 // Adds headers and values to a map.
111 // |extra_headers| is an array of { name, value } pairs, arranged as strings
112 // where the even entries are the header names, and the odd entries are the
113 // header values.
114 // |headers| gets filled in from |extra_headers|.
115 void AppendToHeaderBlock(const char* const extra_headers[],
116 int extra_header_count,
117 SpdyHeaderBlock* headers) {
118 std::string this_header;
119 std::string this_value;
121 if (!extra_header_count)
122 return;
124 // Sanity check: Non-NULL header list.
125 DCHECK(NULL != extra_headers) << "NULL header value pair list";
126 // Sanity check: Non-NULL header map.
127 DCHECK(NULL != headers) << "NULL header map";
128 // Copy in the headers.
129 for (int i = 0; i < extra_header_count; i++) {
130 // Sanity check: Non-empty header.
131 DCHECK_NE('\0', *extra_headers[i * 2]) << "Empty header value pair";
132 this_header = extra_headers[i * 2];
133 std::string::size_type header_len = this_header.length();
134 if (!header_len)
135 continue;
136 this_value = extra_headers[1 + (i * 2)];
137 std::string new_value;
138 if (headers->find(this_header) != headers->end()) {
139 // More than one entry in the header.
140 // Don't add the header again, just the append to the value,
141 // separated by a NULL character.
143 // Adjust the value.
144 new_value = (*headers)[this_header];
145 // Put in a NULL separator.
146 new_value.append(1, '\0');
147 // Append the new value.
148 new_value += this_value;
149 } else {
150 // Not a duplicate, just write the value.
151 new_value = this_value;
153 (*headers)[this_header] = new_value;
157 // Create a MockWrite from the given SpdyFrame.
158 MockWrite CreateMockWrite(const SpdyFrame& req) {
159 return MockWrite(ASYNC, req.data(), req.size());
162 // Create a MockWrite from the given SpdyFrame and sequence number.
163 MockWrite CreateMockWrite(const SpdyFrame& req, int seq) {
164 return CreateMockWrite(req, seq, ASYNC);
167 // Create a MockWrite from the given SpdyFrame and sequence number.
168 MockWrite CreateMockWrite(const SpdyFrame& req, int seq, IoMode mode) {
169 return MockWrite(mode, req.data(), req.size(), seq);
172 // Create a MockRead from the given SpdyFrame.
173 MockRead CreateMockRead(const SpdyFrame& resp) {
174 return MockRead(ASYNC, resp.data(), resp.size());
177 // Create a MockRead from the given SpdyFrame and sequence number.
178 MockRead CreateMockRead(const SpdyFrame& resp, int seq) {
179 return CreateMockRead(resp, seq, ASYNC);
182 // Create a MockRead from the given SpdyFrame and sequence number.
183 MockRead CreateMockRead(const SpdyFrame& resp, int seq, IoMode mode) {
184 return MockRead(mode, resp.data(), resp.size(), seq);
187 // Combines the given SpdyFrames into the given char array and returns
188 // the total length.
189 int CombineFrames(const SpdyFrame** frames, int num_frames,
190 char* buff, int buff_len) {
191 int total_len = 0;
192 for (int i = 0; i < num_frames; ++i) {
193 total_len += frames[i]->size();
195 DCHECK_LE(total_len, buff_len);
196 char* ptr = buff;
197 for (int i = 0; i < num_frames; ++i) {
198 int len = frames[i]->size();
199 memcpy(ptr, frames[i]->data(), len);
200 ptr += len;
202 return total_len;
205 namespace {
207 class PriorityGetter : public BufferedSpdyFramerVisitorInterface {
208 public:
209 PriorityGetter() : priority_(0) {}
210 ~PriorityGetter() override {}
212 SpdyPriority priority() const {
213 return priority_;
216 void OnError(SpdyFramer::SpdyError error_code) override {}
217 void OnStreamError(SpdyStreamId stream_id,
218 const std::string& description) override {}
219 void OnSynStream(SpdyStreamId stream_id,
220 SpdyStreamId associated_stream_id,
221 SpdyPriority priority,
222 bool fin,
223 bool unidirectional,
224 const SpdyHeaderBlock& headers) override {
225 priority_ = priority;
227 void OnSynReply(SpdyStreamId stream_id,
228 bool fin,
229 const SpdyHeaderBlock& headers) override {}
230 void OnHeaders(SpdyStreamId stream_id,
231 bool has_priority,
232 SpdyPriority priority,
233 bool fin,
234 const SpdyHeaderBlock& headers) override {
235 if (has_priority) {
236 priority_ = priority;
239 void OnDataFrameHeader(SpdyStreamId stream_id,
240 size_t length,
241 bool fin) override {}
242 void OnStreamFrameData(SpdyStreamId stream_id,
243 const char* data,
244 size_t len,
245 bool fin) override {}
246 void OnSettings(bool clear_persisted) override {}
247 void OnSetting(SpdySettingsIds id, uint8 flags, uint32 value) override {}
248 void OnPing(SpdyPingId unique_id, bool is_ack) override {}
249 void OnRstStream(SpdyStreamId stream_id,
250 SpdyRstStreamStatus status) override {}
251 void OnGoAway(SpdyStreamId last_accepted_stream_id,
252 SpdyGoAwayStatus status) override {}
253 void OnWindowUpdate(SpdyStreamId stream_id,
254 uint32 delta_window_size) override {}
255 void OnPushPromise(SpdyStreamId stream_id,
256 SpdyStreamId promised_stream_id,
257 const SpdyHeaderBlock& headers) override {}
258 bool OnUnknownFrame(SpdyStreamId stream_id, int frame_type) override {
259 return false;
262 private:
263 SpdyPriority priority_;
266 } // namespace
268 bool GetSpdyPriority(SpdyMajorVersion version,
269 const SpdyFrame& frame,
270 SpdyPriority* priority) {
271 BufferedSpdyFramer framer(version, false);
272 PriorityGetter priority_getter;
273 framer.set_visitor(&priority_getter);
274 size_t frame_size = frame.size();
275 if (framer.ProcessInput(frame.data(), frame_size) != frame_size) {
276 return false;
278 *priority = priority_getter.priority();
279 return true;
282 base::WeakPtr<SpdyStream> CreateStreamSynchronously(
283 SpdyStreamType type,
284 const base::WeakPtr<SpdySession>& session,
285 const GURL& url,
286 RequestPriority priority,
287 const BoundNetLog& net_log) {
288 SpdyStreamRequest stream_request;
289 int rv = stream_request.StartRequest(type, session, url, priority, net_log,
290 CompletionCallback());
291 return
292 (rv == OK) ? stream_request.ReleaseStream() : base::WeakPtr<SpdyStream>();
295 StreamReleaserCallback::StreamReleaserCallback() {}
297 StreamReleaserCallback::~StreamReleaserCallback() {}
299 CompletionCallback StreamReleaserCallback::MakeCallback(
300 SpdyStreamRequest* request) {
301 return base::Bind(&StreamReleaserCallback::OnComplete,
302 base::Unretained(this),
303 request);
306 void StreamReleaserCallback::OnComplete(
307 SpdyStreamRequest* request, int result) {
308 if (result == OK)
309 request->ReleaseStream()->Cancel();
310 SetResult(result);
313 MockECSignatureCreator::MockECSignatureCreator(crypto::ECPrivateKey* key)
314 : key_(key) {
317 bool MockECSignatureCreator::Sign(const uint8* data,
318 int data_len,
319 std::vector<uint8>* signature) {
320 std::vector<uint8> private_key_value;
321 key_->ExportValue(&private_key_value);
322 std::string head = "fakesignature";
323 std::string tail = "/fakesignature";
325 signature->clear();
326 signature->insert(signature->end(), head.begin(), head.end());
327 signature->insert(signature->end(), private_key_value.begin(),
328 private_key_value.end());
329 signature->insert(signature->end(), '-');
330 signature->insert(signature->end(), data, data + data_len);
331 signature->insert(signature->end(), tail.begin(), tail.end());
332 return true;
335 bool MockECSignatureCreator::DecodeSignature(
336 const std::vector<uint8>& signature,
337 std::vector<uint8>* out_raw_sig) {
338 *out_raw_sig = signature;
339 return true;
342 MockECSignatureCreatorFactory::MockECSignatureCreatorFactory() {
343 crypto::ECSignatureCreator::SetFactoryForTesting(this);
346 MockECSignatureCreatorFactory::~MockECSignatureCreatorFactory() {
347 crypto::ECSignatureCreator::SetFactoryForTesting(NULL);
350 crypto::ECSignatureCreator* MockECSignatureCreatorFactory::Create(
351 crypto::ECPrivateKey* key) {
352 return new MockECSignatureCreator(key);
355 SpdySessionDependencies::SpdySessionDependencies(NextProto protocol)
356 : host_resolver(new MockCachingHostResolver),
357 cert_verifier(new MockCertVerifier),
358 transport_security_state(new TransportSecurityState),
359 proxy_service(ProxyService::CreateDirect()),
360 ssl_config_service(new SSLConfigServiceDefaults),
361 socket_factory(new MockClientSocketFactory),
362 deterministic_socket_factory(new DeterministicMockClientSocketFactory),
363 http_auth_handler_factory(
364 HttpAuthHandlerFactory::CreateDefault(host_resolver.get())),
365 enable_ip_pooling(true),
366 enable_compression(false),
367 enable_ping(false),
368 enable_user_alternate_protocol_ports(false),
369 protocol(protocol),
370 stream_initial_recv_window_size(kSpdyStreamInitialWindowSize),
371 time_func(&base::TimeTicks::Now),
372 force_spdy_over_ssl(false),
373 force_spdy_always(false),
374 use_alternate_protocols(false),
375 net_log(NULL) {
376 DCHECK(next_proto_is_spdy(protocol)) << "Invalid protocol: " << protocol;
378 // Note: The CancelledTransaction test does cleanup by running all
379 // tasks in the message loop (RunAllPending). Unfortunately, that
380 // doesn't clean up tasks on the host resolver thread; and
381 // TCPConnectJob is currently not cancellable. Using synchronous
382 // lookups allows the test to shutdown cleanly. Until we have
383 // cancellable TCPConnectJobs, use synchronous lookups.
384 host_resolver->set_synchronous_mode(true);
387 SpdySessionDependencies::SpdySessionDependencies(
388 NextProto protocol, ProxyService* proxy_service)
389 : host_resolver(new MockHostResolver),
390 cert_verifier(new MockCertVerifier),
391 transport_security_state(new TransportSecurityState),
392 proxy_service(proxy_service),
393 ssl_config_service(new SSLConfigServiceDefaults),
394 socket_factory(new MockClientSocketFactory),
395 deterministic_socket_factory(new DeterministicMockClientSocketFactory),
396 http_auth_handler_factory(
397 HttpAuthHandlerFactory::CreateDefault(host_resolver.get())),
398 enable_ip_pooling(true),
399 enable_compression(false),
400 enable_ping(false),
401 enable_user_alternate_protocol_ports(false),
402 protocol(protocol),
403 stream_initial_recv_window_size(kSpdyStreamInitialWindowSize),
404 time_func(&base::TimeTicks::Now),
405 force_spdy_over_ssl(false),
406 force_spdy_always(false),
407 use_alternate_protocols(false),
408 net_log(NULL) {
409 DCHECK(next_proto_is_spdy(protocol)) << "Invalid protocol: " << protocol;
412 SpdySessionDependencies::~SpdySessionDependencies() {}
414 // static
415 HttpNetworkSession* SpdySessionDependencies::SpdyCreateSession(
416 SpdySessionDependencies* session_deps) {
417 net::HttpNetworkSession::Params params = CreateSessionParams(session_deps);
418 params.client_socket_factory = session_deps->socket_factory.get();
419 HttpNetworkSession* http_session = new HttpNetworkSession(params);
420 SpdySessionPoolPeer pool_peer(http_session->spdy_session_pool());
421 pool_peer.SetEnableSendingInitialData(false);
422 return http_session;
425 // static
426 HttpNetworkSession* SpdySessionDependencies::SpdyCreateSessionDeterministic(
427 SpdySessionDependencies* session_deps) {
428 net::HttpNetworkSession::Params params = CreateSessionParams(session_deps);
429 params.client_socket_factory =
430 session_deps->deterministic_socket_factory.get();
431 HttpNetworkSession* http_session = new HttpNetworkSession(params);
432 SpdySessionPoolPeer pool_peer(http_session->spdy_session_pool());
433 pool_peer.SetEnableSendingInitialData(false);
434 return http_session;
437 // static
438 net::HttpNetworkSession::Params SpdySessionDependencies::CreateSessionParams(
439 SpdySessionDependencies* session_deps) {
440 DCHECK(next_proto_is_spdy(session_deps->protocol)) <<
441 "Invalid protocol: " << session_deps->protocol;
443 net::HttpNetworkSession::Params params;
444 params.host_resolver = session_deps->host_resolver.get();
445 params.cert_verifier = session_deps->cert_verifier.get();
446 params.transport_security_state =
447 session_deps->transport_security_state.get();
448 params.proxy_service = session_deps->proxy_service.get();
449 params.ssl_config_service = session_deps->ssl_config_service.get();
450 params.http_auth_handler_factory =
451 session_deps->http_auth_handler_factory.get();
452 params.http_server_properties =
453 session_deps->http_server_properties.GetWeakPtr();
454 params.enable_spdy_compression = session_deps->enable_compression;
455 params.enable_spdy_ping_based_connection_checking = session_deps->enable_ping;
456 params.enable_user_alternate_protocol_ports =
457 session_deps->enable_user_alternate_protocol_ports;
458 params.spdy_default_protocol = session_deps->protocol;
459 params.spdy_stream_initial_recv_window_size =
460 session_deps->stream_initial_recv_window_size;
461 params.time_func = session_deps->time_func;
462 params.next_protos = session_deps->next_protos;
463 params.trusted_spdy_proxy = session_deps->trusted_spdy_proxy;
464 params.force_spdy_over_ssl = session_deps->force_spdy_over_ssl;
465 params.force_spdy_always = session_deps->force_spdy_always;
466 params.use_alternate_protocols = session_deps->use_alternate_protocols;
467 params.net_log = session_deps->net_log;
468 return params;
471 SpdyURLRequestContext::SpdyURLRequestContext(NextProto protocol,
472 bool force_spdy_over_ssl,
473 bool force_spdy_always)
474 : storage_(this) {
475 DCHECK(next_proto_is_spdy(protocol)) << "Invalid protocol: " << protocol;
477 storage_.set_host_resolver(scoped_ptr<HostResolver>(new MockHostResolver));
478 storage_.set_cert_verifier(new MockCertVerifier);
479 storage_.set_transport_security_state(new TransportSecurityState);
480 storage_.set_proxy_service(ProxyService::CreateDirect());
481 storage_.set_ssl_config_service(new SSLConfigServiceDefaults);
482 storage_.set_http_auth_handler_factory(HttpAuthHandlerFactory::CreateDefault(
483 host_resolver()));
484 storage_.set_http_server_properties(
485 scoped_ptr<HttpServerProperties>(new HttpServerPropertiesImpl()));
486 storage_.set_job_factory(new URLRequestJobFactoryImpl());
487 net::HttpNetworkSession::Params params;
488 params.client_socket_factory = &socket_factory_;
489 params.host_resolver = host_resolver();
490 params.cert_verifier = cert_verifier();
491 params.transport_security_state = transport_security_state();
492 params.proxy_service = proxy_service();
493 params.ssl_config_service = ssl_config_service();
494 params.http_auth_handler_factory = http_auth_handler_factory();
495 params.network_delegate = network_delegate();
496 params.enable_spdy_compression = false;
497 params.enable_spdy_ping_based_connection_checking = false;
498 params.spdy_default_protocol = protocol;
499 params.force_spdy_over_ssl = force_spdy_over_ssl;
500 params.force_spdy_always = force_spdy_always;
501 params.http_server_properties = http_server_properties();
502 scoped_refptr<HttpNetworkSession> network_session(
503 new HttpNetworkSession(params));
504 SpdySessionPoolPeer pool_peer(network_session->spdy_session_pool());
505 pool_peer.SetEnableSendingInitialData(false);
506 storage_.set_http_transaction_factory(new HttpCache(
507 network_session.get(), HttpCache::DefaultBackend::InMemory(0)));
510 SpdyURLRequestContext::~SpdyURLRequestContext() {
511 AssertNoURLRequests();
514 bool HasSpdySession(SpdySessionPool* pool, const SpdySessionKey& key) {
515 return pool->FindAvailableSession(key, BoundNetLog()) != NULL;
518 namespace {
520 base::WeakPtr<SpdySession> CreateSpdySessionHelper(
521 const scoped_refptr<HttpNetworkSession>& http_session,
522 const SpdySessionKey& key,
523 const BoundNetLog& net_log,
524 Error expected_status,
525 bool is_secure) {
526 EXPECT_FALSE(HasSpdySession(http_session->spdy_session_pool(), key));
528 scoped_refptr<TransportSocketParams> transport_params(
529 new TransportSocketParams(
530 key.host_port_pair(), false, false, OnHostResolutionCallback(),
531 TransportSocketParams::COMBINE_CONNECT_AND_WRITE_DEFAULT));
533 scoped_ptr<ClientSocketHandle> connection(new ClientSocketHandle);
534 TestCompletionCallback callback;
536 int rv = ERR_UNEXPECTED;
537 if (is_secure) {
538 SSLConfig ssl_config;
539 scoped_refptr<SSLSocketParams> ssl_params(
540 new SSLSocketParams(transport_params,
541 NULL,
542 NULL,
543 key.host_port_pair(),
544 ssl_config,
545 key.privacy_mode(),
547 false,
548 false));
549 rv = connection->Init(key.host_port_pair().ToString(),
550 ssl_params,
551 MEDIUM,
552 callback.callback(),
553 http_session->GetSSLSocketPool(
554 HttpNetworkSession::NORMAL_SOCKET_POOL),
555 net_log);
556 } else {
557 rv = connection->Init(key.host_port_pair().ToString(),
558 transport_params,
559 MEDIUM,
560 callback.callback(),
561 http_session->GetTransportSocketPool(
562 HttpNetworkSession::NORMAL_SOCKET_POOL),
563 net_log);
566 if (rv == ERR_IO_PENDING)
567 rv = callback.WaitForResult();
569 EXPECT_EQ(OK, rv);
571 base::WeakPtr<SpdySession> spdy_session =
572 http_session->spdy_session_pool()->CreateAvailableSessionFromSocket(
573 key, connection.Pass(), net_log, OK, is_secure);
574 // Failure is reported asynchronously.
575 EXPECT_TRUE(spdy_session != NULL);
576 EXPECT_TRUE(HasSpdySession(http_session->spdy_session_pool(), key));
577 return spdy_session;
580 } // namespace
582 base::WeakPtr<SpdySession> CreateInsecureSpdySession(
583 const scoped_refptr<HttpNetworkSession>& http_session,
584 const SpdySessionKey& key,
585 const BoundNetLog& net_log) {
586 return CreateSpdySessionHelper(http_session, key, net_log,
587 OK, false /* is_secure */);
590 base::WeakPtr<SpdySession> TryCreateInsecureSpdySessionExpectingFailure(
591 const scoped_refptr<HttpNetworkSession>& http_session,
592 const SpdySessionKey& key,
593 Error expected_error,
594 const BoundNetLog& net_log) {
595 DCHECK_LT(expected_error, ERR_IO_PENDING);
596 return CreateSpdySessionHelper(http_session, key, net_log,
597 expected_error, false /* is_secure */);
600 base::WeakPtr<SpdySession> CreateSecureSpdySession(
601 const scoped_refptr<HttpNetworkSession>& http_session,
602 const SpdySessionKey& key,
603 const BoundNetLog& net_log) {
604 return CreateSpdySessionHelper(http_session, key, net_log,
605 OK, true /* is_secure */);
608 namespace {
610 // A ClientSocket used for CreateFakeSpdySession() below.
611 class FakeSpdySessionClientSocket : public MockClientSocket {
612 public:
613 FakeSpdySessionClientSocket(int read_result)
614 : MockClientSocket(BoundNetLog()),
615 read_result_(read_result) {}
617 ~FakeSpdySessionClientSocket() override {}
619 int Read(IOBuffer* buf,
620 int buf_len,
621 const CompletionCallback& callback) override {
622 return read_result_;
625 int Write(IOBuffer* buf,
626 int buf_len,
627 const CompletionCallback& callback) override {
628 return ERR_IO_PENDING;
631 // Return kProtoUnknown to use the pool's default protocol.
632 NextProto GetNegotiatedProtocol() const override { return kProtoUnknown; }
634 // The functions below are not expected to be called.
636 int Connect(const CompletionCallback& callback) override {
637 ADD_FAILURE();
638 return ERR_UNEXPECTED;
641 bool WasEverUsed() const override {
642 ADD_FAILURE();
643 return false;
646 bool UsingTCPFastOpen() const override {
647 ADD_FAILURE();
648 return false;
651 bool WasNpnNegotiated() const override {
652 ADD_FAILURE();
653 return false;
656 bool GetSSLInfo(SSLInfo* ssl_info) override {
657 ADD_FAILURE();
658 return false;
661 private:
662 int read_result_;
665 base::WeakPtr<SpdySession> CreateFakeSpdySessionHelper(
666 SpdySessionPool* pool,
667 const SpdySessionKey& key,
668 Error expected_status) {
669 EXPECT_NE(expected_status, ERR_IO_PENDING);
670 EXPECT_FALSE(HasSpdySession(pool, key));
671 scoped_ptr<ClientSocketHandle> handle(new ClientSocketHandle());
672 handle->SetSocket(scoped_ptr<StreamSocket>(new FakeSpdySessionClientSocket(
673 expected_status == OK ? ERR_IO_PENDING : expected_status)));
674 base::WeakPtr<SpdySession> spdy_session =
675 pool->CreateAvailableSessionFromSocket(
676 key, handle.Pass(), BoundNetLog(), OK, true /* is_secure */);
677 // Failure is reported asynchronously.
678 EXPECT_TRUE(spdy_session != NULL);
679 EXPECT_TRUE(HasSpdySession(pool, key));
680 return spdy_session;
683 } // namespace
685 base::WeakPtr<SpdySession> CreateFakeSpdySession(SpdySessionPool* pool,
686 const SpdySessionKey& key) {
687 return CreateFakeSpdySessionHelper(pool, key, OK);
690 base::WeakPtr<SpdySession> TryCreateFakeSpdySessionExpectingFailure(
691 SpdySessionPool* pool,
692 const SpdySessionKey& key,
693 Error expected_error) {
694 DCHECK_LT(expected_error, ERR_IO_PENDING);
695 return CreateFakeSpdySessionHelper(pool, key, expected_error);
698 SpdySessionPoolPeer::SpdySessionPoolPeer(SpdySessionPool* pool) : pool_(pool) {
701 void SpdySessionPoolPeer::RemoveAliases(const SpdySessionKey& key) {
702 pool_->RemoveAliases(key);
705 void SpdySessionPoolPeer::DisableDomainAuthenticationVerification() {
706 pool_->verify_domain_authentication_ = false;
709 void SpdySessionPoolPeer::SetEnableSendingInitialData(bool enabled) {
710 pool_->enable_sending_initial_data_ = enabled;
713 SpdyTestUtil::SpdyTestUtil(NextProto protocol)
714 : protocol_(protocol),
715 spdy_version_(NextProtoToSpdyMajorVersion(protocol)) {
716 DCHECK(next_proto_is_spdy(protocol)) << "Invalid protocol: " << protocol;
719 void SpdyTestUtil::AddUrlToHeaderBlock(base::StringPiece url,
720 SpdyHeaderBlock* headers) const {
721 std::string scheme, host, path;
722 ParseUrl(url, &scheme, &host, &path);
723 (*headers)[GetSchemeKey()] = scheme;
724 (*headers)[GetHostKey()] = host;
725 (*headers)[GetPathKey()] = path;
728 scoped_ptr<SpdyHeaderBlock> SpdyTestUtil::ConstructGetHeaderBlock(
729 base::StringPiece url) const {
730 return ConstructHeaderBlock("GET", url, NULL);
733 scoped_ptr<SpdyHeaderBlock> SpdyTestUtil::ConstructGetHeaderBlockForProxy(
734 base::StringPiece url) const {
735 scoped_ptr<SpdyHeaderBlock> headers(ConstructGetHeaderBlock(url));
736 return headers.Pass();
739 scoped_ptr<SpdyHeaderBlock> SpdyTestUtil::ConstructHeadHeaderBlock(
740 base::StringPiece url,
741 int64 content_length) const {
742 return ConstructHeaderBlock("HEAD", url, &content_length);
745 scoped_ptr<SpdyHeaderBlock> SpdyTestUtil::ConstructPostHeaderBlock(
746 base::StringPiece url,
747 int64 content_length) const {
748 return ConstructHeaderBlock("POST", url, &content_length);
751 scoped_ptr<SpdyHeaderBlock> SpdyTestUtil::ConstructPutHeaderBlock(
752 base::StringPiece url,
753 int64 content_length) const {
754 return ConstructHeaderBlock("PUT", url, &content_length);
757 SpdyFrame* SpdyTestUtil::ConstructSpdyFrame(
758 const SpdyHeaderInfo& header_info,
759 scoped_ptr<SpdyHeaderBlock> headers) const {
760 BufferedSpdyFramer framer(spdy_version_, header_info.compressed);
761 SpdyFrame* frame = NULL;
762 switch (header_info.kind) {
763 case DATA:
764 frame = framer.CreateDataFrame(header_info.id, header_info.data,
765 header_info.data_length,
766 header_info.data_flags);
767 break;
768 case SYN_STREAM:
770 frame = framer.CreateSynStream(header_info.id, header_info.assoc_id,
771 header_info.priority,
772 header_info.control_flags,
773 headers.get());
775 break;
776 case SYN_REPLY:
777 frame = framer.CreateSynReply(header_info.id, header_info.control_flags,
778 headers.get());
779 break;
780 case RST_STREAM:
781 frame = framer.CreateRstStream(header_info.id, header_info.status);
782 break;
783 case HEADERS:
784 frame = framer.CreateHeaders(header_info.id, header_info.control_flags,
785 header_info.priority,
786 headers.get());
787 break;
788 default:
789 ADD_FAILURE();
790 break;
792 return frame;
795 SpdyFrame* SpdyTestUtil::ConstructSpdyFrame(const SpdyHeaderInfo& header_info,
796 const char* const extra_headers[],
797 int extra_header_count,
798 const char* const tail_headers[],
799 int tail_header_count) const {
800 scoped_ptr<SpdyHeaderBlock> headers(new SpdyHeaderBlock());
801 AppendToHeaderBlock(extra_headers, extra_header_count, headers.get());
802 if (tail_headers && tail_header_count)
803 AppendToHeaderBlock(tail_headers, tail_header_count, headers.get());
804 return ConstructSpdyFrame(header_info, headers.Pass());
807 SpdyFrame* SpdyTestUtil::ConstructSpdyControlFrame(
808 scoped_ptr<SpdyHeaderBlock> headers,
809 bool compressed,
810 SpdyStreamId stream_id,
811 RequestPriority request_priority,
812 SpdyFrameType type,
813 SpdyControlFlags flags,
814 SpdyStreamId associated_stream_id) const {
815 EXPECT_GE(type, DATA);
816 EXPECT_LE(type, PRIORITY);
817 const SpdyHeaderInfo header_info = {
818 type,
819 stream_id,
820 associated_stream_id,
821 ConvertRequestPriorityToSpdyPriority(request_priority, spdy_version_),
822 0, // credential slot
823 flags,
824 compressed,
825 RST_STREAM_INVALID, // status
826 NULL, // data
827 0, // length
828 DATA_FLAG_NONE
830 return ConstructSpdyFrame(header_info, headers.Pass());
833 SpdyFrame* SpdyTestUtil::ConstructSpdyControlFrame(
834 const char* const extra_headers[],
835 int extra_header_count,
836 bool compressed,
837 SpdyStreamId stream_id,
838 RequestPriority request_priority,
839 SpdyFrameType type,
840 SpdyControlFlags flags,
841 const char* const* tail_headers,
842 int tail_header_size,
843 SpdyStreamId associated_stream_id) const {
844 scoped_ptr<SpdyHeaderBlock> headers(new SpdyHeaderBlock());
845 AppendToHeaderBlock(extra_headers, extra_header_count, headers.get());
846 if (tail_headers && tail_header_size)
847 AppendToHeaderBlock(tail_headers, tail_header_size / 2, headers.get());
848 return ConstructSpdyControlFrame(
849 headers.Pass(), compressed, stream_id,
850 request_priority, type, flags, associated_stream_id);
853 std::string SpdyTestUtil::ConstructSpdyReplyString(
854 const SpdyHeaderBlock& headers) const {
855 std::string reply_string;
856 for (SpdyHeaderBlock::const_iterator it = headers.begin();
857 it != headers.end(); ++it) {
858 std::string key = it->first;
859 // Remove leading colon from "special" headers (for SPDY3 and
860 // above).
861 if (spdy_version() >= SPDY3 && key[0] == ':')
862 key = key.substr(1);
863 std::vector<std::string> values;
864 base::SplitString(it->second, '\0', &values);
865 for (std::vector<std::string>::const_iterator it2 = values.begin();
866 it2 != values.end(); ++it2) {
867 reply_string += key + ": " + *it2 + "\n";
870 return reply_string;
873 // TODO(jgraettinger): Eliminate uses of this method in tests (prefer
874 // SpdySettingsIR).
875 SpdyFrame* SpdyTestUtil::ConstructSpdySettings(
876 const SettingsMap& settings) const {
877 SpdySettingsIR settings_ir;
878 for (SettingsMap::const_iterator it = settings.begin();
879 it != settings.end();
880 ++it) {
881 settings_ir.AddSetting(
882 it->first,
883 (it->second.first & SETTINGS_FLAG_PLEASE_PERSIST) != 0,
884 (it->second.first & SETTINGS_FLAG_PERSISTED) != 0,
885 it->second.second);
887 return CreateFramer(false)->SerializeFrame(settings_ir);
890 SpdyFrame* SpdyTestUtil::ConstructSpdySettingsAck() const {
891 char kEmptyWrite[] = "";
893 if (spdy_version() > SPDY3) {
894 SpdySettingsIR settings_ir;
895 settings_ir.set_is_ack(true);
896 return CreateFramer(false)->SerializeFrame(settings_ir);
898 // No settings ACK write occurs. Create an empty placeholder write.
899 return new SpdyFrame(kEmptyWrite, 0, false);
902 SpdyFrame* SpdyTestUtil::ConstructSpdyPing(uint32 ping_id, bool is_ack) const {
903 SpdyPingIR ping_ir(ping_id);
904 ping_ir.set_is_ack(is_ack);
905 return CreateFramer(false)->SerializeFrame(ping_ir);
908 SpdyFrame* SpdyTestUtil::ConstructSpdyGoAway() const {
909 return ConstructSpdyGoAway(0);
912 SpdyFrame* SpdyTestUtil::ConstructSpdyGoAway(
913 SpdyStreamId last_good_stream_id) const {
914 SpdyGoAwayIR go_ir(last_good_stream_id, GOAWAY_OK, "go away");
915 return CreateFramer(false)->SerializeFrame(go_ir);
918 SpdyFrame* SpdyTestUtil::ConstructSpdyGoAway(SpdyStreamId last_good_stream_id,
919 SpdyGoAwayStatus status,
920 const std::string& desc) const {
921 SpdyGoAwayIR go_ir(last_good_stream_id, status, desc);
922 return CreateFramer(false)->SerializeFrame(go_ir);
925 SpdyFrame* SpdyTestUtil::ConstructSpdyWindowUpdate(
926 const SpdyStreamId stream_id, uint32 delta_window_size) const {
927 SpdyWindowUpdateIR update_ir(stream_id, delta_window_size);
928 return CreateFramer(false)->SerializeFrame(update_ir);
931 // TODO(jgraettinger): Eliminate uses of this method in tests (prefer
932 // SpdyRstStreamIR).
933 SpdyFrame* SpdyTestUtil::ConstructSpdyRstStream(
934 SpdyStreamId stream_id,
935 SpdyRstStreamStatus status) const {
936 SpdyRstStreamIR rst_ir(stream_id, status, "");
937 return CreateFramer(false)->SerializeRstStream(rst_ir);
940 SpdyFrame* SpdyTestUtil::ConstructSpdyGet(
941 const char* const url,
942 bool compressed,
943 SpdyStreamId stream_id,
944 RequestPriority request_priority) const {
945 scoped_ptr<SpdyHeaderBlock> block(ConstructGetHeaderBlock(url));
946 return ConstructSpdySyn(
947 stream_id, *block, request_priority, compressed, true);
950 SpdyFrame* SpdyTestUtil::ConstructSpdyGet(const char* const extra_headers[],
951 int extra_header_count,
952 bool compressed,
953 int stream_id,
954 RequestPriority request_priority,
955 bool direct) const {
956 SpdyHeaderBlock block;
957 block[GetMethodKey()] = "GET";
958 block[GetPathKey()] = "/";
959 block[GetHostKey()] = "www.google.com";
960 block[GetSchemeKey()] = "http";
961 MaybeAddVersionHeader(&block);
962 AppendToHeaderBlock(extra_headers, extra_header_count, &block);
963 return ConstructSpdySyn(stream_id, block, request_priority, compressed, true);
966 SpdyFrame* SpdyTestUtil::ConstructSpdyConnect(
967 const char* const extra_headers[],
968 int extra_header_count,
969 int stream_id,
970 RequestPriority priority) const {
971 SpdyHeaderBlock block;
972 block[GetMethodKey()] = "CONNECT";
973 block[GetPathKey()] = "www.google.com:443";
974 block[GetHostKey()] = "www.google.com";
975 MaybeAddVersionHeader(&block);
976 AppendToHeaderBlock(extra_headers, extra_header_count, &block);
977 return ConstructSpdySyn(stream_id, block, priority, false, false);
980 SpdyFrame* SpdyTestUtil::ConstructSpdyPush(const char* const extra_headers[],
981 int extra_header_count,
982 int stream_id,
983 int associated_stream_id,
984 const char* url) {
985 if (spdy_version() < SPDY4) {
986 SpdySynStreamIR syn_stream(stream_id);
987 syn_stream.set_associated_to_stream_id(associated_stream_id);
988 syn_stream.SetHeader("hello", "bye");
989 syn_stream.SetHeader(GetStatusKey(), "200 OK");
990 syn_stream.SetHeader(GetVersionKey(), "HTTP/1.1");
991 AddUrlToHeaderBlock(url, syn_stream.mutable_name_value_block());
992 AppendToHeaderBlock(extra_headers,
993 extra_header_count,
994 syn_stream.mutable_name_value_block());
995 return CreateFramer(false)->SerializeFrame(syn_stream);
996 } else {
997 SpdyPushPromiseIR push_promise(associated_stream_id, stream_id);
998 AddUrlToHeaderBlock(url, push_promise.mutable_name_value_block());
999 scoped_ptr<SpdyFrame> push_promise_frame(
1000 CreateFramer(false)->SerializeFrame(push_promise));
1002 SpdyHeadersIR headers(stream_id);
1003 headers.SetHeader("hello", "bye");
1004 headers.SetHeader(GetStatusKey(), "200 OK");
1005 AppendToHeaderBlock(
1006 extra_headers, extra_header_count, headers.mutable_name_value_block());
1007 scoped_ptr<SpdyFrame> headers_frame(
1008 CreateFramer(false)->SerializeFrame(headers));
1010 int joint_data_size = push_promise_frame->size() + headers_frame->size();
1011 scoped_ptr<char[]> data(new char[joint_data_size]);
1012 const SpdyFrame* frames[2] = {
1013 push_promise_frame.get(), headers_frame.get(),
1015 int combined_size =
1016 CombineFrames(frames, arraysize(frames), data.get(), joint_data_size);
1017 DCHECK_EQ(combined_size, joint_data_size);
1018 return new SpdyFrame(data.release(), joint_data_size, true);
1022 SpdyFrame* SpdyTestUtil::ConstructSpdyPush(const char* const extra_headers[],
1023 int extra_header_count,
1024 int stream_id,
1025 int associated_stream_id,
1026 const char* url,
1027 const char* status,
1028 const char* location) {
1029 if (spdy_version() < SPDY4) {
1030 SpdySynStreamIR syn_stream(stream_id);
1031 syn_stream.set_associated_to_stream_id(associated_stream_id);
1032 syn_stream.SetHeader("hello", "bye");
1033 syn_stream.SetHeader(GetStatusKey(), status);
1034 syn_stream.SetHeader(GetVersionKey(), "HTTP/1.1");
1035 syn_stream.SetHeader("location", location);
1036 AddUrlToHeaderBlock(url, syn_stream.mutable_name_value_block());
1037 AppendToHeaderBlock(extra_headers,
1038 extra_header_count,
1039 syn_stream.mutable_name_value_block());
1040 return CreateFramer(false)->SerializeFrame(syn_stream);
1041 } else {
1042 SpdyPushPromiseIR push_promise(associated_stream_id, stream_id);
1043 AddUrlToHeaderBlock(url, push_promise.mutable_name_value_block());
1044 scoped_ptr<SpdyFrame> push_promise_frame(
1045 CreateFramer(false)->SerializeFrame(push_promise));
1047 SpdyHeadersIR headers(stream_id);
1048 headers.SetHeader("hello", "bye");
1049 headers.SetHeader(GetStatusKey(), status);
1050 headers.SetHeader("location", location);
1051 AppendToHeaderBlock(
1052 extra_headers, extra_header_count, headers.mutable_name_value_block());
1053 scoped_ptr<SpdyFrame> headers_frame(
1054 CreateFramer(false)->SerializeFrame(headers));
1056 int joint_data_size = push_promise_frame->size() + headers_frame->size();
1057 scoped_ptr<char[]> data(new char[joint_data_size]);
1058 const SpdyFrame* frames[2] = {
1059 push_promise_frame.get(), headers_frame.get(),
1061 int combined_size =
1062 CombineFrames(frames, arraysize(frames), data.get(), joint_data_size);
1063 DCHECK_EQ(combined_size, joint_data_size);
1064 return new SpdyFrame(data.release(), joint_data_size, true);
1068 SpdyFrame* SpdyTestUtil::ConstructInitialSpdyPushFrame(
1069 scoped_ptr<SpdyHeaderBlock> headers,
1070 int stream_id,
1071 int associated_stream_id) {
1072 if (spdy_version() < SPDY4) {
1073 SpdySynStreamIR syn_stream(stream_id);
1074 syn_stream.set_associated_to_stream_id(associated_stream_id);
1075 SetPriority(LOWEST, &syn_stream);
1076 syn_stream.set_name_value_block(*headers);
1077 return CreateFramer(false)->SerializeFrame(syn_stream);
1078 } else {
1079 SpdyPushPromiseIR push_promise(associated_stream_id, stream_id);
1080 push_promise.set_name_value_block(*headers);
1081 return CreateFramer(false)->SerializeFrame(push_promise);
1085 SpdyFrame* SpdyTestUtil::ConstructSpdyPushHeaders(
1086 int stream_id,
1087 const char* const extra_headers[],
1088 int extra_header_count) {
1089 SpdyHeadersIR headers(stream_id);
1090 headers.SetHeader(GetStatusKey(), "200 OK");
1091 MaybeAddVersionHeader(&headers);
1092 AppendToHeaderBlock(extra_headers, extra_header_count,
1093 headers.mutable_name_value_block());
1094 return CreateFramer(false)->SerializeFrame(headers);
1097 SpdyFrame* SpdyTestUtil::ConstructSpdySyn(int stream_id,
1098 const SpdyHeaderBlock& block,
1099 RequestPriority priority,
1100 bool compressed,
1101 bool fin) const {
1102 if (protocol_ < kProtoSPDY4MinimumVersion) {
1103 SpdySynStreamIR syn_stream(stream_id);
1104 syn_stream.set_name_value_block(block);
1105 syn_stream.set_priority(
1106 ConvertRequestPriorityToSpdyPriority(priority, spdy_version()));
1107 syn_stream.set_fin(fin);
1108 return CreateFramer(compressed)->SerializeFrame(syn_stream);
1109 } else {
1110 SpdyHeadersIR headers(stream_id);
1111 headers.set_name_value_block(block);
1112 headers.set_has_priority(true);
1113 headers.set_priority(
1114 ConvertRequestPriorityToSpdyPriority(priority, spdy_version()));
1115 headers.set_fin(fin);
1116 return CreateFramer(compressed)->SerializeFrame(headers);
1120 SpdyFrame* SpdyTestUtil::ConstructSpdyReply(int stream_id,
1121 const SpdyHeaderBlock& headers) {
1122 if (protocol_ < kProtoSPDY4MinimumVersion) {
1123 SpdySynReplyIR syn_reply(stream_id);
1124 syn_reply.set_name_value_block(headers);
1125 return CreateFramer(false)->SerializeFrame(syn_reply);
1126 } else {
1127 SpdyHeadersIR reply(stream_id);
1128 reply.set_name_value_block(headers);
1129 return CreateFramer(false)->SerializeFrame(reply);
1133 SpdyFrame* SpdyTestUtil::ConstructSpdySynReplyError(
1134 const char* const status,
1135 const char* const* const extra_headers,
1136 int extra_header_count,
1137 int stream_id) {
1138 SpdyHeaderBlock block;
1139 block["hello"] = "bye";
1140 block[GetStatusKey()] = status;
1141 MaybeAddVersionHeader(&block);
1142 AppendToHeaderBlock(extra_headers, extra_header_count, &block);
1144 return ConstructSpdyReply(stream_id, block);
1147 SpdyFrame* SpdyTestUtil::ConstructSpdyGetSynReplyRedirect(int stream_id) {
1148 static const char* const kExtraHeaders[] = {
1149 "location", "http://www.foo.com/index.php",
1151 return ConstructSpdySynReplyError("301 Moved Permanently", kExtraHeaders,
1152 arraysize(kExtraHeaders)/2, stream_id);
1155 SpdyFrame* SpdyTestUtil::ConstructSpdySynReplyError(int stream_id) {
1156 return ConstructSpdySynReplyError("500 Internal Server Error", NULL, 0, 1);
1159 SpdyFrame* SpdyTestUtil::ConstructSpdyGetSynReply(
1160 const char* const extra_headers[],
1161 int extra_header_count,
1162 int stream_id) {
1163 SpdyHeaderBlock block;
1164 block["hello"] = "bye";
1165 block[GetStatusKey()] = "200";
1166 MaybeAddVersionHeader(&block);
1167 AppendToHeaderBlock(extra_headers, extra_header_count, &block);
1169 return ConstructSpdyReply(stream_id, block);
1172 SpdyFrame* SpdyTestUtil::ConstructSpdyPost(const char* url,
1173 SpdyStreamId stream_id,
1174 int64 content_length,
1175 RequestPriority priority,
1176 const char* const extra_headers[],
1177 int extra_header_count) {
1178 scoped_ptr<SpdyHeaderBlock> block(
1179 ConstructPostHeaderBlock(url, content_length));
1180 AppendToHeaderBlock(extra_headers, extra_header_count, block.get());
1181 return ConstructSpdySyn(stream_id, *block, priority, false, false);
1184 SpdyFrame* SpdyTestUtil::ConstructChunkedSpdyPost(
1185 const char* const extra_headers[],
1186 int extra_header_count) {
1187 SpdyHeaderBlock block;
1188 block[GetMethodKey()] = "POST";
1189 block[GetPathKey()] = "/";
1190 block[GetHostKey()] = "www.google.com";
1191 block[GetSchemeKey()] = "http";
1192 MaybeAddVersionHeader(&block);
1193 AppendToHeaderBlock(extra_headers, extra_header_count, &block);
1194 return ConstructSpdySyn(1, block, LOWEST, false, false);
1197 SpdyFrame* SpdyTestUtil::ConstructSpdyPostSynReply(
1198 const char* const extra_headers[],
1199 int extra_header_count) {
1200 // TODO(jgraettinger): Remove this method.
1201 return ConstructSpdyGetSynReply(NULL, 0, 1);
1204 SpdyFrame* SpdyTestUtil::ConstructSpdyBodyFrame(int stream_id, bool fin) {
1205 SpdyFramer framer(spdy_version_);
1206 SpdyDataIR data_ir(stream_id,
1207 base::StringPiece(kUploadData, kUploadDataSize));
1208 data_ir.set_fin(fin);
1209 return framer.SerializeData(data_ir);
1212 SpdyFrame* SpdyTestUtil::ConstructSpdyBodyFrame(int stream_id,
1213 const char* data,
1214 uint32 len,
1215 bool fin) {
1216 SpdyFramer framer(spdy_version_);
1217 SpdyDataIR data_ir(stream_id, base::StringPiece(data, len));
1218 data_ir.set_fin(fin);
1219 return framer.SerializeData(data_ir);
1222 SpdyFrame* SpdyTestUtil::ConstructWrappedSpdyFrame(
1223 const scoped_ptr<SpdyFrame>& frame,
1224 int stream_id) {
1225 return ConstructSpdyBodyFrame(stream_id, frame->data(),
1226 frame->size(), false);
1229 const SpdyHeaderInfo SpdyTestUtil::MakeSpdyHeader(SpdyFrameType type) {
1230 const SpdyHeaderInfo kHeader = {
1231 type,
1232 1, // Stream ID
1233 0, // Associated stream ID
1234 ConvertRequestPriorityToSpdyPriority(LOWEST, spdy_version_),
1235 kSpdyCredentialSlotUnused,
1236 CONTROL_FLAG_FIN, // Control Flags
1237 false, // Compressed
1238 RST_STREAM_INVALID,
1239 NULL, // Data
1240 0, // Length
1241 DATA_FLAG_NONE
1243 return kHeader;
1246 scoped_ptr<SpdyFramer> SpdyTestUtil::CreateFramer(bool compressed) const {
1247 scoped_ptr<SpdyFramer> framer(new SpdyFramer(spdy_version_));
1248 framer->set_enable_compression(compressed);
1249 return framer.Pass();
1252 const char* SpdyTestUtil::GetMethodKey() const {
1253 return ":method";
1256 const char* SpdyTestUtil::GetStatusKey() const {
1257 return ":status";
1260 const char* SpdyTestUtil::GetHostKey() const {
1261 if (protocol_ < kProtoSPDY4MinimumVersion)
1262 return ":host";
1263 else
1264 return ":authority";
1267 const char* SpdyTestUtil::GetSchemeKey() const {
1268 return ":scheme";
1271 const char* SpdyTestUtil::GetVersionKey() const {
1272 return ":version";
1275 const char* SpdyTestUtil::GetPathKey() const {
1276 return ":path";
1279 scoped_ptr<SpdyHeaderBlock> SpdyTestUtil::ConstructHeaderBlock(
1280 base::StringPiece method,
1281 base::StringPiece url,
1282 int64* content_length) const {
1283 std::string scheme, host, path;
1284 ParseUrl(url.data(), &scheme, &host, &path);
1285 scoped_ptr<SpdyHeaderBlock> headers(new SpdyHeaderBlock());
1286 (*headers)[GetMethodKey()] = method.as_string();
1287 (*headers)[GetPathKey()] = path.c_str();
1288 (*headers)[GetHostKey()] = host.c_str();
1289 (*headers)[GetSchemeKey()] = scheme.c_str();
1290 if (include_version_header()) {
1291 (*headers)[GetVersionKey()] = "HTTP/1.1";
1293 if (content_length) {
1294 std::string length_str = base::Int64ToString(*content_length);
1295 (*headers)["content-length"] = length_str;
1297 return headers.Pass();
1300 void SpdyTestUtil::MaybeAddVersionHeader(
1301 SpdyFrameWithNameValueBlockIR* frame_ir) const {
1302 if (include_version_header()) {
1303 frame_ir->SetHeader(GetVersionKey(), "HTTP/1.1");
1307 void SpdyTestUtil::MaybeAddVersionHeader(SpdyHeaderBlock* block) const {
1308 if (include_version_header()) {
1309 (*block)[GetVersionKey()] = "HTTP/1.1";
1313 void SpdyTestUtil::SetPriority(RequestPriority priority,
1314 SpdySynStreamIR* ir) const {
1315 ir->set_priority(ConvertRequestPriorityToSpdyPriority(
1316 priority, spdy_version()));
1319 } // namespace net