1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "build/build_config.h"
15 #include "base/basictypes.h"
16 #include "base/bind.h"
17 #include "base/compiler_specific.h"
18 #include "base/files/file_util.h"
19 #include "base/files/scoped_temp_dir.h"
20 #include "base/format_macros.h"
21 #include "base/memory/scoped_ptr.h"
22 #include "base/memory/weak_ptr.h"
23 #include "base/message_loop/message_loop.h"
24 #include "base/message_loop/message_loop_proxy.h"
25 #include "base/path_service.h"
26 #include "base/run_loop.h"
27 #include "base/strings/string_number_conversions.h"
28 #include "base/strings/string_piece.h"
29 #include "base/strings/string_split.h"
30 #include "base/strings/string_util.h"
31 #include "base/strings/stringprintf.h"
32 #include "base/strings/utf_string_conversions.h"
33 #include "net/base/capturing_net_log.h"
34 #include "net/base/load_flags.h"
35 #include "net/base/load_timing_info.h"
36 #include "net/base/load_timing_info_test_util.h"
37 #include "net/base/net_errors.h"
38 #include "net/base/net_log.h"
39 #include "net/base/net_log_unittest.h"
40 #include "net/base/net_module.h"
41 #include "net/base/net_util.h"
42 #include "net/base/request_priority.h"
43 #include "net/base/test_data_directory.h"
44 #include "net/base/upload_bytes_element_reader.h"
45 #include "net/base/upload_data_stream.h"
46 #include "net/base/upload_file_element_reader.h"
47 #include "net/cert/ev_root_ca_metadata.h"
48 #include "net/cert/mock_cert_verifier.h"
49 #include "net/cert/test_root_certs.h"
50 #include "net/cookies/cookie_monster.h"
51 #include "net/cookies/cookie_store_test_helpers.h"
52 #include "net/disk_cache/disk_cache.h"
53 #include "net/dns/mock_host_resolver.h"
54 #include "net/ftp/ftp_network_layer.h"
55 #include "net/http/http_byte_range.h"
56 #include "net/http/http_cache.h"
57 #include "net/http/http_network_layer.h"
58 #include "net/http/http_network_session.h"
59 #include "net/http/http_request_headers.h"
60 #include "net/http/http_response_headers.h"
61 #include "net/http/http_util.h"
62 #include "net/ocsp/nss_ocsp.h"
63 #include "net/proxy/proxy_service.h"
64 #include "net/socket/ssl_client_socket.h"
65 #include "net/ssl/ssl_cipher_suite_names.h"
66 #include "net/ssl/ssl_connection_status_flags.h"
67 #include "net/test/cert_test_util.h"
68 #include "net/test/spawned_test_server/spawned_test_server.h"
69 #include "net/url_request/data_protocol_handler.h"
70 #include "net/url_request/static_http_user_agent_settings.h"
71 #include "net/url_request/url_request.h"
72 #include "net/url_request/url_request_http_job.h"
73 #include "net/url_request/url_request_job_factory_impl.h"
74 #include "net/url_request/url_request_redirect_job.h"
75 #include "net/url_request/url_request_test_job.h"
76 #include "net/url_request/url_request_test_util.h"
77 #include "testing/gtest/include/gtest/gtest.h"
78 #include "testing/platform_test.h"
80 #if !defined(DISABLE_FILE_SUPPORT)
81 #include "net/base/filename_util.h"
82 #include "net/url_request/file_protocol_handler.h"
83 #include "net/url_request/url_request_file_dir_job.h"
86 #if !defined(DISABLE_FTP_SUPPORT)
87 #include "net/url_request/ftp_protocol_handler.h"
91 #include "base/win/scoped_com_initializer.h"
92 #include "base/win/scoped_comptr.h"
93 #include "base/win/windows_version.h"
96 using base::ASCIIToUTF16
;
103 const base::string16
kChrome(ASCIIToUTF16("chrome"));
104 const base::string16
kSecret(ASCIIToUTF16("secret"));
105 const base::string16
kUser(ASCIIToUTF16("user"));
107 // Tests load timing information in the case a fresh connection was used, with
109 void TestLoadTimingNotReused(const LoadTimingInfo
& load_timing_info
,
110 int connect_timing_flags
) {
111 EXPECT_FALSE(load_timing_info
.socket_reused
);
112 EXPECT_NE(NetLog::Source::kInvalidId
, load_timing_info
.socket_log_id
);
114 EXPECT_FALSE(load_timing_info
.request_start_time
.is_null());
115 EXPECT_FALSE(load_timing_info
.request_start
.is_null());
117 EXPECT_LE(load_timing_info
.request_start
,
118 load_timing_info
.connect_timing
.connect_start
);
119 ExpectConnectTimingHasTimes(load_timing_info
.connect_timing
,
120 connect_timing_flags
);
121 EXPECT_LE(load_timing_info
.connect_timing
.connect_end
,
122 load_timing_info
.send_start
);
123 EXPECT_LE(load_timing_info
.send_start
, load_timing_info
.send_end
);
124 EXPECT_LE(load_timing_info
.send_end
, load_timing_info
.receive_headers_end
);
126 EXPECT_TRUE(load_timing_info
.proxy_resolve_start
.is_null());
127 EXPECT_TRUE(load_timing_info
.proxy_resolve_end
.is_null());
130 // Same as above, but with proxy times.
131 void TestLoadTimingNotReusedWithProxy(
132 const LoadTimingInfo
& load_timing_info
,
133 int connect_timing_flags
) {
134 EXPECT_FALSE(load_timing_info
.socket_reused
);
135 EXPECT_NE(NetLog::Source::kInvalidId
, load_timing_info
.socket_log_id
);
137 EXPECT_FALSE(load_timing_info
.request_start_time
.is_null());
138 EXPECT_FALSE(load_timing_info
.request_start
.is_null());
140 EXPECT_LE(load_timing_info
.request_start
,
141 load_timing_info
.proxy_resolve_start
);
142 EXPECT_LE(load_timing_info
.proxy_resolve_start
,
143 load_timing_info
.proxy_resolve_end
);
144 EXPECT_LE(load_timing_info
.proxy_resolve_end
,
145 load_timing_info
.connect_timing
.connect_start
);
146 ExpectConnectTimingHasTimes(load_timing_info
.connect_timing
,
147 connect_timing_flags
);
148 EXPECT_LE(load_timing_info
.connect_timing
.connect_end
,
149 load_timing_info
.send_start
);
150 EXPECT_LE(load_timing_info
.send_start
, load_timing_info
.send_end
);
151 EXPECT_LE(load_timing_info
.send_end
, load_timing_info
.receive_headers_end
);
154 // Same as above, but with a reused socket and proxy times.
155 void TestLoadTimingReusedWithProxy(
156 const LoadTimingInfo
& load_timing_info
) {
157 EXPECT_TRUE(load_timing_info
.socket_reused
);
158 EXPECT_NE(NetLog::Source::kInvalidId
, load_timing_info
.socket_log_id
);
160 EXPECT_FALSE(load_timing_info
.request_start_time
.is_null());
161 EXPECT_FALSE(load_timing_info
.request_start
.is_null());
163 ExpectConnectTimingHasNoTimes(load_timing_info
.connect_timing
);
165 EXPECT_LE(load_timing_info
.request_start
,
166 load_timing_info
.proxy_resolve_start
);
167 EXPECT_LE(load_timing_info
.proxy_resolve_start
,
168 load_timing_info
.proxy_resolve_end
);
169 EXPECT_LE(load_timing_info
.proxy_resolve_end
,
170 load_timing_info
.send_start
);
171 EXPECT_LE(load_timing_info
.send_start
, load_timing_info
.send_end
);
172 EXPECT_LE(load_timing_info
.send_end
, load_timing_info
.receive_headers_end
);
175 // Tests load timing information in the case of a cache hit, when no cache
176 // validation request was sent over the wire.
177 base::StringPiece
TestNetResourceProvider(int key
) {
181 void FillBuffer(char* buffer
, size_t len
) {
182 static bool called
= false;
185 int seed
= static_cast<int>(Time::Now().ToInternalValue());
189 for (size_t i
= 0; i
< len
; i
++) {
190 buffer
[i
] = static_cast<char>(rand());
197 void TestLoadTimingCacheHitNoNetwork(
198 const LoadTimingInfo
& load_timing_info
) {
199 EXPECT_FALSE(load_timing_info
.socket_reused
);
200 EXPECT_EQ(NetLog::Source::kInvalidId
, load_timing_info
.socket_log_id
);
202 EXPECT_FALSE(load_timing_info
.request_start_time
.is_null());
203 EXPECT_FALSE(load_timing_info
.request_start
.is_null());
205 ExpectConnectTimingHasNoTimes(load_timing_info
.connect_timing
);
206 EXPECT_LE(load_timing_info
.request_start
, load_timing_info
.send_start
);
207 EXPECT_LE(load_timing_info
.send_start
, load_timing_info
.send_end
);
208 EXPECT_LE(load_timing_info
.send_end
, load_timing_info
.receive_headers_end
);
210 EXPECT_TRUE(load_timing_info
.proxy_resolve_start
.is_null());
211 EXPECT_TRUE(load_timing_info
.proxy_resolve_end
.is_null());
214 // Tests load timing in the case that there is no HTTP response. This can be
215 // used to test in the case of errors or non-HTTP requests.
216 void TestLoadTimingNoHttpResponse(
217 const LoadTimingInfo
& load_timing_info
) {
218 EXPECT_FALSE(load_timing_info
.socket_reused
);
219 EXPECT_EQ(NetLog::Source::kInvalidId
, load_timing_info
.socket_log_id
);
221 // Only the request times should be non-null.
222 EXPECT_FALSE(load_timing_info
.request_start_time
.is_null());
223 EXPECT_FALSE(load_timing_info
.request_start
.is_null());
225 ExpectConnectTimingHasNoTimes(load_timing_info
.connect_timing
);
227 EXPECT_TRUE(load_timing_info
.proxy_resolve_start
.is_null());
228 EXPECT_TRUE(load_timing_info
.proxy_resolve_end
.is_null());
229 EXPECT_TRUE(load_timing_info
.send_start
.is_null());
230 EXPECT_TRUE(load_timing_info
.send_end
.is_null());
231 EXPECT_TRUE(load_timing_info
.receive_headers_end
.is_null());
234 // Do a case-insensitive search through |haystack| for |needle|.
235 bool ContainsString(const std::string
& haystack
, const char* needle
) {
236 std::string::const_iterator it
=
237 std::search(haystack
.begin(),
240 needle
+ strlen(needle
),
241 base::CaseInsensitiveCompare
<char>());
242 return it
!= haystack
.end();
245 UploadDataStream
* CreateSimpleUploadData(const char* data
) {
246 scoped_ptr
<UploadElementReader
> reader(
247 new UploadBytesElementReader(data
, strlen(data
)));
248 return UploadDataStream::CreateWithReader(reader
.Pass(), 0);
251 // Verify that the SSLInfo of a successful SSL connection has valid values.
252 void CheckSSLInfo(const SSLInfo
& ssl_info
) {
253 // -1 means unknown. 0 means no encryption.
254 EXPECT_GT(ssl_info
.security_bits
, 0);
256 // The cipher suite TLS_NULL_WITH_NULL_NULL (0) must not be negotiated.
257 int cipher_suite
= SSLConnectionStatusToCipherSuite(
258 ssl_info
.connection_status
);
259 EXPECT_NE(0, cipher_suite
);
262 void CheckFullRequestHeaders(const HttpRequestHeaders
& headers
,
263 const GURL
& host_url
) {
264 std::string sent_value
;
266 EXPECT_TRUE(headers
.GetHeader("Host", &sent_value
));
267 EXPECT_EQ(GetHostAndOptionalPort(host_url
), sent_value
);
269 EXPECT_TRUE(headers
.GetHeader("Connection", &sent_value
));
270 EXPECT_EQ("keep-alive", sent_value
);
273 bool FingerprintsEqual(const HashValueVector
& a
, const HashValueVector
& b
) {
274 size_t size
= a
.size();
276 if (size
!= b
.size())
279 for (size_t i
= 0; i
< size
; ++i
) {
280 if (!a
[i
].Equals(b
[i
]))
286 #endif // !defined(OS_IOS)
288 // A network delegate that allows the user to choose a subset of request stages
289 // to block in. When blocking, the delegate can do one of the following:
290 // * synchronously return a pre-specified error code, or
291 // * asynchronously return that value via an automatically called callback,
293 // * block and wait for the user to do a callback.
294 // Additionally, the user may also specify a redirect URL -- then each request
295 // with the current URL different from the redirect target will be redirected
296 // to that target, in the on-before-URL-request stage, independent of whether
297 // the delegate blocks in ON_BEFORE_URL_REQUEST or not.
298 class BlockingNetworkDelegate
: public TestNetworkDelegate
{
300 // Stages in which the delegate can block.
303 ON_BEFORE_URL_REQUEST
= 1 << 0,
304 ON_BEFORE_SEND_HEADERS
= 1 << 1,
305 ON_HEADERS_RECEIVED
= 1 << 2,
306 ON_AUTH_REQUIRED
= 1 << 3
309 // Behavior during blocked stages. During other stages, just
310 // returns OK or NetworkDelegate::AUTH_REQUIRED_RESPONSE_NO_ACTION.
312 SYNCHRONOUS
, // No callback, returns specified return values.
313 AUTO_CALLBACK
, // |this| posts a task to run the callback using the
314 // specified return codes.
315 USER_CALLBACK
, // User takes care of doing a callback. |retval_| and
316 // |auth_retval_| are ignored. In every blocking stage the
317 // message loop is quit.
320 // Creates a delegate which does not block at all.
321 explicit BlockingNetworkDelegate(BlockMode block_mode
);
323 // For users to trigger a callback returning |response|.
324 // Side-effects: resets |stage_blocked_for_callback_| and stored callbacks.
325 // Only call if |block_mode_| == USER_CALLBACK.
326 void DoCallback(int response
);
327 void DoAuthCallback(NetworkDelegate::AuthRequiredResponse response
);
330 void set_retval(int retval
) {
331 ASSERT_NE(USER_CALLBACK
, block_mode_
);
332 ASSERT_NE(ERR_IO_PENDING
, retval
);
333 ASSERT_NE(OK
, retval
);
337 // If |auth_retval| == AUTH_REQUIRED_RESPONSE_SET_AUTH, then
338 // |auth_credentials_| will be passed with the response.
339 void set_auth_retval(AuthRequiredResponse auth_retval
) {
340 ASSERT_NE(USER_CALLBACK
, block_mode_
);
341 ASSERT_NE(AUTH_REQUIRED_RESPONSE_IO_PENDING
, auth_retval
);
342 auth_retval_
= auth_retval
;
344 void set_auth_credentials(const AuthCredentials
& auth_credentials
) {
345 auth_credentials_
= auth_credentials
;
348 void set_redirect_url(const GURL
& url
) {
352 void set_block_on(int block_on
) {
353 block_on_
= block_on
;
356 // Allows the user to check in which state did we block.
357 Stage
stage_blocked_for_callback() const {
358 EXPECT_EQ(USER_CALLBACK
, block_mode_
);
359 return stage_blocked_for_callback_
;
363 void RunCallback(int response
, const CompletionCallback
& callback
);
364 void RunAuthCallback(AuthRequiredResponse response
,
365 const AuthCallback
& callback
);
367 // TestNetworkDelegate implementation.
368 virtual int OnBeforeURLRequest(URLRequest
* request
,
369 const CompletionCallback
& callback
,
370 GURL
* new_url
) OVERRIDE
;
372 virtual int OnBeforeSendHeaders(URLRequest
* request
,
373 const CompletionCallback
& callback
,
374 HttpRequestHeaders
* headers
) OVERRIDE
;
376 virtual int OnHeadersReceived(
378 const CompletionCallback
& callback
,
379 const HttpResponseHeaders
* original_response_headers
,
380 scoped_refptr
<HttpResponseHeaders
>* override_response_headers
,
381 GURL
* allowed_unsafe_redirect_url
) OVERRIDE
;
383 virtual NetworkDelegate::AuthRequiredResponse
OnAuthRequired(
385 const AuthChallengeInfo
& auth_info
,
386 const AuthCallback
& callback
,
387 AuthCredentials
* credentials
) OVERRIDE
;
389 // Resets the callbacks and |stage_blocked_for_callback_|.
392 // Checks whether we should block in |stage|. If yes, returns an error code
393 // and optionally sets up callback based on |block_mode_|. If no, returns OK.
394 int MaybeBlockStage(Stage stage
, const CompletionCallback
& callback
);
396 // Configuration parameters, can be adjusted by public methods:
397 const BlockMode block_mode_
;
399 // Values returned on blocking stages when mode is SYNCHRONOUS or
400 // AUTO_CALLBACK. For USER_CALLBACK these are set automatically to IO_PENDING.
401 int retval_
; // To be returned in non-auth stages.
402 AuthRequiredResponse auth_retval_
;
404 GURL redirect_url_
; // Used if non-empty during OnBeforeURLRequest.
405 int block_on_
; // Bit mask: in which stages to block.
407 // |auth_credentials_| will be copied to |*target_auth_credential_| on
409 AuthCredentials auth_credentials_
;
410 AuthCredentials
* target_auth_credentials_
;
412 // Internal variables, not set by not the user:
413 // Last blocked stage waiting for user callback (unused if |block_mode_| !=
415 Stage stage_blocked_for_callback_
;
417 // Callback objects stored during blocking stages.
418 CompletionCallback callback_
;
419 AuthCallback auth_callback_
;
421 base::WeakPtrFactory
<BlockingNetworkDelegate
> weak_factory_
;
423 DISALLOW_COPY_AND_ASSIGN(BlockingNetworkDelegate
);
426 BlockingNetworkDelegate::BlockingNetworkDelegate(BlockMode block_mode
)
427 : block_mode_(block_mode
),
429 auth_retval_(AUTH_REQUIRED_RESPONSE_NO_ACTION
),
431 target_auth_credentials_(NULL
),
432 stage_blocked_for_callback_(NOT_BLOCKED
),
433 weak_factory_(this) {
436 void BlockingNetworkDelegate::DoCallback(int response
) {
437 ASSERT_EQ(USER_CALLBACK
, block_mode_
);
438 ASSERT_NE(NOT_BLOCKED
, stage_blocked_for_callback_
);
439 ASSERT_NE(ON_AUTH_REQUIRED
, stage_blocked_for_callback_
);
440 CompletionCallback callback
= callback_
;
442 RunCallback(response
, callback
);
445 void BlockingNetworkDelegate::DoAuthCallback(
446 NetworkDelegate::AuthRequiredResponse response
) {
447 ASSERT_EQ(USER_CALLBACK
, block_mode_
);
448 ASSERT_EQ(ON_AUTH_REQUIRED
, stage_blocked_for_callback_
);
449 AuthCallback auth_callback
= auth_callback_
;
451 RunAuthCallback(response
, auth_callback
);
454 void BlockingNetworkDelegate::RunCallback(int response
,
455 const CompletionCallback
& callback
) {
456 callback
.Run(response
);
459 void BlockingNetworkDelegate::RunAuthCallback(AuthRequiredResponse response
,
460 const AuthCallback
& callback
) {
461 if (auth_retval_
== AUTH_REQUIRED_RESPONSE_SET_AUTH
) {
462 ASSERT_TRUE(target_auth_credentials_
!= NULL
);
463 *target_auth_credentials_
= auth_credentials_
;
465 callback
.Run(response
);
468 int BlockingNetworkDelegate::OnBeforeURLRequest(
470 const CompletionCallback
& callback
,
472 if (redirect_url_
== request
->url())
473 return OK
; // We've already seen this request and redirected elsewhere.
475 TestNetworkDelegate::OnBeforeURLRequest(request
, callback
, new_url
);
477 if (!redirect_url_
.is_empty())
478 *new_url
= redirect_url_
;
480 return MaybeBlockStage(ON_BEFORE_URL_REQUEST
, callback
);
483 int BlockingNetworkDelegate::OnBeforeSendHeaders(
485 const CompletionCallback
& callback
,
486 HttpRequestHeaders
* headers
) {
487 TestNetworkDelegate::OnBeforeSendHeaders(request
, callback
, headers
);
489 return MaybeBlockStage(ON_BEFORE_SEND_HEADERS
, callback
);
492 int BlockingNetworkDelegate::OnHeadersReceived(
494 const CompletionCallback
& callback
,
495 const HttpResponseHeaders
* original_response_headers
,
496 scoped_refptr
<HttpResponseHeaders
>* override_response_headers
,
497 GURL
* allowed_unsafe_redirect_url
) {
498 TestNetworkDelegate::OnHeadersReceived(request
,
500 original_response_headers
,
501 override_response_headers
,
502 allowed_unsafe_redirect_url
);
504 return MaybeBlockStage(ON_HEADERS_RECEIVED
, callback
);
507 NetworkDelegate::AuthRequiredResponse
BlockingNetworkDelegate::OnAuthRequired(
509 const AuthChallengeInfo
& auth_info
,
510 const AuthCallback
& callback
,
511 AuthCredentials
* credentials
) {
512 TestNetworkDelegate::OnAuthRequired(request
, auth_info
, callback
,
514 // Check that the user has provided callback for the previous blocked stage.
515 EXPECT_EQ(NOT_BLOCKED
, stage_blocked_for_callback_
);
517 if ((block_on_
& ON_AUTH_REQUIRED
) == 0) {
518 return AUTH_REQUIRED_RESPONSE_NO_ACTION
;
521 target_auth_credentials_
= credentials
;
523 switch (block_mode_
) {
525 if (auth_retval_
== AUTH_REQUIRED_RESPONSE_SET_AUTH
)
526 *target_auth_credentials_
= auth_credentials_
;
530 base::MessageLoop::current()->PostTask(
532 base::Bind(&BlockingNetworkDelegate::RunAuthCallback
,
533 weak_factory_
.GetWeakPtr(), auth_retval_
, callback
));
534 return AUTH_REQUIRED_RESPONSE_IO_PENDING
;
537 auth_callback_
= callback
;
538 stage_blocked_for_callback_
= ON_AUTH_REQUIRED
;
539 base::MessageLoop::current()->PostTask(FROM_HERE
,
540 base::MessageLoop::QuitClosure());
541 return AUTH_REQUIRED_RESPONSE_IO_PENDING
;
544 return AUTH_REQUIRED_RESPONSE_NO_ACTION
; // Dummy value.
547 void BlockingNetworkDelegate::Reset() {
548 EXPECT_NE(NOT_BLOCKED
, stage_blocked_for_callback_
);
549 stage_blocked_for_callback_
= NOT_BLOCKED
;
551 auth_callback_
.Reset();
554 int BlockingNetworkDelegate::MaybeBlockStage(
555 BlockingNetworkDelegate::Stage stage
,
556 const CompletionCallback
& callback
) {
557 // Check that the user has provided callback for the previous blocked stage.
558 EXPECT_EQ(NOT_BLOCKED
, stage_blocked_for_callback_
);
560 if ((block_on_
& stage
) == 0) {
564 switch (block_mode_
) {
566 EXPECT_NE(OK
, retval_
);
570 base::MessageLoop::current()->PostTask(
572 base::Bind(&BlockingNetworkDelegate::RunCallback
,
573 weak_factory_
.GetWeakPtr(), retval_
, callback
));
574 return ERR_IO_PENDING
;
577 callback_
= callback
;
578 stage_blocked_for_callback_
= stage
;
579 base::MessageLoop::current()->PostTask(FROM_HERE
,
580 base::MessageLoop::QuitClosure());
581 return ERR_IO_PENDING
;
587 class TestURLRequestContextWithProxy
: public TestURLRequestContext
{
589 // Does not own |delegate|.
590 TestURLRequestContextWithProxy(const std::string
& proxy
,
591 NetworkDelegate
* delegate
)
592 : TestURLRequestContext(true) {
593 context_storage_
.set_proxy_service(ProxyService::CreateFixed(proxy
));
594 set_network_delegate(delegate
);
597 virtual ~TestURLRequestContextWithProxy() {}
602 // Inherit PlatformTest since we require the autorelease pool on Mac OS X.
603 class URLRequestTest
: public PlatformTest
{
605 URLRequestTest() : default_context_(true) {
606 default_context_
.set_network_delegate(&default_network_delegate_
);
607 default_context_
.set_net_log(&net_log_
);
608 job_factory_
.SetProtocolHandler("data", new DataProtocolHandler
);
609 #if !defined(DISABLE_FILE_SUPPORT)
610 job_factory_
.SetProtocolHandler(
611 "file", new FileProtocolHandler(base::MessageLoopProxy::current()));
613 default_context_
.set_job_factory(&job_factory_
);
614 default_context_
.Init();
616 virtual ~URLRequestTest() {
617 // URLRequestJobs may post clean-up tasks on destruction.
618 base::RunLoop().RunUntilIdle();
621 // Adds the TestJobInterceptor to the default context.
622 TestJobInterceptor
* AddTestInterceptor() {
623 TestJobInterceptor
* protocol_handler_
= new TestJobInterceptor();
624 job_factory_
.SetProtocolHandler("http", NULL
);
625 job_factory_
.SetProtocolHandler("http", protocol_handler_
);
626 return protocol_handler_
;
630 CapturingNetLog net_log_
;
631 TestNetworkDelegate default_network_delegate_
; // Must outlive URLRequest.
632 URLRequestJobFactoryImpl job_factory_
;
633 TestURLRequestContext default_context_
;
636 TEST_F(URLRequestTest
, AboutBlankTest
) {
639 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
640 GURL("about:blank"), DEFAULT_PRIORITY
, &d
, NULL
));
643 EXPECT_TRUE(r
->is_pending());
645 base::RunLoop().Run();
647 EXPECT_TRUE(!r
->is_pending());
648 EXPECT_FALSE(d
.received_data_before_response());
649 EXPECT_EQ(d
.bytes_received(), 0);
650 EXPECT_EQ("", r
->GetSocketAddress().host());
651 EXPECT_EQ(0, r
->GetSocketAddress().port());
653 HttpRequestHeaders headers
;
654 EXPECT_FALSE(r
->GetFullRequestHeaders(&headers
));
658 TEST_F(URLRequestTest
, DataURLImageTest
) {
661 // Use our nice little Chrome logo.
662 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
664 "data:image/png;base64,"
665 "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAADVklEQVQ4jX2TfUwUBBjG3"
666 "w1y+HGcd9dxhXR8T4awOccJGgOSWclHImznLkTlSw0DDQXkrmgYgbUYnlQTqQxIEVxitD"
667 "5UMCATRA1CEEg+Qjw3bWDxIauJv/5oumqs39/P827vnucRmYN0gyF01GI5MpCVdW0gO7t"
668 "vNC+vqSEtbZefk5NuLv1jdJ46p/zw0HeH4+PHr3h7c1mjoV2t5rKzMx1+fg9bAgK6zHq9"
669 "cU5z+LpA3xOtx34+vTeT21onRuzssC3zxbbSwC13d/pFuC7CkIMDxQpF7r/MWq12UctI1"
670 "dWWm99ypqSYmRUBdKem8MkrO/kgaTt1O7YzlpzE5GIVd0WYUqt57yWf2McHTObYPbVD+Z"
671 "wbtlLTVMZ3BW+TnLyXLaWtmEq6WJVbT3HBh3Svj2HQQcm43XwmtoYM6vVKleh0uoWvnzW"
672 "3v3MpidruPTQPf0bia7sJOtBM0ufTWNvus/nkDFHF9ZS+uYVjRUasMeHUmyLYtcklTvzW"
673 "GFZnNOXczThvpKIzjcahSqIzkvDLayDq6D3eOjtBbNUEIZYyqsvj4V4wY92eNJ4IoyhTb"
674 "xXX1T5xsV9tm9r4TQwHLiZw/pdDZJea8TKmsmR/K0uLh/GwnCHghTja6lPhphezPfO5/5"
675 "MrVvMzNaI3+ERHfrFzPKQukrQGI4d/3EFD/3E2mVNYvi4at7CXWREaxZGD+3hg28zD3gV"
676 "Md6q5c8GdosynKmSeRuGzpjyl1/9UDGtPR5HeaKT8Wjo17WXk579BXVUhN64ehF9fhRtq"
677 "/uxxZKzNiZFGD0wRC3NFROZ5mwIPL/96K/rKMMLrIzF9uhHr+/sYH7DAbwlgC4J+R2Z7F"
678 "Ux1qLnV7MGF40smVSoJ/jvHRfYhQeUJd/SnYtGWhPHR0Sz+GE2F2yth0B36Vcz2KpnufB"
679 "JbsysjjW4kblBUiIjiURUWqJY65zxbnTy57GQyH58zgy0QBtTQv5gH15XMdKkYu+TGaJM"
680 "nlm2O34uI4b9tflqp1+QEFGzoW/ulmcofcpkZCYJhDfSpme7QcrHa+Xfji8paEQkTkSfm"
681 "moRWRNZr/F1KfVMjW+IKEnv2FwZfKdzt0BQR6lClcZR0EfEXEfv/G6W9iLiIyCoReV5En"
682 "hORIBHx+ufPj/gLB/zGI/G4Bk0AAAAASUVORK5CYII="),
683 DEFAULT_PRIORITY
, &d
, NULL
));
686 EXPECT_TRUE(r
->is_pending());
688 base::RunLoop().Run();
690 EXPECT_TRUE(!r
->is_pending());
691 EXPECT_FALSE(d
.received_data_before_response());
692 EXPECT_EQ(d
.bytes_received(), 911);
693 EXPECT_EQ("", r
->GetSocketAddress().host());
694 EXPECT_EQ(0, r
->GetSocketAddress().port());
696 HttpRequestHeaders headers
;
697 EXPECT_FALSE(r
->GetFullRequestHeaders(&headers
));
701 #if !defined(DISABLE_FILE_SUPPORT)
702 TEST_F(URLRequestTest
, FileTest
) {
703 base::FilePath app_path
;
704 PathService::Get(base::FILE_EXE
, &app_path
);
705 GURL app_url
= FilePathToFileURL(app_path
);
709 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
710 app_url
, DEFAULT_PRIORITY
, &d
, NULL
));
713 EXPECT_TRUE(r
->is_pending());
715 base::RunLoop().Run();
717 int64 file_size
= -1;
718 EXPECT_TRUE(base::GetFileSize(app_path
, &file_size
));
720 EXPECT_TRUE(!r
->is_pending());
721 EXPECT_EQ(1, d
.response_started_count());
722 EXPECT_FALSE(d
.received_data_before_response());
723 EXPECT_EQ(d
.bytes_received(), static_cast<int>(file_size
));
724 EXPECT_EQ("", r
->GetSocketAddress().host());
725 EXPECT_EQ(0, r
->GetSocketAddress().port());
727 HttpRequestHeaders headers
;
728 EXPECT_FALSE(r
->GetFullRequestHeaders(&headers
));
732 TEST_F(URLRequestTest
, FileTestCancel
) {
733 base::FilePath app_path
;
734 PathService::Get(base::FILE_EXE
, &app_path
);
735 GURL app_url
= FilePathToFileURL(app_path
);
739 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
740 app_url
, DEFAULT_PRIORITY
, &d
, NULL
));
743 EXPECT_TRUE(r
->is_pending());
746 // Async cancellation should be safe even when URLRequest has been already
748 base::RunLoop().RunUntilIdle();
751 TEST_F(URLRequestTest
, FileTestFullSpecifiedRange
) {
752 const size_t buffer_size
= 4000;
753 scoped_ptr
<char[]> buffer(new char[buffer_size
]);
754 FillBuffer(buffer
.get(), buffer_size
);
756 base::FilePath temp_path
;
757 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path
));
758 GURL temp_url
= FilePathToFileURL(temp_path
);
759 EXPECT_TRUE(base::WriteFile(temp_path
, buffer
.get(), buffer_size
));
762 EXPECT_TRUE(base::GetFileSize(temp_path
, &file_size
));
764 const size_t first_byte_position
= 500;
765 const size_t last_byte_position
= buffer_size
- first_byte_position
;
766 const size_t content_length
= last_byte_position
- first_byte_position
+ 1;
767 std::string
partial_buffer_string(buffer
.get() + first_byte_position
,
768 buffer
.get() + last_byte_position
+ 1);
772 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
773 temp_url
, DEFAULT_PRIORITY
, &d
, NULL
));
775 HttpRequestHeaders headers
;
777 HttpRequestHeaders::kRange
,
778 HttpByteRange::Bounded(
779 first_byte_position
, last_byte_position
).GetHeaderValue());
780 r
->SetExtraRequestHeaders(headers
);
782 EXPECT_TRUE(r
->is_pending());
784 base::RunLoop().Run();
785 EXPECT_TRUE(!r
->is_pending());
786 EXPECT_EQ(1, d
.response_started_count());
787 EXPECT_FALSE(d
.received_data_before_response());
788 EXPECT_EQ(static_cast<int>(content_length
), d
.bytes_received());
789 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
790 EXPECT_TRUE(partial_buffer_string
== d
.data_received());
793 EXPECT_TRUE(base::DeleteFile(temp_path
, false));
796 TEST_F(URLRequestTest
, FileTestHalfSpecifiedRange
) {
797 const size_t buffer_size
= 4000;
798 scoped_ptr
<char[]> buffer(new char[buffer_size
]);
799 FillBuffer(buffer
.get(), buffer_size
);
801 base::FilePath temp_path
;
802 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path
));
803 GURL temp_url
= FilePathToFileURL(temp_path
);
804 EXPECT_TRUE(base::WriteFile(temp_path
, buffer
.get(), buffer_size
));
807 EXPECT_TRUE(base::GetFileSize(temp_path
, &file_size
));
809 const size_t first_byte_position
= 500;
810 const size_t last_byte_position
= buffer_size
- 1;
811 const size_t content_length
= last_byte_position
- first_byte_position
+ 1;
812 std::string
partial_buffer_string(buffer
.get() + first_byte_position
,
813 buffer
.get() + last_byte_position
+ 1);
817 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
818 temp_url
, DEFAULT_PRIORITY
, &d
, NULL
));
820 HttpRequestHeaders headers
;
821 headers
.SetHeader(HttpRequestHeaders::kRange
,
822 HttpByteRange::RightUnbounded(
823 first_byte_position
).GetHeaderValue());
824 r
->SetExtraRequestHeaders(headers
);
826 EXPECT_TRUE(r
->is_pending());
828 base::RunLoop().Run();
829 EXPECT_TRUE(!r
->is_pending());
830 EXPECT_EQ(1, d
.response_started_count());
831 EXPECT_FALSE(d
.received_data_before_response());
832 EXPECT_EQ(static_cast<int>(content_length
), d
.bytes_received());
833 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
834 EXPECT_TRUE(partial_buffer_string
== d
.data_received());
837 EXPECT_TRUE(base::DeleteFile(temp_path
, false));
840 TEST_F(URLRequestTest
, FileTestMultipleRanges
) {
841 const size_t buffer_size
= 400000;
842 scoped_ptr
<char[]> buffer(new char[buffer_size
]);
843 FillBuffer(buffer
.get(), buffer_size
);
845 base::FilePath temp_path
;
846 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path
));
847 GURL temp_url
= FilePathToFileURL(temp_path
);
848 EXPECT_TRUE(base::WriteFile(temp_path
, buffer
.get(), buffer_size
));
851 EXPECT_TRUE(base::GetFileSize(temp_path
, &file_size
));
855 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
856 temp_url
, DEFAULT_PRIORITY
, &d
, NULL
));
858 HttpRequestHeaders headers
;
859 headers
.SetHeader(HttpRequestHeaders::kRange
, "bytes=0-0,10-200,200-300");
860 r
->SetExtraRequestHeaders(headers
);
862 EXPECT_TRUE(r
->is_pending());
864 base::RunLoop().Run();
865 EXPECT_TRUE(d
.request_failed());
868 EXPECT_TRUE(base::DeleteFile(temp_path
, false));
871 TEST_F(URLRequestTest
, AllowFileURLs
) {
872 base::ScopedTempDir temp_dir
;
873 ASSERT_TRUE(temp_dir
.CreateUniqueTempDir());
874 base::FilePath test_file
;
875 ASSERT_TRUE(base::CreateTemporaryFileInDir(temp_dir
.path(), &test_file
));
876 std::string
test_data("monkey");
877 base::WriteFile(test_file
, test_data
.data(), test_data
.size());
878 GURL test_file_url
= FilePathToFileURL(test_file
);
882 TestNetworkDelegate network_delegate
;
883 network_delegate
.set_can_access_files(true);
884 default_context_
.set_network_delegate(&network_delegate
);
885 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
886 test_file_url
, DEFAULT_PRIORITY
, &d
, NULL
));
888 base::RunLoop().Run();
889 EXPECT_FALSE(d
.request_failed());
890 EXPECT_EQ(test_data
, d
.data_received());
895 TestNetworkDelegate network_delegate
;
896 network_delegate
.set_can_access_files(false);
897 default_context_
.set_network_delegate(&network_delegate
);
898 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
899 test_file_url
, DEFAULT_PRIORITY
, &d
, NULL
));
901 base::RunLoop().Run();
902 EXPECT_TRUE(d
.request_failed());
903 EXPECT_EQ("", d
.data_received());
908 TEST_F(URLRequestTest
, FileDirCancelTest
) {
909 // Put in mock resource provider.
910 NetModule::SetResourceProvider(TestNetResourceProvider
);
914 base::FilePath file_path
;
915 PathService::Get(base::DIR_SOURCE_ROOT
, &file_path
);
916 file_path
= file_path
.Append(FILE_PATH_LITERAL("net"));
917 file_path
= file_path
.Append(FILE_PATH_LITERAL("data"));
919 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
920 FilePathToFileURL(file_path
), DEFAULT_PRIORITY
, &d
, NULL
));
922 EXPECT_TRUE(req
->is_pending());
924 d
.set_cancel_in_received_data_pending(true);
926 base::RunLoop().Run();
929 // Take out mock resource provider.
930 NetModule::SetResourceProvider(NULL
);
933 TEST_F(URLRequestTest
, FileDirOutputSanity
) {
934 // Verify the general sanity of the the output of the file:
935 // directory lister by checking for the output of a known existing
937 const char sentinel_name
[] = "filedir-sentinel";
940 PathService::Get(base::DIR_SOURCE_ROOT
, &path
);
941 path
= path
.Append(FILE_PATH_LITERAL("net"));
942 path
= path
.Append(FILE_PATH_LITERAL("data"));
943 path
= path
.Append(FILE_PATH_LITERAL("url_request_unittest"));
946 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
947 FilePathToFileURL(path
), DEFAULT_PRIORITY
, &d
, NULL
));
949 base::RunLoop().Run();
951 // Generate entry for the sentinel file.
952 base::FilePath sentinel_path
= path
.AppendASCII(sentinel_name
);
953 base::File::Info info
;
954 EXPECT_TRUE(base::GetFileInfo(sentinel_path
, &info
));
955 EXPECT_GT(info
.size
, 0);
956 std::string sentinel_output
= GetDirectoryListingEntry(
957 base::string16(sentinel_name
, sentinel_name
+ strlen(sentinel_name
)),
958 std::string(sentinel_name
),
963 ASSERT_LT(0, d
.bytes_received());
964 ASSERT_FALSE(d
.request_failed());
965 ASSERT_TRUE(req
->status().is_success());
966 // Check for the entry generated for the "sentinel" file.
967 const std::string
& data
= d
.data_received();
968 ASSERT_NE(data
.find(sentinel_output
), std::string::npos
);
971 TEST_F(URLRequestTest
, FileDirRedirectNoCrash
) {
972 // There is an implicit redirect when loading a file path that matches a
973 // directory and does not end with a slash. Ensure that following such
974 // redirects does not crash. See http://crbug.com/18686.
977 PathService::Get(base::DIR_SOURCE_ROOT
, &path
);
978 path
= path
.Append(FILE_PATH_LITERAL("net"));
979 path
= path
.Append(FILE_PATH_LITERAL("data"));
980 path
= path
.Append(FILE_PATH_LITERAL("url_request_unittest"));
983 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
984 FilePathToFileURL(path
), DEFAULT_PRIORITY
, &d
, NULL
));
986 base::RunLoop().Run();
988 ASSERT_EQ(1, d
.received_redirect_count());
989 ASSERT_LT(0, d
.bytes_received());
990 ASSERT_FALSE(d
.request_failed());
991 ASSERT_TRUE(req
->status().is_success());
995 // Don't accept the url "file:///" on windows. See http://crbug.com/1474.
996 TEST_F(URLRequestTest
, FileDirRedirectSingleSlash
) {
998 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
999 GURL("file:///"), DEFAULT_PRIORITY
, &d
, NULL
));
1001 base::RunLoop().Run();
1003 ASSERT_EQ(1, d
.received_redirect_count());
1004 ASSERT_FALSE(req
->status().is_success());
1006 #endif // defined(OS_WIN)
1008 #endif // !defined(DISABLE_FILE_SUPPORT)
1010 TEST_F(URLRequestTest
, InvalidUrlTest
) {
1013 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
1014 GURL("invalid url"), DEFAULT_PRIORITY
, &d
, NULL
));
1017 EXPECT_TRUE(r
->is_pending());
1019 base::RunLoop().Run();
1020 EXPECT_TRUE(d
.request_failed());
1024 TEST_F(URLRequestTest
, InvalidReferrerTest
) {
1025 TestURLRequestContext context
;
1026 TestNetworkDelegate network_delegate
;
1027 network_delegate
.set_cancel_request_with_policy_violating_referrer(true);
1028 context
.set_network_delegate(&network_delegate
);
1030 scoped_ptr
<URLRequest
> req(context
.CreateRequest(
1031 GURL("http://localhost/"), DEFAULT_PRIORITY
, &d
, NULL
));
1032 req
->SetReferrer("https://somewhere.com/");
1035 base::RunLoop().Run();
1036 EXPECT_TRUE(d
.request_failed());
1040 TEST_F(URLRequestTest
, ResolveShortcutTest
) {
1041 base::FilePath app_path
;
1042 PathService::Get(base::DIR_SOURCE_ROOT
, &app_path
);
1043 app_path
= app_path
.AppendASCII("net");
1044 app_path
= app_path
.AppendASCII("data");
1045 app_path
= app_path
.AppendASCII("url_request_unittest");
1046 app_path
= app_path
.AppendASCII("with-headers.html");
1048 std::wstring lnk_path
= app_path
.value() + L
".lnk";
1050 base::win::ScopedCOMInitializer com_initializer
;
1052 // Temporarily create a shortcut for test
1054 base::win::ScopedComPtr
<IShellLink
> shell
;
1055 ASSERT_TRUE(SUCCEEDED(shell
.CreateInstance(CLSID_ShellLink
, NULL
,
1056 CLSCTX_INPROC_SERVER
)));
1057 base::win::ScopedComPtr
<IPersistFile
> persist
;
1058 ASSERT_TRUE(SUCCEEDED(shell
.QueryInterface(persist
.Receive())));
1059 EXPECT_TRUE(SUCCEEDED(shell
->SetPath(app_path
.value().c_str())));
1060 EXPECT_TRUE(SUCCEEDED(shell
->SetDescription(L
"ResolveShortcutTest")));
1061 EXPECT_TRUE(SUCCEEDED(persist
->Save(lnk_path
.c_str(), TRUE
)));
1066 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
1067 FilePathToFileURL(base::FilePath(lnk_path
)), DEFAULT_PRIORITY
, &d
,
1071 EXPECT_TRUE(r
->is_pending());
1073 base::RunLoop().Run();
1075 WIN32_FILE_ATTRIBUTE_DATA data
;
1076 GetFileAttributesEx(app_path
.value().c_str(),
1077 GetFileExInfoStandard
, &data
);
1078 HANDLE file
= CreateFile(app_path
.value().c_str(), GENERIC_READ
,
1079 FILE_SHARE_READ
, NULL
, OPEN_EXISTING
,
1080 FILE_ATTRIBUTE_NORMAL
, NULL
);
1081 EXPECT_NE(INVALID_HANDLE_VALUE
, file
);
1082 scoped_ptr
<char[]> buffer(new char[data
.nFileSizeLow
]);
1085 result
= ReadFile(file
, buffer
.get(), data
.nFileSizeLow
,
1087 std::string
content(buffer
.get(), read_size
);
1090 EXPECT_TRUE(!r
->is_pending());
1091 EXPECT_EQ(1, d
.received_redirect_count());
1092 EXPECT_EQ(content
, d
.data_received());
1095 // Clean the shortcut
1096 DeleteFile(lnk_path
.c_str());
1098 #endif // defined(OS_WIN)
1100 // Custom URLRequestJobs for use with interceptor tests
1101 class RestartTestJob
: public URLRequestTestJob
{
1103 RestartTestJob(URLRequest
* request
, NetworkDelegate
* network_delegate
)
1104 : URLRequestTestJob(request
, network_delegate
, true) {}
1106 virtual void StartAsync() OVERRIDE
{
1107 this->NotifyRestartRequired();
1110 virtual ~RestartTestJob() {}
1113 class CancelTestJob
: public URLRequestTestJob
{
1115 explicit CancelTestJob(URLRequest
* request
, NetworkDelegate
* network_delegate
)
1116 : URLRequestTestJob(request
, network_delegate
, true) {}
1118 virtual void StartAsync() OVERRIDE
{
1122 virtual ~CancelTestJob() {}
1125 class CancelThenRestartTestJob
: public URLRequestTestJob
{
1127 explicit CancelThenRestartTestJob(URLRequest
* request
,
1128 NetworkDelegate
* network_delegate
)
1129 : URLRequestTestJob(request
, network_delegate
, true) {
1132 virtual void StartAsync() OVERRIDE
{
1134 this->NotifyRestartRequired();
1137 virtual ~CancelThenRestartTestJob() {}
1140 // An Interceptor for use with interceptor tests
1141 class TestInterceptor
: URLRequest::Interceptor
{
1144 : intercept_main_request_(false), restart_main_request_(false),
1145 cancel_main_request_(false), cancel_then_restart_main_request_(false),
1146 simulate_main_network_error_(false),
1147 intercept_redirect_(false), cancel_redirect_request_(false),
1148 intercept_final_response_(false), cancel_final_request_(false),
1149 did_intercept_main_(false), did_restart_main_(false),
1150 did_cancel_main_(false), did_cancel_then_restart_main_(false),
1151 did_simulate_error_main_(false),
1152 did_intercept_redirect_(false), did_cancel_redirect_(false),
1153 did_intercept_final_(false), did_cancel_final_(false) {
1154 URLRequest::Deprecated::RegisterRequestInterceptor(this);
1157 virtual ~TestInterceptor() {
1158 URLRequest::Deprecated::UnregisterRequestInterceptor(this);
1161 virtual URLRequestJob
* MaybeIntercept(
1162 URLRequest
* request
,
1163 NetworkDelegate
* network_delegate
) OVERRIDE
{
1164 if (restart_main_request_
) {
1165 restart_main_request_
= false;
1166 did_restart_main_
= true;
1167 return new RestartTestJob(request
, network_delegate
);
1169 if (cancel_main_request_
) {
1170 cancel_main_request_
= false;
1171 did_cancel_main_
= true;
1172 return new CancelTestJob(request
, network_delegate
);
1174 if (cancel_then_restart_main_request_
) {
1175 cancel_then_restart_main_request_
= false;
1176 did_cancel_then_restart_main_
= true;
1177 return new CancelThenRestartTestJob(request
, network_delegate
);
1179 if (simulate_main_network_error_
) {
1180 simulate_main_network_error_
= false;
1181 did_simulate_error_main_
= true;
1182 // will error since the requeted url is not one of its canned urls
1183 return new URLRequestTestJob(request
, network_delegate
, true);
1185 if (!intercept_main_request_
)
1187 intercept_main_request_
= false;
1188 did_intercept_main_
= true;
1189 URLRequestTestJob
* job
= new URLRequestTestJob(request
,
1194 job
->set_load_timing_info(main_request_load_timing_info_
);
1198 virtual URLRequestJob
* MaybeInterceptRedirect(
1199 URLRequest
* request
,
1200 NetworkDelegate
* network_delegate
,
1201 const GURL
& location
) OVERRIDE
{
1202 if (cancel_redirect_request_
) {
1203 cancel_redirect_request_
= false;
1204 did_cancel_redirect_
= true;
1205 return new CancelTestJob(request
, network_delegate
);
1207 if (!intercept_redirect_
)
1209 intercept_redirect_
= false;
1210 did_intercept_redirect_
= true;
1211 return new URLRequestTestJob(request
,
1218 virtual URLRequestJob
* MaybeInterceptResponse(
1219 URLRequest
* request
, NetworkDelegate
* network_delegate
) OVERRIDE
{
1220 if (cancel_final_request_
) {
1221 cancel_final_request_
= false;
1222 did_cancel_final_
= true;
1223 return new CancelTestJob(request
, network_delegate
);
1225 if (!intercept_final_response_
)
1227 intercept_final_response_
= false;
1228 did_intercept_final_
= true;
1229 return new URLRequestTestJob(request
,
1236 // Whether to intercept the main request, and if so the response to return and
1237 // the LoadTimingInfo to use.
1238 bool intercept_main_request_
;
1239 std::string main_headers_
;
1240 std::string main_data_
;
1241 LoadTimingInfo main_request_load_timing_info_
;
1243 // Other actions we take at MaybeIntercept time
1244 bool restart_main_request_
;
1245 bool cancel_main_request_
;
1246 bool cancel_then_restart_main_request_
;
1247 bool simulate_main_network_error_
;
1249 // Whether to intercept redirects, and if so the response to return.
1250 bool intercept_redirect_
;
1251 std::string redirect_headers_
;
1252 std::string redirect_data_
;
1254 // Other actions we can take at MaybeInterceptRedirect time
1255 bool cancel_redirect_request_
;
1257 // Whether to intercept final response, and if so the response to return.
1258 bool intercept_final_response_
;
1259 std::string final_headers_
;
1260 std::string final_data_
;
1262 // Other actions we can take at MaybeInterceptResponse time
1263 bool cancel_final_request_
;
1265 // If we did something or not
1266 bool did_intercept_main_
;
1267 bool did_restart_main_
;
1268 bool did_cancel_main_
;
1269 bool did_cancel_then_restart_main_
;
1270 bool did_simulate_error_main_
;
1271 bool did_intercept_redirect_
;
1272 bool did_cancel_redirect_
;
1273 bool did_intercept_final_
;
1274 bool did_cancel_final_
;
1276 // Static getters for canned response header and data strings
1278 static std::string
ok_data() {
1279 return URLRequestTestJob::test_data_1();
1282 static std::string
ok_headers() {
1283 return URLRequestTestJob::test_headers();
1286 static std::string
redirect_data() {
1287 return std::string();
1290 static std::string
redirect_headers() {
1291 return URLRequestTestJob::test_redirect_headers();
1294 static std::string
error_data() {
1295 return std::string("ohhh nooooo mr. bill!");
1298 static std::string
error_headers() {
1299 return URLRequestTestJob::test_error_headers();
1303 TEST_F(URLRequestTest
, Intercept
) {
1304 TestInterceptor interceptor
;
1306 // intercept the main request and respond with a simple response
1307 interceptor
.intercept_main_request_
= true;
1308 interceptor
.main_headers_
= TestInterceptor::ok_headers();
1309 interceptor
.main_data_
= TestInterceptor::ok_data();
1312 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
1313 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY
, &d
, NULL
));
1314 base::SupportsUserData::Data
* user_data0
= new base::SupportsUserData::Data();
1315 base::SupportsUserData::Data
* user_data1
= new base::SupportsUserData::Data();
1316 base::SupportsUserData::Data
* user_data2
= new base::SupportsUserData::Data();
1317 req
->SetUserData(NULL
, user_data0
);
1318 req
->SetUserData(&user_data1
, user_data1
);
1319 req
->SetUserData(&user_data2
, user_data2
);
1320 req
->set_method("GET");
1322 base::RunLoop().Run();
1324 // Make sure we can retrieve our specific user data
1325 EXPECT_EQ(user_data0
, req
->GetUserData(NULL
));
1326 EXPECT_EQ(user_data1
, req
->GetUserData(&user_data1
));
1327 EXPECT_EQ(user_data2
, req
->GetUserData(&user_data2
));
1329 // Check the interceptor got called as expected
1330 EXPECT_TRUE(interceptor
.did_intercept_main_
);
1332 // Check we got one good response
1333 EXPECT_TRUE(req
->status().is_success());
1334 EXPECT_EQ(200, req
->response_headers()->response_code());
1335 EXPECT_EQ(TestInterceptor::ok_data(), d
.data_received());
1336 EXPECT_EQ(1, d
.response_started_count());
1337 EXPECT_EQ(0, d
.received_redirect_count());
1340 TEST_F(URLRequestTest
, InterceptRedirect
) {
1341 TestInterceptor interceptor
;
1343 // intercept the main request and respond with a redirect
1344 interceptor
.intercept_main_request_
= true;
1345 interceptor
.main_headers_
= TestInterceptor::redirect_headers();
1346 interceptor
.main_data_
= TestInterceptor::redirect_data();
1348 // intercept that redirect and respond a final OK response
1349 interceptor
.intercept_redirect_
= true;
1350 interceptor
.redirect_headers_
= TestInterceptor::ok_headers();
1351 interceptor
.redirect_data_
= TestInterceptor::ok_data();
1354 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
1355 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY
, &d
, NULL
));
1356 req
->set_method("GET");
1358 base::RunLoop().Run();
1360 // Check the interceptor got called as expected
1361 EXPECT_TRUE(interceptor
.did_intercept_main_
);
1362 EXPECT_TRUE(interceptor
.did_intercept_redirect_
);
1364 // Check we got one good response
1365 EXPECT_TRUE(req
->status().is_success());
1366 if (req
->status().is_success()) {
1367 EXPECT_EQ(200, req
->response_headers()->response_code());
1369 EXPECT_EQ(TestInterceptor::ok_data(), d
.data_received());
1370 EXPECT_EQ(1, d
.response_started_count());
1371 EXPECT_EQ(0, d
.received_redirect_count());
1374 TEST_F(URLRequestTest
, InterceptServerError
) {
1375 TestInterceptor interceptor
;
1377 // intercept the main request to generate a server error response
1378 interceptor
.intercept_main_request_
= true;
1379 interceptor
.main_headers_
= TestInterceptor::error_headers();
1380 interceptor
.main_data_
= TestInterceptor::error_data();
1382 // intercept that error and respond with an OK response
1383 interceptor
.intercept_final_response_
= true;
1384 interceptor
.final_headers_
= TestInterceptor::ok_headers();
1385 interceptor
.final_data_
= TestInterceptor::ok_data();
1388 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
1389 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY
, &d
, NULL
));
1390 req
->set_method("GET");
1392 base::RunLoop().Run();
1394 // Check the interceptor got called as expected
1395 EXPECT_TRUE(interceptor
.did_intercept_main_
);
1396 EXPECT_TRUE(interceptor
.did_intercept_final_
);
1398 // Check we got one good response
1399 EXPECT_TRUE(req
->status().is_success());
1400 EXPECT_EQ(200, req
->response_headers()->response_code());
1401 EXPECT_EQ(TestInterceptor::ok_data(), d
.data_received());
1402 EXPECT_EQ(1, d
.response_started_count());
1403 EXPECT_EQ(0, d
.received_redirect_count());
1406 TEST_F(URLRequestTest
, InterceptNetworkError
) {
1407 TestInterceptor interceptor
;
1409 // intercept the main request to simulate a network error
1410 interceptor
.simulate_main_network_error_
= true;
1412 // intercept that error and respond with an OK response
1413 interceptor
.intercept_final_response_
= true;
1414 interceptor
.final_headers_
= TestInterceptor::ok_headers();
1415 interceptor
.final_data_
= TestInterceptor::ok_data();
1418 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
1419 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY
, &d
, NULL
));
1420 req
->set_method("GET");
1422 base::RunLoop().Run();
1424 // Check the interceptor got called as expected
1425 EXPECT_TRUE(interceptor
.did_simulate_error_main_
);
1426 EXPECT_TRUE(interceptor
.did_intercept_final_
);
1428 // Check we received one good response
1429 EXPECT_TRUE(req
->status().is_success());
1430 EXPECT_EQ(200, req
->response_headers()->response_code());
1431 EXPECT_EQ(TestInterceptor::ok_data(), d
.data_received());
1432 EXPECT_EQ(1, d
.response_started_count());
1433 EXPECT_EQ(0, d
.received_redirect_count());
1436 TEST_F(URLRequestTest
, InterceptRestartRequired
) {
1437 TestInterceptor interceptor
;
1439 // restart the main request
1440 interceptor
.restart_main_request_
= true;
1442 // then intercept the new main request and respond with an OK response
1443 interceptor
.intercept_main_request_
= true;
1444 interceptor
.main_headers_
= TestInterceptor::ok_headers();
1445 interceptor
.main_data_
= TestInterceptor::ok_data();
1448 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
1449 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY
, &d
, NULL
));
1450 req
->set_method("GET");
1452 base::RunLoop().Run();
1454 // Check the interceptor got called as expected
1455 EXPECT_TRUE(interceptor
.did_restart_main_
);
1456 EXPECT_TRUE(interceptor
.did_intercept_main_
);
1458 // Check we received one good response
1459 EXPECT_TRUE(req
->status().is_success());
1460 if (req
->status().is_success()) {
1461 EXPECT_EQ(200, req
->response_headers()->response_code());
1463 EXPECT_EQ(TestInterceptor::ok_data(), d
.data_received());
1464 EXPECT_EQ(1, d
.response_started_count());
1465 EXPECT_EQ(0, d
.received_redirect_count());
1468 TEST_F(URLRequestTest
, InterceptRespectsCancelMain
) {
1469 TestInterceptor interceptor
;
1471 // intercept the main request and cancel from within the restarted job
1472 interceptor
.cancel_main_request_
= true;
1474 // setup to intercept final response and override it with an OK response
1475 interceptor
.intercept_final_response_
= true;
1476 interceptor
.final_headers_
= TestInterceptor::ok_headers();
1477 interceptor
.final_data_
= TestInterceptor::ok_data();
1480 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
1481 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY
, &d
, NULL
));
1482 req
->set_method("GET");
1484 base::RunLoop().Run();
1486 // Check the interceptor got called as expected
1487 EXPECT_TRUE(interceptor
.did_cancel_main_
);
1488 EXPECT_FALSE(interceptor
.did_intercept_final_
);
1490 // Check we see a canceled request
1491 EXPECT_FALSE(req
->status().is_success());
1492 EXPECT_EQ(URLRequestStatus::CANCELED
, req
->status().status());
1495 TEST_F(URLRequestTest
, InterceptRespectsCancelRedirect
) {
1496 TestInterceptor interceptor
;
1498 // intercept the main request and respond with a redirect
1499 interceptor
.intercept_main_request_
= true;
1500 interceptor
.main_headers_
= TestInterceptor::redirect_headers();
1501 interceptor
.main_data_
= TestInterceptor::redirect_data();
1503 // intercept the redirect and cancel from within that job
1504 interceptor
.cancel_redirect_request_
= true;
1506 // setup to intercept final response and override it with an OK response
1507 interceptor
.intercept_final_response_
= true;
1508 interceptor
.final_headers_
= TestInterceptor::ok_headers();
1509 interceptor
.final_data_
= TestInterceptor::ok_data();
1512 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
1513 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY
, &d
, NULL
));
1514 req
->set_method("GET");
1516 base::RunLoop().Run();
1518 // Check the interceptor got called as expected
1519 EXPECT_TRUE(interceptor
.did_intercept_main_
);
1520 EXPECT_TRUE(interceptor
.did_cancel_redirect_
);
1521 EXPECT_FALSE(interceptor
.did_intercept_final_
);
1523 // Check we see a canceled request
1524 EXPECT_FALSE(req
->status().is_success());
1525 EXPECT_EQ(URLRequestStatus::CANCELED
, req
->status().status());
1528 TEST_F(URLRequestTest
, InterceptRespectsCancelFinal
) {
1529 TestInterceptor interceptor
;
1531 // intercept the main request to simulate a network error
1532 interceptor
.simulate_main_network_error_
= true;
1534 // setup to intercept final response and cancel from within that job
1535 interceptor
.cancel_final_request_
= true;
1538 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
1539 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY
, &d
, NULL
));
1540 req
->set_method("GET");
1542 base::RunLoop().Run();
1544 // Check the interceptor got called as expected
1545 EXPECT_TRUE(interceptor
.did_simulate_error_main_
);
1546 EXPECT_TRUE(interceptor
.did_cancel_final_
);
1548 // Check we see a canceled request
1549 EXPECT_FALSE(req
->status().is_success());
1550 EXPECT_EQ(URLRequestStatus::CANCELED
, req
->status().status());
1553 TEST_F(URLRequestTest
, InterceptRespectsCancelInRestart
) {
1554 TestInterceptor interceptor
;
1556 // intercept the main request and cancel then restart from within that job
1557 interceptor
.cancel_then_restart_main_request_
= true;
1559 // setup to intercept final response and override it with an OK response
1560 interceptor
.intercept_final_response_
= true;
1561 interceptor
.final_headers_
= TestInterceptor::ok_headers();
1562 interceptor
.final_data_
= TestInterceptor::ok_data();
1565 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
1566 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY
, &d
, NULL
));
1567 req
->set_method("GET");
1569 base::RunLoop().Run();
1571 // Check the interceptor got called as expected
1572 EXPECT_TRUE(interceptor
.did_cancel_then_restart_main_
);
1573 EXPECT_FALSE(interceptor
.did_intercept_final_
);
1575 // Check we see a canceled request
1576 EXPECT_FALSE(req
->status().is_success());
1577 EXPECT_EQ(URLRequestStatus::CANCELED
, req
->status().status());
1580 LoadTimingInfo
RunLoadTimingTest(const LoadTimingInfo
& job_load_timing
,
1581 URLRequestContext
* context
) {
1582 TestInterceptor interceptor
;
1583 interceptor
.intercept_main_request_
= true;
1584 interceptor
.main_request_load_timing_info_
= job_load_timing
;
1586 scoped_ptr
<URLRequest
> req(context
->CreateRequest(
1587 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY
, &d
, NULL
));
1589 base::RunLoop().Run();
1591 LoadTimingInfo resulting_load_timing
;
1592 req
->GetLoadTimingInfo(&resulting_load_timing
);
1594 // None of these should be modified by the URLRequest.
1595 EXPECT_EQ(job_load_timing
.socket_reused
, resulting_load_timing
.socket_reused
);
1596 EXPECT_EQ(job_load_timing
.socket_log_id
, resulting_load_timing
.socket_log_id
);
1597 EXPECT_EQ(job_load_timing
.send_start
, resulting_load_timing
.send_start
);
1598 EXPECT_EQ(job_load_timing
.send_end
, resulting_load_timing
.send_end
);
1599 EXPECT_EQ(job_load_timing
.receive_headers_end
,
1600 resulting_load_timing
.receive_headers_end
);
1602 return resulting_load_timing
;
1605 // "Normal" LoadTimingInfo as returned by a job. Everything is in order, not
1606 // reused. |connect_time_flags| is used to indicate if there should be dns
1607 // or SSL times, and |used_proxy| is used for proxy times.
1608 LoadTimingInfo
NormalLoadTimingInfo(base::TimeTicks now
,
1609 int connect_time_flags
,
1611 LoadTimingInfo load_timing
;
1612 load_timing
.socket_log_id
= 1;
1615 load_timing
.proxy_resolve_start
= now
+ base::TimeDelta::FromDays(1);
1616 load_timing
.proxy_resolve_end
= now
+ base::TimeDelta::FromDays(2);
1619 LoadTimingInfo::ConnectTiming
& connect_timing
= load_timing
.connect_timing
;
1620 if (connect_time_flags
& CONNECT_TIMING_HAS_DNS_TIMES
) {
1621 connect_timing
.dns_start
= now
+ base::TimeDelta::FromDays(3);
1622 connect_timing
.dns_end
= now
+ base::TimeDelta::FromDays(4);
1624 connect_timing
.connect_start
= now
+ base::TimeDelta::FromDays(5);
1625 if (connect_time_flags
& CONNECT_TIMING_HAS_SSL_TIMES
) {
1626 connect_timing
.ssl_start
= now
+ base::TimeDelta::FromDays(6);
1627 connect_timing
.ssl_end
= now
+ base::TimeDelta::FromDays(7);
1629 connect_timing
.connect_end
= now
+ base::TimeDelta::FromDays(8);
1631 load_timing
.send_start
= now
+ base::TimeDelta::FromDays(9);
1632 load_timing
.send_end
= now
+ base::TimeDelta::FromDays(10);
1633 load_timing
.receive_headers_end
= now
+ base::TimeDelta::FromDays(11);
1637 // Same as above, but in the case of a reused socket.
1638 LoadTimingInfo
NormalLoadTimingInfoReused(base::TimeTicks now
,
1640 LoadTimingInfo load_timing
;
1641 load_timing
.socket_log_id
= 1;
1642 load_timing
.socket_reused
= true;
1645 load_timing
.proxy_resolve_start
= now
+ base::TimeDelta::FromDays(1);
1646 load_timing
.proxy_resolve_end
= now
+ base::TimeDelta::FromDays(2);
1649 load_timing
.send_start
= now
+ base::TimeDelta::FromDays(9);
1650 load_timing
.send_end
= now
+ base::TimeDelta::FromDays(10);
1651 load_timing
.receive_headers_end
= now
+ base::TimeDelta::FromDays(11);
1655 // Basic test that the intercept + load timing tests work.
1656 TEST_F(URLRequestTest
, InterceptLoadTiming
) {
1657 base::TimeTicks now
= base::TimeTicks::Now();
1658 LoadTimingInfo job_load_timing
=
1659 NormalLoadTimingInfo(now
, CONNECT_TIMING_HAS_DNS_TIMES
, false);
1661 LoadTimingInfo load_timing_result
=
1662 RunLoadTimingTest(job_load_timing
, &default_context_
);
1664 // Nothing should have been changed by the URLRequest.
1665 EXPECT_EQ(job_load_timing
.proxy_resolve_start
,
1666 load_timing_result
.proxy_resolve_start
);
1667 EXPECT_EQ(job_load_timing
.proxy_resolve_end
,
1668 load_timing_result
.proxy_resolve_end
);
1669 EXPECT_EQ(job_load_timing
.connect_timing
.dns_start
,
1670 load_timing_result
.connect_timing
.dns_start
);
1671 EXPECT_EQ(job_load_timing
.connect_timing
.dns_end
,
1672 load_timing_result
.connect_timing
.dns_end
);
1673 EXPECT_EQ(job_load_timing
.connect_timing
.connect_start
,
1674 load_timing_result
.connect_timing
.connect_start
);
1675 EXPECT_EQ(job_load_timing
.connect_timing
.connect_end
,
1676 load_timing_result
.connect_timing
.connect_end
);
1677 EXPECT_EQ(job_load_timing
.connect_timing
.ssl_start
,
1678 load_timing_result
.connect_timing
.ssl_start
);
1679 EXPECT_EQ(job_load_timing
.connect_timing
.ssl_end
,
1680 load_timing_result
.connect_timing
.ssl_end
);
1682 // Redundant sanity check.
1683 TestLoadTimingNotReused(load_timing_result
, CONNECT_TIMING_HAS_DNS_TIMES
);
1686 // Another basic test, with proxy and SSL times, but no DNS times.
1687 TEST_F(URLRequestTest
, InterceptLoadTimingProxy
) {
1688 base::TimeTicks now
= base::TimeTicks::Now();
1689 LoadTimingInfo job_load_timing
=
1690 NormalLoadTimingInfo(now
, CONNECT_TIMING_HAS_SSL_TIMES
, true);
1692 LoadTimingInfo load_timing_result
=
1693 RunLoadTimingTest(job_load_timing
, &default_context_
);
1695 // Nothing should have been changed by the URLRequest.
1696 EXPECT_EQ(job_load_timing
.proxy_resolve_start
,
1697 load_timing_result
.proxy_resolve_start
);
1698 EXPECT_EQ(job_load_timing
.proxy_resolve_end
,
1699 load_timing_result
.proxy_resolve_end
);
1700 EXPECT_EQ(job_load_timing
.connect_timing
.dns_start
,
1701 load_timing_result
.connect_timing
.dns_start
);
1702 EXPECT_EQ(job_load_timing
.connect_timing
.dns_end
,
1703 load_timing_result
.connect_timing
.dns_end
);
1704 EXPECT_EQ(job_load_timing
.connect_timing
.connect_start
,
1705 load_timing_result
.connect_timing
.connect_start
);
1706 EXPECT_EQ(job_load_timing
.connect_timing
.connect_end
,
1707 load_timing_result
.connect_timing
.connect_end
);
1708 EXPECT_EQ(job_load_timing
.connect_timing
.ssl_start
,
1709 load_timing_result
.connect_timing
.ssl_start
);
1710 EXPECT_EQ(job_load_timing
.connect_timing
.ssl_end
,
1711 load_timing_result
.connect_timing
.ssl_end
);
1713 // Redundant sanity check.
1714 TestLoadTimingNotReusedWithProxy(load_timing_result
,
1715 CONNECT_TIMING_HAS_SSL_TIMES
);
1718 // Make sure that URLRequest correctly adjusts proxy times when they're before
1719 // |request_start|, due to already having a connected socket. This happens in
1720 // the case of reusing a SPDY session. The connected socket is not considered
1721 // reused in this test (May be a preconnect).
1723 // To mix things up from the test above, assumes DNS times but no SSL times.
1724 TEST_F(URLRequestTest
, InterceptLoadTimingEarlyProxyResolution
) {
1725 base::TimeTicks now
= base::TimeTicks::Now();
1726 LoadTimingInfo job_load_timing
=
1727 NormalLoadTimingInfo(now
, CONNECT_TIMING_HAS_DNS_TIMES
, true);
1728 job_load_timing
.proxy_resolve_start
= now
- base::TimeDelta::FromDays(6);
1729 job_load_timing
.proxy_resolve_end
= now
- base::TimeDelta::FromDays(5);
1730 job_load_timing
.connect_timing
.dns_start
= now
- base::TimeDelta::FromDays(4);
1731 job_load_timing
.connect_timing
.dns_end
= now
- base::TimeDelta::FromDays(3);
1732 job_load_timing
.connect_timing
.connect_start
=
1733 now
- base::TimeDelta::FromDays(2);
1734 job_load_timing
.connect_timing
.connect_end
=
1735 now
- base::TimeDelta::FromDays(1);
1737 LoadTimingInfo load_timing_result
=
1738 RunLoadTimingTest(job_load_timing
, &default_context_
);
1740 // Proxy times, connect times, and DNS times should all be replaced with
1742 EXPECT_EQ(load_timing_result
.request_start
,
1743 load_timing_result
.proxy_resolve_start
);
1744 EXPECT_EQ(load_timing_result
.request_start
,
1745 load_timing_result
.proxy_resolve_end
);
1746 EXPECT_EQ(load_timing_result
.request_start
,
1747 load_timing_result
.connect_timing
.dns_start
);
1748 EXPECT_EQ(load_timing_result
.request_start
,
1749 load_timing_result
.connect_timing
.dns_end
);
1750 EXPECT_EQ(load_timing_result
.request_start
,
1751 load_timing_result
.connect_timing
.connect_start
);
1752 EXPECT_EQ(load_timing_result
.request_start
,
1753 load_timing_result
.connect_timing
.connect_end
);
1755 // Other times should have been left null.
1756 TestLoadTimingNotReusedWithProxy(load_timing_result
,
1757 CONNECT_TIMING_HAS_DNS_TIMES
);
1760 // Same as above, but in the reused case.
1761 TEST_F(URLRequestTest
, InterceptLoadTimingEarlyProxyResolutionReused
) {
1762 base::TimeTicks now
= base::TimeTicks::Now();
1763 LoadTimingInfo job_load_timing
= NormalLoadTimingInfoReused(now
, true);
1764 job_load_timing
.proxy_resolve_start
= now
- base::TimeDelta::FromDays(4);
1765 job_load_timing
.proxy_resolve_end
= now
- base::TimeDelta::FromDays(3);
1767 LoadTimingInfo load_timing_result
=
1768 RunLoadTimingTest(job_load_timing
, &default_context_
);
1770 // Proxy times and connect times should all be replaced with request_start.
1771 EXPECT_EQ(load_timing_result
.request_start
,
1772 load_timing_result
.proxy_resolve_start
);
1773 EXPECT_EQ(load_timing_result
.request_start
,
1774 load_timing_result
.proxy_resolve_end
);
1776 // Other times should have been left null.
1777 TestLoadTimingReusedWithProxy(load_timing_result
);
1780 // Make sure that URLRequest correctly adjusts connect times when they're before
1781 // |request_start|, due to reusing a connected socket. The connected socket is
1782 // not considered reused in this test (May be a preconnect).
1784 // To mix things up, the request has SSL times, but no DNS times.
1785 TEST_F(URLRequestTest
, InterceptLoadTimingEarlyConnect
) {
1786 base::TimeTicks now
= base::TimeTicks::Now();
1787 LoadTimingInfo job_load_timing
=
1788 NormalLoadTimingInfo(now
, CONNECT_TIMING_HAS_SSL_TIMES
, false);
1789 job_load_timing
.connect_timing
.connect_start
=
1790 now
- base::TimeDelta::FromDays(1);
1791 job_load_timing
.connect_timing
.ssl_start
= now
- base::TimeDelta::FromDays(2);
1792 job_load_timing
.connect_timing
.ssl_end
= now
- base::TimeDelta::FromDays(3);
1793 job_load_timing
.connect_timing
.connect_end
=
1794 now
- base::TimeDelta::FromDays(4);
1796 LoadTimingInfo load_timing_result
=
1797 RunLoadTimingTest(job_load_timing
, &default_context_
);
1799 // Connect times, and SSL times should be replaced with request_start.
1800 EXPECT_EQ(load_timing_result
.request_start
,
1801 load_timing_result
.connect_timing
.connect_start
);
1802 EXPECT_EQ(load_timing_result
.request_start
,
1803 load_timing_result
.connect_timing
.ssl_start
);
1804 EXPECT_EQ(load_timing_result
.request_start
,
1805 load_timing_result
.connect_timing
.ssl_end
);
1806 EXPECT_EQ(load_timing_result
.request_start
,
1807 load_timing_result
.connect_timing
.connect_end
);
1809 // Other times should have been left null.
1810 TestLoadTimingNotReused(load_timing_result
, CONNECT_TIMING_HAS_SSL_TIMES
);
1813 // Make sure that URLRequest correctly adjusts connect times when they're before
1814 // |request_start|, due to reusing a connected socket in the case that there
1815 // are also proxy times. The connected socket is not considered reused in this
1816 // test (May be a preconnect).
1818 // In this test, there are no SSL or DNS times.
1819 TEST_F(URLRequestTest
, InterceptLoadTimingEarlyConnectWithProxy
) {
1820 base::TimeTicks now
= base::TimeTicks::Now();
1821 LoadTimingInfo job_load_timing
=
1822 NormalLoadTimingInfo(now
, CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY
, true);
1823 job_load_timing
.connect_timing
.connect_start
=
1824 now
- base::TimeDelta::FromDays(1);
1825 job_load_timing
.connect_timing
.connect_end
=
1826 now
- base::TimeDelta::FromDays(2);
1828 LoadTimingInfo load_timing_result
=
1829 RunLoadTimingTest(job_load_timing
, &default_context_
);
1831 // Connect times should be replaced with proxy_resolve_end.
1832 EXPECT_EQ(load_timing_result
.proxy_resolve_end
,
1833 load_timing_result
.connect_timing
.connect_start
);
1834 EXPECT_EQ(load_timing_result
.proxy_resolve_end
,
1835 load_timing_result
.connect_timing
.connect_end
);
1837 // Other times should have been left null.
1838 TestLoadTimingNotReusedWithProxy(load_timing_result
,
1839 CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY
);
1842 // Check that two different URL requests have different identifiers.
1843 TEST_F(URLRequestTest
, Identifiers
) {
1845 TestURLRequestContext context
;
1846 scoped_ptr
<URLRequest
> req(context
.CreateRequest(
1847 GURL("http://example.com"), DEFAULT_PRIORITY
, &d
, NULL
));
1848 scoped_ptr
<URLRequest
> other_req(context
.CreateRequest(
1849 GURL("http://example.com"), DEFAULT_PRIORITY
, &d
, NULL
));
1851 ASSERT_NE(req
->identifier(), other_req
->identifier());
1854 // Check that a failure to connect to the proxy is reported to the network
1856 TEST_F(URLRequestTest
, NetworkDelegateProxyError
) {
1857 MockHostResolver host_resolver
;
1858 host_resolver
.rules()->AddSimulatedFailure("*");
1860 TestNetworkDelegate network_delegate
; // Must outlive URLRequests.
1861 TestURLRequestContextWithProxy
context("myproxy:70", &network_delegate
);
1864 scoped_ptr
<URLRequest
> req(context
.CreateRequest(
1865 GURL("http://example.com"), DEFAULT_PRIORITY
, &d
, NULL
));
1866 req
->set_method("GET");
1869 base::RunLoop().Run();
1871 // Check we see a failed request.
1872 EXPECT_FALSE(req
->status().is_success());
1873 // The proxy server is not set before failure.
1874 EXPECT_TRUE(req
->proxy_server().IsEmpty());
1875 EXPECT_EQ(URLRequestStatus::FAILED
, req
->status().status());
1876 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED
, req
->status().error());
1878 EXPECT_EQ(1, network_delegate
.error_count());
1879 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED
, network_delegate
.last_error());
1880 EXPECT_EQ(1, network_delegate
.completed_requests());
1883 // Make sure that NetworkDelegate::NotifyCompleted is called if
1884 // content is empty.
1885 TEST_F(URLRequestTest
, RequestCompletionForEmptyResponse
) {
1887 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
1888 GURL("data:,"), DEFAULT_PRIORITY
, &d
, NULL
));
1890 base::RunLoop().Run();
1891 EXPECT_EQ("", d
.data_received());
1892 EXPECT_EQ(1, default_network_delegate_
.completed_requests());
1895 // Make sure that SetPriority actually sets the URLRequest's priority
1896 // correctly, both before and after start.
1897 TEST_F(URLRequestTest
, SetPriorityBasic
) {
1899 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
1900 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY
, &d
, NULL
));
1901 EXPECT_EQ(DEFAULT_PRIORITY
, req
->priority());
1903 req
->SetPriority(LOW
);
1904 EXPECT_EQ(LOW
, req
->priority());
1907 EXPECT_EQ(LOW
, req
->priority());
1909 req
->SetPriority(MEDIUM
);
1910 EXPECT_EQ(MEDIUM
, req
->priority());
1913 // Make sure that URLRequest calls SetPriority on a job before calling
1915 TEST_F(URLRequestTest
, SetJobPriorityBeforeJobStart
) {
1917 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
1918 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY
, &d
, NULL
));
1919 EXPECT_EQ(DEFAULT_PRIORITY
, req
->priority());
1921 scoped_refptr
<URLRequestTestJob
> job
=
1922 new URLRequestTestJob(req
.get(), &default_network_delegate_
);
1923 AddTestInterceptor()->set_main_intercept_job(job
.get());
1924 EXPECT_EQ(DEFAULT_PRIORITY
, job
->priority());
1926 req
->SetPriority(LOW
);
1929 EXPECT_EQ(LOW
, job
->priority());
1932 // Make sure that URLRequest passes on its priority updates to its
1934 TEST_F(URLRequestTest
, SetJobPriority
) {
1936 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
1937 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY
, &d
, NULL
));
1939 scoped_refptr
<URLRequestTestJob
> job
=
1940 new URLRequestTestJob(req
.get(), &default_network_delegate_
);
1941 AddTestInterceptor()->set_main_intercept_job(job
.get());
1943 req
->SetPriority(LOW
);
1945 EXPECT_EQ(LOW
, job
->priority());
1947 req
->SetPriority(MEDIUM
);
1948 EXPECT_EQ(MEDIUM
, req
->priority());
1949 EXPECT_EQ(MEDIUM
, job
->priority());
1952 // Setting the IGNORE_LIMITS load flag should be okay if the priority
1953 // is MAXIMUM_PRIORITY.
1954 TEST_F(URLRequestTest
, PriorityIgnoreLimits
) {
1956 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
1957 GURL("http://test_intercept/foo"), MAXIMUM_PRIORITY
, &d
, NULL
));
1958 EXPECT_EQ(MAXIMUM_PRIORITY
, req
->priority());
1960 scoped_refptr
<URLRequestTestJob
> job
=
1961 new URLRequestTestJob(req
.get(), &default_network_delegate_
);
1962 AddTestInterceptor()->set_main_intercept_job(job
.get());
1964 req
->SetLoadFlags(LOAD_IGNORE_LIMITS
);
1965 EXPECT_EQ(MAXIMUM_PRIORITY
, req
->priority());
1967 req
->SetPriority(MAXIMUM_PRIORITY
);
1968 EXPECT_EQ(MAXIMUM_PRIORITY
, req
->priority());
1971 EXPECT_EQ(MAXIMUM_PRIORITY
, req
->priority());
1972 EXPECT_EQ(MAXIMUM_PRIORITY
, job
->priority());
1975 // TODO(droger): Support SpawnedTestServer on iOS (see http://crbug.com/148666).
1976 #if !defined(OS_IOS)
1977 // A subclass of SpawnedTestServer that uses a statically-configured hostname.
1978 // This is to work around mysterious failures in chrome_frame_net_tests. See:
1979 // http://crbug.com/114369
1980 // TODO(erikwright): remove or update as needed; see http://crbug.com/334634.
1981 class LocalHttpTestServer
: public SpawnedTestServer
{
1983 explicit LocalHttpTestServer(const base::FilePath
& document_root
)
1984 : SpawnedTestServer(SpawnedTestServer::TYPE_HTTP
,
1985 ScopedCustomUrlRequestTestHttpHost::value(),
1987 LocalHttpTestServer()
1988 : SpawnedTestServer(SpawnedTestServer::TYPE_HTTP
,
1989 ScopedCustomUrlRequestTestHttpHost::value(),
1990 base::FilePath()) {}
1993 TEST_F(URLRequestTest
, DelayedCookieCallback
) {
1994 LocalHttpTestServer test_server
;
1995 ASSERT_TRUE(test_server
.Start());
1997 TestURLRequestContext context
;
1998 scoped_refptr
<DelayedCookieMonster
> delayed_cm
=
1999 new DelayedCookieMonster();
2000 scoped_refptr
<CookieStore
> cookie_store
= delayed_cm
;
2001 context
.set_cookie_store(delayed_cm
.get());
2005 TestNetworkDelegate network_delegate
;
2006 context
.set_network_delegate(&network_delegate
);
2008 scoped_ptr
<URLRequest
> req(context
.CreateRequest(
2009 test_server
.GetURL("set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY
,
2012 base::RunLoop().Run();
2013 EXPECT_EQ(0, network_delegate
.blocked_get_cookies_count());
2014 EXPECT_EQ(0, network_delegate
.blocked_set_cookie_count());
2015 EXPECT_EQ(1, network_delegate
.set_cookie_count());
2018 // Verify that the cookie is set.
2020 TestNetworkDelegate network_delegate
;
2021 context
.set_network_delegate(&network_delegate
);
2023 scoped_ptr
<URLRequest
> req(context
.CreateRequest(
2024 test_server
.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY
, &d
, NULL
));
2026 base::RunLoop().Run();
2028 EXPECT_TRUE(d
.data_received().find("CookieToNotSend=1")
2029 != std::string::npos
);
2030 EXPECT_EQ(0, network_delegate
.blocked_get_cookies_count());
2031 EXPECT_EQ(0, network_delegate
.blocked_set_cookie_count());
2035 TEST_F(URLRequestTest
, DoNotSendCookies
) {
2036 LocalHttpTestServer test_server
;
2037 ASSERT_TRUE(test_server
.Start());
2041 TestNetworkDelegate network_delegate
;
2042 default_context_
.set_network_delegate(&network_delegate
);
2044 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
2045 test_server
.GetURL("set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY
,
2048 base::RunLoop().Run();
2049 EXPECT_EQ(0, network_delegate
.blocked_get_cookies_count());
2050 EXPECT_EQ(0, network_delegate
.blocked_set_cookie_count());
2053 // Verify that the cookie is set.
2055 TestNetworkDelegate network_delegate
;
2056 default_context_
.set_network_delegate(&network_delegate
);
2058 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
2059 test_server
.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY
, &d
, NULL
));
2061 base::RunLoop().Run();
2063 EXPECT_TRUE(d
.data_received().find("CookieToNotSend=1")
2064 != std::string::npos
);
2065 EXPECT_EQ(0, network_delegate
.blocked_get_cookies_count());
2066 EXPECT_EQ(0, network_delegate
.blocked_set_cookie_count());
2069 // Verify that the cookie isn't sent when LOAD_DO_NOT_SEND_COOKIES is set.
2071 TestNetworkDelegate network_delegate
;
2072 default_context_
.set_network_delegate(&network_delegate
);
2074 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
2075 test_server
.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY
, &d
, NULL
));
2076 req
->SetLoadFlags(LOAD_DO_NOT_SEND_COOKIES
);
2078 base::RunLoop().Run();
2080 EXPECT_TRUE(d
.data_received().find("Cookie: CookieToNotSend=1")
2081 == std::string::npos
);
2083 // LOAD_DO_NOT_SEND_COOKIES does not trigger OnGetCookies.
2084 EXPECT_EQ(0, network_delegate
.blocked_get_cookies_count());
2085 EXPECT_EQ(0, network_delegate
.blocked_set_cookie_count());
2089 TEST_F(URLRequestTest
, DoNotSaveCookies
) {
2090 LocalHttpTestServer test_server
;
2091 ASSERT_TRUE(test_server
.Start());
2095 TestNetworkDelegate network_delegate
;
2096 default_context_
.set_network_delegate(&network_delegate
);
2098 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
2099 test_server
.GetURL("set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY
,
2102 base::RunLoop().Run();
2104 EXPECT_EQ(0, network_delegate
.blocked_get_cookies_count());
2105 EXPECT_EQ(0, network_delegate
.blocked_set_cookie_count());
2106 EXPECT_EQ(1, network_delegate
.set_cookie_count());
2109 // Try to set-up another cookie and update the previous cookie.
2111 TestNetworkDelegate network_delegate
;
2112 default_context_
.set_network_delegate(&network_delegate
);
2114 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
2115 test_server
.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
2116 DEFAULT_PRIORITY
, &d
, NULL
));
2117 req
->SetLoadFlags(LOAD_DO_NOT_SAVE_COOKIES
);
2120 base::RunLoop().Run();
2122 // LOAD_DO_NOT_SAVE_COOKIES does not trigger OnSetCookie.
2123 EXPECT_EQ(0, network_delegate
.blocked_get_cookies_count());
2124 EXPECT_EQ(0, network_delegate
.blocked_set_cookie_count());
2125 EXPECT_EQ(0, network_delegate
.set_cookie_count());
2128 // Verify the cookies weren't saved or updated.
2130 TestNetworkDelegate network_delegate
;
2131 default_context_
.set_network_delegate(&network_delegate
);
2133 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
2134 test_server
.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY
, &d
, NULL
));
2136 base::RunLoop().Run();
2138 EXPECT_TRUE(d
.data_received().find("CookieToNotSave=1")
2139 == std::string::npos
);
2140 EXPECT_TRUE(d
.data_received().find("CookieToNotUpdate=2")
2141 != std::string::npos
);
2143 EXPECT_EQ(0, network_delegate
.blocked_get_cookies_count());
2144 EXPECT_EQ(0, network_delegate
.blocked_set_cookie_count());
2145 EXPECT_EQ(0, network_delegate
.set_cookie_count());
2149 TEST_F(URLRequestTest
, DoNotSendCookies_ViaPolicy
) {
2150 LocalHttpTestServer test_server
;
2151 ASSERT_TRUE(test_server
.Start());
2155 TestNetworkDelegate network_delegate
;
2156 default_context_
.set_network_delegate(&network_delegate
);
2158 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
2159 test_server
.GetURL("set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY
,
2162 base::RunLoop().Run();
2164 EXPECT_EQ(0, network_delegate
.blocked_get_cookies_count());
2165 EXPECT_EQ(0, network_delegate
.blocked_set_cookie_count());
2168 // Verify that the cookie is set.
2170 TestNetworkDelegate network_delegate
;
2171 default_context_
.set_network_delegate(&network_delegate
);
2173 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
2174 test_server
.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY
, &d
, NULL
));
2176 base::RunLoop().Run();
2178 EXPECT_TRUE(d
.data_received().find("CookieToNotSend=1")
2179 != std::string::npos
);
2181 EXPECT_EQ(0, network_delegate
.blocked_get_cookies_count());
2182 EXPECT_EQ(0, network_delegate
.blocked_set_cookie_count());
2185 // Verify that the cookie isn't sent.
2187 TestNetworkDelegate network_delegate
;
2188 default_context_
.set_network_delegate(&network_delegate
);
2190 network_delegate
.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES
);
2191 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
2192 test_server
.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY
, &d
, NULL
));
2194 base::RunLoop().Run();
2196 EXPECT_TRUE(d
.data_received().find("Cookie: CookieToNotSend=1")
2197 == std::string::npos
);
2199 EXPECT_EQ(1, network_delegate
.blocked_get_cookies_count());
2200 EXPECT_EQ(0, network_delegate
.blocked_set_cookie_count());
2204 TEST_F(URLRequestTest
, DoNotSaveCookies_ViaPolicy
) {
2205 LocalHttpTestServer test_server
;
2206 ASSERT_TRUE(test_server
.Start());
2210 TestNetworkDelegate network_delegate
;
2211 default_context_
.set_network_delegate(&network_delegate
);
2213 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
2214 test_server
.GetURL("set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY
,
2217 base::RunLoop().Run();
2219 EXPECT_EQ(0, network_delegate
.blocked_get_cookies_count());
2220 EXPECT_EQ(0, network_delegate
.blocked_set_cookie_count());
2223 // Try to set-up another cookie and update the previous cookie.
2225 TestNetworkDelegate network_delegate
;
2226 default_context_
.set_network_delegate(&network_delegate
);
2228 network_delegate
.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE
);
2229 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
2230 test_server
.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
2231 DEFAULT_PRIORITY
, &d
, NULL
));
2234 base::RunLoop().Run();
2236 EXPECT_EQ(0, network_delegate
.blocked_get_cookies_count());
2237 EXPECT_EQ(2, network_delegate
.blocked_set_cookie_count());
2240 // Verify the cookies weren't saved or updated.
2242 TestNetworkDelegate network_delegate
;
2243 default_context_
.set_network_delegate(&network_delegate
);
2245 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
2246 test_server
.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY
, &d
, NULL
));
2248 base::RunLoop().Run();
2250 EXPECT_TRUE(d
.data_received().find("CookieToNotSave=1")
2251 == std::string::npos
);
2252 EXPECT_TRUE(d
.data_received().find("CookieToNotUpdate=2")
2253 != std::string::npos
);
2255 EXPECT_EQ(0, network_delegate
.blocked_get_cookies_count());
2256 EXPECT_EQ(0, network_delegate
.blocked_set_cookie_count());
2260 TEST_F(URLRequestTest
, DoNotSaveEmptyCookies
) {
2261 LocalHttpTestServer test_server
;
2262 ASSERT_TRUE(test_server
.Start());
2264 // Set up an empty cookie.
2266 TestNetworkDelegate network_delegate
;
2267 default_context_
.set_network_delegate(&network_delegate
);
2269 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
2270 test_server
.GetURL("set-cookie"), DEFAULT_PRIORITY
, &d
, NULL
));
2272 base::RunLoop().Run();
2274 EXPECT_EQ(0, network_delegate
.blocked_get_cookies_count());
2275 EXPECT_EQ(0, network_delegate
.blocked_set_cookie_count());
2276 EXPECT_EQ(0, network_delegate
.set_cookie_count());
2280 TEST_F(URLRequestTest
, DoNotSendCookies_ViaPolicy_Async
) {
2281 LocalHttpTestServer test_server
;
2282 ASSERT_TRUE(test_server
.Start());
2286 TestNetworkDelegate network_delegate
;
2287 default_context_
.set_network_delegate(&network_delegate
);
2289 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
2290 test_server
.GetURL("set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY
,
2293 base::RunLoop().Run();
2295 EXPECT_EQ(0, network_delegate
.blocked_get_cookies_count());
2296 EXPECT_EQ(0, network_delegate
.blocked_set_cookie_count());
2299 // Verify that the cookie is set.
2301 TestNetworkDelegate network_delegate
;
2302 default_context_
.set_network_delegate(&network_delegate
);
2304 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
2305 test_server
.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY
, &d
, NULL
));
2307 base::RunLoop().Run();
2309 EXPECT_TRUE(d
.data_received().find("CookieToNotSend=1")
2310 != std::string::npos
);
2312 EXPECT_EQ(0, network_delegate
.blocked_get_cookies_count());
2313 EXPECT_EQ(0, network_delegate
.blocked_set_cookie_count());
2316 // Verify that the cookie isn't sent.
2318 TestNetworkDelegate network_delegate
;
2319 default_context_
.set_network_delegate(&network_delegate
);
2321 network_delegate
.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES
);
2322 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
2323 test_server
.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY
, &d
, NULL
));
2325 base::RunLoop().Run();
2327 EXPECT_TRUE(d
.data_received().find("Cookie: CookieToNotSend=1")
2328 == std::string::npos
);
2330 EXPECT_EQ(1, network_delegate
.blocked_get_cookies_count());
2331 EXPECT_EQ(0, network_delegate
.blocked_set_cookie_count());
2335 TEST_F(URLRequestTest
, DoNotSaveCookies_ViaPolicy_Async
) {
2336 LocalHttpTestServer test_server
;
2337 ASSERT_TRUE(test_server
.Start());
2341 TestNetworkDelegate network_delegate
;
2342 default_context_
.set_network_delegate(&network_delegate
);
2344 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
2345 test_server
.GetURL("set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY
,
2348 base::RunLoop().Run();
2350 EXPECT_EQ(0, network_delegate
.blocked_get_cookies_count());
2351 EXPECT_EQ(0, network_delegate
.blocked_set_cookie_count());
2354 // Try to set-up another cookie and update the previous cookie.
2356 TestNetworkDelegate network_delegate
;
2357 default_context_
.set_network_delegate(&network_delegate
);
2359 network_delegate
.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE
);
2360 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
2361 test_server
.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
2362 DEFAULT_PRIORITY
, &d
, NULL
));
2365 base::RunLoop().Run();
2367 EXPECT_EQ(0, network_delegate
.blocked_get_cookies_count());
2368 EXPECT_EQ(2, network_delegate
.blocked_set_cookie_count());
2371 // Verify the cookies weren't saved or updated.
2373 TestNetworkDelegate network_delegate
;
2374 default_context_
.set_network_delegate(&network_delegate
);
2376 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
2377 test_server
.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY
, &d
, NULL
));
2379 base::RunLoop().Run();
2381 EXPECT_TRUE(d
.data_received().find("CookieToNotSave=1")
2382 == std::string::npos
);
2383 EXPECT_TRUE(d
.data_received().find("CookieToNotUpdate=2")
2384 != std::string::npos
);
2386 EXPECT_EQ(0, network_delegate
.blocked_get_cookies_count());
2387 EXPECT_EQ(0, network_delegate
.blocked_set_cookie_count());
2391 // FixedDateNetworkDelegate swaps out the server's HTTP Date response header
2392 // value for the |fixed_date| argument given to the constructor.
2393 class FixedDateNetworkDelegate
: public TestNetworkDelegate
{
2395 explicit FixedDateNetworkDelegate(const std::string
& fixed_date
)
2396 : fixed_date_(fixed_date
) {}
2397 virtual ~FixedDateNetworkDelegate() {}
2399 // NetworkDelegate implementation
2400 virtual int OnHeadersReceived(
2401 URLRequest
* request
,
2402 const CompletionCallback
& callback
,
2403 const HttpResponseHeaders
* original_response_headers
,
2404 scoped_refptr
<HttpResponseHeaders
>* override_response_headers
,
2405 GURL
* allowed_unsafe_redirect_url
) OVERRIDE
;
2408 std::string fixed_date_
;
2410 DISALLOW_COPY_AND_ASSIGN(FixedDateNetworkDelegate
);
2413 int FixedDateNetworkDelegate::OnHeadersReceived(
2414 URLRequest
* request
,
2415 const CompletionCallback
& callback
,
2416 const HttpResponseHeaders
* original_response_headers
,
2417 scoped_refptr
<HttpResponseHeaders
>* override_response_headers
,
2418 GURL
* allowed_unsafe_redirect_url
) {
2419 HttpResponseHeaders
* new_response_headers
=
2420 new HttpResponseHeaders(original_response_headers
->raw_headers());
2422 new_response_headers
->RemoveHeader("Date");
2423 new_response_headers
->AddHeader("Date: " + fixed_date_
);
2425 *override_response_headers
= new_response_headers
;
2426 return TestNetworkDelegate::OnHeadersReceived(request
,
2428 original_response_headers
,
2429 override_response_headers
,
2430 allowed_unsafe_redirect_url
);
2433 // Test that cookie expiration times are adjusted for server/client clock
2434 // skew and that we handle incorrect timezone specifier "UTC" in HTTP Date
2435 // headers by defaulting to GMT. (crbug.com/135131)
2436 TEST_F(URLRequestTest
, AcceptClockSkewCookieWithWrongDateTimezone
) {
2437 LocalHttpTestServer test_server
;
2438 ASSERT_TRUE(test_server
.Start());
2440 // Set up an expired cookie.
2442 TestNetworkDelegate network_delegate
;
2443 default_context_
.set_network_delegate(&network_delegate
);
2445 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
2447 "set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
2448 DEFAULT_PRIORITY
, &d
, NULL
));
2450 base::RunLoop().Run();
2452 // Verify that the cookie is not set.
2454 TestNetworkDelegate network_delegate
;
2455 default_context_
.set_network_delegate(&network_delegate
);
2457 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
2458 test_server
.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY
, &d
, NULL
));
2460 base::RunLoop().Run();
2462 EXPECT_TRUE(d
.data_received().find("StillGood=1") == std::string::npos
);
2464 // Set up a cookie with clock skew and "UTC" HTTP Date timezone specifier.
2466 FixedDateNetworkDelegate
network_delegate("18-Apr-1977 22:49:13 UTC");
2467 default_context_
.set_network_delegate(&network_delegate
);
2469 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
2471 "set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
2472 DEFAULT_PRIORITY
, &d
, NULL
));
2474 base::RunLoop().Run();
2476 // Verify that the cookie is set.
2478 TestNetworkDelegate network_delegate
;
2479 default_context_
.set_network_delegate(&network_delegate
);
2481 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
2482 test_server
.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY
, &d
, NULL
));
2484 base::RunLoop().Run();
2486 EXPECT_TRUE(d
.data_received().find("StillGood=1") != std::string::npos
);
2491 // Check that it is impossible to change the referrer in the extra headers of
2493 TEST_F(URLRequestTest
, DoNotOverrideReferrer
) {
2494 LocalHttpTestServer test_server
;
2495 ASSERT_TRUE(test_server
.Start());
2497 // If extra headers contain referer and the request contains a referer,
2498 // only the latter shall be respected.
2501 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
2502 test_server
.GetURL("echoheader?Referer"), DEFAULT_PRIORITY
, &d
, NULL
));
2503 req
->SetReferrer("http://foo.com/");
2505 HttpRequestHeaders headers
;
2506 headers
.SetHeader(HttpRequestHeaders::kReferer
, "http://bar.com/");
2507 req
->SetExtraRequestHeaders(headers
);
2510 base::RunLoop().Run();
2512 EXPECT_EQ("http://foo.com/", d
.data_received());
2515 // If extra headers contain a referer but the request does not, no referer
2516 // shall be sent in the header.
2519 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
2520 test_server
.GetURL("echoheader?Referer"), DEFAULT_PRIORITY
, &d
, NULL
));
2522 HttpRequestHeaders headers
;
2523 headers
.SetHeader(HttpRequestHeaders::kReferer
, "http://bar.com/");
2524 req
->SetExtraRequestHeaders(headers
);
2525 req
->SetLoadFlags(LOAD_VALIDATE_CACHE
);
2528 base::RunLoop().Run();
2530 EXPECT_EQ("None", d
.data_received());
2534 class URLRequestTestHTTP
: public URLRequestTest
{
2536 URLRequestTestHTTP()
2537 : test_server_(base::FilePath(FILE_PATH_LITERAL(
2538 "net/data/url_request_unittest"))) {
2542 // Requests |redirect_url|, which must return a HTTP 3xx redirect.
2543 // |request_method| is the method to use for the initial request.
2544 // |redirect_method| is the method that is expected to be used for the second
2545 // request, after redirection.
2546 // If |include_data| is true, data is uploaded with the request. The
2547 // response body is expected to match it exactly, if and only if
2548 // |request_method| == |redirect_method|.
2549 void HTTPRedirectMethodTest(const GURL
& redirect_url
,
2550 const std::string
& request_method
,
2551 const std::string
& redirect_method
,
2552 bool include_data
) {
2553 static const char kData
[] = "hello world";
2555 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
2556 redirect_url
, DEFAULT_PRIORITY
, &d
, NULL
));
2557 req
->set_method(request_method
);
2559 req
->set_upload(make_scoped_ptr(CreateSimpleUploadData(kData
)));
2560 HttpRequestHeaders headers
;
2561 headers
.SetHeader(HttpRequestHeaders::kContentLength
,
2562 base::UintToString(arraysize(kData
) - 1));
2563 req
->SetExtraRequestHeaders(headers
);
2566 base::RunLoop().Run();
2567 EXPECT_EQ(redirect_method
, req
->method());
2568 EXPECT_EQ(URLRequestStatus::SUCCESS
, req
->status().status());
2569 EXPECT_EQ(OK
, req
->status().error());
2571 if (request_method
== redirect_method
) {
2572 EXPECT_EQ(kData
, d
.data_received());
2574 EXPECT_NE(kData
, d
.data_received());
2578 LOG(WARNING
) << "Request method was: " << request_method
;
2581 void HTTPUploadDataOperationTest(const std::string
& method
) {
2582 const int kMsgSize
= 20000; // multiple of 10
2583 const int kIterations
= 50;
2584 char* uploadBytes
= new char[kMsgSize
+1];
2585 char* ptr
= uploadBytes
;
2587 for (int idx
= 0; idx
< kMsgSize
/10; idx
++) {
2588 memcpy(ptr
, "----------", 10);
2590 if (idx
% 100 == 0) {
2597 uploadBytes
[kMsgSize
] = '\0';
2599 for (int i
= 0; i
< kIterations
; ++i
) {
2601 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
2602 test_server_
.GetURL("echo"), DEFAULT_PRIORITY
, &d
, NULL
));
2603 r
->set_method(method
.c_str());
2605 r
->set_upload(make_scoped_ptr(CreateSimpleUploadData(uploadBytes
)));
2608 EXPECT_TRUE(r
->is_pending());
2610 base::RunLoop().Run();
2612 ASSERT_EQ(1, d
.response_started_count())
2613 << "request failed: " << r
->status().status()
2614 << ", os error: " << r
->status().error();
2616 EXPECT_FALSE(d
.received_data_before_response());
2617 EXPECT_EQ(uploadBytes
, d
.data_received());
2619 delete[] uploadBytes
;
2622 void AddChunksToUpload(URLRequest
* r
) {
2623 r
->AppendChunkToUpload("a", 1, false);
2624 r
->AppendChunkToUpload("bcd", 3, false);
2625 r
->AppendChunkToUpload("this is a longer chunk than before.", 35, false);
2626 r
->AppendChunkToUpload("\r\n\r\n", 4, false);
2627 r
->AppendChunkToUpload("0", 1, false);
2628 r
->AppendChunkToUpload("2323", 4, true);
2631 void VerifyReceivedDataMatchesChunks(URLRequest
* r
, TestDelegate
* d
) {
2632 // This should match the chunks sent by AddChunksToUpload().
2633 const std::string expected_data
=
2634 "abcdthis is a longer chunk than before.\r\n\r\n02323";
2636 ASSERT_EQ(1, d
->response_started_count())
2637 << "request failed: " << r
->status().status()
2638 << ", os error: " << r
->status().error();
2640 EXPECT_FALSE(d
->received_data_before_response());
2642 EXPECT_EQ(expected_data
.size(), static_cast<size_t>(d
->bytes_received()));
2643 EXPECT_EQ(expected_data
, d
->data_received());
2646 bool DoManyCookiesRequest(int num_cookies
) {
2648 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
2649 test_server_
.GetURL("set-many-cookies?" +
2650 base::IntToString(num_cookies
)),
2651 DEFAULT_PRIORITY
, &d
, NULL
));
2654 EXPECT_TRUE(r
->is_pending());
2656 base::RunLoop().Run();
2658 bool is_success
= r
->status().is_success();
2661 EXPECT_TRUE(r
->status().error() == ERR_RESPONSE_HEADERS_TOO_BIG
);
2662 // The test server appears to be unable to handle subsequent requests
2663 // after this error is triggered. Force it to restart.
2664 EXPECT_TRUE(test_server_
.Stop());
2665 EXPECT_TRUE(test_server_
.Start());
2671 LocalHttpTestServer test_server_
;
2674 // In this unit test, we're using the HTTPTestServer as a proxy server and
2675 // issuing a CONNECT request with the magic host name "www.redirect.com".
2676 // The HTTPTestServer will return a 302 response, which we should not
2678 TEST_F(URLRequestTestHTTP
, ProxyTunnelRedirectTest
) {
2679 ASSERT_TRUE(test_server_
.Start());
2681 TestNetworkDelegate network_delegate
; // Must outlive URLRequest.
2682 TestURLRequestContextWithProxy
context(
2683 test_server_
.host_port_pair().ToString(), &network_delegate
);
2687 scoped_ptr
<URLRequest
> r(context
.CreateRequest(
2688 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY
, &d
, NULL
));
2690 EXPECT_TRUE(r
->is_pending());
2692 base::RunLoop().Run();
2694 EXPECT_EQ(URLRequestStatus::FAILED
, r
->status().status());
2695 // The proxy server is not set before failure.
2696 EXPECT_TRUE(r
->proxy_server().IsEmpty());
2697 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED
, r
->status().error());
2698 EXPECT_EQ(1, d
.response_started_count());
2699 // We should not have followed the redirect.
2700 EXPECT_EQ(0, d
.received_redirect_count());
2704 // This is the same as the previous test, but checks that the network delegate
2705 // registers the error.
2706 TEST_F(URLRequestTestHTTP
, NetworkDelegateTunnelConnectionFailed
) {
2707 ASSERT_TRUE(test_server_
.Start());
2709 TestNetworkDelegate network_delegate
; // Must outlive URLRequest.
2710 TestURLRequestContextWithProxy
context(
2711 test_server_
.host_port_pair().ToString(), &network_delegate
);
2715 scoped_ptr
<URLRequest
> r(context
.CreateRequest(
2716 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY
, &d
, NULL
));
2718 EXPECT_TRUE(r
->is_pending());
2720 base::RunLoop().Run();
2722 EXPECT_EQ(URLRequestStatus::FAILED
, r
->status().status());
2723 // The proxy server is not set before failure.
2724 EXPECT_TRUE(r
->proxy_server().IsEmpty());
2725 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED
, r
->status().error());
2726 EXPECT_EQ(1, d
.response_started_count());
2727 // We should not have followed the redirect.
2728 EXPECT_EQ(0, d
.received_redirect_count());
2730 EXPECT_EQ(1, network_delegate
.error_count());
2731 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED
, network_delegate
.last_error());
2735 // Tests that we can block and asynchronously return OK in various stages.
2736 TEST_F(URLRequestTestHTTP
, NetworkDelegateBlockAsynchronously
) {
2737 static const BlockingNetworkDelegate::Stage blocking_stages
[] = {
2738 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST
,
2739 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS
,
2740 BlockingNetworkDelegate::ON_HEADERS_RECEIVED
2742 static const size_t blocking_stages_length
= arraysize(blocking_stages
);
2744 ASSERT_TRUE(test_server_
.Start());
2747 BlockingNetworkDelegate
network_delegate(
2748 BlockingNetworkDelegate::USER_CALLBACK
);
2749 network_delegate
.set_block_on(
2750 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST
|
2751 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS
|
2752 BlockingNetworkDelegate::ON_HEADERS_RECEIVED
);
2754 TestURLRequestContext
context(true);
2755 context
.set_network_delegate(&network_delegate
);
2759 scoped_ptr
<URLRequest
> r(context
.CreateRequest(
2760 test_server_
.GetURL("empty.html"), DEFAULT_PRIORITY
, &d
, NULL
));
2763 for (size_t i
= 0; i
< blocking_stages_length
; ++i
) {
2764 base::RunLoop().Run();
2765 EXPECT_EQ(blocking_stages
[i
],
2766 network_delegate
.stage_blocked_for_callback());
2767 network_delegate
.DoCallback(OK
);
2769 base::RunLoop().Run();
2770 EXPECT_EQ(200, r
->GetResponseCode());
2771 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
->status().status());
2772 EXPECT_EQ(1, network_delegate
.created_requests());
2773 EXPECT_EQ(0, network_delegate
.destroyed_requests());
2775 EXPECT_EQ(1, network_delegate
.destroyed_requests());
2778 // Tests that the network delegate can block and cancel a request.
2779 TEST_F(URLRequestTestHTTP
, NetworkDelegateCancelRequest
) {
2780 ASSERT_TRUE(test_server_
.Start());
2783 BlockingNetworkDelegate
network_delegate(
2784 BlockingNetworkDelegate::AUTO_CALLBACK
);
2785 network_delegate
.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST
);
2786 network_delegate
.set_retval(ERR_EMPTY_RESPONSE
);
2788 TestURLRequestContextWithProxy
context(
2789 test_server_
.host_port_pair().ToString(), &network_delegate
);
2792 scoped_ptr
<URLRequest
> r(context
.CreateRequest(
2793 test_server_
.GetURL(std::string()), DEFAULT_PRIORITY
, &d
, NULL
));
2796 base::RunLoop().Run();
2798 EXPECT_EQ(URLRequestStatus::FAILED
, r
->status().status());
2799 // The proxy server is not set before cancellation.
2800 EXPECT_TRUE(r
->proxy_server().IsEmpty());
2801 EXPECT_EQ(ERR_EMPTY_RESPONSE
, r
->status().error());
2802 EXPECT_EQ(1, network_delegate
.created_requests());
2803 EXPECT_EQ(0, network_delegate
.destroyed_requests());
2805 EXPECT_EQ(1, network_delegate
.destroyed_requests());
2808 // Helper function for NetworkDelegateCancelRequestAsynchronously and
2809 // NetworkDelegateCancelRequestSynchronously. Sets up a blocking network
2810 // delegate operating in |block_mode| and a request for |url|. It blocks the
2811 // request in |stage| and cancels it with ERR_BLOCKED_BY_CLIENT.
2812 void NetworkDelegateCancelRequest(BlockingNetworkDelegate::BlockMode block_mode
,
2813 BlockingNetworkDelegate::Stage stage
,
2816 BlockingNetworkDelegate
network_delegate(block_mode
);
2817 network_delegate
.set_retval(ERR_BLOCKED_BY_CLIENT
);
2818 network_delegate
.set_block_on(stage
);
2820 TestURLRequestContext
context(true);
2821 context
.set_network_delegate(&network_delegate
);
2825 scoped_ptr
<URLRequest
> r(context
.CreateRequest(
2826 url
, DEFAULT_PRIORITY
, &d
, NULL
));
2829 base::RunLoop().Run();
2831 EXPECT_EQ(URLRequestStatus::FAILED
, r
->status().status());
2832 // The proxy server is not set before cancellation.
2833 EXPECT_TRUE(r
->proxy_server().IsEmpty());
2834 EXPECT_EQ(ERR_BLOCKED_BY_CLIENT
, r
->status().error());
2835 EXPECT_EQ(1, network_delegate
.created_requests());
2836 EXPECT_EQ(0, network_delegate
.destroyed_requests());
2838 EXPECT_EQ(1, network_delegate
.destroyed_requests());
2841 // The following 3 tests check that the network delegate can cancel a request
2842 // synchronously in various stages of the request.
2843 TEST_F(URLRequestTestHTTP
, NetworkDelegateCancelRequestSynchronously1
) {
2844 ASSERT_TRUE(test_server_
.Start());
2845 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS
,
2846 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST
,
2847 test_server_
.GetURL(std::string()));
2850 TEST_F(URLRequestTestHTTP
, NetworkDelegateCancelRequestSynchronously2
) {
2851 ASSERT_TRUE(test_server_
.Start());
2852 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS
,
2853 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS
,
2854 test_server_
.GetURL(std::string()));
2857 TEST_F(URLRequestTestHTTP
, NetworkDelegateCancelRequestSynchronously3
) {
2858 ASSERT_TRUE(test_server_
.Start());
2859 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS
,
2860 BlockingNetworkDelegate::ON_HEADERS_RECEIVED
,
2861 test_server_
.GetURL(std::string()));
2864 // The following 3 tests check that the network delegate can cancel a request
2865 // asynchronously in various stages of the request.
2866 TEST_F(URLRequestTestHTTP
, NetworkDelegateCancelRequestAsynchronously1
) {
2867 ASSERT_TRUE(test_server_
.Start());
2868 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK
,
2869 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST
,
2870 test_server_
.GetURL(std::string()));
2873 TEST_F(URLRequestTestHTTP
, NetworkDelegateCancelRequestAsynchronously2
) {
2874 ASSERT_TRUE(test_server_
.Start());
2875 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK
,
2876 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS
,
2877 test_server_
.GetURL(std::string()));
2880 TEST_F(URLRequestTestHTTP
, NetworkDelegateCancelRequestAsynchronously3
) {
2881 ASSERT_TRUE(test_server_
.Start());
2882 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK
,
2883 BlockingNetworkDelegate::ON_HEADERS_RECEIVED
,
2884 test_server_
.GetURL(std::string()));
2887 // Tests that the network delegate can block and redirect a request to a new
2889 TEST_F(URLRequestTestHTTP
, NetworkDelegateRedirectRequest
) {
2890 ASSERT_TRUE(test_server_
.Start());
2893 BlockingNetworkDelegate
network_delegate(
2894 BlockingNetworkDelegate::AUTO_CALLBACK
);
2895 network_delegate
.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST
);
2896 GURL
redirect_url(test_server_
.GetURL("simple.html"));
2897 network_delegate
.set_redirect_url(redirect_url
);
2899 TestURLRequestContextWithProxy
context(
2900 test_server_
.host_port_pair().ToString(), &network_delegate
);
2903 GURL
original_url(test_server_
.GetURL("empty.html"));
2904 scoped_ptr
<URLRequest
> r(context
.CreateRequest(
2905 original_url
, DEFAULT_PRIORITY
, &d
, NULL
));
2907 // Quit after hitting the redirect, so can check the headers.
2908 d
.set_quit_on_redirect(true);
2910 base::RunLoop().Run();
2912 // Check headers from URLRequestJob.
2913 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
->status().status());
2914 EXPECT_EQ(307, r
->GetResponseCode());
2915 EXPECT_EQ(307, r
->response_headers()->response_code());
2916 std::string location
;
2917 ASSERT_TRUE(r
->response_headers()->EnumerateHeader(NULL
, "Location",
2919 EXPECT_EQ(redirect_url
, GURL(location
));
2921 // Let the request finish.
2922 r
->FollowDeferredRedirect();
2923 base::RunLoop().Run();
2924 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
->status().status());
2925 EXPECT_TRUE(r
->proxy_server().Equals(test_server_
.host_port_pair()));
2927 1, network_delegate
.observed_before_proxy_headers_sent_callbacks());
2929 network_delegate
.last_observed_proxy().Equals(
2930 test_server_
.host_port_pair()));
2932 EXPECT_EQ(0, r
->status().error());
2933 EXPECT_EQ(redirect_url
, r
->url());
2934 EXPECT_EQ(original_url
, r
->original_url());
2935 EXPECT_EQ(2U, r
->url_chain().size());
2936 EXPECT_EQ(1, network_delegate
.created_requests());
2937 EXPECT_EQ(0, network_delegate
.destroyed_requests());
2939 EXPECT_EQ(1, network_delegate
.destroyed_requests());
2942 // Tests that the network delegate can block and redirect a request to a new
2943 // URL by setting a redirect_url and returning in OnBeforeURLRequest directly.
2944 TEST_F(URLRequestTestHTTP
, NetworkDelegateRedirectRequestSynchronously
) {
2945 ASSERT_TRUE(test_server_
.Start());
2948 BlockingNetworkDelegate
network_delegate(
2949 BlockingNetworkDelegate::SYNCHRONOUS
);
2950 GURL
redirect_url(test_server_
.GetURL("simple.html"));
2951 network_delegate
.set_redirect_url(redirect_url
);
2953 TestURLRequestContextWithProxy
context(
2954 test_server_
.host_port_pair().ToString(), &network_delegate
);
2957 GURL
original_url(test_server_
.GetURL("empty.html"));
2958 scoped_ptr
<URLRequest
> r(context
.CreateRequest(
2959 original_url
, DEFAULT_PRIORITY
, &d
, NULL
));
2961 // Quit after hitting the redirect, so can check the headers.
2962 d
.set_quit_on_redirect(true);
2964 base::RunLoop().Run();
2966 // Check headers from URLRequestJob.
2967 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
->status().status());
2968 EXPECT_EQ(307, r
->GetResponseCode());
2969 EXPECT_EQ(307, r
->response_headers()->response_code());
2970 std::string location
;
2971 ASSERT_TRUE(r
->response_headers()->EnumerateHeader(NULL
, "Location",
2973 EXPECT_EQ(redirect_url
, GURL(location
));
2975 // Let the request finish.
2976 r
->FollowDeferredRedirect();
2977 base::RunLoop().Run();
2979 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
->status().status());
2980 EXPECT_TRUE(r
->proxy_server().Equals(test_server_
.host_port_pair()));
2982 1, network_delegate
.observed_before_proxy_headers_sent_callbacks());
2984 network_delegate
.last_observed_proxy().Equals(
2985 test_server_
.host_port_pair()));
2986 EXPECT_EQ(0, r
->status().error());
2987 EXPECT_EQ(redirect_url
, r
->url());
2988 EXPECT_EQ(original_url
, r
->original_url());
2989 EXPECT_EQ(2U, r
->url_chain().size());
2990 EXPECT_EQ(1, network_delegate
.created_requests());
2991 EXPECT_EQ(0, network_delegate
.destroyed_requests());
2993 EXPECT_EQ(1, network_delegate
.destroyed_requests());
2996 // Tests that redirects caused by the network delegate preserve POST data.
2997 TEST_F(URLRequestTestHTTP
, NetworkDelegateRedirectRequestPost
) {
2998 ASSERT_TRUE(test_server_
.Start());
3000 const char kData
[] = "hello world";
3003 BlockingNetworkDelegate
network_delegate(
3004 BlockingNetworkDelegate::AUTO_CALLBACK
);
3005 network_delegate
.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST
);
3006 GURL
redirect_url(test_server_
.GetURL("echo"));
3007 network_delegate
.set_redirect_url(redirect_url
);
3009 TestURLRequestContext
context(true);
3010 context
.set_network_delegate(&network_delegate
);
3014 GURL
original_url(test_server_
.GetURL("empty.html"));
3015 scoped_ptr
<URLRequest
> r(context
.CreateRequest(
3016 original_url
, DEFAULT_PRIORITY
, &d
, NULL
));
3017 r
->set_method("POST");
3018 r
->set_upload(make_scoped_ptr(CreateSimpleUploadData(kData
)));
3019 HttpRequestHeaders headers
;
3020 headers
.SetHeader(HttpRequestHeaders::kContentLength
,
3021 base::UintToString(arraysize(kData
) - 1));
3022 r
->SetExtraRequestHeaders(headers
);
3024 // Quit after hitting the redirect, so can check the headers.
3025 d
.set_quit_on_redirect(true);
3027 base::RunLoop().Run();
3029 // Check headers from URLRequestJob.
3030 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
->status().status());
3031 EXPECT_EQ(307, r
->GetResponseCode());
3032 EXPECT_EQ(307, r
->response_headers()->response_code());
3033 std::string location
;
3034 ASSERT_TRUE(r
->response_headers()->EnumerateHeader(NULL
, "Location",
3036 EXPECT_EQ(redirect_url
, GURL(location
));
3038 // Let the request finish.
3039 r
->FollowDeferredRedirect();
3040 base::RunLoop().Run();
3042 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
->status().status());
3043 EXPECT_EQ(0, r
->status().error());
3044 EXPECT_EQ(redirect_url
, r
->url());
3045 EXPECT_EQ(original_url
, r
->original_url());
3046 EXPECT_EQ(2U, r
->url_chain().size());
3047 EXPECT_EQ(1, network_delegate
.created_requests());
3048 EXPECT_EQ(0, network_delegate
.destroyed_requests());
3049 EXPECT_EQ("POST", r
->method());
3050 EXPECT_EQ(kData
, d
.data_received());
3052 EXPECT_EQ(1, network_delegate
.destroyed_requests());
3055 // Tests that the network delegate can block and redirect a request to a new
3056 // URL during OnHeadersReceived.
3057 TEST_F(URLRequestTestHTTP
, NetworkDelegateRedirectRequestOnHeadersReceived
) {
3058 ASSERT_TRUE(test_server_
.Start());
3061 BlockingNetworkDelegate
network_delegate(
3062 BlockingNetworkDelegate::AUTO_CALLBACK
);
3063 network_delegate
.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED
);
3064 GURL
redirect_url(test_server_
.GetURL("simple.html"));
3065 network_delegate
.set_redirect_on_headers_received_url(redirect_url
);
3067 TestURLRequestContextWithProxy
context(
3068 test_server_
.host_port_pair().ToString(), &network_delegate
);
3071 GURL
original_url(test_server_
.GetURL("empty.html"));
3072 scoped_ptr
<URLRequest
> r(context
.CreateRequest(
3073 original_url
, DEFAULT_PRIORITY
, &d
, NULL
));
3076 base::RunLoop().Run();
3078 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
->status().status());
3079 EXPECT_TRUE(r
->proxy_server().Equals(test_server_
.host_port_pair()));
3081 2, network_delegate
.observed_before_proxy_headers_sent_callbacks());
3083 network_delegate
.last_observed_proxy().Equals(
3084 test_server_
.host_port_pair()));
3086 EXPECT_EQ(OK
, r
->status().error());
3087 EXPECT_EQ(redirect_url
, r
->url());
3088 EXPECT_EQ(original_url
, r
->original_url());
3089 EXPECT_EQ(2U, r
->url_chain().size());
3090 EXPECT_EQ(2, network_delegate
.created_requests());
3091 EXPECT_EQ(0, network_delegate
.destroyed_requests());
3093 EXPECT_EQ(1, network_delegate
.destroyed_requests());
3096 // Tests that the network delegate can synchronously complete OnAuthRequired
3097 // by taking no action. This indicates that the NetworkDelegate does not want to
3098 // handle the challenge, and is passing the buck along to the
3099 // URLRequest::Delegate.
3100 TEST_F(URLRequestTestHTTP
, NetworkDelegateOnAuthRequiredSyncNoAction
) {
3101 ASSERT_TRUE(test_server_
.Start());
3104 BlockingNetworkDelegate
network_delegate(
3105 BlockingNetworkDelegate::SYNCHRONOUS
);
3107 TestURLRequestContext
context(true);
3108 context
.set_network_delegate(&network_delegate
);
3111 d
.set_credentials(AuthCredentials(kUser
, kSecret
));
3114 GURL
url(test_server_
.GetURL("auth-basic"));
3115 scoped_ptr
<URLRequest
> r(context
.CreateRequest(
3116 url
, DEFAULT_PRIORITY
, &d
, NULL
));
3119 base::RunLoop().Run();
3121 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
->status().status());
3122 EXPECT_EQ(0, r
->status().error());
3123 EXPECT_EQ(200, r
->GetResponseCode());
3124 EXPECT_TRUE(d
.auth_required_called());
3125 EXPECT_EQ(1, network_delegate
.created_requests());
3126 EXPECT_EQ(0, network_delegate
.destroyed_requests());
3128 EXPECT_EQ(1, network_delegate
.destroyed_requests());
3131 TEST_F(URLRequestTestHTTP
,
3132 NetworkDelegateOnAuthRequiredSyncNoAction_GetFullRequestHeaders
) {
3133 ASSERT_TRUE(test_server_
.Start());
3136 BlockingNetworkDelegate
network_delegate(
3137 BlockingNetworkDelegate::SYNCHRONOUS
);
3139 TestURLRequestContext
context(true);
3140 context
.set_network_delegate(&network_delegate
);
3143 d
.set_credentials(AuthCredentials(kUser
, kSecret
));
3146 GURL
url(test_server_
.GetURL("auth-basic"));
3147 scoped_ptr
<URLRequest
> r(context
.CreateRequest(
3148 url
, DEFAULT_PRIORITY
, &d
, NULL
));
3152 HttpRequestHeaders headers
;
3153 EXPECT_TRUE(r
->GetFullRequestHeaders(&headers
));
3154 EXPECT_FALSE(headers
.HasHeader("Authorization"));
3157 base::RunLoop().Run();
3159 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
->status().status());
3160 EXPECT_EQ(0, r
->status().error());
3161 EXPECT_EQ(200, r
->GetResponseCode());
3162 EXPECT_TRUE(d
.auth_required_called());
3163 EXPECT_EQ(1, network_delegate
.created_requests());
3164 EXPECT_EQ(0, network_delegate
.destroyed_requests());
3166 EXPECT_EQ(1, network_delegate
.destroyed_requests());
3169 // Tests that the network delegate can synchronously complete OnAuthRequired
3170 // by setting credentials.
3171 TEST_F(URLRequestTestHTTP
, NetworkDelegateOnAuthRequiredSyncSetAuth
) {
3172 ASSERT_TRUE(test_server_
.Start());
3175 BlockingNetworkDelegate
network_delegate(
3176 BlockingNetworkDelegate::SYNCHRONOUS
);
3177 network_delegate
.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED
);
3178 network_delegate
.set_auth_retval(
3179 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH
);
3181 network_delegate
.set_auth_credentials(AuthCredentials(kUser
, kSecret
));
3183 TestURLRequestContext
context(true);
3184 context
.set_network_delegate(&network_delegate
);
3188 GURL
url(test_server_
.GetURL("auth-basic"));
3189 scoped_ptr
<URLRequest
> r(context
.CreateRequest(
3190 url
, DEFAULT_PRIORITY
, &d
, NULL
));
3192 base::RunLoop().Run();
3194 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
->status().status());
3195 EXPECT_EQ(0, r
->status().error());
3196 EXPECT_EQ(200, r
->GetResponseCode());
3197 EXPECT_FALSE(d
.auth_required_called());
3198 EXPECT_EQ(1, network_delegate
.created_requests());
3199 EXPECT_EQ(0, network_delegate
.destroyed_requests());
3201 EXPECT_EQ(1, network_delegate
.destroyed_requests());
3204 // Same as above, but also tests that GetFullRequestHeaders returns the proper
3205 // headers (for the first or second request) when called at the proper times.
3206 TEST_F(URLRequestTestHTTP
,
3207 NetworkDelegateOnAuthRequiredSyncSetAuth_GetFullRequestHeaders
) {
3208 ASSERT_TRUE(test_server_
.Start());
3211 BlockingNetworkDelegate
network_delegate(
3212 BlockingNetworkDelegate::SYNCHRONOUS
);
3213 network_delegate
.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED
);
3214 network_delegate
.set_auth_retval(
3215 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH
);
3217 network_delegate
.set_auth_credentials(AuthCredentials(kUser
, kSecret
));
3219 TestURLRequestContext
context(true);
3220 context
.set_network_delegate(&network_delegate
);
3224 GURL
url(test_server_
.GetURL("auth-basic"));
3225 scoped_ptr
<URLRequest
> r(context
.CreateRequest(
3226 url
, DEFAULT_PRIORITY
, &d
, NULL
));
3228 base::RunLoop().Run();
3230 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
->status().status());
3231 EXPECT_EQ(0, r
->status().error());
3232 EXPECT_EQ(200, r
->GetResponseCode());
3233 EXPECT_FALSE(d
.auth_required_called());
3234 EXPECT_EQ(1, network_delegate
.created_requests());
3235 EXPECT_EQ(0, network_delegate
.destroyed_requests());
3238 HttpRequestHeaders headers
;
3239 EXPECT_TRUE(r
->GetFullRequestHeaders(&headers
));
3240 EXPECT_TRUE(headers
.HasHeader("Authorization"));
3243 EXPECT_EQ(1, network_delegate
.destroyed_requests());
3246 // Tests that the network delegate can synchronously complete OnAuthRequired
3247 // by cancelling authentication.
3248 TEST_F(URLRequestTestHTTP
, NetworkDelegateOnAuthRequiredSyncCancel
) {
3249 ASSERT_TRUE(test_server_
.Start());
3252 BlockingNetworkDelegate
network_delegate(
3253 BlockingNetworkDelegate::SYNCHRONOUS
);
3254 network_delegate
.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED
);
3255 network_delegate
.set_auth_retval(
3256 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH
);
3258 TestURLRequestContext
context(true);
3259 context
.set_network_delegate(&network_delegate
);
3263 GURL
url(test_server_
.GetURL("auth-basic"));
3264 scoped_ptr
<URLRequest
> r(context
.CreateRequest(
3265 url
, DEFAULT_PRIORITY
, &d
, NULL
));
3267 base::RunLoop().Run();
3269 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
->status().status());
3270 EXPECT_EQ(OK
, r
->status().error());
3271 EXPECT_EQ(401, r
->GetResponseCode());
3272 EXPECT_FALSE(d
.auth_required_called());
3273 EXPECT_EQ(1, network_delegate
.created_requests());
3274 EXPECT_EQ(0, network_delegate
.destroyed_requests());
3276 EXPECT_EQ(1, network_delegate
.destroyed_requests());
3279 // Tests that the network delegate can asynchronously complete OnAuthRequired
3280 // by taking no action. This indicates that the NetworkDelegate does not want
3281 // to handle the challenge, and is passing the buck along to the
3282 // URLRequest::Delegate.
3283 TEST_F(URLRequestTestHTTP
, NetworkDelegateOnAuthRequiredAsyncNoAction
) {
3284 ASSERT_TRUE(test_server_
.Start());
3287 BlockingNetworkDelegate
network_delegate(
3288 BlockingNetworkDelegate::AUTO_CALLBACK
);
3289 network_delegate
.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED
);
3291 TestURLRequestContext
context(true);
3292 context
.set_network_delegate(&network_delegate
);
3295 d
.set_credentials(AuthCredentials(kUser
, kSecret
));
3298 GURL
url(test_server_
.GetURL("auth-basic"));
3299 scoped_ptr
<URLRequest
> r(context
.CreateRequest(
3300 url
, DEFAULT_PRIORITY
, &d
, NULL
));
3302 base::RunLoop().Run();
3304 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
->status().status());
3305 EXPECT_EQ(0, r
->status().error());
3306 EXPECT_EQ(200, r
->GetResponseCode());
3307 EXPECT_TRUE(d
.auth_required_called());
3308 EXPECT_EQ(1, network_delegate
.created_requests());
3309 EXPECT_EQ(0, network_delegate
.destroyed_requests());
3311 EXPECT_EQ(1, network_delegate
.destroyed_requests());
3314 // Tests that the network delegate can asynchronously complete OnAuthRequired
3315 // by setting credentials.
3316 TEST_F(URLRequestTestHTTP
, NetworkDelegateOnAuthRequiredAsyncSetAuth
) {
3317 ASSERT_TRUE(test_server_
.Start());
3320 BlockingNetworkDelegate
network_delegate(
3321 BlockingNetworkDelegate::AUTO_CALLBACK
);
3322 network_delegate
.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED
);
3323 network_delegate
.set_auth_retval(
3324 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH
);
3326 AuthCredentials
auth_credentials(kUser
, kSecret
);
3327 network_delegate
.set_auth_credentials(auth_credentials
);
3329 TestURLRequestContext
context(true);
3330 context
.set_network_delegate(&network_delegate
);
3334 GURL
url(test_server_
.GetURL("auth-basic"));
3335 scoped_ptr
<URLRequest
> r(context
.CreateRequest(
3336 url
, DEFAULT_PRIORITY
, &d
, NULL
));
3338 base::RunLoop().Run();
3340 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
->status().status());
3341 EXPECT_EQ(0, r
->status().error());
3343 EXPECT_EQ(200, r
->GetResponseCode());
3344 EXPECT_FALSE(d
.auth_required_called());
3345 EXPECT_EQ(1, network_delegate
.created_requests());
3346 EXPECT_EQ(0, network_delegate
.destroyed_requests());
3348 EXPECT_EQ(1, network_delegate
.destroyed_requests());
3351 // Tests that the network delegate can asynchronously complete OnAuthRequired
3352 // by cancelling authentication.
3353 TEST_F(URLRequestTestHTTP
, NetworkDelegateOnAuthRequiredAsyncCancel
) {
3354 ASSERT_TRUE(test_server_
.Start());
3357 BlockingNetworkDelegate
network_delegate(
3358 BlockingNetworkDelegate::AUTO_CALLBACK
);
3359 network_delegate
.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED
);
3360 network_delegate
.set_auth_retval(
3361 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH
);
3363 TestURLRequestContext
context(true);
3364 context
.set_network_delegate(&network_delegate
);
3368 GURL
url(test_server_
.GetURL("auth-basic"));
3369 scoped_ptr
<URLRequest
> r(context
.CreateRequest(
3370 url
, DEFAULT_PRIORITY
, &d
, NULL
));
3372 base::RunLoop().Run();
3374 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
->status().status());
3375 EXPECT_EQ(OK
, r
->status().error());
3376 EXPECT_EQ(401, r
->GetResponseCode());
3377 EXPECT_FALSE(d
.auth_required_called());
3378 EXPECT_EQ(1, network_delegate
.created_requests());
3379 EXPECT_EQ(0, network_delegate
.destroyed_requests());
3381 EXPECT_EQ(1, network_delegate
.destroyed_requests());
3384 // Tests that we can handle when a network request was canceled while we were
3385 // waiting for the network delegate.
3386 // Part 1: Request is cancelled while waiting for OnBeforeURLRequest callback.
3387 TEST_F(URLRequestTestHTTP
, NetworkDelegateCancelWhileWaiting1
) {
3388 ASSERT_TRUE(test_server_
.Start());
3391 BlockingNetworkDelegate
network_delegate(
3392 BlockingNetworkDelegate::USER_CALLBACK
);
3393 network_delegate
.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST
);
3395 TestURLRequestContext
context(true);
3396 context
.set_network_delegate(&network_delegate
);
3400 scoped_ptr
<URLRequest
> r(context
.CreateRequest(
3401 test_server_
.GetURL(std::string()), DEFAULT_PRIORITY
, &d
, NULL
));
3404 base::RunLoop().Run();
3405 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST
,
3406 network_delegate
.stage_blocked_for_callback());
3407 EXPECT_EQ(0, network_delegate
.completed_requests());
3408 // Cancel before callback.
3410 // Ensure that network delegate is notified.
3411 EXPECT_EQ(1, network_delegate
.completed_requests());
3412 EXPECT_EQ(URLRequestStatus::CANCELED
, r
->status().status());
3413 EXPECT_EQ(ERR_ABORTED
, r
->status().error());
3414 EXPECT_EQ(1, network_delegate
.created_requests());
3415 EXPECT_EQ(0, network_delegate
.destroyed_requests());
3417 EXPECT_EQ(1, network_delegate
.destroyed_requests());
3420 // Tests that we can handle when a network request was canceled while we were
3421 // waiting for the network delegate.
3422 // Part 2: Request is cancelled while waiting for OnBeforeSendHeaders callback.
3423 TEST_F(URLRequestTestHTTP
, NetworkDelegateCancelWhileWaiting2
) {
3424 ASSERT_TRUE(test_server_
.Start());
3427 BlockingNetworkDelegate
network_delegate(
3428 BlockingNetworkDelegate::USER_CALLBACK
);
3429 network_delegate
.set_block_on(
3430 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS
);
3432 TestURLRequestContext
context(true);
3433 context
.set_network_delegate(&network_delegate
);
3437 scoped_ptr
<URLRequest
> r(context
.CreateRequest(
3438 test_server_
.GetURL(std::string()), DEFAULT_PRIORITY
, &d
, NULL
));
3441 base::RunLoop().Run();
3442 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS
,
3443 network_delegate
.stage_blocked_for_callback());
3444 EXPECT_EQ(0, network_delegate
.completed_requests());
3445 // Cancel before callback.
3447 // Ensure that network delegate is notified.
3448 EXPECT_EQ(1, network_delegate
.completed_requests());
3449 EXPECT_EQ(URLRequestStatus::CANCELED
, r
->status().status());
3450 EXPECT_EQ(ERR_ABORTED
, r
->status().error());
3451 EXPECT_EQ(1, network_delegate
.created_requests());
3452 EXPECT_EQ(0, network_delegate
.destroyed_requests());
3454 EXPECT_EQ(1, network_delegate
.destroyed_requests());
3457 // Tests that we can handle when a network request was canceled while we were
3458 // waiting for the network delegate.
3459 // Part 3: Request is cancelled while waiting for OnHeadersReceived callback.
3460 TEST_F(URLRequestTestHTTP
, NetworkDelegateCancelWhileWaiting3
) {
3461 ASSERT_TRUE(test_server_
.Start());
3464 BlockingNetworkDelegate
network_delegate(
3465 BlockingNetworkDelegate::USER_CALLBACK
);
3466 network_delegate
.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED
);
3468 TestURLRequestContext
context(true);
3469 context
.set_network_delegate(&network_delegate
);
3473 scoped_ptr
<URLRequest
> r(context
.CreateRequest(
3474 test_server_
.GetURL(std::string()), DEFAULT_PRIORITY
, &d
, NULL
));
3477 base::RunLoop().Run();
3478 EXPECT_EQ(BlockingNetworkDelegate::ON_HEADERS_RECEIVED
,
3479 network_delegate
.stage_blocked_for_callback());
3480 EXPECT_EQ(0, network_delegate
.completed_requests());
3481 // Cancel before callback.
3483 // Ensure that network delegate is notified.
3484 EXPECT_EQ(1, network_delegate
.completed_requests());
3485 EXPECT_EQ(URLRequestStatus::CANCELED
, r
->status().status());
3486 EXPECT_EQ(ERR_ABORTED
, r
->status().error());
3487 EXPECT_EQ(1, network_delegate
.created_requests());
3488 EXPECT_EQ(0, network_delegate
.destroyed_requests());
3490 EXPECT_EQ(1, network_delegate
.destroyed_requests());
3493 // Tests that we can handle when a network request was canceled while we were
3494 // waiting for the network delegate.
3495 // Part 4: Request is cancelled while waiting for OnAuthRequired callback.
3496 TEST_F(URLRequestTestHTTP
, NetworkDelegateCancelWhileWaiting4
) {
3497 ASSERT_TRUE(test_server_
.Start());
3500 BlockingNetworkDelegate
network_delegate(
3501 BlockingNetworkDelegate::USER_CALLBACK
);
3502 network_delegate
.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED
);
3504 TestURLRequestContext
context(true);
3505 context
.set_network_delegate(&network_delegate
);
3509 scoped_ptr
<URLRequest
> r(context
.CreateRequest(
3510 test_server_
.GetURL("auth-basic"), DEFAULT_PRIORITY
, &d
, NULL
));
3513 base::RunLoop().Run();
3514 EXPECT_EQ(BlockingNetworkDelegate::ON_AUTH_REQUIRED
,
3515 network_delegate
.stage_blocked_for_callback());
3516 EXPECT_EQ(0, network_delegate
.completed_requests());
3517 // Cancel before callback.
3519 // Ensure that network delegate is notified.
3520 EXPECT_EQ(1, network_delegate
.completed_requests());
3521 EXPECT_EQ(URLRequestStatus::CANCELED
, r
->status().status());
3522 EXPECT_EQ(ERR_ABORTED
, r
->status().error());
3523 EXPECT_EQ(1, network_delegate
.created_requests());
3524 EXPECT_EQ(0, network_delegate
.destroyed_requests());
3526 EXPECT_EQ(1, network_delegate
.destroyed_requests());
3529 // In this unit test, we're using the HTTPTestServer as a proxy server and
3530 // issuing a CONNECT request with the magic host name "www.server-auth.com".
3531 // The HTTPTestServer will return a 401 response, which we should balk at.
3532 TEST_F(URLRequestTestHTTP
, UnexpectedServerAuthTest
) {
3533 ASSERT_TRUE(test_server_
.Start());
3535 TestNetworkDelegate network_delegate
; // Must outlive URLRequest.
3536 TestURLRequestContextWithProxy
context(
3537 test_server_
.host_port_pair().ToString(), &network_delegate
);
3541 scoped_ptr
<URLRequest
> r(context
.CreateRequest(
3542 GURL("https://www.server-auth.com/"), DEFAULT_PRIORITY
, &d
, NULL
));
3545 EXPECT_TRUE(r
->is_pending());
3547 base::RunLoop().Run();
3549 EXPECT_EQ(URLRequestStatus::FAILED
, r
->status().status());
3550 // The proxy server is not set before failure.
3551 EXPECT_TRUE(r
->proxy_server().IsEmpty());
3552 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED
, r
->status().error());
3556 TEST_F(URLRequestTestHTTP
, GetTest_NoCache
) {
3557 ASSERT_TRUE(test_server_
.Start());
3561 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
3562 test_server_
.GetURL(std::string()), DEFAULT_PRIORITY
, &d
, NULL
));
3565 EXPECT_TRUE(r
->is_pending());
3567 base::RunLoop().Run();
3569 EXPECT_EQ(1, d
.response_started_count());
3570 EXPECT_FALSE(d
.received_data_before_response());
3571 EXPECT_NE(0, d
.bytes_received());
3572 EXPECT_EQ(test_server_
.host_port_pair().host(),
3573 r
->GetSocketAddress().host());
3574 EXPECT_EQ(test_server_
.host_port_pair().port(),
3575 r
->GetSocketAddress().port());
3577 // TODO(eroman): Add back the NetLog tests...
3581 // This test has the server send a large number of cookies to the client.
3582 // To ensure that no number of cookies causes a crash, a galloping binary
3583 // search is used to estimate that maximum number of cookies that are accepted
3584 // by the browser. Beyond the maximum number, the request will fail with
3585 // ERR_RESPONSE_HEADERS_TOO_BIG.
3587 // http://crbug.com/177916
3588 #define MAYBE_GetTest_ManyCookies DISABLED_GetTest_ManyCookies
3590 #define MAYBE_GetTest_ManyCookies GetTest_ManyCookies
3591 #endif // defined(OS_WIN)
3592 TEST_F(URLRequestTestHTTP
, MAYBE_GetTest_ManyCookies
) {
3593 ASSERT_TRUE(test_server_
.Start());
3595 int lower_bound
= 0;
3596 int upper_bound
= 1;
3598 // Double the number of cookies until the response header limits are
3600 while (DoManyCookiesRequest(upper_bound
)) {
3601 lower_bound
= upper_bound
;
3603 ASSERT_LT(upper_bound
, 1000000);
3606 int tolerance
= upper_bound
* 0.005;
3610 // Perform a binary search to find the highest possible number of cookies,
3611 // within the desired tolerance.
3612 while (upper_bound
- lower_bound
>= tolerance
) {
3613 int num_cookies
= (lower_bound
+ upper_bound
) / 2;
3615 if (DoManyCookiesRequest(num_cookies
))
3616 lower_bound
= num_cookies
;
3618 upper_bound
= num_cookies
;
3620 // Success: the test did not crash.
3623 TEST_F(URLRequestTestHTTP
, GetTest
) {
3624 ASSERT_TRUE(test_server_
.Start());
3628 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
3629 test_server_
.GetURL(std::string()), DEFAULT_PRIORITY
, &d
, NULL
));
3632 EXPECT_TRUE(r
->is_pending());
3634 base::RunLoop().Run();
3636 EXPECT_EQ(1, d
.response_started_count());
3637 EXPECT_FALSE(d
.received_data_before_response());
3638 EXPECT_NE(0, d
.bytes_received());
3639 EXPECT_EQ(test_server_
.host_port_pair().host(),
3640 r
->GetSocketAddress().host());
3641 EXPECT_EQ(test_server_
.host_port_pair().port(),
3642 r
->GetSocketAddress().port());
3646 TEST_F(URLRequestTestHTTP
, GetTest_GetFullRequestHeaders
) {
3647 ASSERT_TRUE(test_server_
.Start());
3651 GURL
test_url(test_server_
.GetURL(std::string()));
3652 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
3653 test_url
, DEFAULT_PRIORITY
, &d
, NULL
));
3655 HttpRequestHeaders headers
;
3656 EXPECT_FALSE(r
->GetFullRequestHeaders(&headers
));
3659 EXPECT_TRUE(r
->is_pending());
3661 base::RunLoop().Run();
3663 EXPECT_EQ(1, d
.response_started_count());
3664 EXPECT_FALSE(d
.received_data_before_response());
3665 EXPECT_NE(0, d
.bytes_received());
3666 EXPECT_EQ(test_server_
.host_port_pair().host(),
3667 r
->GetSocketAddress().host());
3668 EXPECT_EQ(test_server_
.host_port_pair().port(),
3669 r
->GetSocketAddress().port());
3671 EXPECT_TRUE(d
.have_full_request_headers());
3672 CheckFullRequestHeaders(d
.full_request_headers(), test_url
);
3676 TEST_F(URLRequestTestHTTP
, GetTestLoadTiming
) {
3677 ASSERT_TRUE(test_server_
.Start());
3681 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
3682 test_server_
.GetURL(std::string()), DEFAULT_PRIORITY
, &d
, NULL
));
3685 EXPECT_TRUE(r
->is_pending());
3687 base::RunLoop().Run();
3689 LoadTimingInfo load_timing_info
;
3690 r
->GetLoadTimingInfo(&load_timing_info
);
3691 TestLoadTimingNotReused(load_timing_info
, CONNECT_TIMING_HAS_DNS_TIMES
);
3693 EXPECT_EQ(1, d
.response_started_count());
3694 EXPECT_FALSE(d
.received_data_before_response());
3695 EXPECT_NE(0, d
.bytes_received());
3696 EXPECT_EQ(test_server_
.host_port_pair().host(),
3697 r
->GetSocketAddress().host());
3698 EXPECT_EQ(test_server_
.host_port_pair().port(),
3699 r
->GetSocketAddress().port());
3703 TEST_F(URLRequestTestHTTP
, GetZippedTest
) {
3704 ASSERT_TRUE(test_server_
.Start());
3706 // Parameter that specifies the Content-Length field in the response:
3707 // C - Compressed length.
3708 // U - Uncompressed length.
3709 // L - Large length (larger than both C & U).
3710 // M - Medium length (between C & U).
3711 // S - Small length (smaller than both C & U).
3712 const char test_parameters
[] = "CULMS";
3713 const int num_tests
= arraysize(test_parameters
)- 1; // Skip NULL.
3714 // C & U should be OK.
3715 // L & M are larger than the data sent, and show an error.
3716 // S has too little data, but we seem to accept it.
3717 const bool test_expect_success
[num_tests
] =
3718 { true, true, false, false, true };
3720 for (int i
= 0; i
< num_tests
; i
++) {
3723 std::string test_file
=
3724 base::StringPrintf("compressedfiles/BullRunSpeech.txt?%c",
3725 test_parameters
[i
]);
3727 TestNetworkDelegate network_delegate
; // Must outlive URLRequest.
3728 TestURLRequestContext
context(true);
3729 context
.set_network_delegate(&network_delegate
);
3732 scoped_ptr
<URLRequest
> r(context
.CreateRequest(
3733 test_server_
.GetURL(test_file
), DEFAULT_PRIORITY
, &d
, NULL
));
3735 EXPECT_TRUE(r
->is_pending());
3737 base::RunLoop().Run();
3739 EXPECT_EQ(1, d
.response_started_count());
3740 EXPECT_FALSE(d
.received_data_before_response());
3741 VLOG(1) << " Received " << d
.bytes_received() << " bytes"
3742 << " status = " << r
->status().status()
3743 << " error = " << r
->status().error();
3744 if (test_expect_success
[i
]) {
3745 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
->status().status())
3746 << " Parameter = \"" << test_file
<< "\"";
3748 EXPECT_EQ(URLRequestStatus::FAILED
, r
->status().status());
3749 EXPECT_EQ(ERR_CONTENT_LENGTH_MISMATCH
, r
->status().error())
3750 << " Parameter = \"" << test_file
<< "\"";
3756 TEST_F(URLRequestTestHTTP
, HTTPSToHTTPRedirectNoRefererTest
) {
3757 ASSERT_TRUE(test_server_
.Start());
3759 SpawnedTestServer
https_test_server(
3760 SpawnedTestServer::TYPE_HTTPS
, SpawnedTestServer::kLocalhost
,
3761 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3762 ASSERT_TRUE(https_test_server
.Start());
3764 // An https server is sent a request with an https referer,
3765 // and responds with a redirect to an http url. The http
3766 // server should not be sent the referer.
3767 GURL http_destination
= test_server_
.GetURL(std::string());
3769 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
3770 https_test_server
.GetURL("server-redirect?" + http_destination
.spec()),
3771 DEFAULT_PRIORITY
, &d
, NULL
));
3772 req
->SetReferrer("https://www.referrer.com/");
3774 base::RunLoop().Run();
3776 EXPECT_EQ(1, d
.response_started_count());
3777 EXPECT_EQ(1, d
.received_redirect_count());
3778 EXPECT_EQ(http_destination
, req
->url());
3779 EXPECT_EQ(std::string(), req
->referrer());
3782 TEST_F(URLRequestTestHTTP
, RedirectLoadTiming
) {
3783 ASSERT_TRUE(test_server_
.Start());
3785 GURL destination_url
= test_server_
.GetURL(std::string());
3787 test_server_
.GetURL("server-redirect?" + destination_url
.spec());
3789 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
3790 original_url
, DEFAULT_PRIORITY
, &d
, NULL
));
3792 base::RunLoop().Run();
3794 EXPECT_EQ(1, d
.response_started_count());
3795 EXPECT_EQ(1, d
.received_redirect_count());
3796 EXPECT_EQ(destination_url
, req
->url());
3797 EXPECT_EQ(original_url
, req
->original_url());
3798 ASSERT_EQ(2U, req
->url_chain().size());
3799 EXPECT_EQ(original_url
, req
->url_chain()[0]);
3800 EXPECT_EQ(destination_url
, req
->url_chain()[1]);
3802 LoadTimingInfo load_timing_info_before_redirect
;
3803 EXPECT_TRUE(default_network_delegate_
.GetLoadTimingInfoBeforeRedirect(
3804 &load_timing_info_before_redirect
));
3805 TestLoadTimingNotReused(load_timing_info_before_redirect
,
3806 CONNECT_TIMING_HAS_DNS_TIMES
);
3808 LoadTimingInfo load_timing_info
;
3809 req
->GetLoadTimingInfo(&load_timing_info
);
3810 TestLoadTimingNotReused(load_timing_info
, CONNECT_TIMING_HAS_DNS_TIMES
);
3812 // Check that a new socket was used on redirect, since the server does not
3813 // supposed keep-alive sockets, and that the times before the redirect are
3814 // before the ones recorded for the second request.
3815 EXPECT_NE(load_timing_info_before_redirect
.socket_log_id
,
3816 load_timing_info
.socket_log_id
);
3817 EXPECT_LE(load_timing_info_before_redirect
.receive_headers_end
,
3818 load_timing_info
.connect_timing
.connect_start
);
3821 TEST_F(URLRequestTestHTTP
, MultipleRedirectTest
) {
3822 ASSERT_TRUE(test_server_
.Start());
3824 GURL destination_url
= test_server_
.GetURL(std::string());
3825 GURL middle_redirect_url
=
3826 test_server_
.GetURL("server-redirect?" + destination_url
.spec());
3827 GURL original_url
= test_server_
.GetURL(
3828 "server-redirect?" + middle_redirect_url
.spec());
3830 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
3831 original_url
, DEFAULT_PRIORITY
, &d
, NULL
));
3833 base::RunLoop().Run();
3835 EXPECT_EQ(1, d
.response_started_count());
3836 EXPECT_EQ(2, d
.received_redirect_count());
3837 EXPECT_EQ(destination_url
, req
->url());
3838 EXPECT_EQ(original_url
, req
->original_url());
3839 ASSERT_EQ(3U, req
->url_chain().size());
3840 EXPECT_EQ(original_url
, req
->url_chain()[0]);
3841 EXPECT_EQ(middle_redirect_url
, req
->url_chain()[1]);
3842 EXPECT_EQ(destination_url
, req
->url_chain()[2]);
3845 // First and second pieces of information logged by delegates to URLRequests.
3846 const char kFirstDelegateInfo
[] = "Wonderful delegate";
3847 const char kSecondDelegateInfo
[] = "Exciting delegate";
3849 // Logs delegate information to a URLRequest. The first string is logged
3850 // synchronously on Start(), using DELEGATE_INFO_DEBUG_ONLY. The second is
3851 // logged asynchronously, using DELEGATE_INFO_DISPLAY_TO_USER. Then
3852 // another asynchronous call is used to clear the delegate information
3853 // before calling a callback. The object then deletes itself.
3854 class AsyncDelegateLogger
: public base::RefCounted
<AsyncDelegateLogger
> {
3856 typedef base::Callback
<void()> Callback
;
3858 // Each time delegate information is added to the URLRequest, the resulting
3859 // load state is checked. The expected load state after each request is
3860 // passed in as an argument.
3861 static void Run(URLRequest
* url_request
,
3862 LoadState expected_first_load_state
,
3863 LoadState expected_second_load_state
,
3864 LoadState expected_third_load_state
,
3865 const Callback
& callback
) {
3866 AsyncDelegateLogger
* logger
= new AsyncDelegateLogger(
3868 expected_first_load_state
,
3869 expected_second_load_state
,
3870 expected_third_load_state
,
3875 // Checks that the log entries, starting with log_position, contain the
3876 // DELEGATE_INFO NetLog events that an AsyncDelegateLogger should have
3877 // recorded. Returns the index of entry after the expected number of
3878 // events this logged, or entries.size() if there aren't enough entries.
3879 static size_t CheckDelegateInfo(
3880 const CapturingNetLog::CapturedEntryList
& entries
, size_t log_position
) {
3881 // There should be 4 DELEGATE_INFO events: Two begins and two ends.
3882 if (log_position
+ 3 >= entries
.size()) {
3883 ADD_FAILURE() << "Not enough log entries";
3884 return entries
.size();
3886 std::string delegate_info
;
3887 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO
, entries
[log_position
].type
);
3888 EXPECT_EQ(NetLog::PHASE_BEGIN
, entries
[log_position
].phase
);
3889 EXPECT_TRUE(entries
[log_position
].GetStringValue("delegate_info",
3891 EXPECT_EQ(kFirstDelegateInfo
, delegate_info
);
3894 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO
, entries
[log_position
].type
);
3895 EXPECT_EQ(NetLog::PHASE_END
, entries
[log_position
].phase
);
3898 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO
, entries
[log_position
].type
);
3899 EXPECT_EQ(NetLog::PHASE_BEGIN
, entries
[log_position
].phase
);
3900 EXPECT_TRUE(entries
[log_position
].GetStringValue("delegate_info",
3902 EXPECT_EQ(kSecondDelegateInfo
, delegate_info
);
3905 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO
, entries
[log_position
].type
);
3906 EXPECT_EQ(NetLog::PHASE_END
, entries
[log_position
].phase
);
3908 return log_position
+ 1;
3911 // Find delegate request begin and end messages for OnBeforeNetworkStart.
3912 // Returns the position of the end message.
3913 static size_t ExpectBeforeNetworkEvents(
3914 const CapturingNetLog::CapturedEntryList
& entries
,
3915 size_t log_position
) {
3917 ExpectLogContainsSomewhereAfter(entries
,
3919 NetLog::TYPE_URL_REQUEST_DELEGATE
,
3920 NetLog::PHASE_BEGIN
);
3921 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE
,
3922 entries
[log_position
+ 1].type
);
3923 EXPECT_EQ(NetLog::PHASE_END
, entries
[log_position
+ 1].phase
);
3924 return log_position
+ 1;
3928 friend class base::RefCounted
<AsyncDelegateLogger
>;
3930 AsyncDelegateLogger(URLRequest
* url_request
,
3931 LoadState expected_first_load_state
,
3932 LoadState expected_second_load_state
,
3933 LoadState expected_third_load_state
,
3934 const Callback
& callback
)
3935 : url_request_(url_request
),
3936 expected_first_load_state_(expected_first_load_state
),
3937 expected_second_load_state_(expected_second_load_state
),
3938 expected_third_load_state_(expected_third_load_state
),
3939 callback_(callback
) {
3942 ~AsyncDelegateLogger() {}
3945 url_request_
->LogBlockedBy(kFirstDelegateInfo
);
3946 LoadStateWithParam load_state
= url_request_
->GetLoadState();
3947 EXPECT_EQ(expected_first_load_state_
, load_state
.state
);
3948 EXPECT_NE(ASCIIToUTF16(kFirstDelegateInfo
), load_state
.param
);
3949 base::MessageLoop::current()->PostTask(
3951 base::Bind(&AsyncDelegateLogger::LogSecondDelegate
, this));
3954 void LogSecondDelegate() {
3955 url_request_
->LogAndReportBlockedBy(kSecondDelegateInfo
);
3956 LoadStateWithParam load_state
= url_request_
->GetLoadState();
3957 EXPECT_EQ(expected_second_load_state_
, load_state
.state
);
3958 if (expected_second_load_state_
== LOAD_STATE_WAITING_FOR_DELEGATE
) {
3959 EXPECT_EQ(ASCIIToUTF16(kSecondDelegateInfo
), load_state
.param
);
3961 EXPECT_NE(ASCIIToUTF16(kSecondDelegateInfo
), load_state
.param
);
3963 base::MessageLoop::current()->PostTask(
3965 base::Bind(&AsyncDelegateLogger::LogComplete
, this));
3968 void LogComplete() {
3969 url_request_
->LogUnblocked();
3970 LoadStateWithParam load_state
= url_request_
->GetLoadState();
3971 EXPECT_EQ(expected_third_load_state_
, load_state
.state
);
3972 if (expected_second_load_state_
== LOAD_STATE_WAITING_FOR_DELEGATE
)
3973 EXPECT_EQ(base::string16(), load_state
.param
);
3977 URLRequest
* url_request_
;
3978 const int expected_first_load_state_
;
3979 const int expected_second_load_state_
;
3980 const int expected_third_load_state_
;
3981 const Callback callback_
;
3983 DISALLOW_COPY_AND_ASSIGN(AsyncDelegateLogger
);
3986 // NetworkDelegate that logs delegate information before a request is started,
3987 // before headers are sent, when headers are read, and when auth information
3988 // is requested. Uses AsyncDelegateLogger.
3989 class AsyncLoggingNetworkDelegate
: public TestNetworkDelegate
{
3991 AsyncLoggingNetworkDelegate() {}
3992 virtual ~AsyncLoggingNetworkDelegate() {}
3994 // NetworkDelegate implementation.
3995 virtual int OnBeforeURLRequest(URLRequest
* request
,
3996 const CompletionCallback
& callback
,
3997 GURL
* new_url
) OVERRIDE
{
3998 TestNetworkDelegate::OnBeforeURLRequest(request
, callback
, new_url
);
3999 return RunCallbackAsynchronously(request
, callback
);
4002 virtual int OnBeforeSendHeaders(URLRequest
* request
,
4003 const CompletionCallback
& callback
,
4004 HttpRequestHeaders
* headers
) OVERRIDE
{
4005 TestNetworkDelegate::OnBeforeSendHeaders(request
, callback
, headers
);
4006 return RunCallbackAsynchronously(request
, callback
);
4009 virtual int OnHeadersReceived(
4010 URLRequest
* request
,
4011 const CompletionCallback
& callback
,
4012 const HttpResponseHeaders
* original_response_headers
,
4013 scoped_refptr
<HttpResponseHeaders
>* override_response_headers
,
4014 GURL
* allowed_unsafe_redirect_url
) OVERRIDE
{
4015 TestNetworkDelegate::OnHeadersReceived(request
,
4017 original_response_headers
,
4018 override_response_headers
,
4019 allowed_unsafe_redirect_url
);
4020 return RunCallbackAsynchronously(request
, callback
);
4023 virtual NetworkDelegate::AuthRequiredResponse
OnAuthRequired(
4024 URLRequest
* request
,
4025 const AuthChallengeInfo
& auth_info
,
4026 const AuthCallback
& callback
,
4027 AuthCredentials
* credentials
) OVERRIDE
{
4028 AsyncDelegateLogger::Run(
4030 LOAD_STATE_WAITING_FOR_DELEGATE
,
4031 LOAD_STATE_WAITING_FOR_DELEGATE
,
4032 LOAD_STATE_WAITING_FOR_DELEGATE
,
4033 base::Bind(&AsyncLoggingNetworkDelegate::SetAuthAndResume
,
4034 callback
, credentials
));
4035 return AUTH_REQUIRED_RESPONSE_IO_PENDING
;
4039 static int RunCallbackAsynchronously(
4040 URLRequest
* request
,
4041 const CompletionCallback
& callback
) {
4042 AsyncDelegateLogger::Run(
4044 LOAD_STATE_WAITING_FOR_DELEGATE
,
4045 LOAD_STATE_WAITING_FOR_DELEGATE
,
4046 LOAD_STATE_WAITING_FOR_DELEGATE
,
4047 base::Bind(callback
, OK
));
4048 return ERR_IO_PENDING
;
4051 static void SetAuthAndResume(const AuthCallback
& callback
,
4052 AuthCredentials
* credentials
) {
4053 *credentials
= AuthCredentials(kUser
, kSecret
);
4054 callback
.Run(NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH
);
4057 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingNetworkDelegate
);
4060 // URLRequest::Delegate that logs delegate information when the headers
4061 // are received, when each read completes, and during redirects. Uses
4062 // AsyncDelegateLogger. Can optionally cancel a request in any phase.
4064 // Inherits from TestDelegate to reuse the TestDelegate code to handle
4065 // advancing to the next step in most cases, as well as cancellation.
4066 class AsyncLoggingUrlRequestDelegate
: public TestDelegate
{
4070 CANCEL_ON_RECEIVED_REDIRECT
,
4071 CANCEL_ON_RESPONSE_STARTED
,
4072 CANCEL_ON_READ_COMPLETED
4075 explicit AsyncLoggingUrlRequestDelegate(CancelStage cancel_stage
)
4076 : cancel_stage_(cancel_stage
) {
4077 if (cancel_stage
== CANCEL_ON_RECEIVED_REDIRECT
)
4078 set_cancel_in_received_redirect(true);
4079 else if (cancel_stage
== CANCEL_ON_RESPONSE_STARTED
)
4080 set_cancel_in_response_started(true);
4081 else if (cancel_stage
== CANCEL_ON_READ_COMPLETED
)
4082 set_cancel_in_received_data(true);
4084 virtual ~AsyncLoggingUrlRequestDelegate() {}
4086 // URLRequest::Delegate implementation:
4087 void virtual OnReceivedRedirect(URLRequest
* request
,
4088 const RedirectInfo
& redirect_info
,
4089 bool* defer_redirect
) OVERRIDE
{
4090 *defer_redirect
= true;
4091 AsyncDelegateLogger::Run(
4093 LOAD_STATE_WAITING_FOR_DELEGATE
,
4094 LOAD_STATE_WAITING_FOR_DELEGATE
,
4095 LOAD_STATE_WAITING_FOR_DELEGATE
,
4097 &AsyncLoggingUrlRequestDelegate::OnReceivedRedirectLoggingComplete
,
4098 base::Unretained(this), request
, redirect_info
));
4101 virtual void OnResponseStarted(URLRequest
* request
) OVERRIDE
{
4102 AsyncDelegateLogger::Run(
4104 LOAD_STATE_WAITING_FOR_DELEGATE
,
4105 LOAD_STATE_WAITING_FOR_DELEGATE
,
4106 LOAD_STATE_WAITING_FOR_DELEGATE
,
4108 &AsyncLoggingUrlRequestDelegate::OnResponseStartedLoggingComplete
,
4109 base::Unretained(this), request
));
4112 virtual void OnReadCompleted(URLRequest
* request
,
4113 int bytes_read
) OVERRIDE
{
4114 AsyncDelegateLogger::Run(
4120 &AsyncLoggingUrlRequestDelegate::AfterReadCompletedLoggingComplete
,
4121 base::Unretained(this), request
, bytes_read
));
4125 void OnReceivedRedirectLoggingComplete(URLRequest
* request
,
4126 const RedirectInfo
& redirect_info
) {
4127 bool defer_redirect
= false;
4128 TestDelegate::OnReceivedRedirect(request
, redirect_info
, &defer_redirect
);
4129 // FollowDeferredRedirect should not be called after cancellation.
4130 if (cancel_stage_
== CANCEL_ON_RECEIVED_REDIRECT
)
4132 if (!defer_redirect
)
4133 request
->FollowDeferredRedirect();
4136 void OnResponseStartedLoggingComplete(URLRequest
* request
) {
4137 // The parent class continues the request.
4138 TestDelegate::OnResponseStarted(request
);
4141 void AfterReadCompletedLoggingComplete(URLRequest
* request
, int bytes_read
) {
4142 // The parent class continues the request.
4143 TestDelegate::OnReadCompleted(request
, bytes_read
);
4146 const CancelStage cancel_stage_
;
4148 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingUrlRequestDelegate
);
4151 // Tests handling of delegate info before a request starts.
4152 TEST_F(URLRequestTestHTTP
, DelegateInfoBeforeStart
) {
4153 ASSERT_TRUE(test_server_
.Start());
4155 TestDelegate request_delegate
;
4156 TestURLRequestContext
context(true);
4157 context
.set_network_delegate(NULL
);
4158 context
.set_net_log(&net_log_
);
4162 scoped_ptr
<URLRequest
> r(context
.CreateRequest(
4163 test_server_
.GetURL("empty.html"), DEFAULT_PRIORITY
, &request_delegate
,
4165 LoadStateWithParam load_state
= r
->GetLoadState();
4166 EXPECT_EQ(LOAD_STATE_IDLE
, load_state
.state
);
4167 EXPECT_EQ(base::string16(), load_state
.param
);
4169 AsyncDelegateLogger::Run(
4171 LOAD_STATE_WAITING_FOR_DELEGATE
,
4172 LOAD_STATE_WAITING_FOR_DELEGATE
,
4174 base::Bind(&URLRequest::Start
, base::Unretained(r
.get())));
4176 base::RunLoop().Run();
4178 EXPECT_EQ(200, r
->GetResponseCode());
4179 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
->status().status());
4182 CapturingNetLog::CapturedEntryList entries
;
4183 net_log_
.GetEntries(&entries
);
4184 size_t log_position
= ExpectLogContainsSomewhereAfter(
4187 NetLog::TYPE_DELEGATE_INFO
,
4188 NetLog::PHASE_BEGIN
);
4190 log_position
= AsyncDelegateLogger::CheckDelegateInfo(entries
, log_position
);
4192 // Nothing else should add any delegate info to the request.
4193 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4194 entries
, log_position
+ 1, NetLog::TYPE_DELEGATE_INFO
));
4197 // Tests handling of delegate info from a network delegate.
4198 TEST_F(URLRequestTestHTTP
, NetworkDelegateInfo
) {
4199 ASSERT_TRUE(test_server_
.Start());
4201 TestDelegate request_delegate
;
4202 AsyncLoggingNetworkDelegate network_delegate
;
4203 TestURLRequestContext
context(true);
4204 context
.set_network_delegate(&network_delegate
);
4205 context
.set_net_log(&net_log_
);
4209 scoped_ptr
<URLRequest
> r(context
.CreateRequest(
4210 test_server_
.GetURL("simple.html"), DEFAULT_PRIORITY
, &request_delegate
,
4212 LoadStateWithParam load_state
= r
->GetLoadState();
4213 EXPECT_EQ(LOAD_STATE_IDLE
, load_state
.state
);
4214 EXPECT_EQ(base::string16(), load_state
.param
);
4217 base::RunLoop().Run();
4219 EXPECT_EQ(200, r
->GetResponseCode());
4220 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
->status().status());
4221 EXPECT_EQ(1, network_delegate
.created_requests());
4222 EXPECT_EQ(0, network_delegate
.destroyed_requests());
4224 EXPECT_EQ(1, network_delegate
.destroyed_requests());
4226 size_t log_position
= 0;
4227 CapturingNetLog::CapturedEntryList entries
;
4228 net_log_
.GetEntries(&entries
);
4229 for (size_t i
= 0; i
< 3; ++i
) {
4230 log_position
= ExpectLogContainsSomewhereAfter(
4233 NetLog::TYPE_URL_REQUEST_DELEGATE
,
4234 NetLog::PHASE_BEGIN
);
4236 log_position
= AsyncDelegateLogger::CheckDelegateInfo(entries
,
4239 ASSERT_LT(log_position
, entries
.size());
4240 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE
, entries
[log_position
].type
);
4241 EXPECT_EQ(NetLog::PHASE_END
, entries
[log_position
].phase
);
4244 log_position
= AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4245 entries
, log_position
+ 1);
4249 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4250 entries
, log_position
+ 1, NetLog::TYPE_DELEGATE_INFO
));
4253 // Tests handling of delegate info from a network delegate in the case of an
4255 TEST_F(URLRequestTestHTTP
, NetworkDelegateInfoRedirect
) {
4256 ASSERT_TRUE(test_server_
.Start());
4258 TestDelegate request_delegate
;
4259 AsyncLoggingNetworkDelegate network_delegate
;
4260 TestURLRequestContext
context(true);
4261 context
.set_network_delegate(&network_delegate
);
4262 context
.set_net_log(&net_log_
);
4266 scoped_ptr
<URLRequest
> r(context
.CreateRequest(
4267 test_server_
.GetURL("server-redirect?simple.html"), DEFAULT_PRIORITY
,
4268 &request_delegate
, NULL
));
4269 LoadStateWithParam load_state
= r
->GetLoadState();
4270 EXPECT_EQ(LOAD_STATE_IDLE
, load_state
.state
);
4271 EXPECT_EQ(base::string16(), load_state
.param
);
4274 base::RunLoop().Run();
4276 EXPECT_EQ(200, r
->GetResponseCode());
4277 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
->status().status());
4278 EXPECT_EQ(2, network_delegate
.created_requests());
4279 EXPECT_EQ(0, network_delegate
.destroyed_requests());
4281 EXPECT_EQ(1, network_delegate
.destroyed_requests());
4283 size_t log_position
= 0;
4284 CapturingNetLog::CapturedEntryList entries
;
4285 net_log_
.GetEntries(&entries
);
4286 // The NetworkDelegate logged information in OnBeforeURLRequest,
4287 // OnBeforeSendHeaders, and OnHeadersReceived.
4288 for (size_t i
= 0; i
< 3; ++i
) {
4289 log_position
= ExpectLogContainsSomewhereAfter(
4292 NetLog::TYPE_URL_REQUEST_DELEGATE
,
4293 NetLog::PHASE_BEGIN
);
4295 log_position
= AsyncDelegateLogger::CheckDelegateInfo(entries
,
4298 ASSERT_LT(log_position
, entries
.size());
4299 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE
, entries
[log_position
].type
);
4300 EXPECT_EQ(NetLog::PHASE_END
, entries
[log_position
].phase
);
4303 log_position
= AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4304 entries
, log_position
+ 1);
4308 // The URLRequest::Delegate then gets informed about the redirect.
4309 log_position
= ExpectLogContainsSomewhereAfter(
4312 NetLog::TYPE_URL_REQUEST_DELEGATE
,
4313 NetLog::PHASE_BEGIN
);
4315 // The NetworkDelegate logged information in the same three events as before.
4316 for (size_t i
= 0; i
< 3; ++i
) {
4317 log_position
= ExpectLogContainsSomewhereAfter(
4320 NetLog::TYPE_URL_REQUEST_DELEGATE
,
4321 NetLog::PHASE_BEGIN
);
4323 log_position
= AsyncDelegateLogger::CheckDelegateInfo(entries
,
4326 ASSERT_LT(log_position
, entries
.size());
4327 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE
, entries
[log_position
].type
);
4328 EXPECT_EQ(NetLog::PHASE_END
, entries
[log_position
].phase
);
4331 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4332 entries
, log_position
+ 1, NetLog::TYPE_DELEGATE_INFO
));
4335 // Tests handling of delegate info from a network delegate in the case of HTTP
4337 TEST_F(URLRequestTestHTTP
, NetworkDelegateInfoAuth
) {
4338 ASSERT_TRUE(test_server_
.Start());
4340 TestDelegate request_delegate
;
4341 AsyncLoggingNetworkDelegate network_delegate
;
4342 TestURLRequestContext
context(true);
4343 context
.set_network_delegate(&network_delegate
);
4344 context
.set_net_log(&net_log_
);
4348 scoped_ptr
<URLRequest
> r(context
.CreateRequest(
4349 test_server_
.GetURL("auth-basic"), DEFAULT_PRIORITY
, &request_delegate
,
4351 LoadStateWithParam load_state
= r
->GetLoadState();
4352 EXPECT_EQ(LOAD_STATE_IDLE
, load_state
.state
);
4353 EXPECT_EQ(base::string16(), load_state
.param
);
4356 base::RunLoop().Run();
4358 EXPECT_EQ(200, r
->GetResponseCode());
4359 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
->status().status());
4360 EXPECT_EQ(1, network_delegate
.created_requests());
4361 EXPECT_EQ(0, network_delegate
.destroyed_requests());
4363 EXPECT_EQ(1, network_delegate
.destroyed_requests());
4365 size_t log_position
= 0;
4366 CapturingNetLog::CapturedEntryList entries
;
4367 net_log_
.GetEntries(&entries
);
4368 // The NetworkDelegate should have logged information in OnBeforeURLRequest,
4369 // OnBeforeSendHeaders, OnHeadersReceived, OnAuthRequired, and then again in
4370 // OnBeforeURLRequest and OnBeforeSendHeaders.
4371 for (size_t i
= 0; i
< 6; ++i
) {
4372 log_position
= ExpectLogContainsSomewhereAfter(
4375 NetLog::TYPE_URL_REQUEST_DELEGATE
,
4376 NetLog::PHASE_BEGIN
);
4378 log_position
= AsyncDelegateLogger::CheckDelegateInfo(entries
,
4381 ASSERT_LT(log_position
, entries
.size());
4382 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE
, entries
[log_position
].type
);
4383 EXPECT_EQ(NetLog::PHASE_END
, entries
[log_position
].phase
);
4386 log_position
= AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4387 entries
, log_position
+ 1);
4391 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4392 entries
, log_position
+ 1, NetLog::TYPE_DELEGATE_INFO
));
4395 // Tests handling of delegate info from a URLRequest::Delegate.
4396 TEST_F(URLRequestTestHTTP
, URLRequestDelegateInfo
) {
4397 ASSERT_TRUE(test_server_
.Start());
4399 AsyncLoggingUrlRequestDelegate
request_delegate(
4400 AsyncLoggingUrlRequestDelegate::NO_CANCEL
);
4401 TestURLRequestContext
context(true);
4402 context
.set_network_delegate(NULL
);
4403 context
.set_net_log(&net_log_
);
4407 // A chunked response with delays between chunks is used to make sure that
4408 // attempts by the URLRequest delegate to log information while reading the
4409 // body are ignored. Since they are ignored, this test is robust against
4410 // the possibility of multiple reads being combined in the unlikely event
4412 scoped_ptr
<URLRequest
> r(context
.CreateRequest(
4413 test_server_
.GetURL("chunked?waitBetweenChunks=20"), DEFAULT_PRIORITY
,
4414 &request_delegate
, NULL
));
4415 LoadStateWithParam load_state
= r
->GetLoadState();
4417 base::RunLoop().Run();
4419 EXPECT_EQ(200, r
->GetResponseCode());
4420 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
->status().status());
4423 CapturingNetLog::CapturedEntryList entries
;
4424 net_log_
.GetEntries(&entries
);
4426 size_t log_position
= 0;
4428 log_position
= AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4429 entries
, log_position
);
4431 // The delegate info should only have been logged on header complete. Other
4432 // times it should silently be ignored.
4434 ExpectLogContainsSomewhereAfter(entries
,
4436 NetLog::TYPE_URL_REQUEST_DELEGATE
,
4437 NetLog::PHASE_BEGIN
);
4439 log_position
= AsyncDelegateLogger::CheckDelegateInfo(entries
,
4442 ASSERT_LT(log_position
, entries
.size());
4443 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE
, entries
[log_position
].type
);
4444 EXPECT_EQ(NetLog::PHASE_END
, entries
[log_position
].phase
);
4446 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4447 entries
, log_position
+ 1, NetLog::TYPE_DELEGATE_INFO
));
4448 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4449 entries
, log_position
+ 1, NetLog::TYPE_URL_REQUEST_DELEGATE
));
4452 // Tests handling of delegate info from a URLRequest::Delegate in the case of
4453 // an HTTP redirect.
4454 TEST_F(URLRequestTestHTTP
, URLRequestDelegateInfoOnRedirect
) {
4455 ASSERT_TRUE(test_server_
.Start());
4457 AsyncLoggingUrlRequestDelegate
request_delegate(
4458 AsyncLoggingUrlRequestDelegate::NO_CANCEL
);
4459 TestURLRequestContext
context(true);
4460 context
.set_network_delegate(NULL
);
4461 context
.set_net_log(&net_log_
);
4465 scoped_ptr
<URLRequest
> r(context
.CreateRequest(
4466 test_server_
.GetURL("server-redirect?simple.html"), DEFAULT_PRIORITY
,
4467 &request_delegate
, NULL
));
4468 LoadStateWithParam load_state
= r
->GetLoadState();
4470 base::RunLoop().Run();
4472 EXPECT_EQ(200, r
->GetResponseCode());
4473 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
->status().status());
4476 CapturingNetLog::CapturedEntryList entries
;
4477 net_log_
.GetEntries(&entries
);
4479 // Delegate info should only have been logged in OnReceivedRedirect and
4480 // OnResponseStarted.
4481 size_t log_position
= 0;
4482 for (int i
= 0; i
< 2; ++i
) {
4484 log_position
= AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4485 entries
, log_position
) + 1;
4488 log_position
= ExpectLogContainsSomewhereAfter(
4491 NetLog::TYPE_URL_REQUEST_DELEGATE
,
4492 NetLog::PHASE_BEGIN
);
4494 log_position
= AsyncDelegateLogger::CheckDelegateInfo(entries
,
4497 ASSERT_LT(log_position
, entries
.size());
4498 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE
, entries
[log_position
].type
);
4499 EXPECT_EQ(NetLog::PHASE_END
, entries
[log_position
].phase
);
4502 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4503 entries
, log_position
+ 1, NetLog::TYPE_DELEGATE_INFO
));
4504 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4505 entries
, log_position
+ 1, NetLog::TYPE_URL_REQUEST_DELEGATE
));
4508 // Tests handling of delegate info from a URLRequest::Delegate in the case of
4509 // an HTTP redirect, with cancellation at various points.
4510 TEST_F(URLRequestTestHTTP
, URLRequestDelegateOnRedirectCancelled
) {
4511 ASSERT_TRUE(test_server_
.Start());
4513 const AsyncLoggingUrlRequestDelegate::CancelStage kCancelStages
[] = {
4514 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RECEIVED_REDIRECT
,
4515 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RESPONSE_STARTED
,
4516 AsyncLoggingUrlRequestDelegate::CANCEL_ON_READ_COMPLETED
,
4519 for (size_t test_case
= 0; test_case
< arraysize(kCancelStages
);
4521 AsyncLoggingUrlRequestDelegate
request_delegate(kCancelStages
[test_case
]);
4522 TestURLRequestContext
context(true);
4523 CapturingNetLog net_log
;
4524 context
.set_network_delegate(NULL
);
4525 context
.set_net_log(&net_log
);
4529 scoped_ptr
<URLRequest
> r(context
.CreateRequest(
4530 test_server_
.GetURL("server-redirect?simple.html"), DEFAULT_PRIORITY
,
4531 &request_delegate
, NULL
));
4532 LoadStateWithParam load_state
= r
->GetLoadState();
4534 base::RunLoop().Run();
4535 EXPECT_EQ(URLRequestStatus::CANCELED
, r
->status().status());
4538 CapturingNetLog::CapturedEntryList entries
;
4539 net_log
.GetEntries(&entries
);
4541 // Delegate info is always logged in both OnReceivedRedirect and
4542 // OnResponseStarted. In the CANCEL_ON_RECEIVED_REDIRECT, the
4543 // OnResponseStarted delegate call is after cancellation, but logging is
4544 // still currently supported in that call.
4545 size_t log_position
= 0;
4546 for (int i
= 0; i
< 2; ++i
) {
4548 log_position
= AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4549 entries
, log_position
) + 1;
4552 log_position
= ExpectLogContainsSomewhereAfter(
4555 NetLog::TYPE_URL_REQUEST_DELEGATE
,
4556 NetLog::PHASE_BEGIN
);
4558 log_position
= AsyncDelegateLogger::CheckDelegateInfo(entries
,
4561 ASSERT_LT(log_position
, entries
.size());
4562 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE
, entries
[log_position
].type
);
4563 EXPECT_EQ(NetLog::PHASE_END
, entries
[log_position
].phase
);
4566 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4567 entries
, log_position
+ 1, NetLog::TYPE_DELEGATE_INFO
));
4568 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4569 entries
, log_position
+ 1, NetLog::TYPE_URL_REQUEST_DELEGATE
));
4575 const char kExtraHeader
[] = "Allow-Snafu";
4576 const char kExtraValue
[] = "fubar";
4578 class RedirectWithAdditionalHeadersDelegate
: public TestDelegate
{
4579 virtual void OnReceivedRedirect(URLRequest
* request
,
4580 const RedirectInfo
& redirect_info
,
4581 bool* defer_redirect
) OVERRIDE
{
4582 TestDelegate::OnReceivedRedirect(request
, redirect_info
, defer_redirect
);
4583 request
->SetExtraRequestHeaderByName(kExtraHeader
, kExtraValue
, false);
4589 TEST_F(URLRequestTestHTTP
, RedirectWithAdditionalHeadersTest
) {
4590 ASSERT_TRUE(test_server_
.Start());
4592 GURL destination_url
= test_server_
.GetURL(
4593 "echoheader?" + std::string(kExtraHeader
));
4594 GURL original_url
= test_server_
.GetURL(
4595 "server-redirect?" + destination_url
.spec());
4596 RedirectWithAdditionalHeadersDelegate d
;
4597 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
4598 original_url
, DEFAULT_PRIORITY
, &d
, NULL
));
4600 base::RunLoop().Run();
4603 const HttpRequestHeaders
& headers
= req
->extra_request_headers();
4604 EXPECT_TRUE(headers
.GetHeader(kExtraHeader
, &value
));
4605 EXPECT_EQ(kExtraValue
, value
);
4606 EXPECT_FALSE(req
->is_pending());
4607 EXPECT_FALSE(req
->is_redirecting());
4608 EXPECT_EQ(kExtraValue
, d
.data_received());
4613 const char kExtraHeaderToRemove
[] = "To-Be-Removed";
4615 class RedirectWithHeaderRemovalDelegate
: public TestDelegate
{
4616 virtual void OnReceivedRedirect(URLRequest
* request
,
4617 const RedirectInfo
& redirect_info
,
4618 bool* defer_redirect
) OVERRIDE
{
4619 TestDelegate::OnReceivedRedirect(request
, redirect_info
, defer_redirect
);
4620 request
->RemoveRequestHeaderByName(kExtraHeaderToRemove
);
4626 TEST_F(URLRequestTestHTTP
, RedirectWithHeaderRemovalTest
) {
4627 ASSERT_TRUE(test_server_
.Start());
4629 GURL destination_url
= test_server_
.GetURL(
4630 "echoheader?" + std::string(kExtraHeaderToRemove
));
4631 GURL original_url
= test_server_
.GetURL(
4632 "server-redirect?" + destination_url
.spec());
4633 RedirectWithHeaderRemovalDelegate d
;
4634 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
4635 original_url
, DEFAULT_PRIORITY
, &d
, NULL
));
4636 req
->SetExtraRequestHeaderByName(kExtraHeaderToRemove
, "dummy", false);
4638 base::RunLoop().Run();
4641 const HttpRequestHeaders
& headers
= req
->extra_request_headers();
4642 EXPECT_FALSE(headers
.GetHeader(kExtraHeaderToRemove
, &value
));
4643 EXPECT_FALSE(req
->is_pending());
4644 EXPECT_FALSE(req
->is_redirecting());
4645 EXPECT_EQ("None", d
.data_received());
4648 TEST_F(URLRequestTestHTTP
, CancelTest
) {
4651 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
4652 GURL("http://www.google.com/"), DEFAULT_PRIORITY
, &d
, NULL
));
4655 EXPECT_TRUE(r
->is_pending());
4659 base::RunLoop().Run();
4661 // We expect to receive OnResponseStarted even though the request has been
4663 EXPECT_EQ(1, d
.response_started_count());
4664 EXPECT_EQ(0, d
.bytes_received());
4665 EXPECT_FALSE(d
.received_data_before_response());
4669 TEST_F(URLRequestTestHTTP
, CancelTest2
) {
4670 ASSERT_TRUE(test_server_
.Start());
4674 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
4675 test_server_
.GetURL(std::string()), DEFAULT_PRIORITY
, &d
, NULL
));
4677 d
.set_cancel_in_response_started(true);
4680 EXPECT_TRUE(r
->is_pending());
4682 base::RunLoop().Run();
4684 EXPECT_EQ(1, d
.response_started_count());
4685 EXPECT_EQ(0, d
.bytes_received());
4686 EXPECT_FALSE(d
.received_data_before_response());
4687 EXPECT_EQ(URLRequestStatus::CANCELED
, r
->status().status());
4691 TEST_F(URLRequestTestHTTP
, CancelTest3
) {
4692 ASSERT_TRUE(test_server_
.Start());
4696 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
4697 test_server_
.GetURL(std::string()), DEFAULT_PRIORITY
, &d
, NULL
));
4699 d
.set_cancel_in_received_data(true);
4702 EXPECT_TRUE(r
->is_pending());
4704 base::RunLoop().Run();
4706 EXPECT_EQ(1, d
.response_started_count());
4707 // There is no guarantee about how much data was received
4708 // before the cancel was issued. It could have been 0 bytes,
4709 // or it could have been all the bytes.
4710 // EXPECT_EQ(0, d.bytes_received());
4711 EXPECT_FALSE(d
.received_data_before_response());
4712 EXPECT_EQ(URLRequestStatus::CANCELED
, r
->status().status());
4716 TEST_F(URLRequestTestHTTP
, CancelTest4
) {
4717 ASSERT_TRUE(test_server_
.Start());
4721 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
4722 test_server_
.GetURL(std::string()), DEFAULT_PRIORITY
, &d
, NULL
));
4725 EXPECT_TRUE(r
->is_pending());
4727 // The request will be implicitly canceled when it is destroyed. The
4728 // test delegate must not post a quit message when this happens because
4729 // this test doesn't actually have a message loop. The quit message would
4730 // get put on this thread's message queue and the next test would exit
4731 // early, causing problems.
4732 d
.set_quit_on_complete(false);
4734 // expect things to just cleanup properly.
4736 // we won't actually get a received reponse here because we've never run the
4738 EXPECT_FALSE(d
.received_data_before_response());
4739 EXPECT_EQ(0, d
.bytes_received());
4742 TEST_F(URLRequestTestHTTP
, CancelTest5
) {
4743 ASSERT_TRUE(test_server_
.Start());
4748 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
4749 test_server_
.GetURL("cachetime"), DEFAULT_PRIORITY
, &d
, NULL
));
4751 base::RunLoop().Run();
4752 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
->status().status());
4755 // cancel read from cache (see bug 990242)
4758 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
4759 test_server_
.GetURL("cachetime"), DEFAULT_PRIORITY
, &d
, NULL
));
4762 base::RunLoop().Run();
4764 EXPECT_EQ(URLRequestStatus::CANCELED
, r
->status().status());
4765 EXPECT_EQ(1, d
.response_started_count());
4766 EXPECT_EQ(0, d
.bytes_received());
4767 EXPECT_FALSE(d
.received_data_before_response());
4771 TEST_F(URLRequestTestHTTP
, PostTest
) {
4772 ASSERT_TRUE(test_server_
.Start());
4773 HTTPUploadDataOperationTest("POST");
4776 TEST_F(URLRequestTestHTTP
, PutTest
) {
4777 ASSERT_TRUE(test_server_
.Start());
4778 HTTPUploadDataOperationTest("PUT");
4781 TEST_F(URLRequestTestHTTP
, PostEmptyTest
) {
4782 ASSERT_TRUE(test_server_
.Start());
4786 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
4787 test_server_
.GetURL("echo"), DEFAULT_PRIORITY
, &d
, NULL
));
4788 r
->set_method("POST");
4791 EXPECT_TRUE(r
->is_pending());
4793 base::RunLoop().Run();
4795 ASSERT_EQ(1, d
.response_started_count())
4796 << "request failed: " << r
->status().status()
4797 << ", error: " << r
->status().error();
4799 EXPECT_FALSE(d
.received_data_before_response());
4800 EXPECT_TRUE(d
.data_received().empty());
4804 TEST_F(URLRequestTestHTTP
, PostFileTest
) {
4805 ASSERT_TRUE(test_server_
.Start());
4809 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
4810 test_server_
.GetURL("echo"), DEFAULT_PRIORITY
, &d
, NULL
));
4811 r
->set_method("POST");
4814 PathService::Get(base::DIR_EXE
, &dir
);
4815 base::SetCurrentDirectory(dir
);
4817 ScopedVector
<UploadElementReader
> element_readers
;
4819 base::FilePath path
;
4820 PathService::Get(base::DIR_SOURCE_ROOT
, &path
);
4821 path
= path
.Append(FILE_PATH_LITERAL("net"));
4822 path
= path
.Append(FILE_PATH_LITERAL("data"));
4823 path
= path
.Append(FILE_PATH_LITERAL("url_request_unittest"));
4824 path
= path
.Append(FILE_PATH_LITERAL("with-headers.html"));
4825 element_readers
.push_back(
4826 new UploadFileElementReader(base::MessageLoopProxy::current().get(),
4831 r
->set_upload(make_scoped_ptr(
4832 new UploadDataStream(element_readers
.Pass(), 0)));
4835 EXPECT_TRUE(r
->is_pending());
4837 base::RunLoop().Run();
4840 ASSERT_EQ(true, base::GetFileSize(path
, &size
));
4841 scoped_ptr
<char[]> buf(new char[size
]);
4843 ASSERT_EQ(size
, base::ReadFile(path
, buf
.get(), size
));
4845 ASSERT_EQ(1, d
.response_started_count())
4846 << "request failed: " << r
->status().status()
4847 << ", error: " << r
->status().error();
4849 EXPECT_FALSE(d
.received_data_before_response());
4851 EXPECT_EQ(size
, d
.bytes_received());
4852 EXPECT_EQ(std::string(&buf
[0], size
), d
.data_received());
4856 TEST_F(URLRequestTestHTTP
, PostUnreadableFileTest
) {
4857 ASSERT_TRUE(test_server_
.Start());
4861 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
4862 test_server_
.GetURL("echo"), DEFAULT_PRIORITY
, &d
, NULL
));
4863 r
->set_method("POST");
4865 ScopedVector
<UploadElementReader
> element_readers
;
4867 element_readers
.push_back(new UploadFileElementReader(
4868 base::MessageLoopProxy::current().get(),
4869 base::FilePath(FILE_PATH_LITERAL(
4870 "c:\\path\\to\\non\\existant\\file.randomness.12345")),
4874 r
->set_upload(make_scoped_ptr(
4875 new UploadDataStream(element_readers
.Pass(), 0)));
4878 EXPECT_TRUE(r
->is_pending());
4880 base::RunLoop().Run();
4882 EXPECT_TRUE(d
.request_failed());
4883 EXPECT_FALSE(d
.received_data_before_response());
4884 EXPECT_EQ(0, d
.bytes_received());
4885 EXPECT_EQ(URLRequestStatus::FAILED
, r
->status().status());
4886 EXPECT_EQ(ERR_FILE_NOT_FOUND
, r
->status().error());
4890 TEST_F(URLRequestTestHTTP
, TestPostChunkedDataBeforeStart
) {
4891 ASSERT_TRUE(test_server_
.Start());
4895 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
4896 test_server_
.GetURL("echo"), DEFAULT_PRIORITY
, &d
, NULL
));
4897 r
->EnableChunkedUpload();
4898 r
->set_method("POST");
4899 AddChunksToUpload(r
.get());
4901 EXPECT_TRUE(r
->is_pending());
4903 base::RunLoop().Run();
4905 VerifyReceivedDataMatchesChunks(r
.get(), &d
);
4909 TEST_F(URLRequestTestHTTP
, TestPostChunkedDataJustAfterStart
) {
4910 ASSERT_TRUE(test_server_
.Start());
4914 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
4915 test_server_
.GetURL("echo"), DEFAULT_PRIORITY
, &d
, NULL
));
4916 r
->EnableChunkedUpload();
4917 r
->set_method("POST");
4919 EXPECT_TRUE(r
->is_pending());
4920 AddChunksToUpload(r
.get());
4921 base::RunLoop().Run();
4923 VerifyReceivedDataMatchesChunks(r
.get(), &d
);
4927 TEST_F(URLRequestTestHTTP
, TestPostChunkedDataAfterStart
) {
4928 ASSERT_TRUE(test_server_
.Start());
4932 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
4933 test_server_
.GetURL("echo"), DEFAULT_PRIORITY
, &d
, NULL
));
4934 r
->EnableChunkedUpload();
4935 r
->set_method("POST");
4937 EXPECT_TRUE(r
->is_pending());
4939 base::RunLoop().RunUntilIdle();
4940 AddChunksToUpload(r
.get());
4941 base::RunLoop().Run();
4943 VerifyReceivedDataMatchesChunks(r
.get(), &d
);
4947 TEST_F(URLRequestTestHTTP
, ResponseHeadersTest
) {
4948 ASSERT_TRUE(test_server_
.Start());
4951 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
4952 test_server_
.GetURL("files/with-headers.html"), DEFAULT_PRIORITY
, &d
,
4955 base::RunLoop().Run();
4957 const HttpResponseHeaders
* headers
= req
->response_headers();
4959 // Simple sanity check that response_info() accesses the same data.
4960 EXPECT_EQ(headers
, req
->response_info().headers
.get());
4963 EXPECT_TRUE(headers
->GetNormalizedHeader("cache-control", &header
));
4964 EXPECT_EQ("private", header
);
4967 EXPECT_TRUE(headers
->GetNormalizedHeader("content-type", &header
));
4968 EXPECT_EQ("text/html; charset=ISO-8859-1", header
);
4970 // The response has two "X-Multiple-Entries" headers.
4971 // This verfies our output has them concatenated together.
4973 EXPECT_TRUE(headers
->GetNormalizedHeader("x-multiple-entries", &header
));
4974 EXPECT_EQ("a, b", header
);
4977 TEST_F(URLRequestTestHTTP
, ProcessSTS
) {
4978 SpawnedTestServer::SSLOptions ssl_options
;
4979 SpawnedTestServer
https_test_server(
4980 SpawnedTestServer::TYPE_HTTPS
,
4982 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
4983 ASSERT_TRUE(https_test_server
.Start());
4986 scoped_ptr
<URLRequest
> request(default_context_
.CreateRequest(
4987 https_test_server
.GetURL("files/hsts-headers.html"), DEFAULT_PRIORITY
, &d
,
4990 base::RunLoop().Run();
4992 TransportSecurityState
* security_state
=
4993 default_context_
.transport_security_state();
4994 TransportSecurityState::DomainState domain_state
;
4995 EXPECT_TRUE(security_state
->GetDynamicDomainState(
4996 SpawnedTestServer::kLocalhost
, &domain_state
));
4997 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS
,
4998 domain_state
.sts
.upgrade_mode
);
4999 EXPECT_TRUE(domain_state
.sts
.include_subdomains
);
5000 EXPECT_FALSE(domain_state
.pkp
.include_subdomains
);
5001 #if defined(OS_ANDROID)
5002 // Android's CertVerifyProc does not (yet) handle pins.
5004 EXPECT_FALSE(domain_state
.HasPublicKeyPins());
5008 // Android's CertVerifyProc does not (yet) handle pins. Therefore, it will
5009 // reject HPKP headers, and a test setting only HPKP headers will fail (no
5010 // DomainState present because header rejected).
5011 #if defined(OS_ANDROID)
5012 #define MAYBE_ProcessPKP DISABLED_ProcessPKP
5014 #define MAYBE_ProcessPKP ProcessPKP
5017 // Tests that enabling HPKP on a domain does not affect the HSTS
5018 // validity/expiration.
5019 TEST_F(URLRequestTestHTTP
, MAYBE_ProcessPKP
) {
5020 SpawnedTestServer::SSLOptions ssl_options
;
5021 SpawnedTestServer
https_test_server(
5022 SpawnedTestServer::TYPE_HTTPS
,
5024 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5025 ASSERT_TRUE(https_test_server
.Start());
5028 scoped_ptr
<URLRequest
> request(default_context_
.CreateRequest(
5029 https_test_server
.GetURL("files/hpkp-headers.html"), DEFAULT_PRIORITY
, &d
,
5032 base::RunLoop().Run();
5034 TransportSecurityState
* security_state
=
5035 default_context_
.transport_security_state();
5036 TransportSecurityState::DomainState domain_state
;
5037 EXPECT_TRUE(security_state
->GetDynamicDomainState(
5038 SpawnedTestServer::kLocalhost
, &domain_state
));
5039 EXPECT_EQ(TransportSecurityState::DomainState::MODE_DEFAULT
,
5040 domain_state
.sts
.upgrade_mode
);
5041 EXPECT_FALSE(domain_state
.sts
.include_subdomains
);
5042 EXPECT_FALSE(domain_state
.pkp
.include_subdomains
);
5043 EXPECT_TRUE(domain_state
.HasPublicKeyPins());
5044 EXPECT_NE(domain_state
.sts
.expiry
, domain_state
.pkp
.expiry
);
5047 TEST_F(URLRequestTestHTTP
, ProcessSTSOnce
) {
5048 SpawnedTestServer::SSLOptions ssl_options
;
5049 SpawnedTestServer
https_test_server(
5050 SpawnedTestServer::TYPE_HTTPS
,
5052 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5053 ASSERT_TRUE(https_test_server
.Start());
5056 scoped_ptr
<URLRequest
> request(default_context_
.CreateRequest(
5057 https_test_server
.GetURL("files/hsts-multiple-headers.html"),
5058 DEFAULT_PRIORITY
, &d
, NULL
));
5060 base::RunLoop().Run();
5062 // We should have set parameters from the first header, not the second.
5063 TransportSecurityState
* security_state
=
5064 default_context_
.transport_security_state();
5065 TransportSecurityState::DomainState domain_state
;
5066 EXPECT_TRUE(security_state
->GetDynamicDomainState(
5067 SpawnedTestServer::kLocalhost
, &domain_state
));
5068 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS
,
5069 domain_state
.sts
.upgrade_mode
);
5070 EXPECT_FALSE(domain_state
.sts
.include_subdomains
);
5071 EXPECT_FALSE(domain_state
.pkp
.include_subdomains
);
5074 TEST_F(URLRequestTestHTTP
, ProcessSTSAndPKP
) {
5075 SpawnedTestServer::SSLOptions ssl_options
;
5076 SpawnedTestServer
https_test_server(
5077 SpawnedTestServer::TYPE_HTTPS
,
5079 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5080 ASSERT_TRUE(https_test_server
.Start());
5083 scoped_ptr
<URLRequest
> request(default_context_
.CreateRequest(
5084 https_test_server
.GetURL("files/hsts-and-hpkp-headers.html"),
5085 DEFAULT_PRIORITY
, &d
, NULL
));
5087 base::RunLoop().Run();
5089 // We should have set parameters from the first header, not the second.
5090 TransportSecurityState
* security_state
=
5091 default_context_
.transport_security_state();
5092 TransportSecurityState::DomainState domain_state
;
5093 EXPECT_TRUE(security_state
->GetDynamicDomainState(
5094 SpawnedTestServer::kLocalhost
, &domain_state
));
5095 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS
,
5096 domain_state
.sts
.upgrade_mode
);
5097 #if defined(OS_ANDROID)
5098 // Android's CertVerifyProc does not (yet) handle pins.
5100 EXPECT_TRUE(domain_state
.HasPublicKeyPins());
5102 EXPECT_NE(domain_state
.sts
.expiry
, domain_state
.pkp
.expiry
);
5104 // Even though there is an HSTS header asserting includeSubdomains, it is
5105 // the *second* such header, and we MUST process only the first.
5106 EXPECT_FALSE(domain_state
.sts
.include_subdomains
);
5107 // includeSubdomains does not occur in the test HPKP header.
5108 EXPECT_FALSE(domain_state
.pkp
.include_subdomains
);
5111 // Tests that when multiple HPKP headers are present, asserting different
5112 // policies, that only the first such policy is processed.
5113 TEST_F(URLRequestTestHTTP
, ProcessSTSAndPKP2
) {
5114 SpawnedTestServer::SSLOptions ssl_options
;
5115 SpawnedTestServer
https_test_server(
5116 SpawnedTestServer::TYPE_HTTPS
,
5118 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5119 ASSERT_TRUE(https_test_server
.Start());
5122 scoped_ptr
<URLRequest
> request(default_context_
.CreateRequest(
5123 https_test_server
.GetURL("files/hsts-and-hpkp-headers2.html"),
5124 DEFAULT_PRIORITY
, &d
, NULL
));
5126 base::RunLoop().Run();
5128 TransportSecurityState
* security_state
=
5129 default_context_
.transport_security_state();
5130 TransportSecurityState::DomainState domain_state
;
5131 EXPECT_TRUE(security_state
->GetDynamicDomainState(
5132 SpawnedTestServer::kLocalhost
, &domain_state
));
5133 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS
,
5134 domain_state
.sts
.upgrade_mode
);
5135 #if defined(OS_ANDROID)
5136 // Android's CertVerifyProc does not (yet) handle pins.
5138 EXPECT_TRUE(domain_state
.HasPublicKeyPins());
5140 EXPECT_NE(domain_state
.sts
.expiry
, domain_state
.pkp
.expiry
);
5142 EXPECT_TRUE(domain_state
.sts
.include_subdomains
);
5143 EXPECT_FALSE(domain_state
.pkp
.include_subdomains
);
5146 TEST_F(URLRequestTestHTTP
, ContentTypeNormalizationTest
) {
5147 ASSERT_TRUE(test_server_
.Start());
5150 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
5151 test_server_
.GetURL("files/content-type-normalization.html"),
5152 DEFAULT_PRIORITY
, &d
, NULL
));
5154 base::RunLoop().Run();
5156 std::string mime_type
;
5157 req
->GetMimeType(&mime_type
);
5158 EXPECT_EQ("text/html", mime_type
);
5160 std::string charset
;
5161 req
->GetCharset(&charset
);
5162 EXPECT_EQ("utf-8", charset
);
5166 TEST_F(URLRequestTestHTTP
, ProtocolHandlerAndFactoryRestrictDataRedirects
) {
5167 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
5168 GURL
data_url("data:,foo");
5169 DataProtocolHandler data_protocol_handler
;
5170 EXPECT_FALSE(data_protocol_handler
.IsSafeRedirectTarget(data_url
));
5172 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
5173 EXPECT_FALSE(job_factory_
.IsSafeRedirectTarget(data_url
));
5176 #if !defined(DISABLE_FILE_SUPPORT)
5177 TEST_F(URLRequestTestHTTP
, ProtocolHandlerAndFactoryRestrictFileRedirects
) {
5178 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
5179 GURL
file_url("file:///foo.txt");
5180 FileProtocolHandler
file_protocol_handler(base::MessageLoopProxy::current());
5181 EXPECT_FALSE(file_protocol_handler
.IsSafeRedirectTarget(file_url
));
5183 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
5184 EXPECT_FALSE(job_factory_
.IsSafeRedirectTarget(file_url
));
5187 TEST_F(URLRequestTestHTTP
, RestrictFileRedirects
) {
5188 ASSERT_TRUE(test_server_
.Start());
5191 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
5192 test_server_
.GetURL("files/redirect-to-file.html"), DEFAULT_PRIORITY
, &d
,
5195 base::RunLoop().Run();
5197 EXPECT_EQ(URLRequestStatus::FAILED
, req
->status().status());
5198 EXPECT_EQ(ERR_UNSAFE_REDIRECT
, req
->status().error());
5200 #endif // !defined(DISABLE_FILE_SUPPORT)
5202 TEST_F(URLRequestTestHTTP
, RestrictDataRedirects
) {
5203 ASSERT_TRUE(test_server_
.Start());
5206 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
5207 test_server_
.GetURL("files/redirect-to-data.html"), DEFAULT_PRIORITY
, &d
,
5210 base::MessageLoop::current()->Run();
5212 EXPECT_EQ(URLRequestStatus::FAILED
, req
->status().status());
5213 EXPECT_EQ(ERR_UNSAFE_REDIRECT
, req
->status().error());
5216 TEST_F(URLRequestTestHTTP
, RedirectToInvalidURL
) {
5217 ASSERT_TRUE(test_server_
.Start());
5220 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
5221 test_server_
.GetURL("files/redirect-to-invalid-url.html"),
5222 DEFAULT_PRIORITY
, &d
, NULL
));
5224 base::RunLoop().Run();
5226 EXPECT_EQ(URLRequestStatus::FAILED
, req
->status().status());
5227 EXPECT_EQ(ERR_INVALID_URL
, req
->status().error());
5230 // Make sure redirects are cached, despite not reading their bodies.
5231 TEST_F(URLRequestTestHTTP
, CacheRedirect
) {
5232 ASSERT_TRUE(test_server_
.Start());
5234 test_server_
.GetURL("files/redirect302-to-echo-cacheable");
5238 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
5239 redirect_url
, DEFAULT_PRIORITY
, &d
, NULL
));
5241 base::RunLoop().Run();
5242 EXPECT_EQ(URLRequestStatus::SUCCESS
, req
->status().status());
5243 EXPECT_EQ(1, d
.received_redirect_count());
5244 EXPECT_EQ(test_server_
.GetURL("echo"), req
->url());
5249 d
.set_quit_on_redirect(true);
5250 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
5251 redirect_url
, DEFAULT_PRIORITY
, &d
, NULL
));
5253 base::RunLoop().Run();
5255 EXPECT_EQ(1, d
.received_redirect_count());
5256 EXPECT_EQ(0, d
.response_started_count());
5257 EXPECT_TRUE(req
->was_cached());
5259 req
->FollowDeferredRedirect();
5260 base::RunLoop().Run();
5261 EXPECT_EQ(1, d
.received_redirect_count());
5262 EXPECT_EQ(1, d
.response_started_count());
5263 EXPECT_EQ(URLRequestStatus::SUCCESS
, req
->status().status());
5264 EXPECT_EQ(test_server_
.GetURL("echo"), req
->url());
5268 // Make sure a request isn't cached when a NetworkDelegate forces a redirect
5269 // when the headers are read, since the body won't have been read.
5270 TEST_F(URLRequestTestHTTP
, NoCacheOnNetworkDelegateRedirect
) {
5271 ASSERT_TRUE(test_server_
.Start());
5272 // URL that is normally cached.
5273 GURL initial_url
= test_server_
.GetURL("cachetime");
5276 // Set up the TestNetworkDelegate tp force a redirect.
5277 GURL redirect_to_url
= test_server_
.GetURL("echo");
5278 default_network_delegate_
.set_redirect_on_headers_received_url(
5282 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
5283 initial_url
, DEFAULT_PRIORITY
, &d
, NULL
));
5285 base::RunLoop().Run();
5286 EXPECT_EQ(URLRequestStatus::SUCCESS
, req
->status().status());
5287 EXPECT_EQ(1, d
.received_redirect_count());
5288 EXPECT_EQ(redirect_to_url
, req
->url());
5293 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
5294 initial_url
, DEFAULT_PRIORITY
, &d
, NULL
));
5296 base::RunLoop().Run();
5298 EXPECT_EQ(URLRequestStatus::SUCCESS
, req
->status().status());
5299 EXPECT_FALSE(req
->was_cached());
5300 EXPECT_EQ(0, d
.received_redirect_count());
5301 EXPECT_EQ(initial_url
, req
->url());
5305 // Tests that redirection to an unsafe URL is allowed when it has been marked as
5307 TEST_F(URLRequestTestHTTP
, UnsafeRedirectToWhitelistedUnsafeURL
) {
5308 ASSERT_TRUE(test_server_
.Start());
5310 GURL
unsafe_url("data:text/html,this-is-considered-an-unsafe-url");
5311 default_network_delegate_
.set_redirect_on_headers_received_url(unsafe_url
);
5312 default_network_delegate_
.set_allowed_unsafe_redirect_url(unsafe_url
);
5316 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
5317 test_server_
.GetURL("whatever"), DEFAULT_PRIORITY
, &d
, NULL
));
5320 base::RunLoop().Run();
5322 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
->status().status());
5324 EXPECT_EQ(2U, r
->url_chain().size());
5325 EXPECT_EQ(OK
, r
->status().error());
5326 EXPECT_EQ(unsafe_url
, r
->url());
5327 EXPECT_EQ("this-is-considered-an-unsafe-url", d
.data_received());
5331 // Tests that a redirect to a different unsafe URL is blocked, even after adding
5332 // some other URL to the whitelist.
5333 TEST_F(URLRequestTestHTTP
, UnsafeRedirectToDifferentUnsafeURL
) {
5334 ASSERT_TRUE(test_server_
.Start());
5336 GURL
unsafe_url("data:text/html,something");
5337 GURL
different_unsafe_url("data:text/html,something-else");
5338 default_network_delegate_
.set_redirect_on_headers_received_url(unsafe_url
);
5339 default_network_delegate_
.set_allowed_unsafe_redirect_url(
5340 different_unsafe_url
);
5344 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
5345 test_server_
.GetURL("whatever"), DEFAULT_PRIORITY
, &d
, NULL
));
5348 base::RunLoop().Run();
5350 EXPECT_EQ(URLRequestStatus::FAILED
, r
->status().status());
5351 EXPECT_EQ(ERR_UNSAFE_REDIRECT
, r
->status().error());
5355 // Redirects from an URL with fragment to an unsafe URL with fragment should
5356 // be allowed, and the reference fragment of the target URL should be preserved.
5357 TEST_F(URLRequestTestHTTP
, UnsafeRedirectWithDifferentReferenceFragment
) {
5358 ASSERT_TRUE(test_server_
.Start());
5360 GURL
original_url(test_server_
.GetURL("original#fragment1"));
5361 GURL
unsafe_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
5362 GURL
expected_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
5364 default_network_delegate_
.set_redirect_on_headers_received_url(unsafe_url
);
5365 default_network_delegate_
.set_allowed_unsafe_redirect_url(unsafe_url
);
5369 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
5370 original_url
, DEFAULT_PRIORITY
, &d
, NULL
));
5373 base::RunLoop().Run();
5375 EXPECT_EQ(2U, r
->url_chain().size());
5376 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
->status().status());
5377 EXPECT_EQ(OK
, r
->status().error());
5378 EXPECT_EQ(original_url
, r
->original_url());
5379 EXPECT_EQ(expected_url
, r
->url());
5383 // When a delegate has specified a safe redirect URL, but it does not match the
5384 // redirect target, then do not prevent the reference fragment from being added.
5385 TEST_F(URLRequestTestHTTP
, RedirectWithReferenceFragmentAndUnrelatedUnsafeUrl
) {
5386 ASSERT_TRUE(test_server_
.Start());
5388 GURL
original_url(test_server_
.GetURL("original#expected-fragment"));
5389 GURL
unsafe_url("data:text/html,this-url-does-not-match-redirect-url");
5390 GURL
redirect_url(test_server_
.GetURL("target"));
5391 GURL
expected_redirect_url(test_server_
.GetURL("target#expected-fragment"));
5393 default_network_delegate_
.set_redirect_on_headers_received_url(redirect_url
);
5394 default_network_delegate_
.set_allowed_unsafe_redirect_url(unsafe_url
);
5398 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
5399 original_url
, DEFAULT_PRIORITY
, &d
, NULL
));
5402 base::RunLoop().Run();
5404 EXPECT_EQ(2U, r
->url_chain().size());
5405 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
->status().status());
5406 EXPECT_EQ(OK
, r
->status().error());
5407 EXPECT_EQ(original_url
, r
->original_url());
5408 EXPECT_EQ(expected_redirect_url
, r
->url());
5412 // When a delegate has specified a safe redirect URL, assume that the redirect
5413 // URL should not be changed. In particular, the reference fragment should not
5415 TEST_F(URLRequestTestHTTP
, RedirectWithReferenceFragment
) {
5416 ASSERT_TRUE(test_server_
.Start());
5418 GURL
original_url(test_server_
.GetURL("original#should-not-be-appended"));
5419 GURL
redirect_url("data:text/html,expect-no-reference-fragment");
5421 default_network_delegate_
.set_redirect_on_headers_received_url(redirect_url
);
5422 default_network_delegate_
.set_allowed_unsafe_redirect_url(redirect_url
);
5426 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
5427 original_url
, DEFAULT_PRIORITY
, &d
, NULL
));
5430 base::RunLoop().Run();
5432 EXPECT_EQ(2U, r
->url_chain().size());
5433 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
->status().status());
5434 EXPECT_EQ(OK
, r
->status().error());
5435 EXPECT_EQ(original_url
, r
->original_url());
5436 EXPECT_EQ(redirect_url
, r
->url());
5440 // When a URLRequestRedirectJob is created, the redirection must be followed and
5441 // the reference fragment of the target URL must not be modified.
5442 TEST_F(URLRequestTestHTTP
, RedirectJobWithReferenceFragment
) {
5443 ASSERT_TRUE(test_server_
.Start());
5445 GURL
original_url(test_server_
.GetURL("original#should-not-be-appended"));
5446 GURL
redirect_url(test_server_
.GetURL("echo"));
5449 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
5450 original_url
, DEFAULT_PRIORITY
, &d
, NULL
));
5452 URLRequestRedirectJob
* job
= new URLRequestRedirectJob(
5453 r
.get(), &default_network_delegate_
, redirect_url
,
5454 URLRequestRedirectJob::REDIRECT_302_FOUND
, "Very Good Reason");
5455 AddTestInterceptor()->set_main_intercept_job(job
);
5458 base::RunLoop().Run();
5460 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
->status().status());
5461 EXPECT_EQ(OK
, r
->status().error());
5462 EXPECT_EQ(original_url
, r
->original_url());
5463 EXPECT_EQ(redirect_url
, r
->url());
5466 TEST_F(URLRequestTestHTTP
, NoUserPassInReferrer
) {
5467 ASSERT_TRUE(test_server_
.Start());
5470 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
5471 test_server_
.GetURL("echoheader?Referer"), DEFAULT_PRIORITY
, &d
, NULL
));
5472 req
->SetReferrer("http://user:pass@foo.com/");
5474 base::RunLoop().Run();
5476 EXPECT_EQ(std::string("http://foo.com/"), d
.data_received());
5479 TEST_F(URLRequestTestHTTP
, NoFragmentInReferrer
) {
5480 ASSERT_TRUE(test_server_
.Start());
5483 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
5484 test_server_
.GetURL("echoheader?Referer"), DEFAULT_PRIORITY
, &d
, NULL
));
5485 req
->SetReferrer("http://foo.com/test#fragment");
5487 base::RunLoop().Run();
5489 EXPECT_EQ(std::string("http://foo.com/test"), d
.data_received());
5492 TEST_F(URLRequestTestHTTP
, EmptyReferrerAfterValidReferrer
) {
5493 ASSERT_TRUE(test_server_
.Start());
5496 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
5497 test_server_
.GetURL("echoheader?Referer"), DEFAULT_PRIORITY
, &d
, NULL
));
5498 req
->SetReferrer("http://foo.com/test#fragment");
5499 req
->SetReferrer("");
5501 base::RunLoop().Run();
5503 EXPECT_EQ(std::string("None"), d
.data_received());
5506 // Defer network start and then resume, checking that the request was a success
5507 // and bytes were received.
5508 TEST_F(URLRequestTestHTTP
, DeferredBeforeNetworkStart
) {
5509 ASSERT_TRUE(test_server_
.Start());
5513 d
.set_quit_on_network_start(true);
5514 GURL
test_url(test_server_
.GetURL("echo"));
5515 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
5516 test_url
, DEFAULT_PRIORITY
, &d
, NULL
));
5519 base::RunLoop().Run();
5521 EXPECT_EQ(1, d
.received_before_network_start_count());
5522 EXPECT_EQ(0, d
.response_started_count());
5524 req
->ResumeNetworkStart();
5525 base::RunLoop().Run();
5527 EXPECT_EQ(1, d
.response_started_count());
5528 EXPECT_NE(0, d
.bytes_received());
5529 EXPECT_EQ(URLRequestStatus::SUCCESS
, req
->status().status());
5533 // Check that OnBeforeNetworkStart is only called once even if there is a
5535 TEST_F(URLRequestTestHTTP
, BeforeNetworkStartCalledOnce
) {
5536 ASSERT_TRUE(test_server_
.Start());
5540 d
.set_quit_on_redirect(true);
5541 d
.set_quit_on_network_start(true);
5542 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
5543 test_server_
.GetURL("server-redirect?echo"), DEFAULT_PRIORITY
, &d
,
5547 base::RunLoop().Run();
5549 EXPECT_EQ(1, d
.received_before_network_start_count());
5550 EXPECT_EQ(0, d
.response_started_count());
5551 EXPECT_EQ(0, d
.received_redirect_count());
5553 req
->ResumeNetworkStart();
5554 base::RunLoop().Run();
5556 EXPECT_EQ(1, d
.received_redirect_count());
5557 req
->FollowDeferredRedirect();
5558 base::RunLoop().Run();
5560 // Check that the redirect's new network transaction does not get propagated
5561 // to a second OnBeforeNetworkStart() notification.
5562 EXPECT_EQ(1, d
.received_before_network_start_count());
5564 EXPECT_EQ(1, d
.response_started_count());
5565 EXPECT_NE(0, d
.bytes_received());
5566 EXPECT_EQ(URLRequestStatus::SUCCESS
, req
->status().status());
5570 // Cancel the request after learning that the request would use the network.
5571 TEST_F(URLRequestTestHTTP
, CancelOnBeforeNetworkStart
) {
5572 ASSERT_TRUE(test_server_
.Start());
5576 d
.set_quit_on_network_start(true);
5577 GURL
test_url(test_server_
.GetURL("echo"));
5578 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
5579 test_url
, DEFAULT_PRIORITY
, &d
, NULL
));
5582 base::RunLoop().Run();
5584 EXPECT_EQ(1, d
.received_before_network_start_count());
5585 EXPECT_EQ(0, d
.response_started_count());
5588 base::RunLoop().Run();
5590 EXPECT_EQ(1, d
.response_started_count());
5591 EXPECT_EQ(0, d
.bytes_received());
5592 EXPECT_EQ(URLRequestStatus::CANCELED
, req
->status().status());
5596 TEST_F(URLRequestTestHTTP
, CancelRedirect
) {
5597 ASSERT_TRUE(test_server_
.Start());
5601 d
.set_cancel_in_received_redirect(true);
5602 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
5603 test_server_
.GetURL("files/redirect-test.html"), DEFAULT_PRIORITY
, &d
,
5606 base::RunLoop().Run();
5608 EXPECT_EQ(1, d
.response_started_count());
5609 EXPECT_EQ(0, d
.bytes_received());
5610 EXPECT_FALSE(d
.received_data_before_response());
5611 EXPECT_EQ(URLRequestStatus::CANCELED
, req
->status().status());
5615 TEST_F(URLRequestTestHTTP
, DeferredRedirect
) {
5616 ASSERT_TRUE(test_server_
.Start());
5620 d
.set_quit_on_redirect(true);
5621 GURL
test_url(test_server_
.GetURL("files/redirect-test.html"));
5622 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
5623 test_url
, DEFAULT_PRIORITY
, &d
, NULL
));
5626 base::RunLoop().Run();
5628 EXPECT_EQ(1, d
.received_redirect_count());
5630 req
->FollowDeferredRedirect();
5631 base::RunLoop().Run();
5633 EXPECT_EQ(1, d
.response_started_count());
5634 EXPECT_FALSE(d
.received_data_before_response());
5635 EXPECT_EQ(URLRequestStatus::SUCCESS
, req
->status().status());
5637 base::FilePath path
;
5638 PathService::Get(base::DIR_SOURCE_ROOT
, &path
);
5639 path
= path
.Append(FILE_PATH_LITERAL("net"));
5640 path
= path
.Append(FILE_PATH_LITERAL("data"));
5641 path
= path
.Append(FILE_PATH_LITERAL("url_request_unittest"));
5642 path
= path
.Append(FILE_PATH_LITERAL("with-headers.html"));
5644 std::string contents
;
5645 EXPECT_TRUE(base::ReadFileToString(path
, &contents
));
5646 EXPECT_EQ(contents
, d
.data_received());
5650 TEST_F(URLRequestTestHTTP
, DeferredRedirect_GetFullRequestHeaders
) {
5651 ASSERT_TRUE(test_server_
.Start());
5655 d
.set_quit_on_redirect(true);
5656 GURL
test_url(test_server_
.GetURL("files/redirect-test.html"));
5657 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
5658 test_url
, DEFAULT_PRIORITY
, &d
, NULL
));
5660 EXPECT_FALSE(d
.have_full_request_headers());
5663 base::RunLoop().Run();
5665 EXPECT_EQ(1, d
.received_redirect_count());
5666 EXPECT_TRUE(d
.have_full_request_headers());
5667 CheckFullRequestHeaders(d
.full_request_headers(), test_url
);
5668 d
.ClearFullRequestHeaders();
5670 req
->FollowDeferredRedirect();
5671 base::RunLoop().Run();
5673 GURL
target_url(test_server_
.GetURL("files/with-headers.html"));
5674 EXPECT_EQ(1, d
.response_started_count());
5675 EXPECT_TRUE(d
.have_full_request_headers());
5676 CheckFullRequestHeaders(d
.full_request_headers(), target_url
);
5677 EXPECT_FALSE(d
.received_data_before_response());
5678 EXPECT_EQ(URLRequestStatus::SUCCESS
, req
->status().status());
5680 base::FilePath path
;
5681 PathService::Get(base::DIR_SOURCE_ROOT
, &path
);
5682 path
= path
.Append(FILE_PATH_LITERAL("net"));
5683 path
= path
.Append(FILE_PATH_LITERAL("data"));
5684 path
= path
.Append(FILE_PATH_LITERAL("url_request_unittest"));
5685 path
= path
.Append(FILE_PATH_LITERAL("with-headers.html"));
5687 std::string contents
;
5688 EXPECT_TRUE(base::ReadFileToString(path
, &contents
));
5689 EXPECT_EQ(contents
, d
.data_received());
5693 TEST_F(URLRequestTestHTTP
, CancelDeferredRedirect
) {
5694 ASSERT_TRUE(test_server_
.Start());
5698 d
.set_quit_on_redirect(true);
5699 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
5700 test_server_
.GetURL("files/redirect-test.html"), DEFAULT_PRIORITY
, &d
,
5703 base::RunLoop().Run();
5705 EXPECT_EQ(1, d
.received_redirect_count());
5708 base::RunLoop().Run();
5710 EXPECT_EQ(1, d
.response_started_count());
5711 EXPECT_EQ(0, d
.bytes_received());
5712 EXPECT_FALSE(d
.received_data_before_response());
5713 EXPECT_EQ(URLRequestStatus::CANCELED
, req
->status().status());
5717 TEST_F(URLRequestTestHTTP
, VaryHeader
) {
5718 ASSERT_TRUE(test_server_
.Start());
5720 // Populate the cache.
5723 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
5724 test_server_
.GetURL("echoheadercache?foo"), DEFAULT_PRIORITY
, &d
,
5726 HttpRequestHeaders headers
;
5727 headers
.SetHeader("foo", "1");
5728 req
->SetExtraRequestHeaders(headers
);
5730 base::RunLoop().Run();
5732 LoadTimingInfo load_timing_info
;
5733 req
->GetLoadTimingInfo(&load_timing_info
);
5734 TestLoadTimingNotReused(load_timing_info
, CONNECT_TIMING_HAS_DNS_TIMES
);
5737 // Expect a cache hit.
5740 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
5741 test_server_
.GetURL("echoheadercache?foo"), DEFAULT_PRIORITY
, &d
,
5743 HttpRequestHeaders headers
;
5744 headers
.SetHeader("foo", "1");
5745 req
->SetExtraRequestHeaders(headers
);
5747 base::RunLoop().Run();
5749 EXPECT_TRUE(req
->was_cached());
5751 LoadTimingInfo load_timing_info
;
5752 req
->GetLoadTimingInfo(&load_timing_info
);
5753 TestLoadTimingCacheHitNoNetwork(load_timing_info
);
5756 // Expect a cache miss.
5759 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
5760 test_server_
.GetURL("echoheadercache?foo"), DEFAULT_PRIORITY
, &d
,
5762 HttpRequestHeaders headers
;
5763 headers
.SetHeader("foo", "2");
5764 req
->SetExtraRequestHeaders(headers
);
5766 base::RunLoop().Run();
5768 EXPECT_FALSE(req
->was_cached());
5770 LoadTimingInfo load_timing_info
;
5771 req
->GetLoadTimingInfo(&load_timing_info
);
5772 TestLoadTimingNotReused(load_timing_info
, CONNECT_TIMING_HAS_DNS_TIMES
);
5776 TEST_F(URLRequestTestHTTP
, BasicAuth
) {
5777 ASSERT_TRUE(test_server_
.Start());
5779 // populate the cache
5782 d
.set_credentials(AuthCredentials(kUser
, kSecret
));
5784 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
5785 test_server_
.GetURL("auth-basic"), DEFAULT_PRIORITY
, &d
, NULL
));
5788 base::RunLoop().Run();
5790 EXPECT_TRUE(d
.data_received().find("user/secret") != std::string::npos
);
5793 // repeat request with end-to-end validation. since auth-basic results in a
5794 // cachable page, we expect this test to result in a 304. in which case, the
5795 // response should be fetched from the cache.
5798 d
.set_credentials(AuthCredentials(kUser
, kSecret
));
5800 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
5801 test_server_
.GetURL("auth-basic"), DEFAULT_PRIORITY
, &d
, NULL
));
5802 r
->SetLoadFlags(LOAD_VALIDATE_CACHE
);
5805 base::RunLoop().Run();
5807 EXPECT_TRUE(d
.data_received().find("user/secret") != std::string::npos
);
5809 // Should be the same cached document.
5810 EXPECT_TRUE(r
->was_cached());
5814 // Check that Set-Cookie headers in 401 responses are respected.
5815 // http://crbug.com/6450
5816 TEST_F(URLRequestTestHTTP
, BasicAuthWithCookies
) {
5817 ASSERT_TRUE(test_server_
.Start());
5819 GURL url_requiring_auth
=
5820 test_server_
.GetURL("auth-basic?set-cookie-if-challenged");
5822 // Request a page that will give a 401 containing a Set-Cookie header.
5823 // Verify that when the transaction is restarted, it includes the new cookie.
5825 TestNetworkDelegate network_delegate
; // Must outlive URLRequest.
5826 TestURLRequestContext
context(true);
5827 context
.set_network_delegate(&network_delegate
);
5831 d
.set_credentials(AuthCredentials(kUser
, kSecret
));
5833 scoped_ptr
<URLRequest
> r(context
.CreateRequest(
5834 url_requiring_auth
, DEFAULT_PRIORITY
, &d
, NULL
));
5837 base::RunLoop().Run();
5839 EXPECT_TRUE(d
.data_received().find("user/secret") != std::string::npos
);
5841 // Make sure we sent the cookie in the restarted transaction.
5842 EXPECT_TRUE(d
.data_received().find("Cookie: got_challenged=true")
5843 != std::string::npos
);
5846 // Same test as above, except this time the restart is initiated earlier
5847 // (without user intervention since identity is embedded in the URL).
5849 TestNetworkDelegate network_delegate
; // Must outlive URLRequest.
5850 TestURLRequestContext
context(true);
5851 context
.set_network_delegate(&network_delegate
);
5856 GURL::Replacements replacements
;
5857 std::string
username("user2");
5858 std::string
password("secret");
5859 replacements
.SetUsernameStr(username
);
5860 replacements
.SetPasswordStr(password
);
5861 GURL url_with_identity
= url_requiring_auth
.ReplaceComponents(replacements
);
5863 scoped_ptr
<URLRequest
> r(context
.CreateRequest(
5864 url_with_identity
, DEFAULT_PRIORITY
, &d
, NULL
));
5867 base::RunLoop().Run();
5869 EXPECT_TRUE(d
.data_received().find("user2/secret") != std::string::npos
);
5871 // Make sure we sent the cookie in the restarted transaction.
5872 EXPECT_TRUE(d
.data_received().find("Cookie: got_challenged=true")
5873 != std::string::npos
);
5877 // Tests that load timing works as expected with auth and the cache.
5878 TEST_F(URLRequestTestHTTP
, BasicAuthLoadTiming
) {
5879 ASSERT_TRUE(test_server_
.Start());
5881 // populate the cache
5884 d
.set_credentials(AuthCredentials(kUser
, kSecret
));
5886 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
5887 test_server_
.GetURL("auth-basic"), DEFAULT_PRIORITY
, &d
, NULL
));
5890 base::RunLoop().Run();
5892 EXPECT_TRUE(d
.data_received().find("user/secret") != std::string::npos
);
5894 LoadTimingInfo load_timing_info_before_auth
;
5895 EXPECT_TRUE(default_network_delegate_
.GetLoadTimingInfoBeforeAuth(
5896 &load_timing_info_before_auth
));
5897 TestLoadTimingNotReused(load_timing_info_before_auth
,
5898 CONNECT_TIMING_HAS_DNS_TIMES
);
5900 LoadTimingInfo load_timing_info
;
5901 r
->GetLoadTimingInfo(&load_timing_info
);
5902 // The test server does not support keep alive sockets, so the second
5903 // request with auth should use a new socket.
5904 TestLoadTimingNotReused(load_timing_info
, CONNECT_TIMING_HAS_DNS_TIMES
);
5905 EXPECT_NE(load_timing_info_before_auth
.socket_log_id
,
5906 load_timing_info
.socket_log_id
);
5907 EXPECT_LE(load_timing_info_before_auth
.receive_headers_end
,
5908 load_timing_info
.connect_timing
.connect_start
);
5911 // Repeat request with end-to-end validation. Since auth-basic results in a
5912 // cachable page, we expect this test to result in a 304. In which case, the
5913 // response should be fetched from the cache.
5916 d
.set_credentials(AuthCredentials(kUser
, kSecret
));
5918 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
5919 test_server_
.GetURL("auth-basic"), DEFAULT_PRIORITY
, &d
, NULL
));
5920 r
->SetLoadFlags(LOAD_VALIDATE_CACHE
);
5923 base::RunLoop().Run();
5925 EXPECT_TRUE(d
.data_received().find("user/secret") != std::string::npos
);
5927 // Should be the same cached document.
5928 EXPECT_TRUE(r
->was_cached());
5930 // Since there was a request that went over the wire, the load timing
5931 // information should include connection times.
5932 LoadTimingInfo load_timing_info
;
5933 r
->GetLoadTimingInfo(&load_timing_info
);
5934 TestLoadTimingNotReused(load_timing_info
, CONNECT_TIMING_HAS_DNS_TIMES
);
5938 // In this test, we do a POST which the server will 302 redirect.
5939 // The subsequent transaction should use GET, and should not send the
5940 // Content-Type header.
5941 // http://code.google.com/p/chromium/issues/detail?id=843
5942 TEST_F(URLRequestTestHTTP
, Post302RedirectGet
) {
5943 ASSERT_TRUE(test_server_
.Start());
5945 const char kData
[] = "hello world";
5948 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
5949 test_server_
.GetURL("files/redirect-to-echoall"), DEFAULT_PRIORITY
, &d
,
5951 req
->set_method("POST");
5952 req
->set_upload(make_scoped_ptr(CreateSimpleUploadData(kData
)));
5954 // Set headers (some of which are specific to the POST).
5955 HttpRequestHeaders headers
;
5956 headers
.AddHeadersFromString(
5957 "Content-Type: multipart/form-data; "
5958 "boundary=----WebKitFormBoundaryAADeAA+NAAWMAAwZ\r\n"
5959 "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,"
5960 "text/plain;q=0.8,image/png,*/*;q=0.5\r\n"
5961 "Accept-Language: en-US,en\r\n"
5962 "Accept-Charset: ISO-8859-1,*,utf-8\r\n"
5963 "Content-Length: 11\r\n"
5964 "Origin: http://localhost:1337/");
5965 req
->SetExtraRequestHeaders(headers
);
5967 base::RunLoop().Run();
5969 std::string mime_type
;
5970 req
->GetMimeType(&mime_type
);
5971 EXPECT_EQ("text/html", mime_type
);
5973 const std::string
& data
= d
.data_received();
5975 // Check that the post-specific headers were stripped:
5976 EXPECT_FALSE(ContainsString(data
, "Content-Length:"));
5977 EXPECT_FALSE(ContainsString(data
, "Content-Type:"));
5978 EXPECT_FALSE(ContainsString(data
, "Origin:"));
5980 // These extra request headers should not have been stripped.
5981 EXPECT_TRUE(ContainsString(data
, "Accept:"));
5982 EXPECT_TRUE(ContainsString(data
, "Accept-Language:"));
5983 EXPECT_TRUE(ContainsString(data
, "Accept-Charset:"));
5986 // The following tests check that we handle mutating the request method for
5987 // HTTP redirects as expected.
5988 // See http://crbug.com/56373 and http://crbug.com/102130.
5990 TEST_F(URLRequestTestHTTP
, Redirect301Tests
) {
5991 ASSERT_TRUE(test_server_
.Start());
5993 const GURL url
= test_server_
.GetURL("files/redirect301-to-echo");
5995 HTTPRedirectMethodTest(url
, "POST", "GET", true);
5996 HTTPRedirectMethodTest(url
, "PUT", "PUT", true);
5997 HTTPRedirectMethodTest(url
, "HEAD", "HEAD", false);
6000 TEST_F(URLRequestTestHTTP
, Redirect302Tests
) {
6001 ASSERT_TRUE(test_server_
.Start());
6003 const GURL url
= test_server_
.GetURL("files/redirect302-to-echo");
6005 HTTPRedirectMethodTest(url
, "POST", "GET", true);
6006 HTTPRedirectMethodTest(url
, "PUT", "PUT", true);
6007 HTTPRedirectMethodTest(url
, "HEAD", "HEAD", false);
6010 TEST_F(URLRequestTestHTTP
, Redirect303Tests
) {
6011 ASSERT_TRUE(test_server_
.Start());
6013 const GURL url
= test_server_
.GetURL("files/redirect303-to-echo");
6015 HTTPRedirectMethodTest(url
, "POST", "GET", true);
6016 HTTPRedirectMethodTest(url
, "PUT", "GET", true);
6017 HTTPRedirectMethodTest(url
, "HEAD", "HEAD", false);
6020 TEST_F(URLRequestTestHTTP
, Redirect307Tests
) {
6021 ASSERT_TRUE(test_server_
.Start());
6023 const GURL url
= test_server_
.GetURL("files/redirect307-to-echo");
6025 HTTPRedirectMethodTest(url
, "POST", "POST", true);
6026 HTTPRedirectMethodTest(url
, "PUT", "PUT", true);
6027 HTTPRedirectMethodTest(url
, "HEAD", "HEAD", false);
6030 TEST_F(URLRequestTestHTTP
, Redirect308Tests
) {
6031 ASSERT_TRUE(test_server_
.Start());
6033 const GURL url
= test_server_
.GetURL("files/redirect308-to-echo");
6035 HTTPRedirectMethodTest(url
, "POST", "POST", true);
6036 HTTPRedirectMethodTest(url
, "PUT", "PUT", true);
6037 HTTPRedirectMethodTest(url
, "HEAD", "HEAD", false);
6040 // Make sure that 308 responses without bodies are not treated as redirects.
6041 // Certain legacy apis that pre-date the response code expect this behavior
6042 // (Like Google Drive).
6043 TEST_F(URLRequestTestHTTP
, NoRedirectOn308WithoutLocationHeader
) {
6044 ASSERT_TRUE(test_server_
.Start());
6047 const GURL url
= test_server_
.GetURL("files/308-without-location-header");
6049 scoped_ptr
<URLRequest
> request(default_context_
.CreateRequest(
6050 url
, DEFAULT_PRIORITY
, &d
, NULL
));
6053 base::RunLoop().Run();
6054 EXPECT_EQ(URLRequestStatus::SUCCESS
, request
->status().status());
6055 EXPECT_EQ(OK
, request
->status().error());
6056 EXPECT_EQ(0, d
.received_redirect_count());
6057 EXPECT_EQ(308, request
->response_headers()->response_code());
6058 EXPECT_EQ("This is not a redirect.", d
.data_received());
6061 TEST_F(URLRequestTestHTTP
, Redirect302PreserveReferenceFragment
) {
6062 ASSERT_TRUE(test_server_
.Start());
6064 GURL
original_url(test_server_
.GetURL("files/redirect302-to-echo#fragment"));
6065 GURL
expected_url(test_server_
.GetURL("echo#fragment"));
6069 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
6070 original_url
, DEFAULT_PRIORITY
, &d
, NULL
));
6073 base::RunLoop().Run();
6075 EXPECT_EQ(2U, r
->url_chain().size());
6076 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
->status().status());
6077 EXPECT_EQ(OK
, r
->status().error());
6078 EXPECT_EQ(original_url
, r
->original_url());
6079 EXPECT_EQ(expected_url
, r
->url());
6083 TEST_F(URLRequestTestHTTP
, RedirectPreserveFirstPartyURL
) {
6084 ASSERT_TRUE(test_server_
.Start());
6086 GURL
url(test_server_
.GetURL("files/redirect302-to-echo"));
6087 GURL
first_party_url("http://example.com");
6091 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
6092 url
, DEFAULT_PRIORITY
, &d
, NULL
));
6093 r
->set_first_party_for_cookies(first_party_url
);
6096 base::RunLoop().Run();
6098 EXPECT_EQ(2U, r
->url_chain().size());
6099 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
->status().status());
6100 EXPECT_EQ(OK
, r
->status().error());
6101 EXPECT_EQ(first_party_url
, r
->first_party_for_cookies());
6105 TEST_F(URLRequestTestHTTP
, RedirectUpdateFirstPartyURL
) {
6106 ASSERT_TRUE(test_server_
.Start());
6108 GURL
url(test_server_
.GetURL("files/redirect302-to-echo"));
6109 GURL
original_first_party_url("http://example.com");
6110 GURL
expected_first_party_url(test_server_
.GetURL("echo"));
6114 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
6115 url
, DEFAULT_PRIORITY
, &d
, NULL
));
6116 r
->set_first_party_for_cookies(original_first_party_url
);
6117 r
->set_first_party_url_policy(
6118 URLRequest::UPDATE_FIRST_PARTY_URL_ON_REDIRECT
);
6121 base::RunLoop().Run();
6123 EXPECT_EQ(2U, r
->url_chain().size());
6124 EXPECT_EQ(URLRequestStatus::SUCCESS
, r
->status().status());
6125 EXPECT_EQ(OK
, r
->status().error());
6126 EXPECT_EQ(expected_first_party_url
, r
->first_party_for_cookies());
6130 TEST_F(URLRequestTestHTTP
, InterceptPost302RedirectGet
) {
6131 ASSERT_TRUE(test_server_
.Start());
6133 const char kData
[] = "hello world";
6136 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
6137 test_server_
.GetURL("empty.html"), DEFAULT_PRIORITY
, &d
, NULL
));
6138 req
->set_method("POST");
6139 req
->set_upload(make_scoped_ptr(CreateSimpleUploadData(kData
)));
6140 HttpRequestHeaders headers
;
6141 headers
.SetHeader(HttpRequestHeaders::kContentLength
,
6142 base::UintToString(arraysize(kData
) - 1));
6143 req
->SetExtraRequestHeaders(headers
);
6145 URLRequestRedirectJob
* job
= new URLRequestRedirectJob(
6146 req
.get(), &default_network_delegate_
, test_server_
.GetURL("echo"),
6147 URLRequestRedirectJob::REDIRECT_302_FOUND
, "Very Good Reason");
6148 AddTestInterceptor()->set_main_intercept_job(job
);
6151 base::RunLoop().Run();
6152 EXPECT_EQ("GET", req
->method());
6155 TEST_F(URLRequestTestHTTP
, InterceptPost307RedirectPost
) {
6156 ASSERT_TRUE(test_server_
.Start());
6158 const char kData
[] = "hello world";
6161 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
6162 test_server_
.GetURL("empty.html"), DEFAULT_PRIORITY
, &d
, NULL
));
6163 req
->set_method("POST");
6164 req
->set_upload(make_scoped_ptr(CreateSimpleUploadData(kData
)));
6165 HttpRequestHeaders headers
;
6166 headers
.SetHeader(HttpRequestHeaders::kContentLength
,
6167 base::UintToString(arraysize(kData
) - 1));
6168 req
->SetExtraRequestHeaders(headers
);
6170 URLRequestRedirectJob
* job
= new URLRequestRedirectJob(
6171 req
.get(), &default_network_delegate_
, test_server_
.GetURL("echo"),
6172 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT
,
6173 "Very Good Reason");
6174 AddTestInterceptor()->set_main_intercept_job(job
);
6177 base::RunLoop().Run();
6178 EXPECT_EQ("POST", req
->method());
6179 EXPECT_EQ(kData
, d
.data_received());
6182 // Check that default A-L header is sent.
6183 TEST_F(URLRequestTestHTTP
, DefaultAcceptLanguage
) {
6184 ASSERT_TRUE(test_server_
.Start());
6186 StaticHttpUserAgentSettings
settings("en", std::string());
6187 TestNetworkDelegate network_delegate
; // Must outlive URLRequests.
6188 TestURLRequestContext
context(true);
6189 context
.set_network_delegate(&network_delegate
);
6190 context
.set_http_user_agent_settings(&settings
);
6194 scoped_ptr
<URLRequest
> req(context
.CreateRequest(
6195 test_server_
.GetURL("echoheader?Accept-Language"), DEFAULT_PRIORITY
, &d
,
6198 base::RunLoop().Run();
6199 EXPECT_EQ("en", d
.data_received());
6202 // Check that an empty A-L header is not sent. http://crbug.com/77365.
6203 TEST_F(URLRequestTestHTTP
, EmptyAcceptLanguage
) {
6204 ASSERT_TRUE(test_server_
.Start());
6206 std::string empty_string
; // Avoid most vexing parse on line below.
6207 StaticHttpUserAgentSettings
settings(empty_string
, empty_string
);
6208 TestNetworkDelegate network_delegate
; // Must outlive URLRequests.
6209 TestURLRequestContext
context(true);
6210 context
.set_network_delegate(&network_delegate
);
6212 // We override the language after initialization because empty entries
6213 // get overridden by Init().
6214 context
.set_http_user_agent_settings(&settings
);
6217 scoped_ptr
<URLRequest
> req(context
.CreateRequest(
6218 test_server_
.GetURL("echoheader?Accept-Language"), DEFAULT_PRIORITY
, &d
,
6221 base::RunLoop().Run();
6222 EXPECT_EQ("None", d
.data_received());
6225 // Check that if request overrides the A-L header, the default is not appended.
6226 // See http://crbug.com/20894
6227 TEST_F(URLRequestTestHTTP
, OverrideAcceptLanguage
) {
6228 ASSERT_TRUE(test_server_
.Start());
6231 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
6232 test_server_
.GetURL("echoheader?Accept-Language"), DEFAULT_PRIORITY
, &d
,
6234 HttpRequestHeaders headers
;
6235 headers
.SetHeader(HttpRequestHeaders::kAcceptLanguage
, "ru");
6236 req
->SetExtraRequestHeaders(headers
);
6238 base::RunLoop().Run();
6239 EXPECT_EQ(std::string("ru"), d
.data_received());
6242 // Check that default A-E header is sent.
6243 TEST_F(URLRequestTestHTTP
, DefaultAcceptEncoding
) {
6244 ASSERT_TRUE(test_server_
.Start());
6247 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
6248 test_server_
.GetURL("echoheader?Accept-Encoding"), DEFAULT_PRIORITY
, &d
,
6250 HttpRequestHeaders headers
;
6251 req
->SetExtraRequestHeaders(headers
);
6253 base::RunLoop().Run();
6254 EXPECT_TRUE(ContainsString(d
.data_received(), "gzip"));
6257 // Check that if request overrides the A-E header, the default is not appended.
6258 // See http://crbug.com/47381
6259 TEST_F(URLRequestTestHTTP
, OverrideAcceptEncoding
) {
6260 ASSERT_TRUE(test_server_
.Start());
6263 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
6264 test_server_
.GetURL("echoheader?Accept-Encoding"), DEFAULT_PRIORITY
, &d
,
6266 HttpRequestHeaders headers
;
6267 headers
.SetHeader(HttpRequestHeaders::kAcceptEncoding
, "identity");
6268 req
->SetExtraRequestHeaders(headers
);
6270 base::RunLoop().Run();
6271 EXPECT_FALSE(ContainsString(d
.data_received(), "gzip"));
6272 EXPECT_TRUE(ContainsString(d
.data_received(), "identity"));
6275 // Check that setting the A-C header sends the proper header.
6276 TEST_F(URLRequestTestHTTP
, SetAcceptCharset
) {
6277 ASSERT_TRUE(test_server_
.Start());
6280 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
6281 test_server_
.GetURL("echoheader?Accept-Charset"), DEFAULT_PRIORITY
, &d
,
6283 HttpRequestHeaders headers
;
6284 headers
.SetHeader(HttpRequestHeaders::kAcceptCharset
, "koi-8r");
6285 req
->SetExtraRequestHeaders(headers
);
6287 base::RunLoop().Run();
6288 EXPECT_EQ(std::string("koi-8r"), d
.data_received());
6291 // Check that default User-Agent header is sent.
6292 TEST_F(URLRequestTestHTTP
, DefaultUserAgent
) {
6293 ASSERT_TRUE(test_server_
.Start());
6296 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
6297 test_server_
.GetURL("echoheader?User-Agent"), DEFAULT_PRIORITY
, &d
,
6300 base::RunLoop().Run();
6301 EXPECT_EQ(default_context_
.http_user_agent_settings()->GetUserAgent(),
6305 // Check that if request overrides the User-Agent header,
6306 // the default is not appended.
6307 TEST_F(URLRequestTestHTTP
, OverrideUserAgent
) {
6308 ASSERT_TRUE(test_server_
.Start());
6311 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
6312 test_server_
.GetURL("echoheader?User-Agent"), DEFAULT_PRIORITY
, &d
,
6314 HttpRequestHeaders headers
;
6315 headers
.SetHeader(HttpRequestHeaders::kUserAgent
, "Lynx (textmode)");
6316 req
->SetExtraRequestHeaders(headers
);
6318 base::RunLoop().Run();
6319 EXPECT_EQ(std::string("Lynx (textmode)"), d
.data_received());
6322 // Check that a NULL HttpUserAgentSettings causes the corresponding empty
6323 // User-Agent header to be sent but does not send the Accept-Language and
6324 // Accept-Charset headers.
6325 TEST_F(URLRequestTestHTTP
, EmptyHttpUserAgentSettings
) {
6326 ASSERT_TRUE(test_server_
.Start());
6328 TestNetworkDelegate network_delegate
; // Must outlive URLRequests.
6329 TestURLRequestContext
context(true);
6330 context
.set_network_delegate(&network_delegate
);
6332 // We override the HttpUserAgentSettings after initialization because empty
6333 // entries get overridden by Init().
6334 context
.set_http_user_agent_settings(NULL
);
6337 const char* request
;
6338 const char* expected_response
;
6339 } tests
[] = { { "echoheader?Accept-Language", "None" },
6340 { "echoheader?Accept-Charset", "None" },
6341 { "echoheader?User-Agent", "" } };
6343 for (size_t i
= 0; i
< ARRAYSIZE_UNSAFE(tests
); i
++) {
6345 scoped_ptr
<URLRequest
> req(context
.CreateRequest(
6346 test_server_
.GetURL(tests
[i
].request
), DEFAULT_PRIORITY
, &d
, NULL
));
6348 base::RunLoop().Run();
6349 EXPECT_EQ(tests
[i
].expected_response
, d
.data_received())
6350 << " Request = \"" << tests
[i
].request
<< "\"";
6354 // Make sure that URLRequest passes on its priority updates to
6355 // newly-created jobs after the first one.
6356 TEST_F(URLRequestTestHTTP
, SetSubsequentJobPriority
) {
6357 ASSERT_TRUE(test_server_
.Start());
6360 scoped_ptr
<URLRequest
> req(default_context_
.CreateRequest(
6361 test_server_
.GetURL("empty.html"), DEFAULT_PRIORITY
, &d
, NULL
));
6362 EXPECT_EQ(DEFAULT_PRIORITY
, req
->priority());
6364 scoped_refptr
<URLRequestRedirectJob
> redirect_job
=
6365 new URLRequestRedirectJob(
6366 req
.get(), &default_network_delegate_
, test_server_
.GetURL("echo"),
6367 URLRequestRedirectJob::REDIRECT_302_FOUND
, "Very Good Reason");
6368 AddTestInterceptor()->set_main_intercept_job(redirect_job
.get());
6370 req
->SetPriority(LOW
);
6372 EXPECT_TRUE(req
->is_pending());
6374 scoped_refptr
<URLRequestTestJob
> job
=
6375 new URLRequestTestJob(req
.get(), &default_network_delegate_
);
6376 AddTestInterceptor()->set_main_intercept_job(job
.get());
6378 // Should trigger |job| to be started.
6379 base::RunLoop().Run();
6380 EXPECT_EQ(LOW
, job
->priority());
6383 // Check that creating a network request while entering/exiting suspend mode
6384 // fails as it should. This is the only case where an HttpTransactionFactory
6385 // does not return an HttpTransaction.
6386 TEST_F(URLRequestTestHTTP
, NetworkSuspendTest
) {
6387 // Create a new HttpNetworkLayer that thinks it's suspended.
6388 HttpNetworkSession::Params params
;
6389 params
.host_resolver
= default_context_
.host_resolver();
6390 params
.cert_verifier
= default_context_
.cert_verifier();
6391 params
.transport_security_state
= default_context_
.transport_security_state();
6392 params
.proxy_service
= default_context_
.proxy_service();
6393 params
.ssl_config_service
= default_context_
.ssl_config_service();
6394 params
.http_auth_handler_factory
=
6395 default_context_
.http_auth_handler_factory();
6396 params
.network_delegate
= &default_network_delegate_
;
6397 params
.http_server_properties
= default_context_
.http_server_properties();
6398 scoped_ptr
<HttpNetworkLayer
> network_layer(
6399 new HttpNetworkLayer(new HttpNetworkSession(params
)));
6400 network_layer
->OnSuspend();
6402 HttpCache
http_cache(network_layer
.release(), default_context_
.net_log(),
6403 HttpCache::DefaultBackend::InMemory(0));
6405 TestURLRequestContext
context(true);
6406 context
.set_http_transaction_factory(&http_cache
);
6410 scoped_ptr
<URLRequest
> req(context
.CreateRequest(
6411 GURL("http://127.0.0.1/"), DEFAULT_PRIORITY
, &d
, NULL
));
6413 base::RunLoop().Run();
6415 EXPECT_TRUE(d
.request_failed());
6416 EXPECT_EQ(URLRequestStatus::FAILED
, req
->status().status());
6417 EXPECT_EQ(ERR_NETWORK_IO_SUSPENDED
, req
->status().error());
6420 // Check that creating a network request while entering/exiting suspend mode
6421 // fails as it should in the case there is no cache. This is the only case
6422 // where an HttpTransactionFactory does not return an HttpTransaction.
6423 TEST_F(URLRequestTestHTTP
, NetworkSuspendTestNoCache
) {
6424 // Create a new HttpNetworkLayer that thinks it's suspended.
6425 HttpNetworkSession::Params params
;
6426 params
.host_resolver
= default_context_
.host_resolver();
6427 params
.cert_verifier
= default_context_
.cert_verifier();
6428 params
.transport_security_state
= default_context_
.transport_security_state();
6429 params
.proxy_service
= default_context_
.proxy_service();
6430 params
.ssl_config_service
= default_context_
.ssl_config_service();
6431 params
.http_auth_handler_factory
=
6432 default_context_
.http_auth_handler_factory();
6433 params
.network_delegate
= &default_network_delegate_
;
6434 params
.http_server_properties
= default_context_
.http_server_properties();
6435 HttpNetworkLayer
network_layer(new HttpNetworkSession(params
));
6436 network_layer
.OnSuspend();
6438 TestURLRequestContext
context(true);
6439 context
.set_http_transaction_factory(&network_layer
);
6443 scoped_ptr
<URLRequest
> req(context
.CreateRequest(
6444 GURL("http://127.0.0.1/"), DEFAULT_PRIORITY
, &d
, NULL
));
6446 base::RunLoop().Run();
6448 EXPECT_TRUE(d
.request_failed());
6449 EXPECT_EQ(URLRequestStatus::FAILED
, req
->status().status());
6450 EXPECT_EQ(ERR_NETWORK_IO_SUSPENDED
, req
->status().error());
6453 class HTTPSRequestTest
: public testing::Test
{
6455 HTTPSRequestTest() : default_context_(true) {
6456 default_context_
.set_network_delegate(&default_network_delegate_
);
6457 default_context_
.Init();
6459 virtual ~HTTPSRequestTest() {}
6462 TestNetworkDelegate default_network_delegate_
; // Must outlive URLRequest.
6463 TestURLRequestContext default_context_
;
6466 TEST_F(HTTPSRequestTest
, HTTPSGetTest
) {
6467 SpawnedTestServer
test_server(
6468 SpawnedTestServer::TYPE_HTTPS
,
6469 SpawnedTestServer::kLocalhost
,
6470 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6471 ASSERT_TRUE(test_server
.Start());
6475 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
6476 test_server
.GetURL(std::string()), DEFAULT_PRIORITY
, &d
, NULL
));
6478 EXPECT_TRUE(r
->is_pending());
6480 base::RunLoop().Run();
6482 EXPECT_EQ(1, d
.response_started_count());
6483 EXPECT_FALSE(d
.received_data_before_response());
6484 EXPECT_NE(0, d
.bytes_received());
6485 CheckSSLInfo(r
->ssl_info());
6486 EXPECT_EQ(test_server
.host_port_pair().host(),
6487 r
->GetSocketAddress().host());
6488 EXPECT_EQ(test_server
.host_port_pair().port(),
6489 r
->GetSocketAddress().port());
6493 TEST_F(HTTPSRequestTest
, HTTPSMismatchedTest
) {
6494 SpawnedTestServer::SSLOptions
ssl_options(
6495 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME
);
6496 SpawnedTestServer
test_server(
6497 SpawnedTestServer::TYPE_HTTPS
,
6499 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6500 ASSERT_TRUE(test_server
.Start());
6502 bool err_allowed
= true;
6503 for (int i
= 0; i
< 2 ; i
++, err_allowed
= !err_allowed
) {
6506 d
.set_allow_certificate_errors(err_allowed
);
6507 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
6508 test_server
.GetURL(std::string()), DEFAULT_PRIORITY
, &d
, NULL
));
6511 EXPECT_TRUE(r
->is_pending());
6513 base::RunLoop().Run();
6515 EXPECT_EQ(1, d
.response_started_count());
6516 EXPECT_FALSE(d
.received_data_before_response());
6517 EXPECT_TRUE(d
.have_certificate_errors());
6519 EXPECT_NE(0, d
.bytes_received());
6520 CheckSSLInfo(r
->ssl_info());
6522 EXPECT_EQ(0, d
.bytes_received());
6528 TEST_F(HTTPSRequestTest
, HTTPSExpiredTest
) {
6529 SpawnedTestServer::SSLOptions
ssl_options(
6530 SpawnedTestServer::SSLOptions::CERT_EXPIRED
);
6531 SpawnedTestServer
test_server(
6532 SpawnedTestServer::TYPE_HTTPS
,
6534 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6535 ASSERT_TRUE(test_server
.Start());
6537 // Iterate from false to true, just so that we do the opposite of the
6538 // previous test in order to increase test coverage.
6539 bool err_allowed
= false;
6540 for (int i
= 0; i
< 2 ; i
++, err_allowed
= !err_allowed
) {
6543 d
.set_allow_certificate_errors(err_allowed
);
6544 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
6545 test_server
.GetURL(std::string()), DEFAULT_PRIORITY
, &d
, NULL
));
6548 EXPECT_TRUE(r
->is_pending());
6550 base::RunLoop().Run();
6552 EXPECT_EQ(1, d
.response_started_count());
6553 EXPECT_FALSE(d
.received_data_before_response());
6554 EXPECT_TRUE(d
.have_certificate_errors());
6556 EXPECT_NE(0, d
.bytes_received());
6557 CheckSSLInfo(r
->ssl_info());
6559 EXPECT_EQ(0, d
.bytes_received());
6565 // This tests that a load of www.google.com with a certificate error sets
6566 // the |certificate_errors_are_fatal| flag correctly. This flag will cause
6567 // the interstitial to be fatal.
6568 TEST_F(HTTPSRequestTest
, HTTPSPreloadedHSTSTest
) {
6569 SpawnedTestServer::SSLOptions
ssl_options(
6570 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME
);
6571 SpawnedTestServer
test_server(
6572 SpawnedTestServer::TYPE_HTTPS
,
6574 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6575 ASSERT_TRUE(test_server
.Start());
6577 // We require that the URL be www.google.com in order to pick up the
6578 // preloaded HSTS entries in the TransportSecurityState. This means that we
6579 // have to use a MockHostResolver in order to direct www.google.com to the
6580 // testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
6582 MockHostResolver host_resolver
;
6583 TestNetworkDelegate network_delegate
; // Must outlive URLRequest.
6584 TestURLRequestContext
context(true);
6585 context
.set_network_delegate(&network_delegate
);
6586 context
.set_host_resolver(&host_resolver
);
6587 TransportSecurityState transport_security_state
;
6588 context
.set_transport_security_state(&transport_security_state
);
6592 scoped_ptr
<URLRequest
> r(context
.CreateRequest(
6593 GURL(base::StringPrintf("https://www.google.com:%d",
6594 test_server
.host_port_pair().port())),
6595 DEFAULT_PRIORITY
, &d
, NULL
));
6598 EXPECT_TRUE(r
->is_pending());
6600 base::RunLoop().Run();
6602 EXPECT_EQ(1, d
.response_started_count());
6603 EXPECT_FALSE(d
.received_data_before_response());
6604 EXPECT_TRUE(d
.have_certificate_errors());
6605 EXPECT_TRUE(d
.certificate_errors_are_fatal());
6608 // This tests that cached HTTPS page loads do not cause any updates to the
6609 // TransportSecurityState.
6610 TEST_F(HTTPSRequestTest
, HTTPSErrorsNoClobberTSSTest
) {
6611 // The actual problem -- CERT_MISMATCHED_NAME in this case -- doesn't
6612 // matter. It just has to be any error.
6613 SpawnedTestServer::SSLOptions
ssl_options(
6614 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME
);
6615 SpawnedTestServer
test_server(
6616 SpawnedTestServer::TYPE_HTTPS
,
6618 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6619 ASSERT_TRUE(test_server
.Start());
6621 // We require that the URL be www.google.com in order to pick up the static
6622 // and dynamic STS and PKP entries in the TransportSecurityState. This means
6623 // that we have to use a MockHostResolver in order to direct www.google.com to
6624 // the testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
6626 MockHostResolver host_resolver
;
6627 TestNetworkDelegate network_delegate
; // Must outlive URLRequest.
6628 TestURLRequestContext
context(true);
6629 context
.set_network_delegate(&network_delegate
);
6630 context
.set_host_resolver(&host_resolver
);
6631 TransportSecurityState transport_security_state
;
6633 TransportSecurityState::DomainState static_domain_state
;
6634 EXPECT_TRUE(transport_security_state
.GetStaticDomainState(
6635 "www.google.com", &static_domain_state
));
6636 context
.set_transport_security_state(&transport_security_state
);
6639 TransportSecurityState::DomainState dynamic_domain_state
;
6640 EXPECT_FALSE(transport_security_state
.GetDynamicDomainState(
6641 "www.google.com", &dynamic_domain_state
));
6644 scoped_ptr
<URLRequest
> r(context
.CreateRequest(
6645 GURL(base::StringPrintf("https://www.google.com:%d",
6646 test_server
.host_port_pair().port())),
6647 DEFAULT_PRIORITY
, &d
, NULL
));
6650 EXPECT_TRUE(r
->is_pending());
6652 base::RunLoop().Run();
6654 EXPECT_EQ(1, d
.response_started_count());
6655 EXPECT_FALSE(d
.received_data_before_response());
6656 EXPECT_TRUE(d
.have_certificate_errors());
6657 EXPECT_TRUE(d
.certificate_errors_are_fatal());
6659 // Get a fresh copy of the states, and check that they haven't changed.
6660 TransportSecurityState::DomainState new_static_domain_state
;
6661 EXPECT_TRUE(transport_security_state
.GetStaticDomainState(
6662 "www.google.com", &new_static_domain_state
));
6663 TransportSecurityState::DomainState new_dynamic_domain_state
;
6664 EXPECT_FALSE(transport_security_state
.GetDynamicDomainState(
6665 "www.google.com", &new_dynamic_domain_state
));
6667 EXPECT_EQ(new_static_domain_state
.sts
.upgrade_mode
,
6668 static_domain_state
.sts
.upgrade_mode
);
6669 EXPECT_EQ(new_static_domain_state
.sts
.include_subdomains
,
6670 static_domain_state
.sts
.include_subdomains
);
6671 EXPECT_EQ(new_static_domain_state
.pkp
.include_subdomains
,
6672 static_domain_state
.pkp
.include_subdomains
);
6673 EXPECT_TRUE(FingerprintsEqual(new_static_domain_state
.pkp
.spki_hashes
,
6674 static_domain_state
.pkp
.spki_hashes
));
6675 EXPECT_TRUE(FingerprintsEqual(new_static_domain_state
.pkp
.bad_spki_hashes
,
6676 static_domain_state
.pkp
.bad_spki_hashes
));
6679 // Make sure HSTS preserves a POST request's method and body.
6680 TEST_F(HTTPSRequestTest
, HSTSPreservesPosts
) {
6681 static const char kData
[] = "hello world";
6683 SpawnedTestServer::SSLOptions
ssl_options(
6684 SpawnedTestServer::SSLOptions::CERT_OK
);
6685 SpawnedTestServer
test_server(
6686 SpawnedTestServer::TYPE_HTTPS
,
6688 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6689 ASSERT_TRUE(test_server
.Start());
6692 // Per spec, TransportSecurityState expects a domain name, rather than an IP
6693 // address, so a MockHostResolver is needed to redirect www.somewhere.com to
6694 // the SpawnedTestServer. By default, MockHostResolver maps all hosts
6696 MockHostResolver host_resolver
;
6698 // Force https for www.somewhere.com.
6699 TransportSecurityState transport_security_state
;
6700 base::Time expiry
= base::Time::Now() + base::TimeDelta::FromDays(1000);
6701 bool include_subdomains
= false;
6702 transport_security_state
.AddHSTS("www.somewhere.com", expiry
,
6703 include_subdomains
);
6705 TestNetworkDelegate network_delegate
; // Must outlive URLRequest.
6707 TestURLRequestContext
context(true);
6708 context
.set_host_resolver(&host_resolver
);
6709 context
.set_transport_security_state(&transport_security_state
);
6710 context
.set_network_delegate(&network_delegate
);
6714 // Navigating to https://www.somewhere.com instead of https://127.0.0.1 will
6715 // cause a certificate error. Ignore the error.
6716 d
.set_allow_certificate_errors(true);
6718 scoped_ptr
<URLRequest
> req(context
.CreateRequest(
6719 GURL(base::StringPrintf("http://www.somewhere.com:%d/echo",
6720 test_server
.host_port_pair().port())),
6721 DEFAULT_PRIORITY
, &d
, NULL
));
6722 req
->set_method("POST");
6723 req
->set_upload(make_scoped_ptr(CreateSimpleUploadData(kData
)));
6726 base::RunLoop().Run();
6728 EXPECT_EQ("https", req
->url().scheme());
6729 EXPECT_EQ("POST", req
->method());
6730 EXPECT_EQ(kData
, d
.data_received());
6732 LoadTimingInfo load_timing_info
;
6733 network_delegate
.GetLoadTimingInfoBeforeRedirect(&load_timing_info
);
6734 // LoadTimingInfo of HSTS redirects is similar to that of network cache hits
6735 TestLoadTimingCacheHitNoNetwork(load_timing_info
);
6738 // Make sure that the CORS headers are added to cross-origin HSTS redirects.
6739 TEST_F(HTTPSRequestTest
, HSTSCrossOriginAddHeaders
) {
6740 static const char kOriginHeaderValue
[] = "http://www.example.com";
6742 SpawnedTestServer::SSLOptions
ssl_options(
6743 SpawnedTestServer::SSLOptions::CERT_OK
);
6744 SpawnedTestServer
test_server(
6745 SpawnedTestServer::TYPE_HTTPS
,
6747 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6748 ASSERT_TRUE(test_server
.Start());
6750 // Per spec, TransportSecurityState expects a domain name, rather than an IP
6751 // address, so a MockHostResolver is needed to redirect example.net to the
6752 // SpawnedTestServer. MockHostResolver maps all hosts to 127.0.0.1 by default.
6753 MockHostResolver host_resolver
;
6755 TransportSecurityState transport_security_state
;
6756 base::Time expiry
= base::Time::Now() + base::TimeDelta::FromDays(1);
6757 bool include_subdomains
= false;
6758 transport_security_state
.AddHSTS("example.net", expiry
, include_subdomains
);
6760 TestNetworkDelegate network_delegate
; // Must outlive URLRequest.
6762 MockCertVerifier cert_verifier
;
6763 cert_verifier
.set_default_result(OK
);
6765 TestURLRequestContext
context(true);
6766 context
.set_host_resolver(&host_resolver
);
6767 context
.set_transport_security_state(&transport_security_state
);
6768 context
.set_network_delegate(&network_delegate
);
6769 context
.set_cert_verifier(&cert_verifier
);
6772 GURL
hsts_http_url(base::StringPrintf("http://example.net:%d/somehstssite",
6773 test_server
.host_port_pair().port()));
6774 url::Replacements
<char> replacements
;
6775 const char kNewScheme
[] = "https";
6776 replacements
.SetScheme(kNewScheme
, url::Component(0, strlen(kNewScheme
)));
6777 GURL hsts_https_url
= hsts_http_url
.ReplaceComponents(replacements
);
6780 // Quit on redirect to allow response header inspection upon redirect.
6781 d
.set_quit_on_redirect(true);
6783 scoped_ptr
<URLRequest
> req(context
.CreateRequest(hsts_http_url
,
6784 DEFAULT_PRIORITY
, &d
, NULL
));
6785 // Set Origin header to simulate a cross-origin request.
6786 HttpRequestHeaders request_headers
;
6787 request_headers
.SetHeader("Origin", kOriginHeaderValue
);
6788 req
->SetExtraRequestHeaders(request_headers
);
6791 base::RunLoop().Run();
6793 EXPECT_EQ(1, d
.received_redirect_count());
6795 const HttpResponseHeaders
* headers
= req
->response_headers();
6796 std::string redirect_location
;
6797 EXPECT_TRUE(headers
->EnumerateHeader(NULL
, "Location", &redirect_location
));
6798 EXPECT_EQ(hsts_https_url
.spec(), redirect_location
);
6800 std::string received_cors_header
;
6801 EXPECT_TRUE(headers
->EnumerateHeader(NULL
, "Access-Control-Allow-Origin",
6802 &received_cors_header
));
6803 EXPECT_EQ(kOriginHeaderValue
, received_cors_header
);
6808 class SSLClientAuthTestDelegate
: public TestDelegate
{
6810 SSLClientAuthTestDelegate() : on_certificate_requested_count_(0) {
6812 virtual void OnCertificateRequested(
6813 URLRequest
* request
,
6814 SSLCertRequestInfo
* cert_request_info
) OVERRIDE
{
6815 on_certificate_requested_count_
++;
6816 base::MessageLoop::current()->Quit();
6818 int on_certificate_requested_count() {
6819 return on_certificate_requested_count_
;
6822 int on_certificate_requested_count_
;
6827 // TODO(davidben): Test the rest of the code. Specifically,
6828 // - Filtering which certificates to select.
6829 // - Sending a certificate back.
6830 // - Getting a certificate request in an SSL renegotiation sending the
6832 TEST_F(HTTPSRequestTest
, ClientAuthTest
) {
6833 SpawnedTestServer::SSLOptions ssl_options
;
6834 ssl_options
.request_client_certificate
= true;
6835 SpawnedTestServer
test_server(
6836 SpawnedTestServer::TYPE_HTTPS
,
6838 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6839 ASSERT_TRUE(test_server
.Start());
6841 SSLClientAuthTestDelegate d
;
6843 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
6844 test_server
.GetURL(std::string()), DEFAULT_PRIORITY
, &d
, NULL
));
6847 EXPECT_TRUE(r
->is_pending());
6849 base::RunLoop().Run();
6851 EXPECT_EQ(1, d
.on_certificate_requested_count());
6852 EXPECT_FALSE(d
.received_data_before_response());
6853 EXPECT_EQ(0, d
.bytes_received());
6855 // Send no certificate.
6856 // TODO(davidben): Get temporary client cert import (with keys) working on
6857 // all platforms so we can test sending a cert as well.
6858 r
->ContinueWithCertificate(NULL
);
6860 base::RunLoop().Run();
6862 EXPECT_EQ(1, d
.response_started_count());
6863 EXPECT_FALSE(d
.received_data_before_response());
6864 EXPECT_NE(0, d
.bytes_received());
6868 TEST_F(HTTPSRequestTest
, ResumeTest
) {
6869 // Test that we attempt a session resume when making two connections to the
6871 SpawnedTestServer::SSLOptions ssl_options
;
6872 ssl_options
.record_resume
= true;
6873 SpawnedTestServer
test_server(
6874 SpawnedTestServer::TYPE_HTTPS
,
6876 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6877 ASSERT_TRUE(test_server
.Start());
6879 SSLClientSocket::ClearSessionCache();
6883 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
6884 test_server
.GetURL("ssl-session-cache"), DEFAULT_PRIORITY
, &d
, NULL
));
6887 EXPECT_TRUE(r
->is_pending());
6889 base::RunLoop().Run();
6891 EXPECT_EQ(1, d
.response_started_count());
6894 reinterpret_cast<HttpCache
*>(default_context_
.http_transaction_factory())->
6895 CloseAllConnections();
6899 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
6900 test_server
.GetURL("ssl-session-cache"), DEFAULT_PRIORITY
, &d
, NULL
));
6903 EXPECT_TRUE(r
->is_pending());
6905 base::RunLoop().Run();
6907 // The response will look like;
6912 // With a newline at the end which makes the split think that there are
6915 EXPECT_EQ(1, d
.response_started_count());
6916 std::vector
<std::string
> lines
;
6917 base::SplitString(d
.data_received(), '\n', &lines
);
6918 ASSERT_EQ(4u, lines
.size()) << d
.data_received();
6920 std::string session_id
;
6922 for (size_t i
= 0; i
< 2; i
++) {
6923 std::vector
<std::string
> parts
;
6924 base::SplitString(lines
[i
], '\t', &parts
);
6925 ASSERT_EQ(2u, parts
.size());
6927 EXPECT_EQ("insert", parts
[0]);
6928 session_id
= parts
[1];
6930 EXPECT_EQ("lookup", parts
[0]);
6931 EXPECT_EQ(session_id
, parts
[1]);
6937 TEST_F(HTTPSRequestTest
, SSLSessionCacheShardTest
) {
6938 // Test that sessions aren't resumed when the value of ssl_session_cache_shard
6940 SpawnedTestServer::SSLOptions ssl_options
;
6941 ssl_options
.record_resume
= true;
6942 SpawnedTestServer
test_server(
6943 SpawnedTestServer::TYPE_HTTPS
,
6945 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6946 ASSERT_TRUE(test_server
.Start());
6948 SSLClientSocket::ClearSessionCache();
6952 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
6953 test_server
.GetURL("ssl-session-cache"), DEFAULT_PRIORITY
, &d
, NULL
));
6956 EXPECT_TRUE(r
->is_pending());
6958 base::RunLoop().Run();
6960 EXPECT_EQ(1, d
.response_started_count());
6963 // Now create a new HttpCache with a different ssl_session_cache_shard value.
6964 HttpNetworkSession::Params params
;
6965 params
.host_resolver
= default_context_
.host_resolver();
6966 params
.cert_verifier
= default_context_
.cert_verifier();
6967 params
.transport_security_state
= default_context_
.transport_security_state();
6968 params
.proxy_service
= default_context_
.proxy_service();
6969 params
.ssl_config_service
= default_context_
.ssl_config_service();
6970 params
.http_auth_handler_factory
=
6971 default_context_
.http_auth_handler_factory();
6972 params
.network_delegate
= &default_network_delegate_
;
6973 params
.http_server_properties
= default_context_
.http_server_properties();
6974 params
.ssl_session_cache_shard
= "alternate";
6976 scoped_ptr
<HttpCache
> cache(new HttpCache(
6977 new HttpNetworkSession(params
),
6978 HttpCache::DefaultBackend::InMemory(0)));
6980 default_context_
.set_http_transaction_factory(cache
.get());
6984 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
6985 test_server
.GetURL("ssl-session-cache"), DEFAULT_PRIORITY
, &d
, NULL
));
6988 EXPECT_TRUE(r
->is_pending());
6990 base::RunLoop().Run();
6992 // The response will look like;
6996 // With a newline at the end which makes the split think that there are
6999 EXPECT_EQ(1, d
.response_started_count());
7000 std::vector
<std::string
> lines
;
7001 base::SplitString(d
.data_received(), '\n', &lines
);
7002 ASSERT_EQ(3u, lines
.size());
7004 std::string session_id
;
7005 for (size_t i
= 0; i
< 2; i
++) {
7006 std::vector
<std::string
> parts
;
7007 base::SplitString(lines
[i
], '\t', &parts
);
7008 ASSERT_EQ(2u, parts
.size());
7009 EXPECT_EQ("insert", parts
[0]);
7011 session_id
= parts
[1];
7013 EXPECT_NE(session_id
, parts
[1]);
7023 bool IsECDSACipherSuite(uint16_t cipher_suite
) {
7024 const char* key_exchange
;
7028 SSLCipherSuiteToStrings(&key_exchange
, &cipher
, &mac
, &is_aead
, cipher_suite
);
7029 return std::string(key_exchange
).find("ECDSA") != std::string::npos
;
7034 // Test that ECDSA is disabled on Windows XP, where ECDSA certificates cannot be
7036 // Test seems flaky, see http://crbug.com/411827.
7037 TEST_F(HTTPSRequestTest
, DISABLED_DisableECDSAOnXP
) {
7038 if (base::win::GetVersion() >= base::win::VERSION_VISTA
) {
7039 LOG(INFO
) << "Skipping test on this version.";
7043 SpawnedTestServer
test_server(
7044 SpawnedTestServer::TYPE_HTTPS
,
7045 SpawnedTestServer::kLocalhost
,
7046 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7047 ASSERT_TRUE(test_server
.Start());
7050 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
7051 test_server
.GetURL("client-cipher-list"), DEFAULT_PRIORITY
, &d
, NULL
));
7053 EXPECT_TRUE(r
->is_pending());
7055 base::RunLoop().Run();
7057 EXPECT_EQ(1, d
.response_started_count());
7058 std::vector
<std::string
> lines
;
7059 base::SplitString(d
.data_received(), '\n', &lines
);
7061 for (size_t i
= 0; i
< lines
.size(); i
++) {
7063 ASSERT_TRUE(base::StringToInt(lines
[i
], &cipher_suite
));
7064 EXPECT_FALSE(IsECDSACipherSuite(cipher_suite
))
7065 << "ClientHello advertised " << cipher_suite
;
7071 class HTTPSFallbackTest
: public testing::Test
{
7073 HTTPSFallbackTest() : context_(true) {
7075 delegate_
.set_allow_certificate_errors(true);
7077 virtual ~HTTPSFallbackTest() {}
7080 void DoFallbackTest(const SpawnedTestServer::SSLOptions
& ssl_options
) {
7082 SpawnedTestServer
test_server(
7083 SpawnedTestServer::TYPE_HTTPS
,
7085 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7086 ASSERT_TRUE(test_server
.Start());
7088 request_
= context_
.CreateRequest(
7089 test_server
.GetURL(std::string()), DEFAULT_PRIORITY
, &delegate_
, NULL
);
7092 base::RunLoop().Run();
7095 void ExpectConnection(int version
) {
7096 EXPECT_EQ(1, delegate_
.response_started_count());
7097 EXPECT_NE(0, delegate_
.bytes_received());
7098 EXPECT_EQ(version
, SSLConnectionStatusToVersion(
7099 request_
->ssl_info().connection_status
));
7100 EXPECT_TRUE(request_
->ssl_info().connection_status
&
7101 SSL_CONNECTION_VERSION_FALLBACK
);
7104 void ExpectFailure(int error
) {
7105 EXPECT_EQ(1, delegate_
.response_started_count());
7106 EXPECT_FALSE(request_
->status().is_success());
7107 EXPECT_EQ(URLRequestStatus::FAILED
, request_
->status().status());
7108 EXPECT_EQ(error
, request_
->status().error());
7112 TestDelegate delegate_
;
7113 TestURLRequestContext context_
;
7114 scoped_ptr
<URLRequest
> request_
;
7117 // Tests TLSv1.1 -> TLSv1 fallback. Verifies that we don't fall back more
7119 TEST_F(HTTPSFallbackTest
, TLSv1Fallback
) {
7120 SpawnedTestServer::SSLOptions
ssl_options(
7121 SpawnedTestServer::SSLOptions::CERT_OK
);
7122 ssl_options
.tls_intolerant
=
7123 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1
;
7125 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options
));
7126 ExpectConnection(SSL_CONNECTION_VERSION_TLS1
);
7129 // This test is disabled on Android because the remote test server doesn't cause
7131 #if !defined(OS_ANDROID)
7132 // Tests fallback to TLS 1.0 on connection reset.
7133 TEST_F(HTTPSFallbackTest
, TLSv1FallbackReset
) {
7134 SpawnedTestServer::SSLOptions
ssl_options(
7135 SpawnedTestServer::SSLOptions::CERT_OK
);
7136 ssl_options
.tls_intolerant
=
7137 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1
;
7138 ssl_options
.tls_intolerance_type
=
7139 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_RESET
;
7141 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options
));
7142 ExpectConnection(SSL_CONNECTION_VERSION_TLS1
);
7144 #endif // !OS_ANDROID
7146 // Tests that we don't fallback on handshake failure with servers that implement
7147 // TLS_FALLBACK_SCSV. Also ensure that the original error code is reported.
7148 TEST_F(HTTPSFallbackTest
, FallbackSCSV
) {
7149 SpawnedTestServer::SSLOptions
ssl_options(
7150 SpawnedTestServer::SSLOptions::CERT_OK
);
7151 // Configure HTTPS server to be intolerant of TLS >= 1.0 in order to trigger
7152 // a version fallback.
7153 ssl_options
.tls_intolerant
=
7154 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL
;
7155 // Have the server process TLS_FALLBACK_SCSV so that version fallback
7156 // connections are rejected.
7157 ssl_options
.fallback_scsv_enabled
= true;
7159 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options
));
7161 // ERR_SSL_VERSION_OR_CIPHER_MISMATCH is how the server simulates version
7162 // intolerance. If the fallback SCSV is processed when the original error
7163 // that caused the fallback should be returned, which should be
7164 // ERR_SSL_VERSION_OR_CIPHER_MISMATCH.
7165 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH
);
7168 // Tests that we don't fallback on connection closed with servers that implement
7169 // TLS_FALLBACK_SCSV. Also ensure that the original error code is reported.
7170 TEST_F(HTTPSFallbackTest
, FallbackSCSVClosed
) {
7171 SpawnedTestServer::SSLOptions
ssl_options(
7172 SpawnedTestServer::SSLOptions::CERT_OK
);
7173 // Configure HTTPS server to be intolerant of TLS >= 1.0 in order to trigger
7174 // a version fallback.
7175 ssl_options
.tls_intolerant
=
7176 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL
;
7177 ssl_options
.tls_intolerance_type
=
7178 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_CLOSE
;
7179 // Have the server process TLS_FALLBACK_SCSV so that version fallback
7180 // connections are rejected.
7181 ssl_options
.fallback_scsv_enabled
= true;
7183 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options
));
7185 // The original error should be replayed on rejected fallback.
7186 ExpectFailure(ERR_CONNECTION_CLOSED
);
7189 // Tests that the SSLv3 fallback triggers on alert.
7190 TEST_F(HTTPSFallbackTest
, SSLv3Fallback
) {
7191 SpawnedTestServer::SSLOptions
ssl_options(
7192 SpawnedTestServer::SSLOptions::CERT_OK
);
7193 ssl_options
.tls_intolerant
=
7194 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL
;
7196 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options
));
7197 ExpectConnection(SSL_CONNECTION_VERSION_SSL3
);
7200 // Tests that the SSLv3 fallback triggers on closed connections.
7201 TEST_F(HTTPSFallbackTest
, SSLv3FallbackClosed
) {
7202 SpawnedTestServer::SSLOptions
ssl_options(
7203 SpawnedTestServer::SSLOptions::CERT_OK
);
7204 ssl_options
.tls_intolerant
=
7205 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL
;
7206 ssl_options
.tls_intolerance_type
=
7207 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_CLOSE
;
7209 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options
));
7210 ExpectConnection(SSL_CONNECTION_VERSION_SSL3
);
7213 // This test is disabled on Android because the remote test server doesn't cause
7215 #if !defined(OS_ANDROID)
7216 // Tests that a reset connection does not fallback down to SSL3.
7217 TEST_F(HTTPSFallbackTest
, SSLv3NoFallbackReset
) {
7218 SpawnedTestServer::SSLOptions
ssl_options(
7219 SpawnedTestServer::SSLOptions::CERT_OK
);
7220 ssl_options
.tls_intolerant
=
7221 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL
;
7222 ssl_options
.tls_intolerance_type
=
7223 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_RESET
;
7225 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options
));
7226 ExpectFailure(ERR_CONNECTION_RESET
);
7228 #endif // !OS_ANDROID
7230 class HTTPSSessionTest
: public testing::Test
{
7232 HTTPSSessionTest() : default_context_(true) {
7233 cert_verifier_
.set_default_result(OK
);
7235 default_context_
.set_network_delegate(&default_network_delegate_
);
7236 default_context_
.set_cert_verifier(&cert_verifier_
);
7237 default_context_
.Init();
7239 virtual ~HTTPSSessionTest() {}
7242 MockCertVerifier cert_verifier_
;
7243 TestNetworkDelegate default_network_delegate_
; // Must outlive URLRequest.
7244 TestURLRequestContext default_context_
;
7247 // Tests that session resumption is not attempted if an invalid certificate
7249 TEST_F(HTTPSSessionTest
, DontResumeSessionsForInvalidCertificates
) {
7250 SpawnedTestServer::SSLOptions ssl_options
;
7251 ssl_options
.record_resume
= true;
7252 SpawnedTestServer
test_server(
7253 SpawnedTestServer::TYPE_HTTPS
,
7255 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7256 ASSERT_TRUE(test_server
.Start());
7258 SSLClientSocket::ClearSessionCache();
7260 // Simulate the certificate being expired and attempt a connection.
7261 cert_verifier_
.set_default_result(ERR_CERT_DATE_INVALID
);
7264 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
7265 test_server
.GetURL("ssl-session-cache"), DEFAULT_PRIORITY
, &d
, NULL
));
7268 EXPECT_TRUE(r
->is_pending());
7270 base::RunLoop().Run();
7272 EXPECT_EQ(1, d
.response_started_count());
7275 reinterpret_cast<HttpCache
*>(default_context_
.http_transaction_factory())->
7276 CloseAllConnections();
7278 // Now change the certificate to be acceptable (so that the response is
7279 // loaded), and ensure that no session id is presented to the peer.
7280 cert_verifier_
.set_default_result(OK
);
7283 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
7284 test_server
.GetURL("ssl-session-cache"), DEFAULT_PRIORITY
, &d
, NULL
));
7287 EXPECT_TRUE(r
->is_pending());
7289 base::RunLoop().Run();
7291 // The response will look like;
7295 // With a newline at the end which makes the split think that there are
7298 // If a session was presented (eg: a bug), then the response would look
7304 EXPECT_EQ(1, d
.response_started_count());
7305 std::vector
<std::string
> lines
;
7306 base::SplitString(d
.data_received(), '\n', &lines
);
7307 ASSERT_EQ(3u, lines
.size()) << d
.data_received();
7309 std::string session_id
;
7310 for (size_t i
= 0; i
< 2; i
++) {
7311 std::vector
<std::string
> parts
;
7312 base::SplitString(lines
[i
], '\t', &parts
);
7313 ASSERT_EQ(2u, parts
.size());
7314 EXPECT_EQ("insert", parts
[0]);
7316 session_id
= parts
[1];
7318 EXPECT_NE(session_id
, parts
[1]);
7324 class TestSSLConfigService
: public SSLConfigService
{
7326 TestSSLConfigService(bool ev_enabled
,
7327 bool online_rev_checking
,
7328 bool rev_checking_required_local_anchors
)
7329 : ev_enabled_(ev_enabled
),
7330 online_rev_checking_(online_rev_checking
),
7331 rev_checking_required_local_anchors_(
7332 rev_checking_required_local_anchors
) {}
7334 // SSLConfigService:
7335 virtual void GetSSLConfig(SSLConfig
* config
) OVERRIDE
{
7336 *config
= SSLConfig();
7337 config
->rev_checking_enabled
= online_rev_checking_
;
7338 config
->verify_ev_cert
= ev_enabled_
;
7339 config
->rev_checking_required_local_anchors
=
7340 rev_checking_required_local_anchors_
;
7344 virtual ~TestSSLConfigService() {}
7347 const bool ev_enabled_
;
7348 const bool online_rev_checking_
;
7349 const bool rev_checking_required_local_anchors_
;
7352 // This the fingerprint of the "Testing CA" certificate used by the testserver.
7353 // See net/data/ssl/certificates/ocsp-test-root.pem.
7354 static const SHA1HashValue kOCSPTestCertFingerprint
=
7355 { { 0xf1, 0xad, 0xf6, 0xce, 0x42, 0xac, 0xe7, 0xb4, 0xf4, 0x24,
7356 0xdb, 0x1a, 0xf7, 0xa0, 0x9f, 0x09, 0xa1, 0xea, 0xf1, 0x5c } };
7358 // This is the SHA256, SPKI hash of the "Testing CA" certificate used by the
7360 static const SHA256HashValue kOCSPTestCertSPKI
= { {
7361 0xee, 0xe6, 0x51, 0x2d, 0x4c, 0xfa, 0xf7, 0x3e,
7362 0x6c, 0xd8, 0xca, 0x67, 0xed, 0xb5, 0x5d, 0x49,
7363 0x76, 0xe1, 0x52, 0xa7, 0x6e, 0x0e, 0xa0, 0x74,
7364 0x09, 0x75, 0xe6, 0x23, 0x24, 0xbd, 0x1b, 0x28,
7367 // This is the policy OID contained in the certificates that testserver
7369 static const char kOCSPTestCertPolicy
[] = "1.3.6.1.4.1.11129.2.4.1";
7371 class HTTPSOCSPTest
: public HTTPSRequestTest
{
7376 new ScopedTestEVPolicy(EVRootCAMetadata::GetInstance(),
7377 kOCSPTestCertFingerprint
,
7378 kOCSPTestCertPolicy
)) {
7381 virtual void SetUp() OVERRIDE
{
7382 SetupContext(&context_
);
7385 scoped_refptr
<X509Certificate
> root_cert
=
7386 ImportCertFromFile(GetTestCertsDirectory(), "ocsp-test-root.pem");
7387 CHECK_NE(static_cast<X509Certificate
*>(NULL
), root_cert
.get());
7388 test_root_
.reset(new ScopedTestRoot(root_cert
.get()));
7390 #if defined(USE_NSS) || defined(OS_IOS)
7391 SetURLRequestContextForNSSHttpIO(&context_
);
7392 EnsureNSSHttpIOInit();
7396 void DoConnection(const SpawnedTestServer::SSLOptions
& ssl_options
,
7397 CertStatus
* out_cert_status
) {
7398 // We always overwrite out_cert_status.
7399 *out_cert_status
= 0;
7400 SpawnedTestServer
test_server(
7401 SpawnedTestServer::TYPE_HTTPS
,
7403 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7404 ASSERT_TRUE(test_server
.Start());
7407 d
.set_allow_certificate_errors(true);
7408 scoped_ptr
<URLRequest
> r(context_
.CreateRequest(
7409 test_server
.GetURL(std::string()), DEFAULT_PRIORITY
, &d
, NULL
));
7412 base::RunLoop().Run();
7414 EXPECT_EQ(1, d
.response_started_count());
7415 *out_cert_status
= r
->ssl_info().cert_status
;
7418 virtual ~HTTPSOCSPTest() {
7419 #if defined(USE_NSS) || defined(OS_IOS)
7420 ShutdownNSSHttpIO();
7425 // SetupContext configures the URLRequestContext that will be used for making
7426 // connetions to testserver. This can be overridden in test subclasses for
7427 // different behaviour.
7428 virtual void SetupContext(URLRequestContext
* context
) {
7429 context
->set_ssl_config_service(
7430 new TestSSLConfigService(true /* check for EV */,
7431 true /* online revocation checking */,
7432 false /* require rev. checking for local
7436 scoped_ptr
<ScopedTestRoot
> test_root_
;
7437 TestURLRequestContext context_
;
7438 scoped_ptr
<ScopedTestEVPolicy
> ev_test_policy_
;
7441 static CertStatus
ExpectedCertStatusForFailedOnlineRevocationCheck() {
7443 // Windows can return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION but we don't
7444 // have that ability on other platforms.
7445 return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION
;
7451 // SystemSupportsHardFailRevocationChecking returns true iff the current
7452 // operating system supports revocation checking and can distinguish between
7453 // situations where a given certificate lacks any revocation information (eg:
7454 // no CRLDistributionPoints and no OCSP Responder AuthorityInfoAccess) and when
7455 // revocation information cannot be obtained (eg: the CRL was unreachable).
7456 // If it does not, then tests which rely on 'hard fail' behaviour should be
7458 static bool SystemSupportsHardFailRevocationChecking() {
7459 #if defined(OS_WIN) || defined(USE_NSS) || defined(OS_IOS)
7466 // SystemUsesChromiumEVMetadata returns true iff the current operating system
7467 // uses Chromium's EV metadata (i.e. EVRootCAMetadata). If it does not, then
7468 // several tests are effected because our testing EV certificate won't be
7469 // recognised as EV.
7470 static bool SystemUsesChromiumEVMetadata() {
7471 #if defined(USE_OPENSSL_CERTS) && !defined(OS_ANDROID)
7472 // http://crbug.com/117478 - OpenSSL does not support EV validation.
7474 #elif (defined(OS_MACOSX) && !defined(OS_IOS)) || defined(OS_ANDROID)
7475 // On OS X and Android, we use the system to tell us whether a certificate is
7476 // EV or not and the system won't recognise our testing root.
7483 static bool SystemSupportsOCSP() {
7484 #if defined(USE_OPENSSL)
7485 // http://crbug.com/117478 - OpenSSL does not support OCSP.
7487 #elif defined(OS_WIN)
7488 return base::win::GetVersion() >= base::win::VERSION_VISTA
;
7489 #elif defined(OS_ANDROID)
7490 // TODO(jnd): http://crbug.com/117478 - EV verification is not yet supported.
7497 TEST_F(HTTPSOCSPTest
, Valid
) {
7498 if (!SystemSupportsOCSP()) {
7499 LOG(WARNING
) << "Skipping test because system doesn't support OCSP";
7503 SpawnedTestServer::SSLOptions
ssl_options(
7504 SpawnedTestServer::SSLOptions::CERT_AUTO
);
7505 ssl_options
.ocsp_status
= SpawnedTestServer::SSLOptions::OCSP_OK
;
7507 CertStatus cert_status
;
7508 DoConnection(ssl_options
, &cert_status
);
7510 EXPECT_EQ(0u, cert_status
& CERT_STATUS_ALL_ERRORS
);
7512 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
7513 static_cast<bool>(cert_status
& CERT_STATUS_IS_EV
));
7515 EXPECT_TRUE(cert_status
& CERT_STATUS_REV_CHECKING_ENABLED
);
7518 TEST_F(HTTPSOCSPTest
, Revoked
) {
7519 if (!SystemSupportsOCSP()) {
7520 LOG(WARNING
) << "Skipping test because system doesn't support OCSP";
7524 SpawnedTestServer::SSLOptions
ssl_options(
7525 SpawnedTestServer::SSLOptions::CERT_AUTO
);
7526 ssl_options
.ocsp_status
= SpawnedTestServer::SSLOptions::OCSP_REVOKED
;
7528 CertStatus cert_status
;
7529 DoConnection(ssl_options
, &cert_status
);
7531 #if !(defined(OS_MACOSX) && !defined(OS_IOS))
7532 // Doesn't pass on OS X yet for reasons that need to be investigated.
7533 EXPECT_EQ(CERT_STATUS_REVOKED
, cert_status
& CERT_STATUS_ALL_ERRORS
);
7535 EXPECT_FALSE(cert_status
& CERT_STATUS_IS_EV
);
7536 EXPECT_TRUE(cert_status
& CERT_STATUS_REV_CHECKING_ENABLED
);
7539 TEST_F(HTTPSOCSPTest
, Invalid
) {
7540 if (!SystemSupportsOCSP()) {
7541 LOG(WARNING
) << "Skipping test because system doesn't support OCSP";
7545 SpawnedTestServer::SSLOptions
ssl_options(
7546 SpawnedTestServer::SSLOptions::CERT_AUTO
);
7547 ssl_options
.ocsp_status
= SpawnedTestServer::SSLOptions::OCSP_INVALID
;
7549 CertStatus cert_status
;
7550 DoConnection(ssl_options
, &cert_status
);
7552 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
7553 cert_status
& CERT_STATUS_ALL_ERRORS
);
7555 // Without a positive OCSP response, we shouldn't show the EV status.
7556 EXPECT_FALSE(cert_status
& CERT_STATUS_IS_EV
);
7557 EXPECT_TRUE(cert_status
& CERT_STATUS_REV_CHECKING_ENABLED
);
7560 class HTTPSHardFailTest
: public HTTPSOCSPTest
{
7562 virtual void SetupContext(URLRequestContext
* context
) OVERRIDE
{
7563 context
->set_ssl_config_service(
7564 new TestSSLConfigService(false /* check for EV */,
7565 false /* online revocation checking */,
7566 true /* require rev. checking for local
7572 TEST_F(HTTPSHardFailTest
, FailsOnOCSPInvalid
) {
7573 if (!SystemSupportsOCSP()) {
7574 LOG(WARNING
) << "Skipping test because system doesn't support OCSP";
7578 if (!SystemSupportsHardFailRevocationChecking()) {
7579 LOG(WARNING
) << "Skipping test because system doesn't support hard fail "
7580 << "revocation checking";
7584 SpawnedTestServer::SSLOptions
ssl_options(
7585 SpawnedTestServer::SSLOptions::CERT_AUTO
);
7586 ssl_options
.ocsp_status
= SpawnedTestServer::SSLOptions::OCSP_INVALID
;
7588 CertStatus cert_status
;
7589 DoConnection(ssl_options
, &cert_status
);
7591 EXPECT_EQ(CERT_STATUS_REVOKED
,
7592 cert_status
& CERT_STATUS_REVOKED
);
7594 // Without a positive OCSP response, we shouldn't show the EV status.
7595 EXPECT_TRUE(cert_status
& CERT_STATUS_REV_CHECKING_ENABLED
);
7598 class HTTPSEVCRLSetTest
: public HTTPSOCSPTest
{
7600 virtual void SetupContext(URLRequestContext
* context
) OVERRIDE
{
7601 context
->set_ssl_config_service(
7602 new TestSSLConfigService(true /* check for EV */,
7603 false /* online revocation checking */,
7604 false /* require rev. checking for local
7609 TEST_F(HTTPSEVCRLSetTest
, MissingCRLSetAndInvalidOCSP
) {
7610 if (!SystemSupportsOCSP()) {
7611 LOG(WARNING
) << "Skipping test because system doesn't support OCSP";
7615 SpawnedTestServer::SSLOptions
ssl_options(
7616 SpawnedTestServer::SSLOptions::CERT_AUTO
);
7617 ssl_options
.ocsp_status
= SpawnedTestServer::SSLOptions::OCSP_INVALID
;
7618 SSLConfigService::SetCRLSet(scoped_refptr
<CRLSet
>());
7620 CertStatus cert_status
;
7621 DoConnection(ssl_options
, &cert_status
);
7623 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
7624 cert_status
& CERT_STATUS_ALL_ERRORS
);
7626 EXPECT_FALSE(cert_status
& CERT_STATUS_IS_EV
);
7627 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
7628 static_cast<bool>(cert_status
& CERT_STATUS_REV_CHECKING_ENABLED
));
7631 TEST_F(HTTPSEVCRLSetTest
, MissingCRLSetAndRevokedOCSP
) {
7632 if (!SystemSupportsOCSP()) {
7633 LOG(WARNING
) << "Skipping test because system doesn't support OCSP";
7637 SpawnedTestServer::SSLOptions
ssl_options(
7638 SpawnedTestServer::SSLOptions::CERT_AUTO
);
7639 ssl_options
.ocsp_status
= SpawnedTestServer::SSLOptions::OCSP_REVOKED
;
7640 SSLConfigService::SetCRLSet(scoped_refptr
<CRLSet
>());
7642 CertStatus cert_status
;
7643 DoConnection(ssl_options
, &cert_status
);
7645 // Currently only works for Windows. When using NSS or OS X, it's not
7646 // possible to determine whether the check failed because of actual
7647 // revocation or because there was an OCSP failure.
7649 EXPECT_EQ(CERT_STATUS_REVOKED
, cert_status
& CERT_STATUS_ALL_ERRORS
);
7651 EXPECT_EQ(0u, cert_status
& CERT_STATUS_ALL_ERRORS
);
7654 EXPECT_FALSE(cert_status
& CERT_STATUS_IS_EV
);
7655 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
7656 static_cast<bool>(cert_status
& CERT_STATUS_REV_CHECKING_ENABLED
));
7659 TEST_F(HTTPSEVCRLSetTest
, MissingCRLSetAndGoodOCSP
) {
7660 if (!SystemSupportsOCSP()) {
7661 LOG(WARNING
) << "Skipping test because system doesn't support OCSP";
7665 SpawnedTestServer::SSLOptions
ssl_options(
7666 SpawnedTestServer::SSLOptions::CERT_AUTO
);
7667 ssl_options
.ocsp_status
= SpawnedTestServer::SSLOptions::OCSP_OK
;
7668 SSLConfigService::SetCRLSet(scoped_refptr
<CRLSet
>());
7670 CertStatus cert_status
;
7671 DoConnection(ssl_options
, &cert_status
);
7673 EXPECT_EQ(0u, cert_status
& CERT_STATUS_ALL_ERRORS
);
7675 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
7676 static_cast<bool>(cert_status
& CERT_STATUS_IS_EV
));
7677 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
7678 static_cast<bool>(cert_status
& CERT_STATUS_REV_CHECKING_ENABLED
));
7681 TEST_F(HTTPSEVCRLSetTest
, ExpiredCRLSet
) {
7682 if (!SystemSupportsOCSP()) {
7683 LOG(WARNING
) << "Skipping test because system doesn't support OCSP";
7687 SpawnedTestServer::SSLOptions
ssl_options(
7688 SpawnedTestServer::SSLOptions::CERT_AUTO
);
7689 ssl_options
.ocsp_status
= SpawnedTestServer::SSLOptions::OCSP_INVALID
;
7690 SSLConfigService::SetCRLSet(
7691 scoped_refptr
<CRLSet
>(CRLSet::ExpiredCRLSetForTesting()));
7693 CertStatus cert_status
;
7694 DoConnection(ssl_options
, &cert_status
);
7696 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
7697 cert_status
& CERT_STATUS_ALL_ERRORS
);
7699 EXPECT_FALSE(cert_status
& CERT_STATUS_IS_EV
);
7700 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
7701 static_cast<bool>(cert_status
& CERT_STATUS_REV_CHECKING_ENABLED
));
7704 TEST_F(HTTPSEVCRLSetTest
, FreshCRLSetCovered
) {
7705 if (!SystemSupportsOCSP()) {
7706 LOG(WARNING
) << "Skipping test because system doesn't support OCSP";
7710 SpawnedTestServer::SSLOptions
ssl_options(
7711 SpawnedTestServer::SSLOptions::CERT_AUTO
);
7712 ssl_options
.ocsp_status
= SpawnedTestServer::SSLOptions::OCSP_INVALID
;
7713 SSLConfigService::SetCRLSet(
7714 scoped_refptr
<CRLSet
>(CRLSet::ForTesting(
7715 false, &kOCSPTestCertSPKI
, "")));
7717 CertStatus cert_status
;
7718 DoConnection(ssl_options
, &cert_status
);
7720 // With a fresh CRLSet that covers the issuing certificate, we shouldn't do a
7721 // revocation check for EV.
7722 EXPECT_EQ(0u, cert_status
& CERT_STATUS_ALL_ERRORS
);
7723 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
7724 static_cast<bool>(cert_status
& CERT_STATUS_IS_EV
));
7726 static_cast<bool>(cert_status
& CERT_STATUS_REV_CHECKING_ENABLED
));
7729 TEST_F(HTTPSEVCRLSetTest
, FreshCRLSetNotCovered
) {
7730 if (!SystemSupportsOCSP()) {
7731 LOG(WARNING
) << "Skipping test because system doesn't support OCSP";
7735 SpawnedTestServer::SSLOptions
ssl_options(
7736 SpawnedTestServer::SSLOptions::CERT_AUTO
);
7737 ssl_options
.ocsp_status
= SpawnedTestServer::SSLOptions::OCSP_INVALID
;
7738 SSLConfigService::SetCRLSet(
7739 scoped_refptr
<CRLSet
>(CRLSet::EmptyCRLSetForTesting()));
7741 CertStatus cert_status
= 0;
7742 DoConnection(ssl_options
, &cert_status
);
7744 // Even with a fresh CRLSet, we should still do online revocation checks when
7745 // the certificate chain isn't covered by the CRLSet, which it isn't in this
7747 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
7748 cert_status
& CERT_STATUS_ALL_ERRORS
);
7750 EXPECT_FALSE(cert_status
& CERT_STATUS_IS_EV
);
7751 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
7752 static_cast<bool>(cert_status
& CERT_STATUS_REV_CHECKING_ENABLED
));
7755 TEST_F(HTTPSEVCRLSetTest
, ExpiredCRLSetAndRevokedNonEVCert
) {
7756 // Test that when EV verification is requested, but online revocation
7757 // checking is disabled, and the leaf certificate is not in fact EV, that
7758 // no revocation checking actually happens.
7759 if (!SystemSupportsOCSP()) {
7760 LOG(WARNING
) << "Skipping test because system doesn't support OCSP";
7764 // Unmark the certificate's OID as EV, which should disable revocation
7765 // checking (as per the user preference)
7766 ev_test_policy_
.reset();
7768 SpawnedTestServer::SSLOptions
ssl_options(
7769 SpawnedTestServer::SSLOptions::CERT_AUTO
);
7770 ssl_options
.ocsp_status
= SpawnedTestServer::SSLOptions::OCSP_REVOKED
;
7771 SSLConfigService::SetCRLSet(
7772 scoped_refptr
<CRLSet
>(CRLSet::ExpiredCRLSetForTesting()));
7774 CertStatus cert_status
;
7775 DoConnection(ssl_options
, &cert_status
);
7777 EXPECT_EQ(0u, cert_status
& CERT_STATUS_ALL_ERRORS
);
7779 EXPECT_FALSE(cert_status
& CERT_STATUS_IS_EV
);
7780 EXPECT_FALSE(cert_status
& CERT_STATUS_REV_CHECKING_ENABLED
);
7783 class HTTPSCRLSetTest
: public HTTPSOCSPTest
{
7785 virtual void SetupContext(URLRequestContext
* context
) OVERRIDE
{
7786 context
->set_ssl_config_service(
7787 new TestSSLConfigService(false /* check for EV */,
7788 false /* online revocation checking */,
7789 false /* require rev. checking for local
7794 TEST_F(HTTPSCRLSetTest
, ExpiredCRLSet
) {
7795 SpawnedTestServer::SSLOptions
ssl_options(
7796 SpawnedTestServer::SSLOptions::CERT_AUTO
);
7797 ssl_options
.ocsp_status
= SpawnedTestServer::SSLOptions::OCSP_INVALID
;
7798 SSLConfigService::SetCRLSet(
7799 scoped_refptr
<CRLSet
>(CRLSet::ExpiredCRLSetForTesting()));
7801 CertStatus cert_status
;
7802 DoConnection(ssl_options
, &cert_status
);
7804 // If we're not trying EV verification then, even if the CRLSet has expired,
7805 // we don't fall back to online revocation checks.
7806 EXPECT_EQ(0u, cert_status
& CERT_STATUS_ALL_ERRORS
);
7807 EXPECT_FALSE(cert_status
& CERT_STATUS_IS_EV
);
7808 EXPECT_FALSE(cert_status
& CERT_STATUS_REV_CHECKING_ENABLED
);
7811 TEST_F(HTTPSCRLSetTest
, CRLSetRevoked
) {
7812 #if defined(OS_ANDROID)
7813 LOG(WARNING
) << "Skipping test because system doesn't support CRLSets";
7817 SpawnedTestServer::SSLOptions
ssl_options(
7818 SpawnedTestServer::SSLOptions::CERT_AUTO
);
7819 ssl_options
.ocsp_status
= SpawnedTestServer::SSLOptions::OCSP_OK
;
7820 ssl_options
.cert_serial
= 10;
7821 SSLConfigService::SetCRLSet(
7822 scoped_refptr
<CRLSet
>(CRLSet::ForTesting(
7823 false, &kOCSPTestCertSPKI
, "\x0a")));
7825 CertStatus cert_status
= 0;
7826 DoConnection(ssl_options
, &cert_status
);
7828 // If the certificate is recorded as revoked in the CRLSet, that should be
7829 // reflected without online revocation checking.
7830 EXPECT_EQ(CERT_STATUS_REVOKED
, cert_status
& CERT_STATUS_ALL_ERRORS
);
7831 EXPECT_FALSE(cert_status
& CERT_STATUS_IS_EV
);
7833 static_cast<bool>(cert_status
& CERT_STATUS_REV_CHECKING_ENABLED
));
7835 #endif // !defined(OS_IOS)
7837 #if !defined(DISABLE_FTP_SUPPORT)
7838 class URLRequestTestFTP
: public URLRequestTest
{
7841 : test_server_(SpawnedTestServer::TYPE_FTP
, SpawnedTestServer::kLocalhost
,
7846 SpawnedTestServer test_server_
;
7849 // Make sure an FTP request using an unsafe ports fails.
7850 TEST_F(URLRequestTestFTP
, UnsafePort
) {
7851 ASSERT_TRUE(test_server_
.Start());
7853 URLRequestJobFactoryImpl job_factory
;
7854 FtpNetworkLayer
ftp_transaction_factory(default_context_
.host_resolver());
7856 GURL
url("ftp://127.0.0.1:7");
7857 job_factory
.SetProtocolHandler(
7859 new FtpProtocolHandler(&ftp_transaction_factory
));
7860 default_context_
.set_job_factory(&job_factory
);
7864 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
7865 url
, DEFAULT_PRIORITY
, &d
, NULL
));
7867 EXPECT_TRUE(r
->is_pending());
7869 base::RunLoop().Run();
7871 EXPECT_FALSE(r
->is_pending());
7872 EXPECT_EQ(URLRequestStatus::FAILED
, r
->status().status());
7873 EXPECT_EQ(ERR_UNSAFE_PORT
, r
->status().error());
7877 // Flaky, see http://crbug.com/25045.
7878 TEST_F(URLRequestTestFTP
, DISABLED_FTPDirectoryListing
) {
7879 ASSERT_TRUE(test_server_
.Start());
7883 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
7884 test_server_
.GetURL("/"), DEFAULT_PRIORITY
, &d
, NULL
));
7886 EXPECT_TRUE(r
->is_pending());
7888 base::RunLoop().Run();
7890 EXPECT_FALSE(r
->is_pending());
7891 EXPECT_EQ(1, d
.response_started_count());
7892 EXPECT_FALSE(d
.received_data_before_response());
7893 EXPECT_LT(0, d
.bytes_received());
7894 EXPECT_EQ(test_server_
.host_port_pair().host(),
7895 r
->GetSocketAddress().host());
7896 EXPECT_EQ(test_server_
.host_port_pair().port(),
7897 r
->GetSocketAddress().port());
7901 // Flaky, see http://crbug.com/25045.
7902 TEST_F(URLRequestTestFTP
, DISABLED_FTPGetTestAnonymous
) {
7903 ASSERT_TRUE(test_server_
.Start());
7905 base::FilePath app_path
;
7906 PathService::Get(base::DIR_SOURCE_ROOT
, &app_path
);
7907 app_path
= app_path
.AppendASCII("LICENSE");
7910 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
7911 test_server_
.GetURL("/LICENSE"), DEFAULT_PRIORITY
, &d
, NULL
));
7913 EXPECT_TRUE(r
->is_pending());
7915 base::RunLoop().Run();
7917 int64 file_size
= 0;
7918 base::GetFileSize(app_path
, &file_size
);
7920 EXPECT_FALSE(r
->is_pending());
7921 EXPECT_EQ(1, d
.response_started_count());
7922 EXPECT_FALSE(d
.received_data_before_response());
7923 EXPECT_EQ(d
.bytes_received(), static_cast<int>(file_size
));
7924 EXPECT_EQ(test_server_
.host_port_pair().host(),
7925 r
->GetSocketAddress().host());
7926 EXPECT_EQ(test_server_
.host_port_pair().port(),
7927 r
->GetSocketAddress().port());
7931 // Flaky, see http://crbug.com/25045.
7932 TEST_F(URLRequestTestFTP
, DISABLED_FTPGetTest
) {
7933 ASSERT_TRUE(test_server_
.Start());
7935 base::FilePath app_path
;
7936 PathService::Get(base::DIR_SOURCE_ROOT
, &app_path
);
7937 app_path
= app_path
.AppendASCII("LICENSE");
7940 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
7941 test_server_
.GetURLWithUserAndPassword("/LICENSE", "chrome", "chrome"),
7942 DEFAULT_PRIORITY
, &d
, NULL
));
7944 EXPECT_TRUE(r
->is_pending());
7946 base::RunLoop().Run();
7948 int64 file_size
= 0;
7949 base::GetFileSize(app_path
, &file_size
);
7951 EXPECT_FALSE(r
->is_pending());
7952 EXPECT_EQ(test_server_
.host_port_pair().host(),
7953 r
->GetSocketAddress().host());
7954 EXPECT_EQ(test_server_
.host_port_pair().port(),
7955 r
->GetSocketAddress().port());
7956 EXPECT_EQ(1, d
.response_started_count());
7957 EXPECT_FALSE(d
.received_data_before_response());
7958 EXPECT_EQ(d
.bytes_received(), static_cast<int>(file_size
));
7960 LoadTimingInfo load_timing_info
;
7961 r
->GetLoadTimingInfo(&load_timing_info
);
7962 TestLoadTimingNoHttpResponse(load_timing_info
);
7966 // Flaky, see http://crbug.com/25045.
7967 TEST_F(URLRequestTestFTP
, DISABLED_FTPCheckWrongPassword
) {
7968 ASSERT_TRUE(test_server_
.Start());
7970 base::FilePath app_path
;
7971 PathService::Get(base::DIR_SOURCE_ROOT
, &app_path
);
7972 app_path
= app_path
.AppendASCII("LICENSE");
7975 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
7976 test_server_
.GetURLWithUserAndPassword("/LICENSE", "chrome",
7978 DEFAULT_PRIORITY
, &d
, NULL
));
7980 EXPECT_TRUE(r
->is_pending());
7982 base::RunLoop().Run();
7984 int64 file_size
= 0;
7985 base::GetFileSize(app_path
, &file_size
);
7987 EXPECT_FALSE(r
->is_pending());
7988 EXPECT_EQ(1, d
.response_started_count());
7989 EXPECT_FALSE(d
.received_data_before_response());
7990 EXPECT_EQ(d
.bytes_received(), 0);
7994 // Flaky, see http://crbug.com/25045.
7995 TEST_F(URLRequestTestFTP
, DISABLED_FTPCheckWrongPasswordRestart
) {
7996 ASSERT_TRUE(test_server_
.Start());
7998 base::FilePath app_path
;
7999 PathService::Get(base::DIR_SOURCE_ROOT
, &app_path
);
8000 app_path
= app_path
.AppendASCII("LICENSE");
8002 // Set correct login credentials. The delegate will be asked for them when
8003 // the initial login with wrong credentials will fail.
8004 d
.set_credentials(AuthCredentials(kChrome
, kChrome
));
8006 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
8007 test_server_
.GetURLWithUserAndPassword("/LICENSE", "chrome",
8009 DEFAULT_PRIORITY
, &d
, NULL
));
8011 EXPECT_TRUE(r
->is_pending());
8013 base::RunLoop().Run();
8015 int64 file_size
= 0;
8016 base::GetFileSize(app_path
, &file_size
);
8018 EXPECT_FALSE(r
->is_pending());
8019 EXPECT_EQ(1, d
.response_started_count());
8020 EXPECT_FALSE(d
.received_data_before_response());
8021 EXPECT_EQ(d
.bytes_received(), static_cast<int>(file_size
));
8025 // Flaky, see http://crbug.com/25045.
8026 TEST_F(URLRequestTestFTP
, DISABLED_FTPCheckWrongUser
) {
8027 ASSERT_TRUE(test_server_
.Start());
8029 base::FilePath app_path
;
8030 PathService::Get(base::DIR_SOURCE_ROOT
, &app_path
);
8031 app_path
= app_path
.AppendASCII("LICENSE");
8034 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
8035 test_server_
.GetURLWithUserAndPassword("/LICENSE", "wrong_user",
8037 DEFAULT_PRIORITY
, &d
, NULL
));
8039 EXPECT_TRUE(r
->is_pending());
8041 base::RunLoop().Run();
8043 int64 file_size
= 0;
8044 base::GetFileSize(app_path
, &file_size
);
8046 EXPECT_FALSE(r
->is_pending());
8047 EXPECT_EQ(1, d
.response_started_count());
8048 EXPECT_FALSE(d
.received_data_before_response());
8049 EXPECT_EQ(d
.bytes_received(), 0);
8053 // Flaky, see http://crbug.com/25045.
8054 TEST_F(URLRequestTestFTP
, DISABLED_FTPCheckWrongUserRestart
) {
8055 ASSERT_TRUE(test_server_
.Start());
8057 base::FilePath app_path
;
8058 PathService::Get(base::DIR_SOURCE_ROOT
, &app_path
);
8059 app_path
= app_path
.AppendASCII("LICENSE");
8061 // Set correct login credentials. The delegate will be asked for them when
8062 // the initial login with wrong credentials will fail.
8063 d
.set_credentials(AuthCredentials(kChrome
, kChrome
));
8065 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
8066 test_server_
.GetURLWithUserAndPassword("/LICENSE", "wrong_user",
8068 DEFAULT_PRIORITY
, &d
, NULL
));
8070 EXPECT_TRUE(r
->is_pending());
8072 base::RunLoop().Run();
8074 int64 file_size
= 0;
8075 base::GetFileSize(app_path
, &file_size
);
8077 EXPECT_FALSE(r
->is_pending());
8078 EXPECT_EQ(1, d
.response_started_count());
8079 EXPECT_FALSE(d
.received_data_before_response());
8080 EXPECT_EQ(d
.bytes_received(), static_cast<int>(file_size
));
8084 // Flaky, see http://crbug.com/25045.
8085 TEST_F(URLRequestTestFTP
, DISABLED_FTPCacheURLCredentials
) {
8086 ASSERT_TRUE(test_server_
.Start());
8088 base::FilePath app_path
;
8089 PathService::Get(base::DIR_SOURCE_ROOT
, &app_path
);
8090 app_path
= app_path
.AppendASCII("LICENSE");
8092 scoped_ptr
<TestDelegate
> d(new TestDelegate
);
8094 // Pass correct login identity in the URL.
8095 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
8096 test_server_
.GetURLWithUserAndPassword("/LICENSE", "chrome", "chrome"),
8097 DEFAULT_PRIORITY
, d
.get(), NULL
));
8099 EXPECT_TRUE(r
->is_pending());
8101 base::RunLoop().Run();
8103 int64 file_size
= 0;
8104 base::GetFileSize(app_path
, &file_size
);
8106 EXPECT_FALSE(r
->is_pending());
8107 EXPECT_EQ(1, d
->response_started_count());
8108 EXPECT_FALSE(d
->received_data_before_response());
8109 EXPECT_EQ(d
->bytes_received(), static_cast<int>(file_size
));
8112 d
.reset(new TestDelegate
);
8114 // This request should use cached identity from previous request.
8115 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
8116 test_server_
.GetURL("/LICENSE"), DEFAULT_PRIORITY
, d
.get(), NULL
));
8118 EXPECT_TRUE(r
->is_pending());
8120 base::RunLoop().Run();
8122 int64 file_size
= 0;
8123 base::GetFileSize(app_path
, &file_size
);
8125 EXPECT_FALSE(r
->is_pending());
8126 EXPECT_EQ(1, d
->response_started_count());
8127 EXPECT_FALSE(d
->received_data_before_response());
8128 EXPECT_EQ(d
->bytes_received(), static_cast<int>(file_size
));
8132 // Flaky, see http://crbug.com/25045.
8133 TEST_F(URLRequestTestFTP
, DISABLED_FTPCacheLoginBoxCredentials
) {
8134 ASSERT_TRUE(test_server_
.Start());
8136 base::FilePath app_path
;
8137 PathService::Get(base::DIR_SOURCE_ROOT
, &app_path
);
8138 app_path
= app_path
.AppendASCII("LICENSE");
8140 scoped_ptr
<TestDelegate
> d(new TestDelegate
);
8141 // Set correct login credentials. The delegate will be asked for them when
8142 // the initial login with wrong credentials will fail.
8143 d
->set_credentials(AuthCredentials(kChrome
, kChrome
));
8145 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
8146 test_server_
.GetURLWithUserAndPassword("/LICENSE", "chrome",
8148 DEFAULT_PRIORITY
, d
.get(), NULL
));
8150 EXPECT_TRUE(r
->is_pending());
8152 base::RunLoop().Run();
8154 int64 file_size
= 0;
8155 base::GetFileSize(app_path
, &file_size
);
8157 EXPECT_FALSE(r
->is_pending());
8158 EXPECT_EQ(1, d
->response_started_count());
8159 EXPECT_FALSE(d
->received_data_before_response());
8160 EXPECT_EQ(d
->bytes_received(), static_cast<int>(file_size
));
8163 // Use a new delegate without explicit credentials. The cached ones should be
8165 d
.reset(new TestDelegate
);
8167 // Don't pass wrong credentials in the URL, they would override valid cached
8169 scoped_ptr
<URLRequest
> r(default_context_
.CreateRequest(
8170 test_server_
.GetURL("/LICENSE"), DEFAULT_PRIORITY
, d
.get(), NULL
));
8172 EXPECT_TRUE(r
->is_pending());
8174 base::RunLoop().Run();
8176 int64 file_size
= 0;
8177 base::GetFileSize(app_path
, &file_size
);
8179 EXPECT_FALSE(r
->is_pending());
8180 EXPECT_EQ(1, d
->response_started_count());
8181 EXPECT_FALSE(d
->received_data_before_response());
8182 EXPECT_EQ(d
->bytes_received(), static_cast<int>(file_size
));
8185 #endif // !defined(DISABLE_FTP_SUPPORT)