We started redesigning GpuMemoryBuffer interface to handle multiple buffers [0].
[chromium-blink-merge.git] / net / spdy / spdy_test_util_common.cc
blob057bb5fe85592369cb3d9e0007d6e0f1806d2458
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);
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 OnStreamPadding(SpdyStreamId stream_id, size_t len) override {}
247 void OnSettings(bool clear_persisted) override {}
248 void OnSetting(SpdySettingsIds id, uint8 flags, uint32 value) override {}
249 void OnPing(SpdyPingId unique_id, bool is_ack) override {}
250 void OnRstStream(SpdyStreamId stream_id,
251 SpdyRstStreamStatus status) override {}
252 void OnGoAway(SpdyStreamId last_accepted_stream_id,
253 SpdyGoAwayStatus status) override {}
254 void OnWindowUpdate(SpdyStreamId stream_id,
255 uint32 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(SpdySession::GetInitialWindowSize(protocol)),
372 stream_max_recv_window_size(SpdySession::GetInitialWindowSize(protocol)),
373 time_func(&base::TimeTicks::Now),
374 force_spdy_over_ssl(false),
375 force_spdy_always(false),
376 use_alternate_protocols(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(NextProto protocol,
390 ProxyService* proxy_service)
391 : host_resolver(new MockHostResolver),
392 cert_verifier(new MockCertVerifier),
393 transport_security_state(new TransportSecurityState),
394 proxy_service(proxy_service),
395 ssl_config_service(new SSLConfigServiceDefaults),
396 socket_factory(new MockClientSocketFactory),
397 deterministic_socket_factory(new DeterministicMockClientSocketFactory),
398 http_auth_handler_factory(
399 HttpAuthHandlerFactory::CreateDefault(host_resolver.get())),
400 enable_ip_pooling(true),
401 enable_compression(false),
402 enable_ping(false),
403 enable_user_alternate_protocol_ports(false),
404 protocol(protocol),
405 session_max_recv_window_size(SpdySession::GetInitialWindowSize(protocol)),
406 stream_max_recv_window_size(SpdySession::GetInitialWindowSize(protocol)),
407 time_func(&base::TimeTicks::Now),
408 force_spdy_over_ssl(false),
409 force_spdy_always(false),
410 use_alternate_protocols(false),
411 net_log(NULL) {
412 DCHECK(next_proto_is_spdy(protocol)) << "Invalid protocol: " << protocol;
415 SpdySessionDependencies::~SpdySessionDependencies() {}
417 // static
418 HttpNetworkSession* SpdySessionDependencies::SpdyCreateSession(
419 SpdySessionDependencies* session_deps) {
420 net::HttpNetworkSession::Params params = CreateSessionParams(session_deps);
421 params.client_socket_factory = session_deps->socket_factory.get();
422 HttpNetworkSession* http_session = new HttpNetworkSession(params);
423 SpdySessionPoolPeer pool_peer(http_session->spdy_session_pool());
424 pool_peer.SetEnableSendingInitialData(false);
425 return http_session;
428 // static
429 HttpNetworkSession* SpdySessionDependencies::SpdyCreateSessionDeterministic(
430 SpdySessionDependencies* session_deps) {
431 net::HttpNetworkSession::Params params = CreateSessionParams(session_deps);
432 params.client_socket_factory =
433 session_deps->deterministic_socket_factory.get();
434 HttpNetworkSession* http_session = new HttpNetworkSession(params);
435 SpdySessionPoolPeer pool_peer(http_session->spdy_session_pool());
436 pool_peer.SetEnableSendingInitialData(false);
437 return http_session;
440 // static
441 net::HttpNetworkSession::Params SpdySessionDependencies::CreateSessionParams(
442 SpdySessionDependencies* session_deps) {
443 DCHECK(next_proto_is_spdy(session_deps->protocol)) <<
444 "Invalid protocol: " << session_deps->protocol;
446 net::HttpNetworkSession::Params params;
447 params.host_resolver = session_deps->host_resolver.get();
448 params.cert_verifier = session_deps->cert_verifier.get();
449 params.transport_security_state =
450 session_deps->transport_security_state.get();
451 params.proxy_service = session_deps->proxy_service.get();
452 params.ssl_config_service = session_deps->ssl_config_service.get();
453 params.http_auth_handler_factory =
454 session_deps->http_auth_handler_factory.get();
455 params.http_server_properties =
456 session_deps->http_server_properties.GetWeakPtr();
457 params.enable_spdy_compression = session_deps->enable_compression;
458 params.enable_spdy_ping_based_connection_checking = session_deps->enable_ping;
459 params.enable_user_alternate_protocol_ports =
460 session_deps->enable_user_alternate_protocol_ports;
461 params.spdy_default_protocol = session_deps->protocol;
462 params.spdy_session_max_recv_window_size =
463 session_deps->session_max_recv_window_size;
464 params.spdy_stream_max_recv_window_size =
465 session_deps->stream_max_recv_window_size;
466 params.time_func = session_deps->time_func;
467 params.next_protos = session_deps->next_protos;
468 params.trusted_spdy_proxy = session_deps->trusted_spdy_proxy;
469 params.force_spdy_over_ssl = session_deps->force_spdy_over_ssl;
470 params.force_spdy_always = session_deps->force_spdy_always;
471 params.use_alternate_protocols = session_deps->use_alternate_protocols;
472 params.net_log = session_deps->net_log;
473 return params;
476 SpdyURLRequestContext::SpdyURLRequestContext(NextProto protocol,
477 bool force_spdy_over_ssl,
478 bool force_spdy_always)
479 : storage_(this) {
480 DCHECK(next_proto_is_spdy(protocol)) << "Invalid protocol: " << protocol;
482 storage_.set_host_resolver(scoped_ptr<HostResolver>(new MockHostResolver));
483 storage_.set_cert_verifier(new MockCertVerifier);
484 storage_.set_transport_security_state(new TransportSecurityState);
485 storage_.set_proxy_service(ProxyService::CreateDirect());
486 storage_.set_ssl_config_service(new SSLConfigServiceDefaults);
487 storage_.set_http_auth_handler_factory(HttpAuthHandlerFactory::CreateDefault(
488 host_resolver()));
489 storage_.set_http_server_properties(
490 scoped_ptr<HttpServerProperties>(new HttpServerPropertiesImpl()));
491 storage_.set_job_factory(new URLRequestJobFactoryImpl());
492 net::HttpNetworkSession::Params params;
493 params.client_socket_factory = &socket_factory_;
494 params.host_resolver = host_resolver();
495 params.cert_verifier = cert_verifier();
496 params.transport_security_state = transport_security_state();
497 params.proxy_service = proxy_service();
498 params.ssl_config_service = ssl_config_service();
499 params.http_auth_handler_factory = http_auth_handler_factory();
500 params.network_delegate = network_delegate();
501 params.enable_spdy_compression = false;
502 params.enable_spdy_ping_based_connection_checking = false;
503 params.spdy_default_protocol = protocol;
504 params.force_spdy_over_ssl = force_spdy_over_ssl;
505 params.force_spdy_always = force_spdy_always;
506 params.http_server_properties = http_server_properties();
507 scoped_refptr<HttpNetworkSession> network_session(
508 new HttpNetworkSession(params));
509 SpdySessionPoolPeer pool_peer(network_session->spdy_session_pool());
510 pool_peer.SetEnableSendingInitialData(false);
511 storage_.set_http_transaction_factory(new HttpCache(
512 network_session.get(), HttpCache::DefaultBackend::InMemory(0)));
515 SpdyURLRequestContext::~SpdyURLRequestContext() {
516 AssertNoURLRequests();
519 bool HasSpdySession(SpdySessionPool* pool, const SpdySessionKey& key) {
520 return pool->FindAvailableSession(key, BoundNetLog()) != NULL;
523 namespace {
525 base::WeakPtr<SpdySession> CreateSpdySessionHelper(
526 const scoped_refptr<HttpNetworkSession>& http_session,
527 const SpdySessionKey& key,
528 const BoundNetLog& net_log,
529 Error expected_status,
530 bool is_secure) {
531 EXPECT_FALSE(HasSpdySession(http_session->spdy_session_pool(), key));
533 scoped_refptr<TransportSocketParams> transport_params(
534 new TransportSocketParams(
535 key.host_port_pair(), false, false, OnHostResolutionCallback(),
536 TransportSocketParams::COMBINE_CONNECT_AND_WRITE_DEFAULT));
538 scoped_ptr<ClientSocketHandle> connection(new ClientSocketHandle);
539 TestCompletionCallback callback;
541 int rv = ERR_UNEXPECTED;
542 if (is_secure) {
543 SSLConfig ssl_config;
544 scoped_refptr<SSLSocketParams> ssl_params(
545 new SSLSocketParams(transport_params,
546 NULL,
547 NULL,
548 key.host_port_pair(),
549 ssl_config,
550 key.privacy_mode(),
552 false,
553 false));
554 rv = connection->Init(key.host_port_pair().ToString(),
555 ssl_params,
556 MEDIUM,
557 callback.callback(),
558 http_session->GetSSLSocketPool(
559 HttpNetworkSession::NORMAL_SOCKET_POOL),
560 net_log);
561 } else {
562 rv = connection->Init(key.host_port_pair().ToString(),
563 transport_params,
564 MEDIUM,
565 callback.callback(),
566 http_session->GetTransportSocketPool(
567 HttpNetworkSession::NORMAL_SOCKET_POOL),
568 net_log);
571 if (rv == ERR_IO_PENDING)
572 rv = callback.WaitForResult();
574 EXPECT_EQ(OK, rv);
576 base::WeakPtr<SpdySession> spdy_session =
577 http_session->spdy_session_pool()->CreateAvailableSessionFromSocket(
578 key, connection.Pass(), net_log, OK, is_secure);
579 // Failure is reported asynchronously.
580 EXPECT_TRUE(spdy_session != NULL);
581 EXPECT_TRUE(HasSpdySession(http_session->spdy_session_pool(), key));
582 return spdy_session;
585 } // namespace
587 base::WeakPtr<SpdySession> CreateInsecureSpdySession(
588 const scoped_refptr<HttpNetworkSession>& http_session,
589 const SpdySessionKey& key,
590 const BoundNetLog& net_log) {
591 return CreateSpdySessionHelper(http_session, key, net_log,
592 OK, false /* is_secure */);
595 base::WeakPtr<SpdySession> TryCreateInsecureSpdySessionExpectingFailure(
596 const scoped_refptr<HttpNetworkSession>& http_session,
597 const SpdySessionKey& key,
598 Error expected_error,
599 const BoundNetLog& net_log) {
600 DCHECK_LT(expected_error, ERR_IO_PENDING);
601 return CreateSpdySessionHelper(http_session, key, net_log,
602 expected_error, false /* is_secure */);
605 base::WeakPtr<SpdySession> CreateSecureSpdySession(
606 const scoped_refptr<HttpNetworkSession>& http_session,
607 const SpdySessionKey& key,
608 const BoundNetLog& net_log) {
609 return CreateSpdySessionHelper(http_session, key, net_log,
610 OK, true /* is_secure */);
613 namespace {
615 // A ClientSocket used for CreateFakeSpdySession() below.
616 class FakeSpdySessionClientSocket : public MockClientSocket {
617 public:
618 FakeSpdySessionClientSocket(int read_result)
619 : MockClientSocket(BoundNetLog()),
620 read_result_(read_result) {}
622 ~FakeSpdySessionClientSocket() override {}
624 int Read(IOBuffer* buf,
625 int buf_len,
626 const CompletionCallback& callback) override {
627 return read_result_;
630 int Write(IOBuffer* buf,
631 int buf_len,
632 const CompletionCallback& callback) override {
633 return ERR_IO_PENDING;
636 // Return kProtoUnknown to use the pool's default protocol.
637 NextProto GetNegotiatedProtocol() const override { return kProtoUnknown; }
639 // The functions below are not expected to be called.
641 int Connect(const CompletionCallback& callback) override {
642 ADD_FAILURE();
643 return ERR_UNEXPECTED;
646 bool WasEverUsed() const override {
647 ADD_FAILURE();
648 return false;
651 bool UsingTCPFastOpen() const override {
652 ADD_FAILURE();
653 return false;
656 bool WasNpnNegotiated() const override {
657 ADD_FAILURE();
658 return false;
661 bool GetSSLInfo(SSLInfo* ssl_info) override {
662 ADD_FAILURE();
663 return false;
666 private:
667 int read_result_;
670 base::WeakPtr<SpdySession> CreateFakeSpdySessionHelper(
671 SpdySessionPool* pool,
672 const SpdySessionKey& key,
673 Error expected_status) {
674 EXPECT_NE(expected_status, ERR_IO_PENDING);
675 EXPECT_FALSE(HasSpdySession(pool, key));
676 scoped_ptr<ClientSocketHandle> handle(new ClientSocketHandle());
677 handle->SetSocket(scoped_ptr<StreamSocket>(new FakeSpdySessionClientSocket(
678 expected_status == OK ? ERR_IO_PENDING : expected_status)));
679 base::WeakPtr<SpdySession> spdy_session =
680 pool->CreateAvailableSessionFromSocket(
681 key, handle.Pass(), BoundNetLog(), OK, true /* is_secure */);
682 // Failure is reported asynchronously.
683 EXPECT_TRUE(spdy_session != NULL);
684 EXPECT_TRUE(HasSpdySession(pool, key));
685 return spdy_session;
688 } // namespace
690 base::WeakPtr<SpdySession> CreateFakeSpdySession(SpdySessionPool* pool,
691 const SpdySessionKey& key) {
692 return CreateFakeSpdySessionHelper(pool, key, OK);
695 base::WeakPtr<SpdySession> TryCreateFakeSpdySessionExpectingFailure(
696 SpdySessionPool* pool,
697 const SpdySessionKey& key,
698 Error expected_error) {
699 DCHECK_LT(expected_error, ERR_IO_PENDING);
700 return CreateFakeSpdySessionHelper(pool, key, expected_error);
703 SpdySessionPoolPeer::SpdySessionPoolPeer(SpdySessionPool* pool) : pool_(pool) {
706 void SpdySessionPoolPeer::RemoveAliases(const SpdySessionKey& key) {
707 pool_->RemoveAliases(key);
710 void SpdySessionPoolPeer::DisableDomainAuthenticationVerification() {
711 pool_->verify_domain_authentication_ = false;
714 void SpdySessionPoolPeer::SetEnableSendingInitialData(bool enabled) {
715 pool_->enable_sending_initial_data_ = enabled;
718 void SpdySessionPoolPeer::SetSessionMaxRecvWindowSize(size_t window) {
719 pool_->session_max_recv_window_size_ = window;
722 void SpdySessionPoolPeer::SetStreamInitialRecvWindowSize(size_t window) {
723 pool_->stream_max_recv_window_size_ = window;
726 SpdyTestUtil::SpdyTestUtil(NextProto protocol)
727 : protocol_(protocol),
728 spdy_version_(NextProtoToSpdyMajorVersion(protocol)) {
729 DCHECK(next_proto_is_spdy(protocol)) << "Invalid protocol: " << protocol;
732 void SpdyTestUtil::AddUrlToHeaderBlock(base::StringPiece url,
733 SpdyHeaderBlock* headers) const {
734 std::string scheme, host, path;
735 ParseUrl(url, &scheme, &host, &path);
736 (*headers)[GetSchemeKey()] = scheme;
737 (*headers)[GetHostKey()] = host;
738 (*headers)[GetPathKey()] = path;
741 scoped_ptr<SpdyHeaderBlock> SpdyTestUtil::ConstructGetHeaderBlock(
742 base::StringPiece url) const {
743 return ConstructHeaderBlock("GET", url, NULL);
746 scoped_ptr<SpdyHeaderBlock> SpdyTestUtil::ConstructGetHeaderBlockForProxy(
747 base::StringPiece url) const {
748 scoped_ptr<SpdyHeaderBlock> headers(ConstructGetHeaderBlock(url));
749 return headers.Pass();
752 scoped_ptr<SpdyHeaderBlock> SpdyTestUtil::ConstructHeadHeaderBlock(
753 base::StringPiece url,
754 int64 content_length) const {
755 return ConstructHeaderBlock("HEAD", url, &content_length);
758 scoped_ptr<SpdyHeaderBlock> SpdyTestUtil::ConstructPostHeaderBlock(
759 base::StringPiece url,
760 int64 content_length) const {
761 return ConstructHeaderBlock("POST", url, &content_length);
764 scoped_ptr<SpdyHeaderBlock> SpdyTestUtil::ConstructPutHeaderBlock(
765 base::StringPiece url,
766 int64 content_length) const {
767 return ConstructHeaderBlock("PUT", url, &content_length);
770 SpdyFrame* SpdyTestUtil::ConstructSpdyFrame(
771 const SpdyHeaderInfo& header_info,
772 scoped_ptr<SpdyHeaderBlock> headers) const {
773 BufferedSpdyFramer framer(spdy_version_, header_info.compressed);
774 SpdyFrame* frame = NULL;
775 switch (header_info.kind) {
776 case DATA:
777 frame = framer.CreateDataFrame(header_info.id, header_info.data,
778 header_info.data_length,
779 header_info.data_flags);
780 break;
781 case SYN_STREAM:
783 frame = framer.CreateSynStream(header_info.id, header_info.assoc_id,
784 header_info.priority,
785 header_info.control_flags,
786 headers.get());
788 break;
789 case SYN_REPLY:
790 frame = framer.CreateSynReply(header_info.id, header_info.control_flags,
791 headers.get());
792 break;
793 case RST_STREAM:
794 frame = framer.CreateRstStream(header_info.id, header_info.status);
795 break;
796 case HEADERS:
797 frame = framer.CreateHeaders(header_info.id, header_info.control_flags,
798 header_info.priority,
799 headers.get());
800 break;
801 default:
802 ADD_FAILURE();
803 break;
805 return frame;
808 SpdyFrame* SpdyTestUtil::ConstructSpdyFrame(const SpdyHeaderInfo& header_info,
809 const char* const extra_headers[],
810 int extra_header_count,
811 const char* const tail_headers[],
812 int tail_header_count) const {
813 scoped_ptr<SpdyHeaderBlock> headers(new SpdyHeaderBlock());
814 AppendToHeaderBlock(extra_headers, extra_header_count, headers.get());
815 if (tail_headers && tail_header_count)
816 AppendToHeaderBlock(tail_headers, tail_header_count, headers.get());
817 return ConstructSpdyFrame(header_info, headers.Pass());
820 SpdyFrame* SpdyTestUtil::ConstructSpdyControlFrame(
821 scoped_ptr<SpdyHeaderBlock> headers,
822 bool compressed,
823 SpdyStreamId stream_id,
824 RequestPriority request_priority,
825 SpdyFrameType type,
826 SpdyControlFlags flags,
827 SpdyStreamId associated_stream_id) const {
828 EXPECT_GE(type, DATA);
829 EXPECT_LE(type, PRIORITY);
830 const SpdyHeaderInfo header_info = {
831 type,
832 stream_id,
833 associated_stream_id,
834 ConvertRequestPriorityToSpdyPriority(request_priority, spdy_version_),
835 0, // credential slot
836 flags,
837 compressed,
838 RST_STREAM_INVALID, // status
839 NULL, // data
840 0, // length
841 DATA_FLAG_NONE
843 return ConstructSpdyFrame(header_info, headers.Pass());
846 SpdyFrame* SpdyTestUtil::ConstructSpdyControlFrame(
847 const char* const extra_headers[],
848 int extra_header_count,
849 bool compressed,
850 SpdyStreamId stream_id,
851 RequestPriority request_priority,
852 SpdyFrameType type,
853 SpdyControlFlags flags,
854 const char* const* tail_headers,
855 int tail_header_size,
856 SpdyStreamId associated_stream_id) const {
857 scoped_ptr<SpdyHeaderBlock> headers(new SpdyHeaderBlock());
858 AppendToHeaderBlock(extra_headers, extra_header_count, headers.get());
859 if (tail_headers && tail_header_size)
860 AppendToHeaderBlock(tail_headers, tail_header_size / 2, headers.get());
861 return ConstructSpdyControlFrame(
862 headers.Pass(), compressed, stream_id,
863 request_priority, type, flags, associated_stream_id);
866 std::string SpdyTestUtil::ConstructSpdyReplyString(
867 const SpdyHeaderBlock& headers) const {
868 std::string reply_string;
869 for (SpdyHeaderBlock::const_iterator it = headers.begin();
870 it != headers.end(); ++it) {
871 std::string key = it->first;
872 // Remove leading colon from "special" headers (for SPDY3 and
873 // above).
874 if (spdy_version() >= SPDY3 && key[0] == ':')
875 key = key.substr(1);
876 std::vector<std::string> values;
877 base::SplitString(it->second, '\0', &values);
878 for (std::vector<std::string>::const_iterator it2 = values.begin();
879 it2 != values.end(); ++it2) {
880 reply_string += key + ": " + *it2 + "\n";
883 return reply_string;
886 // TODO(jgraettinger): Eliminate uses of this method in tests (prefer
887 // SpdySettingsIR).
888 SpdyFrame* SpdyTestUtil::ConstructSpdySettings(
889 const SettingsMap& settings) const {
890 SpdySettingsIR settings_ir;
891 for (SettingsMap::const_iterator it = settings.begin();
892 it != settings.end();
893 ++it) {
894 settings_ir.AddSetting(
895 it->first,
896 (it->second.first & SETTINGS_FLAG_PLEASE_PERSIST) != 0,
897 (it->second.first & SETTINGS_FLAG_PERSISTED) != 0,
898 it->second.second);
900 return CreateFramer(false)->SerializeFrame(settings_ir);
903 SpdyFrame* SpdyTestUtil::ConstructSpdySettingsAck() const {
904 char kEmptyWrite[] = "";
906 if (spdy_version() > SPDY3) {
907 SpdySettingsIR settings_ir;
908 settings_ir.set_is_ack(true);
909 return CreateFramer(false)->SerializeFrame(settings_ir);
911 // No settings ACK write occurs. Create an empty placeholder write.
912 return new SpdyFrame(kEmptyWrite, 0, false);
915 SpdyFrame* SpdyTestUtil::ConstructSpdyPing(uint32 ping_id, bool is_ack) const {
916 SpdyPingIR ping_ir(ping_id);
917 ping_ir.set_is_ack(is_ack);
918 return CreateFramer(false)->SerializeFrame(ping_ir);
921 SpdyFrame* SpdyTestUtil::ConstructSpdyGoAway() const {
922 return ConstructSpdyGoAway(0);
925 SpdyFrame* SpdyTestUtil::ConstructSpdyGoAway(
926 SpdyStreamId last_good_stream_id) const {
927 SpdyGoAwayIR go_ir(last_good_stream_id, GOAWAY_OK, "go away");
928 return CreateFramer(false)->SerializeFrame(go_ir);
931 SpdyFrame* SpdyTestUtil::ConstructSpdyGoAway(SpdyStreamId last_good_stream_id,
932 SpdyGoAwayStatus status,
933 const std::string& desc) const {
934 SpdyGoAwayIR go_ir(last_good_stream_id, status, desc);
935 return CreateFramer(false)->SerializeFrame(go_ir);
938 SpdyFrame* SpdyTestUtil::ConstructSpdyWindowUpdate(
939 const SpdyStreamId stream_id, uint32 delta_window_size) const {
940 SpdyWindowUpdateIR update_ir(stream_id, delta_window_size);
941 return CreateFramer(false)->SerializeFrame(update_ir);
944 // TODO(jgraettinger): Eliminate uses of this method in tests (prefer
945 // SpdyRstStreamIR).
946 SpdyFrame* SpdyTestUtil::ConstructSpdyRstStream(
947 SpdyStreamId stream_id,
948 SpdyRstStreamStatus status) const {
949 SpdyRstStreamIR rst_ir(stream_id, status, "");
950 return CreateFramer(false)->SerializeRstStream(rst_ir);
953 SpdyFrame* SpdyTestUtil::ConstructSpdyGet(
954 const char* const url,
955 bool compressed,
956 SpdyStreamId stream_id,
957 RequestPriority request_priority) const {
958 scoped_ptr<SpdyHeaderBlock> block(ConstructGetHeaderBlock(url));
959 return ConstructSpdySyn(
960 stream_id, *block, request_priority, compressed, true);
963 SpdyFrame* SpdyTestUtil::ConstructSpdyGet(const char* const extra_headers[],
964 int extra_header_count,
965 bool compressed,
966 int stream_id,
967 RequestPriority request_priority,
968 bool direct) const {
969 SpdyHeaderBlock block;
970 block[GetMethodKey()] = "GET";
971 block[GetPathKey()] = "/";
972 block[GetHostKey()] = "www.google.com";
973 block[GetSchemeKey()] = "http";
974 MaybeAddVersionHeader(&block);
975 AppendToHeaderBlock(extra_headers, extra_header_count, &block);
976 return ConstructSpdySyn(stream_id, block, request_priority, compressed, true);
979 SpdyFrame* SpdyTestUtil::ConstructSpdyConnect(
980 const char* const extra_headers[],
981 int extra_header_count,
982 int stream_id,
983 RequestPriority priority,
984 const HostPortPair& host_port_pair) const {
985 SpdyHeaderBlock block;
986 block[GetMethodKey()] = "CONNECT";
987 block[GetPathKey()] = host_port_pair.ToString();
988 block[GetHostKey()] = (host_port_pair.port() == 443)
989 ? host_port_pair.host()
990 : 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() < SPDY4) {
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_name_value_block());
1008 AppendToHeaderBlock(extra_headers,
1009 extra_header_count,
1010 syn_stream.mutable_name_value_block());
1011 return CreateFramer(false)->SerializeFrame(syn_stream);
1012 } else {
1013 SpdyPushPromiseIR push_promise(associated_stream_id, stream_id);
1014 AddUrlToHeaderBlock(url, push_promise.mutable_name_value_block());
1015 scoped_ptr<SpdyFrame> push_promise_frame(
1016 CreateFramer(false)->SerializeFrame(push_promise));
1018 SpdyHeadersIR headers(stream_id);
1019 headers.SetHeader("hello", "bye");
1020 headers.SetHeader(GetStatusKey(), "200 OK");
1021 AppendToHeaderBlock(
1022 extra_headers, extra_header_count, headers.mutable_name_value_block());
1023 scoped_ptr<SpdyFrame> headers_frame(
1024 CreateFramer(false)->SerializeFrame(headers));
1026 int joint_data_size = push_promise_frame->size() + headers_frame->size();
1027 scoped_ptr<char[]> data(new char[joint_data_size]);
1028 const SpdyFrame* frames[2] = {
1029 push_promise_frame.get(), headers_frame.get(),
1031 int combined_size =
1032 CombineFrames(frames, arraysize(frames), data.get(), joint_data_size);
1033 DCHECK_EQ(combined_size, joint_data_size);
1034 return new SpdyFrame(data.release(), joint_data_size, true);
1038 SpdyFrame* SpdyTestUtil::ConstructSpdyPush(const char* const extra_headers[],
1039 int extra_header_count,
1040 int stream_id,
1041 int associated_stream_id,
1042 const char* url,
1043 const char* status,
1044 const char* location) {
1045 if (spdy_version() < SPDY4) {
1046 SpdySynStreamIR syn_stream(stream_id);
1047 syn_stream.set_associated_to_stream_id(associated_stream_id);
1048 syn_stream.SetHeader("hello", "bye");
1049 syn_stream.SetHeader(GetStatusKey(), status);
1050 syn_stream.SetHeader(GetVersionKey(), "HTTP/1.1");
1051 syn_stream.SetHeader("location", location);
1052 AddUrlToHeaderBlock(url, syn_stream.mutable_name_value_block());
1053 AppendToHeaderBlock(extra_headers,
1054 extra_header_count,
1055 syn_stream.mutable_name_value_block());
1056 return CreateFramer(false)->SerializeFrame(syn_stream);
1057 } else {
1058 SpdyPushPromiseIR push_promise(associated_stream_id, stream_id);
1059 AddUrlToHeaderBlock(url, push_promise.mutable_name_value_block());
1060 scoped_ptr<SpdyFrame> push_promise_frame(
1061 CreateFramer(false)->SerializeFrame(push_promise));
1063 SpdyHeadersIR headers(stream_id);
1064 headers.SetHeader("hello", "bye");
1065 headers.SetHeader(GetStatusKey(), status);
1066 headers.SetHeader("location", location);
1067 AppendToHeaderBlock(
1068 extra_headers, extra_header_count, headers.mutable_name_value_block());
1069 scoped_ptr<SpdyFrame> headers_frame(
1070 CreateFramer(false)->SerializeFrame(headers));
1072 int joint_data_size = push_promise_frame->size() + headers_frame->size();
1073 scoped_ptr<char[]> data(new char[joint_data_size]);
1074 const SpdyFrame* frames[2] = {
1075 push_promise_frame.get(), headers_frame.get(),
1077 int combined_size =
1078 CombineFrames(frames, arraysize(frames), data.get(), joint_data_size);
1079 DCHECK_EQ(combined_size, joint_data_size);
1080 return new SpdyFrame(data.release(), joint_data_size, true);
1084 SpdyFrame* SpdyTestUtil::ConstructInitialSpdyPushFrame(
1085 scoped_ptr<SpdyHeaderBlock> headers,
1086 int stream_id,
1087 int associated_stream_id) {
1088 if (spdy_version() < SPDY4) {
1089 SpdySynStreamIR syn_stream(stream_id);
1090 syn_stream.set_associated_to_stream_id(associated_stream_id);
1091 SetPriority(LOWEST, &syn_stream);
1092 syn_stream.set_name_value_block(*headers);
1093 return CreateFramer(false)->SerializeFrame(syn_stream);
1094 } else {
1095 SpdyPushPromiseIR push_promise(associated_stream_id, stream_id);
1096 push_promise.set_name_value_block(*headers);
1097 return CreateFramer(false)->SerializeFrame(push_promise);
1101 SpdyFrame* SpdyTestUtil::ConstructSpdyPushHeaders(
1102 int stream_id,
1103 const char* const extra_headers[],
1104 int extra_header_count) {
1105 SpdyHeadersIR headers(stream_id);
1106 headers.SetHeader(GetStatusKey(), "200 OK");
1107 MaybeAddVersionHeader(&headers);
1108 AppendToHeaderBlock(extra_headers, extra_header_count,
1109 headers.mutable_name_value_block());
1110 return CreateFramer(false)->SerializeFrame(headers);
1113 SpdyFrame* SpdyTestUtil::ConstructSpdySyn(int stream_id,
1114 const SpdyHeaderBlock& block,
1115 RequestPriority priority,
1116 bool compressed,
1117 bool fin) const {
1118 if (protocol_ < kProtoSPDY4MinimumVersion) {
1119 SpdySynStreamIR syn_stream(stream_id);
1120 syn_stream.set_name_value_block(block);
1121 syn_stream.set_priority(
1122 ConvertRequestPriorityToSpdyPriority(priority, spdy_version()));
1123 syn_stream.set_fin(fin);
1124 return CreateFramer(compressed)->SerializeFrame(syn_stream);
1125 } else {
1126 SpdyHeadersIR headers(stream_id);
1127 headers.set_name_value_block(block);
1128 headers.set_has_priority(true);
1129 headers.set_priority(
1130 ConvertRequestPriorityToSpdyPriority(priority, spdy_version()));
1131 headers.set_fin(fin);
1132 return CreateFramer(compressed)->SerializeFrame(headers);
1136 SpdyFrame* SpdyTestUtil::ConstructSpdyReply(int stream_id,
1137 const SpdyHeaderBlock& headers) {
1138 if (protocol_ < kProtoSPDY4MinimumVersion) {
1139 SpdySynReplyIR syn_reply(stream_id);
1140 syn_reply.set_name_value_block(headers);
1141 return CreateFramer(false)->SerializeFrame(syn_reply);
1142 } else {
1143 SpdyHeadersIR reply(stream_id);
1144 reply.set_name_value_block(headers);
1145 return CreateFramer(false)->SerializeFrame(reply);
1149 SpdyFrame* SpdyTestUtil::ConstructSpdySynReplyError(
1150 const char* const status,
1151 const char* const* const extra_headers,
1152 int extra_header_count,
1153 int stream_id) {
1154 SpdyHeaderBlock block;
1155 block["hello"] = "bye";
1156 block[GetStatusKey()] = status;
1157 MaybeAddVersionHeader(&block);
1158 AppendToHeaderBlock(extra_headers, extra_header_count, &block);
1160 return ConstructSpdyReply(stream_id, block);
1163 SpdyFrame* SpdyTestUtil::ConstructSpdyGetSynReplyRedirect(int stream_id) {
1164 static const char* const kExtraHeaders[] = {
1165 "location", "http://www.foo.com/index.php",
1167 return ConstructSpdySynReplyError("301 Moved Permanently", kExtraHeaders,
1168 arraysize(kExtraHeaders)/2, stream_id);
1171 SpdyFrame* SpdyTestUtil::ConstructSpdySynReplyError(int stream_id) {
1172 return ConstructSpdySynReplyError("500 Internal Server Error", NULL, 0, 1);
1175 SpdyFrame* SpdyTestUtil::ConstructSpdyGetSynReply(
1176 const char* const extra_headers[],
1177 int extra_header_count,
1178 int stream_id) {
1179 SpdyHeaderBlock block;
1180 block["hello"] = "bye";
1181 block[GetStatusKey()] = "200";
1182 MaybeAddVersionHeader(&block);
1183 AppendToHeaderBlock(extra_headers, extra_header_count, &block);
1185 return ConstructSpdyReply(stream_id, block);
1188 SpdyFrame* SpdyTestUtil::ConstructSpdyPost(const char* url,
1189 SpdyStreamId stream_id,
1190 int64 content_length,
1191 RequestPriority priority,
1192 const char* const extra_headers[],
1193 int extra_header_count) {
1194 scoped_ptr<SpdyHeaderBlock> block(
1195 ConstructPostHeaderBlock(url, content_length));
1196 AppendToHeaderBlock(extra_headers, extra_header_count, block.get());
1197 return ConstructSpdySyn(stream_id, *block, priority, false, false);
1200 SpdyFrame* SpdyTestUtil::ConstructChunkedSpdyPost(
1201 const char* const extra_headers[],
1202 int extra_header_count) {
1203 SpdyHeaderBlock block;
1204 block[GetMethodKey()] = "POST";
1205 block[GetPathKey()] = "/";
1206 block[GetHostKey()] = "www.google.com";
1207 block[GetSchemeKey()] = "http";
1208 MaybeAddVersionHeader(&block);
1209 AppendToHeaderBlock(extra_headers, extra_header_count, &block);
1210 return ConstructSpdySyn(1, block, LOWEST, false, false);
1213 SpdyFrame* SpdyTestUtil::ConstructSpdyPostSynReply(
1214 const char* const extra_headers[],
1215 int extra_header_count) {
1216 // TODO(jgraettinger): Remove this method.
1217 return ConstructSpdyGetSynReply(NULL, 0, 1);
1220 SpdyFrame* SpdyTestUtil::ConstructSpdyBodyFrame(int stream_id, bool fin) {
1221 SpdyFramer framer(spdy_version_);
1222 SpdyDataIR data_ir(stream_id,
1223 base::StringPiece(kUploadData, kUploadDataSize));
1224 data_ir.set_fin(fin);
1225 return framer.SerializeData(data_ir);
1228 SpdyFrame* SpdyTestUtil::ConstructSpdyBodyFrame(int stream_id,
1229 const char* data,
1230 uint32 len,
1231 bool fin) {
1232 SpdyFramer framer(spdy_version_);
1233 SpdyDataIR data_ir(stream_id, base::StringPiece(data, len));
1234 data_ir.set_fin(fin);
1235 return framer.SerializeData(data_ir);
1238 SpdyFrame* SpdyTestUtil::ConstructSpdyBodyFrame(int stream_id,
1239 const char* data,
1240 uint32 len,
1241 bool fin,
1242 int padding_length) {
1243 SpdyFramer framer(spdy_version_);
1244 SpdyDataIR data_ir(stream_id, base::StringPiece(data, len));
1245 data_ir.set_fin(fin);
1246 data_ir.set_padding_len(padding_length);
1247 return framer.SerializeData(data_ir);
1250 SpdyFrame* SpdyTestUtil::ConstructWrappedSpdyFrame(
1251 const scoped_ptr<SpdyFrame>& frame,
1252 int stream_id) {
1253 return ConstructSpdyBodyFrame(stream_id, frame->data(),
1254 frame->size(), false);
1257 const SpdyHeaderInfo SpdyTestUtil::MakeSpdyHeader(SpdyFrameType type) {
1258 const SpdyHeaderInfo kHeader = {
1259 type,
1260 1, // Stream ID
1261 0, // Associated stream ID
1262 ConvertRequestPriorityToSpdyPriority(LOWEST, spdy_version_),
1263 kSpdyCredentialSlotUnused,
1264 CONTROL_FLAG_FIN, // Control Flags
1265 false, // Compressed
1266 RST_STREAM_INVALID,
1267 NULL, // Data
1268 0, // Length
1269 DATA_FLAG_NONE
1271 return kHeader;
1274 scoped_ptr<SpdyFramer> SpdyTestUtil::CreateFramer(bool compressed) const {
1275 scoped_ptr<SpdyFramer> framer(new SpdyFramer(spdy_version_));
1276 framer->set_enable_compression(compressed);
1277 return framer.Pass();
1280 const char* SpdyTestUtil::GetMethodKey() const {
1281 return ":method";
1284 const char* SpdyTestUtil::GetStatusKey() const {
1285 return ":status";
1288 const char* SpdyTestUtil::GetHostKey() const {
1289 if (protocol_ < kProtoSPDY4MinimumVersion)
1290 return ":host";
1291 else
1292 return ":authority";
1295 const char* SpdyTestUtil::GetSchemeKey() const {
1296 return ":scheme";
1299 const char* SpdyTestUtil::GetVersionKey() const {
1300 return ":version";
1303 const char* SpdyTestUtil::GetPathKey() const {
1304 return ":path";
1307 scoped_ptr<SpdyHeaderBlock> SpdyTestUtil::ConstructHeaderBlock(
1308 base::StringPiece method,
1309 base::StringPiece url,
1310 int64* content_length) const {
1311 std::string scheme, host, path;
1312 ParseUrl(url.data(), &scheme, &host, &path);
1313 scoped_ptr<SpdyHeaderBlock> headers(new SpdyHeaderBlock());
1314 (*headers)[GetMethodKey()] = method.as_string();
1315 (*headers)[GetPathKey()] = path.c_str();
1316 (*headers)[GetHostKey()] = host.c_str();
1317 (*headers)[GetSchemeKey()] = scheme.c_str();
1318 if (include_version_header()) {
1319 (*headers)[GetVersionKey()] = "HTTP/1.1";
1321 if (content_length) {
1322 std::string length_str = base::Int64ToString(*content_length);
1323 (*headers)["content-length"] = length_str;
1325 return headers.Pass();
1328 void SpdyTestUtil::MaybeAddVersionHeader(
1329 SpdyFrameWithNameValueBlockIR* frame_ir) const {
1330 if (include_version_header()) {
1331 frame_ir->SetHeader(GetVersionKey(), "HTTP/1.1");
1335 void SpdyTestUtil::MaybeAddVersionHeader(SpdyHeaderBlock* block) const {
1336 if (include_version_header()) {
1337 (*block)[GetVersionKey()] = "HTTP/1.1";
1341 void SpdyTestUtil::SetPriority(RequestPriority priority,
1342 SpdySynStreamIR* ir) const {
1343 ir->set_priority(ConvertRequestPriorityToSpdyPriority(
1344 priority, spdy_version()));
1347 } // namespace net