Remove references to linux_asan from PRESUBMIT files.
[chromium-blink-merge.git] / net / url_request / test_url_fetcher_factory.cc
blobaf76576ff8343797488055504d0d90199de9eecc
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) {
53 TestURLFetcher::~TestURLFetcher() {
54 if (delegate_for_tests_)
55 delegate_for_tests_->OnRequestEnd(id_);
56 if (owner_)
57 owner_->RemoveFetcherFromMap(id_);
60 void TestURLFetcher::SetUploadData(const std::string& upload_content_type,
61 const std::string& upload_content) {
62 upload_content_type_ = upload_content_type;
63 upload_data_ = upload_content;
66 void TestURLFetcher::SetUploadFilePath(
67 const std::string& upload_content_type,
68 const base::FilePath& file_path,
69 uint64 range_offset,
70 uint64 range_length,
71 scoped_refptr<base::TaskRunner> file_task_runner) {
72 upload_file_path_ = file_path;
75 void TestURLFetcher::SetChunkedUpload(const std::string& upload_content_type) {
78 void TestURLFetcher::AppendChunkToUpload(const std::string& data,
79 bool is_last_chunk) {
80 DCHECK(!did_receive_last_chunk_);
81 did_receive_last_chunk_ = is_last_chunk;
82 chunks_.push_back(data);
83 if (delegate_for_tests_)
84 delegate_for_tests_->OnChunkUpload(id_);
87 void TestURLFetcher::SetLoadFlags(int load_flags) {
88 fake_load_flags_= load_flags;
91 int TestURLFetcher::GetLoadFlags() const {
92 return fake_load_flags_;
95 void TestURLFetcher::SetReferrer(const std::string& referrer) {
98 void TestURLFetcher::SetReferrerPolicy(
99 URLRequest::ReferrerPolicy referrer_policy) {
102 void TestURLFetcher::SetExtraRequestHeaders(
103 const std::string& extra_request_headers) {
104 fake_extra_request_headers_.Clear();
105 fake_extra_request_headers_.AddHeadersFromString(extra_request_headers);
108 void TestURLFetcher::AddExtraRequestHeader(const std::string& header_line) {
109 fake_extra_request_headers_.AddHeaderFromString(header_line);
112 void TestURLFetcher::SetRequestContext(
113 URLRequestContextGetter* request_context_getter) {
116 void TestURLFetcher::SetFirstPartyForCookies(
117 const GURL& first_party_for_cookies) {
120 void TestURLFetcher::SetURLRequestUserData(
121 const void* key,
122 const CreateDataCallback& create_data_callback) {
125 void TestURLFetcher::SetStopOnRedirect(bool stop_on_redirect) {
128 void TestURLFetcher::SetAutomaticallyRetryOn5xx(bool retry) {
131 void TestURLFetcher::SetMaxRetriesOn5xx(int max_retries) {
132 fake_max_retries_ = max_retries;
135 int TestURLFetcher::GetMaxRetriesOn5xx() const {
136 return fake_max_retries_;
139 base::TimeDelta TestURLFetcher::GetBackoffDelay() const {
140 return fake_backoff_delay_;
143 void TestURLFetcher::SetAutomaticallyRetryOnNetworkChanges(int max_retries) {
146 void TestURLFetcher::SaveResponseToFileAtPath(
147 const base::FilePath& file_path,
148 scoped_refptr<base::SequencedTaskRunner> file_task_runner) {
149 SetResponseFilePath(file_path);
150 // Asynchronous IO is not supported, so file_task_runner is ignored.
151 base::ThreadRestrictions::ScopedAllowIO allow_io;
152 const size_t written_bytes = base::WriteFile(
153 file_path, fake_response_string_.c_str(), fake_response_string_.size());
154 DCHECK_EQ(written_bytes, fake_response_string_.size());
157 void TestURLFetcher::SaveResponseToTemporaryFile(
158 scoped_refptr<base::SequencedTaskRunner> file_task_runner) {
161 void TestURLFetcher::SaveResponseWithWriter(
162 scoped_ptr<URLFetcherResponseWriter> response_writer) {
163 // In class URLFetcherCore this method is called by all three:
164 // GetResponseAsString() / SaveResponseToFileAtPath() /
165 // SaveResponseToTemporaryFile(). But here (in TestURLFetcher), this method
166 // is never used by any of these three methods. So, file writing is expected
167 // to be done in SaveResponseToFileAtPath(), and this method supports only
168 // URLFetcherStringWriter (for testing of this method only).
169 if (fake_response_destination_ == STRING) {
170 response_writer_ = response_writer.Pass();
171 int response = response_writer_->Initialize(CompletionCallback());
172 // The TestURLFetcher doesn't handle asynchronous writes.
173 DCHECK_EQ(OK, response);
175 scoped_refptr<IOBuffer> buffer(new StringIOBuffer(fake_response_string_));
176 response = response_writer_->Write(buffer.get(),
177 fake_response_string_.size(),
178 CompletionCallback());
179 DCHECK_EQ(static_cast<int>(fake_response_string_.size()), response);
180 response = response_writer_->Finish(CompletionCallback());
181 DCHECK_EQ(OK, response);
182 } else if (fake_response_destination_ == TEMP_FILE) {
183 // SaveResponseToFileAtPath() should be called instead of this method to
184 // save file. Asynchronous file writing using URLFetcherFileWriter is not
185 // supported.
186 NOTIMPLEMENTED();
187 } else {
188 NOTREACHED();
192 HttpResponseHeaders* TestURLFetcher::GetResponseHeaders() const {
193 return fake_response_headers_.get();
196 HostPortPair TestURLFetcher::GetSocketAddress() const {
197 NOTIMPLEMENTED();
198 return HostPortPair();
201 bool TestURLFetcher::WasFetchedViaProxy() const {
202 return fake_was_fetched_via_proxy_;
205 void TestURLFetcher::Start() {
206 // Overriden to do nothing. It is assumed the caller will notify the delegate.
207 if (delegate_for_tests_)
208 delegate_for_tests_->OnRequestStart(id_);
211 const GURL& TestURLFetcher::GetOriginalURL() const {
212 return original_url_;
215 const GURL& TestURLFetcher::GetURL() const {
216 return fake_url_;
219 const URLRequestStatus& TestURLFetcher::GetStatus() const {
220 return fake_status_;
223 int TestURLFetcher::GetResponseCode() const {
224 return fake_response_code_;
227 const ResponseCookies& TestURLFetcher::GetCookies() const {
228 return fake_cookies_;
231 void TestURLFetcher::ReceivedContentWasMalformed() {
234 bool TestURLFetcher::GetResponseAsString(
235 std::string* out_response_string) const {
236 if (fake_response_destination_ != STRING)
237 return false;
239 *out_response_string = fake_response_string_;
240 return true;
243 bool TestURLFetcher::GetResponseAsFilePath(
244 bool take_ownership, base::FilePath* out_response_path) const {
245 if (fake_response_destination_ != TEMP_FILE)
246 return false;
248 *out_response_path = fake_response_file_path_;
249 return true;
252 void TestURLFetcher::GetExtraRequestHeaders(
253 HttpRequestHeaders* headers) const {
254 *headers = fake_extra_request_headers_;
257 void TestURLFetcher::set_status(const URLRequestStatus& status) {
258 fake_status_ = status;
261 void TestURLFetcher::set_was_fetched_via_proxy(bool flag) {
262 fake_was_fetched_via_proxy_ = flag;
265 void TestURLFetcher::set_response_headers(
266 scoped_refptr<HttpResponseHeaders> headers) {
267 fake_response_headers_ = headers;
270 void TestURLFetcher::set_backoff_delay(base::TimeDelta backoff_delay) {
271 fake_backoff_delay_ = backoff_delay;
274 void TestURLFetcher::SetDelegateForTests(DelegateForTests* delegate_for_tests) {
275 delegate_for_tests_ = delegate_for_tests;
278 void TestURLFetcher::SetResponseString(const std::string& response) {
279 fake_response_destination_ = STRING;
280 fake_response_string_ = response;
283 void TestURLFetcher::SetResponseFilePath(const base::FilePath& path) {
284 fake_response_destination_ = TEMP_FILE;
285 fake_response_file_path_ = path;
288 TestURLFetcherFactory::TestURLFetcherFactory()
289 : ScopedURLFetcherFactory(this),
290 delegate_for_tests_(NULL),
291 remove_fetcher_on_delete_(false) {
294 TestURLFetcherFactory::~TestURLFetcherFactory() {}
296 URLFetcher* TestURLFetcherFactory::CreateURLFetcher(
297 int id,
298 const GURL& url,
299 URLFetcher::RequestType request_type,
300 URLFetcherDelegate* d) {
301 TestURLFetcher* fetcher = new TestURLFetcher(id, url, d);
302 if (remove_fetcher_on_delete_)
303 fetcher->set_owner(this);
304 fetcher->SetDelegateForTests(delegate_for_tests_);
305 fetchers_[id] = fetcher;
306 return fetcher;
309 TestURLFetcher* TestURLFetcherFactory::GetFetcherByID(int id) const {
310 Fetchers::const_iterator i = fetchers_.find(id);
311 return i == fetchers_.end() ? NULL : i->second;
314 void TestURLFetcherFactory::RemoveFetcherFromMap(int id) {
315 Fetchers::iterator i = fetchers_.find(id);
316 DCHECK(i != fetchers_.end());
317 fetchers_.erase(i);
320 void TestURLFetcherFactory::SetDelegateForTests(
321 TestURLFetcherDelegateForTests* delegate_for_tests) {
322 delegate_for_tests_ = delegate_for_tests;
325 FakeURLFetcher::FakeURLFetcher(const GURL& url,
326 URLFetcherDelegate* d,
327 const std::string& response_data,
328 HttpStatusCode response_code,
329 URLRequestStatus::Status status)
330 : TestURLFetcher(0, url, d),
331 weak_factory_(this) {
332 Error error = OK;
333 switch(status) {
334 case URLRequestStatus::SUCCESS:
335 // |error| is initialized to OK.
336 break;
337 case URLRequestStatus::IO_PENDING:
338 error = ERR_IO_PENDING;
339 break;
340 case URLRequestStatus::CANCELED:
341 error = ERR_ABORTED;
342 break;
343 case URLRequestStatus::FAILED:
344 error = ERR_FAILED;
345 break;
347 set_status(URLRequestStatus(status, error));
348 set_response_code(response_code);
349 SetResponseString(response_data);
352 FakeURLFetcher::~FakeURLFetcher() {}
354 void FakeURLFetcher::Start() {
355 base::MessageLoop::current()->PostTask(
356 FROM_HERE,
357 base::Bind(&FakeURLFetcher::RunDelegate, weak_factory_.GetWeakPtr()));
360 void FakeURLFetcher::RunDelegate() {
361 delegate()->OnURLFetchComplete(this);
364 const GURL& FakeURLFetcher::GetURL() const {
365 return TestURLFetcher::GetOriginalURL();
368 FakeURLFetcherFactory::FakeURLFetcherFactory(
369 URLFetcherFactory* default_factory)
370 : ScopedURLFetcherFactory(this),
371 creator_(base::Bind(&DefaultFakeURLFetcherCreator)),
372 default_factory_(default_factory) {
375 FakeURLFetcherFactory::FakeURLFetcherFactory(
376 URLFetcherFactory* default_factory,
377 const FakeURLFetcherCreator& creator)
378 : ScopedURLFetcherFactory(this),
379 creator_(creator),
380 default_factory_(default_factory) {
383 scoped_ptr<FakeURLFetcher> FakeURLFetcherFactory::DefaultFakeURLFetcherCreator(
384 const GURL& url,
385 URLFetcherDelegate* delegate,
386 const std::string& response_data,
387 HttpStatusCode response_code,
388 URLRequestStatus::Status status) {
389 return scoped_ptr<FakeURLFetcher>(
390 new FakeURLFetcher(url, delegate, response_data, response_code, status));
393 FakeURLFetcherFactory::~FakeURLFetcherFactory() {}
395 URLFetcher* FakeURLFetcherFactory::CreateURLFetcher(
396 int id,
397 const GURL& url,
398 URLFetcher::RequestType request_type,
399 URLFetcherDelegate* d) {
400 FakeResponseMap::const_iterator it = fake_responses_.find(url);
401 if (it == fake_responses_.end()) {
402 if (default_factory_ == NULL) {
403 // If we don't have a baked response for that URL we return NULL.
404 DLOG(ERROR) << "No baked response for URL: " << url.spec();
405 return NULL;
406 } else {
407 return default_factory_->CreateURLFetcher(id, url, request_type, d);
411 scoped_ptr<FakeURLFetcher> fake_fetcher =
412 creator_.Run(url, d, it->second.response_data,
413 it->second.response_code, it->second.status);
414 // TODO: Make URLFetcherFactory::CreateURLFetcher return a scoped_ptr
415 return fake_fetcher.release();
418 void FakeURLFetcherFactory::SetFakeResponse(
419 const GURL& url,
420 const std::string& response_data,
421 HttpStatusCode response_code,
422 URLRequestStatus::Status status) {
423 // Overwrite existing URL if it already exists.
424 FakeURLResponse response;
425 response.response_data = response_data;
426 response.response_code = response_code;
427 response.status = status;
428 fake_responses_[url] = response;
431 void FakeURLFetcherFactory::ClearFakeResponses() {
432 fake_responses_.clear();
435 URLFetcherImplFactory::URLFetcherImplFactory() {}
437 URLFetcherImplFactory::~URLFetcherImplFactory() {}
439 URLFetcher* URLFetcherImplFactory::CreateURLFetcher(
440 int id,
441 const GURL& url,
442 URLFetcher::RequestType request_type,
443 URLFetcherDelegate* d) {
444 return new URLFetcherImpl(url, request_type, d);
447 } // namespace net