Fix mouse warp with 2x displays
[chromium-blink-merge.git] / net / spdy / spdy_test_util_common.cc
blob0d3e6b216083a35ac6cb1ff092c2650340b68666
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_14);
59 next_protos.push_back(kProtoHTTP2);
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 SpdyStreamId parent_stream_id,
234 bool exclusive,
235 bool fin,
236 const SpdyHeaderBlock& headers) override {
237 if (has_priority) {
238 priority_ = priority;
241 void OnDataFrameHeader(SpdyStreamId stream_id,
242 size_t length,
243 bool fin) override {}
244 void OnStreamFrameData(SpdyStreamId stream_id,
245 const char* data,
246 size_t len,
247 bool fin) override {}
248 void OnStreamPadding(SpdyStreamId stream_id, size_t len) override {}
249 void OnSettings(bool clear_persisted) override {}
250 void OnSetting(SpdySettingsIds id, uint8 flags, uint32 value) override {}
251 void OnPing(SpdyPingId unique_id, bool is_ack) override {}
252 void OnRstStream(SpdyStreamId stream_id,
253 SpdyRstStreamStatus status) override {}
254 void OnGoAway(SpdyStreamId last_accepted_stream_id,
255 SpdyGoAwayStatus status) override {}
256 void OnWindowUpdate(SpdyStreamId stream_id, int delta_window_size) override {}
257 void OnPushPromise(SpdyStreamId stream_id,
258 SpdyStreamId promised_stream_id,
259 const SpdyHeaderBlock& headers) override {}
260 bool OnUnknownFrame(SpdyStreamId stream_id, int frame_type) override {
261 return false;
264 private:
265 SpdyPriority priority_;
268 } // namespace
270 bool GetSpdyPriority(SpdyMajorVersion version,
271 const SpdyFrame& frame,
272 SpdyPriority* priority) {
273 BufferedSpdyFramer framer(version, false);
274 PriorityGetter priority_getter;
275 framer.set_visitor(&priority_getter);
276 size_t frame_size = frame.size();
277 if (framer.ProcessInput(frame.data(), frame_size) != frame_size) {
278 return false;
280 *priority = priority_getter.priority();
281 return true;
284 base::WeakPtr<SpdyStream> CreateStreamSynchronously(
285 SpdyStreamType type,
286 const base::WeakPtr<SpdySession>& session,
287 const GURL& url,
288 RequestPriority priority,
289 const BoundNetLog& net_log) {
290 SpdyStreamRequest stream_request;
291 int rv = stream_request.StartRequest(type, session, url, priority, net_log,
292 CompletionCallback());
293 return
294 (rv == OK) ? stream_request.ReleaseStream() : base::WeakPtr<SpdyStream>();
297 StreamReleaserCallback::StreamReleaserCallback() {}
299 StreamReleaserCallback::~StreamReleaserCallback() {}
301 CompletionCallback StreamReleaserCallback::MakeCallback(
302 SpdyStreamRequest* request) {
303 return base::Bind(&StreamReleaserCallback::OnComplete,
304 base::Unretained(this),
305 request);
308 void StreamReleaserCallback::OnComplete(
309 SpdyStreamRequest* request, int result) {
310 if (result == OK)
311 request->ReleaseStream()->Cancel();
312 SetResult(result);
315 MockECSignatureCreator::MockECSignatureCreator(crypto::ECPrivateKey* key)
316 : key_(key) {
319 bool MockECSignatureCreator::Sign(const uint8* data,
320 int data_len,
321 std::vector<uint8>* signature) {
322 std::vector<uint8> private_key_value;
323 key_->ExportValue(&private_key_value);
324 std::string head = "fakesignature";
325 std::string tail = "/fakesignature";
327 signature->clear();
328 signature->insert(signature->end(), head.begin(), head.end());
329 signature->insert(signature->end(), private_key_value.begin(),
330 private_key_value.end());
331 signature->insert(signature->end(), '-');
332 signature->insert(signature->end(), data, data + data_len);
333 signature->insert(signature->end(), tail.begin(), tail.end());
334 return true;
337 bool MockECSignatureCreator::DecodeSignature(
338 const std::vector<uint8>& signature,
339 std::vector<uint8>* out_raw_sig) {
340 *out_raw_sig = signature;
341 return true;
344 MockECSignatureCreatorFactory::MockECSignatureCreatorFactory() {
345 crypto::ECSignatureCreator::SetFactoryForTesting(this);
348 MockECSignatureCreatorFactory::~MockECSignatureCreatorFactory() {
349 crypto::ECSignatureCreator::SetFactoryForTesting(NULL);
352 crypto::ECSignatureCreator* MockECSignatureCreatorFactory::Create(
353 crypto::ECPrivateKey* key) {
354 return new MockECSignatureCreator(key);
357 SpdySessionDependencies::SpdySessionDependencies(NextProto protocol)
358 : host_resolver(new MockCachingHostResolver),
359 cert_verifier(new MockCertVerifier),
360 transport_security_state(new TransportSecurityState),
361 proxy_service(ProxyService::CreateDirect()),
362 ssl_config_service(new SSLConfigServiceDefaults),
363 socket_factory(new MockClientSocketFactory),
364 deterministic_socket_factory(new DeterministicMockClientSocketFactory),
365 http_auth_handler_factory(
366 HttpAuthHandlerFactory::CreateDefault(host_resolver.get())),
367 enable_ip_pooling(true),
368 enable_compression(false),
369 enable_ping(false),
370 enable_user_alternate_protocol_ports(false),
371 protocol(protocol),
372 session_max_recv_window_size(
373 SpdySession::GetDefaultInitialWindowSize(protocol)),
374 stream_max_recv_window_size(
375 SpdySession::GetDefaultInitialWindowSize(protocol)),
376 time_func(&base::TimeTicks::Now),
377 use_alternate_protocols(false),
378 net_log(NULL) {
379 DCHECK(next_proto_is_spdy(protocol)) << "Invalid protocol: " << protocol;
381 // Note: The CancelledTransaction test does cleanup by running all
382 // tasks in the message loop (RunAllPending). Unfortunately, that
383 // doesn't clean up tasks on the host resolver thread; and
384 // TCPConnectJob is currently not cancellable. Using synchronous
385 // lookups allows the test to shutdown cleanly. Until we have
386 // cancellable TCPConnectJobs, use synchronous lookups.
387 host_resolver->set_synchronous_mode(true);
390 SpdySessionDependencies::SpdySessionDependencies(NextProto protocol,
391 ProxyService* proxy_service)
392 : host_resolver(new MockHostResolver),
393 cert_verifier(new MockCertVerifier),
394 transport_security_state(new TransportSecurityState),
395 proxy_service(proxy_service),
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_alternate_protocols(false),
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_alternate_protocols = session_deps->use_alternate_protocols;
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(new MockCertVerifier);
481 storage_.set_transport_security_state(new TransportSecurityState);
482 storage_.set_proxy_service(ProxyService::CreateDirect());
483 storage_.set_ssl_config_service(new SSLConfigServiceDefaults);
484 storage_.set_http_auth_handler_factory(HttpAuthHandlerFactory::CreateDefault(
485 host_resolver()));
486 storage_.set_http_server_properties(
487 scoped_ptr<HttpServerProperties>(new HttpServerPropertiesImpl()));
488 storage_.set_job_factory(new URLRequestJobFactoryImpl());
489 HttpNetworkSession::Params params;
490 params.client_socket_factory = &socket_factory_;
491 params.host_resolver = host_resolver();
492 params.cert_verifier = cert_verifier();
493 params.transport_security_state = transport_security_state();
494 params.proxy_service = proxy_service();
495 params.ssl_config_service = ssl_config_service();
496 params.http_auth_handler_factory = http_auth_handler_factory();
497 params.network_delegate = network_delegate();
498 params.enable_spdy_compression = false;
499 params.enable_spdy_ping_based_connection_checking = false;
500 params.spdy_default_protocol = protocol;
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 rv = connection->Init(key.host_port_pair().ToString(),
549 ssl_params,
550 MEDIUM,
551 callback.callback(),
552 http_session->GetSSLSocketPool(
553 HttpNetworkSession::NORMAL_SOCKET_POOL),
554 net_log);
555 } else {
556 rv = connection->Init(key.host_port_pair().ToString(),
557 transport_params,
558 MEDIUM,
559 callback.callback(),
560 http_session->GetTransportSocketPool(
561 HttpNetworkSession::NORMAL_SOCKET_POOL),
562 net_log);
565 if (rv == ERR_IO_PENDING)
566 rv = callback.WaitForResult();
568 EXPECT_EQ(OK, rv);
570 base::WeakPtr<SpdySession> spdy_session =
571 http_session->spdy_session_pool()->CreateAvailableSessionFromSocket(
572 key, connection.Pass(), net_log, OK, is_secure);
573 // Failure is reported asynchronously.
574 EXPECT_TRUE(spdy_session != NULL);
575 EXPECT_TRUE(HasSpdySession(http_session->spdy_session_pool(), key));
576 return spdy_session;
579 } // namespace
581 base::WeakPtr<SpdySession> CreateInsecureSpdySession(
582 const scoped_refptr<HttpNetworkSession>& http_session,
583 const SpdySessionKey& key,
584 const BoundNetLog& net_log) {
585 return CreateSpdySessionHelper(http_session, key, net_log,
586 OK, false /* is_secure */);
589 base::WeakPtr<SpdySession> TryCreateInsecureSpdySessionExpectingFailure(
590 const scoped_refptr<HttpNetworkSession>& http_session,
591 const SpdySessionKey& key,
592 Error expected_error,
593 const BoundNetLog& net_log) {
594 DCHECK_LT(expected_error, ERR_IO_PENDING);
595 return CreateSpdySessionHelper(http_session, key, net_log,
596 expected_error, false /* is_secure */);
599 base::WeakPtr<SpdySession> CreateSecureSpdySession(
600 const scoped_refptr<HttpNetworkSession>& http_session,
601 const SpdySessionKey& key,
602 const BoundNetLog& net_log) {
603 return CreateSpdySessionHelper(http_session, key, net_log,
604 OK, true /* is_secure */);
607 namespace {
609 // A ClientSocket used for CreateFakeSpdySession() below.
610 class FakeSpdySessionClientSocket : public MockClientSocket {
611 public:
612 FakeSpdySessionClientSocket(int read_result)
613 : MockClientSocket(BoundNetLog()),
614 read_result_(read_result) {}
616 ~FakeSpdySessionClientSocket() override {}
618 int Read(IOBuffer* buf,
619 int buf_len,
620 const CompletionCallback& callback) override {
621 return read_result_;
624 int Write(IOBuffer* buf,
625 int buf_len,
626 const CompletionCallback& callback) override {
627 return ERR_IO_PENDING;
630 // Return kProtoUnknown to use the pool's default protocol.
631 NextProto GetNegotiatedProtocol() const override { return kProtoUnknown; }
633 // The functions below are not expected to be called.
635 int Connect(const CompletionCallback& callback) override {
636 ADD_FAILURE();
637 return ERR_UNEXPECTED;
640 bool WasEverUsed() const override {
641 ADD_FAILURE();
642 return false;
645 bool UsingTCPFastOpen() const override {
646 ADD_FAILURE();
647 return false;
650 bool WasNpnNegotiated() const override {
651 ADD_FAILURE();
652 return false;
655 bool GetSSLInfo(SSLInfo* ssl_info) override {
656 ADD_FAILURE();
657 return false;
660 private:
661 int read_result_;
664 base::WeakPtr<SpdySession> CreateFakeSpdySessionHelper(
665 SpdySessionPool* pool,
666 const SpdySessionKey& key,
667 Error expected_status) {
668 EXPECT_NE(expected_status, ERR_IO_PENDING);
669 EXPECT_FALSE(HasSpdySession(pool, key));
670 scoped_ptr<ClientSocketHandle> handle(new ClientSocketHandle());
671 handle->SetSocket(scoped_ptr<StreamSocket>(new FakeSpdySessionClientSocket(
672 expected_status == OK ? ERR_IO_PENDING : expected_status)));
673 base::WeakPtr<SpdySession> spdy_session =
674 pool->CreateAvailableSessionFromSocket(
675 key, handle.Pass(), BoundNetLog(), OK, true /* is_secure */);
676 // Failure is reported asynchronously.
677 EXPECT_TRUE(spdy_session != NULL);
678 EXPECT_TRUE(HasSpdySession(pool, key));
679 return spdy_session;
682 } // namespace
684 base::WeakPtr<SpdySession> CreateFakeSpdySession(SpdySessionPool* pool,
685 const SpdySessionKey& key) {
686 return CreateFakeSpdySessionHelper(pool, key, OK);
689 base::WeakPtr<SpdySession> TryCreateFakeSpdySessionExpectingFailure(
690 SpdySessionPool* pool,
691 const SpdySessionKey& key,
692 Error expected_error) {
693 DCHECK_LT(expected_error, ERR_IO_PENDING);
694 return CreateFakeSpdySessionHelper(pool, key, expected_error);
697 SpdySessionPoolPeer::SpdySessionPoolPeer(SpdySessionPool* pool) : pool_(pool) {
700 void SpdySessionPoolPeer::RemoveAliases(const SpdySessionKey& key) {
701 pool_->RemoveAliases(key);
704 void SpdySessionPoolPeer::DisableDomainAuthenticationVerification() {
705 pool_->verify_domain_authentication_ = false;
708 void SpdySessionPoolPeer::SetEnableSendingInitialData(bool enabled) {
709 pool_->enable_sending_initial_data_ = enabled;
712 void SpdySessionPoolPeer::SetSessionMaxRecvWindowSize(size_t window) {
713 pool_->session_max_recv_window_size_ = window;
716 void SpdySessionPoolPeer::SetStreamInitialRecvWindowSize(size_t window) {
717 pool_->stream_max_recv_window_size_ = window;
720 SpdyTestUtil::SpdyTestUtil(NextProto protocol)
721 : protocol_(protocol),
722 spdy_version_(NextProtoToSpdyMajorVersion(protocol)),
723 default_url_(GURL(kDefaultURL)) {
724 DCHECK(next_proto_is_spdy(protocol)) << "Invalid protocol: " << protocol;
727 void SpdyTestUtil::AddUrlToHeaderBlock(base::StringPiece url,
728 SpdyHeaderBlock* headers) const {
729 std::string scheme, host, path;
730 ParseUrl(url, &scheme, &host, &path);
731 (*headers)[GetSchemeKey()] = scheme;
732 (*headers)[GetHostKey()] = host;
733 (*headers)[GetPathKey()] = path;
736 scoped_ptr<SpdyHeaderBlock> SpdyTestUtil::ConstructGetHeaderBlock(
737 base::StringPiece url) const {
738 return ConstructHeaderBlock("GET", url, NULL);
741 scoped_ptr<SpdyHeaderBlock> SpdyTestUtil::ConstructGetHeaderBlockForProxy(
742 base::StringPiece url) const {
743 scoped_ptr<SpdyHeaderBlock> headers(ConstructGetHeaderBlock(url));
744 return headers.Pass();
747 scoped_ptr<SpdyHeaderBlock> SpdyTestUtil::ConstructHeadHeaderBlock(
748 base::StringPiece url,
749 int64 content_length) const {
750 return ConstructHeaderBlock("HEAD", url, &content_length);
753 scoped_ptr<SpdyHeaderBlock> SpdyTestUtil::ConstructPostHeaderBlock(
754 base::StringPiece url,
755 int64 content_length) const {
756 return ConstructHeaderBlock("POST", url, &content_length);
759 scoped_ptr<SpdyHeaderBlock> SpdyTestUtil::ConstructPutHeaderBlock(
760 base::StringPiece url,
761 int64 content_length) const {
762 return ConstructHeaderBlock("PUT", url, &content_length);
765 SpdyFrame* SpdyTestUtil::ConstructSpdyFrame(
766 const SpdyHeaderInfo& header_info,
767 scoped_ptr<SpdyHeaderBlock> headers) const {
768 BufferedSpdyFramer framer(spdy_version_, header_info.compressed);
769 SpdyFrame* frame = NULL;
770 switch (header_info.kind) {
771 case DATA:
772 frame = framer.CreateDataFrame(header_info.id, header_info.data,
773 header_info.data_length,
774 header_info.data_flags);
775 break;
776 case SYN_STREAM:
778 frame = framer.CreateSynStream(header_info.id, header_info.assoc_id,
779 header_info.priority,
780 header_info.control_flags,
781 headers.get());
783 break;
784 case SYN_REPLY:
785 frame = framer.CreateSynReply(header_info.id, header_info.control_flags,
786 headers.get());
787 break;
788 case RST_STREAM:
789 frame = framer.CreateRstStream(header_info.id, header_info.status);
790 break;
791 case HEADERS:
792 frame = framer.CreateHeaders(header_info.id, header_info.control_flags,
793 header_info.priority,
794 headers.get());
795 break;
796 default:
797 ADD_FAILURE();
798 break;
800 return frame;
803 SpdyFrame* SpdyTestUtil::ConstructSpdyFrame(const SpdyHeaderInfo& header_info,
804 const char* const extra_headers[],
805 int extra_header_count,
806 const char* const tail_headers[],
807 int tail_header_count) const {
808 scoped_ptr<SpdyHeaderBlock> headers(new SpdyHeaderBlock());
809 AppendToHeaderBlock(extra_headers, extra_header_count, headers.get());
810 if (tail_headers && tail_header_count)
811 AppendToHeaderBlock(tail_headers, tail_header_count, headers.get());
812 return ConstructSpdyFrame(header_info, headers.Pass());
815 SpdyFrame* SpdyTestUtil::ConstructSpdyControlFrame(
816 scoped_ptr<SpdyHeaderBlock> headers,
817 bool compressed,
818 SpdyStreamId stream_id,
819 RequestPriority request_priority,
820 SpdyFrameType type,
821 SpdyControlFlags flags,
822 SpdyStreamId associated_stream_id) const {
823 EXPECT_GE(type, DATA);
824 EXPECT_LE(type, PRIORITY);
825 const SpdyHeaderInfo header_info = {
826 type,
827 stream_id,
828 associated_stream_id,
829 ConvertRequestPriorityToSpdyPriority(request_priority, spdy_version_),
830 0, // credential slot
831 flags,
832 compressed,
833 RST_STREAM_INVALID, // status
834 NULL, // data
835 0, // length
836 DATA_FLAG_NONE
838 return ConstructSpdyFrame(header_info, headers.Pass());
841 SpdyFrame* SpdyTestUtil::ConstructSpdyControlFrame(
842 const char* const extra_headers[],
843 int extra_header_count,
844 bool compressed,
845 SpdyStreamId stream_id,
846 RequestPriority request_priority,
847 SpdyFrameType type,
848 SpdyControlFlags flags,
849 const char* const* tail_headers,
850 int tail_header_size,
851 SpdyStreamId associated_stream_id) const {
852 scoped_ptr<SpdyHeaderBlock> headers(new SpdyHeaderBlock());
853 AppendToHeaderBlock(extra_headers, extra_header_count, headers.get());
854 if (tail_headers && tail_header_size)
855 AppendToHeaderBlock(tail_headers, tail_header_size / 2, headers.get());
856 return ConstructSpdyControlFrame(
857 headers.Pass(), compressed, stream_id,
858 request_priority, type, flags, associated_stream_id);
861 std::string SpdyTestUtil::ConstructSpdyReplyString(
862 const SpdyHeaderBlock& headers) const {
863 std::string reply_string;
864 for (SpdyHeaderBlock::const_iterator it = headers.begin();
865 it != headers.end(); ++it) {
866 std::string key = it->first;
867 // Remove leading colon from "special" headers (for SPDY3 and
868 // above).
869 if (spdy_version() >= SPDY3 && key[0] == ':')
870 key = key.substr(1);
871 for (const std::string& value :
872 base::SplitString(it->second, base::StringPiece("\0", 1),
873 base::TRIM_WHITESPACE, base::SPLIT_WANT_ALL)) {
874 reply_string += key + ": " + value + "\n";
877 return reply_string;
880 // TODO(jgraettinger): Eliminate uses of this method in tests (prefer
881 // SpdySettingsIR).
882 SpdyFrame* SpdyTestUtil::ConstructSpdySettings(
883 const SettingsMap& settings) const {
884 SpdySettingsIR settings_ir;
885 for (SettingsMap::const_iterator it = settings.begin();
886 it != settings.end();
887 ++it) {
888 settings_ir.AddSetting(
889 it->first,
890 (it->second.first & SETTINGS_FLAG_PLEASE_PERSIST) != 0,
891 (it->second.first & SETTINGS_FLAG_PERSISTED) != 0,
892 it->second.second);
894 return CreateFramer(false)->SerializeFrame(settings_ir);
897 SpdyFrame* SpdyTestUtil::ConstructSpdySettingsAck() const {
898 char kEmptyWrite[] = "";
900 if (spdy_version() > SPDY3) {
901 SpdySettingsIR settings_ir;
902 settings_ir.set_is_ack(true);
903 return CreateFramer(false)->SerializeFrame(settings_ir);
905 // No settings ACK write occurs. Create an empty placeholder write.
906 return new SpdyFrame(kEmptyWrite, 0, false);
909 SpdyFrame* SpdyTestUtil::ConstructSpdyPing(uint32 ping_id, bool is_ack) const {
910 SpdyPingIR ping_ir(ping_id);
911 ping_ir.set_is_ack(is_ack);
912 return CreateFramer(false)->SerializeFrame(ping_ir);
915 SpdyFrame* SpdyTestUtil::ConstructSpdyGoAway() const {
916 return ConstructSpdyGoAway(0);
919 SpdyFrame* SpdyTestUtil::ConstructSpdyGoAway(
920 SpdyStreamId last_good_stream_id) const {
921 SpdyGoAwayIR go_ir(last_good_stream_id, GOAWAY_OK, "go away");
922 return CreateFramer(false)->SerializeFrame(go_ir);
925 SpdyFrame* SpdyTestUtil::ConstructSpdyGoAway(SpdyStreamId last_good_stream_id,
926 SpdyGoAwayStatus status,
927 const std::string& desc) const {
928 SpdyGoAwayIR go_ir(last_good_stream_id, status, desc);
929 return CreateFramer(false)->SerializeFrame(go_ir);
932 SpdyFrame* SpdyTestUtil::ConstructSpdyWindowUpdate(
933 const SpdyStreamId stream_id, uint32 delta_window_size) const {
934 SpdyWindowUpdateIR update_ir(stream_id, delta_window_size);
935 return CreateFramer(false)->SerializeFrame(update_ir);
938 // TODO(jgraettinger): Eliminate uses of this method in tests (prefer
939 // SpdyRstStreamIR).
940 SpdyFrame* SpdyTestUtil::ConstructSpdyRstStream(
941 SpdyStreamId stream_id,
942 SpdyRstStreamStatus status) const {
943 SpdyRstStreamIR rst_ir(stream_id, status, "");
944 return CreateFramer(false)->SerializeRstStream(rst_ir);
947 SpdyFrame* SpdyTestUtil::ConstructSpdyGet(
948 const char* const url,
949 bool compressed,
950 SpdyStreamId stream_id,
951 RequestPriority request_priority) const {
952 scoped_ptr<SpdyHeaderBlock> block(ConstructGetHeaderBlock(url));
953 return ConstructSpdySyn(
954 stream_id, *block, request_priority, compressed, true);
957 SpdyFrame* SpdyTestUtil::ConstructSpdyGet(const char* const extra_headers[],
958 int extra_header_count,
959 bool compressed,
960 int stream_id,
961 RequestPriority request_priority,
962 bool direct) const {
963 SpdyHeaderBlock block;
964 AddUrlToHeaderBlock(default_url_.spec(), &block);
965 block[GetMethodKey()] = "GET";
966 MaybeAddVersionHeader(&block);
967 AppendToHeaderBlock(extra_headers, extra_header_count, &block);
968 return ConstructSpdySyn(stream_id, block, request_priority, compressed, true);
971 SpdyFrame* SpdyTestUtil::ConstructSpdyConnect(
972 const char* const extra_headers[],
973 int extra_header_count,
974 int stream_id,
975 RequestPriority priority,
976 const HostPortPair& host_port_pair) const {
977 SpdyHeaderBlock block;
978 block[GetMethodKey()] = "CONNECT";
979 if (spdy_version() < HTTP2) {
980 block[GetPathKey()] = host_port_pair.ToString();
981 block[GetHostKey()] = (host_port_pair.port() == 443)
982 ? host_port_pair.host()
983 : host_port_pair.ToString();
984 } else {
985 block[GetHostKey()] = host_port_pair.ToString();
988 MaybeAddVersionHeader(&block);
989 AppendToHeaderBlock(extra_headers, extra_header_count, &block);
990 return ConstructSpdySyn(stream_id, block, priority, false, false);
993 SpdyFrame* SpdyTestUtil::ConstructSpdyPush(const char* const extra_headers[],
994 int extra_header_count,
995 int stream_id,
996 int associated_stream_id,
997 const char* url) {
998 if (spdy_version() < HTTP2) {
999 SpdySynStreamIR syn_stream(stream_id);
1000 syn_stream.set_associated_to_stream_id(associated_stream_id);
1001 syn_stream.SetHeader("hello", "bye");
1002 syn_stream.SetHeader(GetStatusKey(), "200 OK");
1003 syn_stream.SetHeader(GetVersionKey(), "HTTP/1.1");
1004 AddUrlToHeaderBlock(url, syn_stream.mutable_header_block());
1005 AppendToHeaderBlock(extra_headers, extra_header_count,
1006 syn_stream.mutable_header_block());
1007 return CreateFramer(false)->SerializeFrame(syn_stream);
1008 } else {
1009 SpdyPushPromiseIR push_promise(associated_stream_id, stream_id);
1010 AddUrlToHeaderBlock(url, push_promise.mutable_header_block());
1011 scoped_ptr<SpdyFrame> push_promise_frame(
1012 CreateFramer(false)->SerializeFrame(push_promise));
1014 SpdyHeadersIR headers(stream_id);
1015 headers.SetHeader("hello", "bye");
1016 headers.SetHeader(GetStatusKey(), "200 OK");
1017 AppendToHeaderBlock(extra_headers, extra_header_count,
1018 headers.mutable_header_block());
1019 scoped_ptr<SpdyFrame> headers_frame(
1020 CreateFramer(false)->SerializeFrame(headers));
1022 int joint_data_size = push_promise_frame->size() + headers_frame->size();
1023 scoped_ptr<char[]> data(new char[joint_data_size]);
1024 const SpdyFrame* frames[2] = {
1025 push_promise_frame.get(), headers_frame.get(),
1027 int combined_size =
1028 CombineFrames(frames, arraysize(frames), data.get(), joint_data_size);
1029 DCHECK_EQ(combined_size, joint_data_size);
1030 return new SpdyFrame(data.release(), joint_data_size, true);
1034 SpdyFrame* SpdyTestUtil::ConstructSpdyPush(const char* const extra_headers[],
1035 int extra_header_count,
1036 int stream_id,
1037 int associated_stream_id,
1038 const char* url,
1039 const char* status,
1040 const char* location) {
1041 if (spdy_version() < HTTP2) {
1042 SpdySynStreamIR syn_stream(stream_id);
1043 syn_stream.set_associated_to_stream_id(associated_stream_id);
1044 syn_stream.SetHeader("hello", "bye");
1045 syn_stream.SetHeader(GetStatusKey(), status);
1046 syn_stream.SetHeader(GetVersionKey(), "HTTP/1.1");
1047 syn_stream.SetHeader("location", location);
1048 AddUrlToHeaderBlock(url, syn_stream.mutable_header_block());
1049 AppendToHeaderBlock(extra_headers, extra_header_count,
1050 syn_stream.mutable_header_block());
1051 return CreateFramer(false)->SerializeFrame(syn_stream);
1052 } else {
1053 SpdyPushPromiseIR push_promise(associated_stream_id, stream_id);
1054 AddUrlToHeaderBlock(url, push_promise.mutable_header_block());
1055 scoped_ptr<SpdyFrame> push_promise_frame(
1056 CreateFramer(false)->SerializeFrame(push_promise));
1058 SpdyHeadersIR headers(stream_id);
1059 headers.SetHeader("hello", "bye");
1060 headers.SetHeader(GetStatusKey(), status);
1061 headers.SetHeader("location", location);
1062 AppendToHeaderBlock(extra_headers, extra_header_count,
1063 headers.mutable_header_block());
1064 scoped_ptr<SpdyFrame> headers_frame(
1065 CreateFramer(false)->SerializeFrame(headers));
1067 int joint_data_size = push_promise_frame->size() + headers_frame->size();
1068 scoped_ptr<char[]> data(new char[joint_data_size]);
1069 const SpdyFrame* frames[2] = {
1070 push_promise_frame.get(), headers_frame.get(),
1072 int combined_size =
1073 CombineFrames(frames, arraysize(frames), data.get(), joint_data_size);
1074 DCHECK_EQ(combined_size, joint_data_size);
1075 return new SpdyFrame(data.release(), joint_data_size, true);
1079 SpdyFrame* SpdyTestUtil::ConstructInitialSpdyPushFrame(
1080 scoped_ptr<SpdyHeaderBlock> headers,
1081 int stream_id,
1082 int associated_stream_id) {
1083 if (spdy_version() < HTTP2) {
1084 SpdySynStreamIR syn_stream(stream_id);
1085 syn_stream.set_associated_to_stream_id(associated_stream_id);
1086 SetPriority(LOWEST, &syn_stream);
1087 syn_stream.set_header_block(*headers);
1088 return CreateFramer(false)->SerializeFrame(syn_stream);
1089 } else {
1090 SpdyPushPromiseIR push_promise(associated_stream_id, stream_id);
1091 push_promise.set_header_block(*headers);
1092 return CreateFramer(false)->SerializeFrame(push_promise);
1096 SpdyFrame* SpdyTestUtil::ConstructSpdyPushHeaders(
1097 int stream_id,
1098 const char* const extra_headers[],
1099 int extra_header_count) {
1100 SpdyHeadersIR headers(stream_id);
1101 headers.SetHeader(GetStatusKey(), "200 OK");
1102 MaybeAddVersionHeader(&headers);
1103 AppendToHeaderBlock(extra_headers, extra_header_count,
1104 headers.mutable_header_block());
1105 return CreateFramer(false)->SerializeFrame(headers);
1108 SpdyFrame* SpdyTestUtil::ConstructSpdySyn(int stream_id,
1109 const SpdyHeaderBlock& block,
1110 RequestPriority priority,
1111 bool compressed,
1112 bool fin) const {
1113 if (protocol_ < kProtoHTTP2MinimumVersion) {
1114 SpdySynStreamIR syn_stream(stream_id);
1115 syn_stream.set_header_block(block);
1116 syn_stream.set_priority(
1117 ConvertRequestPriorityToSpdyPriority(priority, spdy_version()));
1118 syn_stream.set_fin(fin);
1119 return CreateFramer(compressed)->SerializeFrame(syn_stream);
1120 } else {
1121 SpdyHeadersIR headers(stream_id);
1122 headers.set_header_block(block);
1123 headers.set_has_priority(true);
1124 headers.set_priority(
1125 ConvertRequestPriorityToSpdyPriority(priority, spdy_version()));
1126 headers.set_fin(fin);
1127 return CreateFramer(compressed)->SerializeFrame(headers);
1131 SpdyFrame* SpdyTestUtil::ConstructSpdyReply(int stream_id,
1132 const SpdyHeaderBlock& headers) {
1133 if (protocol_ < kProtoHTTP2MinimumVersion) {
1134 SpdySynReplyIR syn_reply(stream_id);
1135 syn_reply.set_header_block(headers);
1136 return CreateFramer(false)->SerializeFrame(syn_reply);
1137 } else {
1138 SpdyHeadersIR reply(stream_id);
1139 reply.set_header_block(headers);
1140 return CreateFramer(false)->SerializeFrame(reply);
1144 SpdyFrame* SpdyTestUtil::ConstructSpdySynReplyError(
1145 const char* const status,
1146 const char* const* const extra_headers,
1147 int extra_header_count,
1148 int stream_id) {
1149 SpdyHeaderBlock block;
1150 block["hello"] = "bye";
1151 block[GetStatusKey()] = status;
1152 MaybeAddVersionHeader(&block);
1153 AppendToHeaderBlock(extra_headers, extra_header_count, &block);
1155 return ConstructSpdyReply(stream_id, block);
1158 SpdyFrame* SpdyTestUtil::ConstructSpdyGetSynReplyRedirect(int stream_id) {
1159 static const char* const kExtraHeaders[] = {
1160 "location", "http://www.foo.com/index.php",
1162 return ConstructSpdySynReplyError("301 Moved Permanently", kExtraHeaders,
1163 arraysize(kExtraHeaders)/2, stream_id);
1166 SpdyFrame* SpdyTestUtil::ConstructSpdySynReplyError(int stream_id) {
1167 return ConstructSpdySynReplyError("500 Internal Server Error", NULL, 0, 1);
1170 SpdyFrame* SpdyTestUtil::ConstructSpdyGetSynReply(
1171 const char* const extra_headers[],
1172 int extra_header_count,
1173 int stream_id) {
1174 SpdyHeaderBlock block;
1175 block["hello"] = "bye";
1176 block[GetStatusKey()] = "200";
1177 MaybeAddVersionHeader(&block);
1178 AppendToHeaderBlock(extra_headers, extra_header_count, &block);
1180 return ConstructSpdyReply(stream_id, block);
1183 SpdyFrame* SpdyTestUtil::ConstructSpdyPost(const char* url,
1184 SpdyStreamId stream_id,
1185 int64 content_length,
1186 RequestPriority priority,
1187 const char* const extra_headers[],
1188 int extra_header_count) {
1189 scoped_ptr<SpdyHeaderBlock> block(
1190 ConstructPostHeaderBlock(url, content_length));
1191 AppendToHeaderBlock(extra_headers, extra_header_count, block.get());
1192 return ConstructSpdySyn(stream_id, *block, priority, false, false);
1195 SpdyFrame* SpdyTestUtil::ConstructChunkedSpdyPost(
1196 const char* const extra_headers[],
1197 int extra_header_count) {
1198 SpdyHeaderBlock block;
1199 block[GetMethodKey()] = "POST";
1200 AddUrlToHeaderBlock(default_url_.spec(), &block);
1201 MaybeAddVersionHeader(&block);
1202 AppendToHeaderBlock(extra_headers, extra_header_count, &block);
1203 return ConstructSpdySyn(1, block, LOWEST, false, false);
1206 SpdyFrame* SpdyTestUtil::ConstructSpdyPostSynReply(
1207 const char* const extra_headers[],
1208 int extra_header_count) {
1209 // TODO(jgraettinger): Remove this method.
1210 return ConstructSpdyGetSynReply(NULL, 0, 1);
1213 SpdyFrame* SpdyTestUtil::ConstructSpdyBodyFrame(int stream_id, bool fin) {
1214 SpdyFramer framer(spdy_version_);
1215 SpdyDataIR data_ir(stream_id,
1216 base::StringPiece(kUploadData, kUploadDataSize));
1217 data_ir.set_fin(fin);
1218 return framer.SerializeData(data_ir);
1221 SpdyFrame* SpdyTestUtil::ConstructSpdyBodyFrame(int stream_id,
1222 const char* data,
1223 uint32 len,
1224 bool fin) {
1225 SpdyFramer framer(spdy_version_);
1226 SpdyDataIR data_ir(stream_id, base::StringPiece(data, len));
1227 data_ir.set_fin(fin);
1228 return framer.SerializeData(data_ir);
1231 SpdyFrame* SpdyTestUtil::ConstructSpdyBodyFrame(int stream_id,
1232 const char* data,
1233 uint32 len,
1234 bool fin,
1235 int padding_length) {
1236 SpdyFramer framer(spdy_version_);
1237 SpdyDataIR data_ir(stream_id, base::StringPiece(data, len));
1238 data_ir.set_fin(fin);
1239 data_ir.set_padding_len(padding_length);
1240 return framer.SerializeData(data_ir);
1243 SpdyFrame* SpdyTestUtil::ConstructWrappedSpdyFrame(
1244 const scoped_ptr<SpdyFrame>& frame,
1245 int stream_id) {
1246 return ConstructSpdyBodyFrame(stream_id, frame->data(),
1247 frame->size(), false);
1250 const SpdyHeaderInfo SpdyTestUtil::MakeSpdyHeader(SpdyFrameType type) {
1251 const SpdyHeaderInfo kHeader = {
1252 type,
1253 1, // Stream ID
1254 0, // Associated stream ID
1255 ConvertRequestPriorityToSpdyPriority(LOWEST, spdy_version_),
1256 kSpdyCredentialSlotUnused,
1257 CONTROL_FLAG_FIN, // Control Flags
1258 false, // Compressed
1259 RST_STREAM_INVALID,
1260 NULL, // Data
1261 0, // Length
1262 DATA_FLAG_NONE
1264 return kHeader;
1267 scoped_ptr<SpdyFramer> SpdyTestUtil::CreateFramer(bool compressed) const {
1268 scoped_ptr<SpdyFramer> framer(new SpdyFramer(spdy_version_));
1269 framer->set_enable_compression(compressed);
1270 return framer.Pass();
1273 const char* SpdyTestUtil::GetMethodKey() const {
1274 return ":method";
1277 const char* SpdyTestUtil::GetStatusKey() const {
1278 return ":status";
1281 const char* SpdyTestUtil::GetHostKey() const {
1282 if (protocol_ < kProtoHTTP2MinimumVersion)
1283 return ":host";
1284 else
1285 return ":authority";
1288 const char* SpdyTestUtil::GetSchemeKey() const {
1289 return ":scheme";
1292 const char* SpdyTestUtil::GetVersionKey() const {
1293 return ":version";
1296 const char* SpdyTestUtil::GetPathKey() const {
1297 return ":path";
1300 scoped_ptr<SpdyHeaderBlock> SpdyTestUtil::ConstructHeaderBlock(
1301 base::StringPiece method,
1302 base::StringPiece url,
1303 int64* content_length) const {
1304 std::string scheme, host, path;
1305 ParseUrl(url.data(), &scheme, &host, &path);
1306 scoped_ptr<SpdyHeaderBlock> headers(new SpdyHeaderBlock());
1307 (*headers)[GetMethodKey()] = method.as_string();
1308 (*headers)[GetPathKey()] = path.c_str();
1309 (*headers)[GetHostKey()] = host.c_str();
1310 (*headers)[GetSchemeKey()] = scheme.c_str();
1311 if (include_version_header()) {
1312 (*headers)[GetVersionKey()] = "HTTP/1.1";
1314 if (content_length) {
1315 std::string length_str = base::Int64ToString(*content_length);
1316 (*headers)["content-length"] = length_str;
1318 return headers.Pass();
1321 void SpdyTestUtil::MaybeAddVersionHeader(
1322 SpdyFrameWithHeaderBlockIR* frame_ir) const {
1323 if (include_version_header()) {
1324 frame_ir->SetHeader(GetVersionKey(), "HTTP/1.1");
1328 void SpdyTestUtil::MaybeAddVersionHeader(SpdyHeaderBlock* block) const {
1329 if (include_version_header()) {
1330 (*block)[GetVersionKey()] = "HTTP/1.1";
1334 void SpdyTestUtil::SetPriority(RequestPriority priority,
1335 SpdySynStreamIR* ir) const {
1336 ir->set_priority(ConvertRequestPriorityToSpdyPriority(
1337 priority, spdy_version()));
1340 } // namespace net