Explicitly add python-numpy dependency to install-build-deps.
[chromium-blink-merge.git] / net / url_request / test_url_fetcher_factory.cc
blob357dfebb0464b345e7900dd4e4e7a8aa6b44a1ea
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 #include "net/url_request/test_url_fetcher_factory.h"
7 #include <string>
9 #include "base/bind.h"
10 #include "base/compiler_specific.h"
11 #include "base/files/file_util.h"
12 #include "base/memory/weak_ptr.h"
13 #include "base/message_loop/message_loop.h"
14 #include "base/threading/thread_restrictions.h"
15 #include "net/base/host_port_pair.h"
16 #include "net/base/io_buffer.h"
17 #include "net/base/net_errors.h"
18 #include "net/http/http_response_headers.h"
19 #include "net/url_request/url_fetcher_delegate.h"
20 #include "net/url_request/url_fetcher_impl.h"
21 #include "net/url_request/url_fetcher_response_writer.h"
22 #include "net/url_request/url_request_status.h"
24 namespace net {
26 ScopedURLFetcherFactory::ScopedURLFetcherFactory(
27 URLFetcherFactory* factory) {
28 DCHECK(!URLFetcherImpl::factory());
29 URLFetcherImpl::set_factory(factory);
32 ScopedURLFetcherFactory::~ScopedURLFetcherFactory() {
33 DCHECK(URLFetcherImpl::factory());
34 URLFetcherImpl::set_factory(NULL);
37 TestURLFetcher::TestURLFetcher(int id,
38 const GURL& url,
39 URLFetcherDelegate* d)
40 : owner_(NULL),
41 id_(id),
42 original_url_(url),
43 delegate_(d),
44 delegate_for_tests_(NULL),
45 did_receive_last_chunk_(false),
46 fake_load_flags_(0),
47 fake_response_code_(-1),
48 fake_response_destination_(STRING),
49 fake_was_fetched_via_proxy_(false),
50 fake_max_retries_(0) {
51 CHECK(original_url_.is_valid());
54 TestURLFetcher::~TestURLFetcher() {
55 if (delegate_for_tests_)
56 delegate_for_tests_->OnRequestEnd(id_);
57 if (owner_)
58 owner_->RemoveFetcherFromMap(id_);
61 void TestURLFetcher::SetUploadData(const std::string& upload_content_type,
62 const std::string& upload_content) {
63 upload_content_type_ = upload_content_type;
64 upload_data_ = upload_content;
67 void TestURLFetcher::SetUploadFilePath(
68 const std::string& upload_content_type,
69 const base::FilePath& file_path,
70 uint64 range_offset,
71 uint64 range_length,
72 scoped_refptr<base::TaskRunner> file_task_runner) {
73 upload_file_path_ = file_path;
76 void TestURLFetcher::SetChunkedUpload(const std::string& upload_content_type) {
79 void TestURLFetcher::AppendChunkToUpload(const std::string& data,
80 bool is_last_chunk) {
81 DCHECK(!did_receive_last_chunk_);
82 did_receive_last_chunk_ = is_last_chunk;
83 chunks_.push_back(data);
84 if (delegate_for_tests_)
85 delegate_for_tests_->OnChunkUpload(id_);
88 void TestURLFetcher::SetLoadFlags(int load_flags) {
89 fake_load_flags_= load_flags;
92 int TestURLFetcher::GetLoadFlags() const {
93 return fake_load_flags_;
96 void TestURLFetcher::SetReferrer(const std::string& referrer) {
99 void TestURLFetcher::SetReferrerPolicy(
100 URLRequest::ReferrerPolicy referrer_policy) {
103 void TestURLFetcher::SetExtraRequestHeaders(
104 const std::string& extra_request_headers) {
105 fake_extra_request_headers_.Clear();
106 fake_extra_request_headers_.AddHeadersFromString(extra_request_headers);
109 void TestURLFetcher::AddExtraRequestHeader(const std::string& header_line) {
110 fake_extra_request_headers_.AddHeaderFromString(header_line);
113 void TestURLFetcher::SetRequestContext(
114 URLRequestContextGetter* request_context_getter) {
117 void TestURLFetcher::SetFirstPartyForCookies(
118 const GURL& first_party_for_cookies) {
121 void TestURLFetcher::SetURLRequestUserData(
122 const void* key,
123 const CreateDataCallback& create_data_callback) {
126 void TestURLFetcher::SetStopOnRedirect(bool stop_on_redirect) {
129 void TestURLFetcher::SetAutomaticallyRetryOn5xx(bool retry) {
132 void TestURLFetcher::SetMaxRetriesOn5xx(int max_retries) {
133 fake_max_retries_ = max_retries;
136 int TestURLFetcher::GetMaxRetriesOn5xx() const {
137 return fake_max_retries_;
140 base::TimeDelta TestURLFetcher::GetBackoffDelay() const {
141 return fake_backoff_delay_;
144 void TestURLFetcher::SetAutomaticallyRetryOnNetworkChanges(int max_retries) {
147 void TestURLFetcher::SaveResponseToFileAtPath(
148 const base::FilePath& file_path,
149 scoped_refptr<base::SequencedTaskRunner> file_task_runner) {
150 SetResponseFilePath(file_path);
151 // Asynchronous IO is not supported, so file_task_runner is ignored.
152 base::ThreadRestrictions::ScopedAllowIO allow_io;
153 const size_t written_bytes = base::WriteFile(
154 file_path, fake_response_string_.c_str(), fake_response_string_.size());
155 DCHECK_EQ(written_bytes, fake_response_string_.size());
158 void TestURLFetcher::SaveResponseToTemporaryFile(
159 scoped_refptr<base::SequencedTaskRunner> file_task_runner) {
162 void TestURLFetcher::SaveResponseWithWriter(
163 scoped_ptr<URLFetcherResponseWriter> response_writer) {
164 // In class URLFetcherCore this method is called by all three:
165 // GetResponseAsString() / SaveResponseToFileAtPath() /
166 // SaveResponseToTemporaryFile(). But here (in TestURLFetcher), this method
167 // is never used by any of these three methods. So, file writing is expected
168 // to be done in SaveResponseToFileAtPath(), and this method supports only
169 // URLFetcherStringWriter (for testing of this method only).
170 if (fake_response_destination_ == STRING) {
171 response_writer_ = response_writer.Pass();
172 int response = response_writer_->Initialize(CompletionCallback());
173 // The TestURLFetcher doesn't handle asynchronous writes.
174 DCHECK_EQ(OK, response);
176 scoped_refptr<IOBuffer> buffer(new StringIOBuffer(fake_response_string_));
177 response = response_writer_->Write(buffer.get(),
178 fake_response_string_.size(),
179 CompletionCallback());
180 DCHECK_EQ(static_cast<int>(fake_response_string_.size()), response);
181 response = response_writer_->Finish(CompletionCallback());
182 DCHECK_EQ(OK, response);
183 } else if (fake_response_destination_ == TEMP_FILE) {
184 // SaveResponseToFileAtPath() should be called instead of this method to
185 // save file. Asynchronous file writing using URLFetcherFileWriter is not
186 // supported.
187 NOTIMPLEMENTED();
188 } else {
189 NOTREACHED();
193 HttpResponseHeaders* TestURLFetcher::GetResponseHeaders() const {
194 return fake_response_headers_.get();
197 HostPortPair TestURLFetcher::GetSocketAddress() const {
198 NOTIMPLEMENTED();
199 return HostPortPair();
202 bool TestURLFetcher::WasFetchedViaProxy() const {
203 return fake_was_fetched_via_proxy_;
206 void TestURLFetcher::Start() {
207 // Overriden to do nothing. It is assumed the caller will notify the delegate.
208 if (delegate_for_tests_)
209 delegate_for_tests_->OnRequestStart(id_);
212 const GURL& TestURLFetcher::GetOriginalURL() const {
213 return original_url_;
216 const GURL& TestURLFetcher::GetURL() const {
217 return fake_url_;
220 const URLRequestStatus& TestURLFetcher::GetStatus() const {
221 return fake_status_;
224 int TestURLFetcher::GetResponseCode() const {
225 return fake_response_code_;
228 const ResponseCookies& TestURLFetcher::GetCookies() const {
229 return fake_cookies_;
232 void TestURLFetcher::ReceivedContentWasMalformed() {
235 bool TestURLFetcher::GetResponseAsString(
236 std::string* out_response_string) const {
237 if (fake_response_destination_ != STRING)
238 return false;
240 *out_response_string = fake_response_string_;
241 return true;
244 bool TestURLFetcher::GetResponseAsFilePath(
245 bool take_ownership, base::FilePath* out_response_path) const {
246 if (fake_response_destination_ != TEMP_FILE)
247 return false;
249 *out_response_path = fake_response_file_path_;
250 return true;
253 void TestURLFetcher::GetExtraRequestHeaders(
254 HttpRequestHeaders* headers) const {
255 *headers = fake_extra_request_headers_;
258 void TestURLFetcher::set_status(const URLRequestStatus& status) {
259 fake_status_ = status;
262 void TestURLFetcher::set_was_fetched_via_proxy(bool flag) {
263 fake_was_fetched_via_proxy_ = flag;
266 void TestURLFetcher::set_response_headers(
267 scoped_refptr<HttpResponseHeaders> headers) {
268 fake_response_headers_ = headers;
271 void TestURLFetcher::set_backoff_delay(base::TimeDelta backoff_delay) {
272 fake_backoff_delay_ = backoff_delay;
275 void TestURLFetcher::SetDelegateForTests(DelegateForTests* delegate_for_tests) {
276 delegate_for_tests_ = delegate_for_tests;
279 void TestURLFetcher::SetResponseString(const std::string& response) {
280 fake_response_destination_ = STRING;
281 fake_response_string_ = response;
284 void TestURLFetcher::SetResponseFilePath(const base::FilePath& path) {
285 fake_response_destination_ = TEMP_FILE;
286 fake_response_file_path_ = path;
289 TestURLFetcherFactory::TestURLFetcherFactory()
290 : ScopedURLFetcherFactory(this),
291 delegate_for_tests_(NULL),
292 remove_fetcher_on_delete_(false) {
295 TestURLFetcherFactory::~TestURLFetcherFactory() {}
297 URLFetcher* TestURLFetcherFactory::CreateURLFetcher(
298 int id,
299 const GURL& url,
300 URLFetcher::RequestType request_type,
301 URLFetcherDelegate* d) {
302 TestURLFetcher* fetcher = new TestURLFetcher(id, url, d);
303 if (remove_fetcher_on_delete_)
304 fetcher->set_owner(this);
305 fetcher->SetDelegateForTests(delegate_for_tests_);
306 fetchers_[id] = fetcher;
307 return fetcher;
310 TestURLFetcher* TestURLFetcherFactory::GetFetcherByID(int id) const {
311 Fetchers::const_iterator i = fetchers_.find(id);
312 return i == fetchers_.end() ? NULL : i->second;
315 void TestURLFetcherFactory::RemoveFetcherFromMap(int id) {
316 Fetchers::iterator i = fetchers_.find(id);
317 DCHECK(i != fetchers_.end());
318 fetchers_.erase(i);
321 void TestURLFetcherFactory::SetDelegateForTests(
322 TestURLFetcherDelegateForTests* delegate_for_tests) {
323 delegate_for_tests_ = delegate_for_tests;
326 FakeURLFetcher::FakeURLFetcher(const GURL& url,
327 URLFetcherDelegate* d,
328 const std::string& response_data,
329 HttpStatusCode response_code,
330 URLRequestStatus::Status status)
331 : TestURLFetcher(0, url, d),
332 weak_factory_(this) {
333 Error error = OK;
334 switch(status) {
335 case URLRequestStatus::SUCCESS:
336 // |error| is initialized to OK.
337 break;
338 case URLRequestStatus::IO_PENDING:
339 error = ERR_IO_PENDING;
340 break;
341 case URLRequestStatus::CANCELED:
342 error = ERR_ABORTED;
343 break;
344 case URLRequestStatus::FAILED:
345 error = ERR_FAILED;
346 break;
348 set_status(URLRequestStatus(status, error));
349 set_response_code(response_code);
350 SetResponseString(response_data);
353 FakeURLFetcher::~FakeURLFetcher() {}
355 void FakeURLFetcher::Start() {
356 base::MessageLoop::current()->PostTask(
357 FROM_HERE,
358 base::Bind(&FakeURLFetcher::RunDelegate, weak_factory_.GetWeakPtr()));
361 void FakeURLFetcher::RunDelegate() {
362 delegate()->OnURLFetchComplete(this);
365 const GURL& FakeURLFetcher::GetURL() const {
366 return TestURLFetcher::GetOriginalURL();
369 FakeURLFetcherFactory::FakeURLFetcherFactory(
370 URLFetcherFactory* default_factory)
371 : ScopedURLFetcherFactory(this),
372 creator_(base::Bind(&DefaultFakeURLFetcherCreator)),
373 default_factory_(default_factory) {
376 FakeURLFetcherFactory::FakeURLFetcherFactory(
377 URLFetcherFactory* default_factory,
378 const FakeURLFetcherCreator& creator)
379 : ScopedURLFetcherFactory(this),
380 creator_(creator),
381 default_factory_(default_factory) {
384 scoped_ptr<FakeURLFetcher> FakeURLFetcherFactory::DefaultFakeURLFetcherCreator(
385 const GURL& url,
386 URLFetcherDelegate* delegate,
387 const std::string& response_data,
388 HttpStatusCode response_code,
389 URLRequestStatus::Status status) {
390 return scoped_ptr<FakeURLFetcher>(
391 new FakeURLFetcher(url, delegate, response_data, response_code, status));
394 FakeURLFetcherFactory::~FakeURLFetcherFactory() {}
396 URLFetcher* FakeURLFetcherFactory::CreateURLFetcher(
397 int id,
398 const GURL& url,
399 URLFetcher::RequestType request_type,
400 URLFetcherDelegate* d) {
401 FakeResponseMap::const_iterator it = fake_responses_.find(url);
402 if (it == fake_responses_.end()) {
403 if (default_factory_ == NULL) {
404 // If we don't have a baked response for that URL we return NULL.
405 DLOG(ERROR) << "No baked response for URL: " << url.spec();
406 return NULL;
407 } else {
408 return default_factory_->CreateURLFetcher(id, url, request_type, d);
412 scoped_ptr<FakeURLFetcher> fake_fetcher =
413 creator_.Run(url, d, it->second.response_data,
414 it->second.response_code, it->second.status);
415 // TODO: Make URLFetcherFactory::CreateURLFetcher return a scoped_ptr
416 return fake_fetcher.release();
419 void FakeURLFetcherFactory::SetFakeResponse(
420 const GURL& url,
421 const std::string& response_data,
422 HttpStatusCode response_code,
423 URLRequestStatus::Status status) {
424 // Overwrite existing URL if it already exists.
425 FakeURLResponse response;
426 response.response_data = response_data;
427 response.response_code = response_code;
428 response.status = status;
429 fake_responses_[url] = response;
432 void FakeURLFetcherFactory::ClearFakeResponses() {
433 fake_responses_.clear();
436 URLFetcherImplFactory::URLFetcherImplFactory() {}
438 URLFetcherImplFactory::~URLFetcherImplFactory() {}
440 URLFetcher* URLFetcherImplFactory::CreateURLFetcher(
441 int id,
442 const GURL& url,
443 URLFetcher::RequestType request_type,
444 URLFetcherDelegate* d) {
445 return new URLFetcherImpl(url, request_type, d);
448 } // namespace net