test_url_fetcher_factory.cc revision 5821806d5e7f356e8fa4b058a389a808ea183019
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 "net/url_request/test_url_fetcher_factory.h"
6
7#include <string>
8
9#include "base/bind.h"
10#include "base/compiler_specific.h"
11#include "base/memory/weak_ptr.h"
12#include "base/message_loop.h"
13#include "net/base/host_port_pair.h"
14#include "net/http/http_response_headers.h"
15#include "net/url_request/url_fetcher_delegate.h"
16#include "net/url_request/url_fetcher_impl.h"
17#include "net/url_request/url_request_status.h"
18
19namespace net {
20
21ScopedURLFetcherFactory::ScopedURLFetcherFactory(
22    URLFetcherFactory* factory) {
23  DCHECK(!URLFetcherImpl::factory());
24  URLFetcherImpl::set_factory(factory);
25}
26
27ScopedURLFetcherFactory::~ScopedURLFetcherFactory() {
28  DCHECK(URLFetcherImpl::factory());
29  URLFetcherImpl::set_factory(NULL);
30}
31
32TestURLFetcher::TestURLFetcher(int id,
33                               const GURL& url,
34                               URLFetcherDelegate* d)
35    : id_(id),
36      original_url_(url),
37      delegate_(d),
38      delegate_for_tests_(NULL),
39      did_receive_last_chunk_(false),
40      fake_load_flags_(0),
41      fake_response_code_(-1),
42      fake_response_destination_(STRING),
43      fake_was_fetched_via_proxy_(false),
44      fake_max_retries_(0) {
45}
46
47TestURLFetcher::~TestURLFetcher() {
48  if (delegate_for_tests_)
49    delegate_for_tests_->OnRequestEnd(id_);
50}
51
52void TestURLFetcher::SetUploadData(const std::string& upload_content_type,
53                                   const std::string& upload_content) {
54  upload_data_ = upload_content;
55}
56
57void TestURLFetcher::SetChunkedUpload(const std::string& upload_content_type) {
58}
59
60void TestURLFetcher::AppendChunkToUpload(const std::string& data,
61                                         bool is_last_chunk) {
62  DCHECK(!did_receive_last_chunk_);
63  did_receive_last_chunk_ = is_last_chunk;
64  chunks_.push_back(data);
65  if (delegate_for_tests_)
66    delegate_for_tests_->OnChunkUpload(id_);
67}
68
69void TestURLFetcher::SetLoadFlags(int load_flags) {
70  fake_load_flags_= load_flags;
71}
72
73int TestURLFetcher::GetLoadFlags() const {
74  return fake_load_flags_;
75}
76
77void TestURLFetcher::SetReferrer(const std::string& referrer) {
78}
79
80void TestURLFetcher::SetExtraRequestHeaders(
81    const std::string& extra_request_headers) {
82  fake_extra_request_headers_.Clear();
83  fake_extra_request_headers_.AddHeadersFromString(extra_request_headers);
84}
85
86void TestURLFetcher::AddExtraRequestHeader(const std::string& header_line) {
87  fake_extra_request_headers_.AddHeaderFromString(header_line);
88}
89
90void TestURLFetcher::GetExtraRequestHeaders(
91    HttpRequestHeaders* headers) const {
92  *headers = fake_extra_request_headers_;
93}
94
95void TestURLFetcher::SetRequestContext(
96    URLRequestContextGetter* request_context_getter) {
97}
98
99void TestURLFetcher::SetFirstPartyForCookies(
100    const GURL& first_party_for_cookies) {
101}
102
103void TestURLFetcher::SetURLRequestUserData(
104    const void* key,
105    const CreateDataCallback& create_data_callback) {
106}
107
108void TestURLFetcher::SetStopOnRedirect(bool stop_on_redirect) {
109}
110
111void TestURLFetcher::SetAutomaticallyRetryOn5xx(bool retry) {
112}
113
114void TestURLFetcher::SetMaxRetries(int max_retries) {
115  fake_max_retries_ = max_retries;
116}
117
118int TestURLFetcher::GetMaxRetries() const {
119  return fake_max_retries_;
120}
121
122base::TimeDelta TestURLFetcher::GetBackoffDelay() const {
123  return fake_backoff_delay_;
124}
125
126void TestURLFetcher::SaveResponseToFileAtPath(
127    const FilePath& file_path,
128    scoped_refptr<base::TaskRunner> file_task_runner) {
129}
130
131void TestURLFetcher::SaveResponseToTemporaryFile(
132    scoped_refptr<base::TaskRunner> file_task_runner) {
133}
134
135HttpResponseHeaders* TestURLFetcher::GetResponseHeaders() const {
136  return fake_response_headers_;
137}
138
139HostPortPair TestURLFetcher::GetSocketAddress() const {
140  NOTIMPLEMENTED();
141  return HostPortPair();
142}
143
144bool TestURLFetcher::WasFetchedViaProxy() const {
145  return fake_was_fetched_via_proxy_;
146}
147
148void TestURLFetcher::Start() {
149  // Overriden to do nothing. It is assumed the caller will notify the delegate.
150  if (delegate_for_tests_)
151    delegate_for_tests_->OnRequestStart(id_);
152}
153
154const GURL& TestURLFetcher::GetOriginalURL() const {
155  return original_url_;
156}
157
158const GURL& TestURLFetcher::GetURL() const {
159  return fake_url_;
160}
161
162const URLRequestStatus& TestURLFetcher::GetStatus() const {
163  return fake_status_;
164}
165
166int TestURLFetcher::GetResponseCode() const {
167  return fake_response_code_;
168}
169
170const ResponseCookies& TestURLFetcher::GetCookies() const {
171  return fake_cookies_;
172}
173
174bool TestURLFetcher::FileErrorOccurred(
175    base::PlatformFileError* out_error_code) const {
176  NOTIMPLEMENTED();
177  return false;
178}
179
180void TestURLFetcher::ReceivedContentWasMalformed() {
181}
182
183bool TestURLFetcher::GetResponseAsString(
184    std::string* out_response_string) const {
185  if (fake_response_destination_ != STRING)
186    return false;
187
188  *out_response_string = fake_response_string_;
189  return true;
190}
191
192bool TestURLFetcher::GetResponseAsFilePath(
193    bool take_ownership, FilePath* out_response_path) const {
194  if (fake_response_destination_ != TEMP_FILE)
195    return false;
196
197  *out_response_path = fake_response_file_path_;
198  return true;
199}
200
201void TestURLFetcher::set_status(const URLRequestStatus& status) {
202  fake_status_ = status;
203}
204
205void TestURLFetcher::set_was_fetched_via_proxy(bool flag) {
206  fake_was_fetched_via_proxy_ = flag;
207}
208
209void TestURLFetcher::set_response_headers(
210    scoped_refptr<HttpResponseHeaders> headers) {
211  fake_response_headers_ = headers;
212}
213
214void TestURLFetcher::set_backoff_delay(base::TimeDelta backoff_delay) {
215  fake_backoff_delay_ = backoff_delay;
216}
217
218void TestURLFetcher::SetDelegateForTests(DelegateForTests* delegate_for_tests) {
219  delegate_for_tests_ = delegate_for_tests;
220}
221
222void TestURLFetcher::SetResponseString(const std::string& response) {
223  fake_response_destination_ = STRING;
224  fake_response_string_ = response;
225}
226
227void TestURLFetcher::SetResponseFilePath(const FilePath& path) {
228  fake_response_destination_ = TEMP_FILE;
229  fake_response_file_path_ = path;
230}
231
232TestURLFetcherFactory::TestURLFetcherFactory()
233    : ScopedURLFetcherFactory(ALLOW_THIS_IN_INITIALIZER_LIST(this)),
234      delegate_for_tests_(NULL) {
235}
236
237TestURLFetcherFactory::~TestURLFetcherFactory() {}
238
239URLFetcher* TestURLFetcherFactory::CreateURLFetcher(
240    int id,
241    const GURL& url,
242    URLFetcher::RequestType request_type,
243    URLFetcherDelegate* d) {
244  TestURLFetcher* fetcher = new TestURLFetcher(id, url, d);
245  fetcher->SetDelegateForTests(delegate_for_tests_);
246  fetchers_[id] = fetcher;
247  return fetcher;
248}
249
250TestURLFetcher* TestURLFetcherFactory::GetFetcherByID(int id) const {
251  Fetchers::const_iterator i = fetchers_.find(id);
252  return i == fetchers_.end() ? NULL : i->second;
253}
254
255void TestURLFetcherFactory::RemoveFetcherFromMap(int id) {
256  Fetchers::iterator i = fetchers_.find(id);
257  DCHECK(i != fetchers_.end());
258  fetchers_.erase(i);
259}
260
261void TestURLFetcherFactory::SetDelegateForTests(
262    TestURLFetcherDelegateForTests* delegate_for_tests) {
263  delegate_for_tests_ = delegate_for_tests;
264}
265
266// This class is used by the FakeURLFetcherFactory below.
267class FakeURLFetcher : public TestURLFetcher {
268 public:
269  // Normal URL fetcher constructor but also takes in a pre-baked response.
270  FakeURLFetcher(const GURL& url,
271                 URLFetcherDelegate* d,
272                 const std::string& response_data, bool success)
273    : TestURLFetcher(0, url, d),
274      ALLOW_THIS_IN_INITIALIZER_LIST(weak_factory_(this)) {
275    set_status(URLRequestStatus(
276        success ? URLRequestStatus::SUCCESS :
277            URLRequestStatus::FAILED,
278        0));
279    set_response_code(success ? 200 : 500);
280    SetResponseString(response_data);
281  }
282
283  // Start the request.  This will call the given delegate asynchronously
284  // with the pre-baked response as parameter.
285  virtual void Start() OVERRIDE {
286    MessageLoop::current()->PostTask(
287        FROM_HERE,
288        base::Bind(&FakeURLFetcher::RunDelegate, weak_factory_.GetWeakPtr()));
289  }
290
291  virtual const GURL& GetURL() const OVERRIDE {
292    return TestURLFetcher::GetOriginalURL();
293  }
294
295 private:
296  virtual ~FakeURLFetcher() {
297  }
298
299  // This is the method which actually calls the delegate that is passed in the
300  // constructor.
301  void RunDelegate() {
302    delegate()->OnURLFetchComplete(this);
303  }
304
305  base::WeakPtrFactory<FakeURLFetcher> weak_factory_;
306
307  DISALLOW_COPY_AND_ASSIGN(FakeURLFetcher);
308};
309
310FakeURLFetcherFactory::FakeURLFetcherFactory()
311    : ScopedURLFetcherFactory(ALLOW_THIS_IN_INITIALIZER_LIST(this)),
312      default_factory_(NULL) {
313}
314
315FakeURLFetcherFactory::FakeURLFetcherFactory(
316    URLFetcherFactory* default_factory)
317    : ScopedURLFetcherFactory(ALLOW_THIS_IN_INITIALIZER_LIST(this)),
318      default_factory_(default_factory) {
319}
320
321FakeURLFetcherFactory::~FakeURLFetcherFactory() {}
322
323URLFetcher* FakeURLFetcherFactory::CreateURLFetcher(
324    int id,
325    const GURL& url,
326    URLFetcher::RequestType request_type,
327    URLFetcherDelegate* d) {
328  FakeResponseMap::const_iterator it = fake_responses_.find(url);
329  if (it == fake_responses_.end()) {
330    if (default_factory_ == NULL) {
331      // If we don't have a baked response for that URL we return NULL.
332      DLOG(ERROR) << "No baked response for URL: " << url.spec();
333      return NULL;
334    } else {
335      return default_factory_->CreateURLFetcher(id, url, request_type, d);
336    }
337  }
338  return new FakeURLFetcher(url, d, it->second.first, it->second.second);
339}
340
341void FakeURLFetcherFactory::SetFakeResponse(const std::string& url,
342                                            const std::string& response_data,
343                                            bool success) {
344  // Overwrite existing URL if it already exists.
345  fake_responses_[GURL(url)] = std::make_pair(response_data, success);
346}
347
348void FakeURLFetcherFactory::ClearFakeResponses() {
349  fake_responses_.clear();
350}
351
352URLFetcherImplFactory::URLFetcherImplFactory() {}
353
354URLFetcherImplFactory::~URLFetcherImplFactory() {}
355
356URLFetcher* URLFetcherImplFactory::CreateURLFetcher(
357    int id,
358    const GURL& url,
359    URLFetcher::RequestType request_type,
360    URLFetcherDelegate* d) {
361  return new URLFetcherImpl(url, request_type, d);
362}
363
364}  // namespace net
365