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_TEST_URL_FETCHER_FACTORY_H_
6 #define NET_URL_REQUEST_TEST_URL_FETCHER_FACTORY_H_
13 #include "base/basictypes.h"
14 #include "base/callback.h"
15 #include "base/compiler_specific.h"
16 #include "base/files/file_path.h"
17 #include "base/memory/scoped_ptr.h"
18 #include "base/memory/weak_ptr.h"
19 #include "base/threading/non_thread_safe.h"
20 #include "net/http/http_request_headers.h"
21 #include "net/http/http_status_code.h"
22 #include "net/url_request/url_fetcher_factory.h"
23 #include "net/url_request/url_request_status.h"
28 // Changes URLFetcher's Factory for the lifetime of the object.
29 // Note that this scoper cannot be nested (to make it even harder to misuse).
30 class ScopedURLFetcherFactory
: public base::NonThreadSafe
{
32 explicit ScopedURLFetcherFactory(URLFetcherFactory
* factory
);
33 virtual ~ScopedURLFetcherFactory();
36 DISALLOW_COPY_AND_ASSIGN(ScopedURLFetcherFactory
);
39 // TestURLFetcher and TestURLFetcherFactory are used for testing consumers of
40 // URLFetcher. TestURLFetcherFactory is a URLFetcherFactory that creates
41 // TestURLFetchers. TestURLFetcher::Start is overriden to do nothing. It is
42 // expected that you'll grab the delegate from the TestURLFetcher and invoke
43 // the callback method when appropriate. In this way it's easy to mock a
46 // // TestURLFetcher requires a MessageLoop.
47 // MessageLoop message_loop;
48 // // And an IO thread to release URLRequestContextGetter in URLFetcher::Core.
49 // BrowserThreadImpl io_thread(BrowserThread::IO, &message_loop);
50 // // Create factory (it automatically sets itself as URLFetcher's factory).
51 // TestURLFetcherFactory factory;
52 // // Do something that triggers creation of a URLFetcher.
54 // TestURLFetcher* fetcher = factory.GetFetcherByID(expected_id);
56 // // Notify delegate with whatever data you want.
57 // fetcher->delegate()->OnURLFetchComplete(...);
58 // // Make sure consumer of URLFetcher does the right thing.
61 // Note: if you don't know when your request objects will be created you
62 // might want to use the FakeURLFetcher and FakeURLFetcherFactory classes
65 class TestURLFetcherFactory
;
66 class TestURLFetcher
: public URLFetcher
{
68 // Interface for tests to intercept production code classes using URLFetcher.
69 // Allows even-driven mock server classes to analyze the correctness of
70 // requests / uploads events and forge responses back at the right moment.
71 class DelegateForTests
{
73 // Callback issued correspondingly to the call to the |Start()| method.
74 virtual void OnRequestStart(int fetcher_id
) = 0;
76 // Callback issued correspondingly to the call to |AppendChunkToUpload|.
77 // Uploaded chunks can be retrieved with the |upload_chunks()| getter.
78 virtual void OnChunkUpload(int fetcher_id
) = 0;
80 // Callback issued correspondingly to the destructor.
81 virtual void OnRequestEnd(int fetcher_id
) = 0;
84 TestURLFetcher(int id
,
86 URLFetcherDelegate
* d
);
87 ~TestURLFetcher() override
;
89 // URLFetcher implementation
90 void SetUploadData(const std::string
& upload_content_type
,
91 const std::string
& upload_content
) override
;
92 void SetUploadFilePath(
93 const std::string
& upload_content_type
,
94 const base::FilePath
& file_path
,
97 scoped_refptr
<base::TaskRunner
> file_task_runner
) override
;
98 void SetChunkedUpload(const std::string
& upload_content_type
) override
;
99 // Overriden to cache the chunks uploaded. Caller can read back the uploaded
100 // chunks with the upload_chunks() accessor.
101 void AppendChunkToUpload(const std::string
& data
,
102 bool is_last_chunk
) override
;
103 void SetLoadFlags(int load_flags
) override
;
104 int GetLoadFlags() const override
;
105 void SetReferrer(const std::string
& referrer
) override
;
106 void SetReferrerPolicy(URLRequest::ReferrerPolicy referrer_policy
) override
;
107 void SetExtraRequestHeaders(
108 const std::string
& extra_request_headers
) override
;
109 void AddExtraRequestHeader(const std::string
& header_line
) override
;
110 void SetRequestContext(
111 URLRequestContextGetter
* request_context_getter
) override
;
112 void SetFirstPartyForCookies(const GURL
& first_party_for_cookies
) override
;
113 void SetURLRequestUserData(
115 const CreateDataCallback
& create_data_callback
) override
;
116 void SetStopOnRedirect(bool stop_on_redirect
) override
;
117 void SetAutomaticallyRetryOn5xx(bool retry
) override
;
118 void SetMaxRetriesOn5xx(int max_retries
) override
;
119 int GetMaxRetriesOn5xx() const override
;
120 base::TimeDelta
GetBackoffDelay() const override
;
121 void SetAutomaticallyRetryOnNetworkChanges(int max_retries
) override
;
122 void SaveResponseToFileAtPath(
123 const base::FilePath
& file_path
,
124 scoped_refptr
<base::SequencedTaskRunner
> file_task_runner
) override
;
125 void SaveResponseToTemporaryFile(
126 scoped_refptr
<base::SequencedTaskRunner
> file_task_runner
) override
;
127 void SaveResponseWithWriter(
128 scoped_ptr
<URLFetcherResponseWriter
> response_writer
) override
;
129 HttpResponseHeaders
* GetResponseHeaders() const override
;
130 HostPortPair
GetSocketAddress() const override
;
131 bool WasFetchedViaProxy() const override
;
132 void Start() override
;
134 // URL we were created with. Because of how we're using URLFetcher GetURL()
135 // always returns an empty URL. Chances are you'll want to use
136 // GetOriginalURL() in your tests.
137 const GURL
& GetOriginalURL() const override
;
138 const GURL
& GetURL() const override
;
139 const URLRequestStatus
& GetStatus() const override
;
140 int GetResponseCode() const override
;
141 const ResponseCookies
& GetCookies() const override
;
142 void ReceivedContentWasMalformed() override
;
143 // Override response access functions to return fake data.
144 bool GetResponseAsString(std::string
* out_response_string
) const override
;
145 bool GetResponseAsFilePath(bool take_ownership
,
146 base::FilePath
* out_response_path
) const override
;
148 void GetExtraRequestHeaders(HttpRequestHeaders
* headers
) const;
150 // Sets owner of this class. Set it to a non-NULL value if you want
151 // to automatically unregister this fetcher from the owning factory
153 void set_owner(TestURLFetcherFactory
* owner
) { owner_
= owner
; }
155 // Unique ID in our factory.
156 int id() const { return id_
; }
158 // Returns the data uploaded on this URLFetcher.
159 const std::string
& upload_content_type() const {
160 return upload_content_type_
;
162 const std::string
& upload_data() const { return upload_data_
; }
163 const base::FilePath
& upload_file_path() const { return upload_file_path_
; }
165 // Returns the chunks of data uploaded on this URLFetcher.
166 const std::list
<std::string
>& upload_chunks() const { return chunks_
; }
168 // Checks whether the last call to |AppendChunkToUpload(...)| was final.
169 bool did_receive_last_chunk() const { return did_receive_last_chunk_
; }
171 // Returns the delegate installed on the URLFetcher.
172 URLFetcherDelegate
* delegate() const { return delegate_
; }
174 void set_url(const GURL
& url
) { fake_url_
= url
; }
175 void set_status(const URLRequestStatus
& status
);
176 void set_response_code(int response_code
) {
177 fake_response_code_
= response_code
;
179 void set_cookies(const ResponseCookies
& c
) { fake_cookies_
= c
; }
180 void set_was_fetched_via_proxy(bool flag
);
181 void set_response_headers(scoped_refptr
<HttpResponseHeaders
> headers
);
182 void set_backoff_delay(base::TimeDelta backoff_delay
);
183 void SetDelegateForTests(DelegateForTests
* delegate_for_tests
);
186 void SetResponseString(const std::string
& response
);
189 void SetResponseFilePath(const base::FilePath
& path
);
192 enum ResponseDestinationType
{
193 STRING
, // Default: In a std::string
194 TEMP_FILE
// Write to a temp file
197 TestURLFetcherFactory
* owner_
;
199 const GURL original_url_
;
200 URLFetcherDelegate
* delegate_
;
201 DelegateForTests
* delegate_for_tests_
;
202 std::string upload_content_type_
;
203 std::string upload_data_
;
204 base::FilePath upload_file_path_
;
205 std::list
<std::string
> chunks_
;
206 bool did_receive_last_chunk_
;
208 // User can use set_* methods to provide values returned by getters.
209 // Setting the real values is not possible, because the real class
210 // has no setters. The data is a private member of a class defined
211 // in a .cc file, so we can't get at it with friendship.
212 int fake_load_flags_
;
214 URLRequestStatus fake_status_
;
215 int fake_response_code_
;
216 ResponseCookies fake_cookies_
;
217 ResponseDestinationType fake_response_destination_
;
218 std::string fake_response_string_
;
219 base::FilePath fake_response_file_path_
;
220 bool fake_was_fetched_via_proxy_
;
221 scoped_refptr
<HttpResponseHeaders
> fake_response_headers_
;
222 HttpRequestHeaders fake_extra_request_headers_
;
223 int fake_max_retries_
;
224 base::TimeDelta fake_backoff_delay_
;
225 scoped_ptr
<URLFetcherResponseWriter
> response_writer_
;
227 DISALLOW_COPY_AND_ASSIGN(TestURLFetcher
);
230 typedef TestURLFetcher::DelegateForTests TestURLFetcherDelegateForTests
;
232 // Simple URLFetcherFactory method that creates TestURLFetchers. All fetchers
233 // are registered in a map by the id passed to the create method.
234 // Optionally, a fetcher may be automatically unregistered from the map upon
236 class TestURLFetcherFactory
: public URLFetcherFactory
,
237 public ScopedURLFetcherFactory
{
239 TestURLFetcherFactory();
240 ~TestURLFetcherFactory() override
;
242 URLFetcher
* CreateURLFetcher(int id
,
244 URLFetcher::RequestType request_type
,
245 URLFetcherDelegate
* d
) override
;
246 TestURLFetcher
* GetFetcherByID(int id
) const;
247 void RemoveFetcherFromMap(int id
);
248 void SetDelegateForTests(TestURLFetcherDelegateForTests
* delegate_for_tests
);
249 void set_remove_fetcher_on_delete(bool remove_fetcher_on_delete
) {
250 remove_fetcher_on_delete_
= remove_fetcher_on_delete
;
254 // Maps from id passed to create to the returned URLFetcher.
255 typedef std::map
<int, TestURLFetcher
*> Fetchers
;
257 TestURLFetcherDelegateForTests
* delegate_for_tests_
;
258 // Whether to automatically unregister a fetcher from this factory upon its
259 // destruction, false by default.
260 bool remove_fetcher_on_delete_
;
262 DISALLOW_COPY_AND_ASSIGN(TestURLFetcherFactory
);
265 // The FakeURLFetcher and FakeURLFetcherFactory classes are similar to the
266 // ones above but don't require you to know when exactly the URLFetcher objects
269 // These classes let you set pre-baked HTTP responses for particular URLs.
270 // E.g., if the user requests http://a.com/ then respond with an HTTP/500.
272 // We assume that the thread that is calling Start() on the URLFetcher object
273 // has a message loop running.
275 // FakeURLFetcher can be used to create a URLFetcher that will emit a fake
276 // response when started. This class can be used in place of an actual
280 // FakeURLFetcher fake_fetcher("http://a.com", some_delegate,
281 // "<html><body>hello world</body></html>",
284 // // Will schedule a call to some_delegate->OnURLFetchComplete(&fake_fetcher).
285 // fake_fetcher.Start();
286 class FakeURLFetcher
: public TestURLFetcher
{
288 // Normal URL fetcher constructor but also takes in a pre-baked response.
289 FakeURLFetcher(const GURL
& url
,
290 URLFetcherDelegate
* d
,
291 const std::string
& response_data
,
292 HttpStatusCode response_code
,
293 URLRequestStatus::Status status
);
295 // Start the request. This will call the given delegate asynchronously
296 // with the pre-baked response as parameter.
297 void Start() override
;
299 const GURL
& GetURL() const override
;
301 ~FakeURLFetcher() override
;
304 // This is the method which actually calls the delegate that is passed in the
308 base::WeakPtrFactory
<FakeURLFetcher
> weak_factory_
;
310 DISALLOW_COPY_AND_ASSIGN(FakeURLFetcher
);
314 // FakeURLFetcherFactory is a factory for FakeURLFetcher objects. When
315 // instantiated, it sets itself up as the default URLFetcherFactory. Fake
316 // responses for given URLs can be set using SetFakeResponse.
318 // This class is not thread-safe. You should not call SetFakeResponse or
319 // ClearFakeResponse at the same time you call CreateURLFetcher. However, it is
320 // OK to start URLFetcher objects while setting or clearing fake responses
321 // since already created URLFetcher objects will not be affected by any changes
322 // made to the fake responses (once a URLFetcher object is created you cannot
323 // change its fake response).
326 // FakeURLFetcherFactory factory;
328 // // You know that class SomeService will request http://a.com/success and you
329 // // want to respond with a simple html page and an HTTP/200 code.
330 // factory.SetFakeResponse("http://a.com/success",
331 // "<html><body>hello world</body></html>",
333 // URLRequestStatus::SUCCESS);
334 // // You know that class SomeService will request url http://a.com/servererror
335 // // and you want to test the service class by returning a server error.
336 // factory.SetFakeResponse("http://a.com/servererror",
338 // HTTP_INTERNAL_SERVER_ERROR,
339 // URLRequestStatus::SUCCESS);
340 // // You know that class SomeService will request url http://a.com/autherror
341 // // and you want to test the service class by returning a specific error
342 // // code, say, a HTTP/401 error.
343 // factory.SetFakeResponse("http://a.com/autherror",
345 // HTTP_UNAUTHORIZED,
346 // URLRequestStatus::SUCCESS);
348 // // You know that class SomeService will request url http://a.com/failure
349 // // and you want to test the service class by returning a failure in the
351 // factory.SetFakeResponse("http://a.com/failure",
353 // HTTP_INTERNAL_SERVER_ERROR,
354 // URLRequestStatus::FAILURE);
356 // SomeService service;
357 // service.Run(); // Will eventually request these three URLs.
358 class FakeURLFetcherFactory
: public URLFetcherFactory
,
359 public ScopedURLFetcherFactory
{
361 // Parameters to FakeURLFetcherCreator: url, delegate, response_data,
363 // |url| URL for instantiated FakeURLFetcher
364 // |delegate| Delegate for FakeURLFetcher
365 // |response_data| response data for FakeURLFetcher
366 // |response_code| response code for FakeURLFetcher
367 // |status| URL fetch status for FakeURLFetcher
368 // These arguments should by default be used in instantiating FakeURLFetcher
370 // new FakeURLFetcher(url, delegate, response_data, response_code, status)
371 typedef base::Callback
<scoped_ptr
<FakeURLFetcher
>(
376 URLRequestStatus::Status
)> FakeURLFetcherCreator
;
378 // |default_factory|, which can be NULL, is a URLFetcherFactory that
379 // will be used to construct a URLFetcher in case the URL being created
380 // has no pre-baked response. If it is NULL, a URLFetcherImpl will be
381 // created in this case.
382 explicit FakeURLFetcherFactory(URLFetcherFactory
* default_factory
);
384 // |default_factory|, which can be NULL, is a URLFetcherFactory that
385 // will be used to construct a URLFetcher in case the URL being created
386 // has no pre-baked response. If it is NULL, a URLFetcherImpl will be
387 // created in this case.
388 // |creator| is a callback that returns will be called to create a
389 // FakeURLFetcher if a response is found to a given URL. It can be
390 // set to MakeFakeURLFetcher.
391 FakeURLFetcherFactory(URLFetcherFactory
* default_factory
,
392 const FakeURLFetcherCreator
& creator
);
394 ~FakeURLFetcherFactory() override
;
396 // If no fake response is set for the given URL this method will delegate the
397 // call to |default_factory_| if it is not NULL, or return NULL if it is
399 // Otherwise, it will return a URLFetcher object which will respond with the
400 // pre-baked response that the client has set by calling SetFakeResponse().
401 URLFetcher
* CreateURLFetcher(int id
,
403 URLFetcher::RequestType request_type
,
404 URLFetcherDelegate
* d
) override
;
406 // Sets the fake response for a given URL. The |response_data| may be empty.
407 // The |response_code| may be any HttpStatusCode. For instance, HTTP_OK will
408 // return an HTTP/200 and HTTP_INTERNAL_SERVER_ERROR will return an HTTP/500.
409 // The |status| argument may be any URLRequestStatus::Status value. Typically,
410 // requests that return a valid HttpStatusCode have the SUCCESS status, while
411 // requests that indicate a failure to connect to the server have the FAILED
413 void SetFakeResponse(const GURL
& url
,
414 const std::string
& response_data
,
415 HttpStatusCode response_code
,
416 URLRequestStatus::Status status
);
418 // Clear all the fake responses that were previously set via
419 // SetFakeResponse().
420 void ClearFakeResponses();
423 struct FakeURLResponse
{
424 std::string response_data
;
425 HttpStatusCode response_code
;
426 URLRequestStatus::Status status
;
428 typedef std::map
<GURL
, FakeURLResponse
> FakeResponseMap
;
430 const FakeURLFetcherCreator creator_
;
431 FakeResponseMap fake_responses_
;
432 URLFetcherFactory
* const default_factory_
;
434 static scoped_ptr
<FakeURLFetcher
> DefaultFakeURLFetcherCreator(
436 URLFetcherDelegate
* delegate
,
437 const std::string
& response_data
,
438 HttpStatusCode response_code
,
439 URLRequestStatus::Status status
);
440 DISALLOW_COPY_AND_ASSIGN(FakeURLFetcherFactory
);
443 // This is an implementation of URLFetcherFactory that will create a
444 // URLFetcherImpl. It can be use in conjunction with a FakeURLFetcherFactory in
445 // integration tests to control the behavior of some requests but execute
446 // all the other ones.
447 class URLFetcherImplFactory
: public URLFetcherFactory
{
449 URLFetcherImplFactory();
450 ~URLFetcherImplFactory() override
;
452 // This method will create a real URLFetcher.
453 URLFetcher
* CreateURLFetcher(int id
,
455 URLFetcher::RequestType request_type
,
456 URLFetcherDelegate
* d
) override
;
461 #endif // NET_URL_REQUEST_TEST_URL_FETCHER_FACTORY_H_