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.
4
5#include "build/build_config.h"
6
7#if defined(OS_WIN)
8#include <windows.h>
9#include <shlobj.h>
10#endif
11
12#include <algorithm>
13#include <string>
14
15#include "base/basictypes.h"
16#include "base/bind.h"
17#include "base/compiler_specific.h"
18#include "base/files/file_util.h"
19#include "base/files/scoped_temp_dir.h"
20#include "base/format_macros.h"
21#include "base/memory/scoped_ptr.h"
22#include "base/memory/weak_ptr.h"
23#include "base/message_loop/message_loop.h"
24#include "base/message_loop/message_loop_proxy.h"
25#include "base/path_service.h"
26#include "base/run_loop.h"
27#include "base/strings/string_number_conversions.h"
28#include "base/strings/string_piece.h"
29#include "base/strings/string_split.h"
30#include "base/strings/string_util.h"
31#include "base/strings/stringprintf.h"
32#include "base/strings/utf_string_conversions.h"
33#include "net/base/capturing_net_log.h"
34#include "net/base/load_flags.h"
35#include "net/base/load_timing_info.h"
36#include "net/base/load_timing_info_test_util.h"
37#include "net/base/net_errors.h"
38#include "net/base/net_log.h"
39#include "net/base/net_log_unittest.h"
40#include "net/base/net_module.h"
41#include "net/base/net_util.h"
42#include "net/base/request_priority.h"
43#include "net/base/test_data_directory.h"
44#include "net/base/upload_bytes_element_reader.h"
45#include "net/base/upload_data_stream.h"
46#include "net/base/upload_file_element_reader.h"
47#include "net/cert/ev_root_ca_metadata.h"
48#include "net/cert/mock_cert_verifier.h"
49#include "net/cert/test_root_certs.h"
50#include "net/cookies/cookie_monster.h"
51#include "net/cookies/cookie_store_test_helpers.h"
52#include "net/disk_cache/disk_cache.h"
53#include "net/dns/mock_host_resolver.h"
54#include "net/ftp/ftp_network_layer.h"
55#include "net/http/http_byte_range.h"
56#include "net/http/http_cache.h"
57#include "net/http/http_network_layer.h"
58#include "net/http/http_network_session.h"
59#include "net/http/http_request_headers.h"
60#include "net/http/http_response_headers.h"
61#include "net/http/http_util.h"
62#include "net/ocsp/nss_ocsp.h"
63#include "net/proxy/proxy_service.h"
64#include "net/socket/ssl_client_socket.h"
65#include "net/ssl/ssl_cipher_suite_names.h"
66#include "net/ssl/ssl_connection_status_flags.h"
67#include "net/test/cert_test_util.h"
68#include "net/test/spawned_test_server/spawned_test_server.h"
69#include "net/url_request/data_protocol_handler.h"
70#include "net/url_request/static_http_user_agent_settings.h"
71#include "net/url_request/url_request.h"
72#include "net/url_request/url_request_http_job.h"
73#include "net/url_request/url_request_job_factory_impl.h"
74#include "net/url_request/url_request_redirect_job.h"
75#include "net/url_request/url_request_test_job.h"
76#include "net/url_request/url_request_test_util.h"
77#include "testing/gtest/include/gtest/gtest.h"
78#include "testing/platform_test.h"
79
80#if !defined(DISABLE_FILE_SUPPORT)
81#include "net/base/filename_util.h"
82#include "net/url_request/file_protocol_handler.h"
83#include "net/url_request/url_request_file_dir_job.h"
84#endif
85
86#if !defined(DISABLE_FTP_SUPPORT)
87#include "net/url_request/ftp_protocol_handler.h"
88#endif
89
90#if defined(OS_WIN)
91#include "base/win/scoped_com_initializer.h"
92#include "base/win/scoped_comptr.h"
93#include "base/win/windows_version.h"
94#endif
95
96using base::ASCIIToUTF16;
97using base::Time;
98
99namespace net {
100
101namespace {
102
103const base::string16 kChrome(ASCIIToUTF16("chrome"));
104const base::string16 kSecret(ASCIIToUTF16("secret"));
105const base::string16 kUser(ASCIIToUTF16("user"));
106
107// Tests load timing information in the case a fresh connection was used, with
108// no proxy.
109void TestLoadTimingNotReused(const LoadTimingInfo& load_timing_info,
110                             int connect_timing_flags) {
111  EXPECT_FALSE(load_timing_info.socket_reused);
112  EXPECT_NE(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
113
114  EXPECT_FALSE(load_timing_info.request_start_time.is_null());
115  EXPECT_FALSE(load_timing_info.request_start.is_null());
116
117  EXPECT_LE(load_timing_info.request_start,
118            load_timing_info.connect_timing.connect_start);
119  ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
120                              connect_timing_flags);
121  EXPECT_LE(load_timing_info.connect_timing.connect_end,
122            load_timing_info.send_start);
123  EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
124  EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
125
126  EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
127  EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
128}
129
130// Same as above, but with proxy times.
131void TestLoadTimingNotReusedWithProxy(
132    const LoadTimingInfo& load_timing_info,
133    int connect_timing_flags) {
134  EXPECT_FALSE(load_timing_info.socket_reused);
135  EXPECT_NE(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
136
137  EXPECT_FALSE(load_timing_info.request_start_time.is_null());
138  EXPECT_FALSE(load_timing_info.request_start.is_null());
139
140  EXPECT_LE(load_timing_info.request_start,
141            load_timing_info.proxy_resolve_start);
142  EXPECT_LE(load_timing_info.proxy_resolve_start,
143            load_timing_info.proxy_resolve_end);
144  EXPECT_LE(load_timing_info.proxy_resolve_end,
145            load_timing_info.connect_timing.connect_start);
146  ExpectConnectTimingHasTimes(load_timing_info.connect_timing,
147                              connect_timing_flags);
148  EXPECT_LE(load_timing_info.connect_timing.connect_end,
149            load_timing_info.send_start);
150  EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
151  EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
152}
153
154// Same as above, but with a reused socket and proxy times.
155void TestLoadTimingReusedWithProxy(
156    const LoadTimingInfo& load_timing_info) {
157  EXPECT_TRUE(load_timing_info.socket_reused);
158  EXPECT_NE(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
159
160  EXPECT_FALSE(load_timing_info.request_start_time.is_null());
161  EXPECT_FALSE(load_timing_info.request_start.is_null());
162
163  ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
164
165  EXPECT_LE(load_timing_info.request_start,
166            load_timing_info.proxy_resolve_start);
167  EXPECT_LE(load_timing_info.proxy_resolve_start,
168            load_timing_info.proxy_resolve_end);
169  EXPECT_LE(load_timing_info.proxy_resolve_end,
170            load_timing_info.send_start);
171  EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
172  EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
173}
174
175// Tests load timing information in the case of a cache hit, when no cache
176// validation request was sent over the wire.
177base::StringPiece TestNetResourceProvider(int key) {
178  return "header";
179}
180
181void FillBuffer(char* buffer, size_t len) {
182  static bool called = false;
183  if (!called) {
184    called = true;
185    int seed = static_cast<int>(Time::Now().ToInternalValue());
186    srand(seed);
187  }
188
189  for (size_t i = 0; i < len; i++) {
190    buffer[i] = static_cast<char>(rand());
191    if (!buffer[i])
192      buffer[i] = 'g';
193  }
194}
195
196#if !defined(OS_IOS)
197void TestLoadTimingCacheHitNoNetwork(
198    const LoadTimingInfo& load_timing_info) {
199  EXPECT_FALSE(load_timing_info.socket_reused);
200  EXPECT_EQ(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
201
202  EXPECT_FALSE(load_timing_info.request_start_time.is_null());
203  EXPECT_FALSE(load_timing_info.request_start.is_null());
204
205  ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
206  EXPECT_LE(load_timing_info.request_start, load_timing_info.send_start);
207  EXPECT_LE(load_timing_info.send_start, load_timing_info.send_end);
208  EXPECT_LE(load_timing_info.send_end, load_timing_info.receive_headers_end);
209
210  EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
211  EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
212}
213
214// Tests load timing in the case that there is no HTTP response.  This can be
215// used to test in the case of errors or non-HTTP requests.
216void TestLoadTimingNoHttpResponse(
217    const LoadTimingInfo& load_timing_info) {
218  EXPECT_FALSE(load_timing_info.socket_reused);
219  EXPECT_EQ(NetLog::Source::kInvalidId, load_timing_info.socket_log_id);
220
221  // Only the request times should be non-null.
222  EXPECT_FALSE(load_timing_info.request_start_time.is_null());
223  EXPECT_FALSE(load_timing_info.request_start.is_null());
224
225  ExpectConnectTimingHasNoTimes(load_timing_info.connect_timing);
226
227  EXPECT_TRUE(load_timing_info.proxy_resolve_start.is_null());
228  EXPECT_TRUE(load_timing_info.proxy_resolve_end.is_null());
229  EXPECT_TRUE(load_timing_info.send_start.is_null());
230  EXPECT_TRUE(load_timing_info.send_end.is_null());
231  EXPECT_TRUE(load_timing_info.receive_headers_end.is_null());
232}
233
234// Do a case-insensitive search through |haystack| for |needle|.
235bool ContainsString(const std::string& haystack, const char* needle) {
236  std::string::const_iterator it =
237      std::search(haystack.begin(),
238                  haystack.end(),
239                  needle,
240                  needle + strlen(needle),
241                  base::CaseInsensitiveCompare<char>());
242  return it != haystack.end();
243}
244
245UploadDataStream* CreateSimpleUploadData(const char* data) {
246  scoped_ptr<UploadElementReader> reader(
247      new UploadBytesElementReader(data, strlen(data)));
248  return UploadDataStream::CreateWithReader(reader.Pass(), 0);
249}
250
251// Verify that the SSLInfo of a successful SSL connection has valid values.
252void CheckSSLInfo(const SSLInfo& ssl_info) {
253  // -1 means unknown.  0 means no encryption.
254  EXPECT_GT(ssl_info.security_bits, 0);
255
256  // The cipher suite TLS_NULL_WITH_NULL_NULL (0) must not be negotiated.
257  int cipher_suite = SSLConnectionStatusToCipherSuite(
258      ssl_info.connection_status);
259  EXPECT_NE(0, cipher_suite);
260}
261
262void CheckFullRequestHeaders(const HttpRequestHeaders& headers,
263                             const GURL& host_url) {
264  std::string sent_value;
265
266  EXPECT_TRUE(headers.GetHeader("Host", &sent_value));
267  EXPECT_EQ(GetHostAndOptionalPort(host_url), sent_value);
268
269  EXPECT_TRUE(headers.GetHeader("Connection", &sent_value));
270  EXPECT_EQ("keep-alive", sent_value);
271}
272
273bool FingerprintsEqual(const HashValueVector& a, const HashValueVector& b) {
274  size_t size = a.size();
275
276  if (size != b.size())
277    return false;
278
279  for (size_t i = 0; i < size; ++i) {
280    if (!a[i].Equals(b[i]))
281      return false;
282  }
283
284  return true;
285}
286#endif  // !defined(OS_IOS)
287
288// A network delegate that allows the user to choose a subset of request stages
289// to block in. When blocking, the delegate can do one of the following:
290//  * synchronously return a pre-specified error code, or
291//  * asynchronously return that value via an automatically called callback,
292//    or
293//  * block and wait for the user to do a callback.
294// Additionally, the user may also specify a redirect URL -- then each request
295// with the current URL different from the redirect target will be redirected
296// to that target, in the on-before-URL-request stage, independent of whether
297// the delegate blocks in ON_BEFORE_URL_REQUEST or not.
298class BlockingNetworkDelegate : public TestNetworkDelegate {
299 public:
300  // Stages in which the delegate can block.
301  enum Stage {
302    NOT_BLOCKED = 0,
303    ON_BEFORE_URL_REQUEST = 1 << 0,
304    ON_BEFORE_SEND_HEADERS = 1 << 1,
305    ON_HEADERS_RECEIVED = 1 << 2,
306    ON_AUTH_REQUIRED = 1 << 3
307  };
308
309  // Behavior during blocked stages.  During other stages, just
310  // returns OK or NetworkDelegate::AUTH_REQUIRED_RESPONSE_NO_ACTION.
311  enum BlockMode {
312    SYNCHRONOUS,    // No callback, returns specified return values.
313    AUTO_CALLBACK,  // |this| posts a task to run the callback using the
314                    // specified return codes.
315    USER_CALLBACK,  // User takes care of doing a callback.  |retval_| and
316                    // |auth_retval_| are ignored. In every blocking stage the
317                    // message loop is quit.
318  };
319
320  // Creates a delegate which does not block at all.
321  explicit BlockingNetworkDelegate(BlockMode block_mode);
322
323  // For users to trigger a callback returning |response|.
324  // Side-effects: resets |stage_blocked_for_callback_| and stored callbacks.
325  // Only call if |block_mode_| == USER_CALLBACK.
326  void DoCallback(int response);
327  void DoAuthCallback(NetworkDelegate::AuthRequiredResponse response);
328
329  // Setters.
330  void set_retval(int retval) {
331    ASSERT_NE(USER_CALLBACK, block_mode_);
332    ASSERT_NE(ERR_IO_PENDING, retval);
333    ASSERT_NE(OK, retval);
334    retval_ = retval;
335  }
336
337  // If |auth_retval| == AUTH_REQUIRED_RESPONSE_SET_AUTH, then
338  // |auth_credentials_| will be passed with the response.
339  void set_auth_retval(AuthRequiredResponse auth_retval) {
340    ASSERT_NE(USER_CALLBACK, block_mode_);
341    ASSERT_NE(AUTH_REQUIRED_RESPONSE_IO_PENDING, auth_retval);
342    auth_retval_ = auth_retval;
343  }
344  void set_auth_credentials(const AuthCredentials& auth_credentials) {
345    auth_credentials_ = auth_credentials;
346  }
347
348  void set_redirect_url(const GURL& url) {
349    redirect_url_ = url;
350  }
351
352  void set_block_on(int block_on) {
353    block_on_ = block_on;
354  }
355
356  // Allows the user to check in which state did we block.
357  Stage stage_blocked_for_callback() const {
358    EXPECT_EQ(USER_CALLBACK, block_mode_);
359    return stage_blocked_for_callback_;
360  }
361
362 private:
363  void RunCallback(int response, const CompletionCallback& callback);
364  void RunAuthCallback(AuthRequiredResponse response,
365                       const AuthCallback& callback);
366
367  // TestNetworkDelegate implementation.
368  virtual int OnBeforeURLRequest(URLRequest* request,
369                                 const CompletionCallback& callback,
370                                 GURL* new_url) OVERRIDE;
371
372  virtual int OnBeforeSendHeaders(URLRequest* request,
373                                  const CompletionCallback& callback,
374                                  HttpRequestHeaders* headers) OVERRIDE;
375
376  virtual int OnHeadersReceived(
377      URLRequest* request,
378      const CompletionCallback& callback,
379      const HttpResponseHeaders* original_response_headers,
380      scoped_refptr<HttpResponseHeaders>* override_response_headers,
381      GURL* allowed_unsafe_redirect_url) OVERRIDE;
382
383  virtual NetworkDelegate::AuthRequiredResponse OnAuthRequired(
384      URLRequest* request,
385      const AuthChallengeInfo& auth_info,
386      const AuthCallback& callback,
387      AuthCredentials* credentials) OVERRIDE;
388
389  // Resets the callbacks and |stage_blocked_for_callback_|.
390  void Reset();
391
392  // Checks whether we should block in |stage|. If yes, returns an error code
393  // and optionally sets up callback based on |block_mode_|. If no, returns OK.
394  int MaybeBlockStage(Stage stage, const CompletionCallback& callback);
395
396  // Configuration parameters, can be adjusted by public methods:
397  const BlockMode block_mode_;
398
399  // Values returned on blocking stages when mode is SYNCHRONOUS or
400  // AUTO_CALLBACK. For USER_CALLBACK these are set automatically to IO_PENDING.
401  int retval_;  // To be returned in non-auth stages.
402  AuthRequiredResponse auth_retval_;
403
404  GURL redirect_url_;  // Used if non-empty during OnBeforeURLRequest.
405  int block_on_;  // Bit mask: in which stages to block.
406
407  // |auth_credentials_| will be copied to |*target_auth_credential_| on
408  // callback.
409  AuthCredentials auth_credentials_;
410  AuthCredentials* target_auth_credentials_;
411
412  // Internal variables, not set by not the user:
413  // Last blocked stage waiting for user callback (unused if |block_mode_| !=
414  // USER_CALLBACK).
415  Stage stage_blocked_for_callback_;
416
417  // Callback objects stored during blocking stages.
418  CompletionCallback callback_;
419  AuthCallback auth_callback_;
420
421  base::WeakPtrFactory<BlockingNetworkDelegate> weak_factory_;
422
423  DISALLOW_COPY_AND_ASSIGN(BlockingNetworkDelegate);
424};
425
426BlockingNetworkDelegate::BlockingNetworkDelegate(BlockMode block_mode)
427    : block_mode_(block_mode),
428      retval_(OK),
429      auth_retval_(AUTH_REQUIRED_RESPONSE_NO_ACTION),
430      block_on_(0),
431      target_auth_credentials_(NULL),
432      stage_blocked_for_callback_(NOT_BLOCKED),
433      weak_factory_(this) {
434}
435
436void BlockingNetworkDelegate::DoCallback(int response) {
437  ASSERT_EQ(USER_CALLBACK, block_mode_);
438  ASSERT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
439  ASSERT_NE(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
440  CompletionCallback callback = callback_;
441  Reset();
442  RunCallback(response, callback);
443}
444
445void BlockingNetworkDelegate::DoAuthCallback(
446    NetworkDelegate::AuthRequiredResponse response) {
447  ASSERT_EQ(USER_CALLBACK, block_mode_);
448  ASSERT_EQ(ON_AUTH_REQUIRED, stage_blocked_for_callback_);
449  AuthCallback auth_callback = auth_callback_;
450  Reset();
451  RunAuthCallback(response, auth_callback);
452}
453
454void BlockingNetworkDelegate::RunCallback(int response,
455                                          const CompletionCallback& callback) {
456  callback.Run(response);
457}
458
459void BlockingNetworkDelegate::RunAuthCallback(AuthRequiredResponse response,
460                                              const AuthCallback& callback) {
461  if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH) {
462    ASSERT_TRUE(target_auth_credentials_ != NULL);
463    *target_auth_credentials_ = auth_credentials_;
464  }
465  callback.Run(response);
466}
467
468int BlockingNetworkDelegate::OnBeforeURLRequest(
469    URLRequest* request,
470    const CompletionCallback& callback,
471    GURL* new_url) {
472  if (redirect_url_ == request->url())
473    return OK;  // We've already seen this request and redirected elsewhere.
474
475  TestNetworkDelegate::OnBeforeURLRequest(request, callback, new_url);
476
477  if (!redirect_url_.is_empty())
478    *new_url = redirect_url_;
479
480  return MaybeBlockStage(ON_BEFORE_URL_REQUEST, callback);
481}
482
483int BlockingNetworkDelegate::OnBeforeSendHeaders(
484    URLRequest* request,
485    const CompletionCallback& callback,
486    HttpRequestHeaders* headers) {
487  TestNetworkDelegate::OnBeforeSendHeaders(request, callback, headers);
488
489  return MaybeBlockStage(ON_BEFORE_SEND_HEADERS, callback);
490}
491
492int BlockingNetworkDelegate::OnHeadersReceived(
493    URLRequest* request,
494    const CompletionCallback& callback,
495    const HttpResponseHeaders* original_response_headers,
496    scoped_refptr<HttpResponseHeaders>* override_response_headers,
497    GURL* allowed_unsafe_redirect_url) {
498  TestNetworkDelegate::OnHeadersReceived(request,
499                                         callback,
500                                         original_response_headers,
501                                         override_response_headers,
502                                         allowed_unsafe_redirect_url);
503
504  return MaybeBlockStage(ON_HEADERS_RECEIVED, callback);
505}
506
507NetworkDelegate::AuthRequiredResponse BlockingNetworkDelegate::OnAuthRequired(
508    URLRequest* request,
509    const AuthChallengeInfo& auth_info,
510    const AuthCallback& callback,
511    AuthCredentials* credentials) {
512  TestNetworkDelegate::OnAuthRequired(request, auth_info, callback,
513                                      credentials);
514  // Check that the user has provided callback for the previous blocked stage.
515  EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
516
517  if ((block_on_ & ON_AUTH_REQUIRED) == 0) {
518    return AUTH_REQUIRED_RESPONSE_NO_ACTION;
519  }
520
521  target_auth_credentials_ = credentials;
522
523  switch (block_mode_) {
524    case SYNCHRONOUS:
525      if (auth_retval_ == AUTH_REQUIRED_RESPONSE_SET_AUTH)
526        *target_auth_credentials_ = auth_credentials_;
527      return auth_retval_;
528
529    case AUTO_CALLBACK:
530      base::MessageLoop::current()->PostTask(
531          FROM_HERE,
532          base::Bind(&BlockingNetworkDelegate::RunAuthCallback,
533                     weak_factory_.GetWeakPtr(), auth_retval_, callback));
534      return AUTH_REQUIRED_RESPONSE_IO_PENDING;
535
536    case USER_CALLBACK:
537      auth_callback_ = callback;
538      stage_blocked_for_callback_ = ON_AUTH_REQUIRED;
539      base::MessageLoop::current()->PostTask(FROM_HERE,
540                                             base::MessageLoop::QuitClosure());
541      return AUTH_REQUIRED_RESPONSE_IO_PENDING;
542  }
543  NOTREACHED();
544  return AUTH_REQUIRED_RESPONSE_NO_ACTION;  // Dummy value.
545}
546
547void BlockingNetworkDelegate::Reset() {
548  EXPECT_NE(NOT_BLOCKED, stage_blocked_for_callback_);
549  stage_blocked_for_callback_ = NOT_BLOCKED;
550  callback_.Reset();
551  auth_callback_.Reset();
552}
553
554int BlockingNetworkDelegate::MaybeBlockStage(
555    BlockingNetworkDelegate::Stage stage,
556    const CompletionCallback& callback) {
557  // Check that the user has provided callback for the previous blocked stage.
558  EXPECT_EQ(NOT_BLOCKED, stage_blocked_for_callback_);
559
560  if ((block_on_ & stage) == 0) {
561    return OK;
562  }
563
564  switch (block_mode_) {
565    case SYNCHRONOUS:
566      EXPECT_NE(OK, retval_);
567      return retval_;
568
569    case AUTO_CALLBACK:
570      base::MessageLoop::current()->PostTask(
571          FROM_HERE,
572          base::Bind(&BlockingNetworkDelegate::RunCallback,
573                     weak_factory_.GetWeakPtr(), retval_, callback));
574      return ERR_IO_PENDING;
575
576    case USER_CALLBACK:
577      callback_ = callback;
578      stage_blocked_for_callback_ = stage;
579      base::MessageLoop::current()->PostTask(FROM_HERE,
580                                             base::MessageLoop::QuitClosure());
581      return ERR_IO_PENDING;
582  }
583  NOTREACHED();
584  return 0;
585}
586
587class TestURLRequestContextWithProxy : public TestURLRequestContext {
588 public:
589  // Does not own |delegate|.
590  TestURLRequestContextWithProxy(const std::string& proxy,
591                                 NetworkDelegate* delegate)
592      : TestURLRequestContext(true) {
593    context_storage_.set_proxy_service(ProxyService::CreateFixed(proxy));
594    set_network_delegate(delegate);
595    Init();
596  }
597  virtual ~TestURLRequestContextWithProxy() {}
598};
599
600}  // namespace
601
602// Inherit PlatformTest since we require the autorelease pool on Mac OS X.
603class URLRequestTest : public PlatformTest {
604 public:
605  URLRequestTest() : default_context_(true) {
606    default_context_.set_network_delegate(&default_network_delegate_);
607    default_context_.set_net_log(&net_log_);
608    job_factory_.SetProtocolHandler("data", new DataProtocolHandler);
609#if !defined(DISABLE_FILE_SUPPORT)
610    job_factory_.SetProtocolHandler(
611        "file", new FileProtocolHandler(base::MessageLoopProxy::current()));
612#endif
613    default_context_.set_job_factory(&job_factory_);
614    default_context_.Init();
615  }
616  virtual ~URLRequestTest() {
617    // URLRequestJobs may post clean-up tasks on destruction.
618    base::RunLoop().RunUntilIdle();
619  }
620
621  // Adds the TestJobInterceptor to the default context.
622  TestJobInterceptor* AddTestInterceptor() {
623    TestJobInterceptor* protocol_handler_ = new TestJobInterceptor();
624    job_factory_.SetProtocolHandler("http", NULL);
625    job_factory_.SetProtocolHandler("http", protocol_handler_);
626    return protocol_handler_;
627  }
628
629 protected:
630  CapturingNetLog net_log_;
631  TestNetworkDelegate default_network_delegate_;  // Must outlive URLRequest.
632  URLRequestJobFactoryImpl job_factory_;
633  TestURLRequestContext default_context_;
634};
635
636TEST_F(URLRequestTest, AboutBlankTest) {
637  TestDelegate d;
638  {
639    scoped_ptr<URLRequest> r(default_context_.CreateRequest(
640        GURL("about:blank"), DEFAULT_PRIORITY, &d, NULL));
641
642    r->Start();
643    EXPECT_TRUE(r->is_pending());
644
645    base::RunLoop().Run();
646
647    EXPECT_TRUE(!r->is_pending());
648    EXPECT_FALSE(d.received_data_before_response());
649    EXPECT_EQ(d.bytes_received(), 0);
650    EXPECT_EQ("", r->GetSocketAddress().host());
651    EXPECT_EQ(0, r->GetSocketAddress().port());
652
653    HttpRequestHeaders headers;
654    EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
655  }
656}
657
658TEST_F(URLRequestTest, DataURLImageTest) {
659  TestDelegate d;
660  {
661    // Use our nice little Chrome logo.
662    scoped_ptr<URLRequest> r(default_context_.CreateRequest(
663        GURL(
664        "data:image/png;base64,"
665        "iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9hAAADVklEQVQ4jX2TfUwUBBjG3"
666        "w1y+HGcd9dxhXR8T4awOccJGgOSWclHImznLkTlSw0DDQXkrmgYgbUYnlQTqQxIEVxitD"
667        "5UMCATRA1CEEg+Qjw3bWDxIauJv/5oumqs39/P827vnucRmYN0gyF01GI5MpCVdW0gO7t"
668        "vNC+vqSEtbZefk5NuLv1jdJ46p/zw0HeH4+PHr3h7c1mjoV2t5rKzMx1+fg9bAgK6zHq9"
669        "cU5z+LpA3xOtx34+vTeT21onRuzssC3zxbbSwC13d/pFuC7CkIMDxQpF7r/MWq12UctI1"
670        "dWWm99ypqSYmRUBdKem8MkrO/kgaTt1O7YzlpzE5GIVd0WYUqt57yWf2McHTObYPbVD+Z"
671        "wbtlLTVMZ3BW+TnLyXLaWtmEq6WJVbT3HBh3Svj2HQQcm43XwmtoYM6vVKleh0uoWvnzW"
672        "3v3MpidruPTQPf0bia7sJOtBM0ufTWNvus/nkDFHF9ZS+uYVjRUasMeHUmyLYtcklTvzW"
673        "GFZnNOXczThvpKIzjcahSqIzkvDLayDq6D3eOjtBbNUEIZYyqsvj4V4wY92eNJ4IoyhTb"
674        "xXX1T5xsV9tm9r4TQwHLiZw/pdDZJea8TKmsmR/K0uLh/GwnCHghTja6lPhphezPfO5/5"
675        "MrVvMzNaI3+ERHfrFzPKQukrQGI4d/3EFD/3E2mVNYvi4at7CXWREaxZGD+3hg28zD3gV"
676        "Md6q5c8GdosynKmSeRuGzpjyl1/9UDGtPR5HeaKT8Wjo17WXk579BXVUhN64ehF9fhRtq"
677        "/uxxZKzNiZFGD0wRC3NFROZ5mwIPL/96K/rKMMLrIzF9uhHr+/sYH7DAbwlgC4J+R2Z7F"
678        "Ux1qLnV7MGF40smVSoJ/jvHRfYhQeUJd/SnYtGWhPHR0Sz+GE2F2yth0B36Vcz2KpnufB"
679        "JbsysjjW4kblBUiIjiURUWqJY65zxbnTy57GQyH58zgy0QBtTQv5gH15XMdKkYu+TGaJM"
680        "nlm2O34uI4b9tflqp1+QEFGzoW/ulmcofcpkZCYJhDfSpme7QcrHa+Xfji8paEQkTkSfm"
681        "moRWRNZr/F1KfVMjW+IKEnv2FwZfKdzt0BQR6lClcZR0EfEXEfv/G6W9iLiIyCoReV5En"
682        "hORIBHx+ufPj/gLB/zGI/G4Bk0AAAAASUVORK5CYII="),
683        DEFAULT_PRIORITY, &d, NULL));
684
685    r->Start();
686    EXPECT_TRUE(r->is_pending());
687
688    base::RunLoop().Run();
689
690    EXPECT_TRUE(!r->is_pending());
691    EXPECT_FALSE(d.received_data_before_response());
692    EXPECT_EQ(d.bytes_received(), 911);
693    EXPECT_EQ("", r->GetSocketAddress().host());
694    EXPECT_EQ(0, r->GetSocketAddress().port());
695
696    HttpRequestHeaders headers;
697    EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
698  }
699}
700
701#if !defined(DISABLE_FILE_SUPPORT)
702TEST_F(URLRequestTest, FileTest) {
703  base::FilePath app_path;
704  PathService::Get(base::FILE_EXE, &app_path);
705  GURL app_url = FilePathToFileURL(app_path);
706
707  TestDelegate d;
708  {
709    scoped_ptr<URLRequest> r(default_context_.CreateRequest(
710        app_url, DEFAULT_PRIORITY, &d, NULL));
711
712    r->Start();
713    EXPECT_TRUE(r->is_pending());
714
715    base::RunLoop().Run();
716
717    int64 file_size = -1;
718    EXPECT_TRUE(base::GetFileSize(app_path, &file_size));
719
720    EXPECT_TRUE(!r->is_pending());
721    EXPECT_EQ(1, d.response_started_count());
722    EXPECT_FALSE(d.received_data_before_response());
723    EXPECT_EQ(d.bytes_received(), static_cast<int>(file_size));
724    EXPECT_EQ("", r->GetSocketAddress().host());
725    EXPECT_EQ(0, r->GetSocketAddress().port());
726
727    HttpRequestHeaders headers;
728    EXPECT_FALSE(r->GetFullRequestHeaders(&headers));
729  }
730}
731
732TEST_F(URLRequestTest, FileTestCancel) {
733  base::FilePath app_path;
734  PathService::Get(base::FILE_EXE, &app_path);
735  GURL app_url = FilePathToFileURL(app_path);
736
737  TestDelegate d;
738  {
739    scoped_ptr<URLRequest> r(default_context_.CreateRequest(
740        app_url, DEFAULT_PRIORITY, &d, NULL));
741
742    r->Start();
743    EXPECT_TRUE(r->is_pending());
744    r->Cancel();
745  }
746  // Async cancellation should be safe even when URLRequest has been already
747  // destroyed.
748  base::RunLoop().RunUntilIdle();
749}
750
751TEST_F(URLRequestTest, FileTestFullSpecifiedRange) {
752  const size_t buffer_size = 4000;
753  scoped_ptr<char[]> buffer(new char[buffer_size]);
754  FillBuffer(buffer.get(), buffer_size);
755
756  base::FilePath temp_path;
757  EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
758  GURL temp_url = FilePathToFileURL(temp_path);
759  EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
760
761  int64 file_size;
762  EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
763
764  const size_t first_byte_position = 500;
765  const size_t last_byte_position = buffer_size - first_byte_position;
766  const size_t content_length = last_byte_position - first_byte_position + 1;
767  std::string partial_buffer_string(buffer.get() + first_byte_position,
768                                    buffer.get() + last_byte_position + 1);
769
770  TestDelegate d;
771  {
772    scoped_ptr<URLRequest> r(default_context_.CreateRequest(
773        temp_url, DEFAULT_PRIORITY, &d, NULL));
774
775    HttpRequestHeaders headers;
776    headers.SetHeader(
777        HttpRequestHeaders::kRange,
778        HttpByteRange::Bounded(
779            first_byte_position, last_byte_position).GetHeaderValue());
780    r->SetExtraRequestHeaders(headers);
781    r->Start();
782    EXPECT_TRUE(r->is_pending());
783
784    base::RunLoop().Run();
785    EXPECT_TRUE(!r->is_pending());
786    EXPECT_EQ(1, d.response_started_count());
787    EXPECT_FALSE(d.received_data_before_response());
788    EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
789    // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
790    EXPECT_TRUE(partial_buffer_string == d.data_received());
791  }
792
793  EXPECT_TRUE(base::DeleteFile(temp_path, false));
794}
795
796TEST_F(URLRequestTest, FileTestHalfSpecifiedRange) {
797  const size_t buffer_size = 4000;
798  scoped_ptr<char[]> buffer(new char[buffer_size]);
799  FillBuffer(buffer.get(), buffer_size);
800
801  base::FilePath temp_path;
802  EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
803  GURL temp_url = FilePathToFileURL(temp_path);
804  EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
805
806  int64 file_size;
807  EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
808
809  const size_t first_byte_position = 500;
810  const size_t last_byte_position = buffer_size - 1;
811  const size_t content_length = last_byte_position - first_byte_position + 1;
812  std::string partial_buffer_string(buffer.get() + first_byte_position,
813                                    buffer.get() + last_byte_position + 1);
814
815  TestDelegate d;
816  {
817    scoped_ptr<URLRequest> r(default_context_.CreateRequest(
818        temp_url, DEFAULT_PRIORITY, &d, NULL));
819
820    HttpRequestHeaders headers;
821    headers.SetHeader(HttpRequestHeaders::kRange,
822                      HttpByteRange::RightUnbounded(
823                          first_byte_position).GetHeaderValue());
824    r->SetExtraRequestHeaders(headers);
825    r->Start();
826    EXPECT_TRUE(r->is_pending());
827
828    base::RunLoop().Run();
829    EXPECT_TRUE(!r->is_pending());
830    EXPECT_EQ(1, d.response_started_count());
831    EXPECT_FALSE(d.received_data_before_response());
832    EXPECT_EQ(static_cast<int>(content_length), d.bytes_received());
833    // Don't use EXPECT_EQ, it will print out a lot of garbage if check failed.
834    EXPECT_TRUE(partial_buffer_string == d.data_received());
835  }
836
837  EXPECT_TRUE(base::DeleteFile(temp_path, false));
838}
839
840TEST_F(URLRequestTest, FileTestMultipleRanges) {
841  const size_t buffer_size = 400000;
842  scoped_ptr<char[]> buffer(new char[buffer_size]);
843  FillBuffer(buffer.get(), buffer_size);
844
845  base::FilePath temp_path;
846  EXPECT_TRUE(base::CreateTemporaryFile(&temp_path));
847  GURL temp_url = FilePathToFileURL(temp_path);
848  EXPECT_TRUE(base::WriteFile(temp_path, buffer.get(), buffer_size));
849
850  int64 file_size;
851  EXPECT_TRUE(base::GetFileSize(temp_path, &file_size));
852
853  TestDelegate d;
854  {
855    scoped_ptr<URLRequest> r(default_context_.CreateRequest(
856        temp_url, DEFAULT_PRIORITY, &d, NULL));
857
858    HttpRequestHeaders headers;
859    headers.SetHeader(HttpRequestHeaders::kRange, "bytes=0-0,10-200,200-300");
860    r->SetExtraRequestHeaders(headers);
861    r->Start();
862    EXPECT_TRUE(r->is_pending());
863
864    base::RunLoop().Run();
865    EXPECT_TRUE(d.request_failed());
866  }
867
868  EXPECT_TRUE(base::DeleteFile(temp_path, false));
869}
870
871TEST_F(URLRequestTest, AllowFileURLs) {
872  base::ScopedTempDir temp_dir;
873  ASSERT_TRUE(temp_dir.CreateUniqueTempDir());
874  base::FilePath test_file;
875  ASSERT_TRUE(base::CreateTemporaryFileInDir(temp_dir.path(), &test_file));
876  std::string test_data("monkey");
877  base::WriteFile(test_file, test_data.data(), test_data.size());
878  GURL test_file_url = FilePathToFileURL(test_file);
879
880  {
881    TestDelegate d;
882    TestNetworkDelegate network_delegate;
883    network_delegate.set_can_access_files(true);
884    default_context_.set_network_delegate(&network_delegate);
885    scoped_ptr<URLRequest> r(default_context_.CreateRequest(
886        test_file_url, DEFAULT_PRIORITY, &d, NULL));
887    r->Start();
888    base::RunLoop().Run();
889    EXPECT_FALSE(d.request_failed());
890    EXPECT_EQ(test_data, d.data_received());
891  }
892
893  {
894    TestDelegate d;
895    TestNetworkDelegate network_delegate;
896    network_delegate.set_can_access_files(false);
897    default_context_.set_network_delegate(&network_delegate);
898    scoped_ptr<URLRequest> r(default_context_.CreateRequest(
899        test_file_url, DEFAULT_PRIORITY, &d, NULL));
900    r->Start();
901    base::RunLoop().Run();
902    EXPECT_TRUE(d.request_failed());
903    EXPECT_EQ("", d.data_received());
904  }
905}
906
907
908TEST_F(URLRequestTest, FileDirCancelTest) {
909  // Put in mock resource provider.
910  NetModule::SetResourceProvider(TestNetResourceProvider);
911
912  TestDelegate d;
913  {
914    base::FilePath file_path;
915    PathService::Get(base::DIR_SOURCE_ROOT, &file_path);
916    file_path = file_path.Append(FILE_PATH_LITERAL("net"));
917    file_path = file_path.Append(FILE_PATH_LITERAL("data"));
918
919    scoped_ptr<URLRequest> req(default_context_.CreateRequest(
920        FilePathToFileURL(file_path), DEFAULT_PRIORITY, &d, NULL));
921    req->Start();
922    EXPECT_TRUE(req->is_pending());
923
924    d.set_cancel_in_received_data_pending(true);
925
926    base::RunLoop().Run();
927  }
928
929  // Take out mock resource provider.
930  NetModule::SetResourceProvider(NULL);
931}
932
933TEST_F(URLRequestTest, FileDirOutputSanity) {
934  // Verify the general sanity of the the output of the file:
935  // directory lister by checking for the output of a known existing
936  // file.
937  const char sentinel_name[] = "filedir-sentinel";
938
939  base::FilePath path;
940  PathService::Get(base::DIR_SOURCE_ROOT, &path);
941  path = path.Append(FILE_PATH_LITERAL("net"));
942  path = path.Append(FILE_PATH_LITERAL("data"));
943  path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
944
945  TestDelegate d;
946  scoped_ptr<URLRequest> req(default_context_.CreateRequest(
947      FilePathToFileURL(path), DEFAULT_PRIORITY, &d, NULL));
948  req->Start();
949  base::RunLoop().Run();
950
951  // Generate entry for the sentinel file.
952  base::FilePath sentinel_path = path.AppendASCII(sentinel_name);
953  base::File::Info info;
954  EXPECT_TRUE(base::GetFileInfo(sentinel_path, &info));
955  EXPECT_GT(info.size, 0);
956  std::string sentinel_output = GetDirectoryListingEntry(
957      base::string16(sentinel_name, sentinel_name + strlen(sentinel_name)),
958      std::string(sentinel_name),
959      false /* is_dir */,
960      info.size,
961      info.last_modified);
962
963  ASSERT_LT(0, d.bytes_received());
964  ASSERT_FALSE(d.request_failed());
965  ASSERT_TRUE(req->status().is_success());
966  // Check for the entry generated for the "sentinel" file.
967  const std::string& data = d.data_received();
968  ASSERT_NE(data.find(sentinel_output), std::string::npos);
969}
970
971TEST_F(URLRequestTest, FileDirRedirectNoCrash) {
972  // There is an implicit redirect when loading a file path that matches a
973  // directory and does not end with a slash.  Ensure that following such
974  // redirects does not crash.  See http://crbug.com/18686.
975
976  base::FilePath path;
977  PathService::Get(base::DIR_SOURCE_ROOT, &path);
978  path = path.Append(FILE_PATH_LITERAL("net"));
979  path = path.Append(FILE_PATH_LITERAL("data"));
980  path = path.Append(FILE_PATH_LITERAL("url_request_unittest"));
981
982  TestDelegate d;
983  scoped_ptr<URLRequest> req(default_context_.CreateRequest(
984      FilePathToFileURL(path), DEFAULT_PRIORITY, &d, NULL));
985  req->Start();
986  base::RunLoop().Run();
987
988  ASSERT_EQ(1, d.received_redirect_count());
989  ASSERT_LT(0, d.bytes_received());
990  ASSERT_FALSE(d.request_failed());
991  ASSERT_TRUE(req->status().is_success());
992}
993
994#if defined(OS_WIN)
995// Don't accept the url "file:///" on windows. See http://crbug.com/1474.
996TEST_F(URLRequestTest, FileDirRedirectSingleSlash) {
997  TestDelegate d;
998  scoped_ptr<URLRequest> req(default_context_.CreateRequest(
999      GURL("file:///"), DEFAULT_PRIORITY, &d, NULL));
1000  req->Start();
1001  base::RunLoop().Run();
1002
1003  ASSERT_EQ(1, d.received_redirect_count());
1004  ASSERT_FALSE(req->status().is_success());
1005}
1006#endif  // defined(OS_WIN)
1007
1008#endif  // !defined(DISABLE_FILE_SUPPORT)
1009
1010TEST_F(URLRequestTest, InvalidUrlTest) {
1011  TestDelegate d;
1012  {
1013    scoped_ptr<URLRequest> r(default_context_.CreateRequest(
1014        GURL("invalid url"), DEFAULT_PRIORITY, &d, NULL));
1015
1016    r->Start();
1017    EXPECT_TRUE(r->is_pending());
1018
1019    base::RunLoop().Run();
1020    EXPECT_TRUE(d.request_failed());
1021  }
1022}
1023
1024TEST_F(URLRequestTest, InvalidReferrerTest) {
1025  TestURLRequestContext context;
1026  TestNetworkDelegate network_delegate;
1027  network_delegate.set_cancel_request_with_policy_violating_referrer(true);
1028  context.set_network_delegate(&network_delegate);
1029  TestDelegate d;
1030  scoped_ptr<URLRequest> req(context.CreateRequest(
1031      GURL("http://localhost/"), DEFAULT_PRIORITY, &d, NULL));
1032  req->SetReferrer("https://somewhere.com/");
1033
1034  req->Start();
1035  base::RunLoop().Run();
1036  EXPECT_TRUE(d.request_failed());
1037}
1038
1039#if defined(OS_WIN)
1040TEST_F(URLRequestTest, ResolveShortcutTest) {
1041  base::FilePath app_path;
1042  PathService::Get(base::DIR_SOURCE_ROOT, &app_path);
1043  app_path = app_path.AppendASCII("net");
1044  app_path = app_path.AppendASCII("data");
1045  app_path = app_path.AppendASCII("url_request_unittest");
1046  app_path = app_path.AppendASCII("with-headers.html");
1047
1048  std::wstring lnk_path = app_path.value() + L".lnk";
1049
1050  base::win::ScopedCOMInitializer com_initializer;
1051
1052  // Temporarily create a shortcut for test
1053  {
1054    base::win::ScopedComPtr<IShellLink> shell;
1055    ASSERT_TRUE(SUCCEEDED(shell.CreateInstance(CLSID_ShellLink, NULL,
1056                                               CLSCTX_INPROC_SERVER)));
1057    base::win::ScopedComPtr<IPersistFile> persist;
1058    ASSERT_TRUE(SUCCEEDED(shell.QueryInterface(persist.Receive())));
1059    EXPECT_TRUE(SUCCEEDED(shell->SetPath(app_path.value().c_str())));
1060    EXPECT_TRUE(SUCCEEDED(shell->SetDescription(L"ResolveShortcutTest")));
1061    EXPECT_TRUE(SUCCEEDED(persist->Save(lnk_path.c_str(), TRUE)));
1062  }
1063
1064  TestDelegate d;
1065  {
1066    scoped_ptr<URLRequest> r(default_context_.CreateRequest(
1067        FilePathToFileURL(base::FilePath(lnk_path)), DEFAULT_PRIORITY, &d,
1068        NULL));
1069
1070    r->Start();
1071    EXPECT_TRUE(r->is_pending());
1072
1073    base::RunLoop().Run();
1074
1075    WIN32_FILE_ATTRIBUTE_DATA data;
1076    GetFileAttributesEx(app_path.value().c_str(),
1077                        GetFileExInfoStandard, &data);
1078    HANDLE file = CreateFile(app_path.value().c_str(), GENERIC_READ,
1079                             FILE_SHARE_READ, NULL, OPEN_EXISTING,
1080                             FILE_ATTRIBUTE_NORMAL, NULL);
1081    EXPECT_NE(INVALID_HANDLE_VALUE, file);
1082    scoped_ptr<char[]> buffer(new char[data.nFileSizeLow]);
1083    DWORD read_size;
1084    BOOL result;
1085    result = ReadFile(file, buffer.get(), data.nFileSizeLow,
1086                      &read_size, NULL);
1087    std::string content(buffer.get(), read_size);
1088    CloseHandle(file);
1089
1090    EXPECT_TRUE(!r->is_pending());
1091    EXPECT_EQ(1, d.received_redirect_count());
1092    EXPECT_EQ(content, d.data_received());
1093  }
1094
1095  // Clean the shortcut
1096  DeleteFile(lnk_path.c_str());
1097}
1098#endif  // defined(OS_WIN)
1099
1100// Custom URLRequestJobs for use with interceptor tests
1101class RestartTestJob : public URLRequestTestJob {
1102 public:
1103  RestartTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1104    : URLRequestTestJob(request, network_delegate, true) {}
1105 protected:
1106  virtual void StartAsync() OVERRIDE {
1107    this->NotifyRestartRequired();
1108  }
1109 private:
1110  virtual ~RestartTestJob() {}
1111};
1112
1113class CancelTestJob : public URLRequestTestJob {
1114 public:
1115  explicit CancelTestJob(URLRequest* request, NetworkDelegate* network_delegate)
1116    : URLRequestTestJob(request, network_delegate, true) {}
1117 protected:
1118  virtual void StartAsync() OVERRIDE {
1119    request_->Cancel();
1120  }
1121 private:
1122  virtual ~CancelTestJob() {}
1123};
1124
1125class CancelThenRestartTestJob : public URLRequestTestJob {
1126 public:
1127  explicit CancelThenRestartTestJob(URLRequest* request,
1128                                    NetworkDelegate* network_delegate)
1129      : URLRequestTestJob(request, network_delegate, true) {
1130  }
1131 protected:
1132  virtual void StartAsync() OVERRIDE {
1133    request_->Cancel();
1134    this->NotifyRestartRequired();
1135  }
1136 private:
1137  virtual ~CancelThenRestartTestJob() {}
1138};
1139
1140// An Interceptor for use with interceptor tests
1141class TestInterceptor : URLRequest::Interceptor {
1142 public:
1143  TestInterceptor()
1144      : intercept_main_request_(false), restart_main_request_(false),
1145        cancel_main_request_(false), cancel_then_restart_main_request_(false),
1146        simulate_main_network_error_(false),
1147        intercept_redirect_(false), cancel_redirect_request_(false),
1148        intercept_final_response_(false), cancel_final_request_(false),
1149        did_intercept_main_(false), did_restart_main_(false),
1150        did_cancel_main_(false), did_cancel_then_restart_main_(false),
1151        did_simulate_error_main_(false),
1152        did_intercept_redirect_(false), did_cancel_redirect_(false),
1153        did_intercept_final_(false), did_cancel_final_(false) {
1154    URLRequest::Deprecated::RegisterRequestInterceptor(this);
1155  }
1156
1157  virtual ~TestInterceptor() {
1158    URLRequest::Deprecated::UnregisterRequestInterceptor(this);
1159  }
1160
1161  virtual URLRequestJob* MaybeIntercept(
1162      URLRequest* request,
1163      NetworkDelegate* network_delegate) OVERRIDE {
1164    if (restart_main_request_) {
1165      restart_main_request_ = false;
1166      did_restart_main_ = true;
1167      return new RestartTestJob(request, network_delegate);
1168    }
1169    if (cancel_main_request_) {
1170      cancel_main_request_ = false;
1171      did_cancel_main_ = true;
1172      return new CancelTestJob(request, network_delegate);
1173    }
1174    if (cancel_then_restart_main_request_) {
1175      cancel_then_restart_main_request_ = false;
1176      did_cancel_then_restart_main_ = true;
1177      return new CancelThenRestartTestJob(request, network_delegate);
1178    }
1179    if (simulate_main_network_error_) {
1180      simulate_main_network_error_ = false;
1181      did_simulate_error_main_ = true;
1182      // will error since the requeted url is not one of its canned urls
1183      return new URLRequestTestJob(request, network_delegate, true);
1184    }
1185    if (!intercept_main_request_)
1186      return NULL;
1187    intercept_main_request_ = false;
1188    did_intercept_main_ = true;
1189    URLRequestTestJob* job =  new URLRequestTestJob(request,
1190                                                    network_delegate,
1191                                                    main_headers_,
1192                                                    main_data_,
1193                                                    true);
1194    job->set_load_timing_info(main_request_load_timing_info_);
1195    return job;
1196  }
1197
1198  virtual URLRequestJob* MaybeInterceptRedirect(
1199      URLRequest* request,
1200      NetworkDelegate* network_delegate,
1201      const GURL& location) OVERRIDE {
1202    if (cancel_redirect_request_) {
1203      cancel_redirect_request_ = false;
1204      did_cancel_redirect_ = true;
1205      return new CancelTestJob(request, network_delegate);
1206    }
1207    if (!intercept_redirect_)
1208      return NULL;
1209    intercept_redirect_ = false;
1210    did_intercept_redirect_ = true;
1211    return new URLRequestTestJob(request,
1212                                 network_delegate,
1213                                 redirect_headers_,
1214                                 redirect_data_,
1215                                 true);
1216  }
1217
1218  virtual URLRequestJob* MaybeInterceptResponse(
1219      URLRequest* request, NetworkDelegate* network_delegate) OVERRIDE {
1220    if (cancel_final_request_) {
1221      cancel_final_request_ = false;
1222      did_cancel_final_ = true;
1223      return new CancelTestJob(request, network_delegate);
1224    }
1225    if (!intercept_final_response_)
1226      return NULL;
1227    intercept_final_response_ = false;
1228    did_intercept_final_ = true;
1229    return new URLRequestTestJob(request,
1230                                 network_delegate,
1231                                 final_headers_,
1232                                 final_data_,
1233                                 true);
1234  }
1235
1236  // Whether to intercept the main request, and if so the response to return and
1237  // the LoadTimingInfo to use.
1238  bool intercept_main_request_;
1239  std::string main_headers_;
1240  std::string main_data_;
1241  LoadTimingInfo main_request_load_timing_info_;
1242
1243  // Other actions we take at MaybeIntercept time
1244  bool restart_main_request_;
1245  bool cancel_main_request_;
1246  bool cancel_then_restart_main_request_;
1247  bool simulate_main_network_error_;
1248
1249  // Whether to intercept redirects, and if so the response to return.
1250  bool intercept_redirect_;
1251  std::string redirect_headers_;
1252  std::string redirect_data_;
1253
1254  // Other actions we can take at MaybeInterceptRedirect time
1255  bool cancel_redirect_request_;
1256
1257  // Whether to intercept final response, and if so the response to return.
1258  bool intercept_final_response_;
1259  std::string final_headers_;
1260  std::string final_data_;
1261
1262  // Other actions we can take at MaybeInterceptResponse time
1263  bool cancel_final_request_;
1264
1265  // If we did something or not
1266  bool did_intercept_main_;
1267  bool did_restart_main_;
1268  bool did_cancel_main_;
1269  bool did_cancel_then_restart_main_;
1270  bool did_simulate_error_main_;
1271  bool did_intercept_redirect_;
1272  bool did_cancel_redirect_;
1273  bool did_intercept_final_;
1274  bool did_cancel_final_;
1275
1276  // Static getters for canned response header and data strings
1277
1278  static std::string ok_data() {
1279    return URLRequestTestJob::test_data_1();
1280  }
1281
1282  static std::string ok_headers() {
1283    return URLRequestTestJob::test_headers();
1284  }
1285
1286  static std::string redirect_data() {
1287    return std::string();
1288  }
1289
1290  static std::string redirect_headers() {
1291    return URLRequestTestJob::test_redirect_headers();
1292  }
1293
1294  static std::string error_data() {
1295    return std::string("ohhh nooooo mr. bill!");
1296  }
1297
1298  static std::string error_headers() {
1299    return URLRequestTestJob::test_error_headers();
1300  }
1301};
1302
1303TEST_F(URLRequestTest, Intercept) {
1304  TestInterceptor interceptor;
1305
1306  // intercept the main request and respond with a simple response
1307  interceptor.intercept_main_request_ = true;
1308  interceptor.main_headers_ = TestInterceptor::ok_headers();
1309  interceptor.main_data_ = TestInterceptor::ok_data();
1310
1311  TestDelegate d;
1312  scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1313      GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
1314  base::SupportsUserData::Data* user_data0 = new base::SupportsUserData::Data();
1315  base::SupportsUserData::Data* user_data1 = new base::SupportsUserData::Data();
1316  base::SupportsUserData::Data* user_data2 = new base::SupportsUserData::Data();
1317  req->SetUserData(NULL, user_data0);
1318  req->SetUserData(&user_data1, user_data1);
1319  req->SetUserData(&user_data2, user_data2);
1320  req->set_method("GET");
1321  req->Start();
1322  base::RunLoop().Run();
1323
1324  // Make sure we can retrieve our specific user data
1325  EXPECT_EQ(user_data0, req->GetUserData(NULL));
1326  EXPECT_EQ(user_data1, req->GetUserData(&user_data1));
1327  EXPECT_EQ(user_data2, req->GetUserData(&user_data2));
1328
1329  // Check the interceptor got called as expected
1330  EXPECT_TRUE(interceptor.did_intercept_main_);
1331
1332  // Check we got one good response
1333  EXPECT_TRUE(req->status().is_success());
1334  EXPECT_EQ(200, req->response_headers()->response_code());
1335  EXPECT_EQ(TestInterceptor::ok_data(), d.data_received());
1336  EXPECT_EQ(1, d.response_started_count());
1337  EXPECT_EQ(0, d.received_redirect_count());
1338}
1339
1340TEST_F(URLRequestTest, InterceptRedirect) {
1341  TestInterceptor interceptor;
1342
1343  // intercept the main request and respond with a redirect
1344  interceptor.intercept_main_request_ = true;
1345  interceptor.main_headers_ = TestInterceptor::redirect_headers();
1346  interceptor.main_data_ = TestInterceptor::redirect_data();
1347
1348  // intercept that redirect and respond a final OK response
1349  interceptor.intercept_redirect_ = true;
1350  interceptor.redirect_headers_ =  TestInterceptor::ok_headers();
1351  interceptor.redirect_data_ = TestInterceptor::ok_data();
1352
1353  TestDelegate d;
1354  scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1355      GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
1356  req->set_method("GET");
1357  req->Start();
1358  base::RunLoop().Run();
1359
1360  // Check the interceptor got called as expected
1361  EXPECT_TRUE(interceptor.did_intercept_main_);
1362  EXPECT_TRUE(interceptor.did_intercept_redirect_);
1363
1364  // Check we got one good response
1365  EXPECT_TRUE(req->status().is_success());
1366  if (req->status().is_success()) {
1367    EXPECT_EQ(200, req->response_headers()->response_code());
1368  }
1369  EXPECT_EQ(TestInterceptor::ok_data(), d.data_received());
1370  EXPECT_EQ(1, d.response_started_count());
1371  EXPECT_EQ(0, d.received_redirect_count());
1372}
1373
1374TEST_F(URLRequestTest, InterceptServerError) {
1375  TestInterceptor interceptor;
1376
1377  // intercept the main request to generate a server error response
1378  interceptor.intercept_main_request_ = true;
1379  interceptor.main_headers_ = TestInterceptor::error_headers();
1380  interceptor.main_data_ = TestInterceptor::error_data();
1381
1382  // intercept that error and respond with an OK response
1383  interceptor.intercept_final_response_ = true;
1384  interceptor.final_headers_ = TestInterceptor::ok_headers();
1385  interceptor.final_data_ = TestInterceptor::ok_data();
1386
1387  TestDelegate d;
1388  scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1389      GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
1390  req->set_method("GET");
1391  req->Start();
1392  base::RunLoop().Run();
1393
1394  // Check the interceptor got called as expected
1395  EXPECT_TRUE(interceptor.did_intercept_main_);
1396  EXPECT_TRUE(interceptor.did_intercept_final_);
1397
1398  // Check we got one good response
1399  EXPECT_TRUE(req->status().is_success());
1400  EXPECT_EQ(200, req->response_headers()->response_code());
1401  EXPECT_EQ(TestInterceptor::ok_data(), d.data_received());
1402  EXPECT_EQ(1, d.response_started_count());
1403  EXPECT_EQ(0, d.received_redirect_count());
1404}
1405
1406TEST_F(URLRequestTest, InterceptNetworkError) {
1407  TestInterceptor interceptor;
1408
1409  // intercept the main request to simulate a network error
1410  interceptor.simulate_main_network_error_ = true;
1411
1412  // intercept that error and respond with an OK response
1413  interceptor.intercept_final_response_ = true;
1414  interceptor.final_headers_ = TestInterceptor::ok_headers();
1415  interceptor.final_data_ = TestInterceptor::ok_data();
1416
1417  TestDelegate d;
1418  scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1419      GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
1420  req->set_method("GET");
1421  req->Start();
1422  base::RunLoop().Run();
1423
1424  // Check the interceptor got called as expected
1425  EXPECT_TRUE(interceptor.did_simulate_error_main_);
1426  EXPECT_TRUE(interceptor.did_intercept_final_);
1427
1428  // Check we received one good response
1429  EXPECT_TRUE(req->status().is_success());
1430  EXPECT_EQ(200, req->response_headers()->response_code());
1431  EXPECT_EQ(TestInterceptor::ok_data(), d.data_received());
1432  EXPECT_EQ(1, d.response_started_count());
1433  EXPECT_EQ(0, d.received_redirect_count());
1434}
1435
1436TEST_F(URLRequestTest, InterceptRestartRequired) {
1437  TestInterceptor interceptor;
1438
1439  // restart the main request
1440  interceptor.restart_main_request_ = true;
1441
1442  // then intercept the new main request and respond with an OK response
1443  interceptor.intercept_main_request_ = true;
1444  interceptor.main_headers_ = TestInterceptor::ok_headers();
1445  interceptor.main_data_ = TestInterceptor::ok_data();
1446
1447  TestDelegate d;
1448  scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1449      GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
1450  req->set_method("GET");
1451  req->Start();
1452  base::RunLoop().Run();
1453
1454  // Check the interceptor got called as expected
1455  EXPECT_TRUE(interceptor.did_restart_main_);
1456  EXPECT_TRUE(interceptor.did_intercept_main_);
1457
1458  // Check we received one good response
1459  EXPECT_TRUE(req->status().is_success());
1460  if (req->status().is_success()) {
1461    EXPECT_EQ(200, req->response_headers()->response_code());
1462  }
1463  EXPECT_EQ(TestInterceptor::ok_data(), d.data_received());
1464  EXPECT_EQ(1, d.response_started_count());
1465  EXPECT_EQ(0, d.received_redirect_count());
1466}
1467
1468TEST_F(URLRequestTest, InterceptRespectsCancelMain) {
1469  TestInterceptor interceptor;
1470
1471  // intercept the main request and cancel from within the restarted job
1472  interceptor.cancel_main_request_ = true;
1473
1474  // setup to intercept final response and override it with an OK response
1475  interceptor.intercept_final_response_ = true;
1476  interceptor.final_headers_ = TestInterceptor::ok_headers();
1477  interceptor.final_data_ = TestInterceptor::ok_data();
1478
1479  TestDelegate d;
1480  scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1481      GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
1482  req->set_method("GET");
1483  req->Start();
1484  base::RunLoop().Run();
1485
1486  // Check the interceptor got called as expected
1487  EXPECT_TRUE(interceptor.did_cancel_main_);
1488  EXPECT_FALSE(interceptor.did_intercept_final_);
1489
1490  // Check we see a canceled request
1491  EXPECT_FALSE(req->status().is_success());
1492  EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
1493}
1494
1495TEST_F(URLRequestTest, InterceptRespectsCancelRedirect) {
1496  TestInterceptor interceptor;
1497
1498  // intercept the main request and respond with a redirect
1499  interceptor.intercept_main_request_ = true;
1500  interceptor.main_headers_ = TestInterceptor::redirect_headers();
1501  interceptor.main_data_ = TestInterceptor::redirect_data();
1502
1503  // intercept the redirect and cancel from within that job
1504  interceptor.cancel_redirect_request_ = true;
1505
1506  // setup to intercept final response and override it with an OK response
1507  interceptor.intercept_final_response_ = true;
1508  interceptor.final_headers_ = TestInterceptor::ok_headers();
1509  interceptor.final_data_ = TestInterceptor::ok_data();
1510
1511  TestDelegate d;
1512  scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1513      GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
1514  req->set_method("GET");
1515  req->Start();
1516  base::RunLoop().Run();
1517
1518  // Check the interceptor got called as expected
1519  EXPECT_TRUE(interceptor.did_intercept_main_);
1520  EXPECT_TRUE(interceptor.did_cancel_redirect_);
1521  EXPECT_FALSE(interceptor.did_intercept_final_);
1522
1523  // Check we see a canceled request
1524  EXPECT_FALSE(req->status().is_success());
1525  EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
1526}
1527
1528TEST_F(URLRequestTest, InterceptRespectsCancelFinal) {
1529  TestInterceptor interceptor;
1530
1531  // intercept the main request to simulate a network error
1532  interceptor.simulate_main_network_error_ = true;
1533
1534  // setup to intercept final response and cancel from within that job
1535  interceptor.cancel_final_request_ = true;
1536
1537  TestDelegate d;
1538  scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1539      GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
1540  req->set_method("GET");
1541  req->Start();
1542  base::RunLoop().Run();
1543
1544  // Check the interceptor got called as expected
1545  EXPECT_TRUE(interceptor.did_simulate_error_main_);
1546  EXPECT_TRUE(interceptor.did_cancel_final_);
1547
1548  // Check we see a canceled request
1549  EXPECT_FALSE(req->status().is_success());
1550  EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
1551}
1552
1553TEST_F(URLRequestTest, InterceptRespectsCancelInRestart) {
1554  TestInterceptor interceptor;
1555
1556  // intercept the main request and cancel then restart from within that job
1557  interceptor.cancel_then_restart_main_request_ = true;
1558
1559  // setup to intercept final response and override it with an OK response
1560  interceptor.intercept_final_response_ = true;
1561  interceptor.final_headers_ = TestInterceptor::ok_headers();
1562  interceptor.final_data_ = TestInterceptor::ok_data();
1563
1564  TestDelegate d;
1565  scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1566      GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
1567  req->set_method("GET");
1568  req->Start();
1569  base::RunLoop().Run();
1570
1571  // Check the interceptor got called as expected
1572  EXPECT_TRUE(interceptor.did_cancel_then_restart_main_);
1573  EXPECT_FALSE(interceptor.did_intercept_final_);
1574
1575  // Check we see a canceled request
1576  EXPECT_FALSE(req->status().is_success());
1577  EXPECT_EQ(URLRequestStatus::CANCELED, req->status().status());
1578}
1579
1580LoadTimingInfo RunLoadTimingTest(const LoadTimingInfo& job_load_timing,
1581                                 URLRequestContext* context) {
1582  TestInterceptor interceptor;
1583  interceptor.intercept_main_request_ = true;
1584  interceptor.main_request_load_timing_info_ = job_load_timing;
1585  TestDelegate d;
1586  scoped_ptr<URLRequest> req(context->CreateRequest(
1587      GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
1588  req->Start();
1589  base::RunLoop().Run();
1590
1591  LoadTimingInfo resulting_load_timing;
1592  req->GetLoadTimingInfo(&resulting_load_timing);
1593
1594  // None of these should be modified by the URLRequest.
1595  EXPECT_EQ(job_load_timing.socket_reused, resulting_load_timing.socket_reused);
1596  EXPECT_EQ(job_load_timing.socket_log_id, resulting_load_timing.socket_log_id);
1597  EXPECT_EQ(job_load_timing.send_start, resulting_load_timing.send_start);
1598  EXPECT_EQ(job_load_timing.send_end, resulting_load_timing.send_end);
1599  EXPECT_EQ(job_load_timing.receive_headers_end,
1600            resulting_load_timing.receive_headers_end);
1601
1602  return resulting_load_timing;
1603}
1604
1605// "Normal" LoadTimingInfo as returned by a job.  Everything is in order, not
1606// reused.  |connect_time_flags| is used to indicate if there should be dns
1607// or SSL times, and |used_proxy| is used for proxy times.
1608LoadTimingInfo NormalLoadTimingInfo(base::TimeTicks now,
1609                                    int connect_time_flags,
1610                                    bool used_proxy) {
1611  LoadTimingInfo load_timing;
1612  load_timing.socket_log_id = 1;
1613
1614  if (used_proxy) {
1615    load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
1616    load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
1617  }
1618
1619  LoadTimingInfo::ConnectTiming& connect_timing = load_timing.connect_timing;
1620  if (connect_time_flags & CONNECT_TIMING_HAS_DNS_TIMES) {
1621    connect_timing.dns_start = now + base::TimeDelta::FromDays(3);
1622    connect_timing.dns_end = now + base::TimeDelta::FromDays(4);
1623  }
1624  connect_timing.connect_start = now + base::TimeDelta::FromDays(5);
1625  if (connect_time_flags & CONNECT_TIMING_HAS_SSL_TIMES) {
1626    connect_timing.ssl_start = now + base::TimeDelta::FromDays(6);
1627    connect_timing.ssl_end = now + base::TimeDelta::FromDays(7);
1628  }
1629  connect_timing.connect_end = now + base::TimeDelta::FromDays(8);
1630
1631  load_timing.send_start = now + base::TimeDelta::FromDays(9);
1632  load_timing.send_end = now + base::TimeDelta::FromDays(10);
1633  load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
1634  return load_timing;
1635}
1636
1637// Same as above, but in the case of a reused socket.
1638LoadTimingInfo NormalLoadTimingInfoReused(base::TimeTicks now,
1639                                          bool used_proxy) {
1640  LoadTimingInfo load_timing;
1641  load_timing.socket_log_id = 1;
1642  load_timing.socket_reused = true;
1643
1644  if (used_proxy) {
1645    load_timing.proxy_resolve_start = now + base::TimeDelta::FromDays(1);
1646    load_timing.proxy_resolve_end = now + base::TimeDelta::FromDays(2);
1647  }
1648
1649  load_timing.send_start = now + base::TimeDelta::FromDays(9);
1650  load_timing.send_end = now + base::TimeDelta::FromDays(10);
1651  load_timing.receive_headers_end = now + base::TimeDelta::FromDays(11);
1652  return load_timing;
1653}
1654
1655// Basic test that the intercept + load timing tests work.
1656TEST_F(URLRequestTest, InterceptLoadTiming) {
1657  base::TimeTicks now = base::TimeTicks::Now();
1658  LoadTimingInfo job_load_timing =
1659      NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, false);
1660
1661  LoadTimingInfo load_timing_result =
1662      RunLoadTimingTest(job_load_timing, &default_context_);
1663
1664  // Nothing should have been changed by the URLRequest.
1665  EXPECT_EQ(job_load_timing.proxy_resolve_start,
1666            load_timing_result.proxy_resolve_start);
1667  EXPECT_EQ(job_load_timing.proxy_resolve_end,
1668            load_timing_result.proxy_resolve_end);
1669  EXPECT_EQ(job_load_timing.connect_timing.dns_start,
1670            load_timing_result.connect_timing.dns_start);
1671  EXPECT_EQ(job_load_timing.connect_timing.dns_end,
1672            load_timing_result.connect_timing.dns_end);
1673  EXPECT_EQ(job_load_timing.connect_timing.connect_start,
1674            load_timing_result.connect_timing.connect_start);
1675  EXPECT_EQ(job_load_timing.connect_timing.connect_end,
1676            load_timing_result.connect_timing.connect_end);
1677  EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
1678            load_timing_result.connect_timing.ssl_start);
1679  EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
1680            load_timing_result.connect_timing.ssl_end);
1681
1682  // Redundant sanity check.
1683  TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_DNS_TIMES);
1684}
1685
1686// Another basic test, with proxy and SSL times, but no DNS times.
1687TEST_F(URLRequestTest, InterceptLoadTimingProxy) {
1688  base::TimeTicks now = base::TimeTicks::Now();
1689  LoadTimingInfo job_load_timing =
1690      NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, true);
1691
1692  LoadTimingInfo load_timing_result =
1693      RunLoadTimingTest(job_load_timing, &default_context_);
1694
1695  // Nothing should have been changed by the URLRequest.
1696  EXPECT_EQ(job_load_timing.proxy_resolve_start,
1697            load_timing_result.proxy_resolve_start);
1698  EXPECT_EQ(job_load_timing.proxy_resolve_end,
1699            load_timing_result.proxy_resolve_end);
1700  EXPECT_EQ(job_load_timing.connect_timing.dns_start,
1701            load_timing_result.connect_timing.dns_start);
1702  EXPECT_EQ(job_load_timing.connect_timing.dns_end,
1703            load_timing_result.connect_timing.dns_end);
1704  EXPECT_EQ(job_load_timing.connect_timing.connect_start,
1705            load_timing_result.connect_timing.connect_start);
1706  EXPECT_EQ(job_load_timing.connect_timing.connect_end,
1707            load_timing_result.connect_timing.connect_end);
1708  EXPECT_EQ(job_load_timing.connect_timing.ssl_start,
1709            load_timing_result.connect_timing.ssl_start);
1710  EXPECT_EQ(job_load_timing.connect_timing.ssl_end,
1711            load_timing_result.connect_timing.ssl_end);
1712
1713  // Redundant sanity check.
1714  TestLoadTimingNotReusedWithProxy(load_timing_result,
1715                                   CONNECT_TIMING_HAS_SSL_TIMES);
1716}
1717
1718// Make sure that URLRequest correctly adjusts proxy times when they're before
1719// |request_start|, due to already having a connected socket.  This happens in
1720// the case of reusing a SPDY session.  The connected socket is not considered
1721// reused in this test (May be a preconnect).
1722//
1723// To mix things up from the test above, assumes DNS times but no SSL times.
1724TEST_F(URLRequestTest, InterceptLoadTimingEarlyProxyResolution) {
1725  base::TimeTicks now = base::TimeTicks::Now();
1726  LoadTimingInfo job_load_timing =
1727      NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_DNS_TIMES, true);
1728  job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(6);
1729  job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(5);
1730  job_load_timing.connect_timing.dns_start = now - base::TimeDelta::FromDays(4);
1731  job_load_timing.connect_timing.dns_end = now - base::TimeDelta::FromDays(3);
1732  job_load_timing.connect_timing.connect_start =
1733      now - base::TimeDelta::FromDays(2);
1734  job_load_timing.connect_timing.connect_end =
1735      now - base::TimeDelta::FromDays(1);
1736
1737  LoadTimingInfo load_timing_result =
1738      RunLoadTimingTest(job_load_timing, &default_context_);
1739
1740  // Proxy times, connect times, and DNS times should all be replaced with
1741  // request_start.
1742  EXPECT_EQ(load_timing_result.request_start,
1743            load_timing_result.proxy_resolve_start);
1744  EXPECT_EQ(load_timing_result.request_start,
1745            load_timing_result.proxy_resolve_end);
1746  EXPECT_EQ(load_timing_result.request_start,
1747            load_timing_result.connect_timing.dns_start);
1748  EXPECT_EQ(load_timing_result.request_start,
1749            load_timing_result.connect_timing.dns_end);
1750  EXPECT_EQ(load_timing_result.request_start,
1751            load_timing_result.connect_timing.connect_start);
1752  EXPECT_EQ(load_timing_result.request_start,
1753            load_timing_result.connect_timing.connect_end);
1754
1755  // Other times should have been left null.
1756  TestLoadTimingNotReusedWithProxy(load_timing_result,
1757                                   CONNECT_TIMING_HAS_DNS_TIMES);
1758}
1759
1760// Same as above, but in the reused case.
1761TEST_F(URLRequestTest, InterceptLoadTimingEarlyProxyResolutionReused) {
1762  base::TimeTicks now = base::TimeTicks::Now();
1763  LoadTimingInfo job_load_timing = NormalLoadTimingInfoReused(now, true);
1764  job_load_timing.proxy_resolve_start = now - base::TimeDelta::FromDays(4);
1765  job_load_timing.proxy_resolve_end = now - base::TimeDelta::FromDays(3);
1766
1767  LoadTimingInfo load_timing_result =
1768      RunLoadTimingTest(job_load_timing, &default_context_);
1769
1770  // Proxy times and connect times should all be replaced with request_start.
1771  EXPECT_EQ(load_timing_result.request_start,
1772            load_timing_result.proxy_resolve_start);
1773  EXPECT_EQ(load_timing_result.request_start,
1774            load_timing_result.proxy_resolve_end);
1775
1776  // Other times should have been left null.
1777  TestLoadTimingReusedWithProxy(load_timing_result);
1778}
1779
1780// Make sure that URLRequest correctly adjusts connect times when they're before
1781// |request_start|, due to reusing a connected socket.  The connected socket is
1782// not considered reused in this test (May be a preconnect).
1783//
1784// To mix things up, the request has SSL times, but no DNS times.
1785TEST_F(URLRequestTest, InterceptLoadTimingEarlyConnect) {
1786  base::TimeTicks now = base::TimeTicks::Now();
1787  LoadTimingInfo job_load_timing =
1788      NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_SSL_TIMES, false);
1789  job_load_timing.connect_timing.connect_start =
1790      now - base::TimeDelta::FromDays(1);
1791  job_load_timing.connect_timing.ssl_start = now - base::TimeDelta::FromDays(2);
1792  job_load_timing.connect_timing.ssl_end = now - base::TimeDelta::FromDays(3);
1793  job_load_timing.connect_timing.connect_end =
1794      now - base::TimeDelta::FromDays(4);
1795
1796  LoadTimingInfo load_timing_result =
1797      RunLoadTimingTest(job_load_timing, &default_context_);
1798
1799  // Connect times, and SSL times should be replaced with request_start.
1800  EXPECT_EQ(load_timing_result.request_start,
1801            load_timing_result.connect_timing.connect_start);
1802  EXPECT_EQ(load_timing_result.request_start,
1803            load_timing_result.connect_timing.ssl_start);
1804  EXPECT_EQ(load_timing_result.request_start,
1805            load_timing_result.connect_timing.ssl_end);
1806  EXPECT_EQ(load_timing_result.request_start,
1807            load_timing_result.connect_timing.connect_end);
1808
1809  // Other times should have been left null.
1810  TestLoadTimingNotReused(load_timing_result, CONNECT_TIMING_HAS_SSL_TIMES);
1811}
1812
1813// Make sure that URLRequest correctly adjusts connect times when they're before
1814// |request_start|, due to reusing a connected socket in the case that there
1815// are also proxy times.  The connected socket is not considered reused in this
1816// test (May be a preconnect).
1817//
1818// In this test, there are no SSL or DNS times.
1819TEST_F(URLRequestTest, InterceptLoadTimingEarlyConnectWithProxy) {
1820  base::TimeTicks now = base::TimeTicks::Now();
1821  LoadTimingInfo job_load_timing =
1822      NormalLoadTimingInfo(now, CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY, true);
1823  job_load_timing.connect_timing.connect_start =
1824      now - base::TimeDelta::FromDays(1);
1825  job_load_timing.connect_timing.connect_end =
1826      now - base::TimeDelta::FromDays(2);
1827
1828  LoadTimingInfo load_timing_result =
1829      RunLoadTimingTest(job_load_timing, &default_context_);
1830
1831  // Connect times should be replaced with proxy_resolve_end.
1832  EXPECT_EQ(load_timing_result.proxy_resolve_end,
1833            load_timing_result.connect_timing.connect_start);
1834  EXPECT_EQ(load_timing_result.proxy_resolve_end,
1835            load_timing_result.connect_timing.connect_end);
1836
1837  // Other times should have been left null.
1838  TestLoadTimingNotReusedWithProxy(load_timing_result,
1839                                   CONNECT_TIMING_HAS_CONNECT_TIMES_ONLY);
1840}
1841
1842// Check that two different URL requests have different identifiers.
1843TEST_F(URLRequestTest, Identifiers) {
1844  TestDelegate d;
1845  TestURLRequestContext context;
1846  scoped_ptr<URLRequest> req(context.CreateRequest(
1847      GURL("http://example.com"), DEFAULT_PRIORITY, &d, NULL));
1848  scoped_ptr<URLRequest> other_req(context.CreateRequest(
1849      GURL("http://example.com"), DEFAULT_PRIORITY, &d, NULL));
1850
1851  ASSERT_NE(req->identifier(), other_req->identifier());
1852}
1853
1854// Check that a failure to connect to the proxy is reported to the network
1855// delegate.
1856TEST_F(URLRequestTest, NetworkDelegateProxyError) {
1857  MockHostResolver host_resolver;
1858  host_resolver.rules()->AddSimulatedFailure("*");
1859
1860  TestNetworkDelegate network_delegate;  // Must outlive URLRequests.
1861  TestURLRequestContextWithProxy context("myproxy:70", &network_delegate);
1862
1863  TestDelegate d;
1864  scoped_ptr<URLRequest> req(context.CreateRequest(
1865      GURL("http://example.com"), DEFAULT_PRIORITY, &d, NULL));
1866  req->set_method("GET");
1867
1868  req->Start();
1869  base::RunLoop().Run();
1870
1871  // Check we see a failed request.
1872  EXPECT_FALSE(req->status().is_success());
1873  // The proxy server is not set before failure.
1874  EXPECT_TRUE(req->proxy_server().IsEmpty());
1875  EXPECT_EQ(URLRequestStatus::FAILED, req->status().status());
1876  EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, req->status().error());
1877
1878  EXPECT_EQ(1, network_delegate.error_count());
1879  EXPECT_EQ(ERR_PROXY_CONNECTION_FAILED, network_delegate.last_error());
1880  EXPECT_EQ(1, network_delegate.completed_requests());
1881}
1882
1883// Make sure that NetworkDelegate::NotifyCompleted is called if
1884// content is empty.
1885TEST_F(URLRequestTest, RequestCompletionForEmptyResponse) {
1886  TestDelegate d;
1887  scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1888      GURL("data:,"), DEFAULT_PRIORITY, &d, NULL));
1889  req->Start();
1890  base::RunLoop().Run();
1891  EXPECT_EQ("", d.data_received());
1892  EXPECT_EQ(1, default_network_delegate_.completed_requests());
1893}
1894
1895// Make sure that SetPriority actually sets the URLRequest's priority
1896// correctly, both before and after start.
1897TEST_F(URLRequestTest, SetPriorityBasic) {
1898  TestDelegate d;
1899  scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1900      GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
1901  EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
1902
1903  req->SetPriority(LOW);
1904  EXPECT_EQ(LOW, req->priority());
1905
1906  req->Start();
1907  EXPECT_EQ(LOW, req->priority());
1908
1909  req->SetPriority(MEDIUM);
1910  EXPECT_EQ(MEDIUM, req->priority());
1911}
1912
1913// Make sure that URLRequest calls SetPriority on a job before calling
1914// Start on it.
1915TEST_F(URLRequestTest, SetJobPriorityBeforeJobStart) {
1916  TestDelegate d;
1917  scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1918      GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
1919  EXPECT_EQ(DEFAULT_PRIORITY, req->priority());
1920
1921  scoped_refptr<URLRequestTestJob> job =
1922      new URLRequestTestJob(req.get(), &default_network_delegate_);
1923  AddTestInterceptor()->set_main_intercept_job(job.get());
1924  EXPECT_EQ(DEFAULT_PRIORITY, job->priority());
1925
1926  req->SetPriority(LOW);
1927
1928  req->Start();
1929  EXPECT_EQ(LOW, job->priority());
1930}
1931
1932// Make sure that URLRequest passes on its priority updates to its
1933// job.
1934TEST_F(URLRequestTest, SetJobPriority) {
1935  TestDelegate d;
1936  scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1937      GURL("http://test_intercept/foo"), DEFAULT_PRIORITY, &d, NULL));
1938
1939  scoped_refptr<URLRequestTestJob> job =
1940      new URLRequestTestJob(req.get(), &default_network_delegate_);
1941  AddTestInterceptor()->set_main_intercept_job(job.get());
1942
1943  req->SetPriority(LOW);
1944  req->Start();
1945  EXPECT_EQ(LOW, job->priority());
1946
1947  req->SetPriority(MEDIUM);
1948  EXPECT_EQ(MEDIUM, req->priority());
1949  EXPECT_EQ(MEDIUM, job->priority());
1950}
1951
1952// Setting the IGNORE_LIMITS load flag should be okay if the priority
1953// is MAXIMUM_PRIORITY.
1954TEST_F(URLRequestTest, PriorityIgnoreLimits) {
1955  TestDelegate d;
1956  scoped_ptr<URLRequest> req(default_context_.CreateRequest(
1957      GURL("http://test_intercept/foo"), MAXIMUM_PRIORITY, &d, NULL));
1958  EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
1959
1960  scoped_refptr<URLRequestTestJob> job =
1961      new URLRequestTestJob(req.get(), &default_network_delegate_);
1962  AddTestInterceptor()->set_main_intercept_job(job.get());
1963
1964  req->SetLoadFlags(LOAD_IGNORE_LIMITS);
1965  EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
1966
1967  req->SetPriority(MAXIMUM_PRIORITY);
1968  EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
1969
1970  req->Start();
1971  EXPECT_EQ(MAXIMUM_PRIORITY, req->priority());
1972  EXPECT_EQ(MAXIMUM_PRIORITY, job->priority());
1973}
1974
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.
1981class 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()) {}
1991};
1992
1993TEST_F(URLRequestTest, DelayedCookieCallback) {
1994  LocalHttpTestServer test_server;
1995  ASSERT_TRUE(test_server.Start());
1996
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());
2002
2003  // Set up a cookie.
2004  {
2005    TestNetworkDelegate network_delegate;
2006    context.set_network_delegate(&network_delegate);
2007    TestDelegate d;
2008    scoped_ptr<URLRequest> req(context.CreateRequest(
2009        test_server.GetURL("set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
2010        &d, NULL));
2011    req->Start();
2012    base::RunLoop().Run();
2013    EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2014    EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2015    EXPECT_EQ(1, network_delegate.set_cookie_count());
2016  }
2017
2018  // Verify that the cookie is set.
2019  {
2020    TestNetworkDelegate network_delegate;
2021    context.set_network_delegate(&network_delegate);
2022    TestDelegate d;
2023    scoped_ptr<URLRequest> req(context.CreateRequest(
2024        test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2025    req->Start();
2026    base::RunLoop().Run();
2027
2028    EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2029                != std::string::npos);
2030    EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2031    EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2032  }
2033}
2034
2035TEST_F(URLRequestTest, DoNotSendCookies) {
2036  LocalHttpTestServer test_server;
2037  ASSERT_TRUE(test_server.Start());
2038
2039  // Set up a cookie.
2040  {
2041    TestNetworkDelegate network_delegate;
2042    default_context_.set_network_delegate(&network_delegate);
2043    TestDelegate d;
2044    scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2045        test_server.GetURL("set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
2046        &d, NULL));
2047    req->Start();
2048    base::RunLoop().Run();
2049    EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2050    EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2051  }
2052
2053  // Verify that the cookie is set.
2054  {
2055    TestNetworkDelegate network_delegate;
2056    default_context_.set_network_delegate(&network_delegate);
2057    TestDelegate d;
2058    scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2059        test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2060    req->Start();
2061    base::RunLoop().Run();
2062
2063    EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2064                != std::string::npos);
2065    EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2066    EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2067  }
2068
2069  // Verify that the cookie isn't sent when LOAD_DO_NOT_SEND_COOKIES is set.
2070  {
2071    TestNetworkDelegate network_delegate;
2072    default_context_.set_network_delegate(&network_delegate);
2073    TestDelegate d;
2074    scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2075        test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2076    req->SetLoadFlags(LOAD_DO_NOT_SEND_COOKIES);
2077    req->Start();
2078    base::RunLoop().Run();
2079
2080    EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2081                == std::string::npos);
2082
2083    // LOAD_DO_NOT_SEND_COOKIES does not trigger OnGetCookies.
2084    EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2085    EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2086  }
2087}
2088
2089TEST_F(URLRequestTest, DoNotSaveCookies) {
2090  LocalHttpTestServer test_server;
2091  ASSERT_TRUE(test_server.Start());
2092
2093  // Set up a cookie.
2094  {
2095    TestNetworkDelegate network_delegate;
2096    default_context_.set_network_delegate(&network_delegate);
2097    TestDelegate d;
2098    scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2099        test_server.GetURL("set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
2100        &d, NULL));
2101    req->Start();
2102    base::RunLoop().Run();
2103
2104    EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2105    EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2106    EXPECT_EQ(1, network_delegate.set_cookie_count());
2107  }
2108
2109  // Try to set-up another cookie and update the previous cookie.
2110  {
2111    TestNetworkDelegate network_delegate;
2112    default_context_.set_network_delegate(&network_delegate);
2113    TestDelegate d;
2114    scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2115        test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
2116        DEFAULT_PRIORITY, &d, NULL));
2117    req->SetLoadFlags(LOAD_DO_NOT_SAVE_COOKIES);
2118    req->Start();
2119
2120    base::RunLoop().Run();
2121
2122    // LOAD_DO_NOT_SAVE_COOKIES does not trigger OnSetCookie.
2123    EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2124    EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2125    EXPECT_EQ(0, network_delegate.set_cookie_count());
2126  }
2127
2128  // Verify the cookies weren't saved or updated.
2129  {
2130    TestNetworkDelegate network_delegate;
2131    default_context_.set_network_delegate(&network_delegate);
2132    TestDelegate d;
2133    scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2134        test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2135    req->Start();
2136    base::RunLoop().Run();
2137
2138    EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2139                == std::string::npos);
2140    EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2141                != std::string::npos);
2142
2143    EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2144    EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2145    EXPECT_EQ(0, network_delegate.set_cookie_count());
2146  }
2147}
2148
2149TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy) {
2150  LocalHttpTestServer test_server;
2151  ASSERT_TRUE(test_server.Start());
2152
2153  // Set up a cookie.
2154  {
2155    TestNetworkDelegate network_delegate;
2156    default_context_.set_network_delegate(&network_delegate);
2157    TestDelegate d;
2158    scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2159        test_server.GetURL("set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
2160        &d, NULL));
2161    req->Start();
2162    base::RunLoop().Run();
2163
2164    EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2165    EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2166  }
2167
2168  // Verify that the cookie is set.
2169  {
2170    TestNetworkDelegate network_delegate;
2171    default_context_.set_network_delegate(&network_delegate);
2172    TestDelegate d;
2173    scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2174        test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2175    req->Start();
2176    base::RunLoop().Run();
2177
2178    EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2179                != std::string::npos);
2180
2181    EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2182    EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2183  }
2184
2185  // Verify that the cookie isn't sent.
2186  {
2187    TestNetworkDelegate network_delegate;
2188    default_context_.set_network_delegate(&network_delegate);
2189    TestDelegate d;
2190    network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
2191    scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2192        test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2193    req->Start();
2194    base::RunLoop().Run();
2195
2196    EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2197                == std::string::npos);
2198
2199    EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
2200    EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2201  }
2202}
2203
2204TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy) {
2205  LocalHttpTestServer test_server;
2206  ASSERT_TRUE(test_server.Start());
2207
2208  // Set up a cookie.
2209  {
2210    TestNetworkDelegate network_delegate;
2211    default_context_.set_network_delegate(&network_delegate);
2212    TestDelegate d;
2213    scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2214        test_server.GetURL("set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
2215        &d, NULL));
2216    req->Start();
2217    base::RunLoop().Run();
2218
2219    EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2220    EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2221  }
2222
2223  // Try to set-up another cookie and update the previous cookie.
2224  {
2225    TestNetworkDelegate network_delegate;
2226    default_context_.set_network_delegate(&network_delegate);
2227    TestDelegate d;
2228    network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
2229    scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2230        test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
2231        DEFAULT_PRIORITY, &d, NULL));
2232    req->Start();
2233
2234    base::RunLoop().Run();
2235
2236    EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2237    EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2238  }
2239
2240  // Verify the cookies weren't saved or updated.
2241  {
2242    TestNetworkDelegate network_delegate;
2243    default_context_.set_network_delegate(&network_delegate);
2244    TestDelegate d;
2245    scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2246        test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2247    req->Start();
2248    base::RunLoop().Run();
2249
2250    EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2251                == std::string::npos);
2252    EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2253                != std::string::npos);
2254
2255    EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2256    EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2257  }
2258}
2259
2260TEST_F(URLRequestTest, DoNotSaveEmptyCookies) {
2261  LocalHttpTestServer test_server;
2262  ASSERT_TRUE(test_server.Start());
2263
2264  // Set up an empty cookie.
2265  {
2266    TestNetworkDelegate network_delegate;
2267    default_context_.set_network_delegate(&network_delegate);
2268    TestDelegate d;
2269    scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2270        test_server.GetURL("set-cookie"), DEFAULT_PRIORITY, &d, NULL));
2271    req->Start();
2272    base::RunLoop().Run();
2273
2274    EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2275    EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2276    EXPECT_EQ(0, network_delegate.set_cookie_count());
2277  }
2278}
2279
2280TEST_F(URLRequestTest, DoNotSendCookies_ViaPolicy_Async) {
2281  LocalHttpTestServer test_server;
2282  ASSERT_TRUE(test_server.Start());
2283
2284  // Set up a cookie.
2285  {
2286    TestNetworkDelegate network_delegate;
2287    default_context_.set_network_delegate(&network_delegate);
2288    TestDelegate d;
2289    scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2290        test_server.GetURL("set-cookie?CookieToNotSend=1"), DEFAULT_PRIORITY,
2291        &d, NULL));
2292    req->Start();
2293    base::RunLoop().Run();
2294
2295    EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2296    EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2297  }
2298
2299  // Verify that the cookie is set.
2300  {
2301    TestNetworkDelegate network_delegate;
2302    default_context_.set_network_delegate(&network_delegate);
2303    TestDelegate d;
2304    scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2305        test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2306    req->Start();
2307    base::RunLoop().Run();
2308
2309    EXPECT_TRUE(d.data_received().find("CookieToNotSend=1")
2310                != std::string::npos);
2311
2312    EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2313    EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2314  }
2315
2316  // Verify that the cookie isn't sent.
2317  {
2318    TestNetworkDelegate network_delegate;
2319    default_context_.set_network_delegate(&network_delegate);
2320    TestDelegate d;
2321    network_delegate.set_cookie_options(TestNetworkDelegate::NO_GET_COOKIES);
2322    scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2323        test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2324    req->Start();
2325    base::RunLoop().Run();
2326
2327    EXPECT_TRUE(d.data_received().find("Cookie: CookieToNotSend=1")
2328                == std::string::npos);
2329
2330    EXPECT_EQ(1, network_delegate.blocked_get_cookies_count());
2331    EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2332  }
2333}
2334
2335TEST_F(URLRequestTest, DoNotSaveCookies_ViaPolicy_Async) {
2336  LocalHttpTestServer test_server;
2337  ASSERT_TRUE(test_server.Start());
2338
2339  // Set up a cookie.
2340  {
2341    TestNetworkDelegate network_delegate;
2342    default_context_.set_network_delegate(&network_delegate);
2343    TestDelegate d;
2344    scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2345        test_server.GetURL("set-cookie?CookieToNotUpdate=2"), DEFAULT_PRIORITY,
2346        &d, NULL));
2347    req->Start();
2348    base::RunLoop().Run();
2349
2350    EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2351    EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2352  }
2353
2354  // Try to set-up another cookie and update the previous cookie.
2355  {
2356    TestNetworkDelegate network_delegate;
2357    default_context_.set_network_delegate(&network_delegate);
2358    TestDelegate d;
2359    network_delegate.set_cookie_options(TestNetworkDelegate::NO_SET_COOKIE);
2360    scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2361        test_server.GetURL("set-cookie?CookieToNotSave=1&CookieToNotUpdate=1"),
2362        DEFAULT_PRIORITY, &d, NULL));
2363    req->Start();
2364
2365    base::RunLoop().Run();
2366
2367    EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2368    EXPECT_EQ(2, network_delegate.blocked_set_cookie_count());
2369  }
2370
2371  // Verify the cookies weren't saved or updated.
2372  {
2373    TestNetworkDelegate network_delegate;
2374    default_context_.set_network_delegate(&network_delegate);
2375    TestDelegate d;
2376    scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2377        test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2378    req->Start();
2379    base::RunLoop().Run();
2380
2381    EXPECT_TRUE(d.data_received().find("CookieToNotSave=1")
2382                == std::string::npos);
2383    EXPECT_TRUE(d.data_received().find("CookieToNotUpdate=2")
2384                != std::string::npos);
2385
2386    EXPECT_EQ(0, network_delegate.blocked_get_cookies_count());
2387    EXPECT_EQ(0, network_delegate.blocked_set_cookie_count());
2388  }
2389}
2390
2391// FixedDateNetworkDelegate swaps out the server's HTTP Date response header
2392// value for the |fixed_date| argument given to the constructor.
2393class FixedDateNetworkDelegate : public TestNetworkDelegate {
2394 public:
2395  explicit FixedDateNetworkDelegate(const std::string& fixed_date)
2396      : fixed_date_(fixed_date) {}
2397  virtual ~FixedDateNetworkDelegate() {}
2398
2399  // NetworkDelegate implementation
2400  virtual int OnHeadersReceived(
2401      URLRequest* request,
2402      const CompletionCallback& callback,
2403      const HttpResponseHeaders* original_response_headers,
2404      scoped_refptr<HttpResponseHeaders>* override_response_headers,
2405      GURL* allowed_unsafe_redirect_url) OVERRIDE;
2406
2407 private:
2408  std::string fixed_date_;
2409
2410  DISALLOW_COPY_AND_ASSIGN(FixedDateNetworkDelegate);
2411};
2412
2413int FixedDateNetworkDelegate::OnHeadersReceived(
2414    URLRequest* request,
2415    const CompletionCallback& callback,
2416    const HttpResponseHeaders* original_response_headers,
2417    scoped_refptr<HttpResponseHeaders>* override_response_headers,
2418    GURL* allowed_unsafe_redirect_url) {
2419  HttpResponseHeaders* new_response_headers =
2420      new HttpResponseHeaders(original_response_headers->raw_headers());
2421
2422  new_response_headers->RemoveHeader("Date");
2423  new_response_headers->AddHeader("Date: " + fixed_date_);
2424
2425  *override_response_headers = new_response_headers;
2426  return TestNetworkDelegate::OnHeadersReceived(request,
2427                                                callback,
2428                                                original_response_headers,
2429                                                override_response_headers,
2430                                                allowed_unsafe_redirect_url);
2431}
2432
2433// Test that cookie expiration times are adjusted for server/client clock
2434// skew and that we handle incorrect timezone specifier "UTC" in HTTP Date
2435// headers by defaulting to GMT. (crbug.com/135131)
2436TEST_F(URLRequestTest, AcceptClockSkewCookieWithWrongDateTimezone) {
2437  LocalHttpTestServer test_server;
2438  ASSERT_TRUE(test_server.Start());
2439
2440  // Set up an expired cookie.
2441  {
2442    TestNetworkDelegate network_delegate;
2443    default_context_.set_network_delegate(&network_delegate);
2444    TestDelegate d;
2445    scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2446        test_server.GetURL(
2447            "set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
2448        DEFAULT_PRIORITY, &d, NULL));
2449    req->Start();
2450    base::RunLoop().Run();
2451  }
2452  // Verify that the cookie is not set.
2453  {
2454    TestNetworkDelegate network_delegate;
2455    default_context_.set_network_delegate(&network_delegate);
2456    TestDelegate d;
2457    scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2458        test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2459    req->Start();
2460    base::RunLoop().Run();
2461
2462    EXPECT_TRUE(d.data_received().find("StillGood=1") == std::string::npos);
2463  }
2464  // Set up a cookie with clock skew and "UTC" HTTP Date timezone specifier.
2465  {
2466    FixedDateNetworkDelegate network_delegate("18-Apr-1977 22:49:13 UTC");
2467    default_context_.set_network_delegate(&network_delegate);
2468    TestDelegate d;
2469    scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2470        test_server.GetURL(
2471            "set-cookie?StillGood=1;expires=Mon,18-Apr-1977,22:50:13,GMT"),
2472        DEFAULT_PRIORITY, &d, NULL));
2473    req->Start();
2474    base::RunLoop().Run();
2475  }
2476  // Verify that the cookie is set.
2477  {
2478    TestNetworkDelegate network_delegate;
2479    default_context_.set_network_delegate(&network_delegate);
2480    TestDelegate d;
2481    scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2482        test_server.GetURL("echoheader?Cookie"), DEFAULT_PRIORITY, &d, NULL));
2483    req->Start();
2484    base::RunLoop().Run();
2485
2486    EXPECT_TRUE(d.data_received().find("StillGood=1") != std::string::npos);
2487  }
2488}
2489
2490
2491// Check that it is impossible to change the referrer in the extra headers of
2492// an URLRequest.
2493TEST_F(URLRequestTest, DoNotOverrideReferrer) {
2494  LocalHttpTestServer test_server;
2495  ASSERT_TRUE(test_server.Start());
2496
2497  // If extra headers contain referer and the request contains a referer,
2498  // only the latter shall be respected.
2499  {
2500    TestDelegate d;
2501    scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2502        test_server.GetURL("echoheader?Referer"), DEFAULT_PRIORITY, &d, NULL));
2503    req->SetReferrer("http://foo.com/");
2504
2505    HttpRequestHeaders headers;
2506    headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
2507    req->SetExtraRequestHeaders(headers);
2508
2509    req->Start();
2510    base::RunLoop().Run();
2511
2512    EXPECT_EQ("http://foo.com/", d.data_received());
2513  }
2514
2515  // If extra headers contain a referer but the request does not, no referer
2516  // shall be sent in the header.
2517  {
2518    TestDelegate d;
2519    scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2520        test_server.GetURL("echoheader?Referer"), DEFAULT_PRIORITY, &d, NULL));
2521
2522    HttpRequestHeaders headers;
2523    headers.SetHeader(HttpRequestHeaders::kReferer, "http://bar.com/");
2524    req->SetExtraRequestHeaders(headers);
2525    req->SetLoadFlags(LOAD_VALIDATE_CACHE);
2526
2527    req->Start();
2528    base::RunLoop().Run();
2529
2530    EXPECT_EQ("None", d.data_received());
2531  }
2532}
2533
2534class URLRequestTestHTTP : public URLRequestTest {
2535 public:
2536  URLRequestTestHTTP()
2537      : test_server_(base::FilePath(FILE_PATH_LITERAL(
2538                                  "net/data/url_request_unittest"))) {
2539  }
2540
2541 protected:
2542  // Requests |redirect_url|, which must return a HTTP 3xx redirect.
2543  // |request_method| is the method to use for the initial request.
2544  // |redirect_method| is the method that is expected to be used for the second
2545  // request, after redirection.
2546  // If |include_data| is true, data is uploaded with the request.  The
2547  // response body is expected to match it exactly, if and only if
2548  // |request_method| == |redirect_method|.
2549  void HTTPRedirectMethodTest(const GURL& redirect_url,
2550                              const std::string& request_method,
2551                              const std::string& redirect_method,
2552                              bool include_data) {
2553    static const char kData[] = "hello world";
2554    TestDelegate d;
2555    scoped_ptr<URLRequest> req(default_context_.CreateRequest(
2556        redirect_url, DEFAULT_PRIORITY, &d, NULL));
2557    req->set_method(request_method);
2558    if (include_data) {
2559      req->set_upload(make_scoped_ptr(CreateSimpleUploadData(kData)));
2560      HttpRequestHeaders headers;
2561      headers.SetHeader(HttpRequestHeaders::kContentLength,
2562                        base::UintToString(arraysize(kData) - 1));
2563      req->SetExtraRequestHeaders(headers);
2564    }
2565    req->Start();
2566    base::RunLoop().Run();
2567    EXPECT_EQ(redirect_method, req->method());
2568    EXPECT_EQ(URLRequestStatus::SUCCESS, req->status().status());
2569    EXPECT_EQ(OK, req->status().error());
2570    if (include_data) {
2571      if (request_method == redirect_method) {
2572        EXPECT_EQ(kData, d.data_received());
2573      } else {
2574        EXPECT_NE(kData, d.data_received());
2575      }
2576    }
2577    if (HasFailure())
2578      LOG(WARNING) << "Request method was: " << request_method;
2579  }
2580
2581  void HTTPUploadDataOperationTest(const std::string& method) {
2582    const int kMsgSize = 20000;  // multiple of 10
2583    const int kIterations = 50;
2584    char* uploadBytes = new char[kMsgSize+1];
2585    char* ptr = uploadBytes;
2586    char marker = 'a';
2587    for (int idx = 0; idx < kMsgSize/10; idx++) {
2588      memcpy(ptr, "----------", 10);
2589      ptr += 10;
2590      if (idx % 100 == 0) {
2591        ptr--;
2592        *ptr++ = marker;
2593        if (++marker > 'z')
2594          marker = 'a';
2595      }
2596    }
2597    uploadBytes[kMsgSize] = '\0';
2598
2599    for (int i = 0; i < kIterations; ++i) {
2600      TestDelegate d;
2601      scoped_ptr<URLRequest> r(default_context_.CreateRequest(
2602          test_server_.GetURL("echo"), DEFAULT_PRIORITY, &d, NULL));
2603      r->set_method(method.c_str());
2604
2605      r->set_upload(make_scoped_ptr(CreateSimpleUploadData(uploadBytes)));
2606
2607      r->Start();
2608      EXPECT_TRUE(r->is_pending());
2609
2610      base::RunLoop().Run();
2611
2612      ASSERT_EQ(1, d.response_started_count())
2613          << "request failed: " << r->status().status()
2614          << ", os error: " << r->status().error();
2615
2616      EXPECT_FALSE(d.received_data_before_response());
2617      EXPECT_EQ(uploadBytes, d.data_received());
2618    }
2619    delete[] uploadBytes;
2620  }
2621
2622  void AddChunksToUpload(URLRequest* r) {
2623    r->AppendChunkToUpload("a", 1, false);
2624    r->AppendChunkToUpload("bcd", 3, false);
2625    r->AppendChunkToUpload("this is a longer chunk than before.", 35, false);
2626    r->AppendChunkToUpload("\r\n\r\n", 4, false);
2627    r->AppendChunkToUpload("0", 1, false);
2628    r->AppendChunkToUpload("2323", 4, true);
2629  }
2630
2631  void VerifyReceivedDataMatchesChunks(URLRequest* r, TestDelegate* d) {
2632    // This should match the chunks sent by AddChunksToUpload().
2633    const std::string expected_data =
2634        "abcdthis is a longer chunk than before.\r\n\r\n02323";
2635
2636    ASSERT_EQ(1, d->response_started_count())
2637        << "request failed: " << r->status().status()
2638        << ", os error: " << r->status().error();
2639
2640    EXPECT_FALSE(d->received_data_before_response());
2641
2642    EXPECT_EQ(expected_data.size(), static_cast<size_t>(d->bytes_received()));
2643    EXPECT_EQ(expected_data, d->data_received());
2644  }
2645
2646  bool DoManyCookiesRequest(int num_cookies) {
2647    TestDelegate d;
2648    scoped_ptr<URLRequest> r(default_context_.CreateRequest(
2649        test_server_.GetURL("set-many-cookies?" +
2650                                base::IntToString(num_cookies)),
2651        DEFAULT_PRIORITY, &d, NULL));
2652
2653    r->Start();
2654    EXPECT_TRUE(r->is_pending());
2655
2656    base::RunLoop().Run();
2657
2658    bool is_success = r->status().is_success();
2659
2660    if (!is_success) {
2661      EXPECT_TRUE(r->status().error() == ERR_RESPONSE_HEADERS_TOO_BIG);
2662      // The test server appears to be unable to handle subsequent requests
2663      // after this error is triggered. Force it to restart.
2664      EXPECT_TRUE(test_server_.Stop());
2665      EXPECT_TRUE(test_server_.Start());
2666    }
2667
2668    return is_success;
2669  }
2670
2671  LocalHttpTestServer test_server_;
2672};
2673
2674// In this unit test, we're using the HTTPTestServer as a proxy server and
2675// issuing a CONNECT request with the magic host name "www.redirect.com".
2676// The HTTPTestServer will return a 302 response, which we should not
2677// follow.
2678TEST_F(URLRequestTestHTTP, ProxyTunnelRedirectTest) {
2679  ASSERT_TRUE(test_server_.Start());
2680
2681  TestNetworkDelegate network_delegate;  // Must outlive URLRequest.
2682  TestURLRequestContextWithProxy context(
2683      test_server_.host_port_pair().ToString(), &network_delegate);
2684
2685  TestDelegate d;
2686  {
2687    scoped_ptr<URLRequest> r(context.CreateRequest(
2688        GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d, NULL));
2689    r->Start();
2690    EXPECT_TRUE(r->is_pending());
2691
2692    base::RunLoop().Run();
2693
2694    EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
2695    // The proxy server is not set before failure.
2696    EXPECT_TRUE(r->proxy_server().IsEmpty());
2697    EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r->status().error());
2698    EXPECT_EQ(1, d.response_started_count());
2699    // We should not have followed the redirect.
2700    EXPECT_EQ(0, d.received_redirect_count());
2701  }
2702}
2703
2704// This is the same as the previous test, but checks that the network delegate
2705// registers the error.
2706TEST_F(URLRequestTestHTTP, NetworkDelegateTunnelConnectionFailed) {
2707  ASSERT_TRUE(test_server_.Start());
2708
2709  TestNetworkDelegate network_delegate;  // Must outlive URLRequest.
2710  TestURLRequestContextWithProxy context(
2711      test_server_.host_port_pair().ToString(), &network_delegate);
2712
2713  TestDelegate d;
2714  {
2715    scoped_ptr<URLRequest> r(context.CreateRequest(
2716        GURL("https://www.redirect.com/"), DEFAULT_PRIORITY, &d, NULL));
2717    r->Start();
2718    EXPECT_TRUE(r->is_pending());
2719
2720    base::RunLoop().Run();
2721
2722    EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
2723    // The proxy server is not set before failure.
2724    EXPECT_TRUE(r->proxy_server().IsEmpty());
2725    EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, r->status().error());
2726    EXPECT_EQ(1, d.response_started_count());
2727    // We should not have followed the redirect.
2728    EXPECT_EQ(0, d.received_redirect_count());
2729
2730    EXPECT_EQ(1, network_delegate.error_count());
2731    EXPECT_EQ(ERR_TUNNEL_CONNECTION_FAILED, network_delegate.last_error());
2732  }
2733}
2734
2735// Tests that we can block and asynchronously return OK in various stages.
2736TEST_F(URLRequestTestHTTP, NetworkDelegateBlockAsynchronously) {
2737  static const BlockingNetworkDelegate::Stage blocking_stages[] = {
2738    BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
2739    BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
2740    BlockingNetworkDelegate::ON_HEADERS_RECEIVED
2741  };
2742  static const size_t blocking_stages_length = arraysize(blocking_stages);
2743
2744  ASSERT_TRUE(test_server_.Start());
2745
2746  TestDelegate d;
2747  BlockingNetworkDelegate network_delegate(
2748      BlockingNetworkDelegate::USER_CALLBACK);
2749  network_delegate.set_block_on(
2750      BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST |
2751      BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS |
2752      BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
2753
2754  TestURLRequestContext context(true);
2755  context.set_network_delegate(&network_delegate);
2756  context.Init();
2757
2758  {
2759    scoped_ptr<URLRequest> r(context.CreateRequest(
2760        test_server_.GetURL("empty.html"), DEFAULT_PRIORITY, &d, NULL));
2761
2762    r->Start();
2763    for (size_t i = 0; i < blocking_stages_length; ++i) {
2764      base::RunLoop().Run();
2765      EXPECT_EQ(blocking_stages[i],
2766                network_delegate.stage_blocked_for_callback());
2767      network_delegate.DoCallback(OK);
2768    }
2769    base::RunLoop().Run();
2770    EXPECT_EQ(200, r->GetResponseCode());
2771    EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
2772    EXPECT_EQ(1, network_delegate.created_requests());
2773    EXPECT_EQ(0, network_delegate.destroyed_requests());
2774  }
2775  EXPECT_EQ(1, network_delegate.destroyed_requests());
2776}
2777
2778// Tests that the network delegate can block and cancel a request.
2779TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequest) {
2780  ASSERT_TRUE(test_server_.Start());
2781
2782  TestDelegate d;
2783  BlockingNetworkDelegate network_delegate(
2784      BlockingNetworkDelegate::AUTO_CALLBACK);
2785  network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
2786  network_delegate.set_retval(ERR_EMPTY_RESPONSE);
2787
2788  TestURLRequestContextWithProxy context(
2789      test_server_.host_port_pair().ToString(), &network_delegate);
2790
2791  {
2792    scoped_ptr<URLRequest> r(context.CreateRequest(
2793        test_server_.GetURL(std::string()), DEFAULT_PRIORITY, &d, NULL));
2794
2795    r->Start();
2796    base::RunLoop().Run();
2797
2798    EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
2799    // The proxy server is not set before cancellation.
2800    EXPECT_TRUE(r->proxy_server().IsEmpty());
2801    EXPECT_EQ(ERR_EMPTY_RESPONSE, r->status().error());
2802    EXPECT_EQ(1, network_delegate.created_requests());
2803    EXPECT_EQ(0, network_delegate.destroyed_requests());
2804  }
2805  EXPECT_EQ(1, network_delegate.destroyed_requests());
2806}
2807
2808// Helper function for NetworkDelegateCancelRequestAsynchronously and
2809// NetworkDelegateCancelRequestSynchronously. Sets up a blocking network
2810// delegate operating in |block_mode| and a request for |url|. It blocks the
2811// request in |stage| and cancels it with ERR_BLOCKED_BY_CLIENT.
2812void NetworkDelegateCancelRequest(BlockingNetworkDelegate::BlockMode block_mode,
2813                                  BlockingNetworkDelegate::Stage stage,
2814                                  const GURL& url) {
2815  TestDelegate d;
2816  BlockingNetworkDelegate network_delegate(block_mode);
2817  network_delegate.set_retval(ERR_BLOCKED_BY_CLIENT);
2818  network_delegate.set_block_on(stage);
2819
2820  TestURLRequestContext context(true);
2821  context.set_network_delegate(&network_delegate);
2822  context.Init();
2823
2824  {
2825    scoped_ptr<URLRequest> r(context.CreateRequest(
2826        url, DEFAULT_PRIORITY, &d, NULL));
2827
2828    r->Start();
2829    base::RunLoop().Run();
2830
2831    EXPECT_EQ(URLRequestStatus::FAILED, r->status().status());
2832    // The proxy server is not set before cancellation.
2833    EXPECT_TRUE(r->proxy_server().IsEmpty());
2834    EXPECT_EQ(ERR_BLOCKED_BY_CLIENT, r->status().error());
2835    EXPECT_EQ(1, network_delegate.created_requests());
2836    EXPECT_EQ(0, network_delegate.destroyed_requests());
2837  }
2838  EXPECT_EQ(1, network_delegate.destroyed_requests());
2839}
2840
2841// The following 3 tests check that the network delegate can cancel a request
2842// synchronously in various stages of the request.
2843TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously1) {
2844  ASSERT_TRUE(test_server_.Start());
2845  NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
2846                               BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
2847                               test_server_.GetURL(std::string()));
2848}
2849
2850TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously2) {
2851  ASSERT_TRUE(test_server_.Start());
2852  NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
2853                               BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
2854                               test_server_.GetURL(std::string()));
2855}
2856
2857TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestSynchronously3) {
2858  ASSERT_TRUE(test_server_.Start());
2859  NetworkDelegateCancelRequest(BlockingNetworkDelegate::SYNCHRONOUS,
2860                               BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
2861                               test_server_.GetURL(std::string()));
2862}
2863
2864// The following 3 tests check that the network delegate can cancel a request
2865// asynchronously in various stages of the request.
2866TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously1) {
2867  ASSERT_TRUE(test_server_.Start());
2868  NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
2869                               BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST,
2870                               test_server_.GetURL(std::string()));
2871}
2872
2873TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously2) {
2874  ASSERT_TRUE(test_server_.Start());
2875  NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
2876                               BlockingNetworkDelegate::ON_BEFORE_SEND_HEADERS,
2877                               test_server_.GetURL(std::string()));
2878}
2879
2880TEST_F(URLRequestTestHTTP, NetworkDelegateCancelRequestAsynchronously3) {
2881  ASSERT_TRUE(test_server_.Start());
2882  NetworkDelegateCancelRequest(BlockingNetworkDelegate::AUTO_CALLBACK,
2883                               BlockingNetworkDelegate::ON_HEADERS_RECEIVED,
2884                               test_server_.GetURL(std::string()));
2885}
2886
2887// Tests that the network delegate can block and redirect a request to a new
2888// URL.
2889TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequest) {
2890  ASSERT_TRUE(test_server_.Start());
2891
2892  TestDelegate d;
2893  BlockingNetworkDelegate network_delegate(
2894      BlockingNetworkDelegate::AUTO_CALLBACK);
2895  network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
2896  GURL redirect_url(test_server_.GetURL("simple.html"));
2897  network_delegate.set_redirect_url(redirect_url);
2898
2899  TestURLRequestContextWithProxy context(
2900      test_server_.host_port_pair().ToString(), &network_delegate);
2901
2902  {
2903    GURL original_url(test_server_.GetURL("empty.html"));
2904    scoped_ptr<URLRequest> r(context.CreateRequest(
2905        original_url, DEFAULT_PRIORITY, &d, NULL));
2906
2907    // Quit after hitting the redirect, so can check the headers.
2908    d.set_quit_on_redirect(true);
2909    r->Start();
2910    base::RunLoop().Run();
2911
2912    // Check headers from URLRequestJob.
2913    EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
2914    EXPECT_EQ(307, r->GetResponseCode());
2915    EXPECT_EQ(307, r->response_headers()->response_code());
2916    std::string location;
2917    ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
2918                                                       &location));
2919    EXPECT_EQ(redirect_url, GURL(location));
2920
2921    // Let the request finish.
2922    r->FollowDeferredRedirect();
2923    base::RunLoop().Run();
2924    EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
2925    EXPECT_TRUE(r->proxy_server().Equals(test_server_.host_port_pair()));
2926    EXPECT_EQ(
2927        1, network_delegate.observed_before_proxy_headers_sent_callbacks());
2928    EXPECT_TRUE(
2929        network_delegate.last_observed_proxy().Equals(
2930            test_server_.host_port_pair()));
2931
2932    EXPECT_EQ(0, r->status().error());
2933    EXPECT_EQ(redirect_url, r->url());
2934    EXPECT_EQ(original_url, r->original_url());
2935    EXPECT_EQ(2U, r->url_chain().size());
2936    EXPECT_EQ(1, network_delegate.created_requests());
2937    EXPECT_EQ(0, network_delegate.destroyed_requests());
2938  }
2939  EXPECT_EQ(1, network_delegate.destroyed_requests());
2940}
2941
2942// Tests that the network delegate can block and redirect a request to a new
2943// URL by setting a redirect_url and returning in OnBeforeURLRequest directly.
2944TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestSynchronously) {
2945  ASSERT_TRUE(test_server_.Start());
2946
2947  TestDelegate d;
2948  BlockingNetworkDelegate network_delegate(
2949      BlockingNetworkDelegate::SYNCHRONOUS);
2950  GURL redirect_url(test_server_.GetURL("simple.html"));
2951  network_delegate.set_redirect_url(redirect_url);
2952
2953  TestURLRequestContextWithProxy context(
2954      test_server_.host_port_pair().ToString(), &network_delegate);
2955
2956  {
2957    GURL original_url(test_server_.GetURL("empty.html"));
2958    scoped_ptr<URLRequest> r(context.CreateRequest(
2959        original_url, DEFAULT_PRIORITY, &d, NULL));
2960
2961    // Quit after hitting the redirect, so can check the headers.
2962    d.set_quit_on_redirect(true);
2963    r->Start();
2964    base::RunLoop().Run();
2965
2966    // Check headers from URLRequestJob.
2967    EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
2968    EXPECT_EQ(307, r->GetResponseCode());
2969    EXPECT_EQ(307, r->response_headers()->response_code());
2970    std::string location;
2971    ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
2972                                                       &location));
2973    EXPECT_EQ(redirect_url, GURL(location));
2974
2975    // Let the request finish.
2976    r->FollowDeferredRedirect();
2977    base::RunLoop().Run();
2978
2979    EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
2980    EXPECT_TRUE(r->proxy_server().Equals(test_server_.host_port_pair()));
2981    EXPECT_EQ(
2982        1, network_delegate.observed_before_proxy_headers_sent_callbacks());
2983    EXPECT_TRUE(
2984        network_delegate.last_observed_proxy().Equals(
2985            test_server_.host_port_pair()));
2986    EXPECT_EQ(0, r->status().error());
2987    EXPECT_EQ(redirect_url, r->url());
2988    EXPECT_EQ(original_url, r->original_url());
2989    EXPECT_EQ(2U, r->url_chain().size());
2990    EXPECT_EQ(1, network_delegate.created_requests());
2991    EXPECT_EQ(0, network_delegate.destroyed_requests());
2992  }
2993  EXPECT_EQ(1, network_delegate.destroyed_requests());
2994}
2995
2996// Tests that redirects caused by the network delegate preserve POST data.
2997TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestPost) {
2998  ASSERT_TRUE(test_server_.Start());
2999
3000  const char kData[] = "hello world";
3001
3002  TestDelegate d;
3003  BlockingNetworkDelegate network_delegate(
3004      BlockingNetworkDelegate::AUTO_CALLBACK);
3005  network_delegate.set_block_on(BlockingNetworkDelegate::ON_BEFORE_URL_REQUEST);
3006  GURL redirect_url(test_server_.GetURL("echo"));
3007  network_delegate.set_redirect_url(redirect_url);
3008
3009  TestURLRequestContext context(true);
3010  context.set_network_delegate(&network_delegate);
3011  context.Init();
3012
3013  {
3014    GURL original_url(test_server_.GetURL("empty.html"));
3015    scoped_ptr<URLRequest> r(context.CreateRequest(
3016        original_url, DEFAULT_PRIORITY, &d, NULL));
3017    r->set_method("POST");
3018    r->set_upload(make_scoped_ptr(CreateSimpleUploadData(kData)));
3019    HttpRequestHeaders headers;
3020    headers.SetHeader(HttpRequestHeaders::kContentLength,
3021                      base::UintToString(arraysize(kData) - 1));
3022    r->SetExtraRequestHeaders(headers);
3023
3024    // Quit after hitting the redirect, so can check the headers.
3025    d.set_quit_on_redirect(true);
3026    r->Start();
3027    base::RunLoop().Run();
3028
3029    // Check headers from URLRequestJob.
3030    EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3031    EXPECT_EQ(307, r->GetResponseCode());
3032    EXPECT_EQ(307, r->response_headers()->response_code());
3033    std::string location;
3034    ASSERT_TRUE(r->response_headers()->EnumerateHeader(NULL, "Location",
3035                                                       &location));
3036    EXPECT_EQ(redirect_url, GURL(location));
3037
3038    // Let the request finish.
3039    r->FollowDeferredRedirect();
3040    base::RunLoop().Run();
3041
3042    EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3043    EXPECT_EQ(0, r->status().error());
3044    EXPECT_EQ(redirect_url, r->url());
3045    EXPECT_EQ(original_url, r->original_url());
3046    EXPECT_EQ(2U, r->url_chain().size());
3047    EXPECT_EQ(1, network_delegate.created_requests());
3048    EXPECT_EQ(0, network_delegate.destroyed_requests());
3049    EXPECT_EQ("POST", r->method());
3050    EXPECT_EQ(kData, d.data_received());
3051  }
3052  EXPECT_EQ(1, network_delegate.destroyed_requests());
3053}
3054
3055// Tests that the network delegate can block and redirect a request to a new
3056// URL during OnHeadersReceived.
3057TEST_F(URLRequestTestHTTP, NetworkDelegateRedirectRequestOnHeadersReceived) {
3058  ASSERT_TRUE(test_server_.Start());
3059
3060  TestDelegate d;
3061  BlockingNetworkDelegate network_delegate(
3062      BlockingNetworkDelegate::AUTO_CALLBACK);
3063  network_delegate.set_block_on(BlockingNetworkDelegate::ON_HEADERS_RECEIVED);
3064  GURL redirect_url(test_server_.GetURL("simple.html"));
3065  network_delegate.set_redirect_on_headers_received_url(redirect_url);
3066
3067  TestURLRequestContextWithProxy context(
3068      test_server_.host_port_pair().ToString(), &network_delegate);
3069
3070  {
3071    GURL original_url(test_server_.GetURL("empty.html"));
3072    scoped_ptr<URLRequest> r(context.CreateRequest(
3073        original_url, DEFAULT_PRIORITY, &d, NULL));
3074
3075    r->Start();
3076    base::RunLoop().Run();
3077
3078    EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3079    EXPECT_TRUE(r->proxy_server().Equals(test_server_.host_port_pair()));
3080    EXPECT_EQ(
3081        2, network_delegate.observed_before_proxy_headers_sent_callbacks());
3082    EXPECT_TRUE(
3083        network_delegate.last_observed_proxy().Equals(
3084            test_server_.host_port_pair()));
3085
3086    EXPECT_EQ(OK, r->status().error());
3087    EXPECT_EQ(redirect_url, r->url());
3088    EXPECT_EQ(original_url, r->original_url());
3089    EXPECT_EQ(2U, r->url_chain().size());
3090    EXPECT_EQ(2, network_delegate.created_requests());
3091    EXPECT_EQ(0, network_delegate.destroyed_requests());
3092  }
3093  EXPECT_EQ(1, network_delegate.destroyed_requests());
3094}
3095
3096// Tests that the network delegate can synchronously complete OnAuthRequired
3097// by taking no action. This indicates that the NetworkDelegate does not want to
3098// handle the challenge, and is passing the buck along to the
3099// URLRequest::Delegate.
3100TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncNoAction) {
3101  ASSERT_TRUE(test_server_.Start());
3102
3103  TestDelegate d;
3104  BlockingNetworkDelegate network_delegate(
3105      BlockingNetworkDelegate::SYNCHRONOUS);
3106
3107  TestURLRequestContext context(true);
3108  context.set_network_delegate(&network_delegate);
3109  context.Init();
3110
3111  d.set_credentials(AuthCredentials(kUser, kSecret));
3112
3113  {
3114    GURL url(test_server_.GetURL("auth-basic"));
3115    scoped_ptr<URLRequest> r(context.CreateRequest(
3116        url, DEFAULT_PRIORITY, &d, NULL));
3117    r->Start();
3118
3119    base::RunLoop().Run();
3120
3121    EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3122    EXPECT_EQ(0, r->status().error());
3123    EXPECT_EQ(200, r->GetResponseCode());
3124    EXPECT_TRUE(d.auth_required_called());
3125    EXPECT_EQ(1, network_delegate.created_requests());
3126    EXPECT_EQ(0, network_delegate.destroyed_requests());
3127  }
3128  EXPECT_EQ(1, network_delegate.destroyed_requests());
3129}
3130
3131TEST_F(URLRequestTestHTTP,
3132    NetworkDelegateOnAuthRequiredSyncNoAction_GetFullRequestHeaders) {
3133  ASSERT_TRUE(test_server_.Start());
3134
3135  TestDelegate d;
3136  BlockingNetworkDelegate network_delegate(
3137      BlockingNetworkDelegate::SYNCHRONOUS);
3138
3139  TestURLRequestContext context(true);
3140  context.set_network_delegate(&network_delegate);
3141  context.Init();
3142
3143  d.set_credentials(AuthCredentials(kUser, kSecret));
3144
3145  {
3146    GURL url(test_server_.GetURL("auth-basic"));
3147    scoped_ptr<URLRequest> r(context.CreateRequest(
3148        url, DEFAULT_PRIORITY, &d, NULL));
3149    r->Start();
3150
3151    {
3152      HttpRequestHeaders headers;
3153      EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
3154      EXPECT_FALSE(headers.HasHeader("Authorization"));
3155    }
3156
3157    base::RunLoop().Run();
3158
3159    EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3160    EXPECT_EQ(0, r->status().error());
3161    EXPECT_EQ(200, r->GetResponseCode());
3162    EXPECT_TRUE(d.auth_required_called());
3163    EXPECT_EQ(1, network_delegate.created_requests());
3164    EXPECT_EQ(0, network_delegate.destroyed_requests());
3165  }
3166  EXPECT_EQ(1, network_delegate.destroyed_requests());
3167}
3168
3169// Tests that the network delegate can synchronously complete OnAuthRequired
3170// by setting credentials.
3171TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncSetAuth) {
3172  ASSERT_TRUE(test_server_.Start());
3173
3174  TestDelegate d;
3175  BlockingNetworkDelegate network_delegate(
3176      BlockingNetworkDelegate::SYNCHRONOUS);
3177  network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3178  network_delegate.set_auth_retval(
3179      NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3180
3181  network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
3182
3183  TestURLRequestContext context(true);
3184  context.set_network_delegate(&network_delegate);
3185  context.Init();
3186
3187  {
3188    GURL url(test_server_.GetURL("auth-basic"));
3189    scoped_ptr<URLRequest> r(context.CreateRequest(
3190        url, DEFAULT_PRIORITY, &d, NULL));
3191    r->Start();
3192    base::RunLoop().Run();
3193
3194    EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3195    EXPECT_EQ(0, r->status().error());
3196    EXPECT_EQ(200, r->GetResponseCode());
3197    EXPECT_FALSE(d.auth_required_called());
3198    EXPECT_EQ(1, network_delegate.created_requests());
3199    EXPECT_EQ(0, network_delegate.destroyed_requests());
3200  }
3201  EXPECT_EQ(1, network_delegate.destroyed_requests());
3202}
3203
3204// Same as above, but also tests that GetFullRequestHeaders returns the proper
3205// headers (for the first or second request) when called at the proper times.
3206TEST_F(URLRequestTestHTTP,
3207    NetworkDelegateOnAuthRequiredSyncSetAuth_GetFullRequestHeaders) {
3208  ASSERT_TRUE(test_server_.Start());
3209
3210  TestDelegate d;
3211  BlockingNetworkDelegate network_delegate(
3212      BlockingNetworkDelegate::SYNCHRONOUS);
3213  network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3214  network_delegate.set_auth_retval(
3215      NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3216
3217  network_delegate.set_auth_credentials(AuthCredentials(kUser, kSecret));
3218
3219  TestURLRequestContext context(true);
3220  context.set_network_delegate(&network_delegate);
3221  context.Init();
3222
3223  {
3224    GURL url(test_server_.GetURL("auth-basic"));
3225    scoped_ptr<URLRequest> r(context.CreateRequest(
3226        url, DEFAULT_PRIORITY, &d, NULL));
3227    r->Start();
3228    base::RunLoop().Run();
3229
3230    EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3231    EXPECT_EQ(0, r->status().error());
3232    EXPECT_EQ(200, r->GetResponseCode());
3233    EXPECT_FALSE(d.auth_required_called());
3234    EXPECT_EQ(1, network_delegate.created_requests());
3235    EXPECT_EQ(0, network_delegate.destroyed_requests());
3236
3237    {
3238      HttpRequestHeaders headers;
3239      EXPECT_TRUE(r->GetFullRequestHeaders(&headers));
3240      EXPECT_TRUE(headers.HasHeader("Authorization"));
3241    }
3242  }
3243  EXPECT_EQ(1, network_delegate.destroyed_requests());
3244}
3245
3246// Tests that the network delegate can synchronously complete OnAuthRequired
3247// by cancelling authentication.
3248TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredSyncCancel) {
3249  ASSERT_TRUE(test_server_.Start());
3250
3251  TestDelegate d;
3252  BlockingNetworkDelegate network_delegate(
3253      BlockingNetworkDelegate::SYNCHRONOUS);
3254  network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3255  network_delegate.set_auth_retval(
3256      NetworkDelegate::AUTH_REQUIRED_RESPONSE_CANCEL_AUTH);
3257
3258  TestURLRequestContext context(true);
3259  context.set_network_delegate(&network_delegate);
3260  context.Init();
3261
3262  {
3263    GURL url(test_server_.GetURL("auth-basic"));
3264    scoped_ptr<URLRequest> r(context.CreateRequest(
3265        url, DEFAULT_PRIORITY, &d, NULL));
3266    r->Start();
3267    base::RunLoop().Run();
3268
3269    EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3270    EXPECT_EQ(OK, r->status().error());
3271    EXPECT_EQ(401, r->GetResponseCode());
3272    EXPECT_FALSE(d.auth_required_called());
3273    EXPECT_EQ(1, network_delegate.created_requests());
3274    EXPECT_EQ(0, network_delegate.destroyed_requests());
3275  }
3276  EXPECT_EQ(1, network_delegate.destroyed_requests());
3277}
3278
3279// Tests that the network delegate can asynchronously complete OnAuthRequired
3280// by taking no action. This indicates that the NetworkDelegate does not want
3281// to handle the challenge, and is passing the buck along to the
3282// URLRequest::Delegate.
3283TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncNoAction) {
3284  ASSERT_TRUE(test_server_.Start());
3285
3286  TestDelegate d;
3287  BlockingNetworkDelegate network_delegate(
3288      BlockingNetworkDelegate::AUTO_CALLBACK);
3289  network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3290
3291  TestURLRequestContext context(true);
3292  context.set_network_delegate(&network_delegate);
3293  context.Init();
3294
3295  d.set_credentials(AuthCredentials(kUser, kSecret));
3296
3297  {
3298    GURL url(test_server_.GetURL("auth-basic"));
3299    scoped_ptr<URLRequest> r(context.CreateRequest(
3300        url, DEFAULT_PRIORITY, &d, NULL));
3301    r->Start();
3302    base::RunLoop().Run();
3303
3304    EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3305    EXPECT_EQ(0, r->status().error());
3306    EXPECT_EQ(200, r->GetResponseCode());
3307    EXPECT_TRUE(d.auth_required_called());
3308    EXPECT_EQ(1, network_delegate.created_requests());
3309    EXPECT_EQ(0, network_delegate.destroyed_requests());
3310  }
3311  EXPECT_EQ(1, network_delegate.destroyed_requests());
3312}
3313
3314// Tests that the network delegate can asynchronously complete OnAuthRequired
3315// by setting credentials.
3316TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncSetAuth) {
3317  ASSERT_TRUE(test_server_.Start());
3318
3319  TestDelegate d;
3320  BlockingNetworkDelegate network_delegate(
3321      BlockingNetworkDelegate::AUTO_CALLBACK);
3322  network_delegate.set_block_on(BlockingNetworkDelegate::ON_AUTH_REQUIRED);
3323  network_delegate.set_auth_retval(
3324      NetworkDelegate::AUTH_REQUIRED_RESPONSE_SET_AUTH);
3325
3326  AuthCredentials auth_credentials(kUser, kSecret);
3327  network_delegate.set_auth_credentials(auth_credentials);
3328
3329  TestURLRequestContext context(true);
3330  context.set_network_delegate(&network_delegate);
3331  context.Init();
3332
3333  {
3334    GURL url(test_server_.GetURL("auth-basic"));
3335    scoped_ptr<URLRequest> r(context.CreateRequest(
3336        url, DEFAULT_PRIORITY, &d, NULL));
3337    r->Start();
3338    base::RunLoop().Run();
3339
3340    EXPECT_EQ(URLRequestStatus::SUCCESS, r->status().status());
3341    EXPECT_EQ(0, r->status().error());
3342
3343    EXPECT_EQ(200, r->GetResponseCode());
3344    EXPECT_FALSE(d.auth_required_called());
3345    EXPECT_EQ(1, network_delegate.created_requests());
3346    EXPECT_EQ(0, network_delegate.destroyed_requests());
3347  }
3348  EXPECT_EQ(1, network_delegate.destroyed_requests());
3349}
3350
3351// Tests that the network delegate can asynchronously complete OnAuthRequired
3352// by cancelling authentication.
3353TEST_F(URLRequestTestHTTP, NetworkDelegateOnAuthRequiredAsyncCancel) {