Cast: Stop logging kVideoFrameSentToEncoder and rename a couple events.
[chromium-blink-merge.git] / net / url_request / url_request_unittest.cc
blob97d36227711c38537b7ee43a4b3d7cf74498ffad
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"
7 #if defined(OS_WIN)
8 #include <windows.h>
9 #include <shlobj.h>
10 #endif
12 #include <algorithm>
13 #include <string>
15 #include "base/basictypes.h"
16 #include "base/bind.h"
17 #include "base/compiler_specific.h"
18 #include "base/file_util.h"
19 #include "base/files/scoped_temp_dir.h"
20 #include "base/format_macros.h"
21 #include "base/memory/weak_ptr.h"
22 #include "base/message_loop/message_loop.h"
23 #include "base/message_loop/message_loop_proxy.h"
24 #include "base/path_service.h"
25 #include "base/run_loop.h"
26 #include "base/strings/string_number_conversions.h"
27 #include "base/strings/string_piece.h"
28 #include "base/strings/string_split.h"
29 #include "base/strings/string_util.h"
30 #include "base/strings/stringprintf.h"
31 #include "base/strings/utf_string_conversions.h"
32 #include "net/base/capturing_net_log.h"
33 #include "net/base/filename_util.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_connection_status_flags.h"
66 #include "net/test/cert_test_util.h"
67 #include "net/test/spawned_test_server/spawned_test_server.h"
68 #include "net/url_request/data_protocol_handler.h"
69 #include "net/url_request/file_protocol_handler.h"
70 #include "net/url_request/ftp_protocol_handler.h"
71 #include "net/url_request/static_http_user_agent_settings.h"
72 #include "net/url_request/url_request.h"
73 #include "net/url_request/url_request_file_dir_job.h"
74 #include "net/url_request/url_request_http_job.h"
75 #include "net/url_request/url_request_job_factory_impl.h"
76 #include "net/url_request/url_request_redirect_job.h"
77 #include "net/url_request/url_request_test_job.h"
78 #include "net/url_request/url_request_test_util.h"
79 #include "testing/gtest/include/gtest/gtest.h"
80 #include "testing/platform_test.h"
82 #if defined(OS_WIN)
83 #include "base/win/scoped_com_initializer.h"
84 #include "base/win/scoped_comptr.h"
85 #include "base/win/windows_version.h"
86 #endif
88 using base::ASCIIToUTF16;
89 using base::Time;
91 namespace net {
93 namespace {
95 const base::string16 kChrome(ASCIIToUTF16("chrome"));
96 const base::string16 kSecret(ASCIIToUTF16("secret"));
97 const base::string16 kUser(ASCIIToUTF16("user"));
99 // Tests load timing information in the case a fresh connection was used, with
100 // no proxy.
101 void TestLoadTimingNotReused(const net::LoadTimingInfo& load_timing_info,
102 int connect_timing_flags) {
103 EXPECT_FALSE(load_timing_info.socket_reused);
104 EXPECT_NE(net::NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
106 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
107 EXPECT_FALSE(load_timing_info.request_start.is_null());
109 EXPECT_LE(load_timing_info.request_start,
110 load_timing_info.connect_timing.connect_start);
111 ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
112 connect_timing_flags);
113 EXPECT_LE(load_timing_info.connect_timing.connect_end,
114 load_timing_info.send_start);
115 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
116 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
118 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
119 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
122 // Same as above, but with proxy times.
123 void TestLoadTimingNotReusedWithProxy(
124 const net::LoadTimingInfo& load_timing_info,
125 int connect_timing_flags) {
126 EXPECT_FALSE(load_timing_info.socket_reused);
127 EXPECT_NE(net::NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
129 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
130 EXPECT_FALSE(load_timing_info.request_start.is_null());
132 EXPECT_LE(load_timing_info.request_start,
133 load_timing_info.proxy_resolve_start);
134 EXPECT_LE(load_timing_info.proxy_resolve_start,
135 load_timing_info.proxy_resolve_end);
136 EXPECT_LE(load_timing_info.proxy_resolve_end,
137 load_timing_info.connect_timing.connect_start);
138 ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
139 connect_timing_flags);
140 EXPECT_LE(load_timing_info.connect_timing.connect_end,
141 load_timing_info.send_start);
142 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
143 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
146 // Same as above, but with a reused socket and proxy times.
147 void TestLoadTimingReusedWithProxy(
148 const net::LoadTimingInfo& load_timing_info) {
149 EXPECT_TRUE(load_timing_info.socket_reused);
150 EXPECT_NE(net::NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
152 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
153 EXPECT_FALSE(load_timing_info.request_start.is_null());
155 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
157 EXPECT_LE(load_timing_info.request_start,
158 load_timing_info.proxy_resolve_start);
159 EXPECT_LE(load_timing_info.proxy_resolve_start,
160 load_timing_info.proxy_resolve_end);
161 EXPECT_LE(load_timing_info.proxy_resolve_end,
162 load_timing_info.send_start);
163 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
164 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
167 // Tests load timing information in the case of a cache hit, when no cache
168 // validation request was sent over the wire.
169 base::StringPiece TestNetResourceProvider(int key) {
170 return "header";
173 void FillBuffer(char* buffer, size_t len) {
174 static bool called = false;
175 if (!called) {
176 called = true;
177 int seed = static_cast<int>(Time::Now().ToInternalValue());
178 srand(seed);
181 for (size_t i = 0; i < len; i++) {
182 buffer[i] = static_cast<char>(rand());
183 if (!buffer[i])
184 buffer[i] = 'g';
188 #if !defined(OS_IOS)
189 void TestLoadTimingCacheHitNoNetwork(
190 const net::LoadTimingInfo& load_timing_info) {
191 EXPECT_FALSE(load_timing_info.socket_reused);
192 EXPECT_EQ(net::NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
194 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
195 EXPECT_FALSE(load_timing_info.request_start.is_null());
197 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
198 EXPECT_LE(load_timing_info.request_start, load_timing_info.send_start);
199 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
200 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
202 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
203 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
206 // Tests load timing in the case that there is no HTTP response. This can be
207 // used to test in the case of errors or non-HTTP requests.
208 void TestLoadTimingNoHttpResponse(
209 const net::LoadTimingInfo& load_timing_info) {
210 EXPECT_FALSE(load_timing_info.socket_reused);
211 EXPECT_EQ(net::NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
213 // Only the request times should be non-null.
214 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
215 EXPECT_FALSE(load_timing_info.request_start.is_null());
217 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
219 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
220 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
221 EXPECT_TRUE(load_timing_info.send_start.is_null());
222 EXPECT_TRUE(load_timing_info.send_end.is_null());
223 EXPECT_TRUE(load_timing_info.receive_headers_end.is_null());
226 // Do a case-insensitive search through |haystack| for |needle|.
227 bool ContainsString(const std::string& haystack, const char* needle) {
228 std::string::const_iterator it =
229 std::search(haystack.begin(),
230 haystack.end(),
231 needle,
232 needle + strlen(needle),
233 base::CaseInsensitiveCompare<char>());
234 return it != haystack.end();
237 UploadDataStream* CreateSimpleUploadData(const char* data) {
238 scoped_ptr<UploadElementReader> reader(
239 new UploadBytesElementReader(data, strlen(data)));
240 return UploadDataStream::CreateWithReader(reader.Pass(), 0);
243 // Verify that the SSLInfo of a successful SSL connection has valid values.
244 void CheckSSLInfo(const SSLInfo& ssl_info) {
245 // -1 means unknown. 0 means no encryption.
246 EXPECT_GT(ssl_info.security_bits, 0);
248 // The cipher suite TLS_NULL_WITH_NULL_NULL (0) must not be negotiated.
249 int cipher_suite = SSLConnectionStatusToCipherSuite(
250 ssl_info.connection_status);
251 EXPECT_NE(0, cipher_suite);
254 void CheckFullRequestHeaders(const HttpRequestHeaders& headers,
255 const GURL& host_url) {
256 std::string sent_value;
258 EXPECT_TRUE(headers.GetHeader("Host", &sent_value));
259 EXPECT_EQ(GetHostAndOptionalPort(host_url), sent_value);
261 EXPECT_TRUE(headers.GetHeader("Connection", &sent_value));
262 EXPECT_EQ("keep-alive", sent_value);
265 bool FingerprintsEqual(const HashValueVector& a, const HashValueVector& b) {
266 size_t size = a.size();
268 if (size != b.size())
269 return false;
271 for (size_t i = 0; i < size; ++i) {
272 if (!a[i].Equals(b[i]))
273 return false;
276 return true;
278 #endif // !defined(OS_IOS)
280 // A network delegate that allows the user to choose a subset of request stages
281 // to block in. When blocking, the delegate can do one of the following:
282 // * synchronously return a pre-specified error code, or
283 // * asynchronously return that value via an automatically called callback,
284 // or
285 // * block and wait for the user to do a callback.
286 // Additionally, the user may also specify a redirect URL -- then each request
287 // with the current URL different from the redirect target will be redirected
288 // to that target, in the on-before-URL-request stage, independent of whether
289 // the delegate blocks in ON_BEFORE_URL_REQUEST or not.
290 class BlockingNetworkDelegate : public TestNetworkDelegate {
291 public:
292 // Stages in which the delegate can block.
293 enum Stage {
294 NOT_BLOCKED = 0,
295 ON_BEFORE_URL_REQUEST = 1 << 0,
296 ON_BEFORE_SEND_HEADERS = 1 << 1,
297 ON_HEADERS_RECEIVED = 1 << 2,
298 ON_AUTH_REQUIRED = 1 << 3
301 // Behavior during blocked stages. During other stages, just
302 // returns net::OK or NetworkDelegate::AUTH_REQUIRED_RESPONSE_NO_ACTION.
303 enum BlockMode {
304 SYNCHRONOUS, // No callback, returns specified return values.
305 AUTO_CALLBACK, // |this| posts a task to run the callback using the
306 // specified return codes.
307 USER_CALLBACK, // User takes care of doing a callback. |retval_| and
308 // |auth_retval_| are ignored. In every blocking stage the
309 // message loop is quit.
312 // Creates a delegate which does not block at all.
313 explicit BlockingNetworkDelegate(BlockMode block_mode);
315 // For users to trigger a callback returning |response|.
316 // Side-effects: resets |stage_blocked_for_callback_| and stored callbacks.
317 // Only call if |block_mode_| == USER_CALLBACK.
318 void DoCallback(int response);
319 void DoAuthCallback(NetworkDelegate::AuthRequiredResponse response);
321 // Setters.
322 void set_retval(int retval) {
323 ASSERT_NE(USER_CALLBACK, block_mode_);
324 ASSERT_NE(ERR_IO_PENDING, retval);
325 ASSERT_NE(OK, retval);
326 retval_ = retval;
329 // If |auth_retval| == AUTH_REQUIRED_RESPONSE_SET_AUTH, then
330 // |auth_credentials_| will be passed with the response.
331 void set_auth_retval(AuthRequiredResponse auth_retval) {
332 ASSERT_NE(USER_CALLBACK, block_mode_);
333 ASSERT_NE(AUTH_REQUIRED_RESPONSE_IO_PENDING, auth_retval);
334 auth_retval_ = auth_retval;
336 void set_auth_credentials(const AuthCredentials& auth_credentials) {
337 auth_credentials_ = auth_credentials;
340 void set_redirect_url(const GURL& url) {
341 redirect_url_ = url;
344 void set_block_on(int block_on) {
345 block_on_ = block_on;
348 // Allows the user to check in which state did we block.
349 Stage stage_blocked_for_callback() const {
350 EXPECT_EQ(USER_CALLBACK, block_mode_);
351 return stage_blocked_for_callback_;
354 private:
355 void RunCallback(int response, const CompletionCallback& callback);
356 void RunAuthCallback(AuthRequiredResponse response,
357 const AuthCallback& callback);
359 // TestNetworkDelegate implementation.
360 virtual int OnBeforeURLRequest(URLRequest* request,
361 const CompletionCallback& callback,
362 GURL* new_url) OVERRIDE;
364 virtual int OnBeforeSendHeaders(URLRequest* request,
365 const CompletionCallback& callback,
366 HttpRequestHeaders* headers) OVERRIDE;
368 virtual int OnHeadersReceived(
369 URLRequest* request,
370 const CompletionCallback& callback,
371 const HttpResponseHeaders* original_response_headers,
372 scoped_refptr<HttpResponseHeaders>* override_response_headers,
373 GURL* allowed_unsafe_redirect_url) OVERRIDE;
375 virtual NetworkDelegate::AuthRequiredResponse OnAuthRequired(
376 URLRequest* request,
377 const AuthChallengeInfo& auth_info,
378 const AuthCallback& callback,
379 AuthCredentials* credentials) OVERRIDE;
381 // Resets the callbacks and |stage_blocked_for_callback_|.
382 void Reset();
384 // Checks whether we should block in |stage|. If yes, returns an error code
385 // and optionally sets up callback based on |block_mode_|. If no, returns OK.
386 int MaybeBlockStage(Stage stage, const CompletionCallback& callback);
388 // Configuration parameters, can be adjusted by public methods:
389 const BlockMode block_mode_;
391 // Values returned on blocking stages when mode is SYNCHRONOUS or
392 // AUTO_CALLBACK. For USER_CALLBACK these are set automatically to IO_PENDING.
393 int retval_; // To be returned in non-auth stages.
394 AuthRequiredResponse auth_retval_;
396 GURL redirect_url_; // Used if non-empty during OnBeforeURLRequest.
397 int block_on_; // Bit mask: in which stages to block.
399 // |auth_credentials_| will be copied to |*target_auth_credential_| on
400 // callback.
401 AuthCredentials auth_credentials_;
402 AuthCredentials* target_auth_credentials_;
404 // Internal variables, not set by not the user:
405 // Last blocked stage waiting for user callback (unused if |block_mode_| !=
406 // USER_CALLBACK).
407 Stage stage_blocked_for_callback_;
409 // Callback objects stored during blocking stages.
410 CompletionCallback callback_;
411 AuthCallback auth_callback_;
413 base::WeakPtrFactory<BlockingNetworkDelegate> weak_factory_;
415 DISALLOW_COPY_AND_ASSIGN(BlockingNetworkDelegate);
418 BlockingNetworkDelegate::BlockingNetworkDelegate(BlockMode block_mode)
419 : block_mode_(block_mode),
420 retval_(OK),
421 auth_retval_(AUTH_REQUIRED_RESPONSE_NO_ACTION),
422 block_on_(0),
423 target_auth_credentials_(NULL),
424 stage_blocked_for_callback_(NOT_BLOCKED),
425 weak_factory_(this) {
428 void BlockingNetworkDelegate::DoCallback(int response) {
429 ASSERT_EQ(USER_CALLBACK, block_mode_);
430 ASSERT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
431 ASSERT_NE(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
432 CompletionCallback callback = callback_;
433 Reset();
434 RunCallback(response, callback);
437 void BlockingNetworkDelegate::DoAuthCallback(
438 NetworkDelegate::AuthRequiredResponse response) {
439 ASSERT_EQ(USER_CALLBACK, block_mode_);
440 ASSERT_EQ(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
441 AuthCallback auth_callback = auth_callback_;
442 Reset();
443 RunAuthCallback(response, auth_callback);
446 void BlockingNetworkDelegate::RunCallback(int response,
447 const CompletionCallback& callback) {
448 callback.Run(response);
451 void BlockingNetworkDelegate::RunAuthCallback(AuthRequiredResponse response,
452 const AuthCallback& callback) {
453 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH) {
454 ASSERT_TRUE(target_auth_credentials_ != NULL);
455 *target_auth_credentials_ = auth_credentials_;
457 callback.Run(response);
460 int BlockingNetworkDelegate::OnBeforeURLRequest(
461 URLRequest* request,
462 const CompletionCallback& callback,
463 GURL* new_url) {
464 if (redirect_url_ == request->url())
465 return OK; // We've already seen this request and redirected elsewhere.
467 TestNetworkDelegate::OnBeforeURLRequest(request, callback, new_url);
469 if (!redirect_url_.is_empty())
470 *new_url = redirect_url_;
472 return MaybeBlockStage(ON_BEFORE_URL_REQUEST, callback);
475 int BlockingNetworkDelegate::OnBeforeSendHeaders(
476 URLRequest* request,
477 const CompletionCallback& callback,
478 HttpRequestHeaders* headers) {
479 TestNetworkDelegate::OnBeforeSendHeaders(request, callback, headers);
481 return MaybeBlockStage(ON_BEFORE_SEND_HEADERS, callback);
484 int BlockingNetworkDelegate::OnHeadersReceived(
485 URLRequest* request,
486 const CompletionCallback& callback,
487 const HttpResponseHeaders* original_response_headers,
488 scoped_refptr<HttpResponseHeaders>* override_response_headers,
489 GURL* allowed_unsafe_redirect_url) {
490 TestNetworkDelegate::OnHeadersReceived(request,
491 callback,
492 original_response_headers,
493 override_response_headers,
494 allowed_unsafe_redirect_url);
496 return MaybeBlockStage(ON_HEADERS_RECEIVED, callback);
499 NetworkDelegate::AuthRequiredResponse BlockingNetworkDelegate::OnAuthRequired(
500 URLRequest* request,
501 const AuthChallengeInfo& auth_info,
502 const AuthCallback& callback,
503 AuthCredentials* credentials) {
504 TestNetworkDelegate::OnAuthRequired(request, auth_info, callback,
505 credentials);
506 // Check that the user has provided callback for the previous blocked stage.
507 EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
509 if ((block_on_ & ON_AUTH_REQUIRED) == 0) {
510 return AUTH_REQUIRED_RESPONSE_NO_ACTION;
513 target_auth_credentials_ = credentials;
515 switch (block_mode_) {
516 case SYNCHRONOUS:
517 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH)
518 *target_auth_credentials_ = auth_credentials_;
519 return auth_retval_;
521 case AUTO_CALLBACK:
522 base::MessageLoop::current()->PostTask(
523 FROM_HERE,
524 base::Bind(&BlockingNetworkDelegate::RunAuthCallback,
525 weak_factory_.GetWeakPtr(), auth_retval_, callback));
526 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
528 case USER_CALLBACK:
529 auth_callback_ = callback;
530 stage_blocked_for_callback_ = ON_AUTH_REQUIRED;
531 base::MessageLoop::current()->PostTask(FROM_HERE,
532 base::MessageLoop::QuitClosure());
533 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
535 NOTREACHED();
536 return AUTH_REQUIRED_RESPONSE_NO_ACTION; // Dummy value.
539 void BlockingNetworkDelegate::Reset() {
540 EXPECT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
541 stage_blocked_for_callback_ = NOT_BLOCKED;
542 callback_.Reset();
543 auth_callback_.Reset();
546 int BlockingNetworkDelegate::MaybeBlockStage(
547 BlockingNetworkDelegate::Stage stage,
548 const CompletionCallback& callback) {
549 // Check that the user has provided callback for the previous blocked stage.
550 EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
552 if ((block_on_ & stage) == 0) {
553 return OK;
556 switch (block_mode_) {
557 case SYNCHRONOUS:
558 EXPECT_NE(OK, retval_);
559 return retval_;
561 case AUTO_CALLBACK:
562 base::MessageLoop::current()->PostTask(
563 FROM_HERE,
564 base::Bind(&BlockingNetworkDelegate::RunCallback,
565 weak_factory_.GetWeakPtr(), retval_, callback));
566 return ERR_IO_PENDING;
568 case USER_CALLBACK:
569 callback_ = callback;
570 stage_blocked_for_callback_ = stage;
571 base::MessageLoop::current()->PostTask(FROM_HERE,
572 base::MessageLoop::QuitClosure());
573 return ERR_IO_PENDING;
575 NOTREACHED();
576 return 0;
579 class TestURLRequestContextWithProxy : public TestURLRequestContext {
580 public:
581 // Does not own |delegate|.
582 TestURLRequestContextWithProxy(const std::string& proxy,
583 NetworkDelegate* delegate)
584 : TestURLRequestContext(true) {
585 context_storage_.set_proxy_service(ProxyService::CreateFixed(proxy));
586 set_network_delegate(delegate);
587 Init();
589 virtual ~TestURLRequestContextWithProxy() {}
592 } // namespace
594 // Inherit PlatformTest since we require the autorelease pool on Mac OS X.
595 class URLRequestTest : public PlatformTest {
596 public:
597 URLRequestTest() : default_context_(true) {
598 default_context_.set_network_delegate(&default_network_delegate_);
599 default_context_.set_net_log(&net_log_);
600 job_factory_.SetProtocolHandler("data", new DataProtocolHandler);
601 job_factory_.SetProtocolHandler(
602 "file", new FileProtocolHandler(base::MessageLoopProxy::current()));
603 default_context_.set_job_factory(&job_factory_);
604 default_context_.Init();
606 virtual ~URLRequestTest() {
607 // URLRequestJobs may post clean-up tasks on destruction.
608 base::RunLoop().RunUntilIdle();
611 // Adds the TestJobInterceptor to the default context.
612 TestJobInterceptor* AddTestInterceptor() {
613 TestJobInterceptor* protocol_handler_ = new TestJobInterceptor();
614 job_factory_.SetProtocolHandler("http", NULL);
615 job_factory_.SetProtocolHandler("http", protocol_handler_);
616 return protocol_handler_;
619 protected:
620 CapturingNetLog net_log_;
621 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
622 URLRequestJobFactoryImpl job_factory_;
623 TestURLRequestContext default_context_;
626 TEST_F(URLRequestTest, AboutBlankTest) {
627 TestDelegate d;
629 URLRequest r(GURL("about:blank"), DEFAULT_PRIORITY, &d, &default_context_);
631 r.Start();
632 EXPECT_TRUE(r.is_pending());
634 base::RunLoop().Run();
636 EXPECT_TRUE(!r.is_pending());
637 EXPECT_FALSE(d.received_data_before_response());
638 EXPECT_EQ(d.bytes_received(), 0);
639 EXPECT_EQ("", r.GetSocketAddress().host());
640 EXPECT_EQ(0, r.GetSocketAddress().port());
642 HttpRequestHeaders headers;
643 EXPECT_FALSE(r.GetFullRequestHeaders(&headers));
647 TEST_F(URLRequestTest, DataURLImageTest) {
648 TestDelegate d;
650 // Use our nice little Chrome logo.
651 URLRequest r(
652 GURL(
653 "data:image/png;base64,"
654 "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAADVklEQVQ4jX2TfUwUBBjG3"
655 "w1y+HGcd9dxhXR8T4awOccJGgOSWclHImznLkTlSw0DDQXkrmgYgbUYnlQTqQxIEVxitD"
656 "5UMCATRA1CEEg+Qjw3bWDxIauJv/5oumqs39/P827vnucRmYN0gyF01GI5MpCVdW0gO7t"
657 "vNC+vqSEtbZefk5NuLv1jdJ46p/zw0HeH4+PHr3h7c1mjoV2t5rKzMx1+fg9bAgK6zHq9"
658 "cU5z+LpA3xOtx34+vTeT21onRuzssC3zxbbSwC13d/pFuC7CkIMDxQpF7r/MWq12UctI1"
659 "dWWm99ypqSYmRUBdKem8MkrO/kgaTt1O7YzlpzE5GIVd0WYUqt57yWf2McHTObYPbVD+Z"
660 "wbtlLTVMZ3BW+TnLyXLaWtmEq6WJVbT3HBh3Svj2HQQcm43XwmtoYM6vVKleh0uoWvnzW"
661 "3v3MpidruPTQPf0bia7sJOtBM0ufTWNvus/nkDFHF9ZS+uYVjRUasMeHUmyLYtcklTvzW"
662 "GFZnNOXczThvpKIzjcahSqIzkvDLayDq6D3eOjtBbNUEIZYyqsvj4V4wY92eNJ4IoyhTb"
663 "xXX1T5xsV9tm9r4TQwHLiZw/pdDZJea8TKmsmR/K0uLh/GwnCHghTja6lPhphezPfO5/5"
664 "MrVvMzNaI3+ERHfrFzPKQukrQGI4d/3EFD/3E2mVNYvi4at7CXWREaxZGD+3hg28zD3gV"
665 "Md6q5c8GdosynKmSeRuGzpjyl1/9UDGtPR5HeaKT8Wjo17WXk579BXVUhN64ehF9fhRtq"
666 "/uxxZKzNiZFGD0wRC3NFROZ5mwIPL/96K/rKMMLrIzF9uhHr+/sYH7DAbwlgC4J+R2Z7F"
667 "Ux1qLnV7MGF40smVSoJ/jvHRfYhQeUJd/SnYtGWhPHR0Sz+GE2F2yth0B36Vcz2KpnufB"
668 "JbsysjjW4kblBUiIjiURUWqJY65zxbnTy57GQyH58zgy0QBtTQv5gH15XMdKkYu+TGaJM"
669 "nlm2O34uI4b9tflqp1+QEFGzoW/ulmcofcpkZCYJhDfSpme7QcrHa+Xfji8paEQkTkSfm"
670 "moRWRNZr/F1KfVMjW+IKEnv2FwZfKdzt0BQR6lClcZR0EfEXEfv/G6W9iLiIyCoReV5En"
671 "hORIBHx+ufPj/gLB/zGI/G4Bk0AAAAASUVORK5CYII="),
672 DEFAULT_PRIORITY,
674 &default_context_);
676 r.Start();
677 EXPECT_TRUE(r.is_pending());
679 base::RunLoop().Run();
681 EXPECT_TRUE(!r.is_pending());
682 EXPECT_FALSE(d.received_data_before_response());
683 EXPECT_EQ(d.bytes_received(), 911);
684 EXPECT_EQ("", r.GetSocketAddress().host());
685 EXPECT_EQ(0, r.GetSocketAddress().port());
687 HttpRequestHeaders headers;
688 EXPECT_FALSE(r.GetFullRequestHeaders(&headers));
692 TEST_F(URLRequestTest, FileTest) {
693 base::FilePath app_path;
694 PathService::Get(base::FILE_EXE, &app_path);
695 GURL app_url = FilePathToFileURL(app_path);
697 TestDelegate d;
699 URLRequest r(app_url, DEFAULT_PRIORITY, &d, &default_context_);
701 r.Start();
702 EXPECT_TRUE(r.is_pending());
704 base::RunLoop().Run();
706 int64 file_size = -1;
707 EXPECT_TRUE(base::GetFileSize(app_path, &file_size));
709 EXPECT_TRUE(!r.is_pending());
710 EXPECT_EQ(1, d.response_started_count());
711 EXPECT_FALSE(d.received_data_before_response());
712 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
713 EXPECT_EQ("", r.GetSocketAddress().host());
714 EXPECT_EQ(0, r.GetSocketAddress().port());
716 HttpRequestHeaders headers;
717 EXPECT_FALSE(r.GetFullRequestHeaders(&headers));
721 TEST_F(URLRequestTest, FileTestCancel) {
722 base::FilePath app_path;
723 PathService::Get(base::FILE_EXE, &app_path);
724 GURL app_url = FilePathToFileURL(app_path);
726 TestDelegate d;
728 URLRequest r(app_url, DEFAULT_PRIORITY, &d, &default_context_);
730 r.Start();
731 EXPECT_TRUE(r.is_pending());
732 r.Cancel();
734 // Async cancellation should be safe even when URLRequest has been already
735 // destroyed.
736 base::RunLoop().RunUntilIdle();
739 TEST_F(URLRequestTest, FileTestFullSpecifiedRange) {
740 const size_t buffer_size = 4000;
741 scoped_ptr<char[]> buffer(new char[buffer_size]);
742 FillBuffer(buffer.get(), buffer_size);
744 base::FilePath temp_path;
745 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
746 GURL temp_url = FilePathToFileURL(temp_path);
747 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
749 int64 file_size;
750 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
752 const size_t first_byte_position = 500;
753 const size_t last_byte_position = buffer_size - first_byte_position;
754 const size_t content_length = last_byte_position - first_byte_position + 1;
755 std::string partial_buffer_string(buffer.get() + first_byte_position,
756 buffer.get() + last_byte_position + 1);
758 TestDelegate d;
760 URLRequest r(temp_url, DEFAULT_PRIORITY, &d, &default_context_);
762 HttpRequestHeaders headers;
763 headers.SetHeader(
764 HttpRequestHeaders::kRange,
765 net::HttpByteRange::Bounded(
766 first_byte_position, last_byte_position).GetHeaderValue());
767 r.SetExtraRequestHeaders(headers);
768 r.Start();
769 EXPECT_TRUE(r.is_pending());
771 base::RunLoop().Run();
772 EXPECT_TRUE(!r.is_pending());
773 EXPECT_EQ(1, d.response_started_count());
774 EXPECT_FALSE(d.received_data_before_response());
775 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
776 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
777 EXPECT_TRUE(partial_buffer_string == d.data_received());
780 EXPECT_TRUE(base::DeleteFile(temp_path, false));
783 TEST_F(URLRequestTest, FileTestHalfSpecifiedRange) {
784 const size_t buffer_size = 4000;
785 scoped_ptr<char[]> buffer(new char[buffer_size]);
786 FillBuffer(buffer.get(), buffer_size);
788 base::FilePath temp_path;
789 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
790 GURL temp_url = FilePathToFileURL(temp_path);
791 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
793 int64 file_size;
794 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
796 const size_t first_byte_position = 500;
797 const size_t last_byte_position = buffer_size - 1;
798 const size_t content_length = last_byte_position - first_byte_position + 1;
799 std::string partial_buffer_string(buffer.get() + first_byte_position,
800 buffer.get() + last_byte_position + 1);
802 TestDelegate d;
804 URLRequest r(temp_url, DEFAULT_PRIORITY, &d, &default_context_);
806 HttpRequestHeaders headers;
807 headers.SetHeader(HttpRequestHeaders::kRange,
808 net::HttpByteRange::RightUnbounded(
809 first_byte_position).GetHeaderValue());
810 r.SetExtraRequestHeaders(headers);
811 r.Start();
812 EXPECT_TRUE(r.is_pending());
814 base::RunLoop().Run();
815 EXPECT_TRUE(!r.is_pending());
816 EXPECT_EQ(1, d.response_started_count());
817 EXPECT_FALSE(d.received_data_before_response());
818 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
819 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
820 EXPECT_TRUE(partial_buffer_string == d.data_received());
823 EXPECT_TRUE(base::DeleteFile(temp_path, false));
826 TEST_F(URLRequestTest, FileTestMultipleRanges) {
827 const size_t buffer_size = 400000;
828 scoped_ptr<char[]> buffer(new char[buffer_size]);
829 FillBuffer(buffer.get(), buffer_size);
831 base::FilePath temp_path;
832 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
833 GURL temp_url = FilePathToFileURL(temp_path);
834 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
836 int64 file_size;
837 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
839 TestDelegate d;
841 URLRequest r(temp_url, DEFAULT_PRIORITY, &d, &default_context_);
843 HttpRequestHeaders headers;
844 headers.SetHeader(HttpRequestHeaders::kRange, "bytes=0-0,10-200,200-300");
845 r.SetExtraRequestHeaders(headers);
846 r.Start();
847 EXPECT_TRUE(r.is_pending());
849 base::RunLoop().Run();
850 EXPECT_TRUE(d.request_failed());
853 EXPECT_TRUE(base::DeleteFile(temp_path, false));
856 TEST_F(URLRequestTest, AllowFileURLs) {
857 base::ScopedTempDir temp_dir;
858 ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
859 base::FilePath test_file;
860 ASSERT_TRUE(base::CreateTemporaryFileInDir(temp_dir.path(), &test_file));
861 std::string test_data("monkey");
862 base::WriteFile(test_file, test_data.data(), test_data.size());
863 GURL test_file_url = net::FilePathToFileURL(test_file);
866 TestDelegate d;
867 TestNetworkDelegate network_delegate;
868 network_delegate.set_can_access_files(true);
869 default_context_.set_network_delegate(&network_delegate);
870 URLRequest r(test_file_url, DEFAULT_PRIORITY, &d, &default_context_);
871 r.Start();
872 base::RunLoop().Run();
873 EXPECT_FALSE(d.request_failed());
874 EXPECT_EQ(test_data, d.data_received());
878 TestDelegate d;
879 TestNetworkDelegate network_delegate;
880 network_delegate.set_can_access_files(false);
881 default_context_.set_network_delegate(&network_delegate);
882 URLRequest r(test_file_url, DEFAULT_PRIORITY, &d, &default_context_);
883 r.Start();
884 base::RunLoop().Run();
885 EXPECT_TRUE(d.request_failed());
886 EXPECT_EQ("", d.data_received());
890 TEST_F(URLRequestTest, InvalidUrlTest) {
891 TestDelegate d;
893 URLRequest r(GURL("invalid url"), DEFAULT_PRIORITY, &d, &default_context_);
895 r.Start();
896 EXPECT_TRUE(r.is_pending());
898 base::RunLoop().Run();
899 EXPECT_TRUE(d.request_failed());
903 #if defined(OS_WIN)
904 TEST_F(URLRequestTest, ResolveShortcutTest) {
905 base::FilePath app_path;
906 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
907 app_path = app_path.AppendASCII("net");
908 app_path = app_path.AppendASCII("data");
909 app_path = app_path.AppendASCII("url_request_unittest");
910 app_path = app_path.AppendASCII("with-headers.html");
912 std::wstring lnk_path = app_path.value() + L".lnk";
914 base::win::ScopedCOMInitializer com_initializer;
916 // Temporarily create a shortcut for test
918 base::win::ScopedComPtr<IShellLink> shell;
919 ASSERT_TRUE(SUCCEEDED(shell.CreateInstance(CLSID_ShellLink, NULL,
920 CLSCTX_INPROC_SERVER)));
921 base::win::ScopedComPtr<IPersistFile> persist;
922 ASSERT_TRUE(SUCCEEDED(shell.QueryInterface(persist.Receive())));
923 EXPECT_TRUE(SUCCEEDED(shell->SetPath(app_path.value().c_str())));
924 EXPECT_TRUE(SUCCEEDED(shell->SetDescription(L"ResolveShortcutTest")));
925 EXPECT_TRUE(SUCCEEDED(persist->Save(lnk_path.c_str(), TRUE)));
928 TestDelegate d;
930 URLRequest r(FilePathToFileURL(base::FilePath(lnk_path)),
931 DEFAULT_PRIORITY,
933 &default_context_);
935 r.Start();
936 EXPECT_TRUE(r.is_pending());
938 base::RunLoop().Run();
940 WIN32_FILE_ATTRIBUTE_DATA data;
941 GetFileAttributesEx(app_path.value().c_str(),
942 GetFileExInfoStandard, &data);
943 HANDLE file = CreateFile(app_path.value().c_str(), GENERIC_READ,
944 FILE_SHARE_READ, NULL, OPEN_EXISTING,
945 FILE_ATTRIBUTE_NORMAL, NULL);
946 EXPECT_NE(INVALID_HANDLE_VALUE, file);
947 scoped_ptr<char[]> buffer(new char[data.nFileSizeLow]);
948 DWORD read_size;
949 BOOL result;
950 result = ReadFile(file, buffer.get(), data.nFileSizeLow,
951 &read_size, NULL);
952 std::string content(buffer.get(), read_size);
953 CloseHandle(file);
955 EXPECT_TRUE(!r.is_pending());
956 EXPECT_EQ(1, d.received_redirect_count());
957 EXPECT_EQ(content, d.data_received());
960 // Clean the shortcut
961 DeleteFile(lnk_path.c_str());
963 #endif // defined(OS_WIN)
965 TEST_F(URLRequestTest, FileDirCancelTest) {
966 // Put in mock resource provider.
967 NetModule::SetResourceProvider(TestNetResourceProvider);
969 TestDelegate d;
971 base::FilePath file_path;
972 PathService::Get(base::DIR_SOURCE_ROOT, &file_path);
973 file_path = file_path.Append(FILE_PATH_LITERAL("net"));
974 file_path = file_path.Append(FILE_PATH_LITERAL("data"));
976 URLRequest req(
977 FilePathToFileURL(file_path), DEFAULT_PRIORITY, &d, &default_context_);
978 req.Start();
979 EXPECT_TRUE(req.is_pending());
981 d.set_cancel_in_received_data_pending(true);
983 base::RunLoop().Run();
986 // Take out mock resource provider.
987 NetModule::SetResourceProvider(NULL);
990 TEST_F(URLRequestTest, FileDirOutputSanity) {
991 // Verify the general sanity of the the output of the file:
992 // directory lister by checking for the output of a known existing
993 // file.
994 const char sentinel_name[] = "filedir-sentinel";
996 base::FilePath path;
997 PathService::Get(base::DIR_SOURCE_ROOT, &path);
998 path = path.Append(FILE_PATH_LITERAL("net"));
999 path = path.Append(FILE_PATH_LITERAL("data"));
1000 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
1002 TestDelegate d;
1003 URLRequest req(
1004 FilePathToFileURL(path), DEFAULT_PRIORITY, &d, &default_context_);
1005 req.Start();
1006 base::RunLoop().Run();
1008 // Generate entry for the sentinel file.
1009 base::FilePath sentinel_path = path.AppendASCII(sentinel_name);
1010 base::File::Info info;
1011 EXPECT_TRUE(base::GetFileInfo(sentinel_path, &info));
1012 EXPECT_GT(info.size, 0);
1013 std::string sentinel_output = GetDirectoryListingEntry(
1014 base::string16(sentinel_name, sentinel_name + strlen(sentinel_name)),
1015 std::string(sentinel_name),
1016 false /* is_dir */,
1017 info.size,
1018 info.last_modified);
1020 ASSERT_LT(0, d.bytes_received());
1021 ASSERT_FALSE(d.request_failed());
1022 ASSERT_TRUE(req.status().is_success());
1023 // Check for the entry generated for the "sentinel" file.
1024 const std::string& data = d.data_received();
1025 ASSERT_NE(data.find(sentinel_output), std::string::npos);
1028 TEST_F(URLRequestTest, FileDirRedirectNoCrash) {
1029 // There is an implicit redirect when loading a file path that matches a
1030 // directory and does not end with a slash. Ensure that following such
1031 // redirects does not crash. See http://crbug.com/18686.
1033 base::FilePath path;
1034 PathService::Get(base::DIR_SOURCE_ROOT, &path);
1035 path = path.Append(FILE_PATH_LITERAL("net"));
1036 path = path.Append(FILE_PATH_LITERAL("data"));
1037 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
1039 TestDelegate d;
1040 URLRequest req(
1041 FilePathToFileURL(path), DEFAULT_PRIORITY, &d, &default_context_);
1042 req.Start();
1043 base::RunLoop().Run();
1045 ASSERT_EQ(1, d.received_redirect_count());
1046 ASSERT_LT(0, d.bytes_received());
1047 ASSERT_FALSE(d.request_failed());
1048 ASSERT_TRUE(req.status().is_success());
1051 #if defined(OS_WIN)
1052 // Don't accept the url "file:///" on windows. See http://crbug.com/1474.
1053 TEST_F(URLRequestTest, FileDirRedirectSingleSlash) {
1054 TestDelegate d;
1055 URLRequest req(GURL("file:///"), DEFAULT_PRIORITY, &d, &default_context_);
1056 req.Start();
1057 base::RunLoop().Run();
1059 ASSERT_EQ(1, d.received_redirect_count());
1060 ASSERT_FALSE(req.status().is_success());
1062 #endif
1064 // Custom URLRequestJobs for use with interceptor tests
1065 class RestartTestJob : public URLRequestTestJob {
1066 public:
1067 RestartTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1068 : URLRequestTestJob(request, network_delegate, true) {}
1069 protected:
1070 virtual void StartAsync() OVERRIDE {
1071 this->NotifyRestartRequired();
1073 private:
1074 virtual ~RestartTestJob() {}
1077 class CancelTestJob : public URLRequestTestJob {
1078 public:
1079 explicit CancelTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1080 : URLRequestTestJob(request, network_delegate, true) {}
1081 protected:
1082 virtual void StartAsync() OVERRIDE {
1083 request_->Cancel();
1085 private:
1086 virtual ~CancelTestJob() {}
1089 class CancelThenRestartTestJob : public URLRequestTestJob {
1090 public:
1091 explicit CancelThenRestartTestJob(URLRequest* request,
1092 NetworkDelegate* network_delegate)
1093 : URLRequestTestJob(request, network_delegate, true) {
1095 protected:
1096 virtual void StartAsync() OVERRIDE {
1097 request_->Cancel();
1098 this->NotifyRestartRequired();
1100 private:
1101 virtual ~CancelThenRestartTestJob() {}
1104 // An Interceptor for use with interceptor tests
1105 class TestInterceptor : URLRequest::Interceptor {
1106 public:
1107 TestInterceptor()
1108 : intercept_main_request_(false), restart_main_request_(false),
1109 cancel_main_request_(false), cancel_then_restart_main_request_(false),
1110 simulate_main_network_error_(false),
1111 intercept_redirect_(false), cancel_redirect_request_(false),
1112 intercept_final_response_(false), cancel_final_request_(false),
1113 did_intercept_main_(false), did_restart_main_(false),
1114 did_cancel_main_(false), did_cancel_then_restart_main_(false),
1115 did_simulate_error_main_(false),
1116 did_intercept_redirect_(false), did_cancel_redirect_(false),
1117 did_intercept_final_(false), did_cancel_final_(false) {
1118 URLRequest::Deprecated::RegisterRequestInterceptor(this);
1121 virtual ~TestInterceptor() {
1122 URLRequest::Deprecated::UnregisterRequestInterceptor(this);
1125 virtual URLRequestJob* MaybeIntercept(
1126 URLRequest* request,
1127 NetworkDelegate* network_delegate) OVERRIDE {
1128 if (restart_main_request_) {
1129 restart_main_request_ = false;
1130 did_restart_main_ = true;
1131 return new RestartTestJob(request, network_delegate);
1133 if (cancel_main_request_) {
1134 cancel_main_request_ = false;
1135 did_cancel_main_ = true;
1136 return new CancelTestJob(request, network_delegate);
1138 if (cancel_then_restart_main_request_) {
1139 cancel_then_restart_main_request_ = false;
1140 did_cancel_then_restart_main_ = true;
1141 return new CancelThenRestartTestJob(request, network_delegate);
1143 if (simulate_main_network_error_) {
1144 simulate_main_network_error_ = false;
1145 did_simulate_error_main_ = true;
1146 // will error since the requeted url is not one of its canned urls
1147 return new URLRequestTestJob(request, network_delegate, true);
1149 if (!intercept_main_request_)
1150 return NULL;
1151 intercept_main_request_ = false;
1152 did_intercept_main_ = true;
1153 URLRequestTestJob* job = new URLRequestTestJob(request,
1154 network_delegate,
1155 main_headers_,
1156 main_data_,
1157 true);
1158 job->set_load_timing_info(main_request_load_timing_info_);
1159 return job;
1162 virtual URLRequestJob* MaybeInterceptRedirect(
1163 URLRequest* request,
1164 NetworkDelegate* network_delegate,
1165 const GURL& location) OVERRIDE {
1166 if (cancel_redirect_request_) {
1167 cancel_redirect_request_ = false;
1168 did_cancel_redirect_ = true;
1169 return new CancelTestJob(request, network_delegate);
1171 if (!intercept_redirect_)
1172 return NULL;
1173 intercept_redirect_ = false;
1174 did_intercept_redirect_ = true;
1175 return new URLRequestTestJob(request,
1176 network_delegate,
1177 redirect_headers_,
1178 redirect_data_,
1179 true);
1182 virtual URLRequestJob* MaybeInterceptResponse(
1183 URLRequest* request, NetworkDelegate* network_delegate) OVERRIDE {
1184 if (cancel_final_request_) {
1185 cancel_final_request_ = false;
1186 did_cancel_final_ = true;
1187 return new CancelTestJob(request, network_delegate);
1189 if (!intercept_final_response_)
1190 return NULL;
1191 intercept_final_response_ = false;
1192 did_intercept_final_ = true;
1193 return new URLRequestTestJob(request,
1194 network_delegate,
1195 final_headers_,
1196 final_data_,
1197 true);
1200 // Whether to intercept the main request, and if so the response to return and
1201 // the LoadTimingInfo to use.
1202 bool intercept_main_request_;
1203 std::string main_headers_;
1204 std::string main_data_;
1205 LoadTimingInfo main_request_load_timing_info_;
1207 // Other actions we take at MaybeIntercept time
1208 bool restart_main_request_;
1209 bool cancel_main_request_;
1210 bool cancel_then_restart_main_request_;
1211 bool simulate_main_network_error_;
1213 // Whether to intercept redirects, and if so the response to return.
1214 bool intercept_redirect_;
1215 std::string redirect_headers_;
1216 std::string redirect_data_;
1218 // Other actions we can take at MaybeInterceptRedirect time
1219 bool cancel_redirect_request_;
1221 // Whether to intercept final response, and if so the response to return.
1222 bool intercept_final_response_;
1223 std::string final_headers_;
1224 std::string final_data_;
1226 // Other actions we can take at MaybeInterceptResponse time
1227 bool cancel_final_request_;
1229 // If we did something or not
1230 bool did_intercept_main_;
1231 bool did_restart_main_;
1232 bool did_cancel_main_;
1233 bool did_cancel_then_restart_main_;
1234 bool did_simulate_error_main_;
1235 bool did_intercept_redirect_;
1236 bool did_cancel_redirect_;
1237 bool did_intercept_final_;
1238 bool did_cancel_final_;
1240 // Static getters for canned response header and data strings
1242 static std::string ok_data() {
1243 return URLRequestTestJob::test_data_1();
1246 static std::string ok_headers() {
1247 return URLRequestTestJob::test_headers();
1250 static std::string redirect_data() {
1251 return std::string();
1254 static std::string redirect_headers() {
1255 return URLRequestTestJob::test_redirect_headers();
1258 static std::string error_data() {
1259 return std::string("ohhh nooooo mr. bill!");
1262 static std::string error_headers() {
1263 return URLRequestTestJob::test_error_headers();
1267 TEST_F(URLRequestTest, Intercept) {
1268 TestInterceptor interceptor;
1270 // intercept the main request and respond with a simple response
1271 interceptor.intercept_main_request_ = true;
1272 interceptor.main_headers_ = TestInterceptor::ok_headers();
1273 interceptor.main_data_ = TestInterceptor::ok_data();
1275 TestDelegate d;
1276 URLRequest req(GURL("http://test_intercept/foo"),
1277 DEFAULT_PRIORITY,
1279 &default_context_);
1280 base::SupportsUserData::Data* user_data0 = new base::SupportsUserData::Data();
1281 base::SupportsUserData::Data* user_data1 = new base::SupportsUserData::Data();
1282 base::SupportsUserData::Data* user_data2 = new base::SupportsUserData::Data();
1283 req.SetUserData(NULL, user_data0);
1284 req.SetUserData(&user_data1, user_data1);
1285 req.SetUserData(&user_data2, user_data2);
1286 req.set_method("GET");
1287 req.Start();
1288 base::RunLoop().Run();
1290 // Make sure we can retrieve our specific user data
1291 EXPECT_EQ(user_data0, req.GetUserData(NULL));
1292 EXPECT_EQ(user_data1, req.GetUserData(&user_data1));
1293 EXPECT_EQ(user_data2, req.GetUserData(&user_data2));
1295 // Check the interceptor got called as expected
1296 EXPECT_TRUE(interceptor.did_intercept_main_);
1298 // Check we got one good response
1299 EXPECT_TRUE(req.status().is_success());
1300 EXPECT_EQ(200, req.response_headers()->response_code());
1301 EXPECT_EQ(TestInterceptor::ok_data(), d.data_received());
1302 EXPECT_EQ(1, d.response_started_count());
1303 EXPECT_EQ(0, d.received_redirect_count());
1306 TEST_F(URLRequestTest, InterceptRedirect) {
1307 TestInterceptor interceptor;
1309 // intercept the main request and respond with a redirect
1310 interceptor.intercept_main_request_ = true;
1311 interceptor.main_headers_ = TestInterceptor::redirect_headers();
1312 interceptor.main_data_ = TestInterceptor::redirect_data();
1314 // intercept that redirect and respond a final OK response
1315 interceptor.intercept_redirect_ = true;
1316 interceptor.redirect_headers_ = TestInterceptor::ok_headers();
1317 interceptor.redirect_data_ = TestInterceptor::ok_data();
1319 TestDelegate d;
1320 URLRequest req(GURL("http://test_intercept/foo"),
1321 DEFAULT_PRIORITY,
1323 &default_context_);
1324 req.set_method("GET");
1325 req.Start();
1326 base::RunLoop().Run();
1328 // Check the interceptor got called as expected
1329 EXPECT_TRUE(interceptor.did_intercept_main_);
1330 EXPECT_TRUE(interceptor.did_intercept_redirect_);
1332 // Check we got one good response
1333 EXPECT_TRUE(req.status().is_success());
1334 if (req.status().is_success()) {
1335 EXPECT_EQ(200, req.response_headers()->response_code());
1337 EXPECT_EQ(TestInterceptor::ok_data(), d.data_received());
1338 EXPECT_EQ(1, d.response_started_count());
1339 EXPECT_EQ(0, d.received_redirect_count());
1342 TEST_F(URLRequestTest, InterceptServerError) {
1343 TestInterceptor interceptor;
1345 // intercept the main request to generate a server error response
1346 interceptor.intercept_main_request_ = true;
1347 interceptor.main_headers_ = TestInterceptor::error_headers();
1348 interceptor.main_data_ = TestInterceptor::error_data();
1350 // intercept that error and respond with an OK response
1351 interceptor.intercept_final_response_ = true;
1352 interceptor.final_headers_ = TestInterceptor::ok_headers();
1353 interceptor.final_data_ = TestInterceptor::ok_data();
1355 TestDelegate d;
1356 URLRequest req(GURL("http://test_intercept/foo"),
1357 DEFAULT_PRIORITY,
1359 &default_context_);
1360 req.set_method("GET");
1361 req.Start();
1362 base::RunLoop().Run();
1364 // Check the interceptor got called as expected
1365 EXPECT_TRUE(interceptor.did_intercept_main_);
1366 EXPECT_TRUE(interceptor.did_intercept_final_);
1368 // Check we got one good response
1369 EXPECT_TRUE(req.status().is_success());
1370 EXPECT_EQ(200, req.response_headers()->response_code());
1371 EXPECT_EQ(TestInterceptor::ok_data(), d.data_received());
1372 EXPECT_EQ(1, d.response_started_count());
1373 EXPECT_EQ(0, d.received_redirect_count());
1376 TEST_F(URLRequestTest, InterceptNetworkError) {
1377 TestInterceptor interceptor;
1379 // intercept the main request to simulate a network error
1380 interceptor.simulate_main_network_error_ = true;
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();
1387 TestDelegate d;
1388 URLRequest req(GURL("http://test_intercept/foo"),
1389 DEFAULT_PRIORITY,
1391 &default_context_);
1392 req.set_method("GET");
1393 req.Start();
1394 base::RunLoop().Run();
1396 // Check the interceptor got called as expected
1397 EXPECT_TRUE(interceptor.did_simulate_error_main_);
1398 EXPECT_TRUE(interceptor.did_intercept_final_);
1400 // Check we received one good response
1401 EXPECT_TRUE(req.status().is_success());
1402 EXPECT_EQ(200, req.response_headers()->response_code());
1403 EXPECT_EQ(TestInterceptor::ok_data(), d.data_received());
1404 EXPECT_EQ(1, d.response_started_count());
1405 EXPECT_EQ(0, d.received_redirect_count());
1408 TEST_F(URLRequestTest, InterceptRestartRequired) {
1409 TestInterceptor interceptor;
1411 // restart the main request
1412 interceptor.restart_main_request_ = true;
1414 // then intercept the new main request and respond with an OK response
1415 interceptor.intercept_main_request_ = true;
1416 interceptor.main_headers_ = TestInterceptor::ok_headers();
1417 interceptor.main_data_ = TestInterceptor::ok_data();
1419 TestDelegate d;
1420 URLRequest req(GURL("http://test_intercept/foo"),
1421 DEFAULT_PRIORITY,
1423 &default_context_);
1424 req.set_method("GET");
1425 req.Start();
1426 base::RunLoop().Run();
1428 // Check the interceptor got called as expected
1429 EXPECT_TRUE(interceptor.did_restart_main_);
1430 EXPECT_TRUE(interceptor.did_intercept_main_);
1432 // Check we received one good response
1433 EXPECT_TRUE(req.status().is_success());
1434 if (req.status().is_success()) {
1435 EXPECT_EQ(200, req.response_headers()->response_code());
1437 EXPECT_EQ(TestInterceptor::ok_data(), d.data_received());
1438 EXPECT_EQ(1, d.response_started_count());
1439 EXPECT_EQ(0, d.received_redirect_count());
1442 TEST_F(URLRequestTest, InterceptRespectsCancelMain) {
1443 TestInterceptor interceptor;
1445 // intercept the main request and cancel from within the restarted job
1446 interceptor.cancel_main_request_ = true;
1448 // setup to intercept final response and override it with an OK response
1449 interceptor.intercept_final_response_ = true;
1450 interceptor.final_headers_ = TestInterceptor::ok_headers();
1451 interceptor.final_data_ = TestInterceptor::ok_data();
1453 TestDelegate d;
1454 URLRequest req(GURL("http://test_intercept/foo"),
1455 DEFAULT_PRIORITY,
1457 &default_context_);
1458 req.set_method("GET");
1459 req.Start();
1460 base::RunLoop().Run();
1462 // Check the interceptor got called as expected
1463 EXPECT_TRUE(interceptor.did_cancel_main_);
1464 EXPECT_FALSE(interceptor.did_intercept_final_);
1466 // Check we see a canceled request
1467 EXPECT_FALSE(req.status().is_success());
1468 EXPECT_EQ(URLRequestStatus::CANCELED, req.status().status());
1471 TEST_F(URLRequestTest, InterceptRespectsCancelRedirect) {
1472 TestInterceptor interceptor;
1474 // intercept the main request and respond with a redirect
1475 interceptor.intercept_main_request_ = true;
1476 interceptor.main_headers_ = TestInterceptor::redirect_headers();
1477 interceptor.main_data_ = TestInterceptor::redirect_data();
1479 // intercept the redirect and cancel from within that job
1480 interceptor.cancel_redirect_request_ = true;
1482 // setup to intercept final response and override it with an OK response
1483 interceptor.intercept_final_response_ = true;
1484 interceptor.final_headers_ = TestInterceptor::ok_headers();
1485 interceptor.final_data_ = TestInterceptor::ok_data();
1487 TestDelegate d;
1488 URLRequest req(GURL("http://test_intercept/foo"),
1489 DEFAULT_PRIORITY,
1491 &default_context_);
1492 req.set_method("GET");
1493 req.Start();
1494 base::RunLoop().Run();
1496 // Check the interceptor got called as expected
1497 EXPECT_TRUE(interceptor.did_intercept_main_);
1498 EXPECT_TRUE(interceptor.did_cancel_redirect_);
1499 EXPECT_FALSE(interceptor.did_intercept_final_);
1501 // Check we see a canceled request
1502 EXPECT_FALSE(req.status().is_success());
1503 EXPECT_EQ(URLRequestStatus::CANCELED, req.status().status());
1506 TEST_F(URLRequestTest, InterceptRespectsCancelFinal) {
1507 TestInterceptor interceptor;
1509 // intercept the main request to simulate a network error
1510 interceptor.simulate_main_network_error_ = true;
1512 // setup to intercept final response and cancel from within that job
1513 interceptor.cancel_final_request_ = true;
1515 TestDelegate d;
1516 URLRequest req(GURL("http://test_intercept/foo"),
1517 DEFAULT_PRIORITY,
1519 &default_context_);
1520 req.set_method("GET");
1521 req.Start();
1522 base::RunLoop().Run();
1524 // Check the interceptor got called as expected
1525 EXPECT_TRUE(interceptor.did_simulate_error_main_);
1526 EXPECT_TRUE(interceptor.did_cancel_final_);
1528 // Check we see a canceled request
1529 EXPECT_FALSE(req.status().is_success());
1530 EXPECT_EQ(URLRequestStatus::CANCELED, req.status().status());
1533 TEST_F(URLRequestTest, InterceptRespectsCancelInRestart) {
1534 TestInterceptor interceptor;
1536 // intercept the main request and cancel then restart from within that job
1537 interceptor.cancel_then_restart_main_request_ = true;
1539 // setup to intercept final response and override it with an OK response
1540 interceptor.intercept_final_response_ = true;
1541 interceptor.final_headers_ = TestInterceptor::ok_headers();
1542 interceptor.final_data_ = TestInterceptor::ok_data();
1544 TestDelegate d;
1545 URLRequest req(GURL("http://test_intercept/foo"),
1546 DEFAULT_PRIORITY,
1548 &default_context_);
1549 req.set_method("GET");
1550 req.Start();
1551 base::RunLoop().Run();
1553 // Check the interceptor got called as expected
1554 EXPECT_TRUE(interceptor.did_cancel_then_restart_main_);
1555 EXPECT_FALSE(interceptor.did_intercept_final_);
1557 // Check we see a canceled request
1558 EXPECT_FALSE(req.status().is_success());
1559 EXPECT_EQ(URLRequestStatus::CANCELED, req.status().status());
1562 LoadTimingInfo RunLoadTimingTest(const LoadTimingInfo& job_load_timing,
1563 URLRequestContext* context) {
1564 TestInterceptor interceptor;
1565 interceptor.intercept_main_request_ = true;
1566 interceptor.main_request_load_timing_info_ = job_load_timing;
1567 TestDelegate d;
1568 URLRequest req(
1569 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, context);
1570 req.Start();
1571 base::RunLoop().Run();
1573 LoadTimingInfo resulting_load_timing;
1574 req.GetLoadTimingInfo(&resulting_load_timing);
1576 // None of these should be modified by the URLRequest.
1577 EXPECT_EQ(job_load_timing.socket_reused, resulting_load_timing.socket_reused);
1578 EXPECT_EQ(job_load_timing.socket_log_id, resulting_load_timing.socket_log_id);
1579 EXPECT_EQ(job_load_timing.send_start, resulting_load_timing.send_start);
1580 EXPECT_EQ(job_load_timing.send_end, resulting_load_timing.send_end);
1581 EXPECT_EQ(job_load_timing.receive_headers_end,
1582 resulting_load_timing.receive_headers_end);
1584 return resulting_load_timing;
1587 // "Normal" LoadTimingInfo as returned by a job. Everything is in order, not
1588 // reused. |connect_time_flags| is used to indicate if there should be dns
1589 // or SSL times, and |used_proxy| is used for proxy times.
1590 LoadTimingInfo NormalLoadTimingInfo(base::TimeTicks now,
1591 int connect_time_flags,
1592 bool used_proxy) {
1593 LoadTimingInfo load_timing;
1594 load_timing.socket_log_id = 1;
1596 if (used_proxy) {
1597 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
1598 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
1601 LoadTimingInfo::ConnectTiming& connect_timing = load_timing.connect_timing;
1602 if (connect_time_flags & CONNECT_TIMING_HAS_DNS_TIMES) {
1603 connect_timing.dns_start = now + base::TimeDelta::FromDays(3);
1604 connect_timing.dns_end = now + base::TimeDelta::FromDays(4);
1606 connect_timing.connect_start = now + base::TimeDelta::FromDays(5);
1607 if (connect_time_flags & CONNECT_TIMING_HAS_SSL_TIMES) {
1608 connect_timing.ssl_start = now + base::TimeDelta::FromDays(6);
1609 connect_timing.ssl_end = now + base::TimeDelta::FromDays(7);
1611 connect_timing.connect_end = now + base::TimeDelta::FromDays(8);
1613 load_timing.send_start = now + base::TimeDelta::FromDays(9);
1614 load_timing.send_end = now + base::TimeDelta::FromDays(10);
1615 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
1616 return load_timing;
1619 // Same as above, but in the case of a reused socket.
1620 LoadTimingInfo NormalLoadTimingInfoReused(base::TimeTicks now,
1621 bool used_proxy) {
1622 LoadTimingInfo load_timing;
1623 load_timing.socket_log_id = 1;
1624 load_timing.socket_reused = true;
1626 if (used_proxy) {
1627 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
1628 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
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);
1634 return load_timing;
1637 // Basic test that the intercept + load timing tests work.
1638 TEST_F(URLRequestTest, InterceptLoadTiming) {
1639 base::TimeTicks now = base::TimeTicks::Now();
1640 LoadTimingInfo job_load_timing =
1641 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, false);
1643 LoadTimingInfo load_timing_result =
1644 RunLoadTimingTest(job_load_timing, &default_context_);
1646 // Nothing should have been changed by the URLRequest.
1647 EXPECT_EQ(job_load_timing.proxy_resolve_start,
1648 load_timing_result.proxy_resolve_start);
1649 EXPECT_EQ(job_load_timing.proxy_resolve_end,
1650 load_timing_result.proxy_resolve_end);
1651 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
1652 load_timing_result.connect_timing.dns_start);
1653 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
1654 load_timing_result.connect_timing.dns_end);
1655 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
1656 load_timing_result.connect_timing.connect_start);
1657 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
1658 load_timing_result.connect_timing.connect_end);
1659 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
1660 load_timing_result.connect_timing.ssl_start);
1661 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
1662 load_timing_result.connect_timing.ssl_end);
1664 // Redundant sanity check.
1665 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_DNS_TIMES);
1668 // Another basic test, with proxy and SSL times, but no DNS times.
1669 TEST_F(URLRequestTest, InterceptLoadTimingProxy) {
1670 base::TimeTicks now = base::TimeTicks::Now();
1671 LoadTimingInfo job_load_timing =
1672 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, true);
1674 LoadTimingInfo load_timing_result =
1675 RunLoadTimingTest(job_load_timing, &default_context_);
1677 // Nothing should have been changed by the URLRequest.
1678 EXPECT_EQ(job_load_timing.proxy_resolve_start,
1679 load_timing_result.proxy_resolve_start);
1680 EXPECT_EQ(job_load_timing.proxy_resolve_end,
1681 load_timing_result.proxy_resolve_end);
1682 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
1683 load_timing_result.connect_timing.dns_start);
1684 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
1685 load_timing_result.connect_timing.dns_end);
1686 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
1687 load_timing_result.connect_timing.connect_start);
1688 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
1689 load_timing_result.connect_timing.connect_end);
1690 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
1691 load_timing_result.connect_timing.ssl_start);
1692 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
1693 load_timing_result.connect_timing.ssl_end);
1695 // Redundant sanity check.
1696 TestLoadTimingNotReusedWithProxy(load_timing_result,
1697 CONNECT_TIMING_HAS_SSL_TIMES);
1700 // Make sure that URLRequest correctly adjusts proxy times when they're before
1701 // |request_start|, due to already having a connected socket. This happens in
1702 // the case of reusing a SPDY session or HTTP pipeline. The connected socket is
1703 // not considered reused in this test (May be a preconnect).
1705 // To mix things up from the test above, assumes DNS times but no SSL times.
1706 TEST_F(URLRequestTest, InterceptLoadTimingEarlyProxyResolution) {
1707 base::TimeTicks now = base::TimeTicks::Now();
1708 LoadTimingInfo job_load_timing =
1709 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, true);
1710 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(6);
1711 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(5);
1712 job_load_timing.connect_timing.dns_start = now - base::TimeDelta::FromDays(4);
1713 job_load_timing.connect_timing.dns_end = now - base::TimeDelta::FromDays(3);
1714 job_load_timing.connect_timing.connect_start =
1715 now - base::TimeDelta::FromDays(2);
1716 job_load_timing.connect_timing.connect_end =
1717 now - base::TimeDelta::FromDays(1);
1719 LoadTimingInfo load_timing_result =
1720 RunLoadTimingTest(job_load_timing, &default_context_);
1722 // Proxy times, connect times, and DNS times should all be replaced with
1723 // request_start.
1724 EXPECT_EQ(load_timing_result.request_start,
1725 load_timing_result.proxy_resolve_start);
1726 EXPECT_EQ(load_timing_result.request_start,
1727 load_timing_result.proxy_resolve_end);
1728 EXPECT_EQ(load_timing_result.request_start,
1729 load_timing_result.connect_timing.dns_start);
1730 EXPECT_EQ(load_timing_result.request_start,
1731 load_timing_result.connect_timing.dns_end);
1732 EXPECT_EQ(load_timing_result.request_start,
1733 load_timing_result.connect_timing.connect_start);
1734 EXPECT_EQ(load_timing_result.request_start,
1735 load_timing_result.connect_timing.connect_end);
1737 // Other times should have been left null.
1738 TestLoadTimingNotReusedWithProxy(load_timing_result,
1739 CONNECT_TIMING_HAS_DNS_TIMES);
1742 // Same as above, but in the reused case.
1743 TEST_F(URLRequestTest, InterceptLoadTimingEarlyProxyResolutionReused) {
1744 base::TimeTicks now = base::TimeTicks::Now();
1745 LoadTimingInfo job_load_timing = NormalLoadTimingInfoReused(now, true);
1746 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(4);
1747 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(3);
1749 LoadTimingInfo load_timing_result =
1750 RunLoadTimingTest(job_load_timing, &default_context_);
1752 // Proxy times and connect times should all be replaced with request_start.
1753 EXPECT_EQ(load_timing_result.request_start,
1754 load_timing_result.proxy_resolve_start);
1755 EXPECT_EQ(load_timing_result.request_start,
1756 load_timing_result.proxy_resolve_end);
1758 // Other times should have been left null.
1759 TestLoadTimingReusedWithProxy(load_timing_result);
1762 // Make sure that URLRequest correctly adjusts connect times when they're before
1763 // |request_start|, due to reusing a connected socket. The connected socket is
1764 // not considered reused in this test (May be a preconnect).
1766 // To mix things up, the request has SSL times, but no DNS times.
1767 TEST_F(URLRequestTest, InterceptLoadTimingEarlyConnect) {
1768 base::TimeTicks now = base::TimeTicks::Now();
1769 LoadTimingInfo job_load_timing =
1770 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, false);
1771 job_load_timing.connect_timing.connect_start =
1772 now - base::TimeDelta::FromDays(1);
1773 job_load_timing.connect_timing.ssl_start = now - base::TimeDelta::FromDays(2);
1774 job_load_timing.connect_timing.ssl_end = now - base::TimeDelta::FromDays(3);
1775 job_load_timing.connect_timing.connect_end =
1776 now - base::TimeDelta::FromDays(4);
1778 LoadTimingInfo load_timing_result =
1779 RunLoadTimingTest(job_load_timing, &default_context_);
1781 // Connect times, and SSL times should be replaced with request_start.
1782 EXPECT_EQ(load_timing_result.request_start,
1783 load_timing_result.connect_timing.connect_start);
1784 EXPECT_EQ(load_timing_result.request_start,
1785 load_timing_result.connect_timing.ssl_start);
1786 EXPECT_EQ(load_timing_result.request_start,
1787 load_timing_result.connect_timing.ssl_end);
1788 EXPECT_EQ(load_timing_result.request_start,
1789 load_timing_result.connect_timing.connect_end);
1791 // Other times should have been left null.
1792 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_SSL_TIMES);
1795 // Make sure that URLRequest correctly adjusts connect times when they're before
1796 // |request_start|, due to reusing a connected socket in the case that there
1797 // are also proxy times. The connected socket is not considered reused in this
1798 // test (May be a preconnect).
1800 // In this test, there are no SSL or DNS times.
1801 TEST_F(URLRequestTest, InterceptLoadTimingEarlyConnectWithProxy) {
1802 base::TimeTicks now = base::TimeTicks::Now();
1803 LoadTimingInfo job_load_timing =
1804 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY, true);
1805 job_load_timing.connect_timing.connect_start =
1806 now - base::TimeDelta::FromDays(1);
1807 job_load_timing.connect_timing.connect_end =
1808 now - base::TimeDelta::FromDays(2);
1810 LoadTimingInfo load_timing_result =
1811 RunLoadTimingTest(job_load_timing, &default_context_);
1813 // Connect times should be replaced with proxy_resolve_end.
1814 EXPECT_EQ(load_timing_result.proxy_resolve_end,
1815 load_timing_result.connect_timing.connect_start);
1816 EXPECT_EQ(load_timing_result.proxy_resolve_end,
1817 load_timing_result.connect_timing.connect_end);
1819 // Other times should have been left null.
1820 TestLoadTimingNotReusedWithProxy(load_timing_result,
1821 CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
1824 // Check that two different URL requests have different identifiers.
1825 TEST_F(URLRequestTest, Identifiers) {
1826 TestDelegate d;
1827 TestURLRequestContext context;
1828 TestURLRequest req(
1829 GURL("http://example.com"), DEFAULT_PRIORITY, &d, &context);
1830 TestURLRequest other_req(
1831 GURL("http://example.com"), DEFAULT_PRIORITY, &d, &context);
1833 ASSERT_NE(req.identifier(), other_req.identifier());
1836 // Check that a failure to connect to the proxy is reported to the network
1837 // delegate.
1838 TEST_F(URLRequestTest, NetworkDelegateProxyError) {
1839 MockHostResolver host_resolver;
1840 host_resolver.rules()->AddSimulatedFailure("*");
1842 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
1843 TestURLRequestContextWithProxy context("myproxy:70", &network_delegate);
1845 TestDelegate d;
1846 URLRequest req(GURL("http://example.com"), DEFAULT_PRIORITY, &d, &context);
1847 req.set_method("GET");
1849 req.Start();
1850 base::RunLoop().Run();
1852 // Check we see a failed request.
1853 EXPECT_FALSE(req.status().is_success());
1854 EXPECT_EQ(URLRequestStatus::FAILED, req.status().status());
1855 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, req.status().error());
1857 EXPECT_EQ(1, network_delegate.error_count());
1858 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, network_delegate.last_error());
1859 EXPECT_EQ(1, network_delegate.completed_requests());
1862 // Make sure that net::NetworkDelegate::NotifyCompleted is called if
1863 // content is empty.
1864 TEST_F(URLRequestTest, RequestCompletionForEmptyResponse) {
1865 TestDelegate d;
1866 URLRequest req(GURL("data:,"), DEFAULT_PRIORITY, &d, &default_context_);
1867 req.Start();
1868 base::RunLoop().Run();
1869 EXPECT_EQ("", d.data_received());
1870 EXPECT_EQ(1, default_network_delegate_.completed_requests());
1873 // Make sure that SetPriority actually sets the URLRequest's priority
1874 // correctly, both before and after start.
1875 TEST_F(URLRequestTest, SetPriorityBasic) {
1876 TestDelegate d;
1877 URLRequest req(GURL("http://test_intercept/foo"),
1878 DEFAULT_PRIORITY,
1880 &default_context_);
1881 EXPECT_EQ(DEFAULT_PRIORITY, req.priority());
1883 req.SetPriority(LOW);
1884 EXPECT_EQ(LOW, req.priority());
1886 req.Start();
1887 EXPECT_EQ(LOW, req.priority());
1889 req.SetPriority(MEDIUM);
1890 EXPECT_EQ(MEDIUM, req.priority());
1893 // Make sure that URLRequest calls SetPriority on a job before calling
1894 // Start on it.
1895 TEST_F(URLRequestTest, SetJobPriorityBeforeJobStart) {
1896 TestDelegate d;
1897 URLRequest req(GURL("http://test_intercept/foo"),
1898 DEFAULT_PRIORITY,
1900 &default_context_);
1901 EXPECT_EQ(DEFAULT_PRIORITY, req.priority());
1903 scoped_refptr<URLRequestTestJob> job =
1904 new URLRequestTestJob(&req, &default_network_delegate_);
1905 AddTestInterceptor()->set_main_intercept_job(job.get());
1906 EXPECT_EQ(DEFAULT_PRIORITY, job->priority());
1908 req.SetPriority(LOW);
1910 req.Start();
1911 EXPECT_EQ(LOW, job->priority());
1914 // Make sure that URLRequest passes on its priority updates to its
1915 // job.
1916 TEST_F(URLRequestTest, SetJobPriority) {
1917 TestDelegate d;
1918 URLRequest req(GURL("http://test_intercept/foo"),
1919 DEFAULT_PRIORITY,
1921 &default_context_);
1923 scoped_refptr<URLRequestTestJob> job =
1924 new URLRequestTestJob(&req, &default_network_delegate_);
1925 AddTestInterceptor()->set_main_intercept_job(job.get());
1927 req.SetPriority(LOW);
1928 req.Start();
1929 EXPECT_EQ(LOW, job->priority());
1931 req.SetPriority(MEDIUM);
1932 EXPECT_EQ(MEDIUM, req.priority());
1933 EXPECT_EQ(MEDIUM, job->priority());
1936 // Setting the IGNORE_LIMITS load flag should be okay if the priority
1937 // is MAXIMUM_PRIORITY.
1938 TEST_F(URLRequestTest, PriorityIgnoreLimits) {
1939 TestDelegate d;
1940 URLRequest req(GURL("http://test_intercept/foo"),
1941 MAXIMUM_PRIORITY,
1943 &default_context_);
1944 EXPECT_EQ(MAXIMUM_PRIORITY, req.priority());
1946 scoped_refptr<URLRequestTestJob> job =
1947 new URLRequestTestJob(&req, &default_network_delegate_);
1948 AddTestInterceptor()->set_main_intercept_job(job.get());
1950 req.SetLoadFlags(LOAD_IGNORE_LIMITS);
1951 EXPECT_EQ(MAXIMUM_PRIORITY, req.priority());
1953 req.SetPriority(MAXIMUM_PRIORITY);
1954 EXPECT_EQ(MAXIMUM_PRIORITY, req.priority());
1956 req.Start();
1957 EXPECT_EQ(MAXIMUM_PRIORITY, req.priority());
1958 EXPECT_EQ(MAXIMUM_PRIORITY, job->priority());
1961 // TODO(droger): Support SpawnedTestServer on iOS (see http://crbug.com/148666).
1962 #if !defined(OS_IOS)
1963 // A subclass of SpawnedTestServer that uses a statically-configured hostname.
1964 // This is to work around mysterious failures in chrome_frame_net_tests. See:
1965 // http://crbug.com/114369
1966 // TODO(erikwright): remove or update as needed; see http://crbug.com/334634.
1967 class LocalHttpTestServer : public SpawnedTestServer {
1968 public:
1969 explicit LocalHttpTestServer(const base::FilePath& document_root)
1970 : SpawnedTestServer(SpawnedTestServer::TYPE_HTTP,
1971 ScopedCustomUrlRequestTestHttpHost::value(),
1972 document_root) {}
1973 LocalHttpTestServer()
1974 : SpawnedTestServer(SpawnedTestServer::TYPE_HTTP,
1975 ScopedCustomUrlRequestTestHttpHost::value(),
1976 base::FilePath()) {}
1979 TEST_F(URLRequestTest, DelayedCookieCallback) {
1980 LocalHttpTestServer test_server;
1981 ASSERT_TRUE(test_server.Start());
1983 TestURLRequestContext context;
1984 scoped_refptr<DelayedCookieMonster> delayed_cm =
1985 new DelayedCookieMonster();
1986 scoped_refptr<CookieStore> cookie_store = delayed_cm;
1987 context.set_cookie_store(delayed_cm.get());
1989 // Set up a cookie.
1991 TestNetworkDelegate network_delegate;
1992 context.set_network_delegate(&network_delegate);
1993 TestDelegate d;
1994 URLRequest req(test_server.GetURL("set-cookie?CookieToNotSend=1"),
1995 DEFAULT_PRIORITY,
1997 &context);
1998 req.Start();
1999 base::RunLoop().Run();
2000 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2001 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2002 EXPECT_EQ(1, network_delegate.set_cookie_count());
2005 // Verify that the cookie is set.
2007 TestNetworkDelegate network_delegate;
2008 context.set_network_delegate(&network_delegate);
2009 TestDelegate d;
2010 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2011 DEFAULT_PRIORITY,
2013 &context);
2014 req.Start();
2015 base::RunLoop().Run();
2017 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2018 != std::string::npos);
2019 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2020 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2024 TEST_F(URLRequestTest, DoNotSendCookies) {
2025 LocalHttpTestServer test_server;
2026 ASSERT_TRUE(test_server.Start());
2028 // Set up a cookie.
2030 TestNetworkDelegate network_delegate;
2031 default_context_.set_network_delegate(&network_delegate);
2032 TestDelegate d;
2033 URLRequest req(test_server.GetURL("set-cookie?CookieToNotSend=1"),
2034 DEFAULT_PRIORITY,
2036 &default_context_);
2037 req.Start();
2038 base::RunLoop().Run();
2039 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2040 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2043 // Verify that the cookie is set.
2045 TestNetworkDelegate network_delegate;
2046 default_context_.set_network_delegate(&network_delegate);
2047 TestDelegate d;
2048 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2049 DEFAULT_PRIORITY,
2051 &default_context_);
2052 req.Start();
2053 base::RunLoop().Run();
2055 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2056 != std::string::npos);
2057 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2058 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2061 // Verify that the cookie isn't sent when LOAD_DO_NOT_SEND_COOKIES is set.
2063 TestNetworkDelegate network_delegate;
2064 default_context_.set_network_delegate(&network_delegate);
2065 TestDelegate d;
2066 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2067 DEFAULT_PRIORITY,
2069 &default_context_);
2070 req.SetLoadFlags(LOAD_DO_NOT_SEND_COOKIES);
2071 req.Start();
2072 base::RunLoop().Run();
2074 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2075 == std::string::npos);
2077 // LOAD_DO_NOT_SEND_COOKIES does not trigger OnGetCookies.
2078 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2079 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2083 TEST_F(URLRequestTest, DoNotSaveCookies) {
2084 LocalHttpTestServer test_server;
2085 ASSERT_TRUE(test_server.Start());
2087 // Set up a cookie.
2089 TestNetworkDelegate network_delegate;
2090 default_context_.set_network_delegate(&network_delegate);
2091 TestDelegate d;
2092 URLRequest req(test_server.GetURL("set-cookie?CookieToNotUpdate=2"),
2093 DEFAULT_PRIORITY,
2095 &default_context_);
2096 req.Start();
2097 base::RunLoop().Run();
2099 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2100 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2101 EXPECT_EQ(1, network_delegate.set_cookie_count());
2104 // Try to set-up another cookie and update the previous cookie.
2106 TestNetworkDelegate network_delegate;
2107 default_context_.set_network_delegate(&network_delegate);
2108 TestDelegate d;
2109 URLRequest req(
2110 test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
2111 DEFAULT_PRIORITY,
2113 &default_context_);
2114 req.SetLoadFlags(LOAD_DO_NOT_SAVE_COOKIES);
2115 req.Start();
2117 base::RunLoop().Run();
2119 // LOAD_DO_NOT_SAVE_COOKIES does not trigger OnSetCookie.
2120 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2121 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2122 EXPECT_EQ(0, network_delegate.set_cookie_count());
2125 // Verify the cookies weren't saved or updated.
2127 TestNetworkDelegate network_delegate;
2128 default_context_.set_network_delegate(&network_delegate);
2129 TestDelegate d;
2130 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2131 DEFAULT_PRIORITY,
2133 &default_context_);
2134 req.Start();
2135 base::RunLoop().Run();
2137 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2138 == std::string::npos);
2139 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2140 != std::string::npos);
2142 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2143 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2144 EXPECT_EQ(0, network_delegate.set_cookie_count());
2148 TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy) {
2149 LocalHttpTestServer test_server;
2150 ASSERT_TRUE(test_server.Start());
2152 // Set up a cookie.
2154 TestNetworkDelegate network_delegate;
2155 default_context_.set_network_delegate(&network_delegate);
2156 TestDelegate d;
2157 URLRequest req(test_server.GetURL("set-cookie?CookieToNotSend=1"),
2158 DEFAULT_PRIORITY,
2160 &default_context_);
2161 req.Start();
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);
2172 TestDelegate d;
2173 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2174 DEFAULT_PRIORITY,
2176 &default_context_);
2177 req.Start();
2178 base::RunLoop().Run();
2180 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2181 != std::string::npos);
2183 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2184 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2187 // Verify that the cookie isn't sent.
2189 TestNetworkDelegate network_delegate;
2190 default_context_.set_network_delegate(&network_delegate);
2191 TestDelegate d;
2192 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
2193 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2194 DEFAULT_PRIORITY,
2196 &default_context_);
2197 req.Start();
2198 base::RunLoop().Run();
2200 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2201 == std::string::npos);
2203 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
2204 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2208 TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy) {
2209 LocalHttpTestServer test_server;
2210 ASSERT_TRUE(test_server.Start());
2212 // Set up a cookie.
2214 TestNetworkDelegate network_delegate;
2215 default_context_.set_network_delegate(&network_delegate);
2216 TestDelegate d;
2217 URLRequest req(test_server.GetURL("set-cookie?CookieToNotUpdate=2"),
2218 DEFAULT_PRIORITY,
2220 &default_context_);
2221 req.Start();
2222 base::RunLoop().Run();
2224 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2225 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2228 // Try to set-up another cookie and update the previous cookie.
2230 TestNetworkDelegate network_delegate;
2231 default_context_.set_network_delegate(&network_delegate);
2232 TestDelegate d;
2233 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
2234 URLRequest req(
2235 test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
2236 DEFAULT_PRIORITY,
2238 &default_context_);
2239 req.Start();
2241 base::RunLoop().Run();
2243 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2244 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2247 // Verify the cookies weren't saved or updated.
2249 TestNetworkDelegate network_delegate;
2250 default_context_.set_network_delegate(&network_delegate);
2251 TestDelegate d;
2252 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2253 DEFAULT_PRIORITY,
2255 &default_context_);
2256 req.Start();
2257 base::RunLoop().Run();
2259 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2260 == std::string::npos);
2261 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2262 != std::string::npos);
2264 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2265 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2269 TEST_F(URLRequestTest, DoNotSaveEmptyCookies) {
2270 LocalHttpTestServer test_server;
2271 ASSERT_TRUE(test_server.Start());
2273 // Set up an empty cookie.
2275 TestNetworkDelegate network_delegate;
2276 default_context_.set_network_delegate(&network_delegate);
2277 TestDelegate d;
2278 URLRequest req(test_server.GetURL("set-cookie"),
2279 DEFAULT_PRIORITY,
2281 &default_context_);
2282 req.Start();
2283 base::RunLoop().Run();
2285 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2286 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2287 EXPECT_EQ(0, network_delegate.set_cookie_count());
2291 TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy_Async) {
2292 LocalHttpTestServer test_server;
2293 ASSERT_TRUE(test_server.Start());
2295 // Set up a cookie.
2297 TestNetworkDelegate network_delegate;
2298 default_context_.set_network_delegate(&network_delegate);
2299 TestDelegate d;
2300 URLRequest req(test_server.GetURL("set-cookie?CookieToNotSend=1"),
2301 DEFAULT_PRIORITY,
2303 &default_context_);
2304 req.Start();
2305 base::RunLoop().Run();
2307 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2308 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2311 // Verify that the cookie is set.
2313 TestNetworkDelegate network_delegate;
2314 default_context_.set_network_delegate(&network_delegate);
2315 TestDelegate d;
2316 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2317 DEFAULT_PRIORITY,
2319 &default_context_);
2320 req.Start();
2321 base::RunLoop().Run();
2323 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2324 != std::string::npos);
2326 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2327 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2330 // Verify that the cookie isn't sent.
2332 TestNetworkDelegate network_delegate;
2333 default_context_.set_network_delegate(&network_delegate);
2334 TestDelegate d;
2335 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
2336 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2337 DEFAULT_PRIORITY,
2339 &default_context_);
2340 req.Start();
2341 base::RunLoop().Run();
2343 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2344 == std::string::npos);
2346 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
2347 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2351 TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy_Async) {
2352 LocalHttpTestServer test_server;
2353 ASSERT_TRUE(test_server.Start());
2355 // Set up a cookie.
2357 TestNetworkDelegate network_delegate;
2358 default_context_.set_network_delegate(&network_delegate);
2359 TestDelegate d;
2360 URLRequest req(test_server.GetURL("set-cookie?CookieToNotUpdate=2"),
2361 DEFAULT_PRIORITY,
2363 &default_context_);
2364 req.Start();
2365 base::RunLoop().Run();
2367 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2368 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2371 // Try to set-up another cookie and update the previous cookie.
2373 TestNetworkDelegate network_delegate;
2374 default_context_.set_network_delegate(&network_delegate);
2375 TestDelegate d;
2376 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
2377 URLRequest req(
2378 test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
2379 DEFAULT_PRIORITY,
2381 &default_context_);
2382 req.Start();
2384 base::RunLoop().Run();
2386 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2387 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2390 // Verify the cookies weren't saved or updated.
2392 TestNetworkDelegate network_delegate;
2393 default_context_.set_network_delegate(&network_delegate);
2394 TestDelegate d;
2395 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2396 DEFAULT_PRIORITY,
2398 &default_context_);
2399 req.Start();
2400 base::RunLoop().Run();
2402 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2403 == std::string::npos);
2404 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2405 != std::string::npos);
2407 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2408 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2412 // FixedDateNetworkDelegate swaps out the server's HTTP Date response header
2413 // value for the |fixed_date| argument given to the constructor.
2414 class FixedDateNetworkDelegate : public TestNetworkDelegate {
2415 public:
2416 explicit FixedDateNetworkDelegate(const std::string& fixed_date)
2417 : fixed_date_(fixed_date) {}
2418 virtual ~FixedDateNetworkDelegate() {}
2420 // net::NetworkDelegate implementation
2421 virtual int OnHeadersReceived(
2422 net::URLRequest* request,
2423 const net::CompletionCallback& callback,
2424 const net::HttpResponseHeaders* original_response_headers,
2425 scoped_refptr<net::HttpResponseHeaders>* override_response_headers,
2426 GURL* allowed_unsafe_redirect_url) OVERRIDE;
2428 private:
2429 std::string fixed_date_;
2431 DISALLOW_COPY_AND_ASSIGN(FixedDateNetworkDelegate);
2434 int FixedDateNetworkDelegate::OnHeadersReceived(
2435 net::URLRequest* request,
2436 const net::CompletionCallback& callback,
2437 const net::HttpResponseHeaders* original_response_headers,
2438 scoped_refptr<net::HttpResponseHeaders>* override_response_headers,
2439 GURL* allowed_unsafe_redirect_url) {
2440 net::HttpResponseHeaders* new_response_headers =
2441 new net::HttpResponseHeaders(original_response_headers->raw_headers());
2443 new_response_headers->RemoveHeader("Date");
2444 new_response_headers->AddHeader("Date: " + fixed_date_);
2446 *override_response_headers = new_response_headers;
2447 return TestNetworkDelegate::OnHeadersReceived(request,
2448 callback,
2449 original_response_headers,
2450 override_response_headers,
2451 allowed_unsafe_redirect_url);
2454 // Test that cookie expiration times are adjusted for server/client clock
2455 // skew and that we handle incorrect timezone specifier "UTC" in HTTP Date
2456 // headers by defaulting to GMT. (crbug.com/135131)
2457 TEST_F(URLRequestTest, AcceptClockSkewCookieWithWrongDateTimezone) {
2458 LocalHttpTestServer test_server;
2459 ASSERT_TRUE(test_server.Start());
2461 // Set up an expired cookie.
2463 TestNetworkDelegate network_delegate;
2464 default_context_.set_network_delegate(&network_delegate);
2465 TestDelegate d;
2466 URLRequest req(
2467 test_server.GetURL(
2468 "set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
2469 DEFAULT_PRIORITY,
2471 &default_context_);
2472 req.Start();
2473 base::RunLoop().Run();
2475 // Verify that the cookie is not set.
2477 TestNetworkDelegate network_delegate;
2478 default_context_.set_network_delegate(&network_delegate);
2479 TestDelegate d;
2480 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2481 DEFAULT_PRIORITY,
2483 &default_context_);
2484 req.Start();
2485 base::RunLoop().Run();
2487 EXPECT_TRUE(d.data_received().find("StillGood=1") == std::string::npos);
2489 // Set up a cookie with clock skew and "UTC" HTTP Date timezone specifier.
2491 FixedDateNetworkDelegate network_delegate("18-Apr-1977 22:49:13 UTC");
2492 default_context_.set_network_delegate(&network_delegate);
2493 TestDelegate d;
2494 URLRequest req(
2495 test_server.GetURL(
2496 "set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
2497 DEFAULT_PRIORITY,
2499 &default_context_);
2500 req.Start();
2501 base::RunLoop().Run();
2503 // Verify that the cookie is set.
2505 TestNetworkDelegate network_delegate;
2506 default_context_.set_network_delegate(&network_delegate);
2507 TestDelegate d;
2508 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2509 DEFAULT_PRIORITY,
2511 &default_context_);
2512 req.Start();
2513 base::RunLoop().Run();
2515 EXPECT_TRUE(d.data_received().find("StillGood=1") != std::string::npos);
2520 // Check that it is impossible to change the referrer in the extra headers of
2521 // an URLRequest.
2522 TEST_F(URLRequestTest, DoNotOverrideReferrer) {
2523 LocalHttpTestServer test_server;
2524 ASSERT_TRUE(test_server.Start());
2526 // If extra headers contain referer and the request contains a referer,
2527 // only the latter shall be respected.
2529 TestDelegate d;
2530 URLRequest req(test_server.GetURL("echoheader?Referer"),
2531 DEFAULT_PRIORITY,
2533 &default_context_);
2534 req.SetReferrer("http://foo.com/");
2536 HttpRequestHeaders headers;
2537 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
2538 req.SetExtraRequestHeaders(headers);
2540 req.Start();
2541 base::RunLoop().Run();
2543 EXPECT_EQ("http://foo.com/", d.data_received());
2546 // If extra headers contain a referer but the request does not, no referer
2547 // shall be sent in the header.
2549 TestDelegate d;
2550 URLRequest req(test_server.GetURL("echoheader?Referer"),
2551 DEFAULT_PRIORITY,
2553 &default_context_);
2555 HttpRequestHeaders headers;
2556 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
2557 req.SetExtraRequestHeaders(headers);
2558 req.SetLoadFlags(LOAD_VALIDATE_CACHE);
2560 req.Start();
2561 base::RunLoop().Run();
2563 EXPECT_EQ("None", d.data_received());
2567 class URLRequestTestHTTP : public URLRequestTest {
2568 public:
2569 URLRequestTestHTTP()
2570 : test_server_(base::FilePath(FILE_PATH_LITERAL(
2571 "net/data/url_request_unittest"))) {
2574 protected:
2575 // Requests |redirect_url|, which must return a HTTP 3xx redirect.
2576 // |request_method| is the method to use for the initial request.
2577 // |redirect_method| is the method that is expected to be used for the second
2578 // request, after redirection.
2579 // If |include_data| is true, data is uploaded with the request. The
2580 // response body is expected to match it exactly, if and only if
2581 // |request_method| == |redirect_method|.
2582 void HTTPRedirectMethodTest(const GURL& redirect_url,
2583 const std::string& request_method,
2584 const std::string& redirect_method,
2585 bool include_data) {
2586 static const char kData[] = "hello world";
2587 TestDelegate d;
2588 URLRequest req(redirect_url, DEFAULT_PRIORITY, &d, &default_context_);
2589 req.set_method(request_method);
2590 if (include_data) {
2591 req.set_upload(make_scoped_ptr(CreateSimpleUploadData(kData)));
2592 HttpRequestHeaders headers;
2593 headers.SetHeader(HttpRequestHeaders::kContentLength,
2594 base::UintToString(arraysize(kData) - 1));
2595 req.SetExtraRequestHeaders(headers);
2597 req.Start();
2598 base::RunLoop().Run();
2599 EXPECT_EQ(redirect_method, req.method());
2600 EXPECT_EQ(URLRequestStatus::SUCCESS, req.status().status());
2601 EXPECT_EQ(OK, req.status().error());
2602 if (include_data) {
2603 if (request_method == redirect_method) {
2604 EXPECT_EQ(kData, d.data_received());
2605 } else {
2606 EXPECT_NE(kData, d.data_received());
2609 if (HasFailure())
2610 LOG(WARNING) << "Request method was: " << request_method;
2613 void HTTPUploadDataOperationTest(const std::string& method) {
2614 const int kMsgSize = 20000; // multiple of 10
2615 const int kIterations = 50;
2616 char* uploadBytes = new char[kMsgSize+1];
2617 char* ptr = uploadBytes;
2618 char marker = 'a';
2619 for (int idx = 0; idx < kMsgSize/10; idx++) {
2620 memcpy(ptr, "----------", 10);
2621 ptr += 10;
2622 if (idx % 100 == 0) {
2623 ptr--;
2624 *ptr++ = marker;
2625 if (++marker > 'z')
2626 marker = 'a';
2629 uploadBytes[kMsgSize] = '\0';
2631 for (int i = 0; i < kIterations; ++i) {
2632 TestDelegate d;
2633 URLRequest r(
2634 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, &default_context_);
2635 r.set_method(method.c_str());
2637 r.set_upload(make_scoped_ptr(CreateSimpleUploadData(uploadBytes)));
2639 r.Start();
2640 EXPECT_TRUE(r.is_pending());
2642 base::RunLoop().Run();
2644 ASSERT_EQ(1, d.response_started_count())
2645 << "request failed: " << r.status().status()
2646 << ", os error: " << r.status().error();
2648 EXPECT_FALSE(d.received_data_before_response());
2649 EXPECT_EQ(uploadBytes, d.data_received());
2651 delete[] uploadBytes;
2654 void AddChunksToUpload(URLRequest* r) {
2655 r->AppendChunkToUpload("a", 1, false);
2656 r->AppendChunkToUpload("bcd", 3, false);
2657 r->AppendChunkToUpload("this is a longer chunk than before.", 35, false);
2658 r->AppendChunkToUpload("\r\n\r\n", 4, false);
2659 r->AppendChunkToUpload("0", 1, false);
2660 r->AppendChunkToUpload("2323", 4, true);
2663 void VerifyReceivedDataMatchesChunks(URLRequest* r, TestDelegate* d) {
2664 // This should match the chunks sent by AddChunksToUpload().
2665 const std::string expected_data =
2666 "abcdthis is a longer chunk than before.\r\n\r\n02323";
2668 ASSERT_EQ(1, d->response_started_count())
2669 << "request failed: " << r->status().status()
2670 << ", os error: " << r->status().error();
2672 EXPECT_FALSE(d->received_data_before_response());
2674 EXPECT_EQ(expected_data.size(), static_cast<size_t>(d->bytes_received()));
2675 EXPECT_EQ(expected_data, d->data_received());
2678 bool DoManyCookiesRequest(int num_cookies) {
2679 TestDelegate d;
2680 URLRequest r(test_server_.GetURL("set-many-cookies?" +
2681 base::IntToString(num_cookies)),
2682 DEFAULT_PRIORITY,
2684 &default_context_);
2686 r.Start();
2687 EXPECT_TRUE(r.is_pending());
2689 base::RunLoop().Run();
2691 bool is_success = r.status().is_success();
2693 if (!is_success) {
2694 EXPECT_TRUE(r.status().error() == ERR_RESPONSE_HEADERS_TOO_BIG);
2695 // The test server appears to be unable to handle subsequent requests
2696 // after this error is triggered. Force it to restart.
2697 EXPECT_TRUE(test_server_.Stop());
2698 EXPECT_TRUE(test_server_.Start());
2701 return is_success;
2704 LocalHttpTestServer test_server_;
2707 // In this unit test, we're using the HTTPTestServer as a proxy server and
2708 // issuing a CONNECT request with the magic host name "www.redirect.com".
2709 // The HTTPTestServer will return a 302 response, which we should not
2710 // follow.
2711 TEST_F(URLRequestTestHTTP, ProxyTunnelRedirectTest) {
2712 ASSERT_TRUE(test_server_.Start());
2714 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
2715 TestURLRequestContextWithProxy context(
2716 test_server_.host_port_pair().ToString(), &network_delegate);
2718 TestDelegate d;
2720 URLRequest r(
2721 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d, &context);
2722 r.Start();
2723 EXPECT_TRUE(r.is_pending());
2725 base::RunLoop().Run();
2727 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
2728 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r.status().error());
2729 EXPECT_EQ(1, d.response_started_count());
2730 // We should not have followed the redirect.
2731 EXPECT_EQ(0, d.received_redirect_count());
2735 // This is the same as the previous test, but checks that the network delegate
2736 // registers the error.
2737 TEST_F(URLRequestTestHTTP, NetworkDelegateTunnelConnectionFailed) {
2738 ASSERT_TRUE(test_server_.Start());
2740 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
2741 TestURLRequestContextWithProxy context(
2742 test_server_.host_port_pair().ToString(), &network_delegate);
2744 TestDelegate d;
2746 URLRequest r(
2747 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d, &context);
2748 r.Start();
2749 EXPECT_TRUE(r.is_pending());
2751 base::RunLoop().Run();
2753 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
2754 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r.status().error());
2755 EXPECT_EQ(1, d.response_started_count());
2756 // We should not have followed the redirect.
2757 EXPECT_EQ(0, d.received_redirect_count());
2759 EXPECT_EQ(1, network_delegate.error_count());
2760 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, network_delegate.last_error());
2764 // Tests that we can block and asynchronously return OK in various stages.
2765 TEST_F(URLRequestTestHTTP, NetworkDelegateBlockAsynchronously) {
2766 static const BlockingNetworkDelegate::Stage blocking_stages[] = {
2767 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
2768 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
2769 BlockingNetworkDelegate::ON_HEADERS_RECEIVED
2771 static const size_t blocking_stages_length = arraysize(blocking_stages);
2773 ASSERT_TRUE(test_server_.Start());
2775 TestDelegate d;
2776 BlockingNetworkDelegate network_delegate(
2777 BlockingNetworkDelegate::USER_CALLBACK);
2778 network_delegate.set_block_on(
2779 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST |
2780 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS |
2781 BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
2783 TestURLRequestContext context(true);
2784 context.set_network_delegate(&network_delegate);
2785 context.Init();
2788 URLRequest r(
2789 test_server_.GetURL("empty.html"), DEFAULT_PRIORITY, &d, &context);
2791 r.Start();
2792 for (size_t i = 0; i < blocking_stages_length; ++i) {
2793 base::RunLoop().Run();
2794 EXPECT_EQ(blocking_stages[i],
2795 network_delegate.stage_blocked_for_callback());
2796 network_delegate.DoCallback(OK);
2798 base::RunLoop().Run();
2799 EXPECT_EQ(200, r.GetResponseCode());
2800 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
2801 EXPECT_EQ(1, network_delegate.created_requests());
2802 EXPECT_EQ(0, network_delegate.destroyed_requests());
2804 EXPECT_EQ(1, network_delegate.destroyed_requests());
2807 // Tests that the network delegate can block and cancel a request.
2808 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequest) {
2809 ASSERT_TRUE(test_server_.Start());
2811 TestDelegate d;
2812 BlockingNetworkDelegate network_delegate(
2813 BlockingNetworkDelegate::AUTO_CALLBACK);
2814 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
2815 network_delegate.set_retval(ERR_EMPTY_RESPONSE);
2817 TestURLRequestContextWithProxy context(
2818 test_server_.host_port_pair().ToString(), &network_delegate);
2821 URLRequest r(
2822 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, &context);
2824 r.Start();
2825 base::RunLoop().Run();
2827 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
2828 EXPECT_EQ(ERR_EMPTY_RESPONSE, r.status().error());
2829 EXPECT_EQ(1, network_delegate.created_requests());
2830 EXPECT_EQ(0, network_delegate.destroyed_requests());
2832 EXPECT_EQ(1, network_delegate.destroyed_requests());
2835 // Helper function for NetworkDelegateCancelRequestAsynchronously and
2836 // NetworkDelegateCancelRequestSynchronously. Sets up a blocking network
2837 // delegate operating in |block_mode| and a request for |url|. It blocks the
2838 // request in |stage| and cancels it with ERR_BLOCKED_BY_CLIENT.
2839 void NetworkDelegateCancelRequest(BlockingNetworkDelegate::BlockMode block_mode,
2840 BlockingNetworkDelegate::Stage stage,
2841 const GURL& url) {
2842 TestDelegate d;
2843 BlockingNetworkDelegate network_delegate(block_mode);
2844 network_delegate.set_retval(ERR_BLOCKED_BY_CLIENT);
2845 network_delegate.set_block_on(stage);
2847 TestURLRequestContext context(true);
2848 context.set_network_delegate(&network_delegate);
2849 context.Init();
2852 URLRequest r(url, DEFAULT_PRIORITY, &d, &context);
2854 r.Start();
2855 base::RunLoop().Run();
2857 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
2858 EXPECT_EQ(ERR_BLOCKED_BY_CLIENT, r.status().error());
2859 EXPECT_EQ(1, network_delegate.created_requests());
2860 EXPECT_EQ(0, network_delegate.destroyed_requests());
2862 EXPECT_EQ(1, network_delegate.destroyed_requests());
2865 // The following 3 tests check that the network delegate can cancel a request
2866 // synchronously in various stages of the request.
2867 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously1) {
2868 ASSERT_TRUE(test_server_.Start());
2869 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
2870 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
2871 test_server_.GetURL(std::string()));
2874 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously2) {
2875 ASSERT_TRUE(test_server_.Start());
2876 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
2877 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
2878 test_server_.GetURL(std::string()));
2881 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously3) {
2882 ASSERT_TRUE(test_server_.Start());
2883 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
2884 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
2885 test_server_.GetURL(std::string()));
2888 // The following 3 tests check that the network delegate can cancel a request
2889 // asynchronously in various stages of the request.
2890 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously1) {
2891 ASSERT_TRUE(test_server_.Start());
2892 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
2893 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
2894 test_server_.GetURL(std::string()));
2897 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously2) {
2898 ASSERT_TRUE(test_server_.Start());
2899 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
2900 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
2901 test_server_.GetURL(std::string()));
2904 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously3) {
2905 ASSERT_TRUE(test_server_.Start());
2906 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
2907 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
2908 test_server_.GetURL(std::string()));
2911 // Tests that the network delegate can block and redirect a request to a new
2912 // URL.
2913 TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequest) {
2914 ASSERT_TRUE(test_server_.Start());
2916 TestDelegate d;
2917 BlockingNetworkDelegate network_delegate(
2918 BlockingNetworkDelegate::AUTO_CALLBACK);
2919 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
2920 GURL redirect_url(test_server_.GetURL("simple.html"));
2921 network_delegate.set_redirect_url(redirect_url);
2923 TestURLRequestContextWithProxy context(
2924 test_server_.host_port_pair().ToString(), &network_delegate);
2927 GURL original_url(test_server_.GetURL("empty.html"));
2928 URLRequest r(original_url, DEFAULT_PRIORITY, &d, &context);
2930 r.Start();
2931 base::RunLoop().Run();
2933 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
2934 EXPECT_EQ(0, r.status().error());
2935 EXPECT_EQ(redirect_url, r.url());
2936 EXPECT_EQ(original_url, r.original_url());
2937 EXPECT_EQ(2U, r.url_chain().size());
2938 EXPECT_EQ(1, network_delegate.created_requests());
2939 EXPECT_EQ(0, network_delegate.destroyed_requests());
2941 EXPECT_EQ(1, network_delegate.destroyed_requests());
2944 // Tests that the network delegate can block and redirect a request to a new
2945 // URL by setting a redirect_url and returning in OnBeforeURLRequest directly.
2946 TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestSynchronously) {
2947 ASSERT_TRUE(test_server_.Start());
2949 TestDelegate d;
2950 BlockingNetworkDelegate network_delegate(
2951 BlockingNetworkDelegate::SYNCHRONOUS);
2952 GURL redirect_url(test_server_.GetURL("simple.html"));
2953 network_delegate.set_redirect_url(redirect_url);
2955 TestURLRequestContextWithProxy context(
2956 test_server_.host_port_pair().ToString(), &network_delegate);
2959 GURL original_url(test_server_.GetURL("empty.html"));
2960 URLRequest r(original_url, DEFAULT_PRIORITY, &d, &context);
2962 r.Start();
2963 base::RunLoop().Run();
2965 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
2966 EXPECT_EQ(0, r.status().error());
2967 EXPECT_EQ(redirect_url, r.url());
2968 EXPECT_EQ(original_url, r.original_url());
2969 EXPECT_EQ(2U, r.url_chain().size());
2970 EXPECT_EQ(1, network_delegate.created_requests());
2971 EXPECT_EQ(0, network_delegate.destroyed_requests());
2973 EXPECT_EQ(1, network_delegate.destroyed_requests());
2976 // Tests that redirects caused by the network delegate preserve POST data.
2977 TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestPost) {
2978 ASSERT_TRUE(test_server_.Start());
2980 const char kData[] = "hello world";
2982 TestDelegate d;
2983 BlockingNetworkDelegate network_delegate(
2984 BlockingNetworkDelegate::AUTO_CALLBACK);
2985 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
2986 GURL redirect_url(test_server_.GetURL("echo"));
2987 network_delegate.set_redirect_url(redirect_url);
2989 TestURLRequestContext context(true);
2990 context.set_network_delegate(&network_delegate);
2991 context.Init();
2994 GURL original_url(test_server_.GetURL("empty.html"));
2995 URLRequest r(original_url, DEFAULT_PRIORITY, &d, &context);
2996 r.set_method("POST");
2997 r.set_upload(make_scoped_ptr(CreateSimpleUploadData(kData)));
2998 HttpRequestHeaders headers;
2999 headers.SetHeader(HttpRequestHeaders::kContentLength,
3000 base::UintToString(arraysize(kData) - 1));
3001 r.SetExtraRequestHeaders(headers);
3002 r.Start();
3003 base::RunLoop().Run();
3005 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3006 EXPECT_EQ(0, r.status().error());
3007 EXPECT_EQ(redirect_url, r.url());
3008 EXPECT_EQ(original_url, r.original_url());
3009 EXPECT_EQ(2U, r.url_chain().size());
3010 EXPECT_EQ(1, network_delegate.created_requests());
3011 EXPECT_EQ(0, network_delegate.destroyed_requests());
3012 EXPECT_EQ("POST", r.method());
3013 EXPECT_EQ(kData, d.data_received());
3015 EXPECT_EQ(1, network_delegate.destroyed_requests());
3018 // Tests that the network delegate can block and redirect a request to a new
3019 // URL during OnHeadersReceived.
3020 TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestOnHeadersReceived) {
3021 ASSERT_TRUE(test_server_.Start());
3023 TestDelegate d;
3024 BlockingNetworkDelegate network_delegate(
3025 BlockingNetworkDelegate::AUTO_CALLBACK);
3026 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
3027 GURL redirect_url(test_server_.GetURL("simple.html"));
3028 network_delegate.set_redirect_on_headers_received_url(redirect_url);
3030 TestURLRequestContextWithProxy context(
3031 test_server_.host_port_pair().ToString(), &network_delegate);
3034 GURL original_url(test_server_.GetURL("empty.html"));
3035 URLRequest r(original_url, DEFAULT_PRIORITY, &d, &context);
3037 r.Start();
3038 base::RunLoop().Run();
3040 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3041 EXPECT_EQ(net::OK, r.status().error());
3042 EXPECT_EQ(redirect_url, r.url());
3043 EXPECT_EQ(original_url, r.original_url());
3044 EXPECT_EQ(2U, r.url_chain().size());
3045 EXPECT_EQ(2, network_delegate.created_requests());
3046 EXPECT_EQ(0, network_delegate.destroyed_requests());
3048 EXPECT_EQ(1, network_delegate.destroyed_requests());
3051 // Tests that the network delegate can synchronously complete OnAuthRequired
3052 // by taking no action. This indicates that the NetworkDelegate does not want to
3053 // handle the challenge, and is passing the buck along to the
3054 // URLRequest::Delegate.
3055 TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncNoAction) {
3056 ASSERT_TRUE(test_server_.Start());
3058 TestDelegate d;
3059 BlockingNetworkDelegate network_delegate(
3060 BlockingNetworkDelegate::SYNCHRONOUS);
3062 TestURLRequestContext context(true);
3063 context.set_network_delegate(&network_delegate);
3064 context.Init();
3066 d.set_credentials(AuthCredentials(kUser, kSecret));
3069 GURL url(test_server_.GetURL("auth-basic"));
3070 URLRequest r(url, DEFAULT_PRIORITY, &d, &context);
3071 r.Start();
3073 base::RunLoop().Run();
3075 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3076 EXPECT_EQ(0, r.status().error());
3077 EXPECT_EQ(200, r.GetResponseCode());
3078 EXPECT_TRUE(d.auth_required_called());
3079 EXPECT_EQ(1, network_delegate.created_requests());
3080 EXPECT_EQ(0, network_delegate.destroyed_requests());
3082 EXPECT_EQ(1, network_delegate.destroyed_requests());
3085 TEST_F(URLRequestTestHTTP,
3086 NetworkDelegateOnAuthRequiredSyncNoAction_GetFullRequestHeaders) {
3087 ASSERT_TRUE(test_server_.Start());
3089 TestDelegate d;
3090 BlockingNetworkDelegate network_delegate(
3091 BlockingNetworkDelegate::SYNCHRONOUS);
3093 TestURLRequestContext context(true);
3094 context.set_network_delegate(&network_delegate);
3095 context.Init();
3097 d.set_credentials(AuthCredentials(kUser, kSecret));
3100 GURL url(test_server_.GetURL("auth-basic"));
3101 URLRequest r(url, DEFAULT_PRIORITY, &d, &context);
3102 r.Start();
3105 HttpRequestHeaders headers;
3106 EXPECT_TRUE(r.GetFullRequestHeaders(&headers));
3107 EXPECT_FALSE(headers.HasHeader("Authorization"));
3110 base::RunLoop().Run();
3112 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3113 EXPECT_EQ(0, r.status().error());
3114 EXPECT_EQ(200, r.GetResponseCode());
3115 EXPECT_TRUE(d.auth_required_called());
3116 EXPECT_EQ(1, network_delegate.created_requests());
3117 EXPECT_EQ(0, network_delegate.destroyed_requests());
3119 EXPECT_EQ(1, network_delegate.destroyed_requests());
3122 // Tests that the network delegate can synchronously complete OnAuthRequired
3123 // by setting credentials.
3124 TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncSetAuth) {
3125 ASSERT_TRUE(test_server_.Start());
3127 TestDelegate d;
3128 BlockingNetworkDelegate network_delegate(
3129 BlockingNetworkDelegate::SYNCHRONOUS);
3130 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3131 network_delegate.set_auth_retval(
3132 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3134 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
3136 TestURLRequestContext context(true);
3137 context.set_network_delegate(&network_delegate);
3138 context.Init();
3141 GURL url(test_server_.GetURL("auth-basic"));
3142 URLRequest r(url, DEFAULT_PRIORITY, &d, &context);
3143 r.Start();
3144 base::RunLoop().Run();
3146 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3147 EXPECT_EQ(0, r.status().error());
3148 EXPECT_EQ(200, r.GetResponseCode());
3149 EXPECT_FALSE(d.auth_required_called());
3150 EXPECT_EQ(1, network_delegate.created_requests());
3151 EXPECT_EQ(0, network_delegate.destroyed_requests());
3153 EXPECT_EQ(1, network_delegate.destroyed_requests());
3156 // Same as above, but also tests that GetFullRequestHeaders returns the proper
3157 // headers (for the first or second request) when called at the proper times.
3158 TEST_F(URLRequestTestHTTP,
3159 NetworkDelegateOnAuthRequiredSyncSetAuth_GetFullRequestHeaders) {
3160 ASSERT_TRUE(test_server_.Start());
3162 TestDelegate d;
3163 BlockingNetworkDelegate network_delegate(
3164 BlockingNetworkDelegate::SYNCHRONOUS);
3165 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3166 network_delegate.set_auth_retval(
3167 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3169 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
3171 TestURLRequestContext context(true);
3172 context.set_network_delegate(&network_delegate);
3173 context.Init();
3176 GURL url(test_server_.GetURL("auth-basic"));
3177 URLRequest r(url, DEFAULT_PRIORITY, &d, &context);
3178 r.Start();
3179 base::RunLoop().Run();
3181 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3182 EXPECT_EQ(0, r.status().error());
3183 EXPECT_EQ(200, r.GetResponseCode());
3184 EXPECT_FALSE(d.auth_required_called());
3185 EXPECT_EQ(1, network_delegate.created_requests());
3186 EXPECT_EQ(0, network_delegate.destroyed_requests());
3189 HttpRequestHeaders headers;
3190 EXPECT_TRUE(r.GetFullRequestHeaders(&headers));
3191 EXPECT_TRUE(headers.HasHeader("Authorization"));
3194 EXPECT_EQ(1, network_delegate.destroyed_requests());
3197 // Tests that the network delegate can synchronously complete OnAuthRequired
3198 // by cancelling authentication.
3199 TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncCancel) {
3200 ASSERT_TRUE(test_server_.Start());
3202 TestDelegate d;
3203 BlockingNetworkDelegate network_delegate(
3204 BlockingNetworkDelegate::SYNCHRONOUS);
3205 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3206 network_delegate.set_auth_retval(
3207 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
3209 TestURLRequestContext context(true);
3210 context.set_network_delegate(&network_delegate);
3211 context.Init();
3214 GURL url(test_server_.GetURL("auth-basic"));
3215 URLRequest r(url, DEFAULT_PRIORITY, &d, &context);
3216 r.Start();
3217 base::RunLoop().Run();
3219 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3220 EXPECT_EQ(OK, r.status().error());
3221 EXPECT_EQ(401, r.GetResponseCode());
3222 EXPECT_FALSE(d.auth_required_called());
3223 EXPECT_EQ(1, network_delegate.created_requests());
3224 EXPECT_EQ(0, network_delegate.destroyed_requests());
3226 EXPECT_EQ(1, network_delegate.destroyed_requests());
3229 // Tests that the network delegate can asynchronously complete OnAuthRequired
3230 // by taking no action. This indicates that the NetworkDelegate does not want
3231 // to handle the challenge, and is passing the buck along to the
3232 // URLRequest::Delegate.
3233 TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncNoAction) {
3234 ASSERT_TRUE(test_server_.Start());
3236 TestDelegate d;
3237 BlockingNetworkDelegate network_delegate(
3238 BlockingNetworkDelegate::AUTO_CALLBACK);
3239 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3241 TestURLRequestContext context(true);
3242 context.set_network_delegate(&network_delegate);
3243 context.Init();
3245 d.set_credentials(AuthCredentials(kUser, kSecret));
3248 GURL url(test_server_.GetURL("auth-basic"));
3249 URLRequest r(url, DEFAULT_PRIORITY, &d, &context);
3250 r.Start();
3251 base::RunLoop().Run();
3253 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3254 EXPECT_EQ(0, r.status().error());
3255 EXPECT_EQ(200, r.GetResponseCode());
3256 EXPECT_TRUE(d.auth_required_called());
3257 EXPECT_EQ(1, network_delegate.created_requests());
3258 EXPECT_EQ(0, network_delegate.destroyed_requests());
3260 EXPECT_EQ(1, network_delegate.destroyed_requests());
3263 // Tests that the network delegate can asynchronously complete OnAuthRequired
3264 // by setting credentials.
3265 TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncSetAuth) {
3266 ASSERT_TRUE(test_server_.Start());
3268 TestDelegate d;
3269 BlockingNetworkDelegate network_delegate(
3270 BlockingNetworkDelegate::AUTO_CALLBACK);
3271 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3272 network_delegate.set_auth_retval(
3273 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3275 AuthCredentials auth_credentials(kUser, kSecret);
3276 network_delegate.set_auth_credentials(auth_credentials);
3278 TestURLRequestContext context(true);
3279 context.set_network_delegate(&network_delegate);
3280 context.Init();
3283 GURL url(test_server_.GetURL("auth-basic"));
3284 URLRequest r(url, DEFAULT_PRIORITY, &d, &context);
3285 r.Start();
3286 base::RunLoop().Run();
3288 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3289 EXPECT_EQ(0, r.status().error());
3291 EXPECT_EQ(200, r.GetResponseCode());
3292 EXPECT_FALSE(d.auth_required_called());
3293 EXPECT_EQ(1, network_delegate.created_requests());
3294 EXPECT_EQ(0, network_delegate.destroyed_requests());
3296 EXPECT_EQ(1, network_delegate.destroyed_requests());
3299 // Tests that the network delegate can asynchronously complete OnAuthRequired
3300 // by cancelling authentication.
3301 TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncCancel) {
3302 ASSERT_TRUE(test_server_.Start());
3304 TestDelegate d;
3305 BlockingNetworkDelegate network_delegate(
3306 BlockingNetworkDelegate::AUTO_CALLBACK);
3307 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3308 network_delegate.set_auth_retval(
3309 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
3311 TestURLRequestContext context(true);
3312 context.set_network_delegate(&network_delegate);
3313 context.Init();
3316 GURL url(test_server_.GetURL("auth-basic"));
3317 URLRequest r(url, DEFAULT_PRIORITY, &d, &context);
3318 r.Start();
3319 base::RunLoop().Run();
3321 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3322 EXPECT_EQ(OK, r.status().error());
3323 EXPECT_EQ(401, r.GetResponseCode());
3324 EXPECT_FALSE(d.auth_required_called());
3325 EXPECT_EQ(1, network_delegate.created_requests());
3326 EXPECT_EQ(0, network_delegate.destroyed_requests());
3328 EXPECT_EQ(1, network_delegate.destroyed_requests());
3331 // Tests that we can handle when a network request was canceled while we were
3332 // waiting for the network delegate.
3333 // Part 1: Request is cancelled while waiting for OnBeforeURLRequest callback.
3334 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting1) {
3335 ASSERT_TRUE(test_server_.Start());
3337 TestDelegate d;
3338 BlockingNetworkDelegate network_delegate(
3339 BlockingNetworkDelegate::USER_CALLBACK);
3340 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
3342 TestURLRequestContext context(true);
3343 context.set_network_delegate(&network_delegate);
3344 context.Init();
3347 URLRequest r(
3348 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, &context);
3350 r.Start();
3351 base::RunLoop().Run();
3352 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
3353 network_delegate.stage_blocked_for_callback());
3354 EXPECT_EQ(0, network_delegate.completed_requests());
3355 // Cancel before callback.
3356 r.Cancel();
3357 // Ensure that network delegate is notified.
3358 EXPECT_EQ(1, network_delegate.completed_requests());
3359 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
3360 EXPECT_EQ(ERR_ABORTED, r.status().error());
3361 EXPECT_EQ(1, network_delegate.created_requests());
3362 EXPECT_EQ(0, network_delegate.destroyed_requests());
3364 EXPECT_EQ(1, network_delegate.destroyed_requests());
3367 // Tests that we can handle when a network request was canceled while we were
3368 // waiting for the network delegate.
3369 // Part 2: Request is cancelled while waiting for OnBeforeSendHeaders callback.
3370 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting2) {
3371 ASSERT_TRUE(test_server_.Start());
3373 TestDelegate d;
3374 BlockingNetworkDelegate network_delegate(
3375 BlockingNetworkDelegate::USER_CALLBACK);
3376 network_delegate.set_block_on(
3377 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS);
3379 TestURLRequestContext context(true);
3380 context.set_network_delegate(&network_delegate);
3381 context.Init();
3384 URLRequest r(
3385 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, &context);
3387 r.Start();
3388 base::RunLoop().Run();
3389 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
3390 network_delegate.stage_blocked_for_callback());
3391 EXPECT_EQ(0, network_delegate.completed_requests());
3392 // Cancel before callback.
3393 r.Cancel();
3394 // Ensure that network delegate is notified.
3395 EXPECT_EQ(1, network_delegate.completed_requests());
3396 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
3397 EXPECT_EQ(ERR_ABORTED, r.status().error());
3398 EXPECT_EQ(1, network_delegate.created_requests());
3399 EXPECT_EQ(0, network_delegate.destroyed_requests());
3401 EXPECT_EQ(1, network_delegate.destroyed_requests());
3404 // Tests that we can handle when a network request was canceled while we were
3405 // waiting for the network delegate.
3406 // Part 3: Request is cancelled while waiting for OnHeadersReceived callback.
3407 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting3) {
3408 ASSERT_TRUE(test_server_.Start());
3410 TestDelegate d;
3411 BlockingNetworkDelegate network_delegate(
3412 BlockingNetworkDelegate::USER_CALLBACK);
3413 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
3415 TestURLRequestContext context(true);
3416 context.set_network_delegate(&network_delegate);
3417 context.Init();
3420 URLRequest r(
3421 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, &context);
3423 r.Start();
3424 base::RunLoop().Run();
3425 EXPECT_EQ(BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
3426 network_delegate.stage_blocked_for_callback());
3427 EXPECT_EQ(0, network_delegate.completed_requests());
3428 // Cancel before callback.
3429 r.Cancel();
3430 // Ensure that network delegate is notified.
3431 EXPECT_EQ(1, network_delegate.completed_requests());
3432 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
3433 EXPECT_EQ(ERR_ABORTED, r.status().error());
3434 EXPECT_EQ(1, network_delegate.created_requests());
3435 EXPECT_EQ(0, network_delegate.destroyed_requests());
3437 EXPECT_EQ(1, network_delegate.destroyed_requests());
3440 // Tests that we can handle when a network request was canceled while we were
3441 // waiting for the network delegate.
3442 // Part 4: Request is cancelled while waiting for OnAuthRequired callback.
3443 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting4) {
3444 ASSERT_TRUE(test_server_.Start());
3446 TestDelegate d;
3447 BlockingNetworkDelegate network_delegate(
3448 BlockingNetworkDelegate::USER_CALLBACK);
3449 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3451 TestURLRequestContext context(true);
3452 context.set_network_delegate(&network_delegate);
3453 context.Init();
3456 URLRequest r(
3457 test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d, &context);
3459 r.Start();
3460 base::RunLoop().Run();
3461 EXPECT_EQ(BlockingNetworkDelegate::ON_AUTH_REQUIRED,
3462 network_delegate.stage_blocked_for_callback());
3463 EXPECT_EQ(0, network_delegate.completed_requests());
3464 // Cancel before callback.
3465 r.Cancel();
3466 // Ensure that network delegate is notified.
3467 EXPECT_EQ(1, network_delegate.completed_requests());
3468 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
3469 EXPECT_EQ(ERR_ABORTED, r.status().error());
3470 EXPECT_EQ(1, network_delegate.created_requests());
3471 EXPECT_EQ(0, network_delegate.destroyed_requests());
3473 EXPECT_EQ(1, network_delegate.destroyed_requests());
3476 // In this unit test, we're using the HTTPTestServer as a proxy server and
3477 // issuing a CONNECT request with the magic host name "www.server-auth.com".
3478 // The HTTPTestServer will return a 401 response, which we should balk at.
3479 TEST_F(URLRequestTestHTTP, UnexpectedServerAuthTest) {
3480 ASSERT_TRUE(test_server_.Start());
3482 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
3483 TestURLRequestContextWithProxy context(
3484 test_server_.host_port_pair().ToString(), &network_delegate);
3486 TestDelegate d;
3488 URLRequest r(
3489 GURL("https://www.server-auth.com/"), DEFAULT_PRIORITY, &d, &context);
3491 r.Start();
3492 EXPECT_TRUE(r.is_pending());
3494 base::RunLoop().Run();
3496 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
3497 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r.status().error());
3501 TEST_F(URLRequestTestHTTP, GetTest_NoCache) {
3502 ASSERT_TRUE(test_server_.Start());
3504 TestDelegate d;
3506 URLRequest r(test_server_.GetURL(std::string()),
3507 DEFAULT_PRIORITY,
3509 &default_context_);
3511 r.Start();
3512 EXPECT_TRUE(r.is_pending());
3514 base::RunLoop().Run();
3516 EXPECT_EQ(1, d.response_started_count());
3517 EXPECT_FALSE(d.received_data_before_response());
3518 EXPECT_NE(0, d.bytes_received());
3519 EXPECT_EQ(test_server_.host_port_pair().host(),
3520 r.GetSocketAddress().host());
3521 EXPECT_EQ(test_server_.host_port_pair().port(),
3522 r.GetSocketAddress().port());
3524 // TODO(eroman): Add back the NetLog tests...
3528 // This test has the server send a large number of cookies to the client.
3529 // To ensure that no number of cookies causes a crash, a galloping binary
3530 // search is used to estimate that maximum number of cookies that are accepted
3531 // by the browser. Beyond the maximum number, the request will fail with
3532 // ERR_RESPONSE_HEADERS_TOO_BIG.
3533 #if defined(OS_WIN)
3534 // http://crbug.com/177916
3535 #define MAYBE_GetTest_ManyCookies DISABLED_GetTest_ManyCookies
3536 #else
3537 #define MAYBE_GetTest_ManyCookies GetTest_ManyCookies
3538 #endif // defined(OS_WIN)
3539 TEST_F(URLRequestTestHTTP, MAYBE_GetTest_ManyCookies) {
3540 ASSERT_TRUE(test_server_.Start());
3542 int lower_bound = 0;
3543 int upper_bound = 1;
3545 // Double the number of cookies until the response header limits are
3546 // exceeded.
3547 while (DoManyCookiesRequest(upper_bound)) {
3548 lower_bound = upper_bound;
3549 upper_bound *= 2;
3550 ASSERT_LT(upper_bound, 1000000);
3553 int tolerance = upper_bound * 0.005;
3554 if (tolerance < 2)
3555 tolerance = 2;
3557 // Perform a binary search to find the highest possible number of cookies,
3558 // within the desired tolerance.
3559 while (upper_bound - lower_bound >= tolerance) {
3560 int num_cookies = (lower_bound + upper_bound) / 2;
3562 if (DoManyCookiesRequest(num_cookies))
3563 lower_bound = num_cookies;
3564 else
3565 upper_bound = num_cookies;
3567 // Success: the test did not crash.
3570 TEST_F(URLRequestTestHTTP, GetTest) {
3571 ASSERT_TRUE(test_server_.Start());
3573 TestDelegate d;
3575 URLRequest r(test_server_.GetURL(std::string()),
3576 DEFAULT_PRIORITY,
3578 &default_context_);
3580 r.Start();
3581 EXPECT_TRUE(r.is_pending());
3583 base::RunLoop().Run();
3585 EXPECT_EQ(1, d.response_started_count());
3586 EXPECT_FALSE(d.received_data_before_response());
3587 EXPECT_NE(0, d.bytes_received());
3588 EXPECT_EQ(test_server_.host_port_pair().host(),
3589 r.GetSocketAddress().host());
3590 EXPECT_EQ(test_server_.host_port_pair().port(),
3591 r.GetSocketAddress().port());
3595 TEST_F(URLRequestTestHTTP, GetTest_GetFullRequestHeaders) {
3596 ASSERT_TRUE(test_server_.Start());
3598 TestDelegate d;
3600 GURL test_url(test_server_.GetURL(std::string()));
3601 URLRequest r(test_url, DEFAULT_PRIORITY, &d, &default_context_);
3603 HttpRequestHeaders headers;
3604 EXPECT_FALSE(r.GetFullRequestHeaders(&headers));
3606 r.Start();
3607 EXPECT_TRUE(r.is_pending());
3609 base::RunLoop().Run();
3611 EXPECT_EQ(1, d.response_started_count());
3612 EXPECT_FALSE(d.received_data_before_response());
3613 EXPECT_NE(0, d.bytes_received());
3614 EXPECT_EQ(test_server_.host_port_pair().host(),
3615 r.GetSocketAddress().host());
3616 EXPECT_EQ(test_server_.host_port_pair().port(),
3617 r.GetSocketAddress().port());
3619 EXPECT_TRUE(d.have_full_request_headers());
3620 CheckFullRequestHeaders(d.full_request_headers(), test_url);
3624 TEST_F(URLRequestTestHTTP, GetTestLoadTiming) {
3625 ASSERT_TRUE(test_server_.Start());
3627 TestDelegate d;
3629 URLRequest r(test_server_.GetURL(std::string()),
3630 DEFAULT_PRIORITY,
3632 &default_context_);
3634 r.Start();
3635 EXPECT_TRUE(r.is_pending());
3637 base::RunLoop().Run();
3639 LoadTimingInfo load_timing_info;
3640 r.GetLoadTimingInfo(&load_timing_info);
3641 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
3643 EXPECT_EQ(1, d.response_started_count());
3644 EXPECT_FALSE(d.received_data_before_response());
3645 EXPECT_NE(0, d.bytes_received());
3646 EXPECT_EQ(test_server_.host_port_pair().host(),
3647 r.GetSocketAddress().host());
3648 EXPECT_EQ(test_server_.host_port_pair().port(),
3649 r.GetSocketAddress().port());
3653 TEST_F(URLRequestTestHTTP, GetZippedTest) {
3654 ASSERT_TRUE(test_server_.Start());
3656 // Parameter that specifies the Content-Length field in the response:
3657 // C - Compressed length.
3658 // U - Uncompressed length.
3659 // L - Large length (larger than both C & U).
3660 // M - Medium length (between C & U).
3661 // S - Small length (smaller than both C & U).
3662 const char test_parameters[] = "CULMS";
3663 const int num_tests = arraysize(test_parameters)- 1; // Skip NULL.
3664 // C & U should be OK.
3665 // L & M are larger than the data sent, and show an error.
3666 // S has too little data, but we seem to accept it.
3667 const bool test_expect_success[num_tests] =
3668 { true, true, false, false, true };
3670 for (int i = 0; i < num_tests ; i++) {
3671 TestDelegate d;
3673 std::string test_file =
3674 base::StringPrintf("compressedfiles/BullRunSpeech.txt?%c",
3675 test_parameters[i]);
3677 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
3678 TestURLRequestContext context(true);
3679 context.set_network_delegate(&network_delegate);
3680 context.Init();
3682 URLRequest r(
3683 test_server_.GetURL(test_file), DEFAULT_PRIORITY, &d, &context);
3684 r.Start();
3685 EXPECT_TRUE(r.is_pending());
3687 base::RunLoop().Run();
3689 EXPECT_EQ(1, d.response_started_count());
3690 EXPECT_FALSE(d.received_data_before_response());
3691 VLOG(1) << " Received " << d.bytes_received() << " bytes"
3692 << " status = " << r.status().status()
3693 << " error = " << r.status().error();
3694 if (test_expect_success[i]) {
3695 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status())
3696 << " Parameter = \"" << test_file << "\"";
3697 } else {
3698 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
3699 EXPECT_EQ(ERR_CONTENT_LENGTH_MISMATCH, r.status().error())
3700 << " Parameter = \"" << test_file << "\"";
3706 TEST_F(URLRequestTestHTTP, HTTPSToHTTPRedirectNoRefererTest) {
3707 ASSERT_TRUE(test_server_.Start());
3709 SpawnedTestServer https_test_server(
3710 SpawnedTestServer::TYPE_HTTPS, SpawnedTestServer::kLocalhost,
3711 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3712 ASSERT_TRUE(https_test_server.Start());
3714 // An https server is sent a request with an https referer,
3715 // and responds with a redirect to an http url. The http
3716 // server should not be sent the referer.
3717 GURL http_destination = test_server_.GetURL(std::string());
3718 TestDelegate d;
3719 URLRequest req(
3720 https_test_server.GetURL("server-redirect?" + http_destination.spec()),
3721 DEFAULT_PRIORITY,
3723 &default_context_);
3724 req.SetReferrer("https://www.referrer.com/");
3725 req.Start();
3726 base::RunLoop().Run();
3728 EXPECT_EQ(1, d.response_started_count());
3729 EXPECT_EQ(1, d.received_redirect_count());
3730 EXPECT_EQ(http_destination, req.url());
3731 EXPECT_EQ(std::string(), req.referrer());
3734 TEST_F(URLRequestTestHTTP, RedirectLoadTiming) {
3735 ASSERT_TRUE(test_server_.Start());
3737 GURL destination_url = test_server_.GetURL(std::string());
3738 GURL original_url =
3739 test_server_.GetURL("server-redirect?" + destination_url.spec());
3740 TestDelegate d;
3741 URLRequest req(original_url, DEFAULT_PRIORITY, &d, &default_context_);
3742 req.Start();
3743 base::RunLoop().Run();
3745 EXPECT_EQ(1, d.response_started_count());
3746 EXPECT_EQ(1, d.received_redirect_count());
3747 EXPECT_EQ(destination_url, req.url());
3748 EXPECT_EQ(original_url, req.original_url());
3749 ASSERT_EQ(2U, req.url_chain().size());
3750 EXPECT_EQ(original_url, req.url_chain()[0]);
3751 EXPECT_EQ(destination_url, req.url_chain()[1]);
3753 LoadTimingInfo load_timing_info_before_redirect;
3754 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeRedirect(
3755 &load_timing_info_before_redirect));
3756 TestLoadTimingNotReused(load_timing_info_before_redirect,
3757 CONNECT_TIMING_HAS_DNS_TIMES);
3759 LoadTimingInfo load_timing_info;
3760 req.GetLoadTimingInfo(&load_timing_info);
3761 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
3763 // Check that a new socket was used on redirect, since the server does not
3764 // supposed keep-alive sockets, and that the times before the redirect are
3765 // before the ones recorded for the second request.
3766 EXPECT_NE(load_timing_info_before_redirect.socket_log_id,
3767 load_timing_info.socket_log_id);
3768 EXPECT_LE(load_timing_info_before_redirect.receive_headers_end,
3769 load_timing_info.connect_timing.connect_start);
3772 TEST_F(URLRequestTestHTTP, MultipleRedirectTest) {
3773 ASSERT_TRUE(test_server_.Start());
3775 GURL destination_url = test_server_.GetURL(std::string());
3776 GURL middle_redirect_url =
3777 test_server_.GetURL("server-redirect?" + destination_url.spec());
3778 GURL original_url = test_server_.GetURL(
3779 "server-redirect?" + middle_redirect_url.spec());
3780 TestDelegate d;
3781 URLRequest req(original_url, DEFAULT_PRIORITY, &d, &default_context_);
3782 req.Start();
3783 base::RunLoop().Run();
3785 EXPECT_EQ(1, d.response_started_count());
3786 EXPECT_EQ(2, d.received_redirect_count());
3787 EXPECT_EQ(destination_url, req.url());
3788 EXPECT_EQ(original_url, req.original_url());
3789 ASSERT_EQ(3U, req.url_chain().size());
3790 EXPECT_EQ(original_url, req.url_chain()[0]);
3791 EXPECT_EQ(middle_redirect_url, req.url_chain()[1]);
3792 EXPECT_EQ(destination_url, req.url_chain()[2]);
3795 // First and second pieces of information logged by delegates to URLRequests.
3796 const char kFirstDelegateInfo[] = "Wonderful delegate";
3797 const char kSecondDelegateInfo[] = "Exciting delegate";
3799 // Logs delegate information to a URLRequest. The first string is logged
3800 // synchronously on Start(), using DELEGATE_INFO_DEBUG_ONLY. The second is
3801 // logged asynchronously, using DELEGATE_INFO_DISPLAY_TO_USER. Then
3802 // another asynchronous call is used to clear the delegate information
3803 // before calling a callback. The object then deletes itself.
3804 class AsyncDelegateLogger : public base::RefCounted<AsyncDelegateLogger> {
3805 public:
3806 typedef base::Callback<void()> Callback;
3808 // Each time delegate information is added to the URLRequest, the resulting
3809 // load state is checked. The expected load state after each request is
3810 // passed in as an argument.
3811 static void Run(URLRequest* url_request,
3812 LoadState expected_first_load_state,
3813 LoadState expected_second_load_state,
3814 LoadState expected_third_load_state,
3815 const Callback& callback) {
3816 AsyncDelegateLogger* logger = new AsyncDelegateLogger(
3817 url_request,
3818 expected_first_load_state,
3819 expected_second_load_state,
3820 expected_third_load_state,
3821 callback);
3822 logger->Start();
3825 // Checks that the log entries, starting with log_position, contain the
3826 // DELEGATE_INFO NetLog events that an AsyncDelegateLogger should have
3827 // recorded. Returns the index of entry after the expected number of
3828 // events this logged, or entries.size() if there aren't enough entries.
3829 static size_t CheckDelegateInfo(
3830 const CapturingNetLog::CapturedEntryList& entries, size_t log_position) {
3831 // There should be 4 DELEGATE_INFO events: Two begins and two ends.
3832 if (log_position + 3 >= entries.size()) {
3833 ADD_FAILURE() << "Not enough log entries";
3834 return entries.size();
3836 std::string delegate_info;
3837 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
3838 EXPECT_EQ(NetLog::PHASE_BEGIN, entries[log_position].phase);
3839 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_info",
3840 &delegate_info));
3841 EXPECT_EQ(kFirstDelegateInfo, delegate_info);
3843 ++log_position;
3844 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
3845 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
3847 ++log_position;
3848 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
3849 EXPECT_EQ(NetLog::PHASE_BEGIN, entries[log_position].phase);
3850 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_info",
3851 &delegate_info));
3852 EXPECT_EQ(kSecondDelegateInfo, delegate_info);
3854 ++log_position;
3855 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
3856 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
3858 return log_position + 1;
3861 // Find delegate request begin and end messages for OnBeforeNetworkStart.
3862 // Returns the position of the end message.
3863 static size_t ExpectBeforeNetworkEvents(
3864 const CapturingNetLog::CapturedEntryList& entries,
3865 size_t log_position) {
3866 log_position =
3867 ExpectLogContainsSomewhereAfter(entries,
3868 log_position,
3869 NetLog::TYPE_URL_REQUEST_DELEGATE,
3870 NetLog::PHASE_BEGIN);
3871 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE,
3872 entries[log_position + 1].type);
3873 EXPECT_EQ(NetLog::PHASE_END, entries[log_position + 1].phase);
3874 return log_position + 1;
3877 private:
3878 friend class base::RefCounted<AsyncDelegateLogger>;
3880 AsyncDelegateLogger(URLRequest* url_request,
3881 LoadState expected_first_load_state,
3882 LoadState expected_second_load_state,
3883 LoadState expected_third_load_state,
3884 const Callback& callback)
3885 : url_request_(url_request),
3886 expected_first_load_state_(expected_first_load_state),
3887 expected_second_load_state_(expected_second_load_state),
3888 expected_third_load_state_(expected_third_load_state),
3889 callback_(callback) {
3892 ~AsyncDelegateLogger() {}
3894 void Start() {
3895 url_request_->LogBlockedBy(kFirstDelegateInfo);
3896 LoadStateWithParam load_state = url_request_->GetLoadState();
3897 EXPECT_EQ(expected_first_load_state_, load_state.state);
3898 EXPECT_NE(ASCIIToUTF16(kFirstDelegateInfo), load_state.param);
3899 base::MessageLoop::current()->PostTask(
3900 FROM_HERE,
3901 base::Bind(&AsyncDelegateLogger::LogSecondDelegate, this));
3904 void LogSecondDelegate() {
3905 url_request_->LogAndReportBlockedBy(kSecondDelegateInfo);
3906 LoadStateWithParam load_state = url_request_->GetLoadState();
3907 EXPECT_EQ(expected_second_load_state_, load_state.state);
3908 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE) {
3909 EXPECT_EQ(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
3910 } else {
3911 EXPECT_NE(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
3913 base::MessageLoop::current()->PostTask(
3914 FROM_HERE,
3915 base::Bind(&AsyncDelegateLogger::LogComplete, this));
3918 void LogComplete() {
3919 url_request_->LogUnblocked();
3920 LoadStateWithParam load_state = url_request_->GetLoadState();
3921 EXPECT_EQ(expected_third_load_state_, load_state.state);
3922 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE)
3923 EXPECT_EQ(base::string16(), load_state.param);
3924 callback_.Run();
3927 URLRequest* url_request_;
3928 const int expected_first_load_state_;
3929 const int expected_second_load_state_;
3930 const int expected_third_load_state_;
3931 const Callback callback_;
3933 DISALLOW_COPY_AND_ASSIGN(AsyncDelegateLogger);
3936 // NetworkDelegate that logs delegate information before a request is started,
3937 // before headers are sent, when headers are read, and when auth information
3938 // is requested. Uses AsyncDelegateLogger.
3939 class AsyncLoggingNetworkDelegate : public TestNetworkDelegate {
3940 public:
3941 AsyncLoggingNetworkDelegate() {}
3942 virtual ~AsyncLoggingNetworkDelegate() {}
3944 // NetworkDelegate implementation.
3945 virtual int OnBeforeURLRequest(URLRequest* request,
3946 const CompletionCallback& callback,
3947 GURL* new_url) OVERRIDE {
3948 TestNetworkDelegate::OnBeforeURLRequest(request, callback, new_url);
3949 return RunCallbackAsynchronously(request, callback);
3952 virtual int OnBeforeSendHeaders(URLRequest* request,
3953 const CompletionCallback& callback,
3954 HttpRequestHeaders* headers) OVERRIDE {
3955 TestNetworkDelegate::OnBeforeSendHeaders(request, callback, headers);
3956 return RunCallbackAsynchronously(request, callback);
3959 virtual int OnHeadersReceived(
3960 URLRequest* request,
3961 const CompletionCallback& callback,
3962 const HttpResponseHeaders* original_response_headers,
3963 scoped_refptr<HttpResponseHeaders>* override_response_headers,
3964 GURL* allowed_unsafe_redirect_url) OVERRIDE {
3965 TestNetworkDelegate::OnHeadersReceived(request,
3966 callback,
3967 original_response_headers,
3968 override_response_headers,
3969 allowed_unsafe_redirect_url);
3970 return RunCallbackAsynchronously(request, callback);
3973 virtual NetworkDelegate::AuthRequiredResponse OnAuthRequired(
3974 URLRequest* request,
3975 const AuthChallengeInfo& auth_info,
3976 const AuthCallback& callback,
3977 AuthCredentials* credentials) OVERRIDE {
3978 AsyncDelegateLogger::Run(
3979 request,
3980 LOAD_STATE_WAITING_FOR_DELEGATE,
3981 LOAD_STATE_WAITING_FOR_DELEGATE,
3982 LOAD_STATE_WAITING_FOR_DELEGATE,
3983 base::Bind(&AsyncLoggingNetworkDelegate::SetAuthAndResume,
3984 callback, credentials));
3985 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
3988 private:
3989 static int RunCallbackAsynchronously(
3990 URLRequest* request,
3991 const CompletionCallback& callback) {
3992 AsyncDelegateLogger::Run(
3993 request,
3994 LOAD_STATE_WAITING_FOR_DELEGATE,
3995 LOAD_STATE_WAITING_FOR_DELEGATE,
3996 LOAD_STATE_WAITING_FOR_DELEGATE,
3997 base::Bind(callback, OK));
3998 return ERR_IO_PENDING;
4001 static void SetAuthAndResume(const AuthCallback& callback,
4002 AuthCredentials* credentials) {
4003 *credentials = AuthCredentials(kUser, kSecret);
4004 callback.Run(NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4007 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingNetworkDelegate);
4010 // URLRequest::Delegate that logs delegate information when the headers
4011 // are received, when each read completes, and during redirects. Uses
4012 // AsyncDelegateLogger. Can optionally cancel a request in any phase.
4014 // Inherits from TestDelegate to reuse the TestDelegate code to handle
4015 // advancing to the next step in most cases, as well as cancellation.
4016 class AsyncLoggingUrlRequestDelegate : public TestDelegate {
4017 public:
4018 enum CancelStage {
4019 NO_CANCEL = 0,
4020 CANCEL_ON_RECEIVED_REDIRECT,
4021 CANCEL_ON_RESPONSE_STARTED,
4022 CANCEL_ON_READ_COMPLETED
4025 explicit AsyncLoggingUrlRequestDelegate(CancelStage cancel_stage)
4026 : cancel_stage_(cancel_stage) {
4027 if (cancel_stage == CANCEL_ON_RECEIVED_REDIRECT)
4028 set_cancel_in_received_redirect(true);
4029 else if (cancel_stage == CANCEL_ON_RESPONSE_STARTED)
4030 set_cancel_in_response_started(true);
4031 else if (cancel_stage == CANCEL_ON_READ_COMPLETED)
4032 set_cancel_in_received_data(true);
4034 virtual ~AsyncLoggingUrlRequestDelegate() {}
4036 // URLRequest::Delegate implementation:
4037 void virtual OnReceivedRedirect(URLRequest* request,
4038 const GURL& new_url,
4039 bool* defer_redirect) OVERRIDE {
4040 *defer_redirect = true;
4041 AsyncDelegateLogger::Run(
4042 request,
4043 LOAD_STATE_WAITING_FOR_DELEGATE,
4044 LOAD_STATE_WAITING_FOR_DELEGATE,
4045 LOAD_STATE_WAITING_FOR_DELEGATE,
4046 base::Bind(
4047 &AsyncLoggingUrlRequestDelegate::OnReceivedRedirectLoggingComplete,
4048 base::Unretained(this), request, new_url));
4051 virtual void OnResponseStarted(URLRequest* request) OVERRIDE {
4052 AsyncDelegateLogger::Run(
4053 request,
4054 LOAD_STATE_WAITING_FOR_DELEGATE,
4055 LOAD_STATE_WAITING_FOR_DELEGATE,
4056 LOAD_STATE_WAITING_FOR_DELEGATE,
4057 base::Bind(
4058 &AsyncLoggingUrlRequestDelegate::OnResponseStartedLoggingComplete,
4059 base::Unretained(this), request));
4062 virtual void OnReadCompleted(URLRequest* request,
4063 int bytes_read) OVERRIDE {
4064 AsyncDelegateLogger::Run(
4065 request,
4066 LOAD_STATE_IDLE,
4067 LOAD_STATE_IDLE,
4068 LOAD_STATE_IDLE,
4069 base::Bind(
4070 &AsyncLoggingUrlRequestDelegate::AfterReadCompletedLoggingComplete,
4071 base::Unretained(this), request, bytes_read));
4074 private:
4075 void OnReceivedRedirectLoggingComplete(URLRequest* request,
4076 const GURL& new_url) {
4077 bool defer_redirect = false;
4078 TestDelegate::OnReceivedRedirect(request, new_url, &defer_redirect);
4079 // FollowDeferredRedirect should not be called after cancellation.
4080 if (cancel_stage_ == CANCEL_ON_RECEIVED_REDIRECT)
4081 return;
4082 if (!defer_redirect)
4083 request->FollowDeferredRedirect();
4086 void OnResponseStartedLoggingComplete(URLRequest* request) {
4087 // The parent class continues the request.
4088 TestDelegate::OnResponseStarted(request);
4091 void AfterReadCompletedLoggingComplete(URLRequest* request, int bytes_read) {
4092 // The parent class continues the request.
4093 TestDelegate::OnReadCompleted(request, bytes_read);
4096 const CancelStage cancel_stage_;
4098 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingUrlRequestDelegate);
4101 // Tests handling of delegate info before a request starts.
4102 TEST_F(URLRequestTestHTTP, DelegateInfoBeforeStart) {
4103 ASSERT_TRUE(test_server_.Start());
4105 TestDelegate request_delegate;
4106 TestURLRequestContext context(true);
4107 context.set_network_delegate(NULL);
4108 context.set_net_log(&net_log_);
4109 context.Init();
4112 URLRequest r(test_server_.GetURL("empty.html"),
4113 DEFAULT_PRIORITY,
4114 &request_delegate,
4115 &context);
4116 LoadStateWithParam load_state = r.GetLoadState();
4117 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
4118 EXPECT_EQ(base::string16(), load_state.param);
4120 AsyncDelegateLogger::Run(
4122 LOAD_STATE_WAITING_FOR_DELEGATE,
4123 LOAD_STATE_WAITING_FOR_DELEGATE,
4124 LOAD_STATE_IDLE,
4125 base::Bind(&URLRequest::Start, base::Unretained(&r)));
4127 base::RunLoop().Run();
4129 EXPECT_EQ(200, r.GetResponseCode());
4130 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
4133 CapturingNetLog::CapturedEntryList entries;
4134 net_log_.GetEntries(&entries);
4135 size_t log_position = ExpectLogContainsSomewhereAfter(
4136 entries,
4138 NetLog::TYPE_DELEGATE_INFO,
4139 NetLog::PHASE_BEGIN);
4141 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries, log_position);
4143 // Nothing else should add any delegate info to the request.
4144 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4145 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4148 // Tests handling of delegate info from a network delegate.
4149 TEST_F(URLRequestTestHTTP, NetworkDelegateInfo) {
4150 ASSERT_TRUE(test_server_.Start());
4152 TestDelegate request_delegate;
4153 AsyncLoggingNetworkDelegate network_delegate;
4154 TestURLRequestContext context(true);
4155 context.set_network_delegate(&network_delegate);
4156 context.set_net_log(&net_log_);
4157 context.Init();
4160 URLRequest r(test_server_.GetURL("simple.html"),
4161 DEFAULT_PRIORITY,
4162 &request_delegate,
4163 &context);
4164 LoadStateWithParam load_state = r.GetLoadState();
4165 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
4166 EXPECT_EQ(base::string16(), load_state.param);
4168 r.Start();
4169 base::RunLoop().Run();
4171 EXPECT_EQ(200, r.GetResponseCode());
4172 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
4173 EXPECT_EQ(1, network_delegate.created_requests());
4174 EXPECT_EQ(0, network_delegate.destroyed_requests());
4176 EXPECT_EQ(1, network_delegate.destroyed_requests());
4178 size_t log_position = 0;
4179 CapturingNetLog::CapturedEntryList entries;
4180 net_log_.GetEntries(&entries);
4181 for (size_t i = 0; i < 3; ++i) {
4182 log_position = ExpectLogContainsSomewhereAfter(
4183 entries,
4184 log_position + 1,
4185 NetLog::TYPE_URL_REQUEST_DELEGATE,
4186 NetLog::PHASE_BEGIN);
4188 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4189 log_position + 1);
4191 ASSERT_LT(log_position, entries.size());
4192 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4193 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4195 if (i == 1) {
4196 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4197 entries, log_position + 1);
4201 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4202 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4205 // Tests handling of delegate info from a network delegate in the case of an
4206 // HTTP redirect.
4207 TEST_F(URLRequestTestHTTP, NetworkDelegateInfoRedirect) {
4208 ASSERT_TRUE(test_server_.Start());
4210 TestDelegate request_delegate;
4211 AsyncLoggingNetworkDelegate network_delegate;
4212 TestURLRequestContext context(true);
4213 context.set_network_delegate(&network_delegate);
4214 context.set_net_log(&net_log_);
4215 context.Init();
4218 URLRequest r(test_server_.GetURL("server-redirect?simple.html"),
4219 DEFAULT_PRIORITY,
4220 &request_delegate,
4221 &context);
4222 LoadStateWithParam load_state = r.GetLoadState();
4223 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
4224 EXPECT_EQ(base::string16(), load_state.param);
4226 r.Start();
4227 base::RunLoop().Run();
4229 EXPECT_EQ(200, r.GetResponseCode());
4230 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
4231 EXPECT_EQ(2, network_delegate.created_requests());
4232 EXPECT_EQ(0, network_delegate.destroyed_requests());
4234 EXPECT_EQ(1, network_delegate.destroyed_requests());
4236 size_t log_position = 0;
4237 CapturingNetLog::CapturedEntryList entries;
4238 net_log_.GetEntries(&entries);
4239 // The NetworkDelegate logged information in OnBeforeURLRequest,
4240 // OnBeforeSendHeaders, and OnHeadersReceived.
4241 for (size_t i = 0; i < 3; ++i) {
4242 log_position = ExpectLogContainsSomewhereAfter(
4243 entries,
4244 log_position + 1,
4245 NetLog::TYPE_URL_REQUEST_DELEGATE,
4246 NetLog::PHASE_BEGIN);
4248 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4249 log_position + 1);
4251 ASSERT_LT(log_position, entries.size());
4252 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4253 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4255 if (i == 1) {
4256 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4257 entries, log_position + 1);
4261 // The URLRequest::Delegate then gets informed about the redirect.
4262 log_position = ExpectLogContainsSomewhereAfter(
4263 entries,
4264 log_position + 1,
4265 NetLog::TYPE_URL_REQUEST_DELEGATE,
4266 NetLog::PHASE_BEGIN);
4268 // The NetworkDelegate logged information in the same three events as before.
4269 for (size_t i = 0; i < 3; ++i) {
4270 log_position = ExpectLogContainsSomewhereAfter(
4271 entries,
4272 log_position + 1,
4273 NetLog::TYPE_URL_REQUEST_DELEGATE,
4274 NetLog::PHASE_BEGIN);
4276 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4277 log_position + 1);
4279 ASSERT_LT(log_position, entries.size());
4280 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4281 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4284 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4285 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4288 // Tests handling of delegate info from a network delegate in the case of HTTP
4289 // AUTH.
4290 TEST_F(URLRequestTestHTTP, NetworkDelegateInfoAuth) {
4291 ASSERT_TRUE(test_server_.Start());
4293 TestDelegate request_delegate;
4294 AsyncLoggingNetworkDelegate network_delegate;
4295 TestURLRequestContext context(true);
4296 context.set_network_delegate(&network_delegate);
4297 context.set_net_log(&net_log_);
4298 context.Init();
4301 URLRequest r(test_server_.GetURL("auth-basic"),
4302 DEFAULT_PRIORITY,
4303 &request_delegate,
4304 &context);
4305 LoadStateWithParam load_state = r.GetLoadState();
4306 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
4307 EXPECT_EQ(base::string16(), load_state.param);
4309 r.Start();
4310 base::RunLoop().Run();
4312 EXPECT_EQ(200, r.GetResponseCode());
4313 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
4314 EXPECT_EQ(1, network_delegate.created_requests());
4315 EXPECT_EQ(0, network_delegate.destroyed_requests());
4317 EXPECT_EQ(1, network_delegate.destroyed_requests());
4319 size_t log_position = 0;
4320 CapturingNetLog::CapturedEntryList entries;
4321 net_log_.GetEntries(&entries);
4322 // The NetworkDelegate should have logged information in OnBeforeURLRequest,
4323 // OnBeforeSendHeaders, OnHeadersReceived, OnAuthRequired, and then again in
4324 // OnBeforeURLRequest and OnBeforeSendHeaders.
4325 for (size_t i = 0; i < 6; ++i) {
4326 log_position = ExpectLogContainsSomewhereAfter(
4327 entries,
4328 log_position + 1,
4329 NetLog::TYPE_URL_REQUEST_DELEGATE,
4330 NetLog::PHASE_BEGIN);
4332 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4333 log_position + 1);
4335 ASSERT_LT(log_position, entries.size());
4336 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4337 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4339 if (i == 1) {
4340 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4341 entries, log_position + 1);
4345 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4346 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4349 // Tests handling of delegate info from a URLRequest::Delegate.
4350 TEST_F(URLRequestTestHTTP, URLRequestDelegateInfo) {
4351 ASSERT_TRUE(test_server_.Start());
4353 AsyncLoggingUrlRequestDelegate request_delegate(
4354 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
4355 TestURLRequestContext context(true);
4356 context.set_network_delegate(NULL);
4357 context.set_net_log(&net_log_);
4358 context.Init();
4361 // A chunked response with delays between chunks is used to make sure that
4362 // attempts by the URLRequest delegate to log information while reading the
4363 // body are ignored. Since they are ignored, this test is robust against
4364 // the possibility of multiple reads being combined in the unlikely event
4365 // that it occurs.
4366 URLRequest r(test_server_.GetURL("chunked?waitBetweenChunks=20"),
4367 DEFAULT_PRIORITY,
4368 &request_delegate,
4369 &context);
4370 LoadStateWithParam load_state = r.GetLoadState();
4371 r.Start();
4372 base::RunLoop().Run();
4374 EXPECT_EQ(200, r.GetResponseCode());
4375 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
4378 CapturingNetLog::CapturedEntryList entries;
4379 net_log_.GetEntries(&entries);
4381 size_t log_position = 0;
4383 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4384 entries, log_position);
4386 // The delegate info should only have been logged on header complete. Other
4387 // times it should silently be ignored.
4388 log_position =
4389 ExpectLogContainsSomewhereAfter(entries,
4390 log_position + 1,
4391 NetLog::TYPE_URL_REQUEST_DELEGATE,
4392 NetLog::PHASE_BEGIN);
4394 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4395 log_position + 1);
4397 ASSERT_LT(log_position, entries.size());
4398 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4399 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4401 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4402 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4403 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4404 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
4407 // Tests handling of delegate info from a URLRequest::Delegate in the case of
4408 // an HTTP redirect.
4409 TEST_F(URLRequestTestHTTP, URLRequestDelegateInfoOnRedirect) {
4410 ASSERT_TRUE(test_server_.Start());
4412 AsyncLoggingUrlRequestDelegate request_delegate(
4413 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
4414 TestURLRequestContext context(true);
4415 context.set_network_delegate(NULL);
4416 context.set_net_log(&net_log_);
4417 context.Init();
4420 URLRequest r(test_server_.GetURL("server-redirect?simple.html"),
4421 DEFAULT_PRIORITY,
4422 &request_delegate,
4423 &context);
4424 LoadStateWithParam load_state = r.GetLoadState();
4425 r.Start();
4426 base::RunLoop().Run();
4428 EXPECT_EQ(200, r.GetResponseCode());
4429 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
4432 CapturingNetLog::CapturedEntryList entries;
4433 net_log_.GetEntries(&entries);
4435 // Delegate info should only have been logged in OnReceivedRedirect and
4436 // OnResponseStarted.
4437 size_t log_position = 0;
4438 for (int i = 0; i < 2; ++i) {
4439 if (i == 0) {
4440 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4441 entries, log_position) + 1;
4444 log_position = ExpectLogContainsSomewhereAfter(
4445 entries,
4446 log_position,
4447 NetLog::TYPE_URL_REQUEST_DELEGATE,
4448 NetLog::PHASE_BEGIN);
4450 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4451 log_position + 1);
4453 ASSERT_LT(log_position, entries.size());
4454 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4455 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4458 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4459 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4460 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4461 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
4464 // Tests handling of delegate info from a URLRequest::Delegate in the case of
4465 // an HTTP redirect, with cancellation at various points.
4466 TEST_F(URLRequestTestHTTP, URLRequestDelegateOnRedirectCancelled) {
4467 ASSERT_TRUE(test_server_.Start());
4469 const AsyncLoggingUrlRequestDelegate::CancelStage kCancelStages[] = {
4470 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RECEIVED_REDIRECT,
4471 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RESPONSE_STARTED,
4472 AsyncLoggingUrlRequestDelegate::CANCEL_ON_READ_COMPLETED,
4475 for (size_t test_case = 0; test_case < arraysize(kCancelStages);
4476 ++test_case) {
4477 AsyncLoggingUrlRequestDelegate request_delegate(kCancelStages[test_case]);
4478 TestURLRequestContext context(true);
4479 CapturingNetLog net_log;
4480 context.set_network_delegate(NULL);
4481 context.set_net_log(&net_log);
4482 context.Init();
4485 URLRequest r(test_server_.GetURL("server-redirect?simple.html"),
4486 DEFAULT_PRIORITY,
4487 &request_delegate,
4488 &context);
4489 LoadStateWithParam load_state = r.GetLoadState();
4490 r.Start();
4491 base::RunLoop().Run();
4492 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
4495 CapturingNetLog::CapturedEntryList entries;
4496 net_log.GetEntries(&entries);
4498 // Delegate info is always logged in both OnReceivedRedirect and
4499 // OnResponseStarted. In the CANCEL_ON_RECEIVED_REDIRECT, the
4500 // OnResponseStarted delegate call is after cancellation, but logging is
4501 // still currently supported in that call.
4502 size_t log_position = 0;
4503 for (int i = 0; i < 2; ++i) {
4504 if (i == 0) {
4505 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4506 entries, log_position) + 1;
4509 log_position = ExpectLogContainsSomewhereAfter(
4510 entries,
4511 log_position,
4512 NetLog::TYPE_URL_REQUEST_DELEGATE,
4513 NetLog::PHASE_BEGIN);
4515 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4516 log_position + 1);
4518 ASSERT_LT(log_position, entries.size());
4519 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4520 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4523 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4524 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4525 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4526 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
4530 namespace {
4532 const char kExtraHeader[] = "Allow-Snafu";
4533 const char kExtraValue[] = "fubar";
4535 class RedirectWithAdditionalHeadersDelegate : public TestDelegate {
4536 virtual void OnReceivedRedirect(net::URLRequest* request,
4537 const GURL& new_url,
4538 bool* defer_redirect) OVERRIDE {
4539 TestDelegate::OnReceivedRedirect(request, new_url, defer_redirect);
4540 request->SetExtraRequestHeaderByName(kExtraHeader, kExtraValue, false);
4544 } // namespace
4546 TEST_F(URLRequestTestHTTP, RedirectWithAdditionalHeadersTest) {
4547 ASSERT_TRUE(test_server_.Start());
4549 GURL destination_url = test_server_.GetURL(
4550 "echoheader?" + std::string(kExtraHeader));
4551 GURL original_url = test_server_.GetURL(
4552 "server-redirect?" + destination_url.spec());
4553 RedirectWithAdditionalHeadersDelegate d;
4554 URLRequest req(original_url, DEFAULT_PRIORITY, &d, &default_context_);
4555 req.Start();
4556 base::RunLoop().Run();
4558 std::string value;
4559 const HttpRequestHeaders& headers = req.extra_request_headers();
4560 EXPECT_TRUE(headers.GetHeader(kExtraHeader, &value));
4561 EXPECT_EQ(kExtraValue, value);
4562 EXPECT_FALSE(req.is_pending());
4563 EXPECT_FALSE(req.is_redirecting());
4564 EXPECT_EQ(kExtraValue, d.data_received());
4567 namespace {
4569 const char kExtraHeaderToRemove[] = "To-Be-Removed";
4571 class RedirectWithHeaderRemovalDelegate : public TestDelegate {
4572 virtual void OnReceivedRedirect(net::URLRequest* request,
4573 const GURL& new_url,
4574 bool* defer_redirect) OVERRIDE {
4575 TestDelegate::OnReceivedRedirect(request, new_url, defer_redirect);
4576 request->RemoveRequestHeaderByName(kExtraHeaderToRemove);
4580 } // namespace
4582 TEST_F(URLRequestTestHTTP, RedirectWithHeaderRemovalTest) {
4583 ASSERT_TRUE(test_server_.Start());
4585 GURL destination_url = test_server_.GetURL(
4586 "echoheader?" + std::string(kExtraHeaderToRemove));
4587 GURL original_url = test_server_.GetURL(
4588 "server-redirect?" + destination_url.spec());
4589 RedirectWithHeaderRemovalDelegate d;
4590 URLRequest req(original_url, DEFAULT_PRIORITY, &d, &default_context_);
4591 req.SetExtraRequestHeaderByName(kExtraHeaderToRemove, "dummy", false);
4592 req.Start();
4593 base::RunLoop().Run();
4595 std::string value;
4596 const HttpRequestHeaders& headers = req.extra_request_headers();
4597 EXPECT_FALSE(headers.GetHeader(kExtraHeaderToRemove, &value));
4598 EXPECT_FALSE(req.is_pending());
4599 EXPECT_FALSE(req.is_redirecting());
4600 EXPECT_EQ("None", d.data_received());
4603 TEST_F(URLRequestTestHTTP, CancelTest) {
4604 TestDelegate d;
4606 URLRequest r(GURL("http://www.google.com/"),
4607 DEFAULT_PRIORITY,
4609 &default_context_);
4611 r.Start();
4612 EXPECT_TRUE(r.is_pending());
4614 r.Cancel();
4616 base::RunLoop().Run();
4618 // We expect to receive OnResponseStarted even though the request has been
4619 // cancelled.
4620 EXPECT_EQ(1, d.response_started_count());
4621 EXPECT_EQ(0, d.bytes_received());
4622 EXPECT_FALSE(d.received_data_before_response());
4626 TEST_F(URLRequestTestHTTP, CancelTest2) {
4627 ASSERT_TRUE(test_server_.Start());
4629 TestDelegate d;
4631 URLRequest r(test_server_.GetURL(std::string()),
4632 DEFAULT_PRIORITY,
4634 &default_context_);
4636 d.set_cancel_in_response_started(true);
4638 r.Start();
4639 EXPECT_TRUE(r.is_pending());
4641 base::RunLoop().Run();
4643 EXPECT_EQ(1, d.response_started_count());
4644 EXPECT_EQ(0, d.bytes_received());
4645 EXPECT_FALSE(d.received_data_before_response());
4646 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
4650 TEST_F(URLRequestTestHTTP, CancelTest3) {
4651 ASSERT_TRUE(test_server_.Start());
4653 TestDelegate d;
4655 URLRequest r(test_server_.GetURL(std::string()),
4656 DEFAULT_PRIORITY,
4658 &default_context_);
4660 d.set_cancel_in_received_data(true);
4662 r.Start();
4663 EXPECT_TRUE(r.is_pending());
4665 base::RunLoop().Run();
4667 EXPECT_EQ(1, d.response_started_count());
4668 // There is no guarantee about how much data was received
4669 // before the cancel was issued. It could have been 0 bytes,
4670 // or it could have been all the bytes.
4671 // EXPECT_EQ(0, d.bytes_received());
4672 EXPECT_FALSE(d.received_data_before_response());
4673 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
4677 TEST_F(URLRequestTestHTTP, CancelTest4) {
4678 ASSERT_TRUE(test_server_.Start());
4680 TestDelegate d;
4682 URLRequest r(test_server_.GetURL(std::string()),
4683 DEFAULT_PRIORITY,
4685 &default_context_);
4687 r.Start();
4688 EXPECT_TRUE(r.is_pending());
4690 // The request will be implicitly canceled when it is destroyed. The
4691 // test delegate must not post a quit message when this happens because
4692 // this test doesn't actually have a message loop. The quit message would
4693 // get put on this thread's message queue and the next test would exit
4694 // early, causing problems.
4695 d.set_quit_on_complete(false);
4697 // expect things to just cleanup properly.
4699 // we won't actually get a received reponse here because we've never run the
4700 // message loop
4701 EXPECT_FALSE(d.received_data_before_response());
4702 EXPECT_EQ(0, d.bytes_received());
4705 TEST_F(URLRequestTestHTTP, CancelTest5) {
4706 ASSERT_TRUE(test_server_.Start());
4708 // populate cache
4710 TestDelegate d;
4711 URLRequest r(test_server_.GetURL("cachetime"),
4712 DEFAULT_PRIORITY,
4714 &default_context_);
4715 r.Start();
4716 base::RunLoop().Run();
4717 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
4720 // cancel read from cache (see bug 990242)
4722 TestDelegate d;
4723 URLRequest r(test_server_.GetURL("cachetime"),
4724 DEFAULT_PRIORITY,
4726 &default_context_);
4727 r.Start();
4728 r.Cancel();
4729 base::RunLoop().Run();
4731 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
4732 EXPECT_EQ(1, d.response_started_count());
4733 EXPECT_EQ(0, d.bytes_received());
4734 EXPECT_FALSE(d.received_data_before_response());
4738 TEST_F(URLRequestTestHTTP, PostTest) {
4739 ASSERT_TRUE(test_server_.Start());
4740 HTTPUploadDataOperationTest("POST");
4743 TEST_F(URLRequestTestHTTP, PutTest) {
4744 ASSERT_TRUE(test_server_.Start());
4745 HTTPUploadDataOperationTest("PUT");
4748 TEST_F(URLRequestTestHTTP, PostEmptyTest) {
4749 ASSERT_TRUE(test_server_.Start());
4751 TestDelegate d;
4753 URLRequest r(
4754 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, &default_context_);
4755 r.set_method("POST");
4757 r.Start();
4758 EXPECT_TRUE(r.is_pending());
4760 base::RunLoop().Run();
4762 ASSERT_EQ(1, d.response_started_count())
4763 << "request failed: " << r.status().status()
4764 << ", error: " << r.status().error();
4766 EXPECT_FALSE(d.received_data_before_response());
4767 EXPECT_TRUE(d.data_received().empty());
4771 TEST_F(URLRequestTestHTTP, PostFileTest) {
4772 ASSERT_TRUE(test_server_.Start());
4774 TestDelegate d;
4776 URLRequest r(
4777 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, &default_context_);
4778 r.set_method("POST");
4780 base::FilePath dir;
4781 PathService::Get(base::DIR_EXE, &dir);
4782 base::SetCurrentDirectory(dir);
4784 ScopedVector<UploadElementReader> element_readers;
4786 base::FilePath path;
4787 PathService::Get(base::DIR_SOURCE_ROOT, &path);
4788 path = path.Append(FILE_PATH_LITERAL("net"));
4789 path = path.Append(FILE_PATH_LITERAL("data"));
4790 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
4791 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
4792 element_readers.push_back(
4793 new UploadFileElementReader(base::MessageLoopProxy::current().get(),
4794 path,
4796 kuint64max,
4797 base::Time()));
4798 r.set_upload(make_scoped_ptr(
4799 new UploadDataStream(element_readers.Pass(), 0)));
4801 r.Start();
4802 EXPECT_TRUE(r.is_pending());
4804 base::RunLoop().Run();
4806 int64 size = 0;
4807 ASSERT_EQ(true, base::GetFileSize(path, &size));
4808 scoped_ptr<char[]> buf(new char[size]);
4810 ASSERT_EQ(size, base::ReadFile(path, buf.get(), size));
4812 ASSERT_EQ(1, d.response_started_count())
4813 << "request failed: " << r.status().status()
4814 << ", error: " << r.status().error();
4816 EXPECT_FALSE(d.received_data_before_response());
4818 EXPECT_EQ(size, d.bytes_received());
4819 EXPECT_EQ(std::string(&buf[0], size), d.data_received());
4823 TEST_F(URLRequestTestHTTP, PostUnreadableFileTest) {
4824 ASSERT_TRUE(test_server_.Start());
4826 TestDelegate d;
4828 URLRequest r(test_server_.GetURL("echo"), DEFAULT_PRIORITY,
4829 &d, &default_context_);
4830 r.set_method("POST");
4832 ScopedVector<UploadElementReader> element_readers;
4834 element_readers.push_back(new UploadFileElementReader(
4835 base::MessageLoopProxy::current().get(),
4836 base::FilePath(FILE_PATH_LITERAL(
4837 "c:\\path\\to\\non\\existant\\file.randomness.12345")),
4839 kuint64max,
4840 base::Time()));
4841 r.set_upload(make_scoped_ptr(
4842 new UploadDataStream(element_readers.Pass(), 0)));
4844 r.Start();
4845 EXPECT_TRUE(r.is_pending());
4847 base::RunLoop().Run();
4849 EXPECT_TRUE(d.request_failed());
4850 EXPECT_FALSE(d.received_data_before_response());
4851 EXPECT_EQ(0, d.bytes_received());
4852 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
4853 EXPECT_EQ(ERR_FILE_NOT_FOUND, r.status().error());
4857 TEST_F(URLRequestTestHTTP, TestPostChunkedDataBeforeStart) {
4858 ASSERT_TRUE(test_server_.Start());
4860 TestDelegate d;
4862 URLRequest r(
4863 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, &default_context_);
4864 r.EnableChunkedUpload();
4865 r.set_method("POST");
4866 AddChunksToUpload(&r);
4867 r.Start();
4868 EXPECT_TRUE(r.is_pending());
4870 base::RunLoop().Run();
4872 VerifyReceivedDataMatchesChunks(&r, &d);
4876 TEST_F(URLRequestTestHTTP, TestPostChunkedDataJustAfterStart) {
4877 ASSERT_TRUE(test_server_.Start());
4879 TestDelegate d;
4881 URLRequest r(
4882 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, &default_context_);
4883 r.EnableChunkedUpload();
4884 r.set_method("POST");
4885 r.Start();
4886 EXPECT_TRUE(r.is_pending());
4887 AddChunksToUpload(&r);
4888 base::RunLoop().Run();
4890 VerifyReceivedDataMatchesChunks(&r, &d);
4894 TEST_F(URLRequestTestHTTP, TestPostChunkedDataAfterStart) {
4895 ASSERT_TRUE(test_server_.Start());
4897 TestDelegate d;
4899 URLRequest r(
4900 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, &default_context_);
4901 r.EnableChunkedUpload();
4902 r.set_method("POST");
4903 r.Start();
4904 EXPECT_TRUE(r.is_pending());
4906 base::RunLoop().RunUntilIdle();
4907 AddChunksToUpload(&r);
4908 base::RunLoop().Run();
4910 VerifyReceivedDataMatchesChunks(&r, &d);
4914 TEST_F(URLRequestTestHTTP, ResponseHeadersTest) {
4915 ASSERT_TRUE(test_server_.Start());
4917 TestDelegate d;
4918 URLRequest req(test_server_.GetURL("files/with-headers.html"),
4919 DEFAULT_PRIORITY,
4921 &default_context_);
4922 req.Start();
4923 base::RunLoop().Run();
4925 const HttpResponseHeaders* headers = req.response_headers();
4927 // Simple sanity check that response_info() accesses the same data.
4928 EXPECT_EQ(headers, req.response_info().headers.get());
4930 std::string header;
4931 EXPECT_TRUE(headers->GetNormalizedHeader("cache-control", &header));
4932 EXPECT_EQ("private", header);
4934 header.clear();
4935 EXPECT_TRUE(headers->GetNormalizedHeader("content-type", &header));
4936 EXPECT_EQ("text/html; charset=ISO-8859-1", header);
4938 // The response has two "X-Multiple-Entries" headers.
4939 // This verfies our output has them concatenated together.
4940 header.clear();
4941 EXPECT_TRUE(headers->GetNormalizedHeader("x-multiple-entries", &header));
4942 EXPECT_EQ("a, b", header);
4945 TEST_F(URLRequestTestHTTP, ProcessSTS) {
4946 SpawnedTestServer::SSLOptions ssl_options;
4947 SpawnedTestServer https_test_server(
4948 SpawnedTestServer::TYPE_HTTPS,
4949 ssl_options,
4950 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
4951 ASSERT_TRUE(https_test_server.Start());
4953 TestDelegate d;
4954 URLRequest request(https_test_server.GetURL("files/hsts-headers.html"),
4955 DEFAULT_PRIORITY,
4957 &default_context_);
4958 request.Start();
4959 base::RunLoop().Run();
4961 TransportSecurityState* security_state =
4962 default_context_.transport_security_state();
4963 bool sni_available = true;
4964 TransportSecurityState::DomainState domain_state;
4965 EXPECT_TRUE(security_state->GetDomainState(
4966 SpawnedTestServer::kLocalhost, sni_available, &domain_state));
4967 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
4968 domain_state.upgrade_mode);
4969 EXPECT_TRUE(domain_state.sts_include_subdomains);
4970 EXPECT_FALSE(domain_state.pkp_include_subdomains);
4971 #if defined(OS_ANDROID)
4972 // Android's CertVerifyProc does not (yet) handle pins.
4973 #else
4974 EXPECT_FALSE(domain_state.HasPublicKeyPins());
4975 #endif
4978 // Android's CertVerifyProc does not (yet) handle pins. Therefore, it will
4979 // reject HPKP headers, and a test setting only HPKP headers will fail (no
4980 // DomainState present because header rejected).
4981 #if defined(OS_ANDROID)
4982 #define MAYBE_ProcessPKP DISABLED_ProcessPKP
4983 #else
4984 #define MAYBE_ProcessPKP ProcessPKP
4985 #endif
4987 // Tests that enabling HPKP on a domain does not affect the HSTS
4988 // validity/expiration.
4989 TEST_F(URLRequestTestHTTP, MAYBE_ProcessPKP) {
4990 SpawnedTestServer::SSLOptions ssl_options;
4991 SpawnedTestServer https_test_server(
4992 SpawnedTestServer::TYPE_HTTPS,
4993 ssl_options,
4994 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
4995 ASSERT_TRUE(https_test_server.Start());
4997 TestDelegate d;
4998 URLRequest request(https_test_server.GetURL("files/hpkp-headers.html"),
4999 DEFAULT_PRIORITY,
5001 &default_context_);
5002 request.Start();
5003 base::RunLoop().Run();
5005 TransportSecurityState* security_state =
5006 default_context_.transport_security_state();
5007 bool sni_available = true;
5008 TransportSecurityState::DomainState domain_state;
5009 EXPECT_TRUE(security_state->GetDomainState(
5010 SpawnedTestServer::kLocalhost, sni_available, &domain_state));
5011 EXPECT_EQ(TransportSecurityState::DomainState::MODE_DEFAULT,
5012 domain_state.upgrade_mode);
5013 EXPECT_FALSE(domain_state.sts_include_subdomains);
5014 EXPECT_FALSE(domain_state.pkp_include_subdomains);
5015 EXPECT_TRUE(domain_state.HasPublicKeyPins());
5016 EXPECT_NE(domain_state.upgrade_expiry,
5017 domain_state.dynamic_spki_hashes_expiry);
5020 TEST_F(URLRequestTestHTTP, ProcessSTSOnce) {
5021 SpawnedTestServer::SSLOptions ssl_options;
5022 SpawnedTestServer https_test_server(
5023 SpawnedTestServer::TYPE_HTTPS,
5024 ssl_options,
5025 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5026 ASSERT_TRUE(https_test_server.Start());
5028 TestDelegate d;
5029 URLRequest request(
5030 https_test_server.GetURL("files/hsts-multiple-headers.html"),
5031 DEFAULT_PRIORITY,
5033 &default_context_);
5034 request.Start();
5035 base::RunLoop().Run();
5037 // We should have set parameters from the first header, not the second.
5038 TransportSecurityState* security_state =
5039 default_context_.transport_security_state();
5040 bool sni_available = true;
5041 TransportSecurityState::DomainState domain_state;
5042 EXPECT_TRUE(security_state->GetDomainState(
5043 SpawnedTestServer::kLocalhost, sni_available, &domain_state));
5044 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
5045 domain_state.upgrade_mode);
5046 EXPECT_FALSE(domain_state.sts_include_subdomains);
5047 EXPECT_FALSE(domain_state.pkp_include_subdomains);
5050 TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP) {
5051 SpawnedTestServer::SSLOptions ssl_options;
5052 SpawnedTestServer https_test_server(
5053 SpawnedTestServer::TYPE_HTTPS,
5054 ssl_options,
5055 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5056 ASSERT_TRUE(https_test_server.Start());
5058 TestDelegate d;
5059 URLRequest request(
5060 https_test_server.GetURL("files/hsts-and-hpkp-headers.html"),
5061 DEFAULT_PRIORITY,
5063 &default_context_);
5064 request.Start();
5065 base::RunLoop().Run();
5067 // We should have set parameters from the first header, not the second.
5068 TransportSecurityState* security_state =
5069 default_context_.transport_security_state();
5070 bool sni_available = true;
5071 TransportSecurityState::DomainState domain_state;
5072 EXPECT_TRUE(security_state->GetDomainState(
5073 SpawnedTestServer::kLocalhost, sni_available, &domain_state));
5074 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
5075 domain_state.upgrade_mode);
5076 #if defined(OS_ANDROID)
5077 // Android's CertVerifyProc does not (yet) handle pins.
5078 #else
5079 EXPECT_TRUE(domain_state.HasPublicKeyPins());
5080 #endif
5081 EXPECT_NE(domain_state.upgrade_expiry,
5082 domain_state.dynamic_spki_hashes_expiry);
5084 // Even though there is an HSTS header asserting includeSubdomains, it is
5085 // the *second* such header, and we MUST process only the first.
5086 EXPECT_FALSE(domain_state.sts_include_subdomains);
5087 // includeSubdomains does not occur in the test HPKP header.
5088 EXPECT_FALSE(domain_state.pkp_include_subdomains);
5091 // Tests that when multiple HPKP headers are present, asserting different
5092 // policies, that only the first such policy is processed.
5093 TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP2) {
5094 SpawnedTestServer::SSLOptions ssl_options;
5095 SpawnedTestServer https_test_server(
5096 SpawnedTestServer::TYPE_HTTPS,
5097 ssl_options,
5098 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5099 ASSERT_TRUE(https_test_server.Start());
5101 TestDelegate d;
5102 URLRequest request(
5103 https_test_server.GetURL("files/hsts-and-hpkp-headers2.html"),
5104 DEFAULT_PRIORITY,
5106 &default_context_);
5107 request.Start();
5108 base::RunLoop().Run();
5110 TransportSecurityState* security_state =
5111 default_context_.transport_security_state();
5112 bool sni_available = true;
5113 TransportSecurityState::DomainState domain_state;
5114 EXPECT_TRUE(security_state->GetDomainState(
5115 SpawnedTestServer::kLocalhost, sni_available, &domain_state));
5116 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
5117 domain_state.upgrade_mode);
5118 #if defined(OS_ANDROID)
5119 // Android's CertVerifyProc does not (yet) handle pins.
5120 #else
5121 EXPECT_TRUE(domain_state.HasPublicKeyPins());
5122 #endif
5123 EXPECT_NE(domain_state.upgrade_expiry,
5124 domain_state.dynamic_spki_hashes_expiry);
5126 EXPECT_TRUE(domain_state.sts_include_subdomains);
5127 EXPECT_FALSE(domain_state.pkp_include_subdomains);
5130 TEST_F(URLRequestTestHTTP, ContentTypeNormalizationTest) {
5131 ASSERT_TRUE(test_server_.Start());
5133 TestDelegate d;
5134 URLRequest req(test_server_.GetURL("files/content-type-normalization.html"),
5135 DEFAULT_PRIORITY,
5137 &default_context_);
5138 req.Start();
5139 base::RunLoop().Run();
5141 std::string mime_type;
5142 req.GetMimeType(&mime_type);
5143 EXPECT_EQ("text/html", mime_type);
5145 std::string charset;
5146 req.GetCharset(&charset);
5147 EXPECT_EQ("utf-8", charset);
5148 req.Cancel();
5151 TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictRedirects) {
5152 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
5153 GURL file_url("file:///foo.txt");
5154 GURL data_url("data:,foo");
5155 FileProtocolHandler file_protocol_handler(base::MessageLoopProxy::current());
5156 EXPECT_FALSE(file_protocol_handler.IsSafeRedirectTarget(file_url));
5157 DataProtocolHandler data_protocol_handler;
5158 EXPECT_FALSE(data_protocol_handler.IsSafeRedirectTarget(data_url));
5160 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
5161 EXPECT_FALSE(job_factory_.IsSafeRedirectTarget(file_url));
5162 EXPECT_FALSE(job_factory_.IsSafeRedirectTarget(data_url));
5165 TEST_F(URLRequestTestHTTP, RestrictFileRedirects) {
5166 ASSERT_TRUE(test_server_.Start());
5168 TestDelegate d;
5169 URLRequest req(test_server_.GetURL("files/redirect-to-file.html"),
5170 DEFAULT_PRIORITY,
5172 &default_context_);
5173 req.Start();
5174 base::RunLoop().Run();
5176 EXPECT_EQ(URLRequestStatus::FAILED, req.status().status());
5177 EXPECT_EQ(ERR_UNSAFE_REDIRECT, req.status().error());
5180 TEST_F(URLRequestTestHTTP, RestrictDataRedirects) {
5181 ASSERT_TRUE(test_server_.Start());
5183 TestDelegate d;
5184 URLRequest req(test_server_.GetURL("files/redirect-to-data.html"),
5185 DEFAULT_PRIORITY,
5187 &default_context_);
5188 req.Start();
5189 base::MessageLoop::current()->Run();
5191 EXPECT_EQ(URLRequestStatus::FAILED, req.status().status());
5192 EXPECT_EQ(ERR_UNSAFE_REDIRECT, req.status().error());
5195 TEST_F(URLRequestTestHTTP, RedirectToInvalidURL) {
5196 ASSERT_TRUE(test_server_.Start());
5198 TestDelegate d;
5199 URLRequest req(test_server_.GetURL("files/redirect-to-invalid-url.html"),
5200 DEFAULT_PRIORITY,
5202 &default_context_);
5203 req.Start();
5204 base::RunLoop().Run();
5206 EXPECT_EQ(URLRequestStatus::FAILED, req.status().status());
5207 EXPECT_EQ(ERR_INVALID_URL, req.status().error());
5210 // Make sure redirects are cached, despite not reading their bodies.
5211 TEST_F(URLRequestTestHTTP, CacheRedirect) {
5212 ASSERT_TRUE(test_server_.Start());
5213 GURL redirect_url =
5214 test_server_.GetURL("files/redirect302-to-echo-cacheable");
5217 TestDelegate d;
5218 URLRequest req(redirect_url, DEFAULT_PRIORITY, &d, &default_context_);
5219 req.Start();
5220 base::RunLoop().Run();
5221 EXPECT_EQ(URLRequestStatus::SUCCESS, req.status().status());
5222 EXPECT_EQ(1, d.received_redirect_count());
5223 EXPECT_EQ(test_server_.GetURL("echo"), req.url());
5227 TestDelegate d;
5228 d.set_quit_on_redirect(true);
5229 URLRequest req(redirect_url, DEFAULT_PRIORITY, &d, &default_context_);
5230 req.Start();
5231 base::RunLoop().Run();
5233 EXPECT_EQ(1, d.received_redirect_count());
5234 EXPECT_EQ(0, d.response_started_count());
5235 EXPECT_TRUE(req.was_cached());
5237 req.FollowDeferredRedirect();
5238 base::RunLoop().Run();
5239 EXPECT_EQ(1, d.received_redirect_count());
5240 EXPECT_EQ(1, d.response_started_count());
5241 EXPECT_EQ(URLRequestStatus::SUCCESS, req.status().status());
5242 EXPECT_EQ(test_server_.GetURL("echo"), req.url());
5246 // Make sure a request isn't cached when a NetworkDelegate forces a redirect
5247 // when the headers are read, since the body won't have been read.
5248 TEST_F(URLRequestTestHTTP, NoCacheOnNetworkDelegateRedirect) {
5249 ASSERT_TRUE(test_server_.Start());
5250 // URL that is normally cached.
5251 GURL initial_url = test_server_.GetURL("cachetime");
5254 // Set up the TestNetworkDelegate tp force a redirect.
5255 GURL redirect_to_url = test_server_.GetURL("echo");
5256 default_network_delegate_.set_redirect_on_headers_received_url(
5257 redirect_to_url);
5259 TestDelegate d;
5260 URLRequest req(initial_url, DEFAULT_PRIORITY, &d, &default_context_);
5261 req.Start();
5262 base::RunLoop().Run();
5263 EXPECT_EQ(URLRequestStatus::SUCCESS, req.status().status());
5264 EXPECT_EQ(1, d.received_redirect_count());
5265 EXPECT_EQ(redirect_to_url, req.url());
5269 TestDelegate d;
5270 URLRequest req(initial_url, DEFAULT_PRIORITY, &d, &default_context_);
5271 req.Start();
5272 base::RunLoop().Run();
5274 EXPECT_EQ(URLRequestStatus::SUCCESS, req.status().status());
5275 EXPECT_FALSE(req.was_cached());
5276 EXPECT_EQ(0, d.received_redirect_count());
5277 EXPECT_EQ(initial_url, req.url());
5281 // Tests that redirection to an unsafe URL is allowed when it has been marked as
5282 // safe.
5283 TEST_F(URLRequestTestHTTP, UnsafeRedirectToWhitelistedUnsafeURL) {
5284 ASSERT_TRUE(test_server_.Start());
5286 GURL unsafe_url("data:text/html,this-is-considered-an-unsafe-url");
5287 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
5288 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
5290 TestDelegate d;
5292 URLRequest r(test_server_.GetURL("whatever"),
5293 DEFAULT_PRIORITY,
5295 &default_context_);
5297 r.Start();
5298 base::RunLoop().Run();
5300 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
5302 EXPECT_EQ(2U, r.url_chain().size());
5303 EXPECT_EQ(net::OK, r.status().error());
5304 EXPECT_EQ(unsafe_url, r.url());
5305 EXPECT_EQ("this-is-considered-an-unsafe-url", d.data_received());
5309 // Tests that a redirect to a different unsafe URL is blocked, even after adding
5310 // some other URL to the whitelist.
5311 TEST_F(URLRequestTestHTTP, UnsafeRedirectToDifferentUnsafeURL) {
5312 ASSERT_TRUE(test_server_.Start());
5314 GURL unsafe_url("data:text/html,something");
5315 GURL different_unsafe_url("data:text/html,something-else");
5316 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
5317 default_network_delegate_.set_allowed_unsafe_redirect_url(
5318 different_unsafe_url);
5320 TestDelegate d;
5322 URLRequest r(test_server_.GetURL("whatever"),
5323 DEFAULT_PRIORITY,
5325 &default_context_);
5327 r.Start();
5328 base::RunLoop().Run();
5330 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
5331 EXPECT_EQ(ERR_UNSAFE_REDIRECT, r.status().error());
5335 // Redirects from an URL with fragment to an unsafe URL with fragment should
5336 // be allowed, and the reference fragment of the target URL should be preserved.
5337 TEST_F(URLRequestTestHTTP, UnsafeRedirectWithDifferentReferenceFragment) {
5338 ASSERT_TRUE(test_server_.Start());
5340 GURL original_url(test_server_.GetURL("original#fragment1"));
5341 GURL unsafe_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
5342 GURL expected_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
5344 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
5345 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
5347 TestDelegate d;
5349 URLRequest r(original_url, DEFAULT_PRIORITY, &d, &default_context_);
5351 r.Start();
5352 base::RunLoop().Run();
5354 EXPECT_EQ(2U, r.url_chain().size());
5355 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
5356 EXPECT_EQ(net::OK, r.status().error());
5357 EXPECT_EQ(original_url, r.original_url());
5358 EXPECT_EQ(expected_url, r.url());
5362 // When a delegate has specified a safe redirect URL, but it does not match the
5363 // redirect target, then do not prevent the reference fragment from being added.
5364 TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragmentAndUnrelatedUnsafeUrl) {
5365 ASSERT_TRUE(test_server_.Start());
5367 GURL original_url(test_server_.GetURL("original#expected-fragment"));
5368 GURL unsafe_url("data:text/html,this-url-does-not-match-redirect-url");
5369 GURL redirect_url(test_server_.GetURL("target"));
5370 GURL expected_redirect_url(test_server_.GetURL("target#expected-fragment"));
5372 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
5373 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
5375 TestDelegate d;
5377 URLRequest r(original_url, DEFAULT_PRIORITY, &d, &default_context_);
5379 r.Start();
5380 base::RunLoop().Run();
5382 EXPECT_EQ(2U, r.url_chain().size());
5383 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
5384 EXPECT_EQ(net::OK, r.status().error());
5385 EXPECT_EQ(original_url, r.original_url());
5386 EXPECT_EQ(expected_redirect_url, r.url());
5390 // When a delegate has specified a safe redirect URL, assume that the redirect
5391 // URL should not be changed. In particular, the reference fragment should not
5392 // be modified.
5393 TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragment) {
5394 ASSERT_TRUE(test_server_.Start());
5396 GURL original_url(test_server_.GetURL("original#should-not-be-appended"));
5397 GURL redirect_url("data:text/html,expect-no-reference-fragment");
5399 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
5400 default_network_delegate_.set_allowed_unsafe_redirect_url(redirect_url);
5402 TestDelegate d;
5404 URLRequest r(original_url, DEFAULT_PRIORITY, &d, &default_context_);
5406 r.Start();
5407 base::RunLoop().Run();
5409 EXPECT_EQ(2U, r.url_chain().size());
5410 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
5411 EXPECT_EQ(net::OK, r.status().error());
5412 EXPECT_EQ(original_url, r.original_url());
5413 EXPECT_EQ(redirect_url, r.url());
5417 // When a URLRequestRedirectJob is created, the redirection must be followed and
5418 // the reference fragment of the target URL must not be modified.
5419 TEST_F(URLRequestTestHTTP, RedirectJobWithReferenceFragment) {
5420 ASSERT_TRUE(test_server_.Start());
5422 GURL original_url(test_server_.GetURL("original#should-not-be-appended"));
5423 GURL redirect_url(test_server_.GetURL("echo"));
5425 TestDelegate d;
5426 URLRequest r(original_url, DEFAULT_PRIORITY, &d, &default_context_);
5428 URLRequestRedirectJob* job = new URLRequestRedirectJob(
5429 &r, &default_network_delegate_, redirect_url,
5430 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason");
5431 AddTestInterceptor()->set_main_intercept_job(job);
5433 r.Start();
5434 base::RunLoop().Run();
5436 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
5437 EXPECT_EQ(net::OK, r.status().error());
5438 EXPECT_EQ(original_url, r.original_url());
5439 EXPECT_EQ(redirect_url, r.url());
5442 TEST_F(URLRequestTestHTTP, NoUserPassInReferrer) {
5443 ASSERT_TRUE(test_server_.Start());
5445 TestDelegate d;
5446 URLRequest req(test_server_.GetURL("echoheader?Referer"),
5447 DEFAULT_PRIORITY,
5449 &default_context_);
5450 req.SetReferrer("http://user:pass@foo.com/");
5451 req.Start();
5452 base::RunLoop().Run();
5454 EXPECT_EQ(std::string("http://foo.com/"), d.data_received());
5457 TEST_F(URLRequestTestHTTP, NoFragmentInReferrer) {
5458 ASSERT_TRUE(test_server_.Start());
5460 TestDelegate d;
5461 URLRequest req(test_server_.GetURL("echoheader?Referer"),
5462 DEFAULT_PRIORITY,
5464 &default_context_);
5465 req.SetReferrer("http://foo.com/test#fragment");
5466 req.Start();
5467 base::RunLoop().Run();
5469 EXPECT_EQ(std::string("http://foo.com/test"), d.data_received());
5472 TEST_F(URLRequestTestHTTP, EmptyReferrerAfterValidReferrer) {
5473 ASSERT_TRUE(test_server_.Start());
5475 TestDelegate d;
5476 URLRequest req(test_server_.GetURL("echoheader?Referer"),
5477 DEFAULT_PRIORITY,
5479 &default_context_);
5480 req.SetReferrer("http://foo.com/test#fragment");
5481 req.SetReferrer("");
5482 req.Start();
5483 base::RunLoop().Run();
5485 EXPECT_EQ(std::string("None"), d.data_received());
5488 // Defer network start and then resume, checking that the request was a success
5489 // and bytes were received.
5490 TEST_F(URLRequestTestHTTP, DeferredBeforeNetworkStart) {
5491 ASSERT_TRUE(test_server_.Start());
5493 TestDelegate d;
5495 d.set_quit_on_network_start(true);
5496 GURL test_url(test_server_.GetURL("echo"));
5497 URLRequest req(test_url, DEFAULT_PRIORITY, &d, &default_context_);
5499 req.Start();
5500 base::RunLoop().Run();
5502 EXPECT_EQ(1, d.received_before_network_start_count());
5503 EXPECT_EQ(0, d.response_started_count());
5505 req.ResumeNetworkStart();
5506 base::RunLoop().Run();
5508 EXPECT_EQ(1, d.response_started_count());
5509 EXPECT_NE(0, d.bytes_received());
5510 EXPECT_EQ(URLRequestStatus::SUCCESS, req.status().status());
5514 // Check that OnBeforeNetworkStart is only called once even if there is a
5515 // redirect.
5516 TEST_F(URLRequestTestHTTP, BeforeNetworkStartCalledOnce) {
5517 ASSERT_TRUE(test_server_.Start());
5519 TestDelegate d;
5521 d.set_quit_on_redirect(true);
5522 d.set_quit_on_network_start(true);
5523 URLRequest req(test_server_.GetURL("server-redirect?echo"),
5524 DEFAULT_PRIORITY,
5526 &default_context_);
5528 req.Start();
5529 base::RunLoop().Run();
5531 EXPECT_EQ(1, d.received_before_network_start_count());
5532 EXPECT_EQ(0, d.response_started_count());
5533 EXPECT_EQ(0, d.received_redirect_count());
5535 req.ResumeNetworkStart();
5536 base::RunLoop().Run();
5538 EXPECT_EQ(1, d.received_redirect_count());
5539 req.FollowDeferredRedirect();
5540 base::RunLoop().Run();
5542 // Check that the redirect's new network transaction does not get propagated
5543 // to a second OnBeforeNetworkStart() notification.
5544 EXPECT_EQ(1, d.received_before_network_start_count());
5546 EXPECT_EQ(1, d.response_started_count());
5547 EXPECT_NE(0, d.bytes_received());
5548 EXPECT_EQ(URLRequestStatus::SUCCESS, req.status().status());
5552 // Cancel the request after learning that the request would use the network.
5553 TEST_F(URLRequestTestHTTP, CancelOnBeforeNetworkStart) {
5554 ASSERT_TRUE(test_server_.Start());
5556 TestDelegate d;
5558 d.set_quit_on_network_start(true);
5559 GURL test_url(test_server_.GetURL("echo"));
5560 URLRequest req(test_url, DEFAULT_PRIORITY, &d, &default_context_);
5562 req.Start();
5563 base::RunLoop().Run();
5565 EXPECT_EQ(1, d.received_before_network_start_count());
5566 EXPECT_EQ(0, d.response_started_count());
5568 req.Cancel();
5569 base::RunLoop().Run();
5571 EXPECT_EQ(1, d.response_started_count());
5572 EXPECT_EQ(0, d.bytes_received());
5573 EXPECT_EQ(URLRequestStatus::CANCELED, req.status().status());
5577 TEST_F(URLRequestTestHTTP, CancelRedirect) {
5578 ASSERT_TRUE(test_server_.Start());
5580 TestDelegate d;
5582 d.set_cancel_in_received_redirect(true);
5583 URLRequest req(test_server_.GetURL("files/redirect-test.html"),
5584 DEFAULT_PRIORITY,
5586 &default_context_);
5587 req.Start();
5588 base::RunLoop().Run();
5590 EXPECT_EQ(1, d.response_started_count());
5591 EXPECT_EQ(0, d.bytes_received());
5592 EXPECT_FALSE(d.received_data_before_response());
5593 EXPECT_EQ(URLRequestStatus::CANCELED, req.status().status());
5597 TEST_F(URLRequestTestHTTP, DeferredRedirect) {
5598 ASSERT_TRUE(test_server_.Start());
5600 TestDelegate d;
5602 d.set_quit_on_redirect(true);
5603 GURL test_url(test_server_.GetURL("files/redirect-test.html"));
5604 URLRequest req(test_url, DEFAULT_PRIORITY, &d, &default_context_);
5606 req.Start();
5607 base::RunLoop().Run();
5609 EXPECT_EQ(1, d.received_redirect_count());
5611 req.FollowDeferredRedirect();
5612 base::RunLoop().Run();
5614 EXPECT_EQ(1, d.response_started_count());
5615 EXPECT_FALSE(d.received_data_before_response());
5616 EXPECT_EQ(URLRequestStatus::SUCCESS, req.status().status());
5618 base::FilePath path;
5619 PathService::Get(base::DIR_SOURCE_ROOT, &path);
5620 path = path.Append(FILE_PATH_LITERAL("net"));
5621 path = path.Append(FILE_PATH_LITERAL("data"));
5622 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
5623 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
5625 std::string contents;
5626 EXPECT_TRUE(base::ReadFileToString(path, &contents));
5627 EXPECT_EQ(contents, d.data_received());
5631 TEST_F(URLRequestTestHTTP, DeferredRedirect_GetFullRequestHeaders) {
5632 ASSERT_TRUE(test_server_.Start());
5634 TestDelegate d;
5636 d.set_quit_on_redirect(true);
5637 GURL test_url(test_server_.GetURL("files/redirect-test.html"));
5638 URLRequest req(test_url, DEFAULT_PRIORITY, &d, &default_context_);
5640 EXPECT_FALSE(d.have_full_request_headers());
5642 req.Start();
5643 base::RunLoop().Run();
5645 EXPECT_EQ(1, d.received_redirect_count());
5646 EXPECT_TRUE(d.have_full_request_headers());
5647 CheckFullRequestHeaders(d.full_request_headers(), test_url);
5648 d.ClearFullRequestHeaders();
5650 req.FollowDeferredRedirect();
5651 base::RunLoop().Run();
5653 GURL target_url(test_server_.GetURL("files/with-headers.html"));
5654 EXPECT_EQ(1, d.response_started_count());
5655 EXPECT_TRUE(d.have_full_request_headers());
5656 CheckFullRequestHeaders(d.full_request_headers(), target_url);
5657 EXPECT_FALSE(d.received_data_before_response());
5658 EXPECT_EQ(URLRequestStatus::SUCCESS, req.status().status());
5660 base::FilePath path;
5661 PathService::Get(base::DIR_SOURCE_ROOT, &path);
5662 path = path.Append(FILE_PATH_LITERAL("net"));
5663 path = path.Append(FILE_PATH_LITERAL("data"));
5664 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
5665 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
5667 std::string contents;
5668 EXPECT_TRUE(base::ReadFileToString(path, &contents));
5669 EXPECT_EQ(contents, d.data_received());
5673 TEST_F(URLRequestTestHTTP, CancelDeferredRedirect) {
5674 ASSERT_TRUE(test_server_.Start());
5676 TestDelegate d;
5678 d.set_quit_on_redirect(true);
5679 URLRequest req(test_server_.GetURL("files/redirect-test.html"),
5680 DEFAULT_PRIORITY,
5682 &default_context_);
5683 req.Start();
5684 base::RunLoop().Run();
5686 EXPECT_EQ(1, d.received_redirect_count());
5688 req.Cancel();
5689 base::RunLoop().Run();
5691 EXPECT_EQ(1, d.response_started_count());
5692 EXPECT_EQ(0, d.bytes_received());
5693 EXPECT_FALSE(d.received_data_before_response());
5694 EXPECT_EQ(URLRequestStatus::CANCELED, req.status().status());
5698 TEST_F(URLRequestTestHTTP, VaryHeader) {
5699 ASSERT_TRUE(test_server_.Start());
5701 // Populate the cache.
5703 TestDelegate d;
5704 URLRequest req(test_server_.GetURL("echoheadercache?foo"),
5705 DEFAULT_PRIORITY,
5707 &default_context_);
5708 HttpRequestHeaders headers;
5709 headers.SetHeader("foo", "1");
5710 req.SetExtraRequestHeaders(headers);
5711 req.Start();
5712 base::RunLoop().Run();
5714 LoadTimingInfo load_timing_info;
5715 req.GetLoadTimingInfo(&load_timing_info);
5716 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
5719 // Expect a cache hit.
5721 TestDelegate d;
5722 URLRequest req(test_server_.GetURL("echoheadercache?foo"),
5723 DEFAULT_PRIORITY,
5725 &default_context_);
5726 HttpRequestHeaders headers;
5727 headers.SetHeader("foo", "1");
5728 req.SetExtraRequestHeaders(headers);
5729 req.Start();
5730 base::RunLoop().Run();
5732 EXPECT_TRUE(req.was_cached());
5734 LoadTimingInfo load_timing_info;
5735 req.GetLoadTimingInfo(&load_timing_info);
5736 TestLoadTimingCacheHitNoNetwork(load_timing_info);
5739 // Expect a cache miss.
5741 TestDelegate d;
5742 URLRequest req(test_server_.GetURL("echoheadercache?foo"),
5743 DEFAULT_PRIORITY,
5745 &default_context_);
5746 HttpRequestHeaders headers;
5747 headers.SetHeader("foo", "2");
5748 req.SetExtraRequestHeaders(headers);
5749 req.Start();
5750 base::RunLoop().Run();
5752 EXPECT_FALSE(req.was_cached());
5754 LoadTimingInfo load_timing_info;
5755 req.GetLoadTimingInfo(&load_timing_info);
5756 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
5760 TEST_F(URLRequestTestHTTP, BasicAuth) {
5761 ASSERT_TRUE(test_server_.Start());
5763 // populate the cache
5765 TestDelegate d;
5766 d.set_credentials(AuthCredentials(kUser, kSecret));
5768 URLRequest r(test_server_.GetURL("auth-basic"),
5769 DEFAULT_PRIORITY,
5771 &default_context_);
5772 r.Start();
5774 base::RunLoop().Run();
5776 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
5779 // repeat request with end-to-end validation. since auth-basic results in a
5780 // cachable page, we expect this test to result in a 304. in which case, the
5781 // response should be fetched from the cache.
5783 TestDelegate d;
5784 d.set_credentials(AuthCredentials(kUser, kSecret));
5786 URLRequest r(test_server_.GetURL("auth-basic"),
5787 DEFAULT_PRIORITY,
5789 &default_context_);
5790 r.SetLoadFlags(LOAD_VALIDATE_CACHE);
5791 r.Start();
5793 base::RunLoop().Run();
5795 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
5797 // Should be the same cached document.
5798 EXPECT_TRUE(r.was_cached());
5802 // Check that Set-Cookie headers in 401 responses are respected.
5803 // http://crbug.com/6450
5804 TEST_F(URLRequestTestHTTP, BasicAuthWithCookies) {
5805 ASSERT_TRUE(test_server_.Start());
5807 GURL url_requiring_auth =
5808 test_server_.GetURL("auth-basic?set-cookie-if-challenged");
5810 // Request a page that will give a 401 containing a Set-Cookie header.
5811 // Verify that when the transaction is restarted, it includes the new cookie.
5813 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
5814 TestURLRequestContext context(true);
5815 context.set_network_delegate(&network_delegate);
5816 context.Init();
5818 TestDelegate d;
5819 d.set_credentials(AuthCredentials(kUser, kSecret));
5821 URLRequest r(url_requiring_auth, DEFAULT_PRIORITY, &d, &context);
5822 r.Start();
5824 base::RunLoop().Run();
5826 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
5828 // Make sure we sent the cookie in the restarted transaction.
5829 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
5830 != std::string::npos);
5833 // Same test as above, except this time the restart is initiated earlier
5834 // (without user intervention since identity is embedded in the URL).
5836 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
5837 TestURLRequestContext context(true);
5838 context.set_network_delegate(&network_delegate);
5839 context.Init();
5841 TestDelegate d;
5843 GURL::Replacements replacements;
5844 std::string username("user2");
5845 std::string password("secret");
5846 replacements.SetUsernameStr(username);
5847 replacements.SetPasswordStr(password);
5848 GURL url_with_identity = url_requiring_auth.ReplaceComponents(replacements);
5850 URLRequest r(url_with_identity, DEFAULT_PRIORITY, &d, &context);
5851 r.Start();
5853 base::RunLoop().Run();
5855 EXPECT_TRUE(d.data_received().find("user2/secret") != std::string::npos);
5857 // Make sure we sent the cookie in the restarted transaction.
5858 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
5859 != std::string::npos);
5863 // Tests that load timing works as expected with auth and the cache.
5864 TEST_F(URLRequestTestHTTP, BasicAuthLoadTiming) {
5865 ASSERT_TRUE(test_server_.Start());
5867 // populate the cache
5869 TestDelegate d;
5870 d.set_credentials(AuthCredentials(kUser, kSecret));
5872 URLRequest r(test_server_.GetURL("auth-basic"),
5873 DEFAULT_PRIORITY,
5875 &default_context_);
5876 r.Start();
5878 base::RunLoop().Run();
5880 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
5882 LoadTimingInfo load_timing_info_before_auth;
5883 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeAuth(
5884 &load_timing_info_before_auth));
5885 TestLoadTimingNotReused(load_timing_info_before_auth,
5886 CONNECT_TIMING_HAS_DNS_TIMES);
5888 LoadTimingInfo load_timing_info;
5889 r.GetLoadTimingInfo(&load_timing_info);
5890 // The test server does not support keep alive sockets, so the second
5891 // request with auth should use a new socket.
5892 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
5893 EXPECT_NE(load_timing_info_before_auth.socket_log_id,
5894 load_timing_info.socket_log_id);
5895 EXPECT_LE(load_timing_info_before_auth.receive_headers_end,
5896 load_timing_info.connect_timing.connect_start);
5899 // Repeat request with end-to-end validation. Since auth-basic results in a
5900 // cachable page, we expect this test to result in a 304. In which case, the
5901 // response should be fetched from the cache.
5903 TestDelegate d;
5904 d.set_credentials(AuthCredentials(kUser, kSecret));
5906 URLRequest r(test_server_.GetURL("auth-basic"),
5907 DEFAULT_PRIORITY,
5909 &default_context_);
5910 r.SetLoadFlags(LOAD_VALIDATE_CACHE);
5911 r.Start();
5913 base::RunLoop().Run();
5915 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
5917 // Should be the same cached document.
5918 EXPECT_TRUE(r.was_cached());
5920 // Since there was a request that went over the wire, the load timing
5921 // information should include connection times.
5922 LoadTimingInfo load_timing_info;
5923 r.GetLoadTimingInfo(&load_timing_info);
5924 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
5928 // In this test, we do a POST which the server will 302 redirect.
5929 // The subsequent transaction should use GET, and should not send the
5930 // Content-Type header.
5931 // http://code.google.com/p/chromium/issues/detail?id=843
5932 TEST_F(URLRequestTestHTTP, Post302RedirectGet) {
5933 ASSERT_TRUE(test_server_.Start());
5935 const char kData[] = "hello world";
5937 TestDelegate d;
5938 URLRequest req(test_server_.GetURL("files/redirect-to-echoall"),
5939 DEFAULT_PRIORITY,
5941 &default_context_);
5942 req.set_method("POST");
5943 req.set_upload(make_scoped_ptr(CreateSimpleUploadData(kData)));
5945 // Set headers (some of which are specific to the POST).
5946 HttpRequestHeaders headers;
5947 headers.AddHeadersFromString(
5948 "Content-Type: multipart/form-data; "
5949 "boundary=----WebKitFormBoundaryAADeAA+NAAWMAAwZ\r\n"
5950 "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,"
5951 "text/plain;q=0.8,image/png,*/*;q=0.5\r\n"
5952 "Accept-Language: en-US,en\r\n"
5953 "Accept-Charset: ISO-8859-1,*,utf-8\r\n"
5954 "Content-Length: 11\r\n"
5955 "Origin: http://localhost:1337/");
5956 req.SetExtraRequestHeaders(headers);
5957 req.Start();
5958 base::RunLoop().Run();
5960 std::string mime_type;
5961 req.GetMimeType(&mime_type);
5962 EXPECT_EQ("text/html", mime_type);
5964 const std::string& data = d.data_received();
5966 // Check that the post-specific headers were stripped:
5967 EXPECT_FALSE(ContainsString(data, "Content-Length:"));
5968 EXPECT_FALSE(ContainsString(data, "Content-Type:"));
5969 EXPECT_FALSE(ContainsString(data, "Origin:"));
5971 // These extra request headers should not have been stripped.
5972 EXPECT_TRUE(ContainsString(data, "Accept:"));
5973 EXPECT_TRUE(ContainsString(data, "Accept-Language:"));
5974 EXPECT_TRUE(ContainsString(data, "Accept-Charset:"));
5977 // The following tests check that we handle mutating the request method for
5978 // HTTP redirects as expected.
5979 // See http://crbug.com/56373 and http://crbug.com/102130.
5981 TEST_F(URLRequestTestHTTP, Redirect301Tests) {
5982 ASSERT_TRUE(test_server_.Start());
5984 const GURL url = test_server_.GetURL("files/redirect301-to-echo");
5986 HTTPRedirectMethodTest(url, "POST", "GET", true);
5987 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
5988 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
5991 TEST_F(URLRequestTestHTTP, Redirect302Tests) {
5992 ASSERT_TRUE(test_server_.Start());
5994 const GURL url = test_server_.GetURL("files/redirect302-to-echo");
5996 HTTPRedirectMethodTest(url, "POST", "GET", true);
5997 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
5998 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
6001 TEST_F(URLRequestTestHTTP, Redirect303Tests) {
6002 ASSERT_TRUE(test_server_.Start());
6004 const GURL url = test_server_.GetURL("files/redirect303-to-echo");
6006 HTTPRedirectMethodTest(url, "POST", "GET", true);
6007 HTTPRedirectMethodTest(url, "PUT", "GET", true);
6008 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
6011 TEST_F(URLRequestTestHTTP, Redirect307Tests) {
6012 ASSERT_TRUE(test_server_.Start());
6014 const GURL url = test_server_.GetURL("files/redirect307-to-echo");
6016 HTTPRedirectMethodTest(url, "POST", "POST", true);
6017 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6018 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
6021 TEST_F(URLRequestTestHTTP, Redirect308Tests) {
6022 ASSERT_TRUE(test_server_.Start());
6024 const GURL url = test_server_.GetURL("files/redirect308-to-echo");
6026 HTTPRedirectMethodTest(url, "POST", "POST", true);
6027 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6028 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
6031 // Make sure that 308 responses without bodies are not treated as redirects.
6032 // Certain legacy apis that pre-date the response code expect this behavior
6033 // (Like Google Drive).
6034 TEST_F(URLRequestTestHTTP, NoRedirectOn308WithoutLocationHeader) {
6035 ASSERT_TRUE(test_server_.Start());
6037 TestDelegate d;
6038 const GURL url = test_server_.GetURL("files/308-without-location-header");
6040 URLRequest request(url, DEFAULT_PRIORITY, &d, &default_context_);
6042 request.Start();
6043 base::RunLoop().Run();
6044 EXPECT_EQ(URLRequestStatus::SUCCESS, request.status().status());
6045 EXPECT_EQ(OK, request.status().error());
6046 EXPECT_EQ(0, d.received_redirect_count());
6047 EXPECT_EQ(308, request.response_headers()->response_code());
6048 EXPECT_EQ("This is not a redirect.", d.data_received());
6051 TEST_F(URLRequestTestHTTP, Redirect302PreserveReferenceFragment) {
6052 ASSERT_TRUE(test_server_.Start());
6054 GURL original_url(test_server_.GetURL("files/redirect302-to-echo#fragment"));
6055 GURL expected_url(test_server_.GetURL("echo#fragment"));
6057 TestDelegate d;
6059 URLRequest r(original_url, DEFAULT_PRIORITY, &d, &default_context_);
6061 r.Start();
6062 base::RunLoop().Run();
6064 EXPECT_EQ(2U, r.url_chain().size());
6065 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
6066 EXPECT_EQ(net::OK, r.status().error());
6067 EXPECT_EQ(original_url, r.original_url());
6068 EXPECT_EQ(expected_url, r.url());
6072 TEST_F(URLRequestTestHTTP, InterceptPost302RedirectGet) {
6073 ASSERT_TRUE(test_server_.Start());
6075 const char kData[] = "hello world";
6077 TestDelegate d;
6078 URLRequest req(test_server_.GetURL("empty.html"),
6079 DEFAULT_PRIORITY,
6081 &default_context_);
6082 req.set_method("POST");
6083 req.set_upload(make_scoped_ptr(CreateSimpleUploadData(kData)));
6084 HttpRequestHeaders headers;
6085 headers.SetHeader(HttpRequestHeaders::kContentLength,
6086 base::UintToString(arraysize(kData) - 1));
6087 req.SetExtraRequestHeaders(headers);
6089 URLRequestRedirectJob* job = new URLRequestRedirectJob(
6090 &req, &default_network_delegate_, test_server_.GetURL("echo"),
6091 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason");
6092 AddTestInterceptor()->set_main_intercept_job(job);
6094 req.Start();
6095 base::RunLoop().Run();
6096 EXPECT_EQ("GET", req.method());
6099 TEST_F(URLRequestTestHTTP, InterceptPost307RedirectPost) {
6100 ASSERT_TRUE(test_server_.Start());
6102 const char kData[] = "hello world";
6104 TestDelegate d;
6105 URLRequest req(test_server_.GetURL("empty.html"),
6106 DEFAULT_PRIORITY,
6108 &default_context_);
6109 req.set_method("POST");
6110 req.set_upload(make_scoped_ptr(CreateSimpleUploadData(kData)));
6111 HttpRequestHeaders headers;
6112 headers.SetHeader(HttpRequestHeaders::kContentLength,
6113 base::UintToString(arraysize(kData) - 1));
6114 req.SetExtraRequestHeaders(headers);
6116 URLRequestRedirectJob* job = new URLRequestRedirectJob(
6117 &req, &default_network_delegate_, test_server_.GetURL("echo"),
6118 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT,
6119 "Very Good Reason");
6120 AddTestInterceptor()->set_main_intercept_job(job);
6122 req.Start();
6123 base::RunLoop().Run();
6124 EXPECT_EQ("POST", req.method());
6125 EXPECT_EQ(kData, d.data_received());
6128 // Check that default A-L header is sent.
6129 TEST_F(URLRequestTestHTTP, DefaultAcceptLanguage) {
6130 ASSERT_TRUE(test_server_.Start());
6132 StaticHttpUserAgentSettings settings("en", std::string());
6133 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
6134 TestURLRequestContext context(true);
6135 context.set_network_delegate(&network_delegate);
6136 context.set_http_user_agent_settings(&settings);
6137 context.Init();
6139 TestDelegate d;
6140 URLRequest req(test_server_.GetURL("echoheader?Accept-Language"),
6141 DEFAULT_PRIORITY,
6143 &context);
6144 req.Start();
6145 base::RunLoop().Run();
6146 EXPECT_EQ("en", d.data_received());
6149 // Check that an empty A-L header is not sent. http://crbug.com/77365.
6150 TEST_F(URLRequestTestHTTP, EmptyAcceptLanguage) {
6151 ASSERT_TRUE(test_server_.Start());
6153 std::string empty_string; // Avoid most vexing parse on line below.
6154 StaticHttpUserAgentSettings settings(empty_string, empty_string);
6155 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
6156 TestURLRequestContext context(true);
6157 context.set_network_delegate(&network_delegate);
6158 context.Init();
6159 // We override the language after initialization because empty entries
6160 // get overridden by Init().
6161 context.set_http_user_agent_settings(&settings);
6163 TestDelegate d;
6164 URLRequest req(test_server_.GetURL("echoheader?Accept-Language"),
6165 DEFAULT_PRIORITY,
6167 &context);
6168 req.Start();
6169 base::RunLoop().Run();
6170 EXPECT_EQ("None", d.data_received());
6173 // Check that if request overrides the A-L header, the default is not appended.
6174 // See http://crbug.com/20894
6175 TEST_F(URLRequestTestHTTP, OverrideAcceptLanguage) {
6176 ASSERT_TRUE(test_server_.Start());
6178 TestDelegate d;
6179 URLRequest req(test_server_.GetURL("echoheader?Accept-Language"),
6180 DEFAULT_PRIORITY,
6182 &default_context_);
6183 HttpRequestHeaders headers;
6184 headers.SetHeader(HttpRequestHeaders::kAcceptLanguage, "ru");
6185 req.SetExtraRequestHeaders(headers);
6186 req.Start();
6187 base::RunLoop().Run();
6188 EXPECT_EQ(std::string("ru"), d.data_received());
6191 // Check that default A-E header is sent.
6192 TEST_F(URLRequestTestHTTP, DefaultAcceptEncoding) {
6193 ASSERT_TRUE(test_server_.Start());
6195 TestDelegate d;
6196 URLRequest req(test_server_.GetURL("echoheader?Accept-Encoding"),
6197 DEFAULT_PRIORITY,
6199 &default_context_);
6200 HttpRequestHeaders headers;
6201 req.SetExtraRequestHeaders(headers);
6202 req.Start();
6203 base::RunLoop().Run();
6204 EXPECT_TRUE(ContainsString(d.data_received(), "gzip"));
6207 // Check that if request overrides the A-E header, the default is not appended.
6208 // See http://crbug.com/47381
6209 TEST_F(URLRequestTestHTTP, OverrideAcceptEncoding) {
6210 ASSERT_TRUE(test_server_.Start());
6212 TestDelegate d;
6213 URLRequest req(test_server_.GetURL("echoheader?Accept-Encoding"),
6214 DEFAULT_PRIORITY,
6216 &default_context_);
6217 HttpRequestHeaders headers;
6218 headers.SetHeader(HttpRequestHeaders::kAcceptEncoding, "identity");
6219 req.SetExtraRequestHeaders(headers);
6220 req.Start();
6221 base::RunLoop().Run();
6222 EXPECT_FALSE(ContainsString(d.data_received(), "gzip"));
6223 EXPECT_TRUE(ContainsString(d.data_received(), "identity"));
6226 // Check that setting the A-C header sends the proper header.
6227 TEST_F(URLRequestTestHTTP, SetAcceptCharset) {
6228 ASSERT_TRUE(test_server_.Start());
6230 TestDelegate d;
6231 URLRequest req(test_server_.GetURL("echoheader?Accept-Charset"),
6232 DEFAULT_PRIORITY,
6234 &default_context_);
6235 HttpRequestHeaders headers;
6236 headers.SetHeader(HttpRequestHeaders::kAcceptCharset, "koi-8r");
6237 req.SetExtraRequestHeaders(headers);
6238 req.Start();
6239 base::RunLoop().Run();
6240 EXPECT_EQ(std::string("koi-8r"), d.data_received());
6243 // Check that default User-Agent header is sent.
6244 TEST_F(URLRequestTestHTTP, DefaultUserAgent) {
6245 ASSERT_TRUE(test_server_.Start());
6247 TestDelegate d;
6248 URLRequest req(test_server_.GetURL("echoheader?User-Agent"),
6249 DEFAULT_PRIORITY,
6251 &default_context_);
6252 req.Start();
6253 base::RunLoop().Run();
6254 EXPECT_EQ(req.context()->http_user_agent_settings()->GetUserAgent(),
6255 d.data_received());
6258 // Check that if request overrides the User-Agent header,
6259 // the default is not appended.
6260 TEST_F(URLRequestTestHTTP, OverrideUserAgent) {
6261 ASSERT_TRUE(test_server_.Start());
6263 TestDelegate d;
6264 URLRequest req(test_server_.GetURL("echoheader?User-Agent"),
6265 DEFAULT_PRIORITY,
6267 &default_context_);
6268 HttpRequestHeaders headers;
6269 headers.SetHeader(HttpRequestHeaders::kUserAgent, "Lynx (textmode)");
6270 req.SetExtraRequestHeaders(headers);
6271 req.Start();
6272 base::RunLoop().Run();
6273 EXPECT_EQ(std::string("Lynx (textmode)"), d.data_received());
6276 // Check that a NULL HttpUserAgentSettings causes the corresponding empty
6277 // User-Agent header to be sent but does not send the Accept-Language and
6278 // Accept-Charset headers.
6279 TEST_F(URLRequestTestHTTP, EmptyHttpUserAgentSettings) {
6280 ASSERT_TRUE(test_server_.Start());
6282 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
6283 TestURLRequestContext context(true);
6284 context.set_network_delegate(&network_delegate);
6285 context.Init();
6286 // We override the HttpUserAgentSettings after initialization because empty
6287 // entries get overridden by Init().
6288 context.set_http_user_agent_settings(NULL);
6290 struct {
6291 const char* request;
6292 const char* expected_response;
6293 } tests[] = { { "echoheader?Accept-Language", "None" },
6294 { "echoheader?Accept-Charset", "None" },
6295 { "echoheader?User-Agent", "" } };
6297 for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); i++) {
6298 TestDelegate d;
6299 URLRequest req(
6300 test_server_.GetURL(tests[i].request), DEFAULT_PRIORITY, &d, &context);
6301 req.Start();
6302 base::RunLoop().Run();
6303 EXPECT_EQ(tests[i].expected_response, d.data_received())
6304 << " Request = \"" << tests[i].request << "\"";
6308 // Make sure that URLRequest passes on its priority updates to
6309 // newly-created jobs after the first one.
6310 TEST_F(URLRequestTestHTTP, SetSubsequentJobPriority) {
6311 ASSERT_TRUE(test_server_.Start());
6313 TestDelegate d;
6314 URLRequest req(test_server_.GetURL("empty.html"),
6315 DEFAULT_PRIORITY,
6317 &default_context_);
6318 EXPECT_EQ(DEFAULT_PRIORITY, req.priority());
6320 scoped_refptr<URLRequestRedirectJob> redirect_job =
6321 new URLRequestRedirectJob(
6322 &req, &default_network_delegate_, test_server_.GetURL("echo"),
6323 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason");
6324 AddTestInterceptor()->set_main_intercept_job(redirect_job.get());
6326 req.SetPriority(LOW);
6327 req.Start();
6328 EXPECT_TRUE(req.is_pending());
6330 scoped_refptr<URLRequestTestJob> job =
6331 new URLRequestTestJob(&req, &default_network_delegate_);
6332 AddTestInterceptor()->set_main_intercept_job(job.get());
6334 // Should trigger |job| to be started.
6335 base::RunLoop().Run();
6336 EXPECT_EQ(LOW, job->priority());
6339 // Check that creating a network request while entering/exiting suspend mode
6340 // fails as it should. This is the only case where an HttpTransactionFactory
6341 // does not return an HttpTransaction.
6342 TEST_F(URLRequestTestHTTP, NetworkSuspendTest) {
6343 // Create a new HttpNetworkLayer that thinks it's suspended.
6344 HttpNetworkSession::Params params;
6345 params.host_resolver = default_context_.host_resolver();
6346 params.cert_verifier = default_context_.cert_verifier();
6347 params.transport_security_state = default_context_.transport_security_state();
6348 params.proxy_service = default_context_.proxy_service();
6349 params.ssl_config_service = default_context_.ssl_config_service();
6350 params.http_auth_handler_factory =
6351 default_context_.http_auth_handler_factory();
6352 params.network_delegate = &default_network_delegate_;
6353 params.http_server_properties = default_context_.http_server_properties();
6354 scoped_ptr<HttpNetworkLayer> network_layer(
6355 new HttpNetworkLayer(new HttpNetworkSession(params)));
6356 network_layer->OnSuspend();
6358 HttpCache http_cache(network_layer.release(), default_context_.net_log(),
6359 HttpCache::DefaultBackend::InMemory(0));
6361 TestURLRequestContext context(true);
6362 context.set_http_transaction_factory(&http_cache);
6363 context.Init();
6365 TestDelegate d;
6366 URLRequest req(GURL("http://127.0.0.1/"),
6367 DEFAULT_PRIORITY,
6369 &context);
6370 req.Start();
6371 base::RunLoop().Run();
6373 EXPECT_TRUE(d.request_failed());
6374 EXPECT_EQ(URLRequestStatus::FAILED, req.status().status());
6375 EXPECT_EQ(ERR_NETWORK_IO_SUSPENDED, req.status().error());
6378 // Check that creating a network request while entering/exiting suspend mode
6379 // fails as it should in the case there is no cache. This is the only case
6380 // where an HttpTransactionFactory does not return an HttpTransaction.
6381 TEST_F(URLRequestTestHTTP, NetworkSuspendTestNoCache) {
6382 // Create a new HttpNetworkLayer that thinks it's suspended.
6383 HttpNetworkSession::Params params;
6384 params.host_resolver = default_context_.host_resolver();
6385 params.cert_verifier = default_context_.cert_verifier();
6386 params.transport_security_state = default_context_.transport_security_state();
6387 params.proxy_service = default_context_.proxy_service();
6388 params.ssl_config_service = default_context_.ssl_config_service();
6389 params.http_auth_handler_factory =
6390 default_context_.http_auth_handler_factory();
6391 params.network_delegate = &default_network_delegate_;
6392 params.http_server_properties = default_context_.http_server_properties();
6393 HttpNetworkLayer network_layer(new HttpNetworkSession(params));
6394 network_layer.OnSuspend();
6396 TestURLRequestContext context(true);
6397 context.set_http_transaction_factory(&network_layer);
6398 context.Init();
6400 TestDelegate d;
6401 URLRequest req(GURL("http://127.0.0.1/"),
6402 DEFAULT_PRIORITY,
6404 &context);
6405 req.Start();
6406 base::RunLoop().Run();
6408 EXPECT_TRUE(d.request_failed());
6409 EXPECT_EQ(URLRequestStatus::FAILED, req.status().status());
6410 EXPECT_EQ(ERR_NETWORK_IO_SUSPENDED, req.status().error());
6413 class HTTPSRequestTest : public testing::Test {
6414 public:
6415 HTTPSRequestTest() : default_context_(true) {
6416 default_context_.set_network_delegate(&default_network_delegate_);
6417 default_context_.Init();
6419 virtual ~HTTPSRequestTest() {}
6421 protected:
6422 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
6423 TestURLRequestContext default_context_;
6426 TEST_F(HTTPSRequestTest, HTTPSGetTest) {
6427 SpawnedTestServer test_server(
6428 SpawnedTestServer::TYPE_HTTPS,
6429 SpawnedTestServer::kLocalhost,
6430 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6431 ASSERT_TRUE(test_server.Start());
6433 TestDelegate d;
6435 URLRequest r(test_server.GetURL(std::string()),
6436 DEFAULT_PRIORITY,
6438 &default_context_);
6439 r.Start();
6440 EXPECT_TRUE(r.is_pending());
6442 base::RunLoop().Run();
6444 EXPECT_EQ(1, d.response_started_count());
6445 EXPECT_FALSE(d.received_data_before_response());
6446 EXPECT_NE(0, d.bytes_received());
6447 CheckSSLInfo(r.ssl_info());
6448 EXPECT_EQ(test_server.host_port_pair().host(),
6449 r.GetSocketAddress().host());
6450 EXPECT_EQ(test_server.host_port_pair().port(),
6451 r.GetSocketAddress().port());
6455 TEST_F(HTTPSRequestTest, HTTPSMismatchedTest) {
6456 SpawnedTestServer::SSLOptions ssl_options(
6457 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
6458 SpawnedTestServer test_server(
6459 SpawnedTestServer::TYPE_HTTPS,
6460 ssl_options,
6461 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6462 ASSERT_TRUE(test_server.Start());
6464 bool err_allowed = true;
6465 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
6466 TestDelegate d;
6468 d.set_allow_certificate_errors(err_allowed);
6469 URLRequest r(test_server.GetURL(std::string()),
6470 DEFAULT_PRIORITY,
6472 &default_context_);
6474 r.Start();
6475 EXPECT_TRUE(r.is_pending());
6477 base::RunLoop().Run();
6479 EXPECT_EQ(1, d.response_started_count());
6480 EXPECT_FALSE(d.received_data_before_response());
6481 EXPECT_TRUE(d.have_certificate_errors());
6482 if (err_allowed) {
6483 EXPECT_NE(0, d.bytes_received());
6484 CheckSSLInfo(r.ssl_info());
6485 } else {
6486 EXPECT_EQ(0, d.bytes_received());
6492 TEST_F(HTTPSRequestTest, HTTPSExpiredTest) {
6493 SpawnedTestServer::SSLOptions ssl_options(
6494 SpawnedTestServer::SSLOptions::CERT_EXPIRED);
6495 SpawnedTestServer test_server(
6496 SpawnedTestServer::TYPE_HTTPS,
6497 ssl_options,
6498 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6499 ASSERT_TRUE(test_server.Start());
6501 // Iterate from false to true, just so that we do the opposite of the
6502 // previous test in order to increase test coverage.
6503 bool err_allowed = false;
6504 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
6505 TestDelegate d;
6507 d.set_allow_certificate_errors(err_allowed);
6508 URLRequest r(test_server.GetURL(std::string()),
6509 DEFAULT_PRIORITY,
6511 &default_context_);
6513 r.Start();
6514 EXPECT_TRUE(r.is_pending());
6516 base::RunLoop().Run();
6518 EXPECT_EQ(1, d.response_started_count());
6519 EXPECT_FALSE(d.received_data_before_response());
6520 EXPECT_TRUE(d.have_certificate_errors());
6521 if (err_allowed) {
6522 EXPECT_NE(0, d.bytes_received());
6523 CheckSSLInfo(r.ssl_info());
6524 } else {
6525 EXPECT_EQ(0, d.bytes_received());
6531 // Tests TLSv1.1 -> TLSv1 fallback. Verifies that we don't fall back more
6532 // than necessary.
6533 TEST_F(HTTPSRequestTest, TLSv1Fallback) {
6534 // The OpenSSL library in use may not support TLS 1.1.
6535 #if !defined(USE_OPENSSL)
6536 EXPECT_GT(kDefaultSSLVersionMax, SSL_PROTOCOL_VERSION_TLS1);
6537 #endif
6538 if (kDefaultSSLVersionMax <= SSL_PROTOCOL_VERSION_TLS1)
6539 return;
6541 SpawnedTestServer::SSLOptions ssl_options(
6542 SpawnedTestServer::SSLOptions::CERT_OK);
6543 ssl_options.tls_intolerant =
6544 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
6545 SpawnedTestServer test_server(
6546 SpawnedTestServer::TYPE_HTTPS,
6547 ssl_options,
6548 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6549 ASSERT_TRUE(test_server.Start());
6551 TestDelegate d;
6552 TestURLRequestContext context(true);
6553 context.Init();
6554 d.set_allow_certificate_errors(true);
6555 URLRequest r(
6556 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d, &context);
6557 r.Start();
6559 base::RunLoop().Run();
6561 EXPECT_EQ(1, d.response_started_count());
6562 EXPECT_NE(0, d.bytes_received());
6563 EXPECT_EQ(static_cast<int>(SSL_CONNECTION_VERSION_TLS1),
6564 SSLConnectionStatusToVersion(r.ssl_info().connection_status));
6565 EXPECT_TRUE(r.ssl_info().connection_status & SSL_CONNECTION_VERSION_FALLBACK);
6568 // Tests that we don't fallback with servers that implement TLS_FALLBACK_SCSV.
6569 #if defined(USE_OPENSSL)
6570 TEST_F(HTTPSRequestTest, DISABLED_FallbackSCSV) {
6571 #else
6572 TEST_F(HTTPSRequestTest, FallbackSCSV) {
6573 #endif
6574 SpawnedTestServer::SSLOptions ssl_options(
6575 SpawnedTestServer::SSLOptions::CERT_OK);
6576 // Configure HTTPS server to be intolerant of TLS >= 1.0 in order to trigger
6577 // a version fallback.
6578 ssl_options.tls_intolerant =
6579 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL;
6580 // Have the server process TLS_FALLBACK_SCSV so that version fallback
6581 // connections are rejected.
6582 ssl_options.fallback_scsv_enabled = true;
6584 SpawnedTestServer test_server(
6585 SpawnedTestServer::TYPE_HTTPS,
6586 ssl_options,
6587 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6588 ASSERT_TRUE(test_server.Start());
6590 TestDelegate d;
6591 TestURLRequestContext context(true);
6592 context.Init();
6593 d.set_allow_certificate_errors(true);
6594 URLRequest r(
6595 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d, &context);
6596 r.Start();
6598 base::RunLoop().Run();
6600 EXPECT_EQ(1, d.response_started_count());
6601 // ERR_SSL_VERSION_OR_CIPHER_MISMATCH is how the server simulates version
6602 // intolerance. If the fallback SCSV is processed when the original error
6603 // that caused the fallback should be returned, which should be
6604 // ERR_SSL_VERSION_OR_CIPHER_MISMATCH.
6605 EXPECT_EQ(ERR_SSL_VERSION_OR_CIPHER_MISMATCH, r.status().error());
6608 // This tests that a load of www.google.com with a certificate error sets
6609 // the |certificate_errors_are_fatal| flag correctly. This flag will cause
6610 // the interstitial to be fatal.
6611 TEST_F(HTTPSRequestTest, HTTPSPreloadedHSTSTest) {
6612 SpawnedTestServer::SSLOptions ssl_options(
6613 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
6614 SpawnedTestServer test_server(
6615 SpawnedTestServer::TYPE_HTTPS,
6616 ssl_options,
6617 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6618 ASSERT_TRUE(test_server.Start());
6620 // We require that the URL be www.google.com in order to pick up the
6621 // preloaded HSTS entries in the TransportSecurityState. This means that we
6622 // have to use a MockHostResolver in order to direct www.google.com to the
6623 // testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
6625 MockHostResolver host_resolver;
6626 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
6627 TestURLRequestContext context(true);
6628 context.set_network_delegate(&network_delegate);
6629 context.set_host_resolver(&host_resolver);
6630 TransportSecurityState transport_security_state;
6631 context.set_transport_security_state(&transport_security_state);
6632 context.Init();
6634 TestDelegate d;
6635 URLRequest r(GURL(base::StringPrintf("https://www.google.com:%d",
6636 test_server.host_port_pair().port())),
6637 DEFAULT_PRIORITY,
6639 &context);
6641 r.Start();
6642 EXPECT_TRUE(r.is_pending());
6644 base::RunLoop().Run();
6646 EXPECT_EQ(1, d.response_started_count());
6647 EXPECT_FALSE(d.received_data_before_response());
6648 EXPECT_TRUE(d.have_certificate_errors());
6649 EXPECT_TRUE(d.certificate_errors_are_fatal());
6652 // This tests that cached HTTPS page loads do not cause any updates to the
6653 // TransportSecurityState.
6654 TEST_F(HTTPSRequestTest, HTTPSErrorsNoClobberTSSTest) {
6655 // The actual problem -- CERT_MISMATCHED_NAME in this case -- doesn't
6656 // matter. It just has to be any error.
6657 SpawnedTestServer::SSLOptions ssl_options(
6658 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
6659 SpawnedTestServer test_server(
6660 SpawnedTestServer::TYPE_HTTPS,
6661 ssl_options,
6662 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6663 ASSERT_TRUE(test_server.Start());
6665 // We require that the URL be www.google.com in order to pick up the
6666 // preloaded and dynamic HSTS and public key pin entries in the
6667 // TransportSecurityState. This means that we have to use a
6668 // MockHostResolver in order to direct www.google.com to the testserver.
6669 // By default, MockHostResolver maps all hosts to 127.0.0.1.
6671 MockHostResolver host_resolver;
6672 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
6673 TestURLRequestContext context(true);
6674 context.set_network_delegate(&network_delegate);
6675 context.set_host_resolver(&host_resolver);
6676 TransportSecurityState transport_security_state;
6677 TransportSecurityState::DomainState domain_state;
6678 EXPECT_TRUE(transport_security_state.GetDomainState("www.google.com", true,
6679 &domain_state));
6680 context.set_transport_security_state(&transport_security_state);
6681 context.Init();
6683 TestDelegate d;
6684 URLRequest r(GURL(base::StringPrintf("https://www.google.com:%d",
6685 test_server.host_port_pair().port())),
6686 DEFAULT_PRIORITY,
6688 &context);
6690 r.Start();
6691 EXPECT_TRUE(r.is_pending());
6693 base::RunLoop().Run();
6695 EXPECT_EQ(1, d.response_started_count());
6696 EXPECT_FALSE(d.received_data_before_response());
6697 EXPECT_TRUE(d.have_certificate_errors());
6698 EXPECT_TRUE(d.certificate_errors_are_fatal());
6700 // Get a fresh copy of the state, and check that it hasn't been updated.
6701 TransportSecurityState::DomainState new_domain_state;
6702 EXPECT_TRUE(transport_security_state.GetDomainState("www.google.com", true,
6703 &new_domain_state));
6704 EXPECT_EQ(new_domain_state.upgrade_mode, domain_state.upgrade_mode);
6705 EXPECT_EQ(new_domain_state.sts_include_subdomains,
6706 domain_state.sts_include_subdomains);
6707 EXPECT_EQ(new_domain_state.pkp_include_subdomains,
6708 domain_state.pkp_include_subdomains);
6709 EXPECT_TRUE(FingerprintsEqual(new_domain_state.static_spki_hashes,
6710 domain_state.static_spki_hashes));
6711 EXPECT_TRUE(FingerprintsEqual(new_domain_state.dynamic_spki_hashes,
6712 domain_state.dynamic_spki_hashes));
6713 EXPECT_TRUE(FingerprintsEqual(new_domain_state.bad_static_spki_hashes,
6714 domain_state.bad_static_spki_hashes));
6717 // Make sure HSTS preserves a POST request's method and body.
6718 TEST_F(HTTPSRequestTest, HSTSPreservesPosts) {
6719 static const char kData[] = "hello world";
6721 SpawnedTestServer::SSLOptions ssl_options(
6722 SpawnedTestServer::SSLOptions::CERT_OK);
6723 SpawnedTestServer test_server(
6724 SpawnedTestServer::TYPE_HTTPS,
6725 ssl_options,
6726 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6727 ASSERT_TRUE(test_server.Start());
6730 // Per spec, TransportSecurityState expects a domain name, rather than an IP
6731 // address, so a MockHostResolver is needed to redirect www.somewhere.com to
6732 // the SpawnedTestServer. By default, MockHostResolver maps all hosts
6733 // to 127.0.0.1.
6734 MockHostResolver host_resolver;
6736 // Force https for www.somewhere.com.
6737 TransportSecurityState transport_security_state;
6738 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1000);
6739 bool include_subdomains = false;
6740 transport_security_state.AddHSTS("www.somewhere.com", expiry,
6741 include_subdomains);
6743 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
6745 TestURLRequestContext context(true);
6746 context.set_host_resolver(&host_resolver);
6747 context.set_transport_security_state(&transport_security_state);
6748 context.set_network_delegate(&network_delegate);
6749 context.Init();
6751 TestDelegate d;
6752 // Navigating to https://www.somewhere.com instead of https://127.0.0.1 will
6753 // cause a certificate error. Ignore the error.
6754 d.set_allow_certificate_errors(true);
6756 URLRequest req(GURL(base::StringPrintf("http://www.somewhere.com:%d/echo",
6757 test_server.host_port_pair().port())),
6758 DEFAULT_PRIORITY,
6760 &context);
6761 req.set_method("POST");
6762 req.set_upload(make_scoped_ptr(CreateSimpleUploadData(kData)));
6764 req.Start();
6765 base::RunLoop().Run();
6767 EXPECT_EQ("https", req.url().scheme());
6768 EXPECT_EQ("POST", req.method());
6769 EXPECT_EQ(kData, d.data_received());
6771 LoadTimingInfo load_timing_info;
6772 network_delegate.GetLoadTimingInfoBeforeRedirect(&load_timing_info);
6773 // LoadTimingInfo of HSTS redirects is similar to that of network cache hits
6774 TestLoadTimingCacheHitNoNetwork(load_timing_info);
6777 TEST_F(HTTPSRequestTest, SSLv3Fallback) {
6778 SpawnedTestServer::SSLOptions ssl_options(
6779 SpawnedTestServer::SSLOptions::CERT_OK);
6780 ssl_options.tls_intolerant =
6781 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL;
6782 SpawnedTestServer test_server(
6783 SpawnedTestServer::TYPE_HTTPS,
6784 ssl_options,
6785 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6786 ASSERT_TRUE(test_server.Start());
6788 TestDelegate d;
6789 TestURLRequestContext context(true);
6790 context.Init();
6791 d.set_allow_certificate_errors(true);
6792 URLRequest r(
6793 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d, &context);
6794 r.Start();
6796 base::RunLoop().Run();
6798 EXPECT_EQ(1, d.response_started_count());
6799 EXPECT_NE(0, d.bytes_received());
6800 EXPECT_EQ(static_cast<int>(SSL_CONNECTION_VERSION_SSL3),
6801 SSLConnectionStatusToVersion(r.ssl_info().connection_status));
6802 EXPECT_TRUE(r.ssl_info().connection_status & SSL_CONNECTION_VERSION_FALLBACK);
6805 namespace {
6807 class SSLClientAuthTestDelegate : public TestDelegate {
6808 public:
6809 SSLClientAuthTestDelegate() : on_certificate_requested_count_(0) {
6811 virtual void OnCertificateRequested(
6812 URLRequest* request,
6813 SSLCertRequestInfo* cert_request_info) OVERRIDE {
6814 on_certificate_requested_count_++;
6815 base::MessageLoop::current()->Quit();
6817 int on_certificate_requested_count() {
6818 return on_certificate_requested_count_;
6820 private:
6821 int on_certificate_requested_count_;
6824 } // namespace
6826 // TODO(davidben): Test the rest of the code. Specifically,
6827 // - Filtering which certificates to select.
6828 // - Sending a certificate back.
6829 // - Getting a certificate request in an SSL renegotiation sending the
6830 // HTTP request.
6831 TEST_F(HTTPSRequestTest, ClientAuthTest) {
6832 SpawnedTestServer::SSLOptions ssl_options;
6833 ssl_options.request_client_certificate = true;
6834 SpawnedTestServer test_server(
6835 SpawnedTestServer::TYPE_HTTPS,
6836 ssl_options,
6837 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6838 ASSERT_TRUE(test_server.Start());
6840 SSLClientAuthTestDelegate d;
6842 URLRequest r(test_server.GetURL(std::string()),
6843 DEFAULT_PRIORITY,
6845 &default_context_);
6847 r.Start();
6848 EXPECT_TRUE(r.is_pending());
6850 base::RunLoop().Run();
6852 EXPECT_EQ(1, d.on_certificate_requested_count());
6853 EXPECT_FALSE(d.received_data_before_response());
6854 EXPECT_EQ(0, d.bytes_received());
6856 // Send no certificate.
6857 // TODO(davidben): Get temporary client cert import (with keys) working on
6858 // all platforms so we can test sending a cert as well.
6859 r.ContinueWithCertificate(NULL);
6861 base::RunLoop().Run();
6863 EXPECT_EQ(1, d.response_started_count());
6864 EXPECT_FALSE(d.received_data_before_response());
6865 EXPECT_NE(0, d.bytes_received());
6869 TEST_F(HTTPSRequestTest, ResumeTest) {
6870 // Test that we attempt a session resume when making two connections to the
6871 // same host.
6872 SpawnedTestServer::SSLOptions ssl_options;
6873 ssl_options.record_resume = true;
6874 SpawnedTestServer test_server(
6875 SpawnedTestServer::TYPE_HTTPS,
6876 ssl_options,
6877 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6878 ASSERT_TRUE(test_server.Start());
6880 SSLClientSocket::ClearSessionCache();
6883 TestDelegate d;
6884 URLRequest r(test_server.GetURL("ssl-session-cache"),
6885 DEFAULT_PRIORITY,
6887 &default_context_);
6889 r.Start();
6890 EXPECT_TRUE(r.is_pending());
6892 base::RunLoop().Run();
6894 EXPECT_EQ(1, d.response_started_count());
6897 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
6898 CloseAllConnections();
6901 TestDelegate d;
6902 URLRequest r(test_server.GetURL("ssl-session-cache"),
6903 DEFAULT_PRIORITY,
6905 &default_context_);
6907 r.Start();
6908 EXPECT_TRUE(r.is_pending());
6910 base::RunLoop().Run();
6912 // The response will look like;
6913 // insert abc
6914 // lookup abc
6915 // insert xyz
6917 // With a newline at the end which makes the split think that there are
6918 // four lines.
6920 EXPECT_EQ(1, d.response_started_count());
6921 std::vector<std::string> lines;
6922 base::SplitString(d.data_received(), '\n', &lines);
6923 ASSERT_EQ(4u, lines.size()) << d.data_received();
6925 std::string session_id;
6927 for (size_t i = 0; i < 2; i++) {
6928 std::vector<std::string> parts;
6929 base::SplitString(lines[i], '\t', &parts);
6930 ASSERT_EQ(2u, parts.size());
6931 if (i == 0) {
6932 EXPECT_EQ("insert", parts[0]);
6933 session_id = parts[1];
6934 } else {
6935 EXPECT_EQ("lookup", parts[0]);
6936 EXPECT_EQ(session_id, parts[1]);
6942 TEST_F(HTTPSRequestTest, SSLSessionCacheShardTest) {
6943 // Test that sessions aren't resumed when the value of ssl_session_cache_shard
6944 // differs.
6945 SpawnedTestServer::SSLOptions ssl_options;
6946 ssl_options.record_resume = true;
6947 SpawnedTestServer test_server(
6948 SpawnedTestServer::TYPE_HTTPS,
6949 ssl_options,
6950 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6951 ASSERT_TRUE(test_server.Start());
6953 SSLClientSocket::ClearSessionCache();
6956 TestDelegate d;
6957 URLRequest r(test_server.GetURL("ssl-session-cache"),
6958 DEFAULT_PRIORITY,
6960 &default_context_);
6962 r.Start();
6963 EXPECT_TRUE(r.is_pending());
6965 base::RunLoop().Run();
6967 EXPECT_EQ(1, d.response_started_count());
6970 // Now create a new HttpCache with a different ssl_session_cache_shard value.
6971 HttpNetworkSession::Params params;
6972 params.host_resolver = default_context_.host_resolver();
6973 params.cert_verifier = default_context_.cert_verifier();
6974 params.transport_security_state = default_context_.transport_security_state();
6975 params.proxy_service = default_context_.proxy_service();
6976 params.ssl_config_service = default_context_.ssl_config_service();
6977 params.http_auth_handler_factory =
6978 default_context_.http_auth_handler_factory();
6979 params.network_delegate = &default_network_delegate_;
6980 params.http_server_properties = default_context_.http_server_properties();
6981 params.ssl_session_cache_shard = "alternate";
6983 scoped_ptr<net::HttpCache> cache(new net::HttpCache(
6984 new net::HttpNetworkSession(params),
6985 net::HttpCache::DefaultBackend::InMemory(0)));
6987 default_context_.set_http_transaction_factory(cache.get());
6990 TestDelegate d;
6991 URLRequest r(test_server.GetURL("ssl-session-cache"),
6992 DEFAULT_PRIORITY,
6994 &default_context_);
6996 r.Start();
6997 EXPECT_TRUE(r.is_pending());
6999 base::RunLoop().Run();
7001 // The response will look like;
7002 // insert abc
7003 // insert xyz
7005 // With a newline at the end which makes the split think that there are
7006 // three lines.
7008 EXPECT_EQ(1, d.response_started_count());
7009 std::vector<std::string> lines;
7010 base::SplitString(d.data_received(), '\n', &lines);
7011 ASSERT_EQ(3u, lines.size());
7013 std::string session_id;
7014 for (size_t i = 0; i < 2; i++) {
7015 std::vector<std::string> parts;
7016 base::SplitString(lines[i], '\t', &parts);
7017 ASSERT_EQ(2u, parts.size());
7018 EXPECT_EQ("insert", parts[0]);
7019 if (i == 0) {
7020 session_id = parts[1];
7021 } else {
7022 EXPECT_NE(session_id, parts[1]);
7028 class HTTPSSessionTest : public testing::Test {
7029 public:
7030 HTTPSSessionTest() : default_context_(true) {
7031 cert_verifier_.set_default_result(net::OK);
7033 default_context_.set_network_delegate(&default_network_delegate_);
7034 default_context_.set_cert_verifier(&cert_verifier_);
7035 default_context_.Init();
7037 virtual ~HTTPSSessionTest() {}
7039 protected:
7040 MockCertVerifier cert_verifier_;
7041 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
7042 TestURLRequestContext default_context_;
7045 // Tests that session resumption is not attempted if an invalid certificate
7046 // is presented.
7047 TEST_F(HTTPSSessionTest, DontResumeSessionsForInvalidCertificates) {
7048 SpawnedTestServer::SSLOptions ssl_options;
7049 ssl_options.record_resume = true;
7050 SpawnedTestServer test_server(
7051 SpawnedTestServer::TYPE_HTTPS,
7052 ssl_options,
7053 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7054 ASSERT_TRUE(test_server.Start());
7056 SSLClientSocket::ClearSessionCache();
7058 // Simulate the certificate being expired and attempt a connection.
7059 cert_verifier_.set_default_result(net::ERR_CERT_DATE_INVALID);
7061 TestDelegate d;
7062 URLRequest r(test_server.GetURL("ssl-session-cache"),
7063 DEFAULT_PRIORITY,
7065 &default_context_);
7067 r.Start();
7068 EXPECT_TRUE(r.is_pending());
7070 base::RunLoop().Run();
7072 EXPECT_EQ(1, d.response_started_count());
7075 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
7076 CloseAllConnections();
7078 // Now change the certificate to be acceptable (so that the response is
7079 // loaded), and ensure that no session id is presented to the peer.
7080 cert_verifier_.set_default_result(net::OK);
7082 TestDelegate d;
7083 URLRequest r(test_server.GetURL("ssl-session-cache"),
7084 DEFAULT_PRIORITY,
7086 &default_context_);
7088 r.Start();
7089 EXPECT_TRUE(r.is_pending());
7091 base::RunLoop().Run();
7093 // The response will look like;
7094 // insert abc
7095 // insert xyz
7097 // With a newline at the end which makes the split think that there are
7098 // three lines.
7100 // If a session was presented (eg: a bug), then the response would look
7101 // like;
7102 // insert abc
7103 // lookup abc
7104 // insert xyz
7106 EXPECT_EQ(1, d.response_started_count());
7107 std::vector<std::string> lines;
7108 base::SplitString(d.data_received(), '\n', &lines);
7109 ASSERT_EQ(3u, lines.size()) << d.data_received();
7111 std::string session_id;
7112 for (size_t i = 0; i < 2; i++) {
7113 std::vector<std::string> parts;
7114 base::SplitString(lines[i], '\t', &parts);
7115 ASSERT_EQ(2u, parts.size());
7116 EXPECT_EQ("insert", parts[0]);
7117 if (i == 0) {
7118 session_id = parts[1];
7119 } else {
7120 EXPECT_NE(session_id, parts[1]);
7126 class TestSSLConfigService : public SSLConfigService {
7127 public:
7128 TestSSLConfigService(bool ev_enabled,
7129 bool online_rev_checking,
7130 bool rev_checking_required_local_anchors)
7131 : ev_enabled_(ev_enabled),
7132 online_rev_checking_(online_rev_checking),
7133 rev_checking_required_local_anchors_(
7134 rev_checking_required_local_anchors) {}
7136 // SSLConfigService:
7137 virtual void GetSSLConfig(SSLConfig* config) OVERRIDE {
7138 *config = SSLConfig();
7139 config->rev_checking_enabled = online_rev_checking_;
7140 config->verify_ev_cert = ev_enabled_;
7141 config->rev_checking_required_local_anchors =
7142 rev_checking_required_local_anchors_;
7145 protected:
7146 virtual ~TestSSLConfigService() {}
7148 private:
7149 const bool ev_enabled_;
7150 const bool online_rev_checking_;
7151 const bool rev_checking_required_local_anchors_;
7154 // This the fingerprint of the "Testing CA" certificate used by the testserver.
7155 // See net/data/ssl/certificates/ocsp-test-root.pem.
7156 static const SHA1HashValue kOCSPTestCertFingerprint =
7157 { { 0xf1, 0xad, 0xf6, 0xce, 0x42, 0xac, 0xe7, 0xb4, 0xf4, 0x24,
7158 0xdb, 0x1a, 0xf7, 0xa0, 0x9f, 0x09, 0xa1, 0xea, 0xf1, 0x5c } };
7160 // This is the SHA256, SPKI hash of the "Testing CA" certificate used by the
7161 // testserver.
7162 static const SHA256HashValue kOCSPTestCertSPKI = { {
7163 0xee, 0xe6, 0x51, 0x2d, 0x4c, 0xfa, 0xf7, 0x3e,
7164 0x6c, 0xd8, 0xca, 0x67, 0xed, 0xb5, 0x5d, 0x49,
7165 0x76, 0xe1, 0x52, 0xa7, 0x6e, 0x0e, 0xa0, 0x74,
7166 0x09, 0x75, 0xe6, 0x23, 0x24, 0xbd, 0x1b, 0x28,
7167 } };
7169 // This is the policy OID contained in the certificates that testserver
7170 // generates.
7171 static const char kOCSPTestCertPolicy[] = "1.3.6.1.4.1.11129.2.4.1";
7173 class HTTPSOCSPTest : public HTTPSRequestTest {
7174 public:
7175 HTTPSOCSPTest()
7176 : context_(true),
7177 ev_test_policy_(
7178 new ScopedTestEVPolicy(EVRootCAMetadata::GetInstance(),
7179 kOCSPTestCertFingerprint,
7180 kOCSPTestCertPolicy)) {
7183 virtual void SetUp() OVERRIDE {
7184 SetupContext(&context_);
7185 context_.Init();
7187 scoped_refptr<net::X509Certificate> root_cert =
7188 ImportCertFromFile(GetTestCertsDirectory(), "ocsp-test-root.pem");
7189 CHECK_NE(static_cast<X509Certificate*>(NULL), root_cert);
7190 test_root_.reset(new ScopedTestRoot(root_cert.get()));
7192 #if defined(USE_NSS) || defined(OS_IOS)
7193 SetURLRequestContextForNSSHttpIO(&context_);
7194 EnsureNSSHttpIOInit();
7195 #endif
7198 void DoConnection(const SpawnedTestServer::SSLOptions& ssl_options,
7199 CertStatus* out_cert_status) {
7200 // We always overwrite out_cert_status.
7201 *out_cert_status = 0;
7202 SpawnedTestServer test_server(
7203 SpawnedTestServer::TYPE_HTTPS,
7204 ssl_options,
7205 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7206 ASSERT_TRUE(test_server.Start());
7208 TestDelegate d;
7209 d.set_allow_certificate_errors(true);
7210 URLRequest r(
7211 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d, &context_);
7212 r.Start();
7214 base::RunLoop().Run();
7216 EXPECT_EQ(1, d.response_started_count());
7217 *out_cert_status = r.ssl_info().cert_status;
7220 virtual ~HTTPSOCSPTest() {
7221 #if defined(USE_NSS) || defined(OS_IOS)
7222 ShutdownNSSHttpIO();
7223 #endif
7226 protected:
7227 // SetupContext configures the URLRequestContext that will be used for making
7228 // connetions to testserver. This can be overridden in test subclasses for
7229 // different behaviour.
7230 virtual void SetupContext(URLRequestContext* context) {
7231 context->set_ssl_config_service(
7232 new TestSSLConfigService(true /* check for EV */,
7233 true /* online revocation checking */,
7234 false /* require rev. checking for local
7235 anchors */));
7238 scoped_ptr<ScopedTestRoot> test_root_;
7239 TestURLRequestContext context_;
7240 scoped_ptr<ScopedTestEVPolicy> ev_test_policy_;
7243 static CertStatus ExpectedCertStatusForFailedOnlineRevocationCheck() {
7244 #if defined(OS_WIN)
7245 // Windows can return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION but we don't
7246 // have that ability on other platforms.
7247 return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION;
7248 #else
7249 return 0;
7250 #endif
7253 // SystemSupportsHardFailRevocationChecking returns true iff the current
7254 // operating system supports revocation checking and can distinguish between
7255 // situations where a given certificate lacks any revocation information (eg:
7256 // no CRLDistributionPoints and no OCSP Responder AuthorityInfoAccess) and when
7257 // revocation information cannot be obtained (eg: the CRL was unreachable).
7258 // If it does not, then tests which rely on 'hard fail' behaviour should be
7259 // skipped.
7260 static bool SystemSupportsHardFailRevocationChecking() {
7261 #if defined(OS_WIN) || defined(USE_NSS) || defined(OS_IOS)
7262 return true;
7263 #else
7264 return false;
7265 #endif
7268 // SystemUsesChromiumEVMetadata returns true iff the current operating system
7269 // uses Chromium's EV metadata (i.e. EVRootCAMetadata). If it does not, then
7270 // several tests are effected because our testing EV certificate won't be
7271 // recognised as EV.
7272 static bool SystemUsesChromiumEVMetadata() {
7273 #if defined(USE_OPENSSL_CERTS) && !defined(OS_ANDROID)
7274 // http://crbug.com/117478 - OpenSSL does not support EV validation.
7275 return false;
7276 #elif (defined(OS_MACOSX) && !defined(OS_IOS)) || defined(OS_ANDROID)
7277 // On OS X and Android, we use the system to tell us whether a certificate is
7278 // EV or not and the system won't recognise our testing root.
7279 return false;
7280 #else
7281 return true;
7282 #endif
7285 static bool SystemSupportsOCSP() {
7286 #if defined(USE_OPENSSL)
7287 // http://crbug.com/117478 - OpenSSL does not support OCSP.
7288 return false;
7289 #elif defined(OS_WIN)
7290 return base::win::GetVersion() >= base::win::VERSION_VISTA;
7291 #elif defined(OS_ANDROID)
7292 // TODO(jnd): http://crbug.com/117478 - EV verification is not yet supported.
7293 return false;
7294 #else
7295 return true;
7296 #endif
7299 TEST_F(HTTPSOCSPTest, Valid) {
7300 if (!SystemSupportsOCSP()) {
7301 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
7302 return;
7305 SpawnedTestServer::SSLOptions ssl_options(
7306 SpawnedTestServer::SSLOptions::CERT_AUTO);
7307 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
7309 CertStatus cert_status;
7310 DoConnection(ssl_options, &cert_status);
7312 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
7314 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
7315 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
7317 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
7320 TEST_F(HTTPSOCSPTest, Revoked) {
7321 if (!SystemSupportsOCSP()) {
7322 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
7323 return;
7326 SpawnedTestServer::SSLOptions ssl_options(
7327 SpawnedTestServer::SSLOptions::CERT_AUTO);
7328 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
7330 CertStatus cert_status;
7331 DoConnection(ssl_options, &cert_status);
7333 #if !(defined(OS_MACOSX) && !defined(OS_IOS))
7334 // Doesn't pass on OS X yet for reasons that need to be investigated.
7335 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
7336 #endif
7337 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
7338 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
7341 TEST_F(HTTPSOCSPTest, Invalid) {
7342 if (!SystemSupportsOCSP()) {
7343 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
7344 return;
7347 SpawnedTestServer::SSLOptions ssl_options(
7348 SpawnedTestServer::SSLOptions::CERT_AUTO);
7349 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
7351 CertStatus cert_status;
7352 DoConnection(ssl_options, &cert_status);
7354 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
7355 cert_status & CERT_STATUS_ALL_ERRORS);
7357 // Without a positive OCSP response, we shouldn't show the EV status.
7358 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
7359 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
7362 class HTTPSHardFailTest : public HTTPSOCSPTest {
7363 protected:
7364 virtual void SetupContext(URLRequestContext* context) OVERRIDE {
7365 context->set_ssl_config_service(
7366 new TestSSLConfigService(false /* check for EV */,
7367 false /* online revocation checking */,
7368 true /* require rev. checking for local
7369 anchors */));
7374 TEST_F(HTTPSHardFailTest, FailsOnOCSPInvalid) {
7375 if (!SystemSupportsOCSP()) {
7376 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
7377 return;
7380 if (!SystemSupportsHardFailRevocationChecking()) {
7381 LOG(WARNING) << "Skipping test because system doesn't support hard fail "
7382 << "revocation checking";
7383 return;
7386 SpawnedTestServer::SSLOptions ssl_options(
7387 SpawnedTestServer::SSLOptions::CERT_AUTO);
7388 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
7390 CertStatus cert_status;
7391 DoConnection(ssl_options, &cert_status);
7393 EXPECT_EQ(CERT_STATUS_REVOKED,
7394 cert_status & CERT_STATUS_REVOKED);
7396 // Without a positive OCSP response, we shouldn't show the EV status.
7397 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
7400 class HTTPSEVCRLSetTest : public HTTPSOCSPTest {
7401 protected:
7402 virtual void SetupContext(URLRequestContext* context) OVERRIDE {
7403 context->set_ssl_config_service(
7404 new TestSSLConfigService(true /* check for EV */,
7405 false /* online revocation checking */,
7406 false /* require rev. checking for local
7407 anchors */));
7411 TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndInvalidOCSP) {
7412 if (!SystemSupportsOCSP()) {
7413 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
7414 return;
7417 SpawnedTestServer::SSLOptions ssl_options(
7418 SpawnedTestServer::SSLOptions::CERT_AUTO);
7419 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
7420 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
7422 CertStatus cert_status;
7423 DoConnection(ssl_options, &cert_status);
7425 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
7426 cert_status & CERT_STATUS_ALL_ERRORS);
7428 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
7429 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
7430 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
7433 TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndRevokedOCSP) {
7434 if (!SystemSupportsOCSP()) {
7435 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
7436 return;
7439 SpawnedTestServer::SSLOptions ssl_options(
7440 SpawnedTestServer::SSLOptions::CERT_AUTO);
7441 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
7442 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
7444 CertStatus cert_status;
7445 DoConnection(ssl_options, &cert_status);
7447 // Currently only works for Windows. When using NSS or OS X, it's not
7448 // possible to determine whether the check failed because of actual
7449 // revocation or because there was an OCSP failure.
7450 #if defined(OS_WIN)
7451 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
7452 #else
7453 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
7454 #endif
7456 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
7457 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
7458 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
7461 TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndGoodOCSP) {
7462 if (!SystemSupportsOCSP()) {
7463 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
7464 return;
7467 SpawnedTestServer::SSLOptions ssl_options(
7468 SpawnedTestServer::SSLOptions::CERT_AUTO);
7469 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
7470 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
7472 CertStatus cert_status;
7473 DoConnection(ssl_options, &cert_status);
7475 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
7477 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
7478 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
7479 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
7480 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
7483 TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSet) {
7484 if (!SystemSupportsOCSP()) {
7485 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
7486 return;
7489 SpawnedTestServer::SSLOptions ssl_options(
7490 SpawnedTestServer::SSLOptions::CERT_AUTO);
7491 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
7492 SSLConfigService::SetCRLSet(
7493 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
7495 CertStatus cert_status;
7496 DoConnection(ssl_options, &cert_status);
7498 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
7499 cert_status & CERT_STATUS_ALL_ERRORS);
7501 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
7502 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
7503 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
7506 TEST_F(HTTPSEVCRLSetTest, FreshCRLSetCovered) {
7507 if (!SystemSupportsOCSP()) {
7508 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
7509 return;
7512 SpawnedTestServer::SSLOptions ssl_options(
7513 SpawnedTestServer::SSLOptions::CERT_AUTO);
7514 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
7515 SSLConfigService::SetCRLSet(
7516 scoped_refptr<CRLSet>(CRLSet::ForTesting(
7517 false, &kOCSPTestCertSPKI, "")));
7519 CertStatus cert_status;
7520 DoConnection(ssl_options, &cert_status);
7522 // With a fresh CRLSet that covers the issuing certificate, we shouldn't do a
7523 // revocation check for EV.
7524 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
7525 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
7526 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
7527 EXPECT_FALSE(
7528 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
7531 TEST_F(HTTPSEVCRLSetTest, FreshCRLSetNotCovered) {
7532 if (!SystemSupportsOCSP()) {
7533 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
7534 return;
7537 SpawnedTestServer::SSLOptions ssl_options(
7538 SpawnedTestServer::SSLOptions::CERT_AUTO);
7539 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
7540 SSLConfigService::SetCRLSet(
7541 scoped_refptr<CRLSet>(CRLSet::EmptyCRLSetForTesting()));
7543 CertStatus cert_status = 0;
7544 DoConnection(ssl_options, &cert_status);
7546 // Even with a fresh CRLSet, we should still do online revocation checks when
7547 // the certificate chain isn't covered by the CRLSet, which it isn't in this
7548 // test.
7549 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
7550 cert_status & CERT_STATUS_ALL_ERRORS);
7552 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
7553 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
7554 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
7557 TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSetAndRevokedNonEVCert) {
7558 // Test that when EV verification is requested, but online revocation
7559 // checking is disabled, and the leaf certificate is not in fact EV, that
7560 // no revocation checking actually happens.
7561 if (!SystemSupportsOCSP()) {
7562 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
7563 return;
7566 // Unmark the certificate's OID as EV, which should disable revocation
7567 // checking (as per the user preference)
7568 ev_test_policy_.reset();
7570 SpawnedTestServer::SSLOptions ssl_options(
7571 SpawnedTestServer::SSLOptions::CERT_AUTO);
7572 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
7573 SSLConfigService::SetCRLSet(
7574 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
7576 CertStatus cert_status;
7577 DoConnection(ssl_options, &cert_status);
7579 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
7581 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
7582 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
7585 class HTTPSCRLSetTest : public HTTPSOCSPTest {
7586 protected:
7587 virtual void SetupContext(URLRequestContext* context) OVERRIDE {
7588 context->set_ssl_config_service(
7589 new TestSSLConfigService(false /* check for EV */,
7590 false /* online revocation checking */,
7591 false /* require rev. checking for local
7592 anchors */));
7596 TEST_F(HTTPSCRLSetTest, ExpiredCRLSet) {
7597 SpawnedTestServer::SSLOptions ssl_options(
7598 SpawnedTestServer::SSLOptions::CERT_AUTO);
7599 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
7600 SSLConfigService::SetCRLSet(
7601 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
7603 CertStatus cert_status;
7604 DoConnection(ssl_options, &cert_status);
7606 // If we're not trying EV verification then, even if the CRLSet has expired,
7607 // we don't fall back to online revocation checks.
7608 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
7609 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
7610 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
7613 TEST_F(HTTPSCRLSetTest, CRLSetRevoked) {
7614 #if defined(USE_OPENSSL)
7615 LOG(WARNING) << "Skipping test because system doesn't support CRLSets";
7616 return;
7617 #endif
7619 SpawnedTestServer::SSLOptions ssl_options(
7620 SpawnedTestServer::SSLOptions::CERT_AUTO);
7621 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
7622 ssl_options.cert_serial = 10;
7623 SSLConfigService::SetCRLSet(
7624 scoped_refptr<CRLSet>(CRLSet::ForTesting(
7625 false, &kOCSPTestCertSPKI, "\x0a")));
7627 CertStatus cert_status = 0;
7628 DoConnection(ssl_options, &cert_status);
7630 // If the certificate is recorded as revoked in the CRLSet, that should be
7631 // reflected without online revocation checking.
7632 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
7633 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
7634 EXPECT_FALSE(
7635 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
7637 #endif // !defined(OS_IOS)
7639 #if !defined(DISABLE_FTP_SUPPORT)
7640 class URLRequestTestFTP : public URLRequestTest {
7641 public:
7642 URLRequestTestFTP()
7643 : test_server_(SpawnedTestServer::TYPE_FTP, SpawnedTestServer::kLocalhost,
7644 base::FilePath()) {
7647 protected:
7648 SpawnedTestServer test_server_;
7651 // Make sure an FTP request using an unsafe ports fails.
7652 TEST_F(URLRequestTestFTP, UnsafePort) {
7653 ASSERT_TRUE(test_server_.Start());
7655 URLRequestJobFactoryImpl job_factory;
7656 FtpNetworkLayer ftp_transaction_factory(default_context_.host_resolver());
7658 GURL url("ftp://127.0.0.1:7");
7659 job_factory.SetProtocolHandler(
7660 "ftp",
7661 new FtpProtocolHandler(&ftp_transaction_factory));
7662 default_context_.set_job_factory(&job_factory);
7664 TestDelegate d;
7666 URLRequest r(url, DEFAULT_PRIORITY, &d, &default_context_);
7667 r.Start();
7668 EXPECT_TRUE(r.is_pending());
7670 base::RunLoop().Run();
7672 EXPECT_FALSE(r.is_pending());
7673 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
7674 EXPECT_EQ(ERR_UNSAFE_PORT, r.status().error());
7678 // Flaky, see http://crbug.com/25045.
7679 TEST_F(URLRequestTestFTP, DISABLED_FTPDirectoryListing) {
7680 ASSERT_TRUE(test_server_.Start());
7682 TestDelegate d;
7684 URLRequest r(
7685 test_server_.GetURL("/"), DEFAULT_PRIORITY, &d, &default_context_);
7686 r.Start();
7687 EXPECT_TRUE(r.is_pending());
7689 base::RunLoop().Run();
7691 EXPECT_FALSE(r.is_pending());
7692 EXPECT_EQ(1, d.response_started_count());
7693 EXPECT_FALSE(d.received_data_before_response());
7694 EXPECT_LT(0, d.bytes_received());
7695 EXPECT_EQ(test_server_.host_port_pair().host(),
7696 r.GetSocketAddress().host());
7697 EXPECT_EQ(test_server_.host_port_pair().port(),
7698 r.GetSocketAddress().port());
7702 // Flaky, see http://crbug.com/25045.
7703 TEST_F(URLRequestTestFTP, DISABLED_FTPGetTestAnonymous) {
7704 ASSERT_TRUE(test_server_.Start());
7706 base::FilePath app_path;
7707 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
7708 app_path = app_path.AppendASCII("LICENSE");
7709 TestDelegate d;
7711 URLRequest r(test_server_.GetURL("/LICENSE"),
7712 DEFAULT_PRIORITY,
7714 &default_context_);
7715 r.Start();
7716 EXPECT_TRUE(r.is_pending());
7718 base::RunLoop().Run();
7720 int64 file_size = 0;
7721 base::GetFileSize(app_path, &file_size);
7723 EXPECT_FALSE(r.is_pending());
7724 EXPECT_EQ(1, d.response_started_count());
7725 EXPECT_FALSE(d.received_data_before_response());
7726 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
7727 EXPECT_EQ(test_server_.host_port_pair().host(),
7728 r.GetSocketAddress().host());
7729 EXPECT_EQ(test_server_.host_port_pair().port(),
7730 r.GetSocketAddress().port());
7734 // Flaky, see http://crbug.com/25045.
7735 TEST_F(URLRequestTestFTP, DISABLED_FTPGetTest) {
7736 ASSERT_TRUE(test_server_.Start());
7738 base::FilePath app_path;
7739 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
7740 app_path = app_path.AppendASCII("LICENSE");
7741 TestDelegate d;
7743 URLRequest r(
7744 test_server_.GetURLWithUserAndPassword("/LICENSE", "chrome", "chrome"),
7745 DEFAULT_PRIORITY,
7747 &default_context_);
7748 r.Start();
7749 EXPECT_TRUE(r.is_pending());
7751 base::RunLoop().Run();
7753 int64 file_size = 0;
7754 base::GetFileSize(app_path, &file_size);
7756 EXPECT_FALSE(r.is_pending());
7757 EXPECT_EQ(test_server_.host_port_pair().host(),
7758 r.GetSocketAddress().host());
7759 EXPECT_EQ(test_server_.host_port_pair().port(),
7760 r.GetSocketAddress().port());
7761 EXPECT_EQ(1, d.response_started_count());
7762 EXPECT_FALSE(d.received_data_before_response());
7763 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
7765 LoadTimingInfo load_timing_info;
7766 r.GetLoadTimingInfo(&load_timing_info);
7767 TestLoadTimingNoHttpResponse(load_timing_info);
7771 // Flaky, see http://crbug.com/25045.
7772 TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongPassword) {
7773 ASSERT_TRUE(test_server_.Start());
7775 base::FilePath app_path;
7776 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
7777 app_path = app_path.AppendASCII("LICENSE");
7778 TestDelegate d;
7780 URLRequest r(test_server_.GetURLWithUserAndPassword(
7781 "/LICENSE", "chrome", "wrong_password"),
7782 DEFAULT_PRIORITY,
7784 &default_context_);
7785 r.Start();
7786 EXPECT_TRUE(r.is_pending());
7788 base::RunLoop().Run();
7790 int64 file_size = 0;
7791 base::GetFileSize(app_path, &file_size);
7793 EXPECT_FALSE(r.is_pending());
7794 EXPECT_EQ(1, d.response_started_count());
7795 EXPECT_FALSE(d.received_data_before_response());
7796 EXPECT_EQ(d.bytes_received(), 0);
7800 // Flaky, see http://crbug.com/25045.
7801 TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongPasswordRestart) {
7802 ASSERT_TRUE(test_server_.Start());
7804 base::FilePath app_path;
7805 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
7806 app_path = app_path.AppendASCII("LICENSE");
7807 TestDelegate d;
7808 // Set correct login credentials. The delegate will be asked for them when
7809 // the initial login with wrong credentials will fail.
7810 d.set_credentials(AuthCredentials(kChrome, kChrome));
7812 URLRequest r(test_server_.GetURLWithUserAndPassword(
7813 "/LICENSE", "chrome", "wrong_password"),
7814 DEFAULT_PRIORITY,
7816 &default_context_);
7817 r.Start();
7818 EXPECT_TRUE(r.is_pending());
7820 base::RunLoop().Run();
7822 int64 file_size = 0;
7823 base::GetFileSize(app_path, &file_size);
7825 EXPECT_FALSE(r.is_pending());
7826 EXPECT_EQ(1, d.response_started_count());
7827 EXPECT_FALSE(d.received_data_before_response());
7828 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
7832 // Flaky, see http://crbug.com/25045.
7833 TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongUser) {
7834 ASSERT_TRUE(test_server_.Start());
7836 base::FilePath app_path;
7837 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
7838 app_path = app_path.AppendASCII("LICENSE");
7839 TestDelegate d;
7841 URLRequest r(test_server_.GetURLWithUserAndPassword(
7842 "/LICENSE", "wrong_user", "chrome"),
7843 DEFAULT_PRIORITY,
7845 &default_context_);
7846 r.Start();
7847 EXPECT_TRUE(r.is_pending());
7849 base::RunLoop().Run();
7851 int64 file_size = 0;
7852 base::GetFileSize(app_path, &file_size);
7854 EXPECT_FALSE(r.is_pending());
7855 EXPECT_EQ(1, d.response_started_count());
7856 EXPECT_FALSE(d.received_data_before_response());
7857 EXPECT_EQ(d.bytes_received(), 0);
7861 // Flaky, see http://crbug.com/25045.
7862 TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongUserRestart) {
7863 ASSERT_TRUE(test_server_.Start());
7865 base::FilePath app_path;
7866 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
7867 app_path = app_path.AppendASCII("LICENSE");
7868 TestDelegate d;
7869 // Set correct login credentials. The delegate will be asked for them when
7870 // the initial login with wrong credentials will fail.
7871 d.set_credentials(AuthCredentials(kChrome, kChrome));
7873 URLRequest r(test_server_.GetURLWithUserAndPassword(
7874 "/LICENSE", "wrong_user", "chrome"),
7875 DEFAULT_PRIORITY,
7877 &default_context_);
7878 r.Start();
7879 EXPECT_TRUE(r.is_pending());
7881 base::RunLoop().Run();
7883 int64 file_size = 0;
7884 base::GetFileSize(app_path, &file_size);
7886 EXPECT_FALSE(r.is_pending());
7887 EXPECT_EQ(1, d.response_started_count());
7888 EXPECT_FALSE(d.received_data_before_response());
7889 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
7893 // Flaky, see http://crbug.com/25045.
7894 TEST_F(URLRequestTestFTP, DISABLED_FTPCacheURLCredentials) {
7895 ASSERT_TRUE(test_server_.Start());
7897 base::FilePath app_path;
7898 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
7899 app_path = app_path.AppendASCII("LICENSE");
7901 scoped_ptr<TestDelegate> d(new TestDelegate);
7903 // Pass correct login identity in the URL.
7904 URLRequest r(
7905 test_server_.GetURLWithUserAndPassword("/LICENSE", "chrome", "chrome"),
7906 DEFAULT_PRIORITY,
7907 d.get(),
7908 &default_context_);
7909 r.Start();
7910 EXPECT_TRUE(r.is_pending());
7912 base::RunLoop().Run();
7914 int64 file_size = 0;
7915 base::GetFileSize(app_path, &file_size);
7917 EXPECT_FALSE(r.is_pending());
7918 EXPECT_EQ(1, d->response_started_count());
7919 EXPECT_FALSE(d->received_data_before_response());
7920 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
7923 d.reset(new TestDelegate);
7925 // This request should use cached identity from previous request.
7926 URLRequest r(test_server_.GetURL("/LICENSE"),
7927 DEFAULT_PRIORITY,
7928 d.get(),
7929 &default_context_);
7930 r.Start();
7931 EXPECT_TRUE(r.is_pending());
7933 base::RunLoop().Run();
7935 int64 file_size = 0;
7936 base::GetFileSize(app_path, &file_size);
7938 EXPECT_FALSE(r.is_pending());
7939 EXPECT_EQ(1, d->response_started_count());
7940 EXPECT_FALSE(d->received_data_before_response());
7941 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
7945 // Flaky, see http://crbug.com/25045.
7946 TEST_F(URLRequestTestFTP, DISABLED_FTPCacheLoginBoxCredentials) {
7947 ASSERT_TRUE(test_server_.Start());
7949 base::FilePath app_path;
7950 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
7951 app_path = app_path.AppendASCII("LICENSE");
7953 scoped_ptr<TestDelegate> d(new TestDelegate);
7954 // Set correct login credentials. The delegate will be asked for them when
7955 // the initial login with wrong credentials will fail.
7956 d->set_credentials(AuthCredentials(kChrome, kChrome));
7958 URLRequest r(test_server_.GetURLWithUserAndPassword(
7959 "/LICENSE", "chrome", "wrong_password"),
7960 DEFAULT_PRIORITY,
7961 d.get(),
7962 &default_context_);
7963 r.Start();
7964 EXPECT_TRUE(r.is_pending());
7966 base::RunLoop().Run();
7968 int64 file_size = 0;
7969 base::GetFileSize(app_path, &file_size);
7971 EXPECT_FALSE(r.is_pending());
7972 EXPECT_EQ(1, d->response_started_count());
7973 EXPECT_FALSE(d->received_data_before_response());
7974 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
7977 // Use a new delegate without explicit credentials. The cached ones should be
7978 // used.
7979 d.reset(new TestDelegate);
7981 // Don't pass wrong credentials in the URL, they would override valid cached
7982 // ones.
7983 URLRequest r(test_server_.GetURL("/LICENSE"),
7984 DEFAULT_PRIORITY,
7985 d.get(),
7986 &default_context_);
7987 r.Start();
7988 EXPECT_TRUE(r.is_pending());
7990 base::RunLoop().Run();
7992 int64 file_size = 0;
7993 base::GetFileSize(app_path, &file_size);
7995 EXPECT_FALSE(r.is_pending());
7996 EXPECT_EQ(1, d->response_started_count());
7997 EXPECT_FALSE(d->received_data_before_response());
7998 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
8001 #endif // !defined(DISABLE_FTP_SUPPORT)
8003 } // namespace net