Update To 11.40.268.0
[platform/framework/web/crosswalk.git] / src / net / url_request / test_url_fetcher_factory.h
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_TEST_URL_FETCHER_FACTORY_H_
6 #define NET_URL_REQUEST_TEST_URL_FETCHER_FACTORY_H_
7
8 #include <list>
9 #include <map>
10 #include <string>
11 #include <utility>
12
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"
24 #include "url/gurl.h"
25
26 namespace net {
27
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 {
31  public:
32   explicit ScopedURLFetcherFactory(URLFetcherFactory* factory);
33   virtual ~ScopedURLFetcherFactory();
34
35  private:
36   DISALLOW_COPY_AND_ASSIGN(ScopedURLFetcherFactory);
37 };
38
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
44 // URLFetcher.
45 // Typical usage:
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.
53 //   ...
54 //   TestURLFetcher* fetcher = factory.GetFetcherByID(expected_id);
55 //   DCHECK(fetcher);
56 //   // Notify delegate with whatever data you want.
57 //   fetcher->delegate()->OnURLFetchComplete(...);
58 //   // Make sure consumer of URLFetcher does the right thing.
59 //   ...
60 //
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
63 // below.
64
65 class TestURLFetcherFactory;
66 class TestURLFetcher : public URLFetcher {
67  public:
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 {
72    public:
73     // Callback issued correspondingly to the call to the |Start()| method.
74     virtual void OnRequestStart(int fetcher_id) = 0;
75
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;
79
80     // Callback issued correspondingly to the destructor.
81     virtual void OnRequestEnd(int fetcher_id) = 0;
82   };
83
84   TestURLFetcher(int id,
85                  const GURL& url,
86                  URLFetcherDelegate* d);
87   ~TestURLFetcher() override;
88
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,
95       uint64 range_offset,
96       uint64 range_length,
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(
114       const void* key,
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;
133
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;
147
148   void GetExtraRequestHeaders(HttpRequestHeaders* headers) const;
149
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
152   // upon destruction.
153   void set_owner(TestURLFetcherFactory* owner) { owner_ = owner; }
154
155   // Unique ID in our factory.
156   int id() const { return id_; }
157
158   // Returns the data uploaded on this URLFetcher.
159   const std::string& upload_content_type() const {
160     return upload_content_type_;
161   }
162   const std::string& upload_data() const { return upload_data_; }
163   const base::FilePath& upload_file_path() const { return upload_file_path_; }
164
165   // Returns the chunks of data uploaded on this URLFetcher.
166   const std::list<std::string>& upload_chunks() const { return chunks_; }
167
168   // Checks whether the last call to |AppendChunkToUpload(...)| was final.
169   bool did_receive_last_chunk() const { return did_receive_last_chunk_; }
170
171   // Returns the delegate installed on the URLFetcher.
172   URLFetcherDelegate* delegate() const { return delegate_; }
173
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;
178   }
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);
184
185   // Set string data.
186   void SetResponseString(const std::string& response);
187
188   // Set File data.
189   void SetResponseFilePath(const base::FilePath& path);
190
191  private:
192   enum ResponseDestinationType {
193     STRING,  // Default: In a std::string
194     TEMP_FILE  // Write to a temp file
195   };
196
197   TestURLFetcherFactory* owner_;
198   const int id_;
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_;
207
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_;
213   GURL fake_url_;
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_;
226
227   DISALLOW_COPY_AND_ASSIGN(TestURLFetcher);
228 };
229
230 typedef TestURLFetcher::DelegateForTests TestURLFetcherDelegateForTests;
231
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
235 // its destruction.
236 class TestURLFetcherFactory : public URLFetcherFactory,
237                               public ScopedURLFetcherFactory {
238  public:
239   TestURLFetcherFactory();
240   ~TestURLFetcherFactory() override;
241
242   URLFetcher* CreateURLFetcher(int id,
243                                const GURL& url,
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;
251   }
252
253  private:
254   // Maps from id passed to create to the returned URLFetcher.
255   typedef std::map<int, TestURLFetcher*> Fetchers;
256   Fetchers 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_;
261
262   DISALLOW_COPY_AND_ASSIGN(TestURLFetcherFactory);
263 };
264
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
267 // will be created.
268 //
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.
271 //
272 // We assume that the thread that is calling Start() on the URLFetcher object
273 // has a message loop running.
274
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
277 // URLFetcher.
278 //
279 // Example usage:
280 //  FakeURLFetcher fake_fetcher("http://a.com", some_delegate,
281 //                              "<html><body>hello world</body></html>",
282 //                              HTTP_OK);
283 //
284 // // Will schedule a call to some_delegate->OnURLFetchComplete(&fake_fetcher).
285 // fake_fetcher.Start();
286 class FakeURLFetcher : public TestURLFetcher {
287  public:
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);
294
295   // Start the request.  This will call the given delegate asynchronously
296   // with the pre-baked response as parameter.
297   void Start() override;
298
299   const GURL& GetURL() const override;
300
301   ~FakeURLFetcher() override;
302
303  private:
304   // This is the method which actually calls the delegate that is passed in the
305   // constructor.
306   void RunDelegate();
307
308   base::WeakPtrFactory<FakeURLFetcher> weak_factory_;
309
310   DISALLOW_COPY_AND_ASSIGN(FakeURLFetcher);
311 };
312
313
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.
317 //
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).
324 //
325 // Example usage:
326 //  FakeURLFetcherFactory factory;
327 //
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>",
332 //                          HTTP_OK,
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",
337 //                          "",
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",
344 //                          "some_response",
345 //                          HTTP_UNAUTHORIZED,
346 //                          URLRequestStatus::SUCCESS);
347 //
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
350 //  // network layer.
351 //  factory.SetFakeResponse("http://a.com/failure",
352 //                          "",
353 //                          HTTP_INTERNAL_SERVER_ERROR,
354 //                          URLRequestStatus::FAILURE);
355 //
356 //  SomeService service;
357 //  service.Run();  // Will eventually request these three URLs.
358 class FakeURLFetcherFactory : public URLFetcherFactory,
359                               public ScopedURLFetcherFactory {
360  public:
361   // Parameters to FakeURLFetcherCreator: url, delegate, response_data,
362   //                                      response_code
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
369   // like so:
370   // new FakeURLFetcher(url, delegate, response_data, response_code, status)
371   typedef base::Callback<scoped_ptr<FakeURLFetcher>(
372       const GURL&,
373       URLFetcherDelegate*,
374       const std::string&,
375       HttpStatusCode,
376       URLRequestStatus::Status)> FakeURLFetcherCreator;
377
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);
383
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);
393
394   ~FakeURLFetcherFactory() override;
395
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
398   // NULL.
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,
402                                const GURL& url,
403                                URLFetcher::RequestType request_type,
404                                URLFetcherDelegate* d) override;
405
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
412   // status.
413   void SetFakeResponse(const GURL& url,
414                        const std::string& response_data,
415                        HttpStatusCode response_code,
416                        URLRequestStatus::Status status);
417
418   // Clear all the fake responses that were previously set via
419   // SetFakeResponse().
420   void ClearFakeResponses();
421
422  private:
423   struct FakeURLResponse {
424     std::string response_data;
425     HttpStatusCode response_code;
426     URLRequestStatus::Status status;
427   };
428   typedef std::map<GURL, FakeURLResponse> FakeResponseMap;
429
430   const FakeURLFetcherCreator creator_;
431   FakeResponseMap fake_responses_;
432   URLFetcherFactory* const default_factory_;
433
434   static scoped_ptr<FakeURLFetcher> DefaultFakeURLFetcherCreator(
435       const GURL& url,
436       URLFetcherDelegate* delegate,
437       const std::string& response_data,
438       HttpStatusCode response_code,
439       URLRequestStatus::Status status);
440   DISALLOW_COPY_AND_ASSIGN(FakeURLFetcherFactory);
441 };
442
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 {
448  public:
449   URLFetcherImplFactory();
450   ~URLFetcherImplFactory() override;
451
452   // This method will create a real URLFetcher.
453   URLFetcher* CreateURLFetcher(int id,
454                                const GURL& url,
455                                URLFetcher::RequestType request_type,
456                                URLFetcherDelegate* d) override;
457 };
458
459 }  // namespace net
460
461 #endif  // NET_URL_REQUEST_TEST_URL_FETCHER_FACTORY_H_