- add sources.
[platform/framework/web/crosswalk.git] / src / net / url_request / url_request_test_job.cc
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/url_request_test_job.h"
6
7 #include <algorithm>
8 #include <list>
9
10 #include "base/bind.h"
11 #include "base/compiler_specific.h"
12 #include "base/lazy_instance.h"
13 #include "base/message_loop/message_loop.h"
14 #include "base/strings/string_util.h"
15 #include "net/base/io_buffer.h"
16 #include "net/base/net_errors.h"
17 #include "net/http/http_response_headers.h"
18
19 namespace net {
20
21 namespace {
22
23 typedef std::list<URLRequestTestJob*> URLRequestJobList;
24 base::LazyInstance<URLRequestJobList>::Leaky
25     g_pending_jobs = LAZY_INSTANCE_INITIALIZER;
26
27 }  // namespace
28
29 // static getters for known URLs
30 GURL URLRequestTestJob::test_url_1() {
31   return GURL("test:url1");
32 }
33 GURL URLRequestTestJob::test_url_2() {
34   return GURL("test:url2");
35 }
36 GURL URLRequestTestJob::test_url_3() {
37   return GURL("test:url3");
38 }
39 GURL URLRequestTestJob::test_url_error() {
40   return GURL("test:error");
41 }
42
43 // static getters for known URL responses
44 std::string URLRequestTestJob::test_data_1() {
45   return std::string("<html><title>Test One</title></html>");
46 }
47 std::string URLRequestTestJob::test_data_2() {
48   return std::string("<html><title>Test Two Two</title></html>");
49 }
50 std::string URLRequestTestJob::test_data_3() {
51   return std::string("<html><title>Test Three Three Three</title></html>");
52 }
53
54 // static getter for simple response headers
55 std::string URLRequestTestJob::test_headers() {
56   static const char kHeaders[] =
57       "HTTP/1.1 200 OK\0"
58       "Content-type: text/html\0"
59       "\0";
60   return std::string(kHeaders, arraysize(kHeaders));
61 }
62
63 // static getter for redirect response headers
64 std::string URLRequestTestJob::test_redirect_headers() {
65   static const char kHeaders[] =
66       "HTTP/1.1 302 MOVED\0"
67       "Location: somewhere\0"
68       "\0";
69   return std::string(kHeaders, arraysize(kHeaders));
70 }
71
72 // static getter for error response headers
73 std::string URLRequestTestJob::test_error_headers() {
74   static const char kHeaders[] =
75       "HTTP/1.1 500 BOO HOO\0"
76       "\0";
77   return std::string(kHeaders, arraysize(kHeaders));
78 }
79
80 // static
81 URLRequestJob* URLRequestTestJob::Factory(URLRequest* request,
82                                           NetworkDelegate* network_delegate,
83                                           const std::string& scheme) {
84   return new URLRequestTestJob(request, network_delegate);
85 }
86
87 URLRequestTestJob::URLRequestTestJob(URLRequest* request,
88                                      NetworkDelegate* network_delegate)
89     : URLRequestJob(request, network_delegate),
90       auto_advance_(false),
91       stage_(WAITING),
92       priority_(DEFAULT_PRIORITY),
93       offset_(0),
94       async_buf_(NULL),
95       async_buf_size_(0),
96       weak_factory_(this) {
97 }
98
99 URLRequestTestJob::URLRequestTestJob(URLRequest* request,
100                                      NetworkDelegate* network_delegate,
101                                      bool auto_advance)
102     : URLRequestJob(request, network_delegate),
103       auto_advance_(auto_advance),
104       stage_(WAITING),
105       priority_(DEFAULT_PRIORITY),
106       offset_(0),
107       async_buf_(NULL),
108       async_buf_size_(0),
109       weak_factory_(this) {
110 }
111
112 URLRequestTestJob::URLRequestTestJob(URLRequest* request,
113                                      NetworkDelegate* network_delegate,
114                                      const std::string& response_headers,
115                                      const std::string& response_data,
116                                      bool auto_advance)
117     : URLRequestJob(request, network_delegate),
118       auto_advance_(auto_advance),
119       stage_(WAITING),
120       priority_(DEFAULT_PRIORITY),
121       response_headers_(new HttpResponseHeaders(response_headers)),
122       response_data_(response_data),
123       offset_(0),
124       async_buf_(NULL),
125       async_buf_size_(0),
126       weak_factory_(this) {
127 }
128
129 URLRequestTestJob::~URLRequestTestJob() {
130   g_pending_jobs.Get().erase(
131       std::remove(
132           g_pending_jobs.Get().begin(), g_pending_jobs.Get().end(), this),
133       g_pending_jobs.Get().end());
134 }
135
136 bool URLRequestTestJob::GetMimeType(std::string* mime_type) const {
137   DCHECK(mime_type);
138   if (!response_headers_.get())
139     return false;
140   return response_headers_->GetMimeType(mime_type);
141 }
142
143 void URLRequestTestJob::SetPriority(RequestPriority priority) {
144   priority_ = priority;
145 }
146
147 void URLRequestTestJob::Start() {
148   // Start reading asynchronously so that all error reporting and data
149   // callbacks happen as they would for network requests.
150   base::MessageLoop::current()->PostTask(
151       FROM_HERE, base::Bind(&URLRequestTestJob::StartAsync,
152                             weak_factory_.GetWeakPtr()));
153 }
154
155 void URLRequestTestJob::StartAsync() {
156   if (!response_headers_.get()) {
157     response_headers_ = new HttpResponseHeaders(test_headers());
158     if (request_->url().spec() == test_url_1().spec()) {
159       response_data_ = test_data_1();
160       stage_ = DATA_AVAILABLE;  // Simulate a synchronous response for this one.
161     } else if (request_->url().spec() == test_url_2().spec()) {
162       response_data_ = test_data_2();
163     } else if (request_->url().spec() == test_url_3().spec()) {
164       response_data_ = test_data_3();
165     } else {
166       AdvanceJob();
167
168       // unexpected url, return error
169       // FIXME(brettw) we may want to use WININET errors or have some more types
170       // of errors
171       NotifyDone(URLRequestStatus(URLRequestStatus::FAILED,
172                                   ERR_INVALID_URL));
173       // FIXME(brettw): this should emulate a network error, and not just fail
174       // initiating a connection
175       return;
176     }
177   }
178
179   AdvanceJob();
180
181   this->NotifyHeadersComplete();
182 }
183
184 bool URLRequestTestJob::ReadRawData(IOBuffer* buf, int buf_size,
185                                     int *bytes_read) {
186   if (stage_ == WAITING) {
187     async_buf_ = buf;
188     async_buf_size_ = buf_size;
189     SetStatus(URLRequestStatus(URLRequestStatus::IO_PENDING, 0));
190     return false;
191   }
192
193   DCHECK(bytes_read);
194   *bytes_read = 0;
195
196   if (offset_ >= static_cast<int>(response_data_.length())) {
197     return true;  // done reading
198   }
199
200   int to_read = buf_size;
201   if (to_read + offset_ > static_cast<int>(response_data_.length()))
202     to_read = static_cast<int>(response_data_.length()) - offset_;
203
204   memcpy(buf->data(), &response_data_.c_str()[offset_], to_read);
205   offset_ += to_read;
206
207   *bytes_read = to_read;
208   return true;
209 }
210
211 void URLRequestTestJob::GetResponseInfo(HttpResponseInfo* info) {
212   if (response_headers_.get())
213     info->headers = response_headers_;
214 }
215
216 void URLRequestTestJob::GetLoadTimingInfo(
217     LoadTimingInfo* load_timing_info) const {
218   // Preserve the times the URLRequest is responsible for, but overwrite all
219   // the others.
220   base::TimeTicks request_start = load_timing_info->request_start;
221   base::Time request_start_time = load_timing_info->request_start_time;
222   *load_timing_info = load_timing_info_;
223   load_timing_info->request_start = request_start;
224   load_timing_info->request_start_time = request_start_time;
225 }
226
227 int URLRequestTestJob::GetResponseCode() const {
228   if (response_headers_.get())
229     return response_headers_->response_code();
230   return -1;
231 }
232
233 bool URLRequestTestJob::IsRedirectResponse(GURL* location,
234                                            int* http_status_code) {
235   if (!response_headers_.get())
236     return false;
237
238   std::string value;
239   if (!response_headers_->IsRedirect(&value))
240     return false;
241
242   *location = request_->url().Resolve(value);
243   *http_status_code = response_headers_->response_code();
244   return true;
245 }
246
247 void URLRequestTestJob::Kill() {
248   stage_ = DONE;
249   URLRequestJob::Kill();
250   weak_factory_.InvalidateWeakPtrs();
251   g_pending_jobs.Get().erase(
252       std::remove(
253           g_pending_jobs.Get().begin(), g_pending_jobs.Get().end(), this),
254       g_pending_jobs.Get().end());
255 }
256
257 void URLRequestTestJob::ProcessNextOperation() {
258   switch (stage_) {
259     case WAITING:
260       // Must call AdvanceJob() prior to NotifyReadComplete() since that may
261       // delete |this|.
262       AdvanceJob();
263       stage_ = DATA_AVAILABLE;
264       // OK if ReadRawData wasn't called yet.
265       if (async_buf_) {
266         int bytes_read;
267         if (!ReadRawData(async_buf_, async_buf_size_, &bytes_read))
268           NOTREACHED() << "This should not return false in DATA_AVAILABLE.";
269         SetStatus(URLRequestStatus());  // clear the io pending flag
270         if (NextReadAsync()) {
271           // Make all future reads return io pending until the next
272           // ProcessNextOperation().
273           stage_ = WAITING;
274         }
275         NotifyReadComplete(bytes_read);
276       }
277       break;
278     case DATA_AVAILABLE:
279       AdvanceJob();
280       stage_ = ALL_DATA;  // done sending data
281       break;
282     case ALL_DATA:
283       stage_ = DONE;
284       return;
285     case DONE:
286       return;
287     default:
288       NOTREACHED() << "Invalid stage";
289       return;
290   }
291 }
292
293 bool URLRequestTestJob::NextReadAsync() {
294   return false;
295 }
296
297 void URLRequestTestJob::AdvanceJob() {
298   if (auto_advance_) {
299     base::MessageLoop::current()->PostTask(
300         FROM_HERE, base::Bind(&URLRequestTestJob::ProcessNextOperation,
301                               weak_factory_.GetWeakPtr()));
302     return;
303   }
304   g_pending_jobs.Get().push_back(this);
305 }
306
307 // static
308 bool URLRequestTestJob::ProcessOnePendingMessage() {
309   if (g_pending_jobs.Get().empty())
310     return false;
311
312   URLRequestTestJob* next_job(g_pending_jobs.Get().front());
313   g_pending_jobs.Get().pop_front();
314
315   DCHECK(!next_job->auto_advance());  // auto_advance jobs should be in this q
316   next_job->ProcessNextOperation();
317   return true;
318 }
319
320 }  // namespace net