1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef NET_URL_REQUEST_URL_REQUEST_TEST_UTIL_H_
6 #define NET_URL_REQUEST_URL_REQUEST_TEST_UTIL_H_
13 #include "base/basictypes.h"
14 #include "base/compiler_specific.h"
15 #include "base/memory/ref_counted.h"
16 #include "base/memory/scoped_ptr.h"
17 #include "base/message_loop/message_loop_proxy.h"
18 #include "base/path_service.h"
19 #include "base/strings/string16.h"
20 #include "base/strings/string_util.h"
21 #include "base/strings/utf_string_conversions.h"
22 #include "base/time/time.h"
23 #include "net/base/io_buffer.h"
24 #include "net/base/load_timing_info.h"
25 #include "net/base/net_errors.h"
26 #include "net/base/network_delegate.h"
27 #include "net/base/request_priority.h"
28 #include "net/cert/cert_verifier.h"
29 #include "net/cookies/cookie_monster.h"
30 #include "net/disk_cache/disk_cache.h"
31 #include "net/ftp/ftp_network_layer.h"
32 #include "net/http/http_auth_handler_factory.h"
33 #include "net/http/http_cache.h"
34 #include "net/http/http_network_layer.h"
35 #include "net/http/http_network_session.h"
36 #include "net/http/http_request_headers.h"
37 #include "net/proxy/proxy_service.h"
38 #include "net/ssl/ssl_config_service_defaults.h"
39 #include "net/url_request/url_request.h"
40 #include "net/url_request/url_request_context.h"
41 #include "net/url_request/url_request_context_getter.h"
42 #include "net/url_request/url_request_context_storage.h"
43 #include "net/url_request/url_request_job_factory.h"
44 #include "url/url_util.h"
46 using base::TimeDelta
;
50 //-----------------------------------------------------------------------------
52 class TestURLRequestContext
: public URLRequestContext
{
54 TestURLRequestContext();
55 // Default constructor like TestURLRequestContext() but does not call
56 // Init() in case |delay_initialization| is true. This allows modifying the
57 // URLRequestContext before it is constructed completely. If
58 // |delay_initialization| is true, Init() needs be be called manually.
59 explicit TestURLRequestContext(bool delay_initialization
);
60 virtual ~TestURLRequestContext();
64 ClientSocketFactory
* client_socket_factory() {
65 return client_socket_factory_
;
67 void set_client_socket_factory(ClientSocketFactory
* factory
) {
68 client_socket_factory_
= factory
;
71 void set_http_network_session_params(
72 const HttpNetworkSession::Params
& params
) {
78 // Optional parameters to override default values. Note that values that
79 // point to other objects the TestURLRequestContext creates will be
81 scoped_ptr
<HttpNetworkSession::Params
> http_network_session_params_
;
84 ClientSocketFactory
* client_socket_factory_
;
87 URLRequestContextStorage context_storage_
;
90 //-----------------------------------------------------------------------------
92 // Used to return a dummy context, which lives on the message loop
93 // given in the constructor.
94 class TestURLRequestContextGetter
: public URLRequestContextGetter
{
96 // |network_task_runner| must not be NULL.
97 explicit TestURLRequestContextGetter(
98 const scoped_refptr
<base::SingleThreadTaskRunner
>& network_task_runner
);
100 // Use to pass a pre-initialized |context|.
101 TestURLRequestContextGetter(
102 const scoped_refptr
<base::SingleThreadTaskRunner
>& network_task_runner
,
103 scoped_ptr
<TestURLRequestContext
> context
);
105 // URLRequestContextGetter implementation.
106 virtual TestURLRequestContext
* GetURLRequestContext() OVERRIDE
;
107 virtual scoped_refptr
<base::SingleThreadTaskRunner
>
108 GetNetworkTaskRunner() const OVERRIDE
;
111 virtual ~TestURLRequestContextGetter();
114 const scoped_refptr
<base::SingleThreadTaskRunner
> network_task_runner_
;
115 scoped_ptr
<TestURLRequestContext
> context_
;
118 //-----------------------------------------------------------------------------
120 class TestURLRequest
: public URLRequest
{
122 TestURLRequest(const GURL
& url
,
123 RequestPriority priority
,
125 TestURLRequestContext
* context
);
126 virtual ~TestURLRequest();
129 //-----------------------------------------------------------------------------
131 class TestDelegate
: public URLRequest::Delegate
{
134 virtual ~TestDelegate();
136 void set_cancel_in_received_redirect(bool val
) { cancel_in_rr_
= val
; }
137 void set_cancel_in_response_started(bool val
) { cancel_in_rs_
= val
; }
138 void set_cancel_in_received_data(bool val
) { cancel_in_rd_
= val
; }
139 void set_cancel_in_received_data_pending(bool val
) {
140 cancel_in_rd_pending_
= val
;
142 void set_quit_on_complete(bool val
) { quit_on_complete_
= val
; }
143 void set_quit_on_redirect(bool val
) { quit_on_redirect_
= val
; }
144 void set_quit_on_network_start(bool val
) {
145 quit_on_before_network_start_
= val
;
147 void set_allow_certificate_errors(bool val
) {
148 allow_certificate_errors_
= val
;
150 void set_credentials(const AuthCredentials
& credentials
) {
151 credentials_
= credentials
;
155 const std::string
& data_received() const { return data_received_
; }
156 int bytes_received() const { return static_cast<int>(data_received_
.size()); }
157 int response_started_count() const { return response_started_count_
; }
158 int received_redirect_count() const { return received_redirect_count_
; }
159 int received_before_network_start_count() const {
160 return received_before_network_start_count_
;
162 bool received_data_before_response() const {
163 return received_data_before_response_
;
165 bool request_failed() const { return request_failed_
; }
166 bool have_certificate_errors() const { return have_certificate_errors_
; }
167 bool certificate_errors_are_fatal() const {
168 return certificate_errors_are_fatal_
;
170 bool auth_required_called() const { return auth_required_
; }
171 bool have_full_request_headers() const { return have_full_request_headers_
; }
172 const HttpRequestHeaders
& full_request_headers() const {
173 return full_request_headers_
;
175 void ClearFullRequestHeaders();
177 // URLRequest::Delegate:
178 virtual void OnReceivedRedirect(URLRequest
* request
, const GURL
& new_url
,
179 bool* defer_redirect
) OVERRIDE
;
180 virtual void OnBeforeNetworkStart(URLRequest
* request
, bool* defer
) OVERRIDE
;
181 virtual void OnAuthRequired(URLRequest
* request
,
182 AuthChallengeInfo
* auth_info
) OVERRIDE
;
183 // NOTE: |fatal| causes |certificate_errors_are_fatal_| to be set to true.
184 // (Unit tests use this as a post-condition.) But for policy, this method
185 // consults |allow_certificate_errors_|.
186 virtual void OnSSLCertificateError(URLRequest
* request
,
187 const SSLInfo
& ssl_info
,
188 bool fatal
) OVERRIDE
;
189 virtual void OnResponseStarted(URLRequest
* request
) OVERRIDE
;
190 virtual void OnReadCompleted(URLRequest
* request
,
191 int bytes_read
) OVERRIDE
;
194 static const int kBufferSize
= 4096;
196 virtual void OnResponseCompleted(URLRequest
* request
);
198 // options for controlling behavior
202 bool cancel_in_rd_pending_
;
203 bool quit_on_complete_
;
204 bool quit_on_redirect_
;
205 bool quit_on_before_network_start_
;
206 bool allow_certificate_errors_
;
207 AuthCredentials credentials_
;
209 // tracks status of callbacks
210 int response_started_count_
;
211 int received_bytes_count_
;
212 int received_redirect_count_
;
213 int received_before_network_start_count_
;
214 bool received_data_before_response_
;
215 bool request_failed_
;
216 bool have_certificate_errors_
;
217 bool certificate_errors_are_fatal_
;
219 std::string data_received_
;
220 bool have_full_request_headers_
;
221 HttpRequestHeaders full_request_headers_
;
224 scoped_refptr
<IOBuffer
> buf_
;
227 //-----------------------------------------------------------------------------
229 class TestNetworkDelegate
: public NetworkDelegate
{
232 NO_GET_COOKIES
= 1 << 0,
233 NO_SET_COOKIE
= 1 << 1,
236 TestNetworkDelegate();
237 virtual ~TestNetworkDelegate();
239 // Writes the LoadTimingInfo during the most recent call to OnBeforeRedirect.
240 bool GetLoadTimingInfoBeforeRedirect(
241 LoadTimingInfo
* load_timing_info_before_redirect
) const;
243 // Same as GetLoadTimingInfoBeforeRedirect, except for calls to
244 // AuthRequiredResponse.
245 bool GetLoadTimingInfoBeforeAuth(
246 LoadTimingInfo
* load_timing_info_before_auth
) const;
248 // Will redirect once to the given URL when the next set of headers are
250 void set_redirect_on_headers_received_url(
251 GURL redirect_on_headers_received_url
) {
252 redirect_on_headers_received_url_
= redirect_on_headers_received_url
;
255 void set_allowed_unsafe_redirect_url(GURL allowed_unsafe_redirect_url
) {
256 allowed_unsafe_redirect_url_
= allowed_unsafe_redirect_url
;
259 void set_cookie_options(int o
) {cookie_options_bit_mask_
= o
; }
261 int last_error() const { return last_error_
; }
262 int error_count() const { return error_count_
; }
263 int created_requests() const { return created_requests_
; }
264 int destroyed_requests() const { return destroyed_requests_
; }
265 int completed_requests() const { return completed_requests_
; }
266 int canceled_requests() const { return canceled_requests_
; }
267 int blocked_get_cookies_count() const { return blocked_get_cookies_count_
; }
268 int blocked_set_cookie_count() const { return blocked_set_cookie_count_
; }
269 int set_cookie_count() const { return set_cookie_count_
; }
271 void set_can_access_files(bool val
) { can_access_files_
= val
; }
272 bool can_access_files() const { return can_access_files_
; }
274 void set_can_throttle_requests(bool val
) { can_throttle_requests_
= val
; }
275 bool can_throttle_requests() const { return can_throttle_requests_
; }
277 int observed_before_proxy_headers_sent_callbacks() const {
278 return observed_before_proxy_headers_sent_callbacks_
;
281 // Last observed proxy in proxy header sent callback.
282 HostPortPair
last_observed_proxy() {
283 return last_observed_proxy_
;
288 virtual int OnBeforeURLRequest(URLRequest
* request
,
289 const CompletionCallback
& callback
,
290 GURL
* new_url
) OVERRIDE
;
291 virtual int OnBeforeSendHeaders(URLRequest
* request
,
292 const CompletionCallback
& callback
,
293 HttpRequestHeaders
* headers
) OVERRIDE
;
294 virtual void OnBeforeSendProxyHeaders(
295 net::URLRequest
* request
,
296 const net::ProxyInfo
& proxy_info
,
297 net::HttpRequestHeaders
* headers
) OVERRIDE
;
298 virtual void OnSendHeaders(URLRequest
* request
,
299 const HttpRequestHeaders
& headers
) OVERRIDE
;
300 virtual int OnHeadersReceived(
302 const CompletionCallback
& callback
,
303 const HttpResponseHeaders
* original_response_headers
,
304 scoped_refptr
<HttpResponseHeaders
>* override_response_headers
,
305 GURL
* allowed_unsafe_redirect_url
) OVERRIDE
;
306 virtual void OnBeforeRedirect(URLRequest
* request
,
307 const GURL
& new_location
) OVERRIDE
;
308 virtual void OnResponseStarted(URLRequest
* request
) OVERRIDE
;
309 virtual void OnRawBytesRead(const URLRequest
& request
,
310 int bytes_read
) OVERRIDE
;
311 virtual void OnCompleted(URLRequest
* request
, bool started
) OVERRIDE
;
312 virtual void OnURLRequestDestroyed(URLRequest
* request
) OVERRIDE
;
313 virtual void OnPACScriptError(int line_number
,
314 const base::string16
& error
) OVERRIDE
;
315 virtual NetworkDelegate::AuthRequiredResponse
OnAuthRequired(
317 const AuthChallengeInfo
& auth_info
,
318 const AuthCallback
& callback
,
319 AuthCredentials
* credentials
) OVERRIDE
;
320 virtual bool OnCanGetCookies(const URLRequest
& request
,
321 const CookieList
& cookie_list
) OVERRIDE
;
322 virtual bool OnCanSetCookie(const URLRequest
& request
,
323 const std::string
& cookie_line
,
324 CookieOptions
* options
) OVERRIDE
;
325 virtual bool OnCanAccessFile(const URLRequest
& request
,
326 const base::FilePath
& path
) const OVERRIDE
;
327 virtual bool OnCanThrottleRequest(
328 const URLRequest
& request
) const OVERRIDE
;
329 virtual int OnBeforeSocketStreamConnect(
330 SocketStream
* stream
,
331 const CompletionCallback
& callback
) OVERRIDE
;
333 void InitRequestStatesIfNew(int request_id
);
335 GURL redirect_on_headers_received_url_
;
336 // URL marked as safe for redirection at the onHeadersReceived stage.
337 GURL allowed_unsafe_redirect_url_
;
341 int created_requests_
;
342 int destroyed_requests_
;
343 int completed_requests_
;
344 int canceled_requests_
;
345 int cookie_options_bit_mask_
;
346 int blocked_get_cookies_count_
;
347 int blocked_set_cookie_count_
;
348 int set_cookie_count_
;
349 int observed_before_proxy_headers_sent_callbacks_
;
350 // Last observed proxy in before proxy header sent callback.
351 HostPortPair last_observed_proxy_
;
353 // NetworkDelegate callbacks happen in a particular order (e.g.
354 // OnBeforeURLRequest is always called before OnBeforeSendHeaders).
355 // This bit-set indicates for each request id (key) what events may be sent
357 std::map
<int, int> next_states_
;
359 // A log that records for each request id (key) the order in which On...
360 // functions were called.
361 std::map
<int, std::string
> event_order_
;
363 LoadTimingInfo load_timing_info_before_redirect_
;
364 bool has_load_timing_info_before_redirect_
;
366 LoadTimingInfo load_timing_info_before_auth_
;
367 bool has_load_timing_info_before_auth_
;
369 bool can_access_files_
; // true by default
370 bool can_throttle_requests_
; // true by default
373 // Overrides the host used by the LocalHttpTestServer in
374 // url_request_unittest.cc . This is used by the chrome_frame_net_tests due to
375 // a mysterious bug when tests execute over the loopback adapter. See
376 // http://crbug.com/114369 .
377 class ScopedCustomUrlRequestTestHttpHost
{
379 // Sets the host name to be used. The previous hostname will be stored and
380 // restored upon destruction. Note that if the lifetimes of two or more
381 // instances of this class overlap, they must be strictly nested.
382 explicit ScopedCustomUrlRequestTestHttpHost(const std::string
& new_value
);
384 ~ScopedCustomUrlRequestTestHttpHost();
386 // Returns the current value to be used by HTTP tests in
387 // url_request_unittest.cc .
388 static const std::string
& value();
391 static std::string value_
;
392 const std::string old_value_
;
393 const std::string new_value_
;
395 DISALLOW_COPY_AND_ASSIGN(ScopedCustomUrlRequestTestHttpHost
);
398 //-----------------------------------------------------------------------------
400 // A simple ProtocolHandler that returns a pre-built URLRequestJob only once.
401 class TestJobInterceptor
: public URLRequestJobFactory::ProtocolHandler
{
403 TestJobInterceptor();
405 virtual URLRequestJob
* MaybeCreateJob(
407 NetworkDelegate
* network_delegate
) const OVERRIDE
;
408 void set_main_intercept_job(URLRequestJob
* job
);
411 mutable URLRequestJob
* main_intercept_job_
;
416 #endif // NET_URL_REQUEST_URL_REQUEST_TEST_UTIL_H_