Lots of random cleanups, mostly for native_theme_win.cc:
[chromium-blink-merge.git] / net / url_request / url_request_unittest.cc
blobd139888eb384e092de81fcfabaf0b011b54866d0
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/load_flags.h"
34 #include "net/base/load_timing_info.h"
35 #include "net/base/load_timing_info_test_util.h"
36 #include "net/base/net_errors.h"
37 #include "net/base/net_log.h"
38 #include "net/base/net_log_unittest.h"
39 #include "net/base/net_module.h"
40 #include "net/base/net_util.h"
41 #include "net/base/request_priority.h"
42 #include "net/base/test_data_directory.h"
43 #include "net/base/upload_bytes_element_reader.h"
44 #include "net/base/upload_data_stream.h"
45 #include "net/base/upload_file_element_reader.h"
46 #include "net/cert/ev_root_ca_metadata.h"
47 #include "net/cert/mock_cert_verifier.h"
48 #include "net/cert/test_root_certs.h"
49 #include "net/cookies/cookie_monster.h"
50 #include "net/cookies/cookie_store_test_helpers.h"
51 #include "net/disk_cache/disk_cache.h"
52 #include "net/dns/mock_host_resolver.h"
53 #include "net/ftp/ftp_network_layer.h"
54 #include "net/http/http_byte_range.h"
55 #include "net/http/http_cache.h"
56 #include "net/http/http_network_layer.h"
57 #include "net/http/http_network_session.h"
58 #include "net/http/http_request_headers.h"
59 #include "net/http/http_response_headers.h"
60 #include "net/http/http_util.h"
61 #include "net/ocsp/nss_ocsp.h"
62 #include "net/proxy/proxy_service.h"
63 #include "net/socket/ssl_client_socket.h"
64 #include "net/ssl/ssl_connection_status_flags.h"
65 #include "net/test/cert_test_util.h"
66 #include "net/test/spawned_test_server/spawned_test_server.h"
67 #include "net/url_request/data_protocol_handler.h"
68 #include "net/url_request/static_http_user_agent_settings.h"
69 #include "net/url_request/url_request.h"
70 #include "net/url_request/url_request_http_job.h"
71 #include "net/url_request/url_request_job_factory_impl.h"
72 #include "net/url_request/url_request_redirect_job.h"
73 #include "net/url_request/url_request_test_job.h"
74 #include "net/url_request/url_request_test_util.h"
75 #include "testing/gtest/include/gtest/gtest.h"
76 #include "testing/platform_test.h"
78 #if !defined(DISABLE_FILE_SUPPORT)
79 #include "net/base/filename_util.h"
80 #include "net/url_request/file_protocol_handler.h"
81 #include "net/url_request/url_request_file_dir_job.h"
82 #endif
84 #if !defined(DISABLE_FTP_SUPPORT)
85 #include "net/url_request/ftp_protocol_handler.h"
86 #endif
88 #if defined(OS_WIN)
89 #include "base/win/scoped_com_initializer.h"
90 #include "base/win/scoped_comptr.h"
91 #include "base/win/windows_version.h"
92 #endif
94 using base::ASCIIToUTF16;
95 using base::Time;
97 namespace net {
99 namespace {
101 const base::string16 kChrome(ASCIIToUTF16("chrome"));
102 const base::string16 kSecret(ASCIIToUTF16("secret"));
103 const base::string16 kUser(ASCIIToUTF16("user"));
105 // Tests load timing information in the case a fresh connection was used, with
106 // no proxy.
107 void TestLoadTimingNotReused(const net::LoadTimingInfo& load_timing_info,
108 int connect_timing_flags) {
109 EXPECT_FALSE(load_timing_info.socket_reused);
110 EXPECT_NE(net::NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
112 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
113 EXPECT_FALSE(load_timing_info.request_start.is_null());
115 EXPECT_LE(load_timing_info.request_start,
116 load_timing_info.connect_timing.connect_start);
117 ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
118 connect_timing_flags);
119 EXPECT_LE(load_timing_info.connect_timing.connect_end,
120 load_timing_info.send_start);
121 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
122 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
124 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
125 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
128 // Same as above, but with proxy times.
129 void TestLoadTimingNotReusedWithProxy(
130 const net::LoadTimingInfo& load_timing_info,
131 int connect_timing_flags) {
132 EXPECT_FALSE(load_timing_info.socket_reused);
133 EXPECT_NE(net::NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
135 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
136 EXPECT_FALSE(load_timing_info.request_start.is_null());
138 EXPECT_LE(load_timing_info.request_start,
139 load_timing_info.proxy_resolve_start);
140 EXPECT_LE(load_timing_info.proxy_resolve_start,
141 load_timing_info.proxy_resolve_end);
142 EXPECT_LE(load_timing_info.proxy_resolve_end,
143 load_timing_info.connect_timing.connect_start);
144 ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
145 connect_timing_flags);
146 EXPECT_LE(load_timing_info.connect_timing.connect_end,
147 load_timing_info.send_start);
148 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
149 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
152 // Same as above, but with a reused socket and proxy times.
153 void TestLoadTimingReusedWithProxy(
154 const net::LoadTimingInfo& load_timing_info) {
155 EXPECT_TRUE(load_timing_info.socket_reused);
156 EXPECT_NE(net::NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
158 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
159 EXPECT_FALSE(load_timing_info.request_start.is_null());
161 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
163 EXPECT_LE(load_timing_info.request_start,
164 load_timing_info.proxy_resolve_start);
165 EXPECT_LE(load_timing_info.proxy_resolve_start,
166 load_timing_info.proxy_resolve_end);
167 EXPECT_LE(load_timing_info.proxy_resolve_end,
168 load_timing_info.send_start);
169 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
170 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
173 // Tests load timing information in the case of a cache hit, when no cache
174 // validation request was sent over the wire.
175 base::StringPiece TestNetResourceProvider(int key) {
176 return "header";
179 void FillBuffer(char* buffer, size_t len) {
180 static bool called = false;
181 if (!called) {
182 called = true;
183 int seed = static_cast<int>(Time::Now().ToInternalValue());
184 srand(seed);
187 for (size_t i = 0; i < len; i++) {
188 buffer[i] = static_cast<char>(rand());
189 if (!buffer[i])
190 buffer[i] = 'g';
194 #if !defined(OS_IOS)
195 void TestLoadTimingCacheHitNoNetwork(
196 const net::LoadTimingInfo& load_timing_info) {
197 EXPECT_FALSE(load_timing_info.socket_reused);
198 EXPECT_EQ(net::NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
200 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
201 EXPECT_FALSE(load_timing_info.request_start.is_null());
203 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
204 EXPECT_LE(load_timing_info.request_start, load_timing_info.send_start);
205 EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
206 EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
208 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
209 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
212 // Tests load timing in the case that there is no HTTP response. This can be
213 // used to test in the case of errors or non-HTTP requests.
214 void TestLoadTimingNoHttpResponse(
215 const net::LoadTimingInfo& load_timing_info) {
216 EXPECT_FALSE(load_timing_info.socket_reused);
217 EXPECT_EQ(net::NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
219 // Only the request times should be non-null.
220 EXPECT_FALSE(load_timing_info.request_start_time.is_null());
221 EXPECT_FALSE(load_timing_info.request_start.is_null());
223 ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
225 EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
226 EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
227 EXPECT_TRUE(load_timing_info.send_start.is_null());
228 EXPECT_TRUE(load_timing_info.send_end.is_null());
229 EXPECT_TRUE(load_timing_info.receive_headers_end.is_null());
232 // Do a case-insensitive search through |haystack| for |needle|.
233 bool ContainsString(const std::string& haystack, const char* needle) {
234 std::string::const_iterator it =
235 std::search(haystack.begin(),
236 haystack.end(),
237 needle,
238 needle + strlen(needle),
239 base::CaseInsensitiveCompare<char>());
240 return it != haystack.end();
243 UploadDataStream* CreateSimpleUploadData(const char* data) {
244 scoped_ptr<UploadElementReader> reader(
245 new UploadBytesElementReader(data, strlen(data)));
246 return UploadDataStream::CreateWithReader(reader.Pass(), 0);
249 // Verify that the SSLInfo of a successful SSL connection has valid values.
250 void CheckSSLInfo(const SSLInfo& ssl_info) {
251 // -1 means unknown. 0 means no encryption.
252 EXPECT_GT(ssl_info.security_bits, 0);
254 // The cipher suite TLS_NULL_WITH_NULL_NULL (0) must not be negotiated.
255 int cipher_suite = SSLConnectionStatusToCipherSuite(
256 ssl_info.connection_status);
257 EXPECT_NE(0, cipher_suite);
260 void CheckFullRequestHeaders(const HttpRequestHeaders& headers,
261 const GURL& host_url) {
262 std::string sent_value;
264 EXPECT_TRUE(headers.GetHeader("Host", &sent_value));
265 EXPECT_EQ(GetHostAndOptionalPort(host_url), sent_value);
267 EXPECT_TRUE(headers.GetHeader("Connection", &sent_value));
268 EXPECT_EQ("keep-alive", sent_value);
271 bool FingerprintsEqual(const HashValueVector& a, const HashValueVector& b) {
272 size_t size = a.size();
274 if (size != b.size())
275 return false;
277 for (size_t i = 0; i < size; ++i) {
278 if (!a[i].Equals(b[i]))
279 return false;
282 return true;
284 #endif // !defined(OS_IOS)
286 // A network delegate that allows the user to choose a subset of request stages
287 // to block in. When blocking, the delegate can do one of the following:
288 // * synchronously return a pre-specified error code, or
289 // * asynchronously return that value via an automatically called callback,
290 // or
291 // * block and wait for the user to do a callback.
292 // Additionally, the user may also specify a redirect URL -- then each request
293 // with the current URL different from the redirect target will be redirected
294 // to that target, in the on-before-URL-request stage, independent of whether
295 // the delegate blocks in ON_BEFORE_URL_REQUEST or not.
296 class BlockingNetworkDelegate : public TestNetworkDelegate {
297 public:
298 // Stages in which the delegate can block.
299 enum Stage {
300 NOT_BLOCKED = 0,
301 ON_BEFORE_URL_REQUEST = 1 << 0,
302 ON_BEFORE_SEND_HEADERS = 1 << 1,
303 ON_HEADERS_RECEIVED = 1 << 2,
304 ON_AUTH_REQUIRED = 1 << 3
307 // Behavior during blocked stages. During other stages, just
308 // returns net::OK or NetworkDelegate::AUTH_REQUIRED_RESPONSE_NO_ACTION.
309 enum BlockMode {
310 SYNCHRONOUS, // No callback, returns specified return values.
311 AUTO_CALLBACK, // |this| posts a task to run the callback using the
312 // specified return codes.
313 USER_CALLBACK, // User takes care of doing a callback. |retval_| and
314 // |auth_retval_| are ignored. In every blocking stage the
315 // message loop is quit.
318 // Creates a delegate which does not block at all.
319 explicit BlockingNetworkDelegate(BlockMode block_mode);
321 // For users to trigger a callback returning |response|.
322 // Side-effects: resets |stage_blocked_for_callback_| and stored callbacks.
323 // Only call if |block_mode_| == USER_CALLBACK.
324 void DoCallback(int response);
325 void DoAuthCallback(NetworkDelegate::AuthRequiredResponse response);
327 // Setters.
328 void set_retval(int retval) {
329 ASSERT_NE(USER_CALLBACK, block_mode_);
330 ASSERT_NE(ERR_IO_PENDING, retval);
331 ASSERT_NE(OK, retval);
332 retval_ = retval;
335 // If |auth_retval| == AUTH_REQUIRED_RESPONSE_SET_AUTH, then
336 // |auth_credentials_| will be passed with the response.
337 void set_auth_retval(AuthRequiredResponse auth_retval) {
338 ASSERT_NE(USER_CALLBACK, block_mode_);
339 ASSERT_NE(AUTH_REQUIRED_RESPONSE_IO_PENDING, auth_retval);
340 auth_retval_ = auth_retval;
342 void set_auth_credentials(const AuthCredentials& auth_credentials) {
343 auth_credentials_ = auth_credentials;
346 void set_redirect_url(const GURL& url) {
347 redirect_url_ = url;
350 void set_block_on(int block_on) {
351 block_on_ = block_on;
354 // Allows the user to check in which state did we block.
355 Stage stage_blocked_for_callback() const {
356 EXPECT_EQ(USER_CALLBACK, block_mode_);
357 return stage_blocked_for_callback_;
360 private:
361 void RunCallback(int response, const CompletionCallback& callback);
362 void RunAuthCallback(AuthRequiredResponse response,
363 const AuthCallback& callback);
365 // TestNetworkDelegate implementation.
366 virtual int OnBeforeURLRequest(URLRequest* request,
367 const CompletionCallback& callback,
368 GURL* new_url) OVERRIDE;
370 virtual int OnBeforeSendHeaders(URLRequest* request,
371 const CompletionCallback& callback,
372 HttpRequestHeaders* headers) OVERRIDE;
374 virtual int OnHeadersReceived(
375 URLRequest* request,
376 const CompletionCallback& callback,
377 const HttpResponseHeaders* original_response_headers,
378 scoped_refptr<HttpResponseHeaders>* override_response_headers,
379 GURL* allowed_unsafe_redirect_url) OVERRIDE;
381 virtual NetworkDelegate::AuthRequiredResponse OnAuthRequired(
382 URLRequest* request,
383 const AuthChallengeInfo& auth_info,
384 const AuthCallback& callback,
385 AuthCredentials* credentials) OVERRIDE;
387 // Resets the callbacks and |stage_blocked_for_callback_|.
388 void Reset();
390 // Checks whether we should block in |stage|. If yes, returns an error code
391 // and optionally sets up callback based on |block_mode_|. If no, returns OK.
392 int MaybeBlockStage(Stage stage, const CompletionCallback& callback);
394 // Configuration parameters, can be adjusted by public methods:
395 const BlockMode block_mode_;
397 // Values returned on blocking stages when mode is SYNCHRONOUS or
398 // AUTO_CALLBACK. For USER_CALLBACK these are set automatically to IO_PENDING.
399 int retval_; // To be returned in non-auth stages.
400 AuthRequiredResponse auth_retval_;
402 GURL redirect_url_; // Used if non-empty during OnBeforeURLRequest.
403 int block_on_; // Bit mask: in which stages to block.
405 // |auth_credentials_| will be copied to |*target_auth_credential_| on
406 // callback.
407 AuthCredentials auth_credentials_;
408 AuthCredentials* target_auth_credentials_;
410 // Internal variables, not set by not the user:
411 // Last blocked stage waiting for user callback (unused if |block_mode_| !=
412 // USER_CALLBACK).
413 Stage stage_blocked_for_callback_;
415 // Callback objects stored during blocking stages.
416 CompletionCallback callback_;
417 AuthCallback auth_callback_;
419 base::WeakPtrFactory<BlockingNetworkDelegate> weak_factory_;
421 DISALLOW_COPY_AND_ASSIGN(BlockingNetworkDelegate);
424 BlockingNetworkDelegate::BlockingNetworkDelegate(BlockMode block_mode)
425 : block_mode_(block_mode),
426 retval_(OK),
427 auth_retval_(AUTH_REQUIRED_RESPONSE_NO_ACTION),
428 block_on_(0),
429 target_auth_credentials_(NULL),
430 stage_blocked_for_callback_(NOT_BLOCKED),
431 weak_factory_(this) {
434 void BlockingNetworkDelegate::DoCallback(int response) {
435 ASSERT_EQ(USER_CALLBACK, block_mode_);
436 ASSERT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
437 ASSERT_NE(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
438 CompletionCallback callback = callback_;
439 Reset();
440 RunCallback(response, callback);
443 void BlockingNetworkDelegate::DoAuthCallback(
444 NetworkDelegate::AuthRequiredResponse response) {
445 ASSERT_EQ(USER_CALLBACK, block_mode_);
446 ASSERT_EQ(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
447 AuthCallback auth_callback = auth_callback_;
448 Reset();
449 RunAuthCallback(response, auth_callback);
452 void BlockingNetworkDelegate::RunCallback(int response,
453 const CompletionCallback& callback) {
454 callback.Run(response);
457 void BlockingNetworkDelegate::RunAuthCallback(AuthRequiredResponse response,
458 const AuthCallback& callback) {
459 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH) {
460 ASSERT_TRUE(target_auth_credentials_ != NULL);
461 *target_auth_credentials_ = auth_credentials_;
463 callback.Run(response);
466 int BlockingNetworkDelegate::OnBeforeURLRequest(
467 URLRequest* request,
468 const CompletionCallback& callback,
469 GURL* new_url) {
470 if (redirect_url_ == request->url())
471 return OK; // We've already seen this request and redirected elsewhere.
473 TestNetworkDelegate::OnBeforeURLRequest(request, callback, new_url);
475 if (!redirect_url_.is_empty())
476 *new_url = redirect_url_;
478 return MaybeBlockStage(ON_BEFORE_URL_REQUEST, callback);
481 int BlockingNetworkDelegate::OnBeforeSendHeaders(
482 URLRequest* request,
483 const CompletionCallback& callback,
484 HttpRequestHeaders* headers) {
485 TestNetworkDelegate::OnBeforeSendHeaders(request, callback, headers);
487 return MaybeBlockStage(ON_BEFORE_SEND_HEADERS, callback);
490 int BlockingNetworkDelegate::OnHeadersReceived(
491 URLRequest* request,
492 const CompletionCallback& callback,
493 const HttpResponseHeaders* original_response_headers,
494 scoped_refptr<HttpResponseHeaders>* override_response_headers,
495 GURL* allowed_unsafe_redirect_url) {
496 TestNetworkDelegate::OnHeadersReceived(request,
497 callback,
498 original_response_headers,
499 override_response_headers,
500 allowed_unsafe_redirect_url);
502 return MaybeBlockStage(ON_HEADERS_RECEIVED, callback);
505 NetworkDelegate::AuthRequiredResponse BlockingNetworkDelegate::OnAuthRequired(
506 URLRequest* request,
507 const AuthChallengeInfo& auth_info,
508 const AuthCallback& callback,
509 AuthCredentials* credentials) {
510 TestNetworkDelegate::OnAuthRequired(request, auth_info, callback,
511 credentials);
512 // Check that the user has provided callback for the previous blocked stage.
513 EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
515 if ((block_on_ & ON_AUTH_REQUIRED) == 0) {
516 return AUTH_REQUIRED_RESPONSE_NO_ACTION;
519 target_auth_credentials_ = credentials;
521 switch (block_mode_) {
522 case SYNCHRONOUS:
523 if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH)
524 *target_auth_credentials_ = auth_credentials_;
525 return auth_retval_;
527 case AUTO_CALLBACK:
528 base::MessageLoop::current()->PostTask(
529 FROM_HERE,
530 base::Bind(&BlockingNetworkDelegate::RunAuthCallback,
531 weak_factory_.GetWeakPtr(), auth_retval_, callback));
532 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
534 case USER_CALLBACK:
535 auth_callback_ = callback;
536 stage_blocked_for_callback_ = ON_AUTH_REQUIRED;
537 base::MessageLoop::current()->PostTask(FROM_HERE,
538 base::MessageLoop::QuitClosure());
539 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
541 NOTREACHED();
542 return AUTH_REQUIRED_RESPONSE_NO_ACTION; // Dummy value.
545 void BlockingNetworkDelegate::Reset() {
546 EXPECT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
547 stage_blocked_for_callback_ = NOT_BLOCKED;
548 callback_.Reset();
549 auth_callback_.Reset();
552 int BlockingNetworkDelegate::MaybeBlockStage(
553 BlockingNetworkDelegate::Stage stage,
554 const CompletionCallback& callback) {
555 // Check that the user has provided callback for the previous blocked stage.
556 EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
558 if ((block_on_ & stage) == 0) {
559 return OK;
562 switch (block_mode_) {
563 case SYNCHRONOUS:
564 EXPECT_NE(OK, retval_);
565 return retval_;
567 case AUTO_CALLBACK:
568 base::MessageLoop::current()->PostTask(
569 FROM_HERE,
570 base::Bind(&BlockingNetworkDelegate::RunCallback,
571 weak_factory_.GetWeakPtr(), retval_, callback));
572 return ERR_IO_PENDING;
574 case USER_CALLBACK:
575 callback_ = callback;
576 stage_blocked_for_callback_ = stage;
577 base::MessageLoop::current()->PostTask(FROM_HERE,
578 base::MessageLoop::QuitClosure());
579 return ERR_IO_PENDING;
581 NOTREACHED();
582 return 0;
585 class TestURLRequestContextWithProxy : public TestURLRequestContext {
586 public:
587 // Does not own |delegate|.
588 TestURLRequestContextWithProxy(const std::string& proxy,
589 NetworkDelegate* delegate)
590 : TestURLRequestContext(true) {
591 context_storage_.set_proxy_service(ProxyService::CreateFixed(proxy));
592 set_network_delegate(delegate);
593 Init();
595 virtual ~TestURLRequestContextWithProxy() {}
598 } // namespace
600 // Inherit PlatformTest since we require the autorelease pool on Mac OS X.
601 class URLRequestTest : public PlatformTest {
602 public:
603 URLRequestTest() : default_context_(true) {
604 default_context_.set_network_delegate(&default_network_delegate_);
605 default_context_.set_net_log(&net_log_);
606 job_factory_.SetProtocolHandler("data", new DataProtocolHandler);
607 #if !defined(DISABLE_FILE_SUPPORT)
608 job_factory_.SetProtocolHandler(
609 "file", new FileProtocolHandler(base::MessageLoopProxy::current()));
610 #endif
611 default_context_.set_job_factory(&job_factory_);
612 default_context_.Init();
614 virtual ~URLRequestTest() {
615 // URLRequestJobs may post clean-up tasks on destruction.
616 base::RunLoop().RunUntilIdle();
619 // Adds the TestJobInterceptor to the default context.
620 TestJobInterceptor* AddTestInterceptor() {
621 TestJobInterceptor* protocol_handler_ = new TestJobInterceptor();
622 job_factory_.SetProtocolHandler("http", NULL);
623 job_factory_.SetProtocolHandler("http", protocol_handler_);
624 return protocol_handler_;
627 protected:
628 CapturingNetLog net_log_;
629 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
630 URLRequestJobFactoryImpl job_factory_;
631 TestURLRequestContext default_context_;
634 TEST_F(URLRequestTest, AboutBlankTest) {
635 TestDelegate d;
637 URLRequest r(GURL("about:blank"), DEFAULT_PRIORITY, &d, &default_context_);
639 r.Start();
640 EXPECT_TRUE(r.is_pending());
642 base::RunLoop().Run();
644 EXPECT_TRUE(!r.is_pending());
645 EXPECT_FALSE(d.received_data_before_response());
646 EXPECT_EQ(d.bytes_received(), 0);
647 EXPECT_EQ("", r.GetSocketAddress().host());
648 EXPECT_EQ(0, r.GetSocketAddress().port());
650 HttpRequestHeaders headers;
651 EXPECT_FALSE(r.GetFullRequestHeaders(&headers));
655 TEST_F(URLRequestTest, DataURLImageTest) {
656 TestDelegate d;
658 // Use our nice little Chrome logo.
659 URLRequest r(
660 GURL(
661 "data:image/png;base64,"
662 "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAADVklEQVQ4jX2TfUwUBBjG3"
663 "w1y+HGcd9dxhXR8T4awOccJGgOSWclHImznLkTlSw0DDQXkrmgYgbUYnlQTqQxIEVxitD"
664 "5UMCATRA1CEEg+Qjw3bWDxIauJv/5oumqs39/P827vnucRmYN0gyF01GI5MpCVdW0gO7t"
665 "vNC+vqSEtbZefk5NuLv1jdJ46p/zw0HeH4+PHr3h7c1mjoV2t5rKzMx1+fg9bAgK6zHq9"
666 "cU5z+LpA3xOtx34+vTeT21onRuzssC3zxbbSwC13d/pFuC7CkIMDxQpF7r/MWq12UctI1"
667 "dWWm99ypqSYmRUBdKem8MkrO/kgaTt1O7YzlpzE5GIVd0WYUqt57yWf2McHTObYPbVD+Z"
668 "wbtlLTVMZ3BW+TnLyXLaWtmEq6WJVbT3HBh3Svj2HQQcm43XwmtoYM6vVKleh0uoWvnzW"
669 "3v3MpidruPTQPf0bia7sJOtBM0ufTWNvus/nkDFHF9ZS+uYVjRUasMeHUmyLYtcklTvzW"
670 "GFZnNOXczThvpKIzjcahSqIzkvDLayDq6D3eOjtBbNUEIZYyqsvj4V4wY92eNJ4IoyhTb"
671 "xXX1T5xsV9tm9r4TQwHLiZw/pdDZJea8TKmsmR/K0uLh/GwnCHghTja6lPhphezPfO5/5"
672 "MrVvMzNaI3+ERHfrFzPKQukrQGI4d/3EFD/3E2mVNYvi4at7CXWREaxZGD+3hg28zD3gV"
673 "Md6q5c8GdosynKmSeRuGzpjyl1/9UDGtPR5HeaKT8Wjo17WXk579BXVUhN64ehF9fhRtq"
674 "/uxxZKzNiZFGD0wRC3NFROZ5mwIPL/96K/rKMMLrIzF9uhHr+/sYH7DAbwlgC4J+R2Z7F"
675 "Ux1qLnV7MGF40smVSoJ/jvHRfYhQeUJd/SnYtGWhPHR0Sz+GE2F2yth0B36Vcz2KpnufB"
676 "JbsysjjW4kblBUiIjiURUWqJY65zxbnTy57GQyH58zgy0QBtTQv5gH15XMdKkYu+TGaJM"
677 "nlm2O34uI4b9tflqp1+QEFGzoW/ulmcofcpkZCYJhDfSpme7QcrHa+Xfji8paEQkTkSfm"
678 "moRWRNZr/F1KfVMjW+IKEnv2FwZfKdzt0BQR6lClcZR0EfEXEfv/G6W9iLiIyCoReV5En"
679 "hORIBHx+ufPj/gLB/zGI/G4Bk0AAAAASUVORK5CYII="),
680 DEFAULT_PRIORITY,
682 &default_context_);
684 r.Start();
685 EXPECT_TRUE(r.is_pending());
687 base::RunLoop().Run();
689 EXPECT_TRUE(!r.is_pending());
690 EXPECT_FALSE(d.received_data_before_response());
691 EXPECT_EQ(d.bytes_received(), 911);
692 EXPECT_EQ("", r.GetSocketAddress().host());
693 EXPECT_EQ(0, r.GetSocketAddress().port());
695 HttpRequestHeaders headers;
696 EXPECT_FALSE(r.GetFullRequestHeaders(&headers));
700 #if !defined(DISABLE_FILE_SUPPORT)
701 TEST_F(URLRequestTest, FileTest) {
702 base::FilePath app_path;
703 PathService::Get(base::FILE_EXE, &app_path);
704 GURL app_url = FilePathToFileURL(app_path);
706 TestDelegate d;
708 URLRequest r(app_url, DEFAULT_PRIORITY, &d, &default_context_);
710 r.Start();
711 EXPECT_TRUE(r.is_pending());
713 base::RunLoop().Run();
715 int64 file_size = -1;
716 EXPECT_TRUE(base::GetFileSize(app_path, &file_size));
718 EXPECT_TRUE(!r.is_pending());
719 EXPECT_EQ(1, d.response_started_count());
720 EXPECT_FALSE(d.received_data_before_response());
721 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
722 EXPECT_EQ("", r.GetSocketAddress().host());
723 EXPECT_EQ(0, r.GetSocketAddress().port());
725 HttpRequestHeaders headers;
726 EXPECT_FALSE(r.GetFullRequestHeaders(&headers));
730 TEST_F(URLRequestTest, FileTestCancel) {
731 base::FilePath app_path;
732 PathService::Get(base::FILE_EXE, &app_path);
733 GURL app_url = FilePathToFileURL(app_path);
735 TestDelegate d;
737 URLRequest r(app_url, DEFAULT_PRIORITY, &d, &default_context_);
739 r.Start();
740 EXPECT_TRUE(r.is_pending());
741 r.Cancel();
743 // Async cancellation should be safe even when URLRequest has been already
744 // destroyed.
745 base::RunLoop().RunUntilIdle();
748 TEST_F(URLRequestTest, FileTestFullSpecifiedRange) {
749 const size_t buffer_size = 4000;
750 scoped_ptr<char[]> buffer(new char[buffer_size]);
751 FillBuffer(buffer.get(), buffer_size);
753 base::FilePath temp_path;
754 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
755 GURL temp_url = FilePathToFileURL(temp_path);
756 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
758 int64 file_size;
759 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
761 const size_t first_byte_position = 500;
762 const size_t last_byte_position = buffer_size - first_byte_position;
763 const size_t content_length = last_byte_position - first_byte_position + 1;
764 std::string partial_buffer_string(buffer.get() + first_byte_position,
765 buffer.get() + last_byte_position + 1);
767 TestDelegate d;
769 URLRequest r(temp_url, DEFAULT_PRIORITY, &d, &default_context_);
771 HttpRequestHeaders headers;
772 headers.SetHeader(
773 HttpRequestHeaders::kRange,
774 net::HttpByteRange::Bounded(
775 first_byte_position, last_byte_position).GetHeaderValue());
776 r.SetExtraRequestHeaders(headers);
777 r.Start();
778 EXPECT_TRUE(r.is_pending());
780 base::RunLoop().Run();
781 EXPECT_TRUE(!r.is_pending());
782 EXPECT_EQ(1, d.response_started_count());
783 EXPECT_FALSE(d.received_data_before_response());
784 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
785 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
786 EXPECT_TRUE(partial_buffer_string == d.data_received());
789 EXPECT_TRUE(base::DeleteFile(temp_path, false));
792 TEST_F(URLRequestTest, FileTestHalfSpecifiedRange) {
793 const size_t buffer_size = 4000;
794 scoped_ptr<char[]> buffer(new char[buffer_size]);
795 FillBuffer(buffer.get(), buffer_size);
797 base::FilePath temp_path;
798 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
799 GURL temp_url = FilePathToFileURL(temp_path);
800 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
802 int64 file_size;
803 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
805 const size_t first_byte_position = 500;
806 const size_t last_byte_position = buffer_size - 1;
807 const size_t content_length = last_byte_position - first_byte_position + 1;
808 std::string partial_buffer_string(buffer.get() + first_byte_position,
809 buffer.get() + last_byte_position + 1);
811 TestDelegate d;
813 URLRequest r(temp_url, DEFAULT_PRIORITY, &d, &default_context_);
815 HttpRequestHeaders headers;
816 headers.SetHeader(HttpRequestHeaders::kRange,
817 net::HttpByteRange::RightUnbounded(
818 first_byte_position).GetHeaderValue());
819 r.SetExtraRequestHeaders(headers);
820 r.Start();
821 EXPECT_TRUE(r.is_pending());
823 base::RunLoop().Run();
824 EXPECT_TRUE(!r.is_pending());
825 EXPECT_EQ(1, d.response_started_count());
826 EXPECT_FALSE(d.received_data_before_response());
827 EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
828 // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
829 EXPECT_TRUE(partial_buffer_string == d.data_received());
832 EXPECT_TRUE(base::DeleteFile(temp_path, false));
835 TEST_F(URLRequestTest, FileTestMultipleRanges) {
836 const size_t buffer_size = 400000;
837 scoped_ptr<char[]> buffer(new char[buffer_size]);
838 FillBuffer(buffer.get(), buffer_size);
840 base::FilePath temp_path;
841 EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
842 GURL temp_url = FilePathToFileURL(temp_path);
843 EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
845 int64 file_size;
846 EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
848 TestDelegate d;
850 URLRequest r(temp_url, DEFAULT_PRIORITY, &d, &default_context_);
852 HttpRequestHeaders headers;
853 headers.SetHeader(HttpRequestHeaders::kRange, "bytes=0-0,10-200,200-300");
854 r.SetExtraRequestHeaders(headers);
855 r.Start();
856 EXPECT_TRUE(r.is_pending());
858 base::RunLoop().Run();
859 EXPECT_TRUE(d.request_failed());
862 EXPECT_TRUE(base::DeleteFile(temp_path, false));
865 TEST_F(URLRequestTest, AllowFileURLs) {
866 base::ScopedTempDir temp_dir;
867 ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
868 base::FilePath test_file;
869 ASSERT_TRUE(base::CreateTemporaryFileInDir(temp_dir.path(), &test_file));
870 std::string test_data("monkey");
871 base::WriteFile(test_file, test_data.data(), test_data.size());
872 GURL test_file_url = net::FilePathToFileURL(test_file);
875 TestDelegate d;
876 TestNetworkDelegate network_delegate;
877 network_delegate.set_can_access_files(true);
878 default_context_.set_network_delegate(&network_delegate);
879 URLRequest r(test_file_url, DEFAULT_PRIORITY, &d, &default_context_);
880 r.Start();
881 base::RunLoop().Run();
882 EXPECT_FALSE(d.request_failed());
883 EXPECT_EQ(test_data, d.data_received());
887 TestDelegate d;
888 TestNetworkDelegate network_delegate;
889 network_delegate.set_can_access_files(false);
890 default_context_.set_network_delegate(&network_delegate);
891 URLRequest r(test_file_url, DEFAULT_PRIORITY, &d, &default_context_);
892 r.Start();
893 base::RunLoop().Run();
894 EXPECT_TRUE(d.request_failed());
895 EXPECT_EQ("", d.data_received());
900 TEST_F(URLRequestTest, FileDirCancelTest) {
901 // Put in mock resource provider.
902 NetModule::SetResourceProvider(TestNetResourceProvider);
904 TestDelegate d;
906 base::FilePath file_path;
907 PathService::Get(base::DIR_SOURCE_ROOT, &file_path);
908 file_path = file_path.Append(FILE_PATH_LITERAL("net"));
909 file_path = file_path.Append(FILE_PATH_LITERAL("data"));
911 URLRequest req(
912 FilePathToFileURL(file_path), DEFAULT_PRIORITY, &d, &default_context_);
913 req.Start();
914 EXPECT_TRUE(req.is_pending());
916 d.set_cancel_in_received_data_pending(true);
918 base::RunLoop().Run();
921 // Take out mock resource provider.
922 NetModule::SetResourceProvider(NULL);
925 TEST_F(URLRequestTest, FileDirOutputSanity) {
926 // Verify the general sanity of the the output of the file:
927 // directory lister by checking for the output of a known existing
928 // file.
929 const char sentinel_name[] = "filedir-sentinel";
931 base::FilePath path;
932 PathService::Get(base::DIR_SOURCE_ROOT, &path);
933 path = path.Append(FILE_PATH_LITERAL("net"));
934 path = path.Append(FILE_PATH_LITERAL("data"));
935 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
937 TestDelegate d;
938 URLRequest req(
939 FilePathToFileURL(path), DEFAULT_PRIORITY, &d, &default_context_);
940 req.Start();
941 base::RunLoop().Run();
943 // Generate entry for the sentinel file.
944 base::FilePath sentinel_path = path.AppendASCII(sentinel_name);
945 base::File::Info info;
946 EXPECT_TRUE(base::GetFileInfo(sentinel_path, &info));
947 EXPECT_GT(info.size, 0);
948 std::string sentinel_output = GetDirectoryListingEntry(
949 base::string16(sentinel_name, sentinel_name + strlen(sentinel_name)),
950 std::string(sentinel_name),
951 false /* is_dir */,
952 info.size,
953 info.last_modified);
955 ASSERT_LT(0, d.bytes_received());
956 ASSERT_FALSE(d.request_failed());
957 ASSERT_TRUE(req.status().is_success());
958 // Check for the entry generated for the "sentinel" file.
959 const std::string& data = d.data_received();
960 ASSERT_NE(data.find(sentinel_output), std::string::npos);
963 TEST_F(URLRequestTest, FileDirRedirectNoCrash) {
964 // There is an implicit redirect when loading a file path that matches a
965 // directory and does not end with a slash. Ensure that following such
966 // redirects does not crash. See http://crbug.com/18686.
968 base::FilePath path;
969 PathService::Get(base::DIR_SOURCE_ROOT, &path);
970 path = path.Append(FILE_PATH_LITERAL("net"));
971 path = path.Append(FILE_PATH_LITERAL("data"));
972 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
974 TestDelegate d;
975 URLRequest req(
976 FilePathToFileURL(path), DEFAULT_PRIORITY, &d, &default_context_);
977 req.Start();
978 base::RunLoop().Run();
980 ASSERT_EQ(1, d.received_redirect_count());
981 ASSERT_LT(0, d.bytes_received());
982 ASSERT_FALSE(d.request_failed());
983 ASSERT_TRUE(req.status().is_success());
986 #if defined(OS_WIN)
987 // Don't accept the url "file:///" on windows. See http://crbug.com/1474.
988 TEST_F(URLRequestTest, FileDirRedirectSingleSlash) {
989 TestDelegate d;
990 URLRequest req(GURL("file:///"), DEFAULT_PRIORITY, &d, &default_context_);
991 req.Start();
992 base::RunLoop().Run();
994 ASSERT_EQ(1, d.received_redirect_count());
995 ASSERT_FALSE(req.status().is_success());
997 #endif // defined(OS_WIN)
999 #endif // !defined(DISABLE_FILE_SUPPORT)
1001 TEST_F(URLRequestTest, InvalidUrlTest) {
1002 TestDelegate d;
1004 URLRequest r(GURL("invalid url"), DEFAULT_PRIORITY, &d, &default_context_);
1006 r.Start();
1007 EXPECT_TRUE(r.is_pending());
1009 base::RunLoop().Run();
1010 EXPECT_TRUE(d.request_failed());
1014 #if defined(OS_WIN)
1015 TEST_F(URLRequestTest, ResolveShortcutTest) {
1016 base::FilePath app_path;
1017 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
1018 app_path = app_path.AppendASCII("net");
1019 app_path = app_path.AppendASCII("data");
1020 app_path = app_path.AppendASCII("url_request_unittest");
1021 app_path = app_path.AppendASCII("with-headers.html");
1023 std::wstring lnk_path = app_path.value() + L".lnk";
1025 base::win::ScopedCOMInitializer com_initializer;
1027 // Temporarily create a shortcut for test
1029 base::win::ScopedComPtr<IShellLink> shell;
1030 ASSERT_TRUE(SUCCEEDED(shell.CreateInstance(CLSID_ShellLink, NULL,
1031 CLSCTX_INPROC_SERVER)));
1032 base::win::ScopedComPtr<IPersistFile> persist;
1033 ASSERT_TRUE(SUCCEEDED(shell.QueryInterface(persist.Receive())));
1034 EXPECT_TRUE(SUCCEEDED(shell->SetPath(app_path.value().c_str())));
1035 EXPECT_TRUE(SUCCEEDED(shell->SetDescription(L"ResolveShortcutTest")));
1036 EXPECT_TRUE(SUCCEEDED(persist->Save(lnk_path.c_str(), TRUE)));
1039 TestDelegate d;
1041 URLRequest r(FilePathToFileURL(base::FilePath(lnk_path)),
1042 DEFAULT_PRIORITY,
1044 &default_context_);
1046 r.Start();
1047 EXPECT_TRUE(r.is_pending());
1049 base::RunLoop().Run();
1051 WIN32_FILE_ATTRIBUTE_DATA data;
1052 GetFileAttributesEx(app_path.value().c_str(),
1053 GetFileExInfoStandard, &data);
1054 HANDLE file = CreateFile(app_path.value().c_str(), GENERIC_READ,
1055 FILE_SHARE_READ, NULL, OPEN_EXISTING,
1056 FILE_ATTRIBUTE_NORMAL, NULL);
1057 EXPECT_NE(INVALID_HANDLE_VALUE, file);
1058 scoped_ptr<char[]> buffer(new char[data.nFileSizeLow]);
1059 DWORD read_size;
1060 BOOL result;
1061 result = ReadFile(file, buffer.get(), data.nFileSizeLow,
1062 &read_size, NULL);
1063 std::string content(buffer.get(), read_size);
1064 CloseHandle(file);
1066 EXPECT_TRUE(!r.is_pending());
1067 EXPECT_EQ(1, d.received_redirect_count());
1068 EXPECT_EQ(content, d.data_received());
1071 // Clean the shortcut
1072 DeleteFile(lnk_path.c_str());
1074 #endif // defined(OS_WIN)
1076 // Custom URLRequestJobs for use with interceptor tests
1077 class RestartTestJob : public URLRequestTestJob {
1078 public:
1079 RestartTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1080 : URLRequestTestJob(request, network_delegate, true) {}
1081 protected:
1082 virtual void StartAsync() OVERRIDE {
1083 this->NotifyRestartRequired();
1085 private:
1086 virtual ~RestartTestJob() {}
1089 class CancelTestJob : public URLRequestTestJob {
1090 public:
1091 explicit CancelTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1092 : URLRequestTestJob(request, network_delegate, true) {}
1093 protected:
1094 virtual void StartAsync() OVERRIDE {
1095 request_->Cancel();
1097 private:
1098 virtual ~CancelTestJob() {}
1101 class CancelThenRestartTestJob : public URLRequestTestJob {
1102 public:
1103 explicit CancelThenRestartTestJob(URLRequest* request,
1104 NetworkDelegate* network_delegate)
1105 : URLRequestTestJob(request, network_delegate, true) {
1107 protected:
1108 virtual void StartAsync() OVERRIDE {
1109 request_->Cancel();
1110 this->NotifyRestartRequired();
1112 private:
1113 virtual ~CancelThenRestartTestJob() {}
1116 // An Interceptor for use with interceptor tests
1117 class TestInterceptor : URLRequest::Interceptor {
1118 public:
1119 TestInterceptor()
1120 : intercept_main_request_(false), restart_main_request_(false),
1121 cancel_main_request_(false), cancel_then_restart_main_request_(false),
1122 simulate_main_network_error_(false),
1123 intercept_redirect_(false), cancel_redirect_request_(false),
1124 intercept_final_response_(false), cancel_final_request_(false),
1125 did_intercept_main_(false), did_restart_main_(false),
1126 did_cancel_main_(false), did_cancel_then_restart_main_(false),
1127 did_simulate_error_main_(false),
1128 did_intercept_redirect_(false), did_cancel_redirect_(false),
1129 did_intercept_final_(false), did_cancel_final_(false) {
1130 URLRequest::Deprecated::RegisterRequestInterceptor(this);
1133 virtual ~TestInterceptor() {
1134 URLRequest::Deprecated::UnregisterRequestInterceptor(this);
1137 virtual URLRequestJob* MaybeIntercept(
1138 URLRequest* request,
1139 NetworkDelegate* network_delegate) OVERRIDE {
1140 if (restart_main_request_) {
1141 restart_main_request_ = false;
1142 did_restart_main_ = true;
1143 return new RestartTestJob(request, network_delegate);
1145 if (cancel_main_request_) {
1146 cancel_main_request_ = false;
1147 did_cancel_main_ = true;
1148 return new CancelTestJob(request, network_delegate);
1150 if (cancel_then_restart_main_request_) {
1151 cancel_then_restart_main_request_ = false;
1152 did_cancel_then_restart_main_ = true;
1153 return new CancelThenRestartTestJob(request, network_delegate);
1155 if (simulate_main_network_error_) {
1156 simulate_main_network_error_ = false;
1157 did_simulate_error_main_ = true;
1158 // will error since the requeted url is not one of its canned urls
1159 return new URLRequestTestJob(request, network_delegate, true);
1161 if (!intercept_main_request_)
1162 return NULL;
1163 intercept_main_request_ = false;
1164 did_intercept_main_ = true;
1165 URLRequestTestJob* job = new URLRequestTestJob(request,
1166 network_delegate,
1167 main_headers_,
1168 main_data_,
1169 true);
1170 job->set_load_timing_info(main_request_load_timing_info_);
1171 return job;
1174 virtual URLRequestJob* MaybeInterceptRedirect(
1175 URLRequest* request,
1176 NetworkDelegate* network_delegate,
1177 const GURL& location) OVERRIDE {
1178 if (cancel_redirect_request_) {
1179 cancel_redirect_request_ = false;
1180 did_cancel_redirect_ = true;
1181 return new CancelTestJob(request, network_delegate);
1183 if (!intercept_redirect_)
1184 return NULL;
1185 intercept_redirect_ = false;
1186 did_intercept_redirect_ = true;
1187 return new URLRequestTestJob(request,
1188 network_delegate,
1189 redirect_headers_,
1190 redirect_data_,
1191 true);
1194 virtual URLRequestJob* MaybeInterceptResponse(
1195 URLRequest* request, NetworkDelegate* network_delegate) OVERRIDE {
1196 if (cancel_final_request_) {
1197 cancel_final_request_ = false;
1198 did_cancel_final_ = true;
1199 return new CancelTestJob(request, network_delegate);
1201 if (!intercept_final_response_)
1202 return NULL;
1203 intercept_final_response_ = false;
1204 did_intercept_final_ = true;
1205 return new URLRequestTestJob(request,
1206 network_delegate,
1207 final_headers_,
1208 final_data_,
1209 true);
1212 // Whether to intercept the main request, and if so the response to return and
1213 // the LoadTimingInfo to use.
1214 bool intercept_main_request_;
1215 std::string main_headers_;
1216 std::string main_data_;
1217 LoadTimingInfo main_request_load_timing_info_;
1219 // Other actions we take at MaybeIntercept time
1220 bool restart_main_request_;
1221 bool cancel_main_request_;
1222 bool cancel_then_restart_main_request_;
1223 bool simulate_main_network_error_;
1225 // Whether to intercept redirects, and if so the response to return.
1226 bool intercept_redirect_;
1227 std::string redirect_headers_;
1228 std::string redirect_data_;
1230 // Other actions we can take at MaybeInterceptRedirect time
1231 bool cancel_redirect_request_;
1233 // Whether to intercept final response, and if so the response to return.
1234 bool intercept_final_response_;
1235 std::string final_headers_;
1236 std::string final_data_;
1238 // Other actions we can take at MaybeInterceptResponse time
1239 bool cancel_final_request_;
1241 // If we did something or not
1242 bool did_intercept_main_;
1243 bool did_restart_main_;
1244 bool did_cancel_main_;
1245 bool did_cancel_then_restart_main_;
1246 bool did_simulate_error_main_;
1247 bool did_intercept_redirect_;
1248 bool did_cancel_redirect_;
1249 bool did_intercept_final_;
1250 bool did_cancel_final_;
1252 // Static getters for canned response header and data strings
1254 static std::string ok_data() {
1255 return URLRequestTestJob::test_data_1();
1258 static std::string ok_headers() {
1259 return URLRequestTestJob::test_headers();
1262 static std::string redirect_data() {
1263 return std::string();
1266 static std::string redirect_headers() {
1267 return URLRequestTestJob::test_redirect_headers();
1270 static std::string error_data() {
1271 return std::string("ohhh nooooo mr. bill!");
1274 static std::string error_headers() {
1275 return URLRequestTestJob::test_error_headers();
1279 TEST_F(URLRequestTest, Intercept) {
1280 TestInterceptor interceptor;
1282 // intercept the main request and respond with a simple response
1283 interceptor.intercept_main_request_ = true;
1284 interceptor.main_headers_ = TestInterceptor::ok_headers();
1285 interceptor.main_data_ = TestInterceptor::ok_data();
1287 TestDelegate d;
1288 URLRequest req(GURL("http://test_intercept/foo"),
1289 DEFAULT_PRIORITY,
1291 &default_context_);
1292 base::SupportsUserData::Data* user_data0 = new base::SupportsUserData::Data();
1293 base::SupportsUserData::Data* user_data1 = new base::SupportsUserData::Data();
1294 base::SupportsUserData::Data* user_data2 = new base::SupportsUserData::Data();
1295 req.SetUserData(NULL, user_data0);
1296 req.SetUserData(&user_data1, user_data1);
1297 req.SetUserData(&user_data2, user_data2);
1298 req.set_method("GET");
1299 req.Start();
1300 base::RunLoop().Run();
1302 // Make sure we can retrieve our specific user data
1303 EXPECT_EQ(user_data0, req.GetUserData(NULL));
1304 EXPECT_EQ(user_data1, req.GetUserData(&user_data1));
1305 EXPECT_EQ(user_data2, req.GetUserData(&user_data2));
1307 // Check the interceptor got called as expected
1308 EXPECT_TRUE(interceptor.did_intercept_main_);
1310 // Check we got one good response
1311 EXPECT_TRUE(req.status().is_success());
1312 EXPECT_EQ(200, req.response_headers()->response_code());
1313 EXPECT_EQ(TestInterceptor::ok_data(), d.data_received());
1314 EXPECT_EQ(1, d.response_started_count());
1315 EXPECT_EQ(0, d.received_redirect_count());
1318 TEST_F(URLRequestTest, InterceptRedirect) {
1319 TestInterceptor interceptor;
1321 // intercept the main request and respond with a redirect
1322 interceptor.intercept_main_request_ = true;
1323 interceptor.main_headers_ = TestInterceptor::redirect_headers();
1324 interceptor.main_data_ = TestInterceptor::redirect_data();
1326 // intercept that redirect and respond a final OK response
1327 interceptor.intercept_redirect_ = true;
1328 interceptor.redirect_headers_ = TestInterceptor::ok_headers();
1329 interceptor.redirect_data_ = TestInterceptor::ok_data();
1331 TestDelegate d;
1332 URLRequest req(GURL("http://test_intercept/foo"),
1333 DEFAULT_PRIORITY,
1335 &default_context_);
1336 req.set_method("GET");
1337 req.Start();
1338 base::RunLoop().Run();
1340 // Check the interceptor got called as expected
1341 EXPECT_TRUE(interceptor.did_intercept_main_);
1342 EXPECT_TRUE(interceptor.did_intercept_redirect_);
1344 // Check we got one good response
1345 EXPECT_TRUE(req.status().is_success());
1346 if (req.status().is_success()) {
1347 EXPECT_EQ(200, req.response_headers()->response_code());
1349 EXPECT_EQ(TestInterceptor::ok_data(), d.data_received());
1350 EXPECT_EQ(1, d.response_started_count());
1351 EXPECT_EQ(0, d.received_redirect_count());
1354 TEST_F(URLRequestTest, InterceptServerError) {
1355 TestInterceptor interceptor;
1357 // intercept the main request to generate a server error response
1358 interceptor.intercept_main_request_ = true;
1359 interceptor.main_headers_ = TestInterceptor::error_headers();
1360 interceptor.main_data_ = TestInterceptor::error_data();
1362 // intercept that error and respond with an OK response
1363 interceptor.intercept_final_response_ = true;
1364 interceptor.final_headers_ = TestInterceptor::ok_headers();
1365 interceptor.final_data_ = TestInterceptor::ok_data();
1367 TestDelegate d;
1368 URLRequest req(GURL("http://test_intercept/foo"),
1369 DEFAULT_PRIORITY,
1371 &default_context_);
1372 req.set_method("GET");
1373 req.Start();
1374 base::RunLoop().Run();
1376 // Check the interceptor got called as expected
1377 EXPECT_TRUE(interceptor.did_intercept_main_);
1378 EXPECT_TRUE(interceptor.did_intercept_final_);
1380 // Check we got one good response
1381 EXPECT_TRUE(req.status().is_success());
1382 EXPECT_EQ(200, req.response_headers()->response_code());
1383 EXPECT_EQ(TestInterceptor::ok_data(), d.data_received());
1384 EXPECT_EQ(1, d.response_started_count());
1385 EXPECT_EQ(0, d.received_redirect_count());
1388 TEST_F(URLRequestTest, InterceptNetworkError) {
1389 TestInterceptor interceptor;
1391 // intercept the main request to simulate a network error
1392 interceptor.simulate_main_network_error_ = true;
1394 // intercept that error and respond with an OK response
1395 interceptor.intercept_final_response_ = true;
1396 interceptor.final_headers_ = TestInterceptor::ok_headers();
1397 interceptor.final_data_ = TestInterceptor::ok_data();
1399 TestDelegate d;
1400 URLRequest req(GURL("http://test_intercept/foo"),
1401 DEFAULT_PRIORITY,
1403 &default_context_);
1404 req.set_method("GET");
1405 req.Start();
1406 base::RunLoop().Run();
1408 // Check the interceptor got called as expected
1409 EXPECT_TRUE(interceptor.did_simulate_error_main_);
1410 EXPECT_TRUE(interceptor.did_intercept_final_);
1412 // Check we received one good response
1413 EXPECT_TRUE(req.status().is_success());
1414 EXPECT_EQ(200, req.response_headers()->response_code());
1415 EXPECT_EQ(TestInterceptor::ok_data(), d.data_received());
1416 EXPECT_EQ(1, d.response_started_count());
1417 EXPECT_EQ(0, d.received_redirect_count());
1420 TEST_F(URLRequestTest, InterceptRestartRequired) {
1421 TestInterceptor interceptor;
1423 // restart the main request
1424 interceptor.restart_main_request_ = true;
1426 // then intercept the new main request and respond with an OK response
1427 interceptor.intercept_main_request_ = true;
1428 interceptor.main_headers_ = TestInterceptor::ok_headers();
1429 interceptor.main_data_ = TestInterceptor::ok_data();
1431 TestDelegate d;
1432 URLRequest req(GURL("http://test_intercept/foo"),
1433 DEFAULT_PRIORITY,
1435 &default_context_);
1436 req.set_method("GET");
1437 req.Start();
1438 base::RunLoop().Run();
1440 // Check the interceptor got called as expected
1441 EXPECT_TRUE(interceptor.did_restart_main_);
1442 EXPECT_TRUE(interceptor.did_intercept_main_);
1444 // Check we received one good response
1445 EXPECT_TRUE(req.status().is_success());
1446 if (req.status().is_success()) {
1447 EXPECT_EQ(200, req.response_headers()->response_code());
1449 EXPECT_EQ(TestInterceptor::ok_data(), d.data_received());
1450 EXPECT_EQ(1, d.response_started_count());
1451 EXPECT_EQ(0, d.received_redirect_count());
1454 TEST_F(URLRequestTest, InterceptRespectsCancelMain) {
1455 TestInterceptor interceptor;
1457 // intercept the main request and cancel from within the restarted job
1458 interceptor.cancel_main_request_ = true;
1460 // setup to intercept final response and override it with an OK response
1461 interceptor.intercept_final_response_ = true;
1462 interceptor.final_headers_ = TestInterceptor::ok_headers();
1463 interceptor.final_data_ = TestInterceptor::ok_data();
1465 TestDelegate d;
1466 URLRequest req(GURL("http://test_intercept/foo"),
1467 DEFAULT_PRIORITY,
1469 &default_context_);
1470 req.set_method("GET");
1471 req.Start();
1472 base::RunLoop().Run();
1474 // Check the interceptor got called as expected
1475 EXPECT_TRUE(interceptor.did_cancel_main_);
1476 EXPECT_FALSE(interceptor.did_intercept_final_);
1478 // Check we see a canceled request
1479 EXPECT_FALSE(req.status().is_success());
1480 EXPECT_EQ(URLRequestStatus::CANCELED, req.status().status());
1483 TEST_F(URLRequestTest, InterceptRespectsCancelRedirect) {
1484 TestInterceptor interceptor;
1486 // intercept the main request and respond with a redirect
1487 interceptor.intercept_main_request_ = true;
1488 interceptor.main_headers_ = TestInterceptor::redirect_headers();
1489 interceptor.main_data_ = TestInterceptor::redirect_data();
1491 // intercept the redirect and cancel from within that job
1492 interceptor.cancel_redirect_request_ = true;
1494 // setup to intercept final response and override it with an OK response
1495 interceptor.intercept_final_response_ = true;
1496 interceptor.final_headers_ = TestInterceptor::ok_headers();
1497 interceptor.final_data_ = TestInterceptor::ok_data();
1499 TestDelegate d;
1500 URLRequest req(GURL("http://test_intercept/foo"),
1501 DEFAULT_PRIORITY,
1503 &default_context_);
1504 req.set_method("GET");
1505 req.Start();
1506 base::RunLoop().Run();
1508 // Check the interceptor got called as expected
1509 EXPECT_TRUE(interceptor.did_intercept_main_);
1510 EXPECT_TRUE(interceptor.did_cancel_redirect_);
1511 EXPECT_FALSE(interceptor.did_intercept_final_);
1513 // Check we see a canceled request
1514 EXPECT_FALSE(req.status().is_success());
1515 EXPECT_EQ(URLRequestStatus::CANCELED, req.status().status());
1518 TEST_F(URLRequestTest, InterceptRespectsCancelFinal) {
1519 TestInterceptor interceptor;
1521 // intercept the main request to simulate a network error
1522 interceptor.simulate_main_network_error_ = true;
1524 // setup to intercept final response and cancel from within that job
1525 interceptor.cancel_final_request_ = true;
1527 TestDelegate d;
1528 URLRequest req(GURL("http://test_intercept/foo"),
1529 DEFAULT_PRIORITY,
1531 &default_context_);
1532 req.set_method("GET");
1533 req.Start();
1534 base::RunLoop().Run();
1536 // Check the interceptor got called as expected
1537 EXPECT_TRUE(interceptor.did_simulate_error_main_);
1538 EXPECT_TRUE(interceptor.did_cancel_final_);
1540 // Check we see a canceled request
1541 EXPECT_FALSE(req.status().is_success());
1542 EXPECT_EQ(URLRequestStatus::CANCELED, req.status().status());
1545 TEST_F(URLRequestTest, InterceptRespectsCancelInRestart) {
1546 TestInterceptor interceptor;
1548 // intercept the main request and cancel then restart from within that job
1549 interceptor.cancel_then_restart_main_request_ = true;
1551 // setup to intercept final response and override it with an OK response
1552 interceptor.intercept_final_response_ = true;
1553 interceptor.final_headers_ = TestInterceptor::ok_headers();
1554 interceptor.final_data_ = TestInterceptor::ok_data();
1556 TestDelegate d;
1557 URLRequest req(GURL("http://test_intercept/foo"),
1558 DEFAULT_PRIORITY,
1560 &default_context_);
1561 req.set_method("GET");
1562 req.Start();
1563 base::RunLoop().Run();
1565 // Check the interceptor got called as expected
1566 EXPECT_TRUE(interceptor.did_cancel_then_restart_main_);
1567 EXPECT_FALSE(interceptor.did_intercept_final_);
1569 // Check we see a canceled request
1570 EXPECT_FALSE(req.status().is_success());
1571 EXPECT_EQ(URLRequestStatus::CANCELED, req.status().status());
1574 LoadTimingInfo RunLoadTimingTest(const LoadTimingInfo& job_load_timing,
1575 URLRequestContext* context) {
1576 TestInterceptor interceptor;
1577 interceptor.intercept_main_request_ = true;
1578 interceptor.main_request_load_timing_info_ = job_load_timing;
1579 TestDelegate d;
1580 URLRequest req(
1581 GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, context);
1582 req.Start();
1583 base::RunLoop().Run();
1585 LoadTimingInfo resulting_load_timing;
1586 req.GetLoadTimingInfo(&resulting_load_timing);
1588 // None of these should be modified by the URLRequest.
1589 EXPECT_EQ(job_load_timing.socket_reused, resulting_load_timing.socket_reused);
1590 EXPECT_EQ(job_load_timing.socket_log_id, resulting_load_timing.socket_log_id);
1591 EXPECT_EQ(job_load_timing.send_start, resulting_load_timing.send_start);
1592 EXPECT_EQ(job_load_timing.send_end, resulting_load_timing.send_end);
1593 EXPECT_EQ(job_load_timing.receive_headers_end,
1594 resulting_load_timing.receive_headers_end);
1596 return resulting_load_timing;
1599 // "Normal" LoadTimingInfo as returned by a job. Everything is in order, not
1600 // reused. |connect_time_flags| is used to indicate if there should be dns
1601 // or SSL times, and |used_proxy| is used for proxy times.
1602 LoadTimingInfo NormalLoadTimingInfo(base::TimeTicks now,
1603 int connect_time_flags,
1604 bool used_proxy) {
1605 LoadTimingInfo load_timing;
1606 load_timing.socket_log_id = 1;
1608 if (used_proxy) {
1609 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
1610 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
1613 LoadTimingInfo::ConnectTiming& connect_timing = load_timing.connect_timing;
1614 if (connect_time_flags & CONNECT_TIMING_HAS_DNS_TIMES) {
1615 connect_timing.dns_start = now + base::TimeDelta::FromDays(3);
1616 connect_timing.dns_end = now + base::TimeDelta::FromDays(4);
1618 connect_timing.connect_start = now + base::TimeDelta::FromDays(5);
1619 if (connect_time_flags & CONNECT_TIMING_HAS_SSL_TIMES) {
1620 connect_timing.ssl_start = now + base::TimeDelta::FromDays(6);
1621 connect_timing.ssl_end = now + base::TimeDelta::FromDays(7);
1623 connect_timing.connect_end = now + base::TimeDelta::FromDays(8);
1625 load_timing.send_start = now + base::TimeDelta::FromDays(9);
1626 load_timing.send_end = now + base::TimeDelta::FromDays(10);
1627 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
1628 return load_timing;
1631 // Same as above, but in the case of a reused socket.
1632 LoadTimingInfo NormalLoadTimingInfoReused(base::TimeTicks now,
1633 bool used_proxy) {
1634 LoadTimingInfo load_timing;
1635 load_timing.socket_log_id = 1;
1636 load_timing.socket_reused = true;
1638 if (used_proxy) {
1639 load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
1640 load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
1643 load_timing.send_start = now + base::TimeDelta::FromDays(9);
1644 load_timing.send_end = now + base::TimeDelta::FromDays(10);
1645 load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
1646 return load_timing;
1649 // Basic test that the intercept + load timing tests work.
1650 TEST_F(URLRequestTest, InterceptLoadTiming) {
1651 base::TimeTicks now = base::TimeTicks::Now();
1652 LoadTimingInfo job_load_timing =
1653 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, false);
1655 LoadTimingInfo load_timing_result =
1656 RunLoadTimingTest(job_load_timing, &default_context_);
1658 // Nothing should have been changed by the URLRequest.
1659 EXPECT_EQ(job_load_timing.proxy_resolve_start,
1660 load_timing_result.proxy_resolve_start);
1661 EXPECT_EQ(job_load_timing.proxy_resolve_end,
1662 load_timing_result.proxy_resolve_end);
1663 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
1664 load_timing_result.connect_timing.dns_start);
1665 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
1666 load_timing_result.connect_timing.dns_end);
1667 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
1668 load_timing_result.connect_timing.connect_start);
1669 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
1670 load_timing_result.connect_timing.connect_end);
1671 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
1672 load_timing_result.connect_timing.ssl_start);
1673 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
1674 load_timing_result.connect_timing.ssl_end);
1676 // Redundant sanity check.
1677 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_DNS_TIMES);
1680 // Another basic test, with proxy and SSL times, but no DNS times.
1681 TEST_F(URLRequestTest, InterceptLoadTimingProxy) {
1682 base::TimeTicks now = base::TimeTicks::Now();
1683 LoadTimingInfo job_load_timing =
1684 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, true);
1686 LoadTimingInfo load_timing_result =
1687 RunLoadTimingTest(job_load_timing, &default_context_);
1689 // Nothing should have been changed by the URLRequest.
1690 EXPECT_EQ(job_load_timing.proxy_resolve_start,
1691 load_timing_result.proxy_resolve_start);
1692 EXPECT_EQ(job_load_timing.proxy_resolve_end,
1693 load_timing_result.proxy_resolve_end);
1694 EXPECT_EQ(job_load_timing.connect_timing.dns_start,
1695 load_timing_result.connect_timing.dns_start);
1696 EXPECT_EQ(job_load_timing.connect_timing.dns_end,
1697 load_timing_result.connect_timing.dns_end);
1698 EXPECT_EQ(job_load_timing.connect_timing.connect_start,
1699 load_timing_result.connect_timing.connect_start);
1700 EXPECT_EQ(job_load_timing.connect_timing.connect_end,
1701 load_timing_result.connect_timing.connect_end);
1702 EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
1703 load_timing_result.connect_timing.ssl_start);
1704 EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
1705 load_timing_result.connect_timing.ssl_end);
1707 // Redundant sanity check.
1708 TestLoadTimingNotReusedWithProxy(load_timing_result,
1709 CONNECT_TIMING_HAS_SSL_TIMES);
1712 // Make sure that URLRequest correctly adjusts proxy times when they're before
1713 // |request_start|, due to already having a connected socket. This happens in
1714 // the case of reusing a SPDY session. The connected socket is not considered
1715 // reused in this test (May be a preconnect).
1717 // To mix things up from the test above, assumes DNS times but no SSL times.
1718 TEST_F(URLRequestTest, InterceptLoadTimingEarlyProxyResolution) {
1719 base::TimeTicks now = base::TimeTicks::Now();
1720 LoadTimingInfo job_load_timing =
1721 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, true);
1722 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(6);
1723 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(5);
1724 job_load_timing.connect_timing.dns_start = now - base::TimeDelta::FromDays(4);
1725 job_load_timing.connect_timing.dns_end = now - base::TimeDelta::FromDays(3);
1726 job_load_timing.connect_timing.connect_start =
1727 now - base::TimeDelta::FromDays(2);
1728 job_load_timing.connect_timing.connect_end =
1729 now - base::TimeDelta::FromDays(1);
1731 LoadTimingInfo load_timing_result =
1732 RunLoadTimingTest(job_load_timing, &default_context_);
1734 // Proxy times, connect times, and DNS times should all be replaced with
1735 // request_start.
1736 EXPECT_EQ(load_timing_result.request_start,
1737 load_timing_result.proxy_resolve_start);
1738 EXPECT_EQ(load_timing_result.request_start,
1739 load_timing_result.proxy_resolve_end);
1740 EXPECT_EQ(load_timing_result.request_start,
1741 load_timing_result.connect_timing.dns_start);
1742 EXPECT_EQ(load_timing_result.request_start,
1743 load_timing_result.connect_timing.dns_end);
1744 EXPECT_EQ(load_timing_result.request_start,
1745 load_timing_result.connect_timing.connect_start);
1746 EXPECT_EQ(load_timing_result.request_start,
1747 load_timing_result.connect_timing.connect_end);
1749 // Other times should have been left null.
1750 TestLoadTimingNotReusedWithProxy(load_timing_result,
1751 CONNECT_TIMING_HAS_DNS_TIMES);
1754 // Same as above, but in the reused case.
1755 TEST_F(URLRequestTest, InterceptLoadTimingEarlyProxyResolutionReused) {
1756 base::TimeTicks now = base::TimeTicks::Now();
1757 LoadTimingInfo job_load_timing = NormalLoadTimingInfoReused(now, true);
1758 job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(4);
1759 job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(3);
1761 LoadTimingInfo load_timing_result =
1762 RunLoadTimingTest(job_load_timing, &default_context_);
1764 // Proxy times and connect times should all be replaced with request_start.
1765 EXPECT_EQ(load_timing_result.request_start,
1766 load_timing_result.proxy_resolve_start);
1767 EXPECT_EQ(load_timing_result.request_start,
1768 load_timing_result.proxy_resolve_end);
1770 // Other times should have been left null.
1771 TestLoadTimingReusedWithProxy(load_timing_result);
1774 // Make sure that URLRequest correctly adjusts connect times when they're before
1775 // |request_start|, due to reusing a connected socket. The connected socket is
1776 // not considered reused in this test (May be a preconnect).
1778 // To mix things up, the request has SSL times, but no DNS times.
1779 TEST_F(URLRequestTest, InterceptLoadTimingEarlyConnect) {
1780 base::TimeTicks now = base::TimeTicks::Now();
1781 LoadTimingInfo job_load_timing =
1782 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, false);
1783 job_load_timing.connect_timing.connect_start =
1784 now - base::TimeDelta::FromDays(1);
1785 job_load_timing.connect_timing.ssl_start = now - base::TimeDelta::FromDays(2);
1786 job_load_timing.connect_timing.ssl_end = now - base::TimeDelta::FromDays(3);
1787 job_load_timing.connect_timing.connect_end =
1788 now - base::TimeDelta::FromDays(4);
1790 LoadTimingInfo load_timing_result =
1791 RunLoadTimingTest(job_load_timing, &default_context_);
1793 // Connect times, and SSL times should be replaced with request_start.
1794 EXPECT_EQ(load_timing_result.request_start,
1795 load_timing_result.connect_timing.connect_start);
1796 EXPECT_EQ(load_timing_result.request_start,
1797 load_timing_result.connect_timing.ssl_start);
1798 EXPECT_EQ(load_timing_result.request_start,
1799 load_timing_result.connect_timing.ssl_end);
1800 EXPECT_EQ(load_timing_result.request_start,
1801 load_timing_result.connect_timing.connect_end);
1803 // Other times should have been left null.
1804 TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_SSL_TIMES);
1807 // Make sure that URLRequest correctly adjusts connect times when they're before
1808 // |request_start|, due to reusing a connected socket in the case that there
1809 // are also proxy times. The connected socket is not considered reused in this
1810 // test (May be a preconnect).
1812 // In this test, there are no SSL or DNS times.
1813 TEST_F(URLRequestTest, InterceptLoadTimingEarlyConnectWithProxy) {
1814 base::TimeTicks now = base::TimeTicks::Now();
1815 LoadTimingInfo job_load_timing =
1816 NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY, true);
1817 job_load_timing.connect_timing.connect_start =
1818 now - base::TimeDelta::FromDays(1);
1819 job_load_timing.connect_timing.connect_end =
1820 now - base::TimeDelta::FromDays(2);
1822 LoadTimingInfo load_timing_result =
1823 RunLoadTimingTest(job_load_timing, &default_context_);
1825 // Connect times should be replaced with proxy_resolve_end.
1826 EXPECT_EQ(load_timing_result.proxy_resolve_end,
1827 load_timing_result.connect_timing.connect_start);
1828 EXPECT_EQ(load_timing_result.proxy_resolve_end,
1829 load_timing_result.connect_timing.connect_end);
1831 // Other times should have been left null.
1832 TestLoadTimingNotReusedWithProxy(load_timing_result,
1833 CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
1836 // Check that two different URL requests have different identifiers.
1837 TEST_F(URLRequestTest, Identifiers) {
1838 TestDelegate d;
1839 TestURLRequestContext context;
1840 TestURLRequest req(
1841 GURL("http://example.com"), DEFAULT_PRIORITY, &d, &context);
1842 TestURLRequest other_req(
1843 GURL("http://example.com"), DEFAULT_PRIORITY, &d, &context);
1845 ASSERT_NE(req.identifier(), other_req.identifier());
1848 // Check that a failure to connect to the proxy is reported to the network
1849 // delegate.
1850 TEST_F(URLRequestTest, NetworkDelegateProxyError) {
1851 MockHostResolver host_resolver;
1852 host_resolver.rules()->AddSimulatedFailure("*");
1854 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
1855 TestURLRequestContextWithProxy context("myproxy:70", &network_delegate);
1857 TestDelegate d;
1858 URLRequest req(GURL("http://example.com"), DEFAULT_PRIORITY, &d, &context);
1859 req.set_method("GET");
1861 req.Start();
1862 base::RunLoop().Run();
1864 // Check we see a failed request.
1865 EXPECT_FALSE(req.status().is_success());
1866 // The proxy server is not set before failure.
1867 EXPECT_TRUE(req.proxy_server().IsEmpty());
1868 EXPECT_EQ(URLRequestStatus::FAILED, req.status().status());
1869 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, req.status().error());
1871 EXPECT_EQ(1, network_delegate.error_count());
1872 EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, network_delegate.last_error());
1873 EXPECT_EQ(1, network_delegate.completed_requests());
1876 // Make sure that net::NetworkDelegate::NotifyCompleted is called if
1877 // content is empty.
1878 TEST_F(URLRequestTest, RequestCompletionForEmptyResponse) {
1879 TestDelegate d;
1880 URLRequest req(GURL("data:,"), DEFAULT_PRIORITY, &d, &default_context_);
1881 req.Start();
1882 base::RunLoop().Run();
1883 EXPECT_EQ("", d.data_received());
1884 EXPECT_EQ(1, default_network_delegate_.completed_requests());
1887 // Make sure that SetPriority actually sets the URLRequest's priority
1888 // correctly, both before and after start.
1889 TEST_F(URLRequestTest, SetPriorityBasic) {
1890 TestDelegate d;
1891 URLRequest req(GURL("http://test_intercept/foo"),
1892 DEFAULT_PRIORITY,
1894 &default_context_);
1895 EXPECT_EQ(DEFAULT_PRIORITY, req.priority());
1897 req.SetPriority(LOW);
1898 EXPECT_EQ(LOW, req.priority());
1900 req.Start();
1901 EXPECT_EQ(LOW, req.priority());
1903 req.SetPriority(MEDIUM);
1904 EXPECT_EQ(MEDIUM, req.priority());
1907 // Make sure that URLRequest calls SetPriority on a job before calling
1908 // Start on it.
1909 TEST_F(URLRequestTest, SetJobPriorityBeforeJobStart) {
1910 TestDelegate d;
1911 URLRequest req(GURL("http://test_intercept/foo"),
1912 DEFAULT_PRIORITY,
1914 &default_context_);
1915 EXPECT_EQ(DEFAULT_PRIORITY, req.priority());
1917 scoped_refptr<URLRequestTestJob> job =
1918 new URLRequestTestJob(&req, &default_network_delegate_);
1919 AddTestInterceptor()->set_main_intercept_job(job.get());
1920 EXPECT_EQ(DEFAULT_PRIORITY, job->priority());
1922 req.SetPriority(LOW);
1924 req.Start();
1925 EXPECT_EQ(LOW, job->priority());
1928 // Make sure that URLRequest passes on its priority updates to its
1929 // job.
1930 TEST_F(URLRequestTest, SetJobPriority) {
1931 TestDelegate d;
1932 URLRequest req(GURL("http://test_intercept/foo"),
1933 DEFAULT_PRIORITY,
1935 &default_context_);
1937 scoped_refptr<URLRequestTestJob> job =
1938 new URLRequestTestJob(&req, &default_network_delegate_);
1939 AddTestInterceptor()->set_main_intercept_job(job.get());
1941 req.SetPriority(LOW);
1942 req.Start();
1943 EXPECT_EQ(LOW, job->priority());
1945 req.SetPriority(MEDIUM);
1946 EXPECT_EQ(MEDIUM, req.priority());
1947 EXPECT_EQ(MEDIUM, job->priority());
1950 // Setting the IGNORE_LIMITS load flag should be okay if the priority
1951 // is MAXIMUM_PRIORITY.
1952 TEST_F(URLRequestTest, PriorityIgnoreLimits) {
1953 TestDelegate d;
1954 URLRequest req(GURL("http://test_intercept/foo"),
1955 MAXIMUM_PRIORITY,
1957 &default_context_);
1958 EXPECT_EQ(MAXIMUM_PRIORITY, req.priority());
1960 scoped_refptr<URLRequestTestJob> job =
1961 new URLRequestTestJob(&req, &default_network_delegate_);
1962 AddTestInterceptor()->set_main_intercept_job(job.get());
1964 req.SetLoadFlags(LOAD_IGNORE_LIMITS);
1965 EXPECT_EQ(MAXIMUM_PRIORITY, req.priority());
1967 req.SetPriority(MAXIMUM_PRIORITY);
1968 EXPECT_EQ(MAXIMUM_PRIORITY, req.priority());
1970 req.Start();
1971 EXPECT_EQ(MAXIMUM_PRIORITY, req.priority());
1972 EXPECT_EQ(MAXIMUM_PRIORITY, job->priority());
1975 // TODO(droger): Support SpawnedTestServer on iOS (see http://crbug.com/148666).
1976 #if !defined(OS_IOS)
1977 // A subclass of SpawnedTestServer that uses a statically-configured hostname.
1978 // This is to work around mysterious failures in chrome_frame_net_tests. See:
1979 // http://crbug.com/114369
1980 // TODO(erikwright): remove or update as needed; see http://crbug.com/334634.
1981 class LocalHttpTestServer : public SpawnedTestServer {
1982 public:
1983 explicit LocalHttpTestServer(const base::FilePath& document_root)
1984 : SpawnedTestServer(SpawnedTestServer::TYPE_HTTP,
1985 ScopedCustomUrlRequestTestHttpHost::value(),
1986 document_root) {}
1987 LocalHttpTestServer()
1988 : SpawnedTestServer(SpawnedTestServer::TYPE_HTTP,
1989 ScopedCustomUrlRequestTestHttpHost::value(),
1990 base::FilePath()) {}
1993 TEST_F(URLRequestTest, DelayedCookieCallback) {
1994 LocalHttpTestServer test_server;
1995 ASSERT_TRUE(test_server.Start());
1997 TestURLRequestContext context;
1998 scoped_refptr<DelayedCookieMonster> delayed_cm =
1999 new DelayedCookieMonster();
2000 scoped_refptr<CookieStore> cookie_store = delayed_cm;
2001 context.set_cookie_store(delayed_cm.get());
2003 // Set up a cookie.
2005 TestNetworkDelegate network_delegate;
2006 context.set_network_delegate(&network_delegate);
2007 TestDelegate d;
2008 URLRequest req(test_server.GetURL("set-cookie?CookieToNotSend=1"),
2009 DEFAULT_PRIORITY,
2011 &context);
2012 req.Start();
2013 base::RunLoop().Run();
2014 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2015 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2016 EXPECT_EQ(1, network_delegate.set_cookie_count());
2019 // Verify that the cookie is set.
2021 TestNetworkDelegate network_delegate;
2022 context.set_network_delegate(&network_delegate);
2023 TestDelegate d;
2024 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2025 DEFAULT_PRIORITY,
2027 &context);
2028 req.Start();
2029 base::RunLoop().Run();
2031 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2032 != std::string::npos);
2033 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2034 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2038 TEST_F(URLRequestTest, DoNotSendCookies) {
2039 LocalHttpTestServer test_server;
2040 ASSERT_TRUE(test_server.Start());
2042 // Set up a cookie.
2044 TestNetworkDelegate network_delegate;
2045 default_context_.set_network_delegate(&network_delegate);
2046 TestDelegate d;
2047 URLRequest req(test_server.GetURL("set-cookie?CookieToNotSend=1"),
2048 DEFAULT_PRIORITY,
2050 &default_context_);
2051 req.Start();
2052 base::RunLoop().Run();
2053 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2054 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2057 // Verify that the cookie is set.
2059 TestNetworkDelegate network_delegate;
2060 default_context_.set_network_delegate(&network_delegate);
2061 TestDelegate d;
2062 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2063 DEFAULT_PRIORITY,
2065 &default_context_);
2066 req.Start();
2067 base::RunLoop().Run();
2069 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2070 != std::string::npos);
2071 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2072 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2075 // Verify that the cookie isn't sent when LOAD_DO_NOT_SEND_COOKIES is set.
2077 TestNetworkDelegate network_delegate;
2078 default_context_.set_network_delegate(&network_delegate);
2079 TestDelegate d;
2080 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2081 DEFAULT_PRIORITY,
2083 &default_context_);
2084 req.SetLoadFlags(LOAD_DO_NOT_SEND_COOKIES);
2085 req.Start();
2086 base::RunLoop().Run();
2088 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2089 == std::string::npos);
2091 // LOAD_DO_NOT_SEND_COOKIES does not trigger OnGetCookies.
2092 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2093 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2097 TEST_F(URLRequestTest, DoNotSaveCookies) {
2098 LocalHttpTestServer test_server;
2099 ASSERT_TRUE(test_server.Start());
2101 // Set up a cookie.
2103 TestNetworkDelegate network_delegate;
2104 default_context_.set_network_delegate(&network_delegate);
2105 TestDelegate d;
2106 URLRequest req(test_server.GetURL("set-cookie?CookieToNotUpdate=2"),
2107 DEFAULT_PRIORITY,
2109 &default_context_);
2110 req.Start();
2111 base::RunLoop().Run();
2113 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2114 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2115 EXPECT_EQ(1, network_delegate.set_cookie_count());
2118 // Try to set-up another cookie and update the previous cookie.
2120 TestNetworkDelegate network_delegate;
2121 default_context_.set_network_delegate(&network_delegate);
2122 TestDelegate d;
2123 URLRequest req(
2124 test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
2125 DEFAULT_PRIORITY,
2127 &default_context_);
2128 req.SetLoadFlags(LOAD_DO_NOT_SAVE_COOKIES);
2129 req.Start();
2131 base::RunLoop().Run();
2133 // LOAD_DO_NOT_SAVE_COOKIES does not trigger OnSetCookie.
2134 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2135 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2136 EXPECT_EQ(0, network_delegate.set_cookie_count());
2139 // Verify the cookies weren't saved or updated.
2141 TestNetworkDelegate network_delegate;
2142 default_context_.set_network_delegate(&network_delegate);
2143 TestDelegate d;
2144 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2145 DEFAULT_PRIORITY,
2147 &default_context_);
2148 req.Start();
2149 base::RunLoop().Run();
2151 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2152 == std::string::npos);
2153 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2154 != std::string::npos);
2156 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2157 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2158 EXPECT_EQ(0, network_delegate.set_cookie_count());
2162 TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy) {
2163 LocalHttpTestServer test_server;
2164 ASSERT_TRUE(test_server.Start());
2166 // Set up a cookie.
2168 TestNetworkDelegate network_delegate;
2169 default_context_.set_network_delegate(&network_delegate);
2170 TestDelegate d;
2171 URLRequest req(test_server.GetURL("set-cookie?CookieToNotSend=1"),
2172 DEFAULT_PRIORITY,
2174 &default_context_);
2175 req.Start();
2176 base::RunLoop().Run();
2178 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2179 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2182 // Verify that the cookie is set.
2184 TestNetworkDelegate network_delegate;
2185 default_context_.set_network_delegate(&network_delegate);
2186 TestDelegate d;
2187 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2188 DEFAULT_PRIORITY,
2190 &default_context_);
2191 req.Start();
2192 base::RunLoop().Run();
2194 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2195 != std::string::npos);
2197 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2198 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2201 // Verify that the cookie isn't sent.
2203 TestNetworkDelegate network_delegate;
2204 default_context_.set_network_delegate(&network_delegate);
2205 TestDelegate d;
2206 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
2207 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2208 DEFAULT_PRIORITY,
2210 &default_context_);
2211 req.Start();
2212 base::RunLoop().Run();
2214 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2215 == std::string::npos);
2217 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
2218 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2222 TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy) {
2223 LocalHttpTestServer test_server;
2224 ASSERT_TRUE(test_server.Start());
2226 // Set up a cookie.
2228 TestNetworkDelegate network_delegate;
2229 default_context_.set_network_delegate(&network_delegate);
2230 TestDelegate d;
2231 URLRequest req(test_server.GetURL("set-cookie?CookieToNotUpdate=2"),
2232 DEFAULT_PRIORITY,
2234 &default_context_);
2235 req.Start();
2236 base::RunLoop().Run();
2238 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2239 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2242 // Try to set-up another cookie and update the previous cookie.
2244 TestNetworkDelegate network_delegate;
2245 default_context_.set_network_delegate(&network_delegate);
2246 TestDelegate d;
2247 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
2248 URLRequest req(
2249 test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
2250 DEFAULT_PRIORITY,
2252 &default_context_);
2253 req.Start();
2255 base::RunLoop().Run();
2257 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2258 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2261 // Verify the cookies weren't saved or updated.
2263 TestNetworkDelegate network_delegate;
2264 default_context_.set_network_delegate(&network_delegate);
2265 TestDelegate d;
2266 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2267 DEFAULT_PRIORITY,
2269 &default_context_);
2270 req.Start();
2271 base::RunLoop().Run();
2273 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2274 == std::string::npos);
2275 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2276 != std::string::npos);
2278 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2279 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2283 TEST_F(URLRequestTest, DoNotSaveEmptyCookies) {
2284 LocalHttpTestServer test_server;
2285 ASSERT_TRUE(test_server.Start());
2287 // Set up an empty cookie.
2289 TestNetworkDelegate network_delegate;
2290 default_context_.set_network_delegate(&network_delegate);
2291 TestDelegate d;
2292 URLRequest req(test_server.GetURL("set-cookie"),
2293 DEFAULT_PRIORITY,
2295 &default_context_);
2296 req.Start();
2297 base::RunLoop().Run();
2299 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2300 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2301 EXPECT_EQ(0, network_delegate.set_cookie_count());
2305 TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy_Async) {
2306 LocalHttpTestServer test_server;
2307 ASSERT_TRUE(test_server.Start());
2309 // Set up a cookie.
2311 TestNetworkDelegate network_delegate;
2312 default_context_.set_network_delegate(&network_delegate);
2313 TestDelegate d;
2314 URLRequest req(test_server.GetURL("set-cookie?CookieToNotSend=1"),
2315 DEFAULT_PRIORITY,
2317 &default_context_);
2318 req.Start();
2319 base::RunLoop().Run();
2321 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2322 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2325 // Verify that the cookie is set.
2327 TestNetworkDelegate network_delegate;
2328 default_context_.set_network_delegate(&network_delegate);
2329 TestDelegate d;
2330 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2331 DEFAULT_PRIORITY,
2333 &default_context_);
2334 req.Start();
2335 base::RunLoop().Run();
2337 EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2338 != std::string::npos);
2340 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2341 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2344 // Verify that the cookie isn't sent.
2346 TestNetworkDelegate network_delegate;
2347 default_context_.set_network_delegate(&network_delegate);
2348 TestDelegate d;
2349 network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
2350 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2351 DEFAULT_PRIORITY,
2353 &default_context_);
2354 req.Start();
2355 base::RunLoop().Run();
2357 EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2358 == std::string::npos);
2360 EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
2361 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2365 TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy_Async) {
2366 LocalHttpTestServer test_server;
2367 ASSERT_TRUE(test_server.Start());
2369 // Set up a cookie.
2371 TestNetworkDelegate network_delegate;
2372 default_context_.set_network_delegate(&network_delegate);
2373 TestDelegate d;
2374 URLRequest req(test_server.GetURL("set-cookie?CookieToNotUpdate=2"),
2375 DEFAULT_PRIORITY,
2377 &default_context_);
2378 req.Start();
2379 base::RunLoop().Run();
2381 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2382 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2385 // Try to set-up another cookie and update the previous cookie.
2387 TestNetworkDelegate network_delegate;
2388 default_context_.set_network_delegate(&network_delegate);
2389 TestDelegate d;
2390 network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
2391 URLRequest req(
2392 test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
2393 DEFAULT_PRIORITY,
2395 &default_context_);
2396 req.Start();
2398 base::RunLoop().Run();
2400 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2401 EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2404 // Verify the cookies weren't saved or updated.
2406 TestNetworkDelegate network_delegate;
2407 default_context_.set_network_delegate(&network_delegate);
2408 TestDelegate d;
2409 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2410 DEFAULT_PRIORITY,
2412 &default_context_);
2413 req.Start();
2414 base::RunLoop().Run();
2416 EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2417 == std::string::npos);
2418 EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2419 != std::string::npos);
2421 EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2422 EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2426 // FixedDateNetworkDelegate swaps out the server's HTTP Date response header
2427 // value for the |fixed_date| argument given to the constructor.
2428 class FixedDateNetworkDelegate : public TestNetworkDelegate {
2429 public:
2430 explicit FixedDateNetworkDelegate(const std::string& fixed_date)
2431 : fixed_date_(fixed_date) {}
2432 virtual ~FixedDateNetworkDelegate() {}
2434 // net::NetworkDelegate implementation
2435 virtual int OnHeadersReceived(
2436 net::URLRequest* request,
2437 const net::CompletionCallback& callback,
2438 const net::HttpResponseHeaders* original_response_headers,
2439 scoped_refptr<net::HttpResponseHeaders>* override_response_headers,
2440 GURL* allowed_unsafe_redirect_url) OVERRIDE;
2442 private:
2443 std::string fixed_date_;
2445 DISALLOW_COPY_AND_ASSIGN(FixedDateNetworkDelegate);
2448 int FixedDateNetworkDelegate::OnHeadersReceived(
2449 net::URLRequest* request,
2450 const net::CompletionCallback& callback,
2451 const net::HttpResponseHeaders* original_response_headers,
2452 scoped_refptr<net::HttpResponseHeaders>* override_response_headers,
2453 GURL* allowed_unsafe_redirect_url) {
2454 net::HttpResponseHeaders* new_response_headers =
2455 new net::HttpResponseHeaders(original_response_headers->raw_headers());
2457 new_response_headers->RemoveHeader("Date");
2458 new_response_headers->AddHeader("Date: " + fixed_date_);
2460 *override_response_headers = new_response_headers;
2461 return TestNetworkDelegate::OnHeadersReceived(request,
2462 callback,
2463 original_response_headers,
2464 override_response_headers,
2465 allowed_unsafe_redirect_url);
2468 // Test that cookie expiration times are adjusted for server/client clock
2469 // skew and that we handle incorrect timezone specifier "UTC" in HTTP Date
2470 // headers by defaulting to GMT. (crbug.com/135131)
2471 TEST_F(URLRequestTest, AcceptClockSkewCookieWithWrongDateTimezone) {
2472 LocalHttpTestServer test_server;
2473 ASSERT_TRUE(test_server.Start());
2475 // Set up an expired cookie.
2477 TestNetworkDelegate network_delegate;
2478 default_context_.set_network_delegate(&network_delegate);
2479 TestDelegate d;
2480 URLRequest req(
2481 test_server.GetURL(
2482 "set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
2483 DEFAULT_PRIORITY,
2485 &default_context_);
2486 req.Start();
2487 base::RunLoop().Run();
2489 // Verify that the cookie is not set.
2491 TestNetworkDelegate network_delegate;
2492 default_context_.set_network_delegate(&network_delegate);
2493 TestDelegate d;
2494 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2495 DEFAULT_PRIORITY,
2497 &default_context_);
2498 req.Start();
2499 base::RunLoop().Run();
2501 EXPECT_TRUE(d.data_received().find("StillGood=1") == std::string::npos);
2503 // Set up a cookie with clock skew and "UTC" HTTP Date timezone specifier.
2505 FixedDateNetworkDelegate network_delegate("18-Apr-1977 22:49:13 UTC");
2506 default_context_.set_network_delegate(&network_delegate);
2507 TestDelegate d;
2508 URLRequest req(
2509 test_server.GetURL(
2510 "set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
2511 DEFAULT_PRIORITY,
2513 &default_context_);
2514 req.Start();
2515 base::RunLoop().Run();
2517 // Verify that the cookie is set.
2519 TestNetworkDelegate network_delegate;
2520 default_context_.set_network_delegate(&network_delegate);
2521 TestDelegate d;
2522 URLRequest req(test_server.GetURL("echoheader?Cookie"),
2523 DEFAULT_PRIORITY,
2525 &default_context_);
2526 req.Start();
2527 base::RunLoop().Run();
2529 EXPECT_TRUE(d.data_received().find("StillGood=1") != std::string::npos);
2534 // Check that it is impossible to change the referrer in the extra headers of
2535 // an URLRequest.
2536 TEST_F(URLRequestTest, DoNotOverrideReferrer) {
2537 LocalHttpTestServer test_server;
2538 ASSERT_TRUE(test_server.Start());
2540 // If extra headers contain referer and the request contains a referer,
2541 // only the latter shall be respected.
2543 TestDelegate d;
2544 URLRequest req(test_server.GetURL("echoheader?Referer"),
2545 DEFAULT_PRIORITY,
2547 &default_context_);
2548 req.SetReferrer("http://foo.com/");
2550 HttpRequestHeaders headers;
2551 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
2552 req.SetExtraRequestHeaders(headers);
2554 req.Start();
2555 base::RunLoop().Run();
2557 EXPECT_EQ("http://foo.com/", d.data_received());
2560 // If extra headers contain a referer but the request does not, no referer
2561 // shall be sent in the header.
2563 TestDelegate d;
2564 URLRequest req(test_server.GetURL("echoheader?Referer"),
2565 DEFAULT_PRIORITY,
2567 &default_context_);
2569 HttpRequestHeaders headers;
2570 headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
2571 req.SetExtraRequestHeaders(headers);
2572 req.SetLoadFlags(LOAD_VALIDATE_CACHE);
2574 req.Start();
2575 base::RunLoop().Run();
2577 EXPECT_EQ("None", d.data_received());
2581 class URLRequestTestHTTP : public URLRequestTest {
2582 public:
2583 URLRequestTestHTTP()
2584 : test_server_(base::FilePath(FILE_PATH_LITERAL(
2585 "net/data/url_request_unittest"))) {
2588 protected:
2589 // Requests |redirect_url|, which must return a HTTP 3xx redirect.
2590 // |request_method| is the method to use for the initial request.
2591 // |redirect_method| is the method that is expected to be used for the second
2592 // request, after redirection.
2593 // If |include_data| is true, data is uploaded with the request. The
2594 // response body is expected to match it exactly, if and only if
2595 // |request_method| == |redirect_method|.
2596 void HTTPRedirectMethodTest(const GURL& redirect_url,
2597 const std::string& request_method,
2598 const std::string& redirect_method,
2599 bool include_data) {
2600 static const char kData[] = "hello world";
2601 TestDelegate d;
2602 URLRequest req(redirect_url, DEFAULT_PRIORITY, &d, &default_context_);
2603 req.set_method(request_method);
2604 if (include_data) {
2605 req.set_upload(make_scoped_ptr(CreateSimpleUploadData(kData)));
2606 HttpRequestHeaders headers;
2607 headers.SetHeader(HttpRequestHeaders::kContentLength,
2608 base::UintToString(arraysize(kData) - 1));
2609 req.SetExtraRequestHeaders(headers);
2611 req.Start();
2612 base::RunLoop().Run();
2613 EXPECT_EQ(redirect_method, req.method());
2614 EXPECT_EQ(URLRequestStatus::SUCCESS, req.status().status());
2615 EXPECT_EQ(OK, req.status().error());
2616 if (include_data) {
2617 if (request_method == redirect_method) {
2618 EXPECT_EQ(kData, d.data_received());
2619 } else {
2620 EXPECT_NE(kData, d.data_received());
2623 if (HasFailure())
2624 LOG(WARNING) << "Request method was: " << request_method;
2627 void HTTPUploadDataOperationTest(const std::string& method) {
2628 const int kMsgSize = 20000; // multiple of 10
2629 const int kIterations = 50;
2630 char* uploadBytes = new char[kMsgSize+1];
2631 char* ptr = uploadBytes;
2632 char marker = 'a';
2633 for (int idx = 0; idx < kMsgSize/10; idx++) {
2634 memcpy(ptr, "----------", 10);
2635 ptr += 10;
2636 if (idx % 100 == 0) {
2637 ptr--;
2638 *ptr++ = marker;
2639 if (++marker > 'z')
2640 marker = 'a';
2643 uploadBytes[kMsgSize] = '\0';
2645 for (int i = 0; i < kIterations; ++i) {
2646 TestDelegate d;
2647 URLRequest r(
2648 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, &default_context_);
2649 r.set_method(method.c_str());
2651 r.set_upload(make_scoped_ptr(CreateSimpleUploadData(uploadBytes)));
2653 r.Start();
2654 EXPECT_TRUE(r.is_pending());
2656 base::RunLoop().Run();
2658 ASSERT_EQ(1, d.response_started_count())
2659 << "request failed: " << r.status().status()
2660 << ", os error: " << r.status().error();
2662 EXPECT_FALSE(d.received_data_before_response());
2663 EXPECT_EQ(uploadBytes, d.data_received());
2665 delete[] uploadBytes;
2668 void AddChunksToUpload(URLRequest* r) {
2669 r->AppendChunkToUpload("a", 1, false);
2670 r->AppendChunkToUpload("bcd", 3, false);
2671 r->AppendChunkToUpload("this is a longer chunk than before.", 35, false);
2672 r->AppendChunkToUpload("\r\n\r\n", 4, false);
2673 r->AppendChunkToUpload("0", 1, false);
2674 r->AppendChunkToUpload("2323", 4, true);
2677 void VerifyReceivedDataMatchesChunks(URLRequest* r, TestDelegate* d) {
2678 // This should match the chunks sent by AddChunksToUpload().
2679 const std::string expected_data =
2680 "abcdthis is a longer chunk than before.\r\n\r\n02323";
2682 ASSERT_EQ(1, d->response_started_count())
2683 << "request failed: " << r->status().status()
2684 << ", os error: " << r->status().error();
2686 EXPECT_FALSE(d->received_data_before_response());
2688 EXPECT_EQ(expected_data.size(), static_cast<size_t>(d->bytes_received()));
2689 EXPECT_EQ(expected_data, d->data_received());
2692 bool DoManyCookiesRequest(int num_cookies) {
2693 TestDelegate d;
2694 URLRequest r(test_server_.GetURL("set-many-cookies?" +
2695 base::IntToString(num_cookies)),
2696 DEFAULT_PRIORITY,
2698 &default_context_);
2700 r.Start();
2701 EXPECT_TRUE(r.is_pending());
2703 base::RunLoop().Run();
2705 bool is_success = r.status().is_success();
2707 if (!is_success) {
2708 EXPECT_TRUE(r.status().error() == ERR_RESPONSE_HEADERS_TOO_BIG);
2709 // The test server appears to be unable to handle subsequent requests
2710 // after this error is triggered. Force it to restart.
2711 EXPECT_TRUE(test_server_.Stop());
2712 EXPECT_TRUE(test_server_.Start());
2715 return is_success;
2718 LocalHttpTestServer test_server_;
2721 // In this unit test, we're using the HTTPTestServer as a proxy server and
2722 // issuing a CONNECT request with the magic host name "www.redirect.com".
2723 // The HTTPTestServer will return a 302 response, which we should not
2724 // follow.
2725 TEST_F(URLRequestTestHTTP, ProxyTunnelRedirectTest) {
2726 ASSERT_TRUE(test_server_.Start());
2728 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
2729 TestURLRequestContextWithProxy context(
2730 test_server_.host_port_pair().ToString(), &network_delegate);
2732 TestDelegate d;
2734 URLRequest r(
2735 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d, &context);
2736 r.Start();
2737 EXPECT_TRUE(r.is_pending());
2739 base::RunLoop().Run();
2741 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
2742 // The proxy server is not set before failure.
2743 EXPECT_TRUE(r.proxy_server().IsEmpty());
2744 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r.status().error());
2745 EXPECT_EQ(1, d.response_started_count());
2746 // We should not have followed the redirect.
2747 EXPECT_EQ(0, d.received_redirect_count());
2751 // This is the same as the previous test, but checks that the network delegate
2752 // registers the error.
2753 TEST_F(URLRequestTestHTTP, NetworkDelegateTunnelConnectionFailed) {
2754 ASSERT_TRUE(test_server_.Start());
2756 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
2757 TestURLRequestContextWithProxy context(
2758 test_server_.host_port_pair().ToString(), &network_delegate);
2760 TestDelegate d;
2762 URLRequest r(
2763 GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d, &context);
2764 r.Start();
2765 EXPECT_TRUE(r.is_pending());
2767 base::RunLoop().Run();
2769 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
2770 // The proxy server is not set before failure.
2771 EXPECT_TRUE(r.proxy_server().IsEmpty());
2772 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r.status().error());
2773 EXPECT_EQ(1, d.response_started_count());
2774 // We should not have followed the redirect.
2775 EXPECT_EQ(0, d.received_redirect_count());
2777 EXPECT_EQ(1, network_delegate.error_count());
2778 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, network_delegate.last_error());
2782 // Tests that we can block and asynchronously return OK in various stages.
2783 TEST_F(URLRequestTestHTTP, NetworkDelegateBlockAsynchronously) {
2784 static const BlockingNetworkDelegate::Stage blocking_stages[] = {
2785 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
2786 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
2787 BlockingNetworkDelegate::ON_HEADERS_RECEIVED
2789 static const size_t blocking_stages_length = arraysize(blocking_stages);
2791 ASSERT_TRUE(test_server_.Start());
2793 TestDelegate d;
2794 BlockingNetworkDelegate network_delegate(
2795 BlockingNetworkDelegate::USER_CALLBACK);
2796 network_delegate.set_block_on(
2797 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST |
2798 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS |
2799 BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
2801 TestURLRequestContext context(true);
2802 context.set_network_delegate(&network_delegate);
2803 context.Init();
2806 URLRequest r(
2807 test_server_.GetURL("empty.html"), DEFAULT_PRIORITY, &d, &context);
2809 r.Start();
2810 for (size_t i = 0; i < blocking_stages_length; ++i) {
2811 base::RunLoop().Run();
2812 EXPECT_EQ(blocking_stages[i],
2813 network_delegate.stage_blocked_for_callback());
2814 network_delegate.DoCallback(OK);
2816 base::RunLoop().Run();
2817 EXPECT_EQ(200, r.GetResponseCode());
2818 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
2819 EXPECT_EQ(1, network_delegate.created_requests());
2820 EXPECT_EQ(0, network_delegate.destroyed_requests());
2822 EXPECT_EQ(1, network_delegate.destroyed_requests());
2825 // Tests that the network delegate can block and cancel a request.
2826 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequest) {
2827 ASSERT_TRUE(test_server_.Start());
2829 TestDelegate d;
2830 BlockingNetworkDelegate network_delegate(
2831 BlockingNetworkDelegate::AUTO_CALLBACK);
2832 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
2833 network_delegate.set_retval(ERR_EMPTY_RESPONSE);
2835 TestURLRequestContextWithProxy context(
2836 test_server_.host_port_pair().ToString(), &network_delegate);
2839 URLRequest r(
2840 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, &context);
2842 r.Start();
2843 base::RunLoop().Run();
2845 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
2846 // The proxy server is not set before cancellation.
2847 EXPECT_TRUE(r.proxy_server().IsEmpty());
2848 EXPECT_EQ(ERR_EMPTY_RESPONSE, r.status().error());
2849 EXPECT_EQ(1, network_delegate.created_requests());
2850 EXPECT_EQ(0, network_delegate.destroyed_requests());
2852 EXPECT_EQ(1, network_delegate.destroyed_requests());
2855 // Helper function for NetworkDelegateCancelRequestAsynchronously and
2856 // NetworkDelegateCancelRequestSynchronously. Sets up a blocking network
2857 // delegate operating in |block_mode| and a request for |url|. It blocks the
2858 // request in |stage| and cancels it with ERR_BLOCKED_BY_CLIENT.
2859 void NetworkDelegateCancelRequest(BlockingNetworkDelegate::BlockMode block_mode,
2860 BlockingNetworkDelegate::Stage stage,
2861 const GURL& url) {
2862 TestDelegate d;
2863 BlockingNetworkDelegate network_delegate(block_mode);
2864 network_delegate.set_retval(ERR_BLOCKED_BY_CLIENT);
2865 network_delegate.set_block_on(stage);
2867 TestURLRequestContext context(true);
2868 context.set_network_delegate(&network_delegate);
2869 context.Init();
2872 URLRequest r(url, DEFAULT_PRIORITY, &d, &context);
2874 r.Start();
2875 base::RunLoop().Run();
2877 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
2878 // The proxy server is not set before cancellation.
2879 EXPECT_TRUE(r.proxy_server().IsEmpty());
2880 EXPECT_EQ(ERR_BLOCKED_BY_CLIENT, r.status().error());
2881 EXPECT_EQ(1, network_delegate.created_requests());
2882 EXPECT_EQ(0, network_delegate.destroyed_requests());
2884 EXPECT_EQ(1, network_delegate.destroyed_requests());
2887 // The following 3 tests check that the network delegate can cancel a request
2888 // synchronously in various stages of the request.
2889 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously1) {
2890 ASSERT_TRUE(test_server_.Start());
2891 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
2892 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
2893 test_server_.GetURL(std::string()));
2896 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously2) {
2897 ASSERT_TRUE(test_server_.Start());
2898 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
2899 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
2900 test_server_.GetURL(std::string()));
2903 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously3) {
2904 ASSERT_TRUE(test_server_.Start());
2905 NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
2906 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
2907 test_server_.GetURL(std::string()));
2910 // The following 3 tests check that the network delegate can cancel a request
2911 // asynchronously in various stages of the request.
2912 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously1) {
2913 ASSERT_TRUE(test_server_.Start());
2914 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
2915 BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
2916 test_server_.GetURL(std::string()));
2919 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously2) {
2920 ASSERT_TRUE(test_server_.Start());
2921 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
2922 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
2923 test_server_.GetURL(std::string()));
2926 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously3) {
2927 ASSERT_TRUE(test_server_.Start());
2928 NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
2929 BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
2930 test_server_.GetURL(std::string()));
2933 // Tests that the network delegate can block and redirect a request to a new
2934 // URL.
2935 TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequest) {
2936 ASSERT_TRUE(test_server_.Start());
2938 TestDelegate d;
2939 BlockingNetworkDelegate network_delegate(
2940 BlockingNetworkDelegate::AUTO_CALLBACK);
2941 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
2942 GURL redirect_url(test_server_.GetURL("simple.html"));
2943 network_delegate.set_redirect_url(redirect_url);
2945 TestURLRequestContextWithProxy context(
2946 test_server_.host_port_pair().ToString(), &network_delegate);
2949 GURL original_url(test_server_.GetURL("empty.html"));
2950 URLRequest r(original_url, DEFAULT_PRIORITY, &d, &context);
2952 r.Start();
2953 base::RunLoop().Run();
2955 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
2956 EXPECT_TRUE(r.proxy_server().Equals(test_server_.host_port_pair()));
2957 EXPECT_EQ(
2958 1, network_delegate.observed_before_proxy_headers_sent_callbacks());
2959 EXPECT_TRUE(
2960 network_delegate.last_observed_proxy().Equals(
2961 test_server_.host_port_pair()));
2963 EXPECT_EQ(0, r.status().error());
2964 EXPECT_EQ(redirect_url, r.url());
2965 EXPECT_EQ(original_url, r.original_url());
2966 EXPECT_EQ(2U, r.url_chain().size());
2967 EXPECT_EQ(1, network_delegate.created_requests());
2968 EXPECT_EQ(0, network_delegate.destroyed_requests());
2970 EXPECT_EQ(1, network_delegate.destroyed_requests());
2973 // Tests that the network delegate can block and redirect a request to a new
2974 // URL by setting a redirect_url and returning in OnBeforeURLRequest directly.
2975 TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestSynchronously) {
2976 ASSERT_TRUE(test_server_.Start());
2978 TestDelegate d;
2979 BlockingNetworkDelegate network_delegate(
2980 BlockingNetworkDelegate::SYNCHRONOUS);
2981 GURL redirect_url(test_server_.GetURL("simple.html"));
2982 network_delegate.set_redirect_url(redirect_url);
2984 TestURLRequestContextWithProxy context(
2985 test_server_.host_port_pair().ToString(), &network_delegate);
2988 GURL original_url(test_server_.GetURL("empty.html"));
2989 URLRequest r(original_url, DEFAULT_PRIORITY, &d, &context);
2991 r.Start();
2992 base::RunLoop().Run();
2994 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
2995 EXPECT_TRUE(r.proxy_server().Equals(test_server_.host_port_pair()));
2996 EXPECT_EQ(
2997 1, network_delegate.observed_before_proxy_headers_sent_callbacks());
2998 EXPECT_TRUE(
2999 network_delegate.last_observed_proxy().Equals(
3000 test_server_.host_port_pair()));
3001 EXPECT_EQ(0, r.status().error());
3002 EXPECT_EQ(redirect_url, r.url());
3003 EXPECT_EQ(original_url, r.original_url());
3004 EXPECT_EQ(2U, r.url_chain().size());
3005 EXPECT_EQ(1, network_delegate.created_requests());
3006 EXPECT_EQ(0, network_delegate.destroyed_requests());
3008 EXPECT_EQ(1, network_delegate.destroyed_requests());
3011 // Tests that redirects caused by the network delegate preserve POST data.
3012 TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestPost) {
3013 ASSERT_TRUE(test_server_.Start());
3015 const char kData[] = "hello world";
3017 TestDelegate d;
3018 BlockingNetworkDelegate network_delegate(
3019 BlockingNetworkDelegate::AUTO_CALLBACK);
3020 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
3021 GURL redirect_url(test_server_.GetURL("echo"));
3022 network_delegate.set_redirect_url(redirect_url);
3024 TestURLRequestContext context(true);
3025 context.set_network_delegate(&network_delegate);
3026 context.Init();
3029 GURL original_url(test_server_.GetURL("empty.html"));
3030 URLRequest r(original_url, DEFAULT_PRIORITY, &d, &context);
3031 r.set_method("POST");
3032 r.set_upload(make_scoped_ptr(CreateSimpleUploadData(kData)));
3033 HttpRequestHeaders headers;
3034 headers.SetHeader(HttpRequestHeaders::kContentLength,
3035 base::UintToString(arraysize(kData) - 1));
3036 r.SetExtraRequestHeaders(headers);
3037 r.Start();
3038 base::RunLoop().Run();
3040 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3041 EXPECT_EQ(0, 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(1, network_delegate.created_requests());
3046 EXPECT_EQ(0, network_delegate.destroyed_requests());
3047 EXPECT_EQ("POST", r.method());
3048 EXPECT_EQ(kData, d.data_received());
3050 EXPECT_EQ(1, network_delegate.destroyed_requests());
3053 // Tests that the network delegate can block and redirect a request to a new
3054 // URL during OnHeadersReceived.
3055 TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestOnHeadersReceived) {
3056 ASSERT_TRUE(test_server_.Start());
3058 TestDelegate d;
3059 BlockingNetworkDelegate network_delegate(
3060 BlockingNetworkDelegate::AUTO_CALLBACK);
3061 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
3062 GURL redirect_url(test_server_.GetURL("simple.html"));
3063 network_delegate.set_redirect_on_headers_received_url(redirect_url);
3065 TestURLRequestContextWithProxy context(
3066 test_server_.host_port_pair().ToString(), &network_delegate);
3069 GURL original_url(test_server_.GetURL("empty.html"));
3070 URLRequest r(original_url, DEFAULT_PRIORITY, &d, &context);
3072 r.Start();
3073 base::RunLoop().Run();
3075 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3076 EXPECT_TRUE(r.proxy_server().Equals(test_server_.host_port_pair()));
3077 EXPECT_EQ(
3078 2, network_delegate.observed_before_proxy_headers_sent_callbacks());
3079 EXPECT_TRUE(
3080 network_delegate.last_observed_proxy().Equals(
3081 test_server_.host_port_pair()));
3082 EXPECT_EQ(net::OK, r.status().error());
3083 EXPECT_EQ(redirect_url, r.url());
3084 EXPECT_EQ(original_url, r.original_url());
3085 EXPECT_EQ(2U, r.url_chain().size());
3086 EXPECT_EQ(2, network_delegate.created_requests());
3087 EXPECT_EQ(0, network_delegate.destroyed_requests());
3089 EXPECT_EQ(1, network_delegate.destroyed_requests());
3092 // Tests that the network delegate can synchronously complete OnAuthRequired
3093 // by taking no action. This indicates that the NetworkDelegate does not want to
3094 // handle the challenge, and is passing the buck along to the
3095 // URLRequest::Delegate.
3096 TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncNoAction) {
3097 ASSERT_TRUE(test_server_.Start());
3099 TestDelegate d;
3100 BlockingNetworkDelegate network_delegate(
3101 BlockingNetworkDelegate::SYNCHRONOUS);
3103 TestURLRequestContext context(true);
3104 context.set_network_delegate(&network_delegate);
3105 context.Init();
3107 d.set_credentials(AuthCredentials(kUser, kSecret));
3110 GURL url(test_server_.GetURL("auth-basic"));
3111 URLRequest r(url, DEFAULT_PRIORITY, &d, &context);
3112 r.Start();
3114 base::RunLoop().Run();
3116 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3117 EXPECT_EQ(0, r.status().error());
3118 EXPECT_EQ(200, r.GetResponseCode());
3119 EXPECT_TRUE(d.auth_required_called());
3120 EXPECT_EQ(1, network_delegate.created_requests());
3121 EXPECT_EQ(0, network_delegate.destroyed_requests());
3123 EXPECT_EQ(1, network_delegate.destroyed_requests());
3126 TEST_F(URLRequestTestHTTP,
3127 NetworkDelegateOnAuthRequiredSyncNoAction_GetFullRequestHeaders) {
3128 ASSERT_TRUE(test_server_.Start());
3130 TestDelegate d;
3131 BlockingNetworkDelegate network_delegate(
3132 BlockingNetworkDelegate::SYNCHRONOUS);
3134 TestURLRequestContext context(true);
3135 context.set_network_delegate(&network_delegate);
3136 context.Init();
3138 d.set_credentials(AuthCredentials(kUser, kSecret));
3141 GURL url(test_server_.GetURL("auth-basic"));
3142 URLRequest r(url, DEFAULT_PRIORITY, &d, &context);
3143 r.Start();
3146 HttpRequestHeaders headers;
3147 EXPECT_TRUE(r.GetFullRequestHeaders(&headers));
3148 EXPECT_FALSE(headers.HasHeader("Authorization"));
3151 base::RunLoop().Run();
3153 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3154 EXPECT_EQ(0, r.status().error());
3155 EXPECT_EQ(200, r.GetResponseCode());
3156 EXPECT_TRUE(d.auth_required_called());
3157 EXPECT_EQ(1, network_delegate.created_requests());
3158 EXPECT_EQ(0, network_delegate.destroyed_requests());
3160 EXPECT_EQ(1, network_delegate.destroyed_requests());
3163 // Tests that the network delegate can synchronously complete OnAuthRequired
3164 // by setting credentials.
3165 TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncSetAuth) {
3166 ASSERT_TRUE(test_server_.Start());
3168 TestDelegate d;
3169 BlockingNetworkDelegate network_delegate(
3170 BlockingNetworkDelegate::SYNCHRONOUS);
3171 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3172 network_delegate.set_auth_retval(
3173 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3175 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
3177 TestURLRequestContext context(true);
3178 context.set_network_delegate(&network_delegate);
3179 context.Init();
3182 GURL url(test_server_.GetURL("auth-basic"));
3183 URLRequest r(url, DEFAULT_PRIORITY, &d, &context);
3184 r.Start();
3185 base::RunLoop().Run();
3187 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3188 EXPECT_EQ(0, r.status().error());
3189 EXPECT_EQ(200, r.GetResponseCode());
3190 EXPECT_FALSE(d.auth_required_called());
3191 EXPECT_EQ(1, network_delegate.created_requests());
3192 EXPECT_EQ(0, network_delegate.destroyed_requests());
3194 EXPECT_EQ(1, network_delegate.destroyed_requests());
3197 // Same as above, but also tests that GetFullRequestHeaders returns the proper
3198 // headers (for the first or second request) when called at the proper times.
3199 TEST_F(URLRequestTestHTTP,
3200 NetworkDelegateOnAuthRequiredSyncSetAuth_GetFullRequestHeaders) {
3201 ASSERT_TRUE(test_server_.Start());
3203 TestDelegate d;
3204 BlockingNetworkDelegate network_delegate(
3205 BlockingNetworkDelegate::SYNCHRONOUS);
3206 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3207 network_delegate.set_auth_retval(
3208 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3210 network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
3212 TestURLRequestContext context(true);
3213 context.set_network_delegate(&network_delegate);
3214 context.Init();
3217 GURL url(test_server_.GetURL("auth-basic"));
3218 URLRequest r(url, DEFAULT_PRIORITY, &d, &context);
3219 r.Start();
3220 base::RunLoop().Run();
3222 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3223 EXPECT_EQ(0, r.status().error());
3224 EXPECT_EQ(200, r.GetResponseCode());
3225 EXPECT_FALSE(d.auth_required_called());
3226 EXPECT_EQ(1, network_delegate.created_requests());
3227 EXPECT_EQ(0, network_delegate.destroyed_requests());
3230 HttpRequestHeaders headers;
3231 EXPECT_TRUE(r.GetFullRequestHeaders(&headers));
3232 EXPECT_TRUE(headers.HasHeader("Authorization"));
3235 EXPECT_EQ(1, network_delegate.destroyed_requests());
3238 // Tests that the network delegate can synchronously complete OnAuthRequired
3239 // by cancelling authentication.
3240 TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncCancel) {
3241 ASSERT_TRUE(test_server_.Start());
3243 TestDelegate d;
3244 BlockingNetworkDelegate network_delegate(
3245 BlockingNetworkDelegate::SYNCHRONOUS);
3246 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3247 network_delegate.set_auth_retval(
3248 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
3250 TestURLRequestContext context(true);
3251 context.set_network_delegate(&network_delegate);
3252 context.Init();
3255 GURL url(test_server_.GetURL("auth-basic"));
3256 URLRequest r(url, DEFAULT_PRIORITY, &d, &context);
3257 r.Start();
3258 base::RunLoop().Run();
3260 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3261 EXPECT_EQ(OK, r.status().error());
3262 EXPECT_EQ(401, r.GetResponseCode());
3263 EXPECT_FALSE(d.auth_required_called());
3264 EXPECT_EQ(1, network_delegate.created_requests());
3265 EXPECT_EQ(0, network_delegate.destroyed_requests());
3267 EXPECT_EQ(1, network_delegate.destroyed_requests());
3270 // Tests that the network delegate can asynchronously complete OnAuthRequired
3271 // by taking no action. This indicates that the NetworkDelegate does not want
3272 // to handle the challenge, and is passing the buck along to the
3273 // URLRequest::Delegate.
3274 TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncNoAction) {
3275 ASSERT_TRUE(test_server_.Start());
3277 TestDelegate d;
3278 BlockingNetworkDelegate network_delegate(
3279 BlockingNetworkDelegate::AUTO_CALLBACK);
3280 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3282 TestURLRequestContext context(true);
3283 context.set_network_delegate(&network_delegate);
3284 context.Init();
3286 d.set_credentials(AuthCredentials(kUser, kSecret));
3289 GURL url(test_server_.GetURL("auth-basic"));
3290 URLRequest r(url, DEFAULT_PRIORITY, &d, &context);
3291 r.Start();
3292 base::RunLoop().Run();
3294 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3295 EXPECT_EQ(0, r.status().error());
3296 EXPECT_EQ(200, r.GetResponseCode());
3297 EXPECT_TRUE(d.auth_required_called());
3298 EXPECT_EQ(1, network_delegate.created_requests());
3299 EXPECT_EQ(0, network_delegate.destroyed_requests());
3301 EXPECT_EQ(1, network_delegate.destroyed_requests());
3304 // Tests that the network delegate can asynchronously complete OnAuthRequired
3305 // by setting credentials.
3306 TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncSetAuth) {
3307 ASSERT_TRUE(test_server_.Start());
3309 TestDelegate d;
3310 BlockingNetworkDelegate network_delegate(
3311 BlockingNetworkDelegate::AUTO_CALLBACK);
3312 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3313 network_delegate.set_auth_retval(
3314 NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3316 AuthCredentials auth_credentials(kUser, kSecret);
3317 network_delegate.set_auth_credentials(auth_credentials);
3319 TestURLRequestContext context(true);
3320 context.set_network_delegate(&network_delegate);
3321 context.Init();
3324 GURL url(test_server_.GetURL("auth-basic"));
3325 URLRequest r(url, DEFAULT_PRIORITY, &d, &context);
3326 r.Start();
3327 base::RunLoop().Run();
3329 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3330 EXPECT_EQ(0, r.status().error());
3332 EXPECT_EQ(200, r.GetResponseCode());
3333 EXPECT_FALSE(d.auth_required_called());
3334 EXPECT_EQ(1, network_delegate.created_requests());
3335 EXPECT_EQ(0, network_delegate.destroyed_requests());
3337 EXPECT_EQ(1, network_delegate.destroyed_requests());
3340 // Tests that the network delegate can asynchronously complete OnAuthRequired
3341 // by cancelling authentication.
3342 TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncCancel) {
3343 ASSERT_TRUE(test_server_.Start());
3345 TestDelegate d;
3346 BlockingNetworkDelegate network_delegate(
3347 BlockingNetworkDelegate::AUTO_CALLBACK);
3348 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3349 network_delegate.set_auth_retval(
3350 NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
3352 TestURLRequestContext context(true);
3353 context.set_network_delegate(&network_delegate);
3354 context.Init();
3357 GURL url(test_server_.GetURL("auth-basic"));
3358 URLRequest r(url, DEFAULT_PRIORITY, &d, &context);
3359 r.Start();
3360 base::RunLoop().Run();
3362 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
3363 EXPECT_EQ(OK, r.status().error());
3364 EXPECT_EQ(401, r.GetResponseCode());
3365 EXPECT_FALSE(d.auth_required_called());
3366 EXPECT_EQ(1, network_delegate.created_requests());
3367 EXPECT_EQ(0, network_delegate.destroyed_requests());
3369 EXPECT_EQ(1, network_delegate.destroyed_requests());
3372 // Tests that we can handle when a network request was canceled while we were
3373 // waiting for the network delegate.
3374 // Part 1: Request is cancelled while waiting for OnBeforeURLRequest callback.
3375 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting1) {
3376 ASSERT_TRUE(test_server_.Start());
3378 TestDelegate d;
3379 BlockingNetworkDelegate network_delegate(
3380 BlockingNetworkDelegate::USER_CALLBACK);
3381 network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
3383 TestURLRequestContext context(true);
3384 context.set_network_delegate(&network_delegate);
3385 context.Init();
3388 URLRequest r(
3389 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, &context);
3391 r.Start();
3392 base::RunLoop().Run();
3393 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
3394 network_delegate.stage_blocked_for_callback());
3395 EXPECT_EQ(0, network_delegate.completed_requests());
3396 // Cancel before callback.
3397 r.Cancel();
3398 // Ensure that network delegate is notified.
3399 EXPECT_EQ(1, network_delegate.completed_requests());
3400 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
3401 EXPECT_EQ(ERR_ABORTED, r.status().error());
3402 EXPECT_EQ(1, network_delegate.created_requests());
3403 EXPECT_EQ(0, network_delegate.destroyed_requests());
3405 EXPECT_EQ(1, network_delegate.destroyed_requests());
3408 // Tests that we can handle when a network request was canceled while we were
3409 // waiting for the network delegate.
3410 // Part 2: Request is cancelled while waiting for OnBeforeSendHeaders callback.
3411 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting2) {
3412 ASSERT_TRUE(test_server_.Start());
3414 TestDelegate d;
3415 BlockingNetworkDelegate network_delegate(
3416 BlockingNetworkDelegate::USER_CALLBACK);
3417 network_delegate.set_block_on(
3418 BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS);
3420 TestURLRequestContext context(true);
3421 context.set_network_delegate(&network_delegate);
3422 context.Init();
3425 URLRequest r(
3426 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, &context);
3428 r.Start();
3429 base::RunLoop().Run();
3430 EXPECT_EQ(BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
3431 network_delegate.stage_blocked_for_callback());
3432 EXPECT_EQ(0, network_delegate.completed_requests());
3433 // Cancel before callback.
3434 r.Cancel();
3435 // Ensure that network delegate is notified.
3436 EXPECT_EQ(1, network_delegate.completed_requests());
3437 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
3438 EXPECT_EQ(ERR_ABORTED, r.status().error());
3439 EXPECT_EQ(1, network_delegate.created_requests());
3440 EXPECT_EQ(0, network_delegate.destroyed_requests());
3442 EXPECT_EQ(1, network_delegate.destroyed_requests());
3445 // Tests that we can handle when a network request was canceled while we were
3446 // waiting for the network delegate.
3447 // Part 3: Request is cancelled while waiting for OnHeadersReceived callback.
3448 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting3) {
3449 ASSERT_TRUE(test_server_.Start());
3451 TestDelegate d;
3452 BlockingNetworkDelegate network_delegate(
3453 BlockingNetworkDelegate::USER_CALLBACK);
3454 network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
3456 TestURLRequestContext context(true);
3457 context.set_network_delegate(&network_delegate);
3458 context.Init();
3461 URLRequest r(
3462 test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, &context);
3464 r.Start();
3465 base::RunLoop().Run();
3466 EXPECT_EQ(BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
3467 network_delegate.stage_blocked_for_callback());
3468 EXPECT_EQ(0, network_delegate.completed_requests());
3469 // Cancel before callback.
3470 r.Cancel();
3471 // Ensure that network delegate is notified.
3472 EXPECT_EQ(1, network_delegate.completed_requests());
3473 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
3474 EXPECT_EQ(ERR_ABORTED, r.status().error());
3475 EXPECT_EQ(1, network_delegate.created_requests());
3476 EXPECT_EQ(0, network_delegate.destroyed_requests());
3478 EXPECT_EQ(1, network_delegate.destroyed_requests());
3481 // Tests that we can handle when a network request was canceled while we were
3482 // waiting for the network delegate.
3483 // Part 4: Request is cancelled while waiting for OnAuthRequired callback.
3484 TEST_F(URLRequestTestHTTP, NetworkDelegateCancelWhileWaiting4) {
3485 ASSERT_TRUE(test_server_.Start());
3487 TestDelegate d;
3488 BlockingNetworkDelegate network_delegate(
3489 BlockingNetworkDelegate::USER_CALLBACK);
3490 network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3492 TestURLRequestContext context(true);
3493 context.set_network_delegate(&network_delegate);
3494 context.Init();
3497 URLRequest r(
3498 test_server_.GetURL("auth-basic"), DEFAULT_PRIORITY, &d, &context);
3500 r.Start();
3501 base::RunLoop().Run();
3502 EXPECT_EQ(BlockingNetworkDelegate::ON_AUTH_REQUIRED,
3503 network_delegate.stage_blocked_for_callback());
3504 EXPECT_EQ(0, network_delegate.completed_requests());
3505 // Cancel before callback.
3506 r.Cancel();
3507 // Ensure that network delegate is notified.
3508 EXPECT_EQ(1, network_delegate.completed_requests());
3509 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
3510 EXPECT_EQ(ERR_ABORTED, r.status().error());
3511 EXPECT_EQ(1, network_delegate.created_requests());
3512 EXPECT_EQ(0, network_delegate.destroyed_requests());
3514 EXPECT_EQ(1, network_delegate.destroyed_requests());
3517 // In this unit test, we're using the HTTPTestServer as a proxy server and
3518 // issuing a CONNECT request with the magic host name "www.server-auth.com".
3519 // The HTTPTestServer will return a 401 response, which we should balk at.
3520 TEST_F(URLRequestTestHTTP, UnexpectedServerAuthTest) {
3521 ASSERT_TRUE(test_server_.Start());
3523 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
3524 TestURLRequestContextWithProxy context(
3525 test_server_.host_port_pair().ToString(), &network_delegate);
3527 TestDelegate d;
3529 URLRequest r(
3530 GURL("https://www.server-auth.com/"), DEFAULT_PRIORITY, &d, &context);
3532 r.Start();
3533 EXPECT_TRUE(r.is_pending());
3535 base::RunLoop().Run();
3537 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
3538 // The proxy server is not set before failure.
3539 EXPECT_TRUE(r.proxy_server().IsEmpty());
3540 EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r.status().error());
3544 TEST_F(URLRequestTestHTTP, GetTest_NoCache) {
3545 ASSERT_TRUE(test_server_.Start());
3547 TestDelegate d;
3549 URLRequest r(test_server_.GetURL(std::string()),
3550 DEFAULT_PRIORITY,
3552 &default_context_);
3554 r.Start();
3555 EXPECT_TRUE(r.is_pending());
3557 base::RunLoop().Run();
3559 EXPECT_EQ(1, d.response_started_count());
3560 EXPECT_FALSE(d.received_data_before_response());
3561 EXPECT_NE(0, d.bytes_received());
3562 EXPECT_EQ(test_server_.host_port_pair().host(),
3563 r.GetSocketAddress().host());
3564 EXPECT_EQ(test_server_.host_port_pair().port(),
3565 r.GetSocketAddress().port());
3567 // TODO(eroman): Add back the NetLog tests...
3571 // This test has the server send a large number of cookies to the client.
3572 // To ensure that no number of cookies causes a crash, a galloping binary
3573 // search is used to estimate that maximum number of cookies that are accepted
3574 // by the browser. Beyond the maximum number, the request will fail with
3575 // ERR_RESPONSE_HEADERS_TOO_BIG.
3576 #if defined(OS_WIN)
3577 // http://crbug.com/177916
3578 #define MAYBE_GetTest_ManyCookies DISABLED_GetTest_ManyCookies
3579 #else
3580 #define MAYBE_GetTest_ManyCookies GetTest_ManyCookies
3581 #endif // defined(OS_WIN)
3582 TEST_F(URLRequestTestHTTP, MAYBE_GetTest_ManyCookies) {
3583 ASSERT_TRUE(test_server_.Start());
3585 int lower_bound = 0;
3586 int upper_bound = 1;
3588 // Double the number of cookies until the response header limits are
3589 // exceeded.
3590 while (DoManyCookiesRequest(upper_bound)) {
3591 lower_bound = upper_bound;
3592 upper_bound *= 2;
3593 ASSERT_LT(upper_bound, 1000000);
3596 int tolerance = upper_bound * 0.005;
3597 if (tolerance < 2)
3598 tolerance = 2;
3600 // Perform a binary search to find the highest possible number of cookies,
3601 // within the desired tolerance.
3602 while (upper_bound - lower_bound >= tolerance) {
3603 int num_cookies = (lower_bound + upper_bound) / 2;
3605 if (DoManyCookiesRequest(num_cookies))
3606 lower_bound = num_cookies;
3607 else
3608 upper_bound = num_cookies;
3610 // Success: the test did not crash.
3613 TEST_F(URLRequestTestHTTP, GetTest) {
3614 ASSERT_TRUE(test_server_.Start());
3616 TestDelegate d;
3618 URLRequest r(test_server_.GetURL(std::string()),
3619 DEFAULT_PRIORITY,
3621 &default_context_);
3623 r.Start();
3624 EXPECT_TRUE(r.is_pending());
3626 base::RunLoop().Run();
3628 EXPECT_EQ(1, d.response_started_count());
3629 EXPECT_FALSE(d.received_data_before_response());
3630 EXPECT_NE(0, d.bytes_received());
3631 EXPECT_EQ(test_server_.host_port_pair().host(),
3632 r.GetSocketAddress().host());
3633 EXPECT_EQ(test_server_.host_port_pair().port(),
3634 r.GetSocketAddress().port());
3638 TEST_F(URLRequestTestHTTP, GetTest_GetFullRequestHeaders) {
3639 ASSERT_TRUE(test_server_.Start());
3641 TestDelegate d;
3643 GURL test_url(test_server_.GetURL(std::string()));
3644 URLRequest r(test_url, DEFAULT_PRIORITY, &d, &default_context_);
3646 HttpRequestHeaders headers;
3647 EXPECT_FALSE(r.GetFullRequestHeaders(&headers));
3649 r.Start();
3650 EXPECT_TRUE(r.is_pending());
3652 base::RunLoop().Run();
3654 EXPECT_EQ(1, d.response_started_count());
3655 EXPECT_FALSE(d.received_data_before_response());
3656 EXPECT_NE(0, d.bytes_received());
3657 EXPECT_EQ(test_server_.host_port_pair().host(),
3658 r.GetSocketAddress().host());
3659 EXPECT_EQ(test_server_.host_port_pair().port(),
3660 r.GetSocketAddress().port());
3662 EXPECT_TRUE(d.have_full_request_headers());
3663 CheckFullRequestHeaders(d.full_request_headers(), test_url);
3667 TEST_F(URLRequestTestHTTP, GetTestLoadTiming) {
3668 ASSERT_TRUE(test_server_.Start());
3670 TestDelegate d;
3672 URLRequest r(test_server_.GetURL(std::string()),
3673 DEFAULT_PRIORITY,
3675 &default_context_);
3677 r.Start();
3678 EXPECT_TRUE(r.is_pending());
3680 base::RunLoop().Run();
3682 LoadTimingInfo load_timing_info;
3683 r.GetLoadTimingInfo(&load_timing_info);
3684 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
3686 EXPECT_EQ(1, d.response_started_count());
3687 EXPECT_FALSE(d.received_data_before_response());
3688 EXPECT_NE(0, d.bytes_received());
3689 EXPECT_EQ(test_server_.host_port_pair().host(),
3690 r.GetSocketAddress().host());
3691 EXPECT_EQ(test_server_.host_port_pair().port(),
3692 r.GetSocketAddress().port());
3696 TEST_F(URLRequestTestHTTP, GetZippedTest) {
3697 ASSERT_TRUE(test_server_.Start());
3699 // Parameter that specifies the Content-Length field in the response:
3700 // C - Compressed length.
3701 // U - Uncompressed length.
3702 // L - Large length (larger than both C & U).
3703 // M - Medium length (between C & U).
3704 // S - Small length (smaller than both C & U).
3705 const char test_parameters[] = "CULMS";
3706 const int num_tests = arraysize(test_parameters)- 1; // Skip NULL.
3707 // C & U should be OK.
3708 // L & M are larger than the data sent, and show an error.
3709 // S has too little data, but we seem to accept it.
3710 const bool test_expect_success[num_tests] =
3711 { true, true, false, false, true };
3713 for (int i = 0; i < num_tests ; i++) {
3714 TestDelegate d;
3716 std::string test_file =
3717 base::StringPrintf("compressedfiles/BullRunSpeech.txt?%c",
3718 test_parameters[i]);
3720 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
3721 TestURLRequestContext context(true);
3722 context.set_network_delegate(&network_delegate);
3723 context.Init();
3725 URLRequest r(
3726 test_server_.GetURL(test_file), DEFAULT_PRIORITY, &d, &context);
3727 r.Start();
3728 EXPECT_TRUE(r.is_pending());
3730 base::RunLoop().Run();
3732 EXPECT_EQ(1, d.response_started_count());
3733 EXPECT_FALSE(d.received_data_before_response());
3734 VLOG(1) << " Received " << d.bytes_received() << " bytes"
3735 << " status = " << r.status().status()
3736 << " error = " << r.status().error();
3737 if (test_expect_success[i]) {
3738 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status())
3739 << " Parameter = \"" << test_file << "\"";
3740 } else {
3741 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
3742 EXPECT_EQ(ERR_CONTENT_LENGTH_MISMATCH, r.status().error())
3743 << " Parameter = \"" << test_file << "\"";
3749 TEST_F(URLRequestTestHTTP, HTTPSToHTTPRedirectNoRefererTest) {
3750 ASSERT_TRUE(test_server_.Start());
3752 SpawnedTestServer https_test_server(
3753 SpawnedTestServer::TYPE_HTTPS, SpawnedTestServer::kLocalhost,
3754 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
3755 ASSERT_TRUE(https_test_server.Start());
3757 // An https server is sent a request with an https referer,
3758 // and responds with a redirect to an http url. The http
3759 // server should not be sent the referer.
3760 GURL http_destination = test_server_.GetURL(std::string());
3761 TestDelegate d;
3762 URLRequest req(
3763 https_test_server.GetURL("server-redirect?" + http_destination.spec()),
3764 DEFAULT_PRIORITY,
3766 &default_context_);
3767 req.SetReferrer("https://www.referrer.com/");
3768 req.Start();
3769 base::RunLoop().Run();
3771 EXPECT_EQ(1, d.response_started_count());
3772 EXPECT_EQ(1, d.received_redirect_count());
3773 EXPECT_EQ(http_destination, req.url());
3774 EXPECT_EQ(std::string(), req.referrer());
3777 TEST_F(URLRequestTestHTTP, RedirectLoadTiming) {
3778 ASSERT_TRUE(test_server_.Start());
3780 GURL destination_url = test_server_.GetURL(std::string());
3781 GURL original_url =
3782 test_server_.GetURL("server-redirect?" + destination_url.spec());
3783 TestDelegate d;
3784 URLRequest req(original_url, DEFAULT_PRIORITY, &d, &default_context_);
3785 req.Start();
3786 base::RunLoop().Run();
3788 EXPECT_EQ(1, d.response_started_count());
3789 EXPECT_EQ(1, d.received_redirect_count());
3790 EXPECT_EQ(destination_url, req.url());
3791 EXPECT_EQ(original_url, req.original_url());
3792 ASSERT_EQ(2U, req.url_chain().size());
3793 EXPECT_EQ(original_url, req.url_chain()[0]);
3794 EXPECT_EQ(destination_url, req.url_chain()[1]);
3796 LoadTimingInfo load_timing_info_before_redirect;
3797 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeRedirect(
3798 &load_timing_info_before_redirect));
3799 TestLoadTimingNotReused(load_timing_info_before_redirect,
3800 CONNECT_TIMING_HAS_DNS_TIMES);
3802 LoadTimingInfo load_timing_info;
3803 req.GetLoadTimingInfo(&load_timing_info);
3804 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
3806 // Check that a new socket was used on redirect, since the server does not
3807 // supposed keep-alive sockets, and that the times before the redirect are
3808 // before the ones recorded for the second request.
3809 EXPECT_NE(load_timing_info_before_redirect.socket_log_id,
3810 load_timing_info.socket_log_id);
3811 EXPECT_LE(load_timing_info_before_redirect.receive_headers_end,
3812 load_timing_info.connect_timing.connect_start);
3815 TEST_F(URLRequestTestHTTP, MultipleRedirectTest) {
3816 ASSERT_TRUE(test_server_.Start());
3818 GURL destination_url = test_server_.GetURL(std::string());
3819 GURL middle_redirect_url =
3820 test_server_.GetURL("server-redirect?" + destination_url.spec());
3821 GURL original_url = test_server_.GetURL(
3822 "server-redirect?" + middle_redirect_url.spec());
3823 TestDelegate d;
3824 URLRequest req(original_url, DEFAULT_PRIORITY, &d, &default_context_);
3825 req.Start();
3826 base::RunLoop().Run();
3828 EXPECT_EQ(1, d.response_started_count());
3829 EXPECT_EQ(2, d.received_redirect_count());
3830 EXPECT_EQ(destination_url, req.url());
3831 EXPECT_EQ(original_url, req.original_url());
3832 ASSERT_EQ(3U, req.url_chain().size());
3833 EXPECT_EQ(original_url, req.url_chain()[0]);
3834 EXPECT_EQ(middle_redirect_url, req.url_chain()[1]);
3835 EXPECT_EQ(destination_url, req.url_chain()[2]);
3838 // First and second pieces of information logged by delegates to URLRequests.
3839 const char kFirstDelegateInfo[] = "Wonderful delegate";
3840 const char kSecondDelegateInfo[] = "Exciting delegate";
3842 // Logs delegate information to a URLRequest. The first string is logged
3843 // synchronously on Start(), using DELEGATE_INFO_DEBUG_ONLY. The second is
3844 // logged asynchronously, using DELEGATE_INFO_DISPLAY_TO_USER. Then
3845 // another asynchronous call is used to clear the delegate information
3846 // before calling a callback. The object then deletes itself.
3847 class AsyncDelegateLogger : public base::RefCounted<AsyncDelegateLogger> {
3848 public:
3849 typedef base::Callback<void()> Callback;
3851 // Each time delegate information is added to the URLRequest, the resulting
3852 // load state is checked. The expected load state after each request is
3853 // passed in as an argument.
3854 static void Run(URLRequest* url_request,
3855 LoadState expected_first_load_state,
3856 LoadState expected_second_load_state,
3857 LoadState expected_third_load_state,
3858 const Callback& callback) {
3859 AsyncDelegateLogger* logger = new AsyncDelegateLogger(
3860 url_request,
3861 expected_first_load_state,
3862 expected_second_load_state,
3863 expected_third_load_state,
3864 callback);
3865 logger->Start();
3868 // Checks that the log entries, starting with log_position, contain the
3869 // DELEGATE_INFO NetLog events that an AsyncDelegateLogger should have
3870 // recorded. Returns the index of entry after the expected number of
3871 // events this logged, or entries.size() if there aren't enough entries.
3872 static size_t CheckDelegateInfo(
3873 const CapturingNetLog::CapturedEntryList& entries, size_t log_position) {
3874 // There should be 4 DELEGATE_INFO events: Two begins and two ends.
3875 if (log_position + 3 >= entries.size()) {
3876 ADD_FAILURE() << "Not enough log entries";
3877 return entries.size();
3879 std::string delegate_info;
3880 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
3881 EXPECT_EQ(NetLog::PHASE_BEGIN, entries[log_position].phase);
3882 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_info",
3883 &delegate_info));
3884 EXPECT_EQ(kFirstDelegateInfo, delegate_info);
3886 ++log_position;
3887 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
3888 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
3890 ++log_position;
3891 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
3892 EXPECT_EQ(NetLog::PHASE_BEGIN, entries[log_position].phase);
3893 EXPECT_TRUE(entries[log_position].GetStringValue("delegate_info",
3894 &delegate_info));
3895 EXPECT_EQ(kSecondDelegateInfo, delegate_info);
3897 ++log_position;
3898 EXPECT_EQ(NetLog::TYPE_DELEGATE_INFO, entries[log_position].type);
3899 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
3901 return log_position + 1;
3904 // Find delegate request begin and end messages for OnBeforeNetworkStart.
3905 // Returns the position of the end message.
3906 static size_t ExpectBeforeNetworkEvents(
3907 const CapturingNetLog::CapturedEntryList& entries,
3908 size_t log_position) {
3909 log_position =
3910 ExpectLogContainsSomewhereAfter(entries,
3911 log_position,
3912 NetLog::TYPE_URL_REQUEST_DELEGATE,
3913 NetLog::PHASE_BEGIN);
3914 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE,
3915 entries[log_position + 1].type);
3916 EXPECT_EQ(NetLog::PHASE_END, entries[log_position + 1].phase);
3917 return log_position + 1;
3920 private:
3921 friend class base::RefCounted<AsyncDelegateLogger>;
3923 AsyncDelegateLogger(URLRequest* url_request,
3924 LoadState expected_first_load_state,
3925 LoadState expected_second_load_state,
3926 LoadState expected_third_load_state,
3927 const Callback& callback)
3928 : url_request_(url_request),
3929 expected_first_load_state_(expected_first_load_state),
3930 expected_second_load_state_(expected_second_load_state),
3931 expected_third_load_state_(expected_third_load_state),
3932 callback_(callback) {
3935 ~AsyncDelegateLogger() {}
3937 void Start() {
3938 url_request_->LogBlockedBy(kFirstDelegateInfo);
3939 LoadStateWithParam load_state = url_request_->GetLoadState();
3940 EXPECT_EQ(expected_first_load_state_, load_state.state);
3941 EXPECT_NE(ASCIIToUTF16(kFirstDelegateInfo), load_state.param);
3942 base::MessageLoop::current()->PostTask(
3943 FROM_HERE,
3944 base::Bind(&AsyncDelegateLogger::LogSecondDelegate, this));
3947 void LogSecondDelegate() {
3948 url_request_->LogAndReportBlockedBy(kSecondDelegateInfo);
3949 LoadStateWithParam load_state = url_request_->GetLoadState();
3950 EXPECT_EQ(expected_second_load_state_, load_state.state);
3951 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE) {
3952 EXPECT_EQ(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
3953 } else {
3954 EXPECT_NE(ASCIIToUTF16(kSecondDelegateInfo), load_state.param);
3956 base::MessageLoop::current()->PostTask(
3957 FROM_HERE,
3958 base::Bind(&AsyncDelegateLogger::LogComplete, this));
3961 void LogComplete() {
3962 url_request_->LogUnblocked();
3963 LoadStateWithParam load_state = url_request_->GetLoadState();
3964 EXPECT_EQ(expected_third_load_state_, load_state.state);
3965 if (expected_second_load_state_ == LOAD_STATE_WAITING_FOR_DELEGATE)
3966 EXPECT_EQ(base::string16(), load_state.param);
3967 callback_.Run();
3970 URLRequest* url_request_;
3971 const int expected_first_load_state_;
3972 const int expected_second_load_state_;
3973 const int expected_third_load_state_;
3974 const Callback callback_;
3976 DISALLOW_COPY_AND_ASSIGN(AsyncDelegateLogger);
3979 // NetworkDelegate that logs delegate information before a request is started,
3980 // before headers are sent, when headers are read, and when auth information
3981 // is requested. Uses AsyncDelegateLogger.
3982 class AsyncLoggingNetworkDelegate : public TestNetworkDelegate {
3983 public:
3984 AsyncLoggingNetworkDelegate() {}
3985 virtual ~AsyncLoggingNetworkDelegate() {}
3987 // NetworkDelegate implementation.
3988 virtual int OnBeforeURLRequest(URLRequest* request,
3989 const CompletionCallback& callback,
3990 GURL* new_url) OVERRIDE {
3991 TestNetworkDelegate::OnBeforeURLRequest(request, callback, new_url);
3992 return RunCallbackAsynchronously(request, callback);
3995 virtual int OnBeforeSendHeaders(URLRequest* request,
3996 const CompletionCallback& callback,
3997 HttpRequestHeaders* headers) OVERRIDE {
3998 TestNetworkDelegate::OnBeforeSendHeaders(request, callback, headers);
3999 return RunCallbackAsynchronously(request, callback);
4002 virtual int OnHeadersReceived(
4003 URLRequest* request,
4004 const CompletionCallback& callback,
4005 const HttpResponseHeaders* original_response_headers,
4006 scoped_refptr<HttpResponseHeaders>* override_response_headers,
4007 GURL* allowed_unsafe_redirect_url) OVERRIDE {
4008 TestNetworkDelegate::OnHeadersReceived(request,
4009 callback,
4010 original_response_headers,
4011 override_response_headers,
4012 allowed_unsafe_redirect_url);
4013 return RunCallbackAsynchronously(request, callback);
4016 virtual NetworkDelegate::AuthRequiredResponse OnAuthRequired(
4017 URLRequest* request,
4018 const AuthChallengeInfo& auth_info,
4019 const AuthCallback& callback,
4020 AuthCredentials* credentials) OVERRIDE {
4021 AsyncDelegateLogger::Run(
4022 request,
4023 LOAD_STATE_WAITING_FOR_DELEGATE,
4024 LOAD_STATE_WAITING_FOR_DELEGATE,
4025 LOAD_STATE_WAITING_FOR_DELEGATE,
4026 base::Bind(&AsyncLoggingNetworkDelegate::SetAuthAndResume,
4027 callback, credentials));
4028 return AUTH_REQUIRED_RESPONSE_IO_PENDING;
4031 private:
4032 static int RunCallbackAsynchronously(
4033 URLRequest* request,
4034 const CompletionCallback& callback) {
4035 AsyncDelegateLogger::Run(
4036 request,
4037 LOAD_STATE_WAITING_FOR_DELEGATE,
4038 LOAD_STATE_WAITING_FOR_DELEGATE,
4039 LOAD_STATE_WAITING_FOR_DELEGATE,
4040 base::Bind(callback, OK));
4041 return ERR_IO_PENDING;
4044 static void SetAuthAndResume(const AuthCallback& callback,
4045 AuthCredentials* credentials) {
4046 *credentials = AuthCredentials(kUser, kSecret);
4047 callback.Run(NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
4050 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingNetworkDelegate);
4053 // URLRequest::Delegate that logs delegate information when the headers
4054 // are received, when each read completes, and during redirects. Uses
4055 // AsyncDelegateLogger. Can optionally cancel a request in any phase.
4057 // Inherits from TestDelegate to reuse the TestDelegate code to handle
4058 // advancing to the next step in most cases, as well as cancellation.
4059 class AsyncLoggingUrlRequestDelegate : public TestDelegate {
4060 public:
4061 enum CancelStage {
4062 NO_CANCEL = 0,
4063 CANCEL_ON_RECEIVED_REDIRECT,
4064 CANCEL_ON_RESPONSE_STARTED,
4065 CANCEL_ON_READ_COMPLETED
4068 explicit AsyncLoggingUrlRequestDelegate(CancelStage cancel_stage)
4069 : cancel_stage_(cancel_stage) {
4070 if (cancel_stage == CANCEL_ON_RECEIVED_REDIRECT)
4071 set_cancel_in_received_redirect(true);
4072 else if (cancel_stage == CANCEL_ON_RESPONSE_STARTED)
4073 set_cancel_in_response_started(true);
4074 else if (cancel_stage == CANCEL_ON_READ_COMPLETED)
4075 set_cancel_in_received_data(true);
4077 virtual ~AsyncLoggingUrlRequestDelegate() {}
4079 // URLRequest::Delegate implementation:
4080 void virtual OnReceivedRedirect(URLRequest* request,
4081 const GURL& new_url,
4082 bool* defer_redirect) OVERRIDE {
4083 *defer_redirect = true;
4084 AsyncDelegateLogger::Run(
4085 request,
4086 LOAD_STATE_WAITING_FOR_DELEGATE,
4087 LOAD_STATE_WAITING_FOR_DELEGATE,
4088 LOAD_STATE_WAITING_FOR_DELEGATE,
4089 base::Bind(
4090 &AsyncLoggingUrlRequestDelegate::OnReceivedRedirectLoggingComplete,
4091 base::Unretained(this), request, new_url));
4094 virtual void OnResponseStarted(URLRequest* request) OVERRIDE {
4095 AsyncDelegateLogger::Run(
4096 request,
4097 LOAD_STATE_WAITING_FOR_DELEGATE,
4098 LOAD_STATE_WAITING_FOR_DELEGATE,
4099 LOAD_STATE_WAITING_FOR_DELEGATE,
4100 base::Bind(
4101 &AsyncLoggingUrlRequestDelegate::OnResponseStartedLoggingComplete,
4102 base::Unretained(this), request));
4105 virtual void OnReadCompleted(URLRequest* request,
4106 int bytes_read) OVERRIDE {
4107 AsyncDelegateLogger::Run(
4108 request,
4109 LOAD_STATE_IDLE,
4110 LOAD_STATE_IDLE,
4111 LOAD_STATE_IDLE,
4112 base::Bind(
4113 &AsyncLoggingUrlRequestDelegate::AfterReadCompletedLoggingComplete,
4114 base::Unretained(this), request, bytes_read));
4117 private:
4118 void OnReceivedRedirectLoggingComplete(URLRequest* request,
4119 const GURL& new_url) {
4120 bool defer_redirect = false;
4121 TestDelegate::OnReceivedRedirect(request, new_url, &defer_redirect);
4122 // FollowDeferredRedirect should not be called after cancellation.
4123 if (cancel_stage_ == CANCEL_ON_RECEIVED_REDIRECT)
4124 return;
4125 if (!defer_redirect)
4126 request->FollowDeferredRedirect();
4129 void OnResponseStartedLoggingComplete(URLRequest* request) {
4130 // The parent class continues the request.
4131 TestDelegate::OnResponseStarted(request);
4134 void AfterReadCompletedLoggingComplete(URLRequest* request, int bytes_read) {
4135 // The parent class continues the request.
4136 TestDelegate::OnReadCompleted(request, bytes_read);
4139 const CancelStage cancel_stage_;
4141 DISALLOW_COPY_AND_ASSIGN(AsyncLoggingUrlRequestDelegate);
4144 // Tests handling of delegate info before a request starts.
4145 TEST_F(URLRequestTestHTTP, DelegateInfoBeforeStart) {
4146 ASSERT_TRUE(test_server_.Start());
4148 TestDelegate request_delegate;
4149 TestURLRequestContext context(true);
4150 context.set_network_delegate(NULL);
4151 context.set_net_log(&net_log_);
4152 context.Init();
4155 URLRequest r(test_server_.GetURL("empty.html"),
4156 DEFAULT_PRIORITY,
4157 &request_delegate,
4158 &context);
4159 LoadStateWithParam load_state = r.GetLoadState();
4160 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
4161 EXPECT_EQ(base::string16(), load_state.param);
4163 AsyncDelegateLogger::Run(
4165 LOAD_STATE_WAITING_FOR_DELEGATE,
4166 LOAD_STATE_WAITING_FOR_DELEGATE,
4167 LOAD_STATE_IDLE,
4168 base::Bind(&URLRequest::Start, base::Unretained(&r)));
4170 base::RunLoop().Run();
4172 EXPECT_EQ(200, r.GetResponseCode());
4173 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
4176 CapturingNetLog::CapturedEntryList entries;
4177 net_log_.GetEntries(&entries);
4178 size_t log_position = ExpectLogContainsSomewhereAfter(
4179 entries,
4181 NetLog::TYPE_DELEGATE_INFO,
4182 NetLog::PHASE_BEGIN);
4184 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries, log_position);
4186 // Nothing else should add any delegate info to the request.
4187 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4188 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4191 // Tests handling of delegate info from a network delegate.
4192 TEST_F(URLRequestTestHTTP, NetworkDelegateInfo) {
4193 ASSERT_TRUE(test_server_.Start());
4195 TestDelegate request_delegate;
4196 AsyncLoggingNetworkDelegate network_delegate;
4197 TestURLRequestContext context(true);
4198 context.set_network_delegate(&network_delegate);
4199 context.set_net_log(&net_log_);
4200 context.Init();
4203 URLRequest r(test_server_.GetURL("simple.html"),
4204 DEFAULT_PRIORITY,
4205 &request_delegate,
4206 &context);
4207 LoadStateWithParam load_state = r.GetLoadState();
4208 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
4209 EXPECT_EQ(base::string16(), load_state.param);
4211 r.Start();
4212 base::RunLoop().Run();
4214 EXPECT_EQ(200, r.GetResponseCode());
4215 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
4216 EXPECT_EQ(1, network_delegate.created_requests());
4217 EXPECT_EQ(0, network_delegate.destroyed_requests());
4219 EXPECT_EQ(1, network_delegate.destroyed_requests());
4221 size_t log_position = 0;
4222 CapturingNetLog::CapturedEntryList entries;
4223 net_log_.GetEntries(&entries);
4224 for (size_t i = 0; i < 3; ++i) {
4225 log_position = ExpectLogContainsSomewhereAfter(
4226 entries,
4227 log_position + 1,
4228 NetLog::TYPE_URL_REQUEST_DELEGATE,
4229 NetLog::PHASE_BEGIN);
4231 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4232 log_position + 1);
4234 ASSERT_LT(log_position, entries.size());
4235 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4236 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4238 if (i == 1) {
4239 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4240 entries, log_position + 1);
4244 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4245 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4248 // Tests handling of delegate info from a network delegate in the case of an
4249 // HTTP redirect.
4250 TEST_F(URLRequestTestHTTP, NetworkDelegateInfoRedirect) {
4251 ASSERT_TRUE(test_server_.Start());
4253 TestDelegate request_delegate;
4254 AsyncLoggingNetworkDelegate network_delegate;
4255 TestURLRequestContext context(true);
4256 context.set_network_delegate(&network_delegate);
4257 context.set_net_log(&net_log_);
4258 context.Init();
4261 URLRequest r(test_server_.GetURL("server-redirect?simple.html"),
4262 DEFAULT_PRIORITY,
4263 &request_delegate,
4264 &context);
4265 LoadStateWithParam load_state = r.GetLoadState();
4266 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
4267 EXPECT_EQ(base::string16(), load_state.param);
4269 r.Start();
4270 base::RunLoop().Run();
4272 EXPECT_EQ(200, r.GetResponseCode());
4273 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
4274 EXPECT_EQ(2, network_delegate.created_requests());
4275 EXPECT_EQ(0, network_delegate.destroyed_requests());
4277 EXPECT_EQ(1, network_delegate.destroyed_requests());
4279 size_t log_position = 0;
4280 CapturingNetLog::CapturedEntryList entries;
4281 net_log_.GetEntries(&entries);
4282 // The NetworkDelegate logged information in OnBeforeURLRequest,
4283 // OnBeforeSendHeaders, and OnHeadersReceived.
4284 for (size_t i = 0; i < 3; ++i) {
4285 log_position = ExpectLogContainsSomewhereAfter(
4286 entries,
4287 log_position + 1,
4288 NetLog::TYPE_URL_REQUEST_DELEGATE,
4289 NetLog::PHASE_BEGIN);
4291 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4292 log_position + 1);
4294 ASSERT_LT(log_position, entries.size());
4295 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4296 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4298 if (i == 1) {
4299 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4300 entries, log_position + 1);
4304 // The URLRequest::Delegate then gets informed about the redirect.
4305 log_position = ExpectLogContainsSomewhereAfter(
4306 entries,
4307 log_position + 1,
4308 NetLog::TYPE_URL_REQUEST_DELEGATE,
4309 NetLog::PHASE_BEGIN);
4311 // The NetworkDelegate logged information in the same three events as before.
4312 for (size_t i = 0; i < 3; ++i) {
4313 log_position = ExpectLogContainsSomewhereAfter(
4314 entries,
4315 log_position + 1,
4316 NetLog::TYPE_URL_REQUEST_DELEGATE,
4317 NetLog::PHASE_BEGIN);
4319 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4320 log_position + 1);
4322 ASSERT_LT(log_position, entries.size());
4323 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4324 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4327 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4328 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4331 // Tests handling of delegate info from a network delegate in the case of HTTP
4332 // AUTH.
4333 TEST_F(URLRequestTestHTTP, NetworkDelegateInfoAuth) {
4334 ASSERT_TRUE(test_server_.Start());
4336 TestDelegate request_delegate;
4337 AsyncLoggingNetworkDelegate network_delegate;
4338 TestURLRequestContext context(true);
4339 context.set_network_delegate(&network_delegate);
4340 context.set_net_log(&net_log_);
4341 context.Init();
4344 URLRequest r(test_server_.GetURL("auth-basic"),
4345 DEFAULT_PRIORITY,
4346 &request_delegate,
4347 &context);
4348 LoadStateWithParam load_state = r.GetLoadState();
4349 EXPECT_EQ(LOAD_STATE_IDLE, load_state.state);
4350 EXPECT_EQ(base::string16(), load_state.param);
4352 r.Start();
4353 base::RunLoop().Run();
4355 EXPECT_EQ(200, r.GetResponseCode());
4356 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
4357 EXPECT_EQ(1, network_delegate.created_requests());
4358 EXPECT_EQ(0, network_delegate.destroyed_requests());
4360 EXPECT_EQ(1, network_delegate.destroyed_requests());
4362 size_t log_position = 0;
4363 CapturingNetLog::CapturedEntryList entries;
4364 net_log_.GetEntries(&entries);
4365 // The NetworkDelegate should have logged information in OnBeforeURLRequest,
4366 // OnBeforeSendHeaders, OnHeadersReceived, OnAuthRequired, and then again in
4367 // OnBeforeURLRequest and OnBeforeSendHeaders.
4368 for (size_t i = 0; i < 6; ++i) {
4369 log_position = ExpectLogContainsSomewhereAfter(
4370 entries,
4371 log_position + 1,
4372 NetLog::TYPE_URL_REQUEST_DELEGATE,
4373 NetLog::PHASE_BEGIN);
4375 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4376 log_position + 1);
4378 ASSERT_LT(log_position, entries.size());
4379 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4380 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4382 if (i == 1) {
4383 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4384 entries, log_position + 1);
4388 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4389 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4392 // Tests handling of delegate info from a URLRequest::Delegate.
4393 TEST_F(URLRequestTestHTTP, URLRequestDelegateInfo) {
4394 ASSERT_TRUE(test_server_.Start());
4396 AsyncLoggingUrlRequestDelegate request_delegate(
4397 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
4398 TestURLRequestContext context(true);
4399 context.set_network_delegate(NULL);
4400 context.set_net_log(&net_log_);
4401 context.Init();
4404 // A chunked response with delays between chunks is used to make sure that
4405 // attempts by the URLRequest delegate to log information while reading the
4406 // body are ignored. Since they are ignored, this test is robust against
4407 // the possibility of multiple reads being combined in the unlikely event
4408 // that it occurs.
4409 URLRequest r(test_server_.GetURL("chunked?waitBetweenChunks=20"),
4410 DEFAULT_PRIORITY,
4411 &request_delegate,
4412 &context);
4413 LoadStateWithParam load_state = r.GetLoadState();
4414 r.Start();
4415 base::RunLoop().Run();
4417 EXPECT_EQ(200, r.GetResponseCode());
4418 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
4421 CapturingNetLog::CapturedEntryList entries;
4422 net_log_.GetEntries(&entries);
4424 size_t log_position = 0;
4426 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4427 entries, log_position);
4429 // The delegate info should only have been logged on header complete. Other
4430 // times it should silently be ignored.
4431 log_position =
4432 ExpectLogContainsSomewhereAfter(entries,
4433 log_position + 1,
4434 NetLog::TYPE_URL_REQUEST_DELEGATE,
4435 NetLog::PHASE_BEGIN);
4437 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4438 log_position + 1);
4440 ASSERT_LT(log_position, entries.size());
4441 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4442 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4444 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4445 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4446 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4447 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
4450 // Tests handling of delegate info from a URLRequest::Delegate in the case of
4451 // an HTTP redirect.
4452 TEST_F(URLRequestTestHTTP, URLRequestDelegateInfoOnRedirect) {
4453 ASSERT_TRUE(test_server_.Start());
4455 AsyncLoggingUrlRequestDelegate request_delegate(
4456 AsyncLoggingUrlRequestDelegate::NO_CANCEL);
4457 TestURLRequestContext context(true);
4458 context.set_network_delegate(NULL);
4459 context.set_net_log(&net_log_);
4460 context.Init();
4463 URLRequest r(test_server_.GetURL("server-redirect?simple.html"),
4464 DEFAULT_PRIORITY,
4465 &request_delegate,
4466 &context);
4467 LoadStateWithParam load_state = r.GetLoadState();
4468 r.Start();
4469 base::RunLoop().Run();
4471 EXPECT_EQ(200, r.GetResponseCode());
4472 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
4475 CapturingNetLog::CapturedEntryList entries;
4476 net_log_.GetEntries(&entries);
4478 // Delegate info should only have been logged in OnReceivedRedirect and
4479 // OnResponseStarted.
4480 size_t log_position = 0;
4481 for (int i = 0; i < 2; ++i) {
4482 if (i == 0) {
4483 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4484 entries, log_position) + 1;
4487 log_position = ExpectLogContainsSomewhereAfter(
4488 entries,
4489 log_position,
4490 NetLog::TYPE_URL_REQUEST_DELEGATE,
4491 NetLog::PHASE_BEGIN);
4493 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4494 log_position + 1);
4496 ASSERT_LT(log_position, entries.size());
4497 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4498 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4501 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4502 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4503 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4504 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
4507 // Tests handling of delegate info from a URLRequest::Delegate in the case of
4508 // an HTTP redirect, with cancellation at various points.
4509 TEST_F(URLRequestTestHTTP, URLRequestDelegateOnRedirectCancelled) {
4510 ASSERT_TRUE(test_server_.Start());
4512 const AsyncLoggingUrlRequestDelegate::CancelStage kCancelStages[] = {
4513 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RECEIVED_REDIRECT,
4514 AsyncLoggingUrlRequestDelegate::CANCEL_ON_RESPONSE_STARTED,
4515 AsyncLoggingUrlRequestDelegate::CANCEL_ON_READ_COMPLETED,
4518 for (size_t test_case = 0; test_case < arraysize(kCancelStages);
4519 ++test_case) {
4520 AsyncLoggingUrlRequestDelegate request_delegate(kCancelStages[test_case]);
4521 TestURLRequestContext context(true);
4522 CapturingNetLog net_log;
4523 context.set_network_delegate(NULL);
4524 context.set_net_log(&net_log);
4525 context.Init();
4528 URLRequest r(test_server_.GetURL("server-redirect?simple.html"),
4529 DEFAULT_PRIORITY,
4530 &request_delegate,
4531 &context);
4532 LoadStateWithParam load_state = r.GetLoadState();
4533 r.Start();
4534 base::RunLoop().Run();
4535 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
4538 CapturingNetLog::CapturedEntryList entries;
4539 net_log.GetEntries(&entries);
4541 // Delegate info is always logged in both OnReceivedRedirect and
4542 // OnResponseStarted. In the CANCEL_ON_RECEIVED_REDIRECT, the
4543 // OnResponseStarted delegate call is after cancellation, but logging is
4544 // still currently supported in that call.
4545 size_t log_position = 0;
4546 for (int i = 0; i < 2; ++i) {
4547 if (i == 0) {
4548 log_position = AsyncDelegateLogger::ExpectBeforeNetworkEvents(
4549 entries, log_position) + 1;
4552 log_position = ExpectLogContainsSomewhereAfter(
4553 entries,
4554 log_position,
4555 NetLog::TYPE_URL_REQUEST_DELEGATE,
4556 NetLog::PHASE_BEGIN);
4558 log_position = AsyncDelegateLogger::CheckDelegateInfo(entries,
4559 log_position + 1);
4561 ASSERT_LT(log_position, entries.size());
4562 EXPECT_EQ(NetLog::TYPE_URL_REQUEST_DELEGATE, entries[log_position].type);
4563 EXPECT_EQ(NetLog::PHASE_END, entries[log_position].phase);
4566 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4567 entries, log_position + 1, NetLog::TYPE_DELEGATE_INFO));
4568 EXPECT_FALSE(LogContainsEntryWithTypeAfter(
4569 entries, log_position + 1, NetLog::TYPE_URL_REQUEST_DELEGATE));
4573 namespace {
4575 const char kExtraHeader[] = "Allow-Snafu";
4576 const char kExtraValue[] = "fubar";
4578 class RedirectWithAdditionalHeadersDelegate : public TestDelegate {
4579 virtual void OnReceivedRedirect(net::URLRequest* request,
4580 const GURL& new_url,
4581 bool* defer_redirect) OVERRIDE {
4582 TestDelegate::OnReceivedRedirect(request, new_url, defer_redirect);
4583 request->SetExtraRequestHeaderByName(kExtraHeader, kExtraValue, false);
4587 } // namespace
4589 TEST_F(URLRequestTestHTTP, RedirectWithAdditionalHeadersTest) {
4590 ASSERT_TRUE(test_server_.Start());
4592 GURL destination_url = test_server_.GetURL(
4593 "echoheader?" + std::string(kExtraHeader));
4594 GURL original_url = test_server_.GetURL(
4595 "server-redirect?" + destination_url.spec());
4596 RedirectWithAdditionalHeadersDelegate d;
4597 URLRequest req(original_url, DEFAULT_PRIORITY, &d, &default_context_);
4598 req.Start();
4599 base::RunLoop().Run();
4601 std::string value;
4602 const HttpRequestHeaders& headers = req.extra_request_headers();
4603 EXPECT_TRUE(headers.GetHeader(kExtraHeader, &value));
4604 EXPECT_EQ(kExtraValue, value);
4605 EXPECT_FALSE(req.is_pending());
4606 EXPECT_FALSE(req.is_redirecting());
4607 EXPECT_EQ(kExtraValue, d.data_received());
4610 namespace {
4612 const char kExtraHeaderToRemove[] = "To-Be-Removed";
4614 class RedirectWithHeaderRemovalDelegate : public TestDelegate {
4615 virtual void OnReceivedRedirect(net::URLRequest* request,
4616 const GURL& new_url,
4617 bool* defer_redirect) OVERRIDE {
4618 TestDelegate::OnReceivedRedirect(request, new_url, defer_redirect);
4619 request->RemoveRequestHeaderByName(kExtraHeaderToRemove);
4623 } // namespace
4625 TEST_F(URLRequestTestHTTP, RedirectWithHeaderRemovalTest) {
4626 ASSERT_TRUE(test_server_.Start());
4628 GURL destination_url = test_server_.GetURL(
4629 "echoheader?" + std::string(kExtraHeaderToRemove));
4630 GURL original_url = test_server_.GetURL(
4631 "server-redirect?" + destination_url.spec());
4632 RedirectWithHeaderRemovalDelegate d;
4633 URLRequest req(original_url, DEFAULT_PRIORITY, &d, &default_context_);
4634 req.SetExtraRequestHeaderByName(kExtraHeaderToRemove, "dummy", false);
4635 req.Start();
4636 base::RunLoop().Run();
4638 std::string value;
4639 const HttpRequestHeaders& headers = req.extra_request_headers();
4640 EXPECT_FALSE(headers.GetHeader(kExtraHeaderToRemove, &value));
4641 EXPECT_FALSE(req.is_pending());
4642 EXPECT_FALSE(req.is_redirecting());
4643 EXPECT_EQ("None", d.data_received());
4646 TEST_F(URLRequestTestHTTP, CancelTest) {
4647 TestDelegate d;
4649 URLRequest r(GURL("http://www.google.com/"),
4650 DEFAULT_PRIORITY,
4652 &default_context_);
4654 r.Start();
4655 EXPECT_TRUE(r.is_pending());
4657 r.Cancel();
4659 base::RunLoop().Run();
4661 // We expect to receive OnResponseStarted even though the request has been
4662 // cancelled.
4663 EXPECT_EQ(1, d.response_started_count());
4664 EXPECT_EQ(0, d.bytes_received());
4665 EXPECT_FALSE(d.received_data_before_response());
4669 TEST_F(URLRequestTestHTTP, CancelTest2) {
4670 ASSERT_TRUE(test_server_.Start());
4672 TestDelegate d;
4674 URLRequest r(test_server_.GetURL(std::string()),
4675 DEFAULT_PRIORITY,
4677 &default_context_);
4679 d.set_cancel_in_response_started(true);
4681 r.Start();
4682 EXPECT_TRUE(r.is_pending());
4684 base::RunLoop().Run();
4686 EXPECT_EQ(1, d.response_started_count());
4687 EXPECT_EQ(0, d.bytes_received());
4688 EXPECT_FALSE(d.received_data_before_response());
4689 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
4693 TEST_F(URLRequestTestHTTP, CancelTest3) {
4694 ASSERT_TRUE(test_server_.Start());
4696 TestDelegate d;
4698 URLRequest r(test_server_.GetURL(std::string()),
4699 DEFAULT_PRIORITY,
4701 &default_context_);
4703 d.set_cancel_in_received_data(true);
4705 r.Start();
4706 EXPECT_TRUE(r.is_pending());
4708 base::RunLoop().Run();
4710 EXPECT_EQ(1, d.response_started_count());
4711 // There is no guarantee about how much data was received
4712 // before the cancel was issued. It could have been 0 bytes,
4713 // or it could have been all the bytes.
4714 // EXPECT_EQ(0, d.bytes_received());
4715 EXPECT_FALSE(d.received_data_before_response());
4716 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
4720 TEST_F(URLRequestTestHTTP, CancelTest4) {
4721 ASSERT_TRUE(test_server_.Start());
4723 TestDelegate d;
4725 URLRequest r(test_server_.GetURL(std::string()),
4726 DEFAULT_PRIORITY,
4728 &default_context_);
4730 r.Start();
4731 EXPECT_TRUE(r.is_pending());
4733 // The request will be implicitly canceled when it is destroyed. The
4734 // test delegate must not post a quit message when this happens because
4735 // this test doesn't actually have a message loop. The quit message would
4736 // get put on this thread's message queue and the next test would exit
4737 // early, causing problems.
4738 d.set_quit_on_complete(false);
4740 // expect things to just cleanup properly.
4742 // we won't actually get a received reponse here because we've never run the
4743 // message loop
4744 EXPECT_FALSE(d.received_data_before_response());
4745 EXPECT_EQ(0, d.bytes_received());
4748 TEST_F(URLRequestTestHTTP, CancelTest5) {
4749 ASSERT_TRUE(test_server_.Start());
4751 // populate cache
4753 TestDelegate d;
4754 URLRequest r(test_server_.GetURL("cachetime"),
4755 DEFAULT_PRIORITY,
4757 &default_context_);
4758 r.Start();
4759 base::RunLoop().Run();
4760 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
4763 // cancel read from cache (see bug 990242)
4765 TestDelegate d;
4766 URLRequest r(test_server_.GetURL("cachetime"),
4767 DEFAULT_PRIORITY,
4769 &default_context_);
4770 r.Start();
4771 r.Cancel();
4772 base::RunLoop().Run();
4774 EXPECT_EQ(URLRequestStatus::CANCELED, r.status().status());
4775 EXPECT_EQ(1, d.response_started_count());
4776 EXPECT_EQ(0, d.bytes_received());
4777 EXPECT_FALSE(d.received_data_before_response());
4781 TEST_F(URLRequestTestHTTP, PostTest) {
4782 ASSERT_TRUE(test_server_.Start());
4783 HTTPUploadDataOperationTest("POST");
4786 TEST_F(URLRequestTestHTTP, PutTest) {
4787 ASSERT_TRUE(test_server_.Start());
4788 HTTPUploadDataOperationTest("PUT");
4791 TEST_F(URLRequestTestHTTP, PostEmptyTest) {
4792 ASSERT_TRUE(test_server_.Start());
4794 TestDelegate d;
4796 URLRequest r(
4797 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, &default_context_);
4798 r.set_method("POST");
4800 r.Start();
4801 EXPECT_TRUE(r.is_pending());
4803 base::RunLoop().Run();
4805 ASSERT_EQ(1, d.response_started_count())
4806 << "request failed: " << r.status().status()
4807 << ", error: " << r.status().error();
4809 EXPECT_FALSE(d.received_data_before_response());
4810 EXPECT_TRUE(d.data_received().empty());
4814 TEST_F(URLRequestTestHTTP, PostFileTest) {
4815 ASSERT_TRUE(test_server_.Start());
4817 TestDelegate d;
4819 URLRequest r(
4820 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, &default_context_);
4821 r.set_method("POST");
4823 base::FilePath dir;
4824 PathService::Get(base::DIR_EXE, &dir);
4825 base::SetCurrentDirectory(dir);
4827 ScopedVector<UploadElementReader> element_readers;
4829 base::FilePath path;
4830 PathService::Get(base::DIR_SOURCE_ROOT, &path);
4831 path = path.Append(FILE_PATH_LITERAL("net"));
4832 path = path.Append(FILE_PATH_LITERAL("data"));
4833 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
4834 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
4835 element_readers.push_back(
4836 new UploadFileElementReader(base::MessageLoopProxy::current().get(),
4837 path,
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 int64 size = 0;
4850 ASSERT_EQ(true, base::GetFileSize(path, &size));
4851 scoped_ptr<char[]> buf(new char[size]);
4853 ASSERT_EQ(size, base::ReadFile(path, buf.get(), size));
4855 ASSERT_EQ(1, d.response_started_count())
4856 << "request failed: " << r.status().status()
4857 << ", error: " << r.status().error();
4859 EXPECT_FALSE(d.received_data_before_response());
4861 EXPECT_EQ(size, d.bytes_received());
4862 EXPECT_EQ(std::string(&buf[0], size), d.data_received());
4866 TEST_F(URLRequestTestHTTP, PostUnreadableFileTest) {
4867 ASSERT_TRUE(test_server_.Start());
4869 TestDelegate d;
4871 URLRequest r(test_server_.GetURL("echo"), DEFAULT_PRIORITY,
4872 &d, &default_context_);
4873 r.set_method("POST");
4875 ScopedVector<UploadElementReader> element_readers;
4877 element_readers.push_back(new UploadFileElementReader(
4878 base::MessageLoopProxy::current().get(),
4879 base::FilePath(FILE_PATH_LITERAL(
4880 "c:\\path\\to\\non\\existant\\file.randomness.12345")),
4882 kuint64max,
4883 base::Time()));
4884 r.set_upload(make_scoped_ptr(
4885 new UploadDataStream(element_readers.Pass(), 0)));
4887 r.Start();
4888 EXPECT_TRUE(r.is_pending());
4890 base::RunLoop().Run();
4892 EXPECT_TRUE(d.request_failed());
4893 EXPECT_FALSE(d.received_data_before_response());
4894 EXPECT_EQ(0, d.bytes_received());
4895 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
4896 EXPECT_EQ(ERR_FILE_NOT_FOUND, r.status().error());
4900 TEST_F(URLRequestTestHTTP, TestPostChunkedDataBeforeStart) {
4901 ASSERT_TRUE(test_server_.Start());
4903 TestDelegate d;
4905 URLRequest r(
4906 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, &default_context_);
4907 r.EnableChunkedUpload();
4908 r.set_method("POST");
4909 AddChunksToUpload(&r);
4910 r.Start();
4911 EXPECT_TRUE(r.is_pending());
4913 base::RunLoop().Run();
4915 VerifyReceivedDataMatchesChunks(&r, &d);
4919 TEST_F(URLRequestTestHTTP, TestPostChunkedDataJustAfterStart) {
4920 ASSERT_TRUE(test_server_.Start());
4922 TestDelegate d;
4924 URLRequest r(
4925 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, &default_context_);
4926 r.EnableChunkedUpload();
4927 r.set_method("POST");
4928 r.Start();
4929 EXPECT_TRUE(r.is_pending());
4930 AddChunksToUpload(&r);
4931 base::RunLoop().Run();
4933 VerifyReceivedDataMatchesChunks(&r, &d);
4937 TEST_F(URLRequestTestHTTP, TestPostChunkedDataAfterStart) {
4938 ASSERT_TRUE(test_server_.Start());
4940 TestDelegate d;
4942 URLRequest r(
4943 test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, &default_context_);
4944 r.EnableChunkedUpload();
4945 r.set_method("POST");
4946 r.Start();
4947 EXPECT_TRUE(r.is_pending());
4949 base::RunLoop().RunUntilIdle();
4950 AddChunksToUpload(&r);
4951 base::RunLoop().Run();
4953 VerifyReceivedDataMatchesChunks(&r, &d);
4957 TEST_F(URLRequestTestHTTP, ResponseHeadersTest) {
4958 ASSERT_TRUE(test_server_.Start());
4960 TestDelegate d;
4961 URLRequest req(test_server_.GetURL("files/with-headers.html"),
4962 DEFAULT_PRIORITY,
4964 &default_context_);
4965 req.Start();
4966 base::RunLoop().Run();
4968 const HttpResponseHeaders* headers = req.response_headers();
4970 // Simple sanity check that response_info() accesses the same data.
4971 EXPECT_EQ(headers, req.response_info().headers.get());
4973 std::string header;
4974 EXPECT_TRUE(headers->GetNormalizedHeader("cache-control", &header));
4975 EXPECT_EQ("private", header);
4977 header.clear();
4978 EXPECT_TRUE(headers->GetNormalizedHeader("content-type", &header));
4979 EXPECT_EQ("text/html; charset=ISO-8859-1", header);
4981 // The response has two "X-Multiple-Entries" headers.
4982 // This verfies our output has them concatenated together.
4983 header.clear();
4984 EXPECT_TRUE(headers->GetNormalizedHeader("x-multiple-entries", &header));
4985 EXPECT_EQ("a, b", header);
4988 TEST_F(URLRequestTestHTTP, ProcessSTS) {
4989 SpawnedTestServer::SSLOptions ssl_options;
4990 SpawnedTestServer https_test_server(
4991 SpawnedTestServer::TYPE_HTTPS,
4992 ssl_options,
4993 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
4994 ASSERT_TRUE(https_test_server.Start());
4996 TestDelegate d;
4997 URLRequest request(https_test_server.GetURL("files/hsts-headers.html"),
4998 DEFAULT_PRIORITY,
5000 &default_context_);
5001 request.Start();
5002 base::RunLoop().Run();
5004 TransportSecurityState* security_state =
5005 default_context_.transport_security_state();
5006 TransportSecurityState::DomainState domain_state;
5007 EXPECT_TRUE(security_state->GetDynamicDomainState(
5008 SpawnedTestServer::kLocalhost, &domain_state));
5009 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
5010 domain_state.sts.upgrade_mode);
5011 EXPECT_TRUE(domain_state.sts.include_subdomains);
5012 EXPECT_FALSE(domain_state.pkp.include_subdomains);
5013 #if defined(OS_ANDROID)
5014 // Android's CertVerifyProc does not (yet) handle pins.
5015 #else
5016 EXPECT_FALSE(domain_state.HasPublicKeyPins());
5017 #endif
5020 // Android's CertVerifyProc does not (yet) handle pins. Therefore, it will
5021 // reject HPKP headers, and a test setting only HPKP headers will fail (no
5022 // DomainState present because header rejected).
5023 #if defined(OS_ANDROID)
5024 #define MAYBE_ProcessPKP DISABLED_ProcessPKP
5025 #else
5026 #define MAYBE_ProcessPKP ProcessPKP
5027 #endif
5029 // Tests that enabling HPKP on a domain does not affect the HSTS
5030 // validity/expiration.
5031 TEST_F(URLRequestTestHTTP, MAYBE_ProcessPKP) {
5032 SpawnedTestServer::SSLOptions ssl_options;
5033 SpawnedTestServer https_test_server(
5034 SpawnedTestServer::TYPE_HTTPS,
5035 ssl_options,
5036 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5037 ASSERT_TRUE(https_test_server.Start());
5039 TestDelegate d;
5040 URLRequest request(https_test_server.GetURL("files/hpkp-headers.html"),
5041 DEFAULT_PRIORITY,
5043 &default_context_);
5044 request.Start();
5045 base::RunLoop().Run();
5047 TransportSecurityState* security_state =
5048 default_context_.transport_security_state();
5049 TransportSecurityState::DomainState domain_state;
5050 EXPECT_TRUE(security_state->GetDynamicDomainState(
5051 SpawnedTestServer::kLocalhost, &domain_state));
5052 EXPECT_EQ(TransportSecurityState::DomainState::MODE_DEFAULT,
5053 domain_state.sts.upgrade_mode);
5054 EXPECT_FALSE(domain_state.sts.include_subdomains);
5055 EXPECT_FALSE(domain_state.pkp.include_subdomains);
5056 EXPECT_TRUE(domain_state.HasPublicKeyPins());
5057 EXPECT_NE(domain_state.sts.expiry, domain_state.pkp.expiry);
5060 TEST_F(URLRequestTestHTTP, ProcessSTSOnce) {
5061 SpawnedTestServer::SSLOptions ssl_options;
5062 SpawnedTestServer https_test_server(
5063 SpawnedTestServer::TYPE_HTTPS,
5064 ssl_options,
5065 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5066 ASSERT_TRUE(https_test_server.Start());
5068 TestDelegate d;
5069 URLRequest request(
5070 https_test_server.GetURL("files/hsts-multiple-headers.html"),
5071 DEFAULT_PRIORITY,
5073 &default_context_);
5074 request.Start();
5075 base::RunLoop().Run();
5077 // We should have set parameters from the first header, not the second.
5078 TransportSecurityState* security_state =
5079 default_context_.transport_security_state();
5080 TransportSecurityState::DomainState domain_state;
5081 EXPECT_TRUE(security_state->GetDynamicDomainState(
5082 SpawnedTestServer::kLocalhost, &domain_state));
5083 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
5084 domain_state.sts.upgrade_mode);
5085 EXPECT_FALSE(domain_state.sts.include_subdomains);
5086 EXPECT_FALSE(domain_state.pkp.include_subdomains);
5089 TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP) {
5090 SpawnedTestServer::SSLOptions ssl_options;
5091 SpawnedTestServer https_test_server(
5092 SpawnedTestServer::TYPE_HTTPS,
5093 ssl_options,
5094 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5095 ASSERT_TRUE(https_test_server.Start());
5097 TestDelegate d;
5098 URLRequest request(
5099 https_test_server.GetURL("files/hsts-and-hpkp-headers.html"),
5100 DEFAULT_PRIORITY,
5102 &default_context_);
5103 request.Start();
5104 base::RunLoop().Run();
5106 // We should have set parameters from the first header, not the second.
5107 TransportSecurityState* security_state =
5108 default_context_.transport_security_state();
5109 TransportSecurityState::DomainState domain_state;
5110 EXPECT_TRUE(security_state->GetDynamicDomainState(
5111 SpawnedTestServer::kLocalhost, &domain_state));
5112 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
5113 domain_state.sts.upgrade_mode);
5114 #if defined(OS_ANDROID)
5115 // Android's CertVerifyProc does not (yet) handle pins.
5116 #else
5117 EXPECT_TRUE(domain_state.HasPublicKeyPins());
5118 #endif
5119 EXPECT_NE(domain_state.sts.expiry, domain_state.pkp.expiry);
5121 // Even though there is an HSTS header asserting includeSubdomains, it is
5122 // the *second* such header, and we MUST process only the first.
5123 EXPECT_FALSE(domain_state.sts.include_subdomains);
5124 // includeSubdomains does not occur in the test HPKP header.
5125 EXPECT_FALSE(domain_state.pkp.include_subdomains);
5128 // Tests that when multiple HPKP headers are present, asserting different
5129 // policies, that only the first such policy is processed.
5130 TEST_F(URLRequestTestHTTP, ProcessSTSAndPKP2) {
5131 SpawnedTestServer::SSLOptions ssl_options;
5132 SpawnedTestServer https_test_server(
5133 SpawnedTestServer::TYPE_HTTPS,
5134 ssl_options,
5135 base::FilePath(FILE_PATH_LITERAL("net/data/url_request_unittest")));
5136 ASSERT_TRUE(https_test_server.Start());
5138 TestDelegate d;
5139 URLRequest request(
5140 https_test_server.GetURL("files/hsts-and-hpkp-headers2.html"),
5141 DEFAULT_PRIORITY,
5143 &default_context_);
5144 request.Start();
5145 base::RunLoop().Run();
5147 TransportSecurityState* security_state =
5148 default_context_.transport_security_state();
5149 TransportSecurityState::DomainState domain_state;
5150 EXPECT_TRUE(security_state->GetDynamicDomainState(
5151 SpawnedTestServer::kLocalhost, &domain_state));
5152 EXPECT_EQ(TransportSecurityState::DomainState::MODE_FORCE_HTTPS,
5153 domain_state.sts.upgrade_mode);
5154 #if defined(OS_ANDROID)
5155 // Android's CertVerifyProc does not (yet) handle pins.
5156 #else
5157 EXPECT_TRUE(domain_state.HasPublicKeyPins());
5158 #endif
5159 EXPECT_NE(domain_state.sts.expiry, domain_state.pkp.expiry);
5161 EXPECT_TRUE(domain_state.sts.include_subdomains);
5162 EXPECT_FALSE(domain_state.pkp.include_subdomains);
5165 TEST_F(URLRequestTestHTTP, ContentTypeNormalizationTest) {
5166 ASSERT_TRUE(test_server_.Start());
5168 TestDelegate d;
5169 URLRequest req(test_server_.GetURL("files/content-type-normalization.html"),
5170 DEFAULT_PRIORITY,
5172 &default_context_);
5173 req.Start();
5174 base::RunLoop().Run();
5176 std::string mime_type;
5177 req.GetMimeType(&mime_type);
5178 EXPECT_EQ("text/html", mime_type);
5180 std::string charset;
5181 req.GetCharset(&charset);
5182 EXPECT_EQ("utf-8", charset);
5183 req.Cancel();
5186 TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictDataRedirects) {
5187 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
5188 GURL data_url("data:,foo");
5189 DataProtocolHandler data_protocol_handler;
5190 EXPECT_FALSE(data_protocol_handler.IsSafeRedirectTarget(data_url));
5192 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
5193 EXPECT_FALSE(job_factory_.IsSafeRedirectTarget(data_url));
5196 #if !defined(DISABLE_FILE_SUPPORT)
5197 TEST_F(URLRequestTestHTTP, ProtocolHandlerAndFactoryRestrictFileRedirects) {
5198 // Test URLRequestJobFactory::ProtocolHandler::IsSafeRedirectTarget().
5199 GURL file_url("file:///foo.txt");
5200 FileProtocolHandler file_protocol_handler(base::MessageLoopProxy::current());
5201 EXPECT_FALSE(file_protocol_handler.IsSafeRedirectTarget(file_url));
5203 // Test URLRequestJobFactoryImpl::IsSafeRedirectTarget().
5204 EXPECT_FALSE(job_factory_.IsSafeRedirectTarget(file_url));
5207 TEST_F(URLRequestTestHTTP, RestrictFileRedirects) {
5208 ASSERT_TRUE(test_server_.Start());
5210 TestDelegate d;
5211 URLRequest req(test_server_.GetURL("files/redirect-to-file.html"),
5212 DEFAULT_PRIORITY,
5214 &default_context_);
5215 req.Start();
5216 base::RunLoop().Run();
5218 EXPECT_EQ(URLRequestStatus::FAILED, req.status().status());
5219 EXPECT_EQ(ERR_UNSAFE_REDIRECT, req.status().error());
5221 #endif // !defined(DISABLE_FILE_SUPPORT)
5223 TEST_F(URLRequestTestHTTP, RestrictDataRedirects) {
5224 ASSERT_TRUE(test_server_.Start());
5226 TestDelegate d;
5227 URLRequest req(test_server_.GetURL("files/redirect-to-data.html"),
5228 DEFAULT_PRIORITY,
5230 &default_context_);
5231 req.Start();
5232 base::MessageLoop::current()->Run();
5234 EXPECT_EQ(URLRequestStatus::FAILED, req.status().status());
5235 EXPECT_EQ(ERR_UNSAFE_REDIRECT, req.status().error());
5238 TEST_F(URLRequestTestHTTP, RedirectToInvalidURL) {
5239 ASSERT_TRUE(test_server_.Start());
5241 TestDelegate d;
5242 URLRequest req(test_server_.GetURL("files/redirect-to-invalid-url.html"),
5243 DEFAULT_PRIORITY,
5245 &default_context_);
5246 req.Start();
5247 base::RunLoop().Run();
5249 EXPECT_EQ(URLRequestStatus::FAILED, req.status().status());
5250 EXPECT_EQ(ERR_INVALID_URL, req.status().error());
5253 // Make sure redirects are cached, despite not reading their bodies.
5254 TEST_F(URLRequestTestHTTP, CacheRedirect) {
5255 ASSERT_TRUE(test_server_.Start());
5256 GURL redirect_url =
5257 test_server_.GetURL("files/redirect302-to-echo-cacheable");
5260 TestDelegate d;
5261 URLRequest req(redirect_url, DEFAULT_PRIORITY, &d, &default_context_);
5262 req.Start();
5263 base::RunLoop().Run();
5264 EXPECT_EQ(URLRequestStatus::SUCCESS, req.status().status());
5265 EXPECT_EQ(1, d.received_redirect_count());
5266 EXPECT_EQ(test_server_.GetURL("echo"), req.url());
5270 TestDelegate d;
5271 d.set_quit_on_redirect(true);
5272 URLRequest req(redirect_url, DEFAULT_PRIORITY, &d, &default_context_);
5273 req.Start();
5274 base::RunLoop().Run();
5276 EXPECT_EQ(1, d.received_redirect_count());
5277 EXPECT_EQ(0, d.response_started_count());
5278 EXPECT_TRUE(req.was_cached());
5280 req.FollowDeferredRedirect();
5281 base::RunLoop().Run();
5282 EXPECT_EQ(1, d.received_redirect_count());
5283 EXPECT_EQ(1, d.response_started_count());
5284 EXPECT_EQ(URLRequestStatus::SUCCESS, req.status().status());
5285 EXPECT_EQ(test_server_.GetURL("echo"), req.url());
5289 // Make sure a request isn't cached when a NetworkDelegate forces a redirect
5290 // when the headers are read, since the body won't have been read.
5291 TEST_F(URLRequestTestHTTP, NoCacheOnNetworkDelegateRedirect) {
5292 ASSERT_TRUE(test_server_.Start());
5293 // URL that is normally cached.
5294 GURL initial_url = test_server_.GetURL("cachetime");
5297 // Set up the TestNetworkDelegate tp force a redirect.
5298 GURL redirect_to_url = test_server_.GetURL("echo");
5299 default_network_delegate_.set_redirect_on_headers_received_url(
5300 redirect_to_url);
5302 TestDelegate d;
5303 URLRequest req(initial_url, DEFAULT_PRIORITY, &d, &default_context_);
5304 req.Start();
5305 base::RunLoop().Run();
5306 EXPECT_EQ(URLRequestStatus::SUCCESS, req.status().status());
5307 EXPECT_EQ(1, d.received_redirect_count());
5308 EXPECT_EQ(redirect_to_url, req.url());
5312 TestDelegate d;
5313 URLRequest req(initial_url, DEFAULT_PRIORITY, &d, &default_context_);
5314 req.Start();
5315 base::RunLoop().Run();
5317 EXPECT_EQ(URLRequestStatus::SUCCESS, req.status().status());
5318 EXPECT_FALSE(req.was_cached());
5319 EXPECT_EQ(0, d.received_redirect_count());
5320 EXPECT_EQ(initial_url, req.url());
5324 // Tests that redirection to an unsafe URL is allowed when it has been marked as
5325 // safe.
5326 TEST_F(URLRequestTestHTTP, UnsafeRedirectToWhitelistedUnsafeURL) {
5327 ASSERT_TRUE(test_server_.Start());
5329 GURL unsafe_url("data:text/html,this-is-considered-an-unsafe-url");
5330 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
5331 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
5333 TestDelegate d;
5335 URLRequest r(test_server_.GetURL("whatever"),
5336 DEFAULT_PRIORITY,
5338 &default_context_);
5340 r.Start();
5341 base::RunLoop().Run();
5343 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
5345 EXPECT_EQ(2U, r.url_chain().size());
5346 EXPECT_EQ(net::OK, r.status().error());
5347 EXPECT_EQ(unsafe_url, r.url());
5348 EXPECT_EQ("this-is-considered-an-unsafe-url", d.data_received());
5352 // Tests that a redirect to a different unsafe URL is blocked, even after adding
5353 // some other URL to the whitelist.
5354 TEST_F(URLRequestTestHTTP, UnsafeRedirectToDifferentUnsafeURL) {
5355 ASSERT_TRUE(test_server_.Start());
5357 GURL unsafe_url("data:text/html,something");
5358 GURL different_unsafe_url("data:text/html,something-else");
5359 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
5360 default_network_delegate_.set_allowed_unsafe_redirect_url(
5361 different_unsafe_url);
5363 TestDelegate d;
5365 URLRequest r(test_server_.GetURL("whatever"),
5366 DEFAULT_PRIORITY,
5368 &default_context_);
5370 r.Start();
5371 base::RunLoop().Run();
5373 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
5374 EXPECT_EQ(ERR_UNSAFE_REDIRECT, r.status().error());
5378 // Redirects from an URL with fragment to an unsafe URL with fragment should
5379 // be allowed, and the reference fragment of the target URL should be preserved.
5380 TEST_F(URLRequestTestHTTP, UnsafeRedirectWithDifferentReferenceFragment) {
5381 ASSERT_TRUE(test_server_.Start());
5383 GURL original_url(test_server_.GetURL("original#fragment1"));
5384 GURL unsafe_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
5385 GURL expected_url("data:,url-marked-safe-and-used-in-redirect#fragment2");
5387 default_network_delegate_.set_redirect_on_headers_received_url(unsafe_url);
5388 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
5390 TestDelegate d;
5392 URLRequest r(original_url, DEFAULT_PRIORITY, &d, &default_context_);
5394 r.Start();
5395 base::RunLoop().Run();
5397 EXPECT_EQ(2U, r.url_chain().size());
5398 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
5399 EXPECT_EQ(net::OK, r.status().error());
5400 EXPECT_EQ(original_url, r.original_url());
5401 EXPECT_EQ(expected_url, r.url());
5405 // When a delegate has specified a safe redirect URL, but it does not match the
5406 // redirect target, then do not prevent the reference fragment from being added.
5407 TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragmentAndUnrelatedUnsafeUrl) {
5408 ASSERT_TRUE(test_server_.Start());
5410 GURL original_url(test_server_.GetURL("original#expected-fragment"));
5411 GURL unsafe_url("data:text/html,this-url-does-not-match-redirect-url");
5412 GURL redirect_url(test_server_.GetURL("target"));
5413 GURL expected_redirect_url(test_server_.GetURL("target#expected-fragment"));
5415 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
5416 default_network_delegate_.set_allowed_unsafe_redirect_url(unsafe_url);
5418 TestDelegate d;
5420 URLRequest r(original_url, DEFAULT_PRIORITY, &d, &default_context_);
5422 r.Start();
5423 base::RunLoop().Run();
5425 EXPECT_EQ(2U, r.url_chain().size());
5426 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
5427 EXPECT_EQ(net::OK, r.status().error());
5428 EXPECT_EQ(original_url, r.original_url());
5429 EXPECT_EQ(expected_redirect_url, r.url());
5433 // When a delegate has specified a safe redirect URL, assume that the redirect
5434 // URL should not be changed. In particular, the reference fragment should not
5435 // be modified.
5436 TEST_F(URLRequestTestHTTP, RedirectWithReferenceFragment) {
5437 ASSERT_TRUE(test_server_.Start());
5439 GURL original_url(test_server_.GetURL("original#should-not-be-appended"));
5440 GURL redirect_url("data:text/html,expect-no-reference-fragment");
5442 default_network_delegate_.set_redirect_on_headers_received_url(redirect_url);
5443 default_network_delegate_.set_allowed_unsafe_redirect_url(redirect_url);
5445 TestDelegate d;
5447 URLRequest r(original_url, DEFAULT_PRIORITY, &d, &default_context_);
5449 r.Start();
5450 base::RunLoop().Run();
5452 EXPECT_EQ(2U, r.url_chain().size());
5453 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
5454 EXPECT_EQ(net::OK, r.status().error());
5455 EXPECT_EQ(original_url, r.original_url());
5456 EXPECT_EQ(redirect_url, r.url());
5460 // When a URLRequestRedirectJob is created, the redirection must be followed and
5461 // the reference fragment of the target URL must not be modified.
5462 TEST_F(URLRequestTestHTTP, RedirectJobWithReferenceFragment) {
5463 ASSERT_TRUE(test_server_.Start());
5465 GURL original_url(test_server_.GetURL("original#should-not-be-appended"));
5466 GURL redirect_url(test_server_.GetURL("echo"));
5468 TestDelegate d;
5469 URLRequest r(original_url, DEFAULT_PRIORITY, &d, &default_context_);
5471 URLRequestRedirectJob* job = new URLRequestRedirectJob(
5472 &r, &default_network_delegate_, redirect_url,
5473 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason");
5474 AddTestInterceptor()->set_main_intercept_job(job);
5476 r.Start();
5477 base::RunLoop().Run();
5479 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
5480 EXPECT_EQ(net::OK, r.status().error());
5481 EXPECT_EQ(original_url, r.original_url());
5482 EXPECT_EQ(redirect_url, r.url());
5485 TEST_F(URLRequestTestHTTP, NoUserPassInReferrer) {
5486 ASSERT_TRUE(test_server_.Start());
5488 TestDelegate d;
5489 URLRequest req(test_server_.GetURL("echoheader?Referer"),
5490 DEFAULT_PRIORITY,
5492 &default_context_);
5493 req.SetReferrer("http://user:pass@foo.com/");
5494 req.Start();
5495 base::RunLoop().Run();
5497 EXPECT_EQ(std::string("http://foo.com/"), d.data_received());
5500 TEST_F(URLRequestTestHTTP, NoFragmentInReferrer) {
5501 ASSERT_TRUE(test_server_.Start());
5503 TestDelegate d;
5504 URLRequest req(test_server_.GetURL("echoheader?Referer"),
5505 DEFAULT_PRIORITY,
5507 &default_context_);
5508 req.SetReferrer("http://foo.com/test#fragment");
5509 req.Start();
5510 base::RunLoop().Run();
5512 EXPECT_EQ(std::string("http://foo.com/test"), d.data_received());
5515 TEST_F(URLRequestTestHTTP, EmptyReferrerAfterValidReferrer) {
5516 ASSERT_TRUE(test_server_.Start());
5518 TestDelegate d;
5519 URLRequest req(test_server_.GetURL("echoheader?Referer"),
5520 DEFAULT_PRIORITY,
5522 &default_context_);
5523 req.SetReferrer("http://foo.com/test#fragment");
5524 req.SetReferrer("");
5525 req.Start();
5526 base::RunLoop().Run();
5528 EXPECT_EQ(std::string("None"), d.data_received());
5531 // Defer network start and then resume, checking that the request was a success
5532 // and bytes were received.
5533 TEST_F(URLRequestTestHTTP, DeferredBeforeNetworkStart) {
5534 ASSERT_TRUE(test_server_.Start());
5536 TestDelegate d;
5538 d.set_quit_on_network_start(true);
5539 GURL test_url(test_server_.GetURL("echo"));
5540 URLRequest req(test_url, DEFAULT_PRIORITY, &d, &default_context_);
5542 req.Start();
5543 base::RunLoop().Run();
5545 EXPECT_EQ(1, d.received_before_network_start_count());
5546 EXPECT_EQ(0, d.response_started_count());
5548 req.ResumeNetworkStart();
5549 base::RunLoop().Run();
5551 EXPECT_EQ(1, d.response_started_count());
5552 EXPECT_NE(0, d.bytes_received());
5553 EXPECT_EQ(URLRequestStatus::SUCCESS, req.status().status());
5557 // Check that OnBeforeNetworkStart is only called once even if there is a
5558 // redirect.
5559 TEST_F(URLRequestTestHTTP, BeforeNetworkStartCalledOnce) {
5560 ASSERT_TRUE(test_server_.Start());
5562 TestDelegate d;
5564 d.set_quit_on_redirect(true);
5565 d.set_quit_on_network_start(true);
5566 URLRequest req(test_server_.GetURL("server-redirect?echo"),
5567 DEFAULT_PRIORITY,
5569 &default_context_);
5571 req.Start();
5572 base::RunLoop().Run();
5574 EXPECT_EQ(1, d.received_before_network_start_count());
5575 EXPECT_EQ(0, d.response_started_count());
5576 EXPECT_EQ(0, d.received_redirect_count());
5578 req.ResumeNetworkStart();
5579 base::RunLoop().Run();
5581 EXPECT_EQ(1, d.received_redirect_count());
5582 req.FollowDeferredRedirect();
5583 base::RunLoop().Run();
5585 // Check that the redirect's new network transaction does not get propagated
5586 // to a second OnBeforeNetworkStart() notification.
5587 EXPECT_EQ(1, d.received_before_network_start_count());
5589 EXPECT_EQ(1, d.response_started_count());
5590 EXPECT_NE(0, d.bytes_received());
5591 EXPECT_EQ(URLRequestStatus::SUCCESS, req.status().status());
5595 // Cancel the request after learning that the request would use the network.
5596 TEST_F(URLRequestTestHTTP, CancelOnBeforeNetworkStart) {
5597 ASSERT_TRUE(test_server_.Start());
5599 TestDelegate d;
5601 d.set_quit_on_network_start(true);
5602 GURL test_url(test_server_.GetURL("echo"));
5603 URLRequest req(test_url, DEFAULT_PRIORITY, &d, &default_context_);
5605 req.Start();
5606 base::RunLoop().Run();
5608 EXPECT_EQ(1, d.received_before_network_start_count());
5609 EXPECT_EQ(0, d.response_started_count());
5611 req.Cancel();
5612 base::RunLoop().Run();
5614 EXPECT_EQ(1, d.response_started_count());
5615 EXPECT_EQ(0, d.bytes_received());
5616 EXPECT_EQ(URLRequestStatus::CANCELED, req.status().status());
5620 TEST_F(URLRequestTestHTTP, CancelRedirect) {
5621 ASSERT_TRUE(test_server_.Start());
5623 TestDelegate d;
5625 d.set_cancel_in_received_redirect(true);
5626 URLRequest req(test_server_.GetURL("files/redirect-test.html"),
5627 DEFAULT_PRIORITY,
5629 &default_context_);
5630 req.Start();
5631 base::RunLoop().Run();
5633 EXPECT_EQ(1, d.response_started_count());
5634 EXPECT_EQ(0, d.bytes_received());
5635 EXPECT_FALSE(d.received_data_before_response());
5636 EXPECT_EQ(URLRequestStatus::CANCELED, req.status().status());
5640 TEST_F(URLRequestTestHTTP, DeferredRedirect) {
5641 ASSERT_TRUE(test_server_.Start());
5643 TestDelegate d;
5645 d.set_quit_on_redirect(true);
5646 GURL test_url(test_server_.GetURL("files/redirect-test.html"));
5647 URLRequest req(test_url, DEFAULT_PRIORITY, &d, &default_context_);
5649 req.Start();
5650 base::RunLoop().Run();
5652 EXPECT_EQ(1, d.received_redirect_count());
5654 req.FollowDeferredRedirect();
5655 base::RunLoop().Run();
5657 EXPECT_EQ(1, d.response_started_count());
5658 EXPECT_FALSE(d.received_data_before_response());
5659 EXPECT_EQ(URLRequestStatus::SUCCESS, req.status().status());
5661 base::FilePath path;
5662 PathService::Get(base::DIR_SOURCE_ROOT, &path);
5663 path = path.Append(FILE_PATH_LITERAL("net"));
5664 path = path.Append(FILE_PATH_LITERAL("data"));
5665 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
5666 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
5668 std::string contents;
5669 EXPECT_TRUE(base::ReadFileToString(path, &contents));
5670 EXPECT_EQ(contents, d.data_received());
5674 TEST_F(URLRequestTestHTTP, DeferredRedirect_GetFullRequestHeaders) {
5675 ASSERT_TRUE(test_server_.Start());
5677 TestDelegate d;
5679 d.set_quit_on_redirect(true);
5680 GURL test_url(test_server_.GetURL("files/redirect-test.html"));
5681 URLRequest req(test_url, DEFAULT_PRIORITY, &d, &default_context_);
5683 EXPECT_FALSE(d.have_full_request_headers());
5685 req.Start();
5686 base::RunLoop().Run();
5688 EXPECT_EQ(1, d.received_redirect_count());
5689 EXPECT_TRUE(d.have_full_request_headers());
5690 CheckFullRequestHeaders(d.full_request_headers(), test_url);
5691 d.ClearFullRequestHeaders();
5693 req.FollowDeferredRedirect();
5694 base::RunLoop().Run();
5696 GURL target_url(test_server_.GetURL("files/with-headers.html"));
5697 EXPECT_EQ(1, d.response_started_count());
5698 EXPECT_TRUE(d.have_full_request_headers());
5699 CheckFullRequestHeaders(d.full_request_headers(), target_url);
5700 EXPECT_FALSE(d.received_data_before_response());
5701 EXPECT_EQ(URLRequestStatus::SUCCESS, req.status().status());
5703 base::FilePath path;
5704 PathService::Get(base::DIR_SOURCE_ROOT, &path);
5705 path = path.Append(FILE_PATH_LITERAL("net"));
5706 path = path.Append(FILE_PATH_LITERAL("data"));
5707 path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
5708 path = path.Append(FILE_PATH_LITERAL("with-headers.html"));
5710 std::string contents;
5711 EXPECT_TRUE(base::ReadFileToString(path, &contents));
5712 EXPECT_EQ(contents, d.data_received());
5716 TEST_F(URLRequestTestHTTP, CancelDeferredRedirect) {
5717 ASSERT_TRUE(test_server_.Start());
5719 TestDelegate d;
5721 d.set_quit_on_redirect(true);
5722 URLRequest req(test_server_.GetURL("files/redirect-test.html"),
5723 DEFAULT_PRIORITY,
5725 &default_context_);
5726 req.Start();
5727 base::RunLoop().Run();
5729 EXPECT_EQ(1, d.received_redirect_count());
5731 req.Cancel();
5732 base::RunLoop().Run();
5734 EXPECT_EQ(1, d.response_started_count());
5735 EXPECT_EQ(0, d.bytes_received());
5736 EXPECT_FALSE(d.received_data_before_response());
5737 EXPECT_EQ(URLRequestStatus::CANCELED, req.status().status());
5741 TEST_F(URLRequestTestHTTP, VaryHeader) {
5742 ASSERT_TRUE(test_server_.Start());
5744 // Populate the cache.
5746 TestDelegate d;
5747 URLRequest req(test_server_.GetURL("echoheadercache?foo"),
5748 DEFAULT_PRIORITY,
5750 &default_context_);
5751 HttpRequestHeaders headers;
5752 headers.SetHeader("foo", "1");
5753 req.SetExtraRequestHeaders(headers);
5754 req.Start();
5755 base::RunLoop().Run();
5757 LoadTimingInfo load_timing_info;
5758 req.GetLoadTimingInfo(&load_timing_info);
5759 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
5762 // Expect a cache hit.
5764 TestDelegate d;
5765 URLRequest req(test_server_.GetURL("echoheadercache?foo"),
5766 DEFAULT_PRIORITY,
5768 &default_context_);
5769 HttpRequestHeaders headers;
5770 headers.SetHeader("foo", "1");
5771 req.SetExtraRequestHeaders(headers);
5772 req.Start();
5773 base::RunLoop().Run();
5775 EXPECT_TRUE(req.was_cached());
5777 LoadTimingInfo load_timing_info;
5778 req.GetLoadTimingInfo(&load_timing_info);
5779 TestLoadTimingCacheHitNoNetwork(load_timing_info);
5782 // Expect a cache miss.
5784 TestDelegate d;
5785 URLRequest req(test_server_.GetURL("echoheadercache?foo"),
5786 DEFAULT_PRIORITY,
5788 &default_context_);
5789 HttpRequestHeaders headers;
5790 headers.SetHeader("foo", "2");
5791 req.SetExtraRequestHeaders(headers);
5792 req.Start();
5793 base::RunLoop().Run();
5795 EXPECT_FALSE(req.was_cached());
5797 LoadTimingInfo load_timing_info;
5798 req.GetLoadTimingInfo(&load_timing_info);
5799 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
5803 TEST_F(URLRequestTestHTTP, BasicAuth) {
5804 ASSERT_TRUE(test_server_.Start());
5806 // populate the cache
5808 TestDelegate d;
5809 d.set_credentials(AuthCredentials(kUser, kSecret));
5811 URLRequest r(test_server_.GetURL("auth-basic"),
5812 DEFAULT_PRIORITY,
5814 &default_context_);
5815 r.Start();
5817 base::RunLoop().Run();
5819 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
5822 // repeat request with end-to-end validation. since auth-basic results in a
5823 // cachable page, we expect this test to result in a 304. in which case, the
5824 // response should be fetched from the cache.
5826 TestDelegate d;
5827 d.set_credentials(AuthCredentials(kUser, kSecret));
5829 URLRequest r(test_server_.GetURL("auth-basic"),
5830 DEFAULT_PRIORITY,
5832 &default_context_);
5833 r.SetLoadFlags(LOAD_VALIDATE_CACHE);
5834 r.Start();
5836 base::RunLoop().Run();
5838 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
5840 // Should be the same cached document.
5841 EXPECT_TRUE(r.was_cached());
5845 // Check that Set-Cookie headers in 401 responses are respected.
5846 // http://crbug.com/6450
5847 TEST_F(URLRequestTestHTTP, BasicAuthWithCookies) {
5848 ASSERT_TRUE(test_server_.Start());
5850 GURL url_requiring_auth =
5851 test_server_.GetURL("auth-basic?set-cookie-if-challenged");
5853 // Request a page that will give a 401 containing a Set-Cookie header.
5854 // Verify that when the transaction is restarted, it includes the new cookie.
5856 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
5857 TestURLRequestContext context(true);
5858 context.set_network_delegate(&network_delegate);
5859 context.Init();
5861 TestDelegate d;
5862 d.set_credentials(AuthCredentials(kUser, kSecret));
5864 URLRequest r(url_requiring_auth, DEFAULT_PRIORITY, &d, &context);
5865 r.Start();
5867 base::RunLoop().Run();
5869 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
5871 // Make sure we sent the cookie in the restarted transaction.
5872 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
5873 != std::string::npos);
5876 // Same test as above, except this time the restart is initiated earlier
5877 // (without user intervention since identity is embedded in the URL).
5879 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
5880 TestURLRequestContext context(true);
5881 context.set_network_delegate(&network_delegate);
5882 context.Init();
5884 TestDelegate d;
5886 GURL::Replacements replacements;
5887 std::string username("user2");
5888 std::string password("secret");
5889 replacements.SetUsernameStr(username);
5890 replacements.SetPasswordStr(password);
5891 GURL url_with_identity = url_requiring_auth.ReplaceComponents(replacements);
5893 URLRequest r(url_with_identity, DEFAULT_PRIORITY, &d, &context);
5894 r.Start();
5896 base::RunLoop().Run();
5898 EXPECT_TRUE(d.data_received().find("user2/secret") != std::string::npos);
5900 // Make sure we sent the cookie in the restarted transaction.
5901 EXPECT_TRUE(d.data_received().find("Cookie: got_challenged=true")
5902 != std::string::npos);
5906 // Tests that load timing works as expected with auth and the cache.
5907 TEST_F(URLRequestTestHTTP, BasicAuthLoadTiming) {
5908 ASSERT_TRUE(test_server_.Start());
5910 // populate the cache
5912 TestDelegate d;
5913 d.set_credentials(AuthCredentials(kUser, kSecret));
5915 URLRequest r(test_server_.GetURL("auth-basic"),
5916 DEFAULT_PRIORITY,
5918 &default_context_);
5919 r.Start();
5921 base::RunLoop().Run();
5923 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
5925 LoadTimingInfo load_timing_info_before_auth;
5926 EXPECT_TRUE(default_network_delegate_.GetLoadTimingInfoBeforeAuth(
5927 &load_timing_info_before_auth));
5928 TestLoadTimingNotReused(load_timing_info_before_auth,
5929 CONNECT_TIMING_HAS_DNS_TIMES);
5931 LoadTimingInfo load_timing_info;
5932 r.GetLoadTimingInfo(&load_timing_info);
5933 // The test server does not support keep alive sockets, so the second
5934 // request with auth should use a new socket.
5935 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
5936 EXPECT_NE(load_timing_info_before_auth.socket_log_id,
5937 load_timing_info.socket_log_id);
5938 EXPECT_LE(load_timing_info_before_auth.receive_headers_end,
5939 load_timing_info.connect_timing.connect_start);
5942 // Repeat request with end-to-end validation. Since auth-basic results in a
5943 // cachable page, we expect this test to result in a 304. In which case, the
5944 // response should be fetched from the cache.
5946 TestDelegate d;
5947 d.set_credentials(AuthCredentials(kUser, kSecret));
5949 URLRequest r(test_server_.GetURL("auth-basic"),
5950 DEFAULT_PRIORITY,
5952 &default_context_);
5953 r.SetLoadFlags(LOAD_VALIDATE_CACHE);
5954 r.Start();
5956 base::RunLoop().Run();
5958 EXPECT_TRUE(d.data_received().find("user/secret") != std::string::npos);
5960 // Should be the same cached document.
5961 EXPECT_TRUE(r.was_cached());
5963 // Since there was a request that went over the wire, the load timing
5964 // information should include connection times.
5965 LoadTimingInfo load_timing_info;
5966 r.GetLoadTimingInfo(&load_timing_info);
5967 TestLoadTimingNotReused(load_timing_info, CONNECT_TIMING_HAS_DNS_TIMES);
5971 // In this test, we do a POST which the server will 302 redirect.
5972 // The subsequent transaction should use GET, and should not send the
5973 // Content-Type header.
5974 // http://code.google.com/p/chromium/issues/detail?id=843
5975 TEST_F(URLRequestTestHTTP, Post302RedirectGet) {
5976 ASSERT_TRUE(test_server_.Start());
5978 const char kData[] = "hello world";
5980 TestDelegate d;
5981 URLRequest req(test_server_.GetURL("files/redirect-to-echoall"),
5982 DEFAULT_PRIORITY,
5984 &default_context_);
5985 req.set_method("POST");
5986 req.set_upload(make_scoped_ptr(CreateSimpleUploadData(kData)));
5988 // Set headers (some of which are specific to the POST).
5989 HttpRequestHeaders headers;
5990 headers.AddHeadersFromString(
5991 "Content-Type: multipart/form-data; "
5992 "boundary=----WebKitFormBoundaryAADeAA+NAAWMAAwZ\r\n"
5993 "Accept: text/xml,application/xml,application/xhtml+xml,text/html;q=0.9,"
5994 "text/plain;q=0.8,image/png,*/*;q=0.5\r\n"
5995 "Accept-Language: en-US,en\r\n"
5996 "Accept-Charset: ISO-8859-1,*,utf-8\r\n"
5997 "Content-Length: 11\r\n"
5998 "Origin: http://localhost:1337/");
5999 req.SetExtraRequestHeaders(headers);
6000 req.Start();
6001 base::RunLoop().Run();
6003 std::string mime_type;
6004 req.GetMimeType(&mime_type);
6005 EXPECT_EQ("text/html", mime_type);
6007 const std::string& data = d.data_received();
6009 // Check that the post-specific headers were stripped:
6010 EXPECT_FALSE(ContainsString(data, "Content-Length:"));
6011 EXPECT_FALSE(ContainsString(data, "Content-Type:"));
6012 EXPECT_FALSE(ContainsString(data, "Origin:"));
6014 // These extra request headers should not have been stripped.
6015 EXPECT_TRUE(ContainsString(data, "Accept:"));
6016 EXPECT_TRUE(ContainsString(data, "Accept-Language:"));
6017 EXPECT_TRUE(ContainsString(data, "Accept-Charset:"));
6020 // The following tests check that we handle mutating the request method for
6021 // HTTP redirects as expected.
6022 // See http://crbug.com/56373 and http://crbug.com/102130.
6024 TEST_F(URLRequestTestHTTP, Redirect301Tests) {
6025 ASSERT_TRUE(test_server_.Start());
6027 const GURL url = test_server_.GetURL("files/redirect301-to-echo");
6029 HTTPRedirectMethodTest(url, "POST", "GET", true);
6030 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6031 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
6034 TEST_F(URLRequestTestHTTP, Redirect302Tests) {
6035 ASSERT_TRUE(test_server_.Start());
6037 const GURL url = test_server_.GetURL("files/redirect302-to-echo");
6039 HTTPRedirectMethodTest(url, "POST", "GET", true);
6040 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6041 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
6044 TEST_F(URLRequestTestHTTP, Redirect303Tests) {
6045 ASSERT_TRUE(test_server_.Start());
6047 const GURL url = test_server_.GetURL("files/redirect303-to-echo");
6049 HTTPRedirectMethodTest(url, "POST", "GET", true);
6050 HTTPRedirectMethodTest(url, "PUT", "GET", true);
6051 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
6054 TEST_F(URLRequestTestHTTP, Redirect307Tests) {
6055 ASSERT_TRUE(test_server_.Start());
6057 const GURL url = test_server_.GetURL("files/redirect307-to-echo");
6059 HTTPRedirectMethodTest(url, "POST", "POST", true);
6060 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6061 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
6064 TEST_F(URLRequestTestHTTP, Redirect308Tests) {
6065 ASSERT_TRUE(test_server_.Start());
6067 const GURL url = test_server_.GetURL("files/redirect308-to-echo");
6069 HTTPRedirectMethodTest(url, "POST", "POST", true);
6070 HTTPRedirectMethodTest(url, "PUT", "PUT", true);
6071 HTTPRedirectMethodTest(url, "HEAD", "HEAD", false);
6074 // Make sure that 308 responses without bodies are not treated as redirects.
6075 // Certain legacy apis that pre-date the response code expect this behavior
6076 // (Like Google Drive).
6077 TEST_F(URLRequestTestHTTP, NoRedirectOn308WithoutLocationHeader) {
6078 ASSERT_TRUE(test_server_.Start());
6080 TestDelegate d;
6081 const GURL url = test_server_.GetURL("files/308-without-location-header");
6083 URLRequest request(url, DEFAULT_PRIORITY, &d, &default_context_);
6085 request.Start();
6086 base::RunLoop().Run();
6087 EXPECT_EQ(URLRequestStatus::SUCCESS, request.status().status());
6088 EXPECT_EQ(OK, request.status().error());
6089 EXPECT_EQ(0, d.received_redirect_count());
6090 EXPECT_EQ(308, request.response_headers()->response_code());
6091 EXPECT_EQ("This is not a redirect.", d.data_received());
6094 TEST_F(URLRequestTestHTTP, Redirect302PreserveReferenceFragment) {
6095 ASSERT_TRUE(test_server_.Start());
6097 GURL original_url(test_server_.GetURL("files/redirect302-to-echo#fragment"));
6098 GURL expected_url(test_server_.GetURL("echo#fragment"));
6100 TestDelegate d;
6102 URLRequest r(original_url, DEFAULT_PRIORITY, &d, &default_context_);
6104 r.Start();
6105 base::RunLoop().Run();
6107 EXPECT_EQ(2U, r.url_chain().size());
6108 EXPECT_EQ(URLRequestStatus::SUCCESS, r.status().status());
6109 EXPECT_EQ(net::OK, r.status().error());
6110 EXPECT_EQ(original_url, r.original_url());
6111 EXPECT_EQ(expected_url, r.url());
6115 TEST_F(URLRequestTestHTTP, InterceptPost302RedirectGet) {
6116 ASSERT_TRUE(test_server_.Start());
6118 const char kData[] = "hello world";
6120 TestDelegate d;
6121 URLRequest req(test_server_.GetURL("empty.html"),
6122 DEFAULT_PRIORITY,
6124 &default_context_);
6125 req.set_method("POST");
6126 req.set_upload(make_scoped_ptr(CreateSimpleUploadData(kData)));
6127 HttpRequestHeaders headers;
6128 headers.SetHeader(HttpRequestHeaders::kContentLength,
6129 base::UintToString(arraysize(kData) - 1));
6130 req.SetExtraRequestHeaders(headers);
6132 URLRequestRedirectJob* job = new URLRequestRedirectJob(
6133 &req, &default_network_delegate_, test_server_.GetURL("echo"),
6134 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason");
6135 AddTestInterceptor()->set_main_intercept_job(job);
6137 req.Start();
6138 base::RunLoop().Run();
6139 EXPECT_EQ("GET", req.method());
6142 TEST_F(URLRequestTestHTTP, InterceptPost307RedirectPost) {
6143 ASSERT_TRUE(test_server_.Start());
6145 const char kData[] = "hello world";
6147 TestDelegate d;
6148 URLRequest req(test_server_.GetURL("empty.html"),
6149 DEFAULT_PRIORITY,
6151 &default_context_);
6152 req.set_method("POST");
6153 req.set_upload(make_scoped_ptr(CreateSimpleUploadData(kData)));
6154 HttpRequestHeaders headers;
6155 headers.SetHeader(HttpRequestHeaders::kContentLength,
6156 base::UintToString(arraysize(kData) - 1));
6157 req.SetExtraRequestHeaders(headers);
6159 URLRequestRedirectJob* job = new URLRequestRedirectJob(
6160 &req, &default_network_delegate_, test_server_.GetURL("echo"),
6161 URLRequestRedirectJob::REDIRECT_307_TEMPORARY_REDIRECT,
6162 "Very Good Reason");
6163 AddTestInterceptor()->set_main_intercept_job(job);
6165 req.Start();
6166 base::RunLoop().Run();
6167 EXPECT_EQ("POST", req.method());
6168 EXPECT_EQ(kData, d.data_received());
6171 // Check that default A-L header is sent.
6172 TEST_F(URLRequestTestHTTP, DefaultAcceptLanguage) {
6173 ASSERT_TRUE(test_server_.Start());
6175 StaticHttpUserAgentSettings settings("en", std::string());
6176 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
6177 TestURLRequestContext context(true);
6178 context.set_network_delegate(&network_delegate);
6179 context.set_http_user_agent_settings(&settings);
6180 context.Init();
6182 TestDelegate d;
6183 URLRequest req(test_server_.GetURL("echoheader?Accept-Language"),
6184 DEFAULT_PRIORITY,
6186 &context);
6187 req.Start();
6188 base::RunLoop().Run();
6189 EXPECT_EQ("en", d.data_received());
6192 // Check that an empty A-L header is not sent. http://crbug.com/77365.
6193 TEST_F(URLRequestTestHTTP, EmptyAcceptLanguage) {
6194 ASSERT_TRUE(test_server_.Start());
6196 std::string empty_string; // Avoid most vexing parse on line below.
6197 StaticHttpUserAgentSettings settings(empty_string, empty_string);
6198 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
6199 TestURLRequestContext context(true);
6200 context.set_network_delegate(&network_delegate);
6201 context.Init();
6202 // We override the language after initialization because empty entries
6203 // get overridden by Init().
6204 context.set_http_user_agent_settings(&settings);
6206 TestDelegate d;
6207 URLRequest req(test_server_.GetURL("echoheader?Accept-Language"),
6208 DEFAULT_PRIORITY,
6210 &context);
6211 req.Start();
6212 base::RunLoop().Run();
6213 EXPECT_EQ("None", d.data_received());
6216 // Check that if request overrides the A-L header, the default is not appended.
6217 // See http://crbug.com/20894
6218 TEST_F(URLRequestTestHTTP, OverrideAcceptLanguage) {
6219 ASSERT_TRUE(test_server_.Start());
6221 TestDelegate d;
6222 URLRequest req(test_server_.GetURL("echoheader?Accept-Language"),
6223 DEFAULT_PRIORITY,
6225 &default_context_);
6226 HttpRequestHeaders headers;
6227 headers.SetHeader(HttpRequestHeaders::kAcceptLanguage, "ru");
6228 req.SetExtraRequestHeaders(headers);
6229 req.Start();
6230 base::RunLoop().Run();
6231 EXPECT_EQ(std::string("ru"), d.data_received());
6234 // Check that default A-E header is sent.
6235 TEST_F(URLRequestTestHTTP, DefaultAcceptEncoding) {
6236 ASSERT_TRUE(test_server_.Start());
6238 TestDelegate d;
6239 URLRequest req(test_server_.GetURL("echoheader?Accept-Encoding"),
6240 DEFAULT_PRIORITY,
6242 &default_context_);
6243 HttpRequestHeaders headers;
6244 req.SetExtraRequestHeaders(headers);
6245 req.Start();
6246 base::RunLoop().Run();
6247 EXPECT_TRUE(ContainsString(d.data_received(), "gzip"));
6250 // Check that if request overrides the A-E header, the default is not appended.
6251 // See http://crbug.com/47381
6252 TEST_F(URLRequestTestHTTP, OverrideAcceptEncoding) {
6253 ASSERT_TRUE(test_server_.Start());
6255 TestDelegate d;
6256 URLRequest req(test_server_.GetURL("echoheader?Accept-Encoding"),
6257 DEFAULT_PRIORITY,
6259 &default_context_);
6260 HttpRequestHeaders headers;
6261 headers.SetHeader(HttpRequestHeaders::kAcceptEncoding, "identity");
6262 req.SetExtraRequestHeaders(headers);
6263 req.Start();
6264 base::RunLoop().Run();
6265 EXPECT_FALSE(ContainsString(d.data_received(), "gzip"));
6266 EXPECT_TRUE(ContainsString(d.data_received(), "identity"));
6269 // Check that setting the A-C header sends the proper header.
6270 TEST_F(URLRequestTestHTTP, SetAcceptCharset) {
6271 ASSERT_TRUE(test_server_.Start());
6273 TestDelegate d;
6274 URLRequest req(test_server_.GetURL("echoheader?Accept-Charset"),
6275 DEFAULT_PRIORITY,
6277 &default_context_);
6278 HttpRequestHeaders headers;
6279 headers.SetHeader(HttpRequestHeaders::kAcceptCharset, "koi-8r");
6280 req.SetExtraRequestHeaders(headers);
6281 req.Start();
6282 base::RunLoop().Run();
6283 EXPECT_EQ(std::string("koi-8r"), d.data_received());
6286 // Check that default User-Agent header is sent.
6287 TEST_F(URLRequestTestHTTP, DefaultUserAgent) {
6288 ASSERT_TRUE(test_server_.Start());
6290 TestDelegate d;
6291 URLRequest req(test_server_.GetURL("echoheader?User-Agent"),
6292 DEFAULT_PRIORITY,
6294 &default_context_);
6295 req.Start();
6296 base::RunLoop().Run();
6297 EXPECT_EQ(req.context()->http_user_agent_settings()->GetUserAgent(),
6298 d.data_received());
6301 // Check that if request overrides the User-Agent header,
6302 // the default is not appended.
6303 TEST_F(URLRequestTestHTTP, OverrideUserAgent) {
6304 ASSERT_TRUE(test_server_.Start());
6306 TestDelegate d;
6307 URLRequest req(test_server_.GetURL("echoheader?User-Agent"),
6308 DEFAULT_PRIORITY,
6310 &default_context_);
6311 HttpRequestHeaders headers;
6312 headers.SetHeader(HttpRequestHeaders::kUserAgent, "Lynx (textmode)");
6313 req.SetExtraRequestHeaders(headers);
6314 req.Start();
6315 base::RunLoop().Run();
6316 EXPECT_EQ(std::string("Lynx (textmode)"), d.data_received());
6319 // Check that a NULL HttpUserAgentSettings causes the corresponding empty
6320 // User-Agent header to be sent but does not send the Accept-Language and
6321 // Accept-Charset headers.
6322 TEST_F(URLRequestTestHTTP, EmptyHttpUserAgentSettings) {
6323 ASSERT_TRUE(test_server_.Start());
6325 TestNetworkDelegate network_delegate; // Must outlive URLRequests.
6326 TestURLRequestContext context(true);
6327 context.set_network_delegate(&network_delegate);
6328 context.Init();
6329 // We override the HttpUserAgentSettings after initialization because empty
6330 // entries get overridden by Init().
6331 context.set_http_user_agent_settings(NULL);
6333 struct {
6334 const char* request;
6335 const char* expected_response;
6336 } tests[] = { { "echoheader?Accept-Language", "None" },
6337 { "echoheader?Accept-Charset", "None" },
6338 { "echoheader?User-Agent", "" } };
6340 for (size_t i = 0; i < ARRAYSIZE_UNSAFE(tests); i++) {
6341 TestDelegate d;
6342 URLRequest req(
6343 test_server_.GetURL(tests[i].request), DEFAULT_PRIORITY, &d, &context);
6344 req.Start();
6345 base::RunLoop().Run();
6346 EXPECT_EQ(tests[i].expected_response, d.data_received())
6347 << " Request = \"" << tests[i].request << "\"";
6351 // Make sure that URLRequest passes on its priority updates to
6352 // newly-created jobs after the first one.
6353 TEST_F(URLRequestTestHTTP, SetSubsequentJobPriority) {
6354 ASSERT_TRUE(test_server_.Start());
6356 TestDelegate d;
6357 URLRequest req(test_server_.GetURL("empty.html"),
6358 DEFAULT_PRIORITY,
6360 &default_context_);
6361 EXPECT_EQ(DEFAULT_PRIORITY, req.priority());
6363 scoped_refptr<URLRequestRedirectJob> redirect_job =
6364 new URLRequestRedirectJob(
6365 &req, &default_network_delegate_, test_server_.GetURL("echo"),
6366 URLRequestRedirectJob::REDIRECT_302_FOUND, "Very Good Reason");
6367 AddTestInterceptor()->set_main_intercept_job(redirect_job.get());
6369 req.SetPriority(LOW);
6370 req.Start();
6371 EXPECT_TRUE(req.is_pending());
6373 scoped_refptr<URLRequestTestJob> job =
6374 new URLRequestTestJob(&req, &default_network_delegate_);
6375 AddTestInterceptor()->set_main_intercept_job(job.get());
6377 // Should trigger |job| to be started.
6378 base::RunLoop().Run();
6379 EXPECT_EQ(LOW, job->priority());
6382 // Check that creating a network request while entering/exiting suspend mode
6383 // fails as it should. This is the only case where an HttpTransactionFactory
6384 // does not return an HttpTransaction.
6385 TEST_F(URLRequestTestHTTP, NetworkSuspendTest) {
6386 // Create a new HttpNetworkLayer that thinks it's suspended.
6387 HttpNetworkSession::Params params;
6388 params.host_resolver = default_context_.host_resolver();
6389 params.cert_verifier = default_context_.cert_verifier();
6390 params.transport_security_state = default_context_.transport_security_state();
6391 params.proxy_service = default_context_.proxy_service();
6392 params.ssl_config_service = default_context_.ssl_config_service();
6393 params.http_auth_handler_factory =
6394 default_context_.http_auth_handler_factory();
6395 params.network_delegate = &default_network_delegate_;
6396 params.http_server_properties = default_context_.http_server_properties();
6397 scoped_ptr<HttpNetworkLayer> network_layer(
6398 new HttpNetworkLayer(new HttpNetworkSession(params)));
6399 network_layer->OnSuspend();
6401 HttpCache http_cache(network_layer.release(), default_context_.net_log(),
6402 HttpCache::DefaultBackend::InMemory(0));
6404 TestURLRequestContext context(true);
6405 context.set_http_transaction_factory(&http_cache);
6406 context.Init();
6408 TestDelegate d;
6409 URLRequest req(GURL("http://127.0.0.1/"),
6410 DEFAULT_PRIORITY,
6412 &context);
6413 req.Start();
6414 base::RunLoop().Run();
6416 EXPECT_TRUE(d.request_failed());
6417 EXPECT_EQ(URLRequestStatus::FAILED, req.status().status());
6418 EXPECT_EQ(ERR_NETWORK_IO_SUSPENDED, req.status().error());
6421 // Check that creating a network request while entering/exiting suspend mode
6422 // fails as it should in the case there is no cache. This is the only case
6423 // where an HttpTransactionFactory does not return an HttpTransaction.
6424 TEST_F(URLRequestTestHTTP, NetworkSuspendTestNoCache) {
6425 // Create a new HttpNetworkLayer that thinks it's suspended.
6426 HttpNetworkSession::Params params;
6427 params.host_resolver = default_context_.host_resolver();
6428 params.cert_verifier = default_context_.cert_verifier();
6429 params.transport_security_state = default_context_.transport_security_state();
6430 params.proxy_service = default_context_.proxy_service();
6431 params.ssl_config_service = default_context_.ssl_config_service();
6432 params.http_auth_handler_factory =
6433 default_context_.http_auth_handler_factory();
6434 params.network_delegate = &default_network_delegate_;
6435 params.http_server_properties = default_context_.http_server_properties();
6436 HttpNetworkLayer network_layer(new HttpNetworkSession(params));
6437 network_layer.OnSuspend();
6439 TestURLRequestContext context(true);
6440 context.set_http_transaction_factory(&network_layer);
6441 context.Init();
6443 TestDelegate d;
6444 URLRequest req(GURL("http://127.0.0.1/"),
6445 DEFAULT_PRIORITY,
6447 &context);
6448 req.Start();
6449 base::RunLoop().Run();
6451 EXPECT_TRUE(d.request_failed());
6452 EXPECT_EQ(URLRequestStatus::FAILED, req.status().status());
6453 EXPECT_EQ(ERR_NETWORK_IO_SUSPENDED, req.status().error());
6456 class HTTPSRequestTest : public testing::Test {
6457 public:
6458 HTTPSRequestTest() : default_context_(true) {
6459 default_context_.set_network_delegate(&default_network_delegate_);
6460 default_context_.Init();
6462 virtual ~HTTPSRequestTest() {}
6464 protected:
6465 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
6466 TestURLRequestContext default_context_;
6469 TEST_F(HTTPSRequestTest, HTTPSGetTest) {
6470 SpawnedTestServer test_server(
6471 SpawnedTestServer::TYPE_HTTPS,
6472 SpawnedTestServer::kLocalhost,
6473 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6474 ASSERT_TRUE(test_server.Start());
6476 TestDelegate d;
6478 URLRequest r(test_server.GetURL(std::string()),
6479 DEFAULT_PRIORITY,
6481 &default_context_);
6482 r.Start();
6483 EXPECT_TRUE(r.is_pending());
6485 base::RunLoop().Run();
6487 EXPECT_EQ(1, d.response_started_count());
6488 EXPECT_FALSE(d.received_data_before_response());
6489 EXPECT_NE(0, d.bytes_received());
6490 CheckSSLInfo(r.ssl_info());
6491 EXPECT_EQ(test_server.host_port_pair().host(),
6492 r.GetSocketAddress().host());
6493 EXPECT_EQ(test_server.host_port_pair().port(),
6494 r.GetSocketAddress().port());
6498 TEST_F(HTTPSRequestTest, HTTPSMismatchedTest) {
6499 SpawnedTestServer::SSLOptions ssl_options(
6500 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
6501 SpawnedTestServer test_server(
6502 SpawnedTestServer::TYPE_HTTPS,
6503 ssl_options,
6504 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6505 ASSERT_TRUE(test_server.Start());
6507 bool err_allowed = true;
6508 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
6509 TestDelegate d;
6511 d.set_allow_certificate_errors(err_allowed);
6512 URLRequest r(test_server.GetURL(std::string()),
6513 DEFAULT_PRIORITY,
6515 &default_context_);
6517 r.Start();
6518 EXPECT_TRUE(r.is_pending());
6520 base::RunLoop().Run();
6522 EXPECT_EQ(1, d.response_started_count());
6523 EXPECT_FALSE(d.received_data_before_response());
6524 EXPECT_TRUE(d.have_certificate_errors());
6525 if (err_allowed) {
6526 EXPECT_NE(0, d.bytes_received());
6527 CheckSSLInfo(r.ssl_info());
6528 } else {
6529 EXPECT_EQ(0, d.bytes_received());
6535 TEST_F(HTTPSRequestTest, HTTPSExpiredTest) {
6536 SpawnedTestServer::SSLOptions ssl_options(
6537 SpawnedTestServer::SSLOptions::CERT_EXPIRED);
6538 SpawnedTestServer test_server(
6539 SpawnedTestServer::TYPE_HTTPS,
6540 ssl_options,
6541 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6542 ASSERT_TRUE(test_server.Start());
6544 // Iterate from false to true, just so that we do the opposite of the
6545 // previous test in order to increase test coverage.
6546 bool err_allowed = false;
6547 for (int i = 0; i < 2 ; i++, err_allowed = !err_allowed) {
6548 TestDelegate d;
6550 d.set_allow_certificate_errors(err_allowed);
6551 URLRequest r(test_server.GetURL(std::string()),
6552 DEFAULT_PRIORITY,
6554 &default_context_);
6556 r.Start();
6557 EXPECT_TRUE(r.is_pending());
6559 base::RunLoop().Run();
6561 EXPECT_EQ(1, d.response_started_count());
6562 EXPECT_FALSE(d.received_data_before_response());
6563 EXPECT_TRUE(d.have_certificate_errors());
6564 if (err_allowed) {
6565 EXPECT_NE(0, d.bytes_received());
6566 CheckSSLInfo(r.ssl_info());
6567 } else {
6568 EXPECT_EQ(0, d.bytes_received());
6574 // This tests that a load of www.google.com with a certificate error sets
6575 // the |certificate_errors_are_fatal| flag correctly. This flag will cause
6576 // the interstitial to be fatal.
6577 TEST_F(HTTPSRequestTest, HTTPSPreloadedHSTSTest) {
6578 SpawnedTestServer::SSLOptions ssl_options(
6579 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
6580 SpawnedTestServer test_server(
6581 SpawnedTestServer::TYPE_HTTPS,
6582 ssl_options,
6583 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6584 ASSERT_TRUE(test_server.Start());
6586 // We require that the URL be www.google.com in order to pick up the
6587 // preloaded HSTS entries in the TransportSecurityState. This means that we
6588 // have to use a MockHostResolver in order to direct www.google.com to the
6589 // testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
6591 MockHostResolver host_resolver;
6592 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
6593 TestURLRequestContext context(true);
6594 context.set_network_delegate(&network_delegate);
6595 context.set_host_resolver(&host_resolver);
6596 TransportSecurityState transport_security_state;
6597 context.set_transport_security_state(&transport_security_state);
6598 context.Init();
6600 TestDelegate d;
6601 URLRequest r(GURL(base::StringPrintf("https://www.google.com:%d",
6602 test_server.host_port_pair().port())),
6603 DEFAULT_PRIORITY,
6605 &context);
6607 r.Start();
6608 EXPECT_TRUE(r.is_pending());
6610 base::RunLoop().Run();
6612 EXPECT_EQ(1, d.response_started_count());
6613 EXPECT_FALSE(d.received_data_before_response());
6614 EXPECT_TRUE(d.have_certificate_errors());
6615 EXPECT_TRUE(d.certificate_errors_are_fatal());
6618 // This tests that cached HTTPS page loads do not cause any updates to the
6619 // TransportSecurityState.
6620 TEST_F(HTTPSRequestTest, HTTPSErrorsNoClobberTSSTest) {
6621 // The actual problem -- CERT_MISMATCHED_NAME in this case -- doesn't
6622 // matter. It just has to be any error.
6623 SpawnedTestServer::SSLOptions ssl_options(
6624 SpawnedTestServer::SSLOptions::CERT_MISMATCHED_NAME);
6625 SpawnedTestServer test_server(
6626 SpawnedTestServer::TYPE_HTTPS,
6627 ssl_options,
6628 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6629 ASSERT_TRUE(test_server.Start());
6631 // We require that the URL be www.google.com in order to pick up the static
6632 // and dynamic STS and PKP entries in the TransportSecurityState. This means
6633 // that we have to use a MockHostResolver in order to direct www.google.com to
6634 // the testserver. By default, MockHostResolver maps all hosts to 127.0.0.1.
6636 MockHostResolver host_resolver;
6637 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
6638 TestURLRequestContext context(true);
6639 context.set_network_delegate(&network_delegate);
6640 context.set_host_resolver(&host_resolver);
6641 TransportSecurityState transport_security_state;
6643 TransportSecurityState::DomainState static_domain_state;
6644 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
6645 "www.google.com", true, &static_domain_state));
6646 context.set_transport_security_state(&transport_security_state);
6647 context.Init();
6649 TransportSecurityState::DomainState dynamic_domain_state;
6650 EXPECT_FALSE(transport_security_state.GetDynamicDomainState(
6651 "www.google.com", &dynamic_domain_state));
6653 TestDelegate d;
6654 URLRequest r(GURL(base::StringPrintf("https://www.google.com:%d",
6655 test_server.host_port_pair().port())),
6656 DEFAULT_PRIORITY,
6658 &context);
6660 r.Start();
6661 EXPECT_TRUE(r.is_pending());
6663 base::RunLoop().Run();
6665 EXPECT_EQ(1, d.response_started_count());
6666 EXPECT_FALSE(d.received_data_before_response());
6667 EXPECT_TRUE(d.have_certificate_errors());
6668 EXPECT_TRUE(d.certificate_errors_are_fatal());
6670 // Get a fresh copy of the states, and check that they haven't changed.
6671 TransportSecurityState::DomainState new_static_domain_state;
6672 EXPECT_TRUE(transport_security_state.GetStaticDomainState(
6673 "www.google.com", true, &new_static_domain_state));
6674 TransportSecurityState::DomainState new_dynamic_domain_state;
6675 EXPECT_FALSE(transport_security_state.GetDynamicDomainState(
6676 "www.google.com", &new_dynamic_domain_state));
6678 EXPECT_EQ(new_static_domain_state.sts.upgrade_mode,
6679 static_domain_state.sts.upgrade_mode);
6680 EXPECT_EQ(new_static_domain_state.sts.include_subdomains,
6681 static_domain_state.sts.include_subdomains);
6682 EXPECT_EQ(new_static_domain_state.pkp.include_subdomains,
6683 static_domain_state.pkp.include_subdomains);
6684 EXPECT_TRUE(FingerprintsEqual(new_static_domain_state.pkp.spki_hashes,
6685 static_domain_state.pkp.spki_hashes));
6686 EXPECT_TRUE(FingerprintsEqual(new_static_domain_state.pkp.bad_spki_hashes,
6687 static_domain_state.pkp.bad_spki_hashes));
6690 // Make sure HSTS preserves a POST request's method and body.
6691 TEST_F(HTTPSRequestTest, HSTSPreservesPosts) {
6692 static const char kData[] = "hello world";
6694 SpawnedTestServer::SSLOptions ssl_options(
6695 SpawnedTestServer::SSLOptions::CERT_OK);
6696 SpawnedTestServer test_server(
6697 SpawnedTestServer::TYPE_HTTPS,
6698 ssl_options,
6699 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6700 ASSERT_TRUE(test_server.Start());
6703 // Per spec, TransportSecurityState expects a domain name, rather than an IP
6704 // address, so a MockHostResolver is needed to redirect www.somewhere.com to
6705 // the SpawnedTestServer. By default, MockHostResolver maps all hosts
6706 // to 127.0.0.1.
6707 MockHostResolver host_resolver;
6709 // Force https for www.somewhere.com.
6710 TransportSecurityState transport_security_state;
6711 base::Time expiry = base::Time::Now() + base::TimeDelta::FromDays(1000);
6712 bool include_subdomains = false;
6713 transport_security_state.AddHSTS("www.somewhere.com", expiry,
6714 include_subdomains);
6716 TestNetworkDelegate network_delegate; // Must outlive URLRequest.
6718 TestURLRequestContext context(true);
6719 context.set_host_resolver(&host_resolver);
6720 context.set_transport_security_state(&transport_security_state);
6721 context.set_network_delegate(&network_delegate);
6722 context.Init();
6724 TestDelegate d;
6725 // Navigating to https://www.somewhere.com instead of https://127.0.0.1 will
6726 // cause a certificate error. Ignore the error.
6727 d.set_allow_certificate_errors(true);
6729 URLRequest req(GURL(base::StringPrintf("http://www.somewhere.com:%d/echo",
6730 test_server.host_port_pair().port())),
6731 DEFAULT_PRIORITY,
6733 &context);
6734 req.set_method("POST");
6735 req.set_upload(make_scoped_ptr(CreateSimpleUploadData(kData)));
6737 req.Start();
6738 base::RunLoop().Run();
6740 EXPECT_EQ("https", req.url().scheme());
6741 EXPECT_EQ("POST", req.method());
6742 EXPECT_EQ(kData, d.data_received());
6744 LoadTimingInfo load_timing_info;
6745 network_delegate.GetLoadTimingInfoBeforeRedirect(&load_timing_info);
6746 // LoadTimingInfo of HSTS redirects is similar to that of network cache hits
6747 TestLoadTimingCacheHitNoNetwork(load_timing_info);
6750 namespace {
6752 class SSLClientAuthTestDelegate : public TestDelegate {
6753 public:
6754 SSLClientAuthTestDelegate() : on_certificate_requested_count_(0) {
6756 virtual void OnCertificateRequested(
6757 URLRequest* request,
6758 SSLCertRequestInfo* cert_request_info) OVERRIDE {
6759 on_certificate_requested_count_++;
6760 base::MessageLoop::current()->Quit();
6762 int on_certificate_requested_count() {
6763 return on_certificate_requested_count_;
6765 private:
6766 int on_certificate_requested_count_;
6769 } // namespace
6771 // TODO(davidben): Test the rest of the code. Specifically,
6772 // - Filtering which certificates to select.
6773 // - Sending a certificate back.
6774 // - Getting a certificate request in an SSL renegotiation sending the
6775 // HTTP request.
6776 TEST_F(HTTPSRequestTest, ClientAuthTest) {
6777 SpawnedTestServer::SSLOptions ssl_options;
6778 ssl_options.request_client_certificate = true;
6779 SpawnedTestServer test_server(
6780 SpawnedTestServer::TYPE_HTTPS,
6781 ssl_options,
6782 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6783 ASSERT_TRUE(test_server.Start());
6785 SSLClientAuthTestDelegate d;
6787 URLRequest r(test_server.GetURL(std::string()),
6788 DEFAULT_PRIORITY,
6790 &default_context_);
6792 r.Start();
6793 EXPECT_TRUE(r.is_pending());
6795 base::RunLoop().Run();
6797 EXPECT_EQ(1, d.on_certificate_requested_count());
6798 EXPECT_FALSE(d.received_data_before_response());
6799 EXPECT_EQ(0, d.bytes_received());
6801 // Send no certificate.
6802 // TODO(davidben): Get temporary client cert import (with keys) working on
6803 // all platforms so we can test sending a cert as well.
6804 r.ContinueWithCertificate(NULL);
6806 base::RunLoop().Run();
6808 EXPECT_EQ(1, d.response_started_count());
6809 EXPECT_FALSE(d.received_data_before_response());
6810 EXPECT_NE(0, d.bytes_received());
6814 TEST_F(HTTPSRequestTest, ResumeTest) {
6815 // Test that we attempt a session resume when making two connections to the
6816 // same host.
6817 SpawnedTestServer::SSLOptions ssl_options;
6818 ssl_options.record_resume = true;
6819 SpawnedTestServer test_server(
6820 SpawnedTestServer::TYPE_HTTPS,
6821 ssl_options,
6822 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6823 ASSERT_TRUE(test_server.Start());
6825 SSLClientSocket::ClearSessionCache();
6828 TestDelegate d;
6829 URLRequest r(test_server.GetURL("ssl-session-cache"),
6830 DEFAULT_PRIORITY,
6832 &default_context_);
6834 r.Start();
6835 EXPECT_TRUE(r.is_pending());
6837 base::RunLoop().Run();
6839 EXPECT_EQ(1, d.response_started_count());
6842 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
6843 CloseAllConnections();
6846 TestDelegate d;
6847 URLRequest r(test_server.GetURL("ssl-session-cache"),
6848 DEFAULT_PRIORITY,
6850 &default_context_);
6852 r.Start();
6853 EXPECT_TRUE(r.is_pending());
6855 base::RunLoop().Run();
6857 // The response will look like;
6858 // insert abc
6859 // lookup abc
6860 // insert xyz
6862 // With a newline at the end which makes the split think that there are
6863 // four lines.
6865 EXPECT_EQ(1, d.response_started_count());
6866 std::vector<std::string> lines;
6867 base::SplitString(d.data_received(), '\n', &lines);
6868 ASSERT_EQ(4u, lines.size()) << d.data_received();
6870 std::string session_id;
6872 for (size_t i = 0; i < 2; i++) {
6873 std::vector<std::string> parts;
6874 base::SplitString(lines[i], '\t', &parts);
6875 ASSERT_EQ(2u, parts.size());
6876 if (i == 0) {
6877 EXPECT_EQ("insert", parts[0]);
6878 session_id = parts[1];
6879 } else {
6880 EXPECT_EQ("lookup", parts[0]);
6881 EXPECT_EQ(session_id, parts[1]);
6887 TEST_F(HTTPSRequestTest, SSLSessionCacheShardTest) {
6888 // Test that sessions aren't resumed when the value of ssl_session_cache_shard
6889 // differs.
6890 SpawnedTestServer::SSLOptions ssl_options;
6891 ssl_options.record_resume = true;
6892 SpawnedTestServer test_server(
6893 SpawnedTestServer::TYPE_HTTPS,
6894 ssl_options,
6895 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6896 ASSERT_TRUE(test_server.Start());
6898 SSLClientSocket::ClearSessionCache();
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 EXPECT_EQ(1, d.response_started_count());
6915 // Now create a new HttpCache with a different ssl_session_cache_shard value.
6916 HttpNetworkSession::Params params;
6917 params.host_resolver = default_context_.host_resolver();
6918 params.cert_verifier = default_context_.cert_verifier();
6919 params.transport_security_state = default_context_.transport_security_state();
6920 params.proxy_service = default_context_.proxy_service();
6921 params.ssl_config_service = default_context_.ssl_config_service();
6922 params.http_auth_handler_factory =
6923 default_context_.http_auth_handler_factory();
6924 params.network_delegate = &default_network_delegate_;
6925 params.http_server_properties = default_context_.http_server_properties();
6926 params.ssl_session_cache_shard = "alternate";
6928 scoped_ptr<net::HttpCache> cache(new net::HttpCache(
6929 new net::HttpNetworkSession(params),
6930 net::HttpCache::DefaultBackend::InMemory(0)));
6932 default_context_.set_http_transaction_factory(cache.get());
6935 TestDelegate d;
6936 URLRequest r(test_server.GetURL("ssl-session-cache"),
6937 DEFAULT_PRIORITY,
6939 &default_context_);
6941 r.Start();
6942 EXPECT_TRUE(r.is_pending());
6944 base::RunLoop().Run();
6946 // The response will look like;
6947 // insert abc
6948 // insert xyz
6950 // With a newline at the end which makes the split think that there are
6951 // three lines.
6953 EXPECT_EQ(1, d.response_started_count());
6954 std::vector<std::string> lines;
6955 base::SplitString(d.data_received(), '\n', &lines);
6956 ASSERT_EQ(3u, lines.size());
6958 std::string session_id;
6959 for (size_t i = 0; i < 2; i++) {
6960 std::vector<std::string> parts;
6961 base::SplitString(lines[i], '\t', &parts);
6962 ASSERT_EQ(2u, parts.size());
6963 EXPECT_EQ("insert", parts[0]);
6964 if (i == 0) {
6965 session_id = parts[1];
6966 } else {
6967 EXPECT_NE(session_id, parts[1]);
6973 class HTTPSFallbackTest : public testing::Test {
6974 public:
6975 HTTPSFallbackTest() : context_(true) {
6976 context_.Init();
6977 delegate_.set_allow_certificate_errors(true);
6979 virtual ~HTTPSFallbackTest() {}
6981 protected:
6982 void DoFallbackTest(const SpawnedTestServer::SSLOptions& ssl_options) {
6983 DCHECK(!request_);
6984 SpawnedTestServer test_server(
6985 SpawnedTestServer::TYPE_HTTPS,
6986 ssl_options,
6987 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
6988 ASSERT_TRUE(test_server.Start());
6990 request_.reset(new URLRequest(
6991 test_server.GetURL(std::string()), DEFAULT_PRIORITY,
6992 &delegate_, &context_));
6993 request_->Start();
6995 base::RunLoop().Run();
6998 void ExpectConnection(int version) {
6999 EXPECT_EQ(1, delegate_.response_started_count());
7000 EXPECT_NE(0, delegate_.bytes_received());
7001 EXPECT_EQ(version, SSLConnectionStatusToVersion(
7002 request_->ssl_info().connection_status));
7003 EXPECT_TRUE(request_->ssl_info().connection_status &
7004 SSL_CONNECTION_VERSION_FALLBACK);
7007 void ExpectFailure(int error) {
7008 EXPECT_EQ(1, delegate_.response_started_count());
7009 EXPECT_FALSE(request_->status().is_success());
7010 EXPECT_EQ(URLRequestStatus::FAILED, request_->status().status());
7011 EXPECT_EQ(error, request_->status().error());
7014 private:
7015 TestDelegate delegate_;
7016 TestURLRequestContext context_;
7017 scoped_ptr<URLRequest> request_;
7020 // Tests TLSv1.1 -> TLSv1 fallback. Verifies that we don't fall back more
7021 // than necessary.
7022 TEST_F(HTTPSFallbackTest, TLSv1Fallback) {
7023 SpawnedTestServer::SSLOptions ssl_options(
7024 SpawnedTestServer::SSLOptions::CERT_OK);
7025 ssl_options.tls_intolerant =
7026 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
7028 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
7029 ExpectConnection(SSL_CONNECTION_VERSION_TLS1);
7032 // This test is disabled on Android because the remote test server doesn't cause
7033 // a TCP reset.
7034 #if !defined(OS_ANDROID)
7035 // Tests fallback to TLS 1.0 on connection reset.
7036 TEST_F(HTTPSFallbackTest, TLSv1FallbackReset) {
7037 SpawnedTestServer::SSLOptions ssl_options(
7038 SpawnedTestServer::SSLOptions::CERT_OK);
7039 ssl_options.tls_intolerant =
7040 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_TLS1_1;
7041 ssl_options.tls_intolerance_type =
7042 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_RESET;
7044 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
7045 ExpectConnection(SSL_CONNECTION_VERSION_TLS1);
7047 #endif // !OS_ANDROID
7049 // Tests that we don't fallback on handshake failure with servers that implement
7050 // TLS_FALLBACK_SCSV. Also ensure that the original error code is reported.
7051 #if defined(USE_OPENSSL)
7052 TEST_F(HTTPSFallbackTest, DISABLED_FallbackSCSV) {
7053 #else
7054 TEST_F(HTTPSFallbackTest, FallbackSCSV) {
7055 #endif
7056 SpawnedTestServer::SSLOptions ssl_options(
7057 SpawnedTestServer::SSLOptions::CERT_OK);
7058 // Configure HTTPS server to be intolerant of TLS >= 1.0 in order to trigger
7059 // a version fallback.
7060 ssl_options.tls_intolerant =
7061 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL;
7062 // Have the server process TLS_FALLBACK_SCSV so that version fallback
7063 // connections are rejected.
7064 ssl_options.fallback_scsv_enabled = true;
7066 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
7068 // ERR_SSL_VERSION_OR_CIPHER_MISMATCH is how the server simulates version
7069 // intolerance. If the fallback SCSV is processed when the original error
7070 // that caused the fallback should be returned, which should be
7071 // ERR_SSL_VERSION_OR_CIPHER_MISMATCH.
7072 ExpectFailure(ERR_SSL_VERSION_OR_CIPHER_MISMATCH);
7075 // Tests that we don't fallback on connection closed with servers that implement
7076 // TLS_FALLBACK_SCSV. Also ensure that the original error code is reported.
7077 #if defined(USE_OPENSSL)
7078 TEST_F(HTTPSFallbackTest, DISABLED_FallbackSCSVClosed) {
7079 #else
7080 TEST_F(HTTPSFallbackTest, FallbackSCSVClosed) {
7081 #endif
7082 SpawnedTestServer::SSLOptions ssl_options(
7083 SpawnedTestServer::SSLOptions::CERT_OK);
7084 // Configure HTTPS server to be intolerant of TLS >= 1.0 in order to trigger
7085 // a version fallback.
7086 ssl_options.tls_intolerant =
7087 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL;
7088 ssl_options.tls_intolerance_type =
7089 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_CLOSE;
7090 // Have the server process TLS_FALLBACK_SCSV so that version fallback
7091 // connections are rejected.
7092 ssl_options.fallback_scsv_enabled = true;
7094 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
7096 // The original error should be replayed on rejected fallback.
7097 ExpectFailure(ERR_CONNECTION_CLOSED);
7100 // Tests that the SSLv3 fallback triggers on alert.
7101 TEST_F(HTTPSFallbackTest, SSLv3Fallback) {
7102 SpawnedTestServer::SSLOptions ssl_options(
7103 SpawnedTestServer::SSLOptions::CERT_OK);
7104 ssl_options.tls_intolerant =
7105 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL;
7107 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
7108 ExpectConnection(SSL_CONNECTION_VERSION_SSL3);
7111 // Tests that the SSLv3 fallback triggers on closed connections.
7112 TEST_F(HTTPSFallbackTest, SSLv3FallbackClosed) {
7113 SpawnedTestServer::SSLOptions ssl_options(
7114 SpawnedTestServer::SSLOptions::CERT_OK);
7115 ssl_options.tls_intolerant =
7116 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL;
7117 ssl_options.tls_intolerance_type =
7118 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_CLOSE;
7120 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
7121 ExpectConnection(SSL_CONNECTION_VERSION_SSL3);
7124 // This test is disabled on Android because the remote test server doesn't cause
7125 // a TCP reset. It also does not pass on OpenSSL. https://crbug.com/372849
7126 #if !defined(OS_ANDROID) && !defined(USE_OPENSSL)
7127 // Tests that a reset connection does not fallback down to SSL3.
7128 TEST_F(HTTPSFallbackTest, SSLv3NoFallbackReset) {
7129 SpawnedTestServer::SSLOptions ssl_options(
7130 SpawnedTestServer::SSLOptions::CERT_OK);
7131 ssl_options.tls_intolerant =
7132 SpawnedTestServer::SSLOptions::TLS_INTOLERANT_ALL;
7133 ssl_options.tls_intolerance_type =
7134 SpawnedTestServer::SSLOptions::TLS_INTOLERANCE_RESET;
7136 ASSERT_NO_FATAL_FAILURE(DoFallbackTest(ssl_options));
7137 ExpectFailure(ERR_CONNECTION_RESET);
7139 #endif // !OS_ANDROID && !USE_OPENSSL
7141 class HTTPSSessionTest : public testing::Test {
7142 public:
7143 HTTPSSessionTest() : default_context_(true) {
7144 cert_verifier_.set_default_result(net::OK);
7146 default_context_.set_network_delegate(&default_network_delegate_);
7147 default_context_.set_cert_verifier(&cert_verifier_);
7148 default_context_.Init();
7150 virtual ~HTTPSSessionTest() {}
7152 protected:
7153 MockCertVerifier cert_verifier_;
7154 TestNetworkDelegate default_network_delegate_; // Must outlive URLRequest.
7155 TestURLRequestContext default_context_;
7158 // Tests that session resumption is not attempted if an invalid certificate
7159 // is presented.
7160 TEST_F(HTTPSSessionTest, DontResumeSessionsForInvalidCertificates) {
7161 SpawnedTestServer::SSLOptions ssl_options;
7162 ssl_options.record_resume = true;
7163 SpawnedTestServer test_server(
7164 SpawnedTestServer::TYPE_HTTPS,
7165 ssl_options,
7166 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7167 ASSERT_TRUE(test_server.Start());
7169 SSLClientSocket::ClearSessionCache();
7171 // Simulate the certificate being expired and attempt a connection.
7172 cert_verifier_.set_default_result(net::ERR_CERT_DATE_INVALID);
7174 TestDelegate d;
7175 URLRequest r(test_server.GetURL("ssl-session-cache"),
7176 DEFAULT_PRIORITY,
7178 &default_context_);
7180 r.Start();
7181 EXPECT_TRUE(r.is_pending());
7183 base::RunLoop().Run();
7185 EXPECT_EQ(1, d.response_started_count());
7188 reinterpret_cast<HttpCache*>(default_context_.http_transaction_factory())->
7189 CloseAllConnections();
7191 // Now change the certificate to be acceptable (so that the response is
7192 // loaded), and ensure that no session id is presented to the peer.
7193 cert_verifier_.set_default_result(net::OK);
7195 TestDelegate d;
7196 URLRequest r(test_server.GetURL("ssl-session-cache"),
7197 DEFAULT_PRIORITY,
7199 &default_context_);
7201 r.Start();
7202 EXPECT_TRUE(r.is_pending());
7204 base::RunLoop().Run();
7206 // The response will look like;
7207 // insert abc
7208 // insert xyz
7210 // With a newline at the end which makes the split think that there are
7211 // three lines.
7213 // If a session was presented (eg: a bug), then the response would look
7214 // like;
7215 // insert abc
7216 // lookup abc
7217 // insert xyz
7219 EXPECT_EQ(1, d.response_started_count());
7220 std::vector<std::string> lines;
7221 base::SplitString(d.data_received(), '\n', &lines);
7222 ASSERT_EQ(3u, lines.size()) << d.data_received();
7224 std::string session_id;
7225 for (size_t i = 0; i < 2; i++) {
7226 std::vector<std::string> parts;
7227 base::SplitString(lines[i], '\t', &parts);
7228 ASSERT_EQ(2u, parts.size());
7229 EXPECT_EQ("insert", parts[0]);
7230 if (i == 0) {
7231 session_id = parts[1];
7232 } else {
7233 EXPECT_NE(session_id, parts[1]);
7239 class TestSSLConfigService : public SSLConfigService {
7240 public:
7241 TestSSLConfigService(bool ev_enabled,
7242 bool online_rev_checking,
7243 bool rev_checking_required_local_anchors)
7244 : ev_enabled_(ev_enabled),
7245 online_rev_checking_(online_rev_checking),
7246 rev_checking_required_local_anchors_(
7247 rev_checking_required_local_anchors) {}
7249 // SSLConfigService:
7250 virtual void GetSSLConfig(SSLConfig* config) OVERRIDE {
7251 *config = SSLConfig();
7252 config->rev_checking_enabled = online_rev_checking_;
7253 config->verify_ev_cert = ev_enabled_;
7254 config->rev_checking_required_local_anchors =
7255 rev_checking_required_local_anchors_;
7258 protected:
7259 virtual ~TestSSLConfigService() {}
7261 private:
7262 const bool ev_enabled_;
7263 const bool online_rev_checking_;
7264 const bool rev_checking_required_local_anchors_;
7267 // This the fingerprint of the "Testing CA" certificate used by the testserver.
7268 // See net/data/ssl/certificates/ocsp-test-root.pem.
7269 static const SHA1HashValue kOCSPTestCertFingerprint =
7270 { { 0xf1, 0xad, 0xf6, 0xce, 0x42, 0xac, 0xe7, 0xb4, 0xf4, 0x24,
7271 0xdb, 0x1a, 0xf7, 0xa0, 0x9f, 0x09, 0xa1, 0xea, 0xf1, 0x5c } };
7273 // This is the SHA256, SPKI hash of the "Testing CA" certificate used by the
7274 // testserver.
7275 static const SHA256HashValue kOCSPTestCertSPKI = { {
7276 0xee, 0xe6, 0x51, 0x2d, 0x4c, 0xfa, 0xf7, 0x3e,
7277 0x6c, 0xd8, 0xca, 0x67, 0xed, 0xb5, 0x5d, 0x49,
7278 0x76, 0xe1, 0x52, 0xa7, 0x6e, 0x0e, 0xa0, 0x74,
7279 0x09, 0x75, 0xe6, 0x23, 0x24, 0xbd, 0x1b, 0x28,
7280 } };
7282 // This is the policy OID contained in the certificates that testserver
7283 // generates.
7284 static const char kOCSPTestCertPolicy[] = "1.3.6.1.4.1.11129.2.4.1";
7286 class HTTPSOCSPTest : public HTTPSRequestTest {
7287 public:
7288 HTTPSOCSPTest()
7289 : context_(true),
7290 ev_test_policy_(
7291 new ScopedTestEVPolicy(EVRootCAMetadata::GetInstance(),
7292 kOCSPTestCertFingerprint,
7293 kOCSPTestCertPolicy)) {
7296 virtual void SetUp() OVERRIDE {
7297 SetupContext(&context_);
7298 context_.Init();
7300 scoped_refptr<net::X509Certificate> root_cert =
7301 ImportCertFromFile(GetTestCertsDirectory(), "ocsp-test-root.pem");
7302 CHECK_NE(static_cast<X509Certificate*>(NULL), root_cert);
7303 test_root_.reset(new ScopedTestRoot(root_cert.get()));
7305 #if defined(USE_NSS) || defined(OS_IOS)
7306 SetURLRequestContextForNSSHttpIO(&context_);
7307 EnsureNSSHttpIOInit();
7308 #endif
7311 void DoConnection(const SpawnedTestServer::SSLOptions& ssl_options,
7312 CertStatus* out_cert_status) {
7313 // We always overwrite out_cert_status.
7314 *out_cert_status = 0;
7315 SpawnedTestServer test_server(
7316 SpawnedTestServer::TYPE_HTTPS,
7317 ssl_options,
7318 base::FilePath(FILE_PATH_LITERAL("net/data/ssl")));
7319 ASSERT_TRUE(test_server.Start());
7321 TestDelegate d;
7322 d.set_allow_certificate_errors(true);
7323 URLRequest r(
7324 test_server.GetURL(std::string()), DEFAULT_PRIORITY, &d, &context_);
7325 r.Start();
7327 base::RunLoop().Run();
7329 EXPECT_EQ(1, d.response_started_count());
7330 *out_cert_status = r.ssl_info().cert_status;
7333 virtual ~HTTPSOCSPTest() {
7334 #if defined(USE_NSS) || defined(OS_IOS)
7335 ShutdownNSSHttpIO();
7336 #endif
7339 protected:
7340 // SetupContext configures the URLRequestContext that will be used for making
7341 // connetions to testserver. This can be overridden in test subclasses for
7342 // different behaviour.
7343 virtual void SetupContext(URLRequestContext* context) {
7344 context->set_ssl_config_service(
7345 new TestSSLConfigService(true /* check for EV */,
7346 true /* online revocation checking */,
7347 false /* require rev. checking for local
7348 anchors */));
7351 scoped_ptr<ScopedTestRoot> test_root_;
7352 TestURLRequestContext context_;
7353 scoped_ptr<ScopedTestEVPolicy> ev_test_policy_;
7356 static CertStatus ExpectedCertStatusForFailedOnlineRevocationCheck() {
7357 #if defined(OS_WIN)
7358 // Windows can return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION but we don't
7359 // have that ability on other platforms.
7360 return CERT_STATUS_UNABLE_TO_CHECK_REVOCATION;
7361 #else
7362 return 0;
7363 #endif
7366 // SystemSupportsHardFailRevocationChecking returns true iff the current
7367 // operating system supports revocation checking and can distinguish between
7368 // situations where a given certificate lacks any revocation information (eg:
7369 // no CRLDistributionPoints and no OCSP Responder AuthorityInfoAccess) and when
7370 // revocation information cannot be obtained (eg: the CRL was unreachable).
7371 // If it does not, then tests which rely on 'hard fail' behaviour should be
7372 // skipped.
7373 static bool SystemSupportsHardFailRevocationChecking() {
7374 #if defined(OS_WIN) || defined(USE_NSS) || defined(OS_IOS)
7375 return true;
7376 #else
7377 return false;
7378 #endif
7381 // SystemUsesChromiumEVMetadata returns true iff the current operating system
7382 // uses Chromium's EV metadata (i.e. EVRootCAMetadata). If it does not, then
7383 // several tests are effected because our testing EV certificate won't be
7384 // recognised as EV.
7385 static bool SystemUsesChromiumEVMetadata() {
7386 #if defined(USE_OPENSSL_CERTS) && !defined(OS_ANDROID)
7387 // http://crbug.com/117478 - OpenSSL does not support EV validation.
7388 return false;
7389 #elif (defined(OS_MACOSX) && !defined(OS_IOS)) || defined(OS_ANDROID)
7390 // On OS X and Android, we use the system to tell us whether a certificate is
7391 // EV or not and the system won't recognise our testing root.
7392 return false;
7393 #else
7394 return true;
7395 #endif
7398 static bool SystemSupportsOCSP() {
7399 #if defined(USE_OPENSSL)
7400 // http://crbug.com/117478 - OpenSSL does not support OCSP.
7401 return false;
7402 #elif defined(OS_WIN)
7403 return base::win::GetVersion() >= base::win::VERSION_VISTA;
7404 #elif defined(OS_ANDROID)
7405 // TODO(jnd): http://crbug.com/117478 - EV verification is not yet supported.
7406 return false;
7407 #else
7408 return true;
7409 #endif
7412 TEST_F(HTTPSOCSPTest, Valid) {
7413 if (!SystemSupportsOCSP()) {
7414 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
7415 return;
7418 SpawnedTestServer::SSLOptions ssl_options(
7419 SpawnedTestServer::SSLOptions::CERT_AUTO);
7420 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
7422 CertStatus cert_status;
7423 DoConnection(ssl_options, &cert_status);
7425 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
7427 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
7428 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
7430 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
7433 TEST_F(HTTPSOCSPTest, Revoked) {
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;
7443 CertStatus cert_status;
7444 DoConnection(ssl_options, &cert_status);
7446 #if !(defined(OS_MACOSX) && !defined(OS_IOS))
7447 // Doesn't pass on OS X yet for reasons that need to be investigated.
7448 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
7449 #endif
7450 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
7451 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
7454 TEST_F(HTTPSOCSPTest, Invalid) {
7455 if (!SystemSupportsOCSP()) {
7456 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
7457 return;
7460 SpawnedTestServer::SSLOptions ssl_options(
7461 SpawnedTestServer::SSLOptions::CERT_AUTO);
7462 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
7464 CertStatus cert_status;
7465 DoConnection(ssl_options, &cert_status);
7467 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
7468 cert_status & CERT_STATUS_ALL_ERRORS);
7470 // Without a positive OCSP response, we shouldn't show the EV status.
7471 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
7472 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
7475 class HTTPSHardFailTest : public HTTPSOCSPTest {
7476 protected:
7477 virtual void SetupContext(URLRequestContext* context) OVERRIDE {
7478 context->set_ssl_config_service(
7479 new TestSSLConfigService(false /* check for EV */,
7480 false /* online revocation checking */,
7481 true /* require rev. checking for local
7482 anchors */));
7487 TEST_F(HTTPSHardFailTest, FailsOnOCSPInvalid) {
7488 if (!SystemSupportsOCSP()) {
7489 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
7490 return;
7493 if (!SystemSupportsHardFailRevocationChecking()) {
7494 LOG(WARNING) << "Skipping test because system doesn't support hard fail "
7495 << "revocation checking";
7496 return;
7499 SpawnedTestServer::SSLOptions ssl_options(
7500 SpawnedTestServer::SSLOptions::CERT_AUTO);
7501 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
7503 CertStatus cert_status;
7504 DoConnection(ssl_options, &cert_status);
7506 EXPECT_EQ(CERT_STATUS_REVOKED,
7507 cert_status & CERT_STATUS_REVOKED);
7509 // Without a positive OCSP response, we shouldn't show the EV status.
7510 EXPECT_TRUE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
7513 class HTTPSEVCRLSetTest : public HTTPSOCSPTest {
7514 protected:
7515 virtual void SetupContext(URLRequestContext* context) OVERRIDE {
7516 context->set_ssl_config_service(
7517 new TestSSLConfigService(true /* check for EV */,
7518 false /* online revocation checking */,
7519 false /* require rev. checking for local
7520 anchors */));
7524 TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndInvalidOCSP) {
7525 if (!SystemSupportsOCSP()) {
7526 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
7527 return;
7530 SpawnedTestServer::SSLOptions ssl_options(
7531 SpawnedTestServer::SSLOptions::CERT_AUTO);
7532 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
7533 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
7535 CertStatus cert_status;
7536 DoConnection(ssl_options, &cert_status);
7538 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
7539 cert_status & CERT_STATUS_ALL_ERRORS);
7541 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
7542 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
7543 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
7546 TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndRevokedOCSP) {
7547 if (!SystemSupportsOCSP()) {
7548 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
7549 return;
7552 SpawnedTestServer::SSLOptions ssl_options(
7553 SpawnedTestServer::SSLOptions::CERT_AUTO);
7554 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
7555 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
7557 CertStatus cert_status;
7558 DoConnection(ssl_options, &cert_status);
7560 // Currently only works for Windows. When using NSS or OS X, it's not
7561 // possible to determine whether the check failed because of actual
7562 // revocation or because there was an OCSP failure.
7563 #if defined(OS_WIN)
7564 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
7565 #else
7566 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
7567 #endif
7569 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
7570 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
7571 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
7574 TEST_F(HTTPSEVCRLSetTest, MissingCRLSetAndGoodOCSP) {
7575 if (!SystemSupportsOCSP()) {
7576 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
7577 return;
7580 SpawnedTestServer::SSLOptions ssl_options(
7581 SpawnedTestServer::SSLOptions::CERT_AUTO);
7582 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
7583 SSLConfigService::SetCRLSet(scoped_refptr<CRLSet>());
7585 CertStatus cert_status;
7586 DoConnection(ssl_options, &cert_status);
7588 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
7590 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
7591 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
7592 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
7593 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
7596 TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSet) {
7597 if (!SystemSupportsOCSP()) {
7598 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
7599 return;
7602 SpawnedTestServer::SSLOptions ssl_options(
7603 SpawnedTestServer::SSLOptions::CERT_AUTO);
7604 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
7605 SSLConfigService::SetCRLSet(
7606 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
7608 CertStatus cert_status;
7609 DoConnection(ssl_options, &cert_status);
7611 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
7612 cert_status & CERT_STATUS_ALL_ERRORS);
7614 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
7615 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
7616 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
7619 TEST_F(HTTPSEVCRLSetTest, FreshCRLSetCovered) {
7620 if (!SystemSupportsOCSP()) {
7621 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
7622 return;
7625 SpawnedTestServer::SSLOptions ssl_options(
7626 SpawnedTestServer::SSLOptions::CERT_AUTO);
7627 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
7628 SSLConfigService::SetCRLSet(
7629 scoped_refptr<CRLSet>(CRLSet::ForTesting(
7630 false, &kOCSPTestCertSPKI, "")));
7632 CertStatus cert_status;
7633 DoConnection(ssl_options, &cert_status);
7635 // With a fresh CRLSet that covers the issuing certificate, we shouldn't do a
7636 // revocation check for EV.
7637 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
7638 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
7639 static_cast<bool>(cert_status & CERT_STATUS_IS_EV));
7640 EXPECT_FALSE(
7641 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
7644 TEST_F(HTTPSEVCRLSetTest, FreshCRLSetNotCovered) {
7645 if (!SystemSupportsOCSP()) {
7646 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
7647 return;
7650 SpawnedTestServer::SSLOptions ssl_options(
7651 SpawnedTestServer::SSLOptions::CERT_AUTO);
7652 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
7653 SSLConfigService::SetCRLSet(
7654 scoped_refptr<CRLSet>(CRLSet::EmptyCRLSetForTesting()));
7656 CertStatus cert_status = 0;
7657 DoConnection(ssl_options, &cert_status);
7659 // Even with a fresh CRLSet, we should still do online revocation checks when
7660 // the certificate chain isn't covered by the CRLSet, which it isn't in this
7661 // test.
7662 EXPECT_EQ(ExpectedCertStatusForFailedOnlineRevocationCheck(),
7663 cert_status & CERT_STATUS_ALL_ERRORS);
7665 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
7666 EXPECT_EQ(SystemUsesChromiumEVMetadata(),
7667 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
7670 TEST_F(HTTPSEVCRLSetTest, ExpiredCRLSetAndRevokedNonEVCert) {
7671 // Test that when EV verification is requested, but online revocation
7672 // checking is disabled, and the leaf certificate is not in fact EV, that
7673 // no revocation checking actually happens.
7674 if (!SystemSupportsOCSP()) {
7675 LOG(WARNING) << "Skipping test because system doesn't support OCSP";
7676 return;
7679 // Unmark the certificate's OID as EV, which should disable revocation
7680 // checking (as per the user preference)
7681 ev_test_policy_.reset();
7683 SpawnedTestServer::SSLOptions ssl_options(
7684 SpawnedTestServer::SSLOptions::CERT_AUTO);
7685 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_REVOKED;
7686 SSLConfigService::SetCRLSet(
7687 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
7689 CertStatus cert_status;
7690 DoConnection(ssl_options, &cert_status);
7692 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
7694 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
7695 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
7698 class HTTPSCRLSetTest : public HTTPSOCSPTest {
7699 protected:
7700 virtual void SetupContext(URLRequestContext* context) OVERRIDE {
7701 context->set_ssl_config_service(
7702 new TestSSLConfigService(false /* check for EV */,
7703 false /* online revocation checking */,
7704 false /* require rev. checking for local
7705 anchors */));
7709 TEST_F(HTTPSCRLSetTest, ExpiredCRLSet) {
7710 SpawnedTestServer::SSLOptions ssl_options(
7711 SpawnedTestServer::SSLOptions::CERT_AUTO);
7712 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_INVALID;
7713 SSLConfigService::SetCRLSet(
7714 scoped_refptr<CRLSet>(CRLSet::ExpiredCRLSetForTesting()));
7716 CertStatus cert_status;
7717 DoConnection(ssl_options, &cert_status);
7719 // If we're not trying EV verification then, even if the CRLSet has expired,
7720 // we don't fall back to online revocation checks.
7721 EXPECT_EQ(0u, cert_status & CERT_STATUS_ALL_ERRORS);
7722 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
7723 EXPECT_FALSE(cert_status & CERT_STATUS_REV_CHECKING_ENABLED);
7726 TEST_F(HTTPSCRLSetTest, CRLSetRevoked) {
7727 #if defined(USE_OPENSSL)
7728 LOG(WARNING) << "Skipping test because system doesn't support CRLSets";
7729 return;
7730 #endif
7732 SpawnedTestServer::SSLOptions ssl_options(
7733 SpawnedTestServer::SSLOptions::CERT_AUTO);
7734 ssl_options.ocsp_status = SpawnedTestServer::SSLOptions::OCSP_OK;
7735 ssl_options.cert_serial = 10;
7736 SSLConfigService::SetCRLSet(
7737 scoped_refptr<CRLSet>(CRLSet::ForTesting(
7738 false, &kOCSPTestCertSPKI, "\x0a")));
7740 CertStatus cert_status = 0;
7741 DoConnection(ssl_options, &cert_status);
7743 // If the certificate is recorded as revoked in the CRLSet, that should be
7744 // reflected without online revocation checking.
7745 EXPECT_EQ(CERT_STATUS_REVOKED, cert_status & CERT_STATUS_ALL_ERRORS);
7746 EXPECT_FALSE(cert_status & CERT_STATUS_IS_EV);
7747 EXPECT_FALSE(
7748 static_cast<bool>(cert_status & CERT_STATUS_REV_CHECKING_ENABLED));
7750 #endif // !defined(OS_IOS)
7752 #if !defined(DISABLE_FTP_SUPPORT)
7753 class URLRequestTestFTP : public URLRequestTest {
7754 public:
7755 URLRequestTestFTP()
7756 : test_server_(SpawnedTestServer::TYPE_FTP, SpawnedTestServer::kLocalhost,
7757 base::FilePath()) {
7760 protected:
7761 SpawnedTestServer test_server_;
7764 // Make sure an FTP request using an unsafe ports fails.
7765 TEST_F(URLRequestTestFTP, UnsafePort) {
7766 ASSERT_TRUE(test_server_.Start());
7768 URLRequestJobFactoryImpl job_factory;
7769 FtpNetworkLayer ftp_transaction_factory(default_context_.host_resolver());
7771 GURL url("ftp://127.0.0.1:7");
7772 job_factory.SetProtocolHandler(
7773 "ftp",
7774 new FtpProtocolHandler(&ftp_transaction_factory));
7775 default_context_.set_job_factory(&job_factory);
7777 TestDelegate d;
7779 URLRequest r(url, DEFAULT_PRIORITY, &d, &default_context_);
7780 r.Start();
7781 EXPECT_TRUE(r.is_pending());
7783 base::RunLoop().Run();
7785 EXPECT_FALSE(r.is_pending());
7786 EXPECT_EQ(URLRequestStatus::FAILED, r.status().status());
7787 EXPECT_EQ(ERR_UNSAFE_PORT, r.status().error());
7791 // Flaky, see http://crbug.com/25045.
7792 TEST_F(URLRequestTestFTP, DISABLED_FTPDirectoryListing) {
7793 ASSERT_TRUE(test_server_.Start());
7795 TestDelegate d;
7797 URLRequest r(
7798 test_server_.GetURL("/"), DEFAULT_PRIORITY, &d, &default_context_);
7799 r.Start();
7800 EXPECT_TRUE(r.is_pending());
7802 base::RunLoop().Run();
7804 EXPECT_FALSE(r.is_pending());
7805 EXPECT_EQ(1, d.response_started_count());
7806 EXPECT_FALSE(d.received_data_before_response());
7807 EXPECT_LT(0, d.bytes_received());
7808 EXPECT_EQ(test_server_.host_port_pair().host(),
7809 r.GetSocketAddress().host());
7810 EXPECT_EQ(test_server_.host_port_pair().port(),
7811 r.GetSocketAddress().port());
7815 // Flaky, see http://crbug.com/25045.
7816 TEST_F(URLRequestTestFTP, DISABLED_FTPGetTestAnonymous) {
7817 ASSERT_TRUE(test_server_.Start());
7819 base::FilePath app_path;
7820 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
7821 app_path = app_path.AppendASCII("LICENSE");
7822 TestDelegate d;
7824 URLRequest r(test_server_.GetURL("/LICENSE"),
7825 DEFAULT_PRIORITY,
7827 &default_context_);
7828 r.Start();
7829 EXPECT_TRUE(r.is_pending());
7831 base::RunLoop().Run();
7833 int64 file_size = 0;
7834 base::GetFileSize(app_path, &file_size);
7836 EXPECT_FALSE(r.is_pending());
7837 EXPECT_EQ(1, d.response_started_count());
7838 EXPECT_FALSE(d.received_data_before_response());
7839 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
7840 EXPECT_EQ(test_server_.host_port_pair().host(),
7841 r.GetSocketAddress().host());
7842 EXPECT_EQ(test_server_.host_port_pair().port(),
7843 r.GetSocketAddress().port());
7847 // Flaky, see http://crbug.com/25045.
7848 TEST_F(URLRequestTestFTP, DISABLED_FTPGetTest) {
7849 ASSERT_TRUE(test_server_.Start());
7851 base::FilePath app_path;
7852 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
7853 app_path = app_path.AppendASCII("LICENSE");
7854 TestDelegate d;
7856 URLRequest r(
7857 test_server_.GetURLWithUserAndPassword("/LICENSE", "chrome", "chrome"),
7858 DEFAULT_PRIORITY,
7860 &default_context_);
7861 r.Start();
7862 EXPECT_TRUE(r.is_pending());
7864 base::RunLoop().Run();
7866 int64 file_size = 0;
7867 base::GetFileSize(app_path, &file_size);
7869 EXPECT_FALSE(r.is_pending());
7870 EXPECT_EQ(test_server_.host_port_pair().host(),
7871 r.GetSocketAddress().host());
7872 EXPECT_EQ(test_server_.host_port_pair().port(),
7873 r.GetSocketAddress().port());
7874 EXPECT_EQ(1, d.response_started_count());
7875 EXPECT_FALSE(d.received_data_before_response());
7876 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
7878 LoadTimingInfo load_timing_info;
7879 r.GetLoadTimingInfo(&load_timing_info);
7880 TestLoadTimingNoHttpResponse(load_timing_info);
7884 // Flaky, see http://crbug.com/25045.
7885 TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongPassword) {
7886 ASSERT_TRUE(test_server_.Start());
7888 base::FilePath app_path;
7889 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
7890 app_path = app_path.AppendASCII("LICENSE");
7891 TestDelegate d;
7893 URLRequest r(test_server_.GetURLWithUserAndPassword(
7894 "/LICENSE", "chrome", "wrong_password"),
7895 DEFAULT_PRIORITY,
7897 &default_context_);
7898 r.Start();
7899 EXPECT_TRUE(r.is_pending());
7901 base::RunLoop().Run();
7903 int64 file_size = 0;
7904 base::GetFileSize(app_path, &file_size);
7906 EXPECT_FALSE(r.is_pending());
7907 EXPECT_EQ(1, d.response_started_count());
7908 EXPECT_FALSE(d.received_data_before_response());
7909 EXPECT_EQ(d.bytes_received(), 0);
7913 // Flaky, see http://crbug.com/25045.
7914 TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongPasswordRestart) {
7915 ASSERT_TRUE(test_server_.Start());
7917 base::FilePath app_path;
7918 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
7919 app_path = app_path.AppendASCII("LICENSE");
7920 TestDelegate d;
7921 // Set correct login credentials. The delegate will be asked for them when
7922 // the initial login with wrong credentials will fail.
7923 d.set_credentials(AuthCredentials(kChrome, kChrome));
7925 URLRequest r(test_server_.GetURLWithUserAndPassword(
7926 "/LICENSE", "chrome", "wrong_password"),
7927 DEFAULT_PRIORITY,
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_FTPCheckWrongUser) {
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");
7952 TestDelegate d;
7954 URLRequest r(test_server_.GetURLWithUserAndPassword(
7955 "/LICENSE", "wrong_user", "chrome"),
7956 DEFAULT_PRIORITY,
7958 &default_context_);
7959 r.Start();
7960 EXPECT_TRUE(r.is_pending());
7962 base::RunLoop().Run();
7964 int64 file_size = 0;
7965 base::GetFileSize(app_path, &file_size);
7967 EXPECT_FALSE(r.is_pending());
7968 EXPECT_EQ(1, d.response_started_count());
7969 EXPECT_FALSE(d.received_data_before_response());
7970 EXPECT_EQ(d.bytes_received(), 0);
7974 // Flaky, see http://crbug.com/25045.
7975 TEST_F(URLRequestTestFTP, DISABLED_FTPCheckWrongUserRestart) {
7976 ASSERT_TRUE(test_server_.Start());
7978 base::FilePath app_path;
7979 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
7980 app_path = app_path.AppendASCII("LICENSE");
7981 TestDelegate d;
7982 // Set correct login credentials. The delegate will be asked for them when
7983 // the initial login with wrong credentials will fail.
7984 d.set_credentials(AuthCredentials(kChrome, kChrome));
7986 URLRequest r(test_server_.GetURLWithUserAndPassword(
7987 "/LICENSE", "wrong_user", "chrome"),
7988 DEFAULT_PRIORITY,
7990 &default_context_);
7991 r.Start();
7992 EXPECT_TRUE(r.is_pending());
7994 base::RunLoop().Run();
7996 int64 file_size = 0;
7997 base::GetFileSize(app_path, &file_size);
7999 EXPECT_FALSE(r.is_pending());
8000 EXPECT_EQ(1, d.response_started_count());
8001 EXPECT_FALSE(d.received_data_before_response());
8002 EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
8006 // Flaky, see http://crbug.com/25045.
8007 TEST_F(URLRequestTestFTP, DISABLED_FTPCacheURLCredentials) {
8008 ASSERT_TRUE(test_server_.Start());
8010 base::FilePath app_path;
8011 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
8012 app_path = app_path.AppendASCII("LICENSE");
8014 scoped_ptr<TestDelegate> d(new TestDelegate);
8016 // Pass correct login identity in the URL.
8017 URLRequest r(
8018 test_server_.GetURLWithUserAndPassword("/LICENSE", "chrome", "chrome"),
8019 DEFAULT_PRIORITY,
8020 d.get(),
8021 &default_context_);
8022 r.Start();
8023 EXPECT_TRUE(r.is_pending());
8025 base::RunLoop().Run();
8027 int64 file_size = 0;
8028 base::GetFileSize(app_path, &file_size);
8030 EXPECT_FALSE(r.is_pending());
8031 EXPECT_EQ(1, d->response_started_count());
8032 EXPECT_FALSE(d->received_data_before_response());
8033 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
8036 d.reset(new TestDelegate);
8038 // This request should use cached identity from previous request.
8039 URLRequest r(test_server_.GetURL("/LICENSE"),
8040 DEFAULT_PRIORITY,
8041 d.get(),
8042 &default_context_);
8043 r.Start();
8044 EXPECT_TRUE(r.is_pending());
8046 base::RunLoop().Run();
8048 int64 file_size = 0;
8049 base::GetFileSize(app_path, &file_size);
8051 EXPECT_FALSE(r.is_pending());
8052 EXPECT_EQ(1, d->response_started_count());
8053 EXPECT_FALSE(d->received_data_before_response());
8054 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
8058 // Flaky, see http://crbug.com/25045.
8059 TEST_F(URLRequestTestFTP, DISABLED_FTPCacheLoginBoxCredentials) {
8060 ASSERT_TRUE(test_server_.Start());
8062 base::FilePath app_path;
8063 PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
8064 app_path = app_path.AppendASCII("LICENSE");
8066 scoped_ptr<TestDelegate> d(new TestDelegate);
8067 // Set correct login credentials. The delegate will be asked for them when
8068 // the initial login with wrong credentials will fail.
8069 d->set_credentials(AuthCredentials(kChrome, kChrome));
8071 URLRequest r(test_server_.GetURLWithUserAndPassword(
8072 "/LICENSE", "chrome", "wrong_password"),
8073 DEFAULT_PRIORITY,
8074 d.get(),
8075 &default_context_);
8076 r.Start();
8077 EXPECT_TRUE(r.is_pending());
8079 base::RunLoop().Run();
8081 int64 file_size = 0;
8082 base::GetFileSize(app_path, &file_size);
8084 EXPECT_FALSE(r.is_pending());
8085 EXPECT_EQ(1, d->response_started_count());
8086 EXPECT_FALSE(d->received_data_before_response());
8087 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
8090 // Use a new delegate without explicit credentials. The cached ones should be
8091 // used.
8092 d.reset(new TestDelegate);
8094 // Don't pass wrong credentials in the URL, they would override valid cached
8095 // ones.
8096 URLRequest r(test_server_.GetURL("/LICENSE"),
8097 DEFAULT_PRIORITY,
8098 d.get(),
8099 &default_context_);
8100 r.Start();
8101 EXPECT_TRUE(r.is_pending());
8103 base::RunLoop().Run();
8105 int64 file_size = 0;
8106 base::GetFileSize(app_path, &file_size);
8108 EXPECT_FALSE(r.is_pending());
8109 EXPECT_EQ(1, d->response_started_count());
8110 EXPECT_FALSE(d->received_data_before_response());
8111 EXPECT_EQ(d->bytes_received(), static_cast<int>(file_size));
8114 #endif // !defined(DISABLE_FTP_SUPPORT)
8116 } // namespace net