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 #ifndef NET_URL_REQUEST_URL_REQUEST_TEST_UTIL_H_ 6 #define NET_URL_REQUEST_URL_REQUEST_TEST_UTIL_H_ 7 8 #include <stdlib.h> 9 10 #include <map> 11 #include <string> 12 13 #include "base/basictypes.h" 14 #include "base/compiler_specific.h" 15 #include "base/memory/ref_counted.h" 16 #include "base/message_loop/message_loop_proxy.h" 17 #include "base/path_service.h" 18 #include "base/strings/string16.h" 19 #include "base/strings/string_util.h" 20 #include "base/strings/utf_string_conversions.h" 21 #include "base/time/time.h" 22 #include "net/base/io_buffer.h" 23 #include "net/base/load_timing_info.h" 24 #include "net/base/net_errors.h" 25 #include "net/base/network_delegate.h" 26 #include "net/base/request_priority.h" 27 #include "net/cert/cert_verifier.h" 28 #include "net/cookies/cookie_monster.h" 29 #include "net/disk_cache/disk_cache.h" 30 #include "net/ftp/ftp_network_layer.h" 31 #include "net/http/http_auth_handler_factory.h" 32 #include "net/http/http_cache.h" 33 #include "net/http/http_network_layer.h" 34 #include "net/http/http_request_headers.h" 35 #include "net/proxy/proxy_service.h" 36 #include "net/ssl/ssl_config_service_defaults.h" 37 #include "net/url_request/url_request.h" 38 #include "net/url_request/url_request_context.h" 39 #include "net/url_request/url_request_context_getter.h" 40 #include "net/url_request/url_request_context_storage.h" 41 #include "net/url_request/url_request_job_factory.h" 42 #include "url/url_util.h" 43 44 using base::TimeDelta; 45 46 namespace net { 47 48 //----------------------------------------------------------------------------- 49 50 class TestURLRequestContext : public URLRequestContext { 51 public: 52 TestURLRequestContext(); 53 // Default constructor like TestURLRequestContext() but does not call 54 // Init() in case |delay_initialization| is true. This allows modifying the 55 // URLRequestContext before it is constructed completely. If 56 // |delay_initialization| is true, Init() needs be be called manually. 57 explicit TestURLRequestContext(bool delay_initialization); 58 virtual ~TestURLRequestContext(); 59 60 void Init(); 61 62 ClientSocketFactory* client_socket_factory() { 63 return client_socket_factory_; 64 } 65 void set_client_socket_factory(ClientSocketFactory* factory) { 66 client_socket_factory_ = factory; 67 } 68 69 private: 70 bool initialized_; 71 72 // Not owned: 73 ClientSocketFactory* client_socket_factory_; 74 75 protected: 76 URLRequestContextStorage context_storage_; 77 }; 78 79 //----------------------------------------------------------------------------- 80 81 // Used to return a dummy context, which lives on the message loop 82 // given in the constructor. 83 class TestURLRequestContextGetter : public URLRequestContextGetter { 84 public: 85 // |network_task_runner| must not be NULL. 86 explicit TestURLRequestContextGetter( 87 const scoped_refptr<base::SingleThreadTaskRunner>& network_task_runner); 88 89 // Use to pass a pre-initialized |context|. 90 TestURLRequestContextGetter( 91 const scoped_refptr<base::SingleThreadTaskRunner>& network_task_runner, 92 scoped_ptr<TestURLRequestContext> context); 93 94 // URLRequestContextGetter implementation. 95 virtual TestURLRequestContext* GetURLRequestContext() OVERRIDE; 96 virtual scoped_refptr<base::SingleThreadTaskRunner> 97 GetNetworkTaskRunner() const OVERRIDE; 98 99 protected: 100 virtual ~TestURLRequestContextGetter(); 101 102 private: 103 const scoped_refptr<base::SingleThreadTaskRunner> network_task_runner_; 104 scoped_ptr<TestURLRequestContext> context_; 105 }; 106 107 //----------------------------------------------------------------------------- 108 109 class TestURLRequest : public URLRequest { 110 public: 111 TestURLRequest(const GURL& url, 112 RequestPriority priority, 113 Delegate* delegate, 114 TestURLRequestContext* context); 115 virtual ~TestURLRequest(); 116 }; 117 118 //----------------------------------------------------------------------------- 119 120 class TestDelegate : public URLRequest::Delegate { 121 public: 122 TestDelegate(); 123 virtual ~TestDelegate(); 124 125 void set_cancel_in_received_redirect(bool val) { cancel_in_rr_ = val; } 126 void set_cancel_in_response_started(bool val) { cancel_in_rs_ = val; } 127 void set_cancel_in_received_data(bool val) { cancel_in_rd_ = val; } 128 void set_cancel_in_received_data_pending(bool val) { 129 cancel_in_rd_pending_ = val; 130 } 131 void set_quit_on_complete(bool val) { quit_on_complete_ = val; } 132 void set_quit_on_redirect(bool val) { quit_on_redirect_ = val; } 133 void set_allow_certificate_errors(bool val) { 134 allow_certificate_errors_ = val; 135 } 136 void set_credentials(const AuthCredentials& credentials) { 137 credentials_ = credentials; 138 } 139 140 // query state 141 const std::string& data_received() const { return data_received_; } 142 int bytes_received() const { return static_cast<int>(data_received_.size()); } 143 int response_started_count() const { return response_started_count_; } 144 int received_redirect_count() const { return received_redirect_count_; } 145 bool received_data_before_response() const { 146 return received_data_before_response_; 147 } 148 bool request_failed() const { return request_failed_; } 149 bool have_certificate_errors() const { return have_certificate_errors_; } 150 bool certificate_errors_are_fatal() const { 151 return certificate_errors_are_fatal_; 152 } 153 bool auth_required_called() const { return auth_required_; } 154 bool have_full_request_headers() const { return have_full_request_headers_; } 155 const HttpRequestHeaders& full_request_headers() const { 156 return full_request_headers_; 157 } 158 void ClearFullRequestHeaders(); 159 160 // URLRequest::Delegate: 161 virtual void OnReceivedRedirect(URLRequest* request, const GURL& new_url, 162 bool* defer_redirect) OVERRIDE; 163 virtual void OnAuthRequired(URLRequest* request, 164 AuthChallengeInfo* auth_info) OVERRIDE; 165 // NOTE: |fatal| causes |certificate_errors_are_fatal_| to be set to true. 166 // (Unit tests use this as a post-condition.) But for policy, this method 167 // consults |allow_certificate_errors_|. 168 virtual void OnSSLCertificateError(URLRequest* request, 169 const SSLInfo& ssl_info, 170 bool fatal) OVERRIDE; 171 virtual void OnResponseStarted(URLRequest* request) OVERRIDE; 172 virtual void OnReadCompleted(URLRequest* request, 173 int bytes_read) OVERRIDE; 174 175 private: 176 static const int kBufferSize = 4096; 177 178 virtual void OnResponseCompleted(URLRequest* request); 179 180 // options for controlling behavior 181 bool cancel_in_rr_; 182 bool cancel_in_rs_; 183 bool cancel_in_rd_; 184 bool cancel_in_rd_pending_; 185 bool quit_on_complete_; 186 bool quit_on_redirect_; 187 bool allow_certificate_errors_; 188 AuthCredentials credentials_; 189 190 // tracks status of callbacks 191 int response_started_count_; 192 int received_bytes_count_; 193 int received_redirect_count_; 194 bool received_data_before_response_; 195 bool request_failed_; 196 bool have_certificate_errors_; 197 bool certificate_errors_are_fatal_; 198 bool auth_required_; 199 std::string data_received_; 200 bool have_full_request_headers_; 201 HttpRequestHeaders full_request_headers_; 202 203 // our read buffer 204 scoped_refptr<IOBuffer> buf_; 205 }; 206 207 //----------------------------------------------------------------------------- 208 209 class TestNetworkDelegate : public NetworkDelegate { 210 public: 211 enum Options { 212 NO_GET_COOKIES = 1 << 0, 213 NO_SET_COOKIE = 1 << 1, 214 }; 215 216 TestNetworkDelegate(); 217 virtual ~TestNetworkDelegate(); 218 219 // Writes the LoadTimingInfo during the most recent call to OnBeforeRedirect. 220 bool GetLoadTimingInfoBeforeRedirect( 221 LoadTimingInfo* load_timing_info_before_redirect) const; 222 223 // Same as GetLoadTimingInfoBeforeRedirect, except for calls to 224 // AuthRequiredResponse. 225 bool GetLoadTimingInfoBeforeAuth( 226 LoadTimingInfo* load_timing_info_before_auth) const; 227 228 void set_cookie_options(int o) {cookie_options_bit_mask_ = o; } 229 230 int last_error() const { return last_error_; } 231 int error_count() const { return error_count_; } 232 int created_requests() const { return created_requests_; } 233 int destroyed_requests() const { return destroyed_requests_; } 234 int completed_requests() const { return completed_requests_; } 235 int canceled_requests() const { return canceled_requests_; } 236 int blocked_get_cookies_count() const { return blocked_get_cookies_count_; } 237 int blocked_set_cookie_count() const { return blocked_set_cookie_count_; } 238 int set_cookie_count() const { return set_cookie_count_; } 239 240 void set_can_access_files(bool val) { can_access_files_ = val; } 241 bool can_access_files() const { return can_access_files_; } 242 243 void set_can_throttle_requests(bool val) { can_throttle_requests_ = val; } 244 bool can_throttle_requests() const { return can_throttle_requests_; } 245 246 protected: 247 // NetworkDelegate: 248 virtual int OnBeforeURLRequest(URLRequest* request, 249 const CompletionCallback& callback, 250 GURL* new_url) OVERRIDE; 251 virtual int OnBeforeSendHeaders(URLRequest* request, 252 const CompletionCallback& callback, 253 HttpRequestHeaders* headers) OVERRIDE; 254 virtual void OnSendHeaders(URLRequest* request, 255 const HttpRequestHeaders& headers) OVERRIDE; 256 virtual int OnHeadersReceived( 257 URLRequest* request, 258 const CompletionCallback& callback, 259 const HttpResponseHeaders* original_response_headers, 260 scoped_refptr<HttpResponseHeaders>* override_response_headers) OVERRIDE; 261 virtual void OnBeforeRedirect(URLRequest* request, 262 const GURL& new_location) OVERRIDE; 263 virtual void OnResponseStarted(URLRequest* request) OVERRIDE; 264 virtual void OnRawBytesRead(const URLRequest& request, 265 int bytes_read) OVERRIDE; 266 virtual void OnCompleted(URLRequest* request, bool started) OVERRIDE; 267 virtual void OnURLRequestDestroyed(URLRequest* request) OVERRIDE; 268 virtual void OnPACScriptError(int line_number, 269 const base::string16& error) OVERRIDE; 270 virtual NetworkDelegate::AuthRequiredResponse OnAuthRequired( 271 URLRequest* request, 272 const AuthChallengeInfo& auth_info, 273 const AuthCallback& callback, 274 AuthCredentials* credentials) OVERRIDE; 275 virtual bool OnCanGetCookies(const URLRequest& request, 276 const CookieList& cookie_list) OVERRIDE; 277 virtual bool OnCanSetCookie(const URLRequest& request, 278 const std::string& cookie_line, 279 CookieOptions* options) OVERRIDE; 280 virtual bool OnCanAccessFile(const URLRequest& request, 281 const base::FilePath& path) const OVERRIDE; 282 virtual bool OnCanThrottleRequest( 283 const URLRequest& request) const OVERRIDE; 284 virtual int OnBeforeSocketStreamConnect( 285 SocketStream* stream, 286 const CompletionCallback& callback) OVERRIDE; 287 virtual void OnRequestWaitStateChange(const URLRequest& request, 288 RequestWaitState state) OVERRIDE; 289 290 void InitRequestStatesIfNew(int request_id); 291 292 int last_error_; 293 int error_count_; 294 int created_requests_; 295 int destroyed_requests_; 296 int completed_requests_; 297 int canceled_requests_; 298 int cookie_options_bit_mask_; 299 int blocked_get_cookies_count_; 300 int blocked_set_cookie_count_; 301 int set_cookie_count_; 302 303 // NetworkDelegate callbacks happen in a particular order (e.g. 304 // OnBeforeURLRequest is always called before OnBeforeSendHeaders). 305 // This bit-set indicates for each request id (key) what events may be sent 306 // next. 307 std::map<int, int> next_states_; 308 309 // A log that records for each request id (key) the order in which On... 310 // functions were called. 311 std::map<int, std::string> event_order_; 312 313 LoadTimingInfo load_timing_info_before_redirect_; 314 bool has_load_timing_info_before_redirect_; 315 316 LoadTimingInfo load_timing_info_before_auth_; 317 bool has_load_timing_info_before_auth_; 318 319 bool can_access_files_; // true by default 320 bool can_throttle_requests_; // true by default 321 }; 322 323 // Overrides the host used by the LocalHttpTestServer in 324 // url_request_unittest.cc . This is used by the chrome_frame_net_tests due to 325 // a mysterious bug when tests execute over the loopback adapter. See 326 // http://crbug.com/114369 . 327 class ScopedCustomUrlRequestTestHttpHost { 328 public: 329 // Sets the host name to be used. The previous hostname will be stored and 330 // restored upon destruction. Note that if the lifetimes of two or more 331 // instances of this class overlap, they must be strictly nested. 332 explicit ScopedCustomUrlRequestTestHttpHost(const std::string& new_value); 333 334 ~ScopedCustomUrlRequestTestHttpHost(); 335 336 // Returns the current value to be used by HTTP tests in 337 // url_request_unittest.cc . 338 static const std::string& value(); 339 340 private: 341 static std::string value_; 342 const std::string old_value_; 343 const std::string new_value_; 344 345 DISALLOW_COPY_AND_ASSIGN(ScopedCustomUrlRequestTestHttpHost); 346 }; 347 348 //----------------------------------------------------------------------------- 349 350 // A simple ProtocolHandler that returns a pre-built URLRequestJob only once. 351 class TestJobInterceptor : public URLRequestJobFactory::ProtocolHandler { 352 public: 353 TestJobInterceptor(); 354 355 virtual URLRequestJob* MaybeCreateJob( 356 URLRequest* request, 357 NetworkDelegate* network_delegate) const OVERRIDE; 358 void set_main_intercept_job(URLRequestJob* job); 359 360 private: 361 mutable URLRequestJob* main_intercept_job_; 362 }; 363 364 } // namespace net 365 366 #endif // NET_URL_REQUEST_URL_REQUEST_TEST_UTIL_H_ 367