Roll src/third_party/WebKit eac3800:0237a66 (svn 202606:202607)
[chromium-blink-merge.git] / net / url_request / url_request_test_job.cc
blob7530d42bb7a3b824a1cc27ec3ac56d6b51390b58
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/url_request_test_job.h"
7 #include <algorithm>
8 #include <list>
10 #include "base/bind.h"
11 #include "base/compiler_specific.h"
12 #include "base/lazy_instance.h"
13 #include "base/location.h"
14 #include "base/single_thread_task_runner.h"
15 #include "base/strings/string_util.h"
16 #include "base/thread_task_runner_handle.h"
17 #include "net/base/io_buffer.h"
18 #include "net/base/net_errors.h"
19 #include "net/http/http_response_headers.h"
21 namespace net {
23 namespace {
25 typedef std::list<URLRequestTestJob*> URLRequestJobList;
26 base::LazyInstance<URLRequestJobList>::Leaky
27 g_pending_jobs = LAZY_INSTANCE_INITIALIZER;
29 class TestJobProtocolHandler : public URLRequestJobFactory::ProtocolHandler {
30 public:
31 // URLRequestJobFactory::ProtocolHandler implementation:
32 URLRequestJob* MaybeCreateJob(
33 URLRequest* request,
34 NetworkDelegate* network_delegate) const override {
35 return new URLRequestTestJob(request, network_delegate);
39 } // namespace
41 // static getters for known URLs
42 GURL URLRequestTestJob::test_url_1() {
43 return GURL("test:url1");
45 GURL URLRequestTestJob::test_url_2() {
46 return GURL("test:url2");
48 GURL URLRequestTestJob::test_url_3() {
49 return GURL("test:url3");
51 GURL URLRequestTestJob::test_url_4() {
52 return GURL("test:url4");
54 GURL URLRequestTestJob::test_url_error() {
55 return GURL("test:error");
57 GURL URLRequestTestJob::test_url_redirect_to_url_2() {
58 return GURL("test:redirect_to_2");
61 // static getters for known URL responses
62 std::string URLRequestTestJob::test_data_1() {
63 return std::string("<html><title>Test One</title></html>");
65 std::string URLRequestTestJob::test_data_2() {
66 return std::string("<html><title>Test Two Two</title></html>");
68 std::string URLRequestTestJob::test_data_3() {
69 return std::string("<html><title>Test Three Three Three</title></html>");
71 std::string URLRequestTestJob::test_data_4() {
72 return std::string("<html><title>Test Four Four Four Four</title></html>");
75 // static getter for simple response headers
76 std::string URLRequestTestJob::test_headers() {
77 static const char kHeaders[] =
78 "HTTP/1.1 200 OK\0"
79 "Content-type: text/html\0"
80 "\0";
81 return std::string(kHeaders, arraysize(kHeaders));
84 // static getter for redirect response headers
85 std::string URLRequestTestJob::test_redirect_headers() {
86 static const char kHeaders[] =
87 "HTTP/1.1 302 MOVED\0"
88 "Location: somewhere\0"
89 "\0";
90 return std::string(kHeaders, arraysize(kHeaders));
93 // static getter for redirect response headers
94 std::string URLRequestTestJob::test_redirect_to_url_2_headers() {
95 std::string headers = "HTTP/1.1 302 MOVED";
96 headers.push_back('\0');
97 headers += "Location: ";
98 headers += test_url_2().spec();
99 headers.push_back('\0');
100 headers.push_back('\0');
101 return headers;
104 // static getter for error response headers
105 std::string URLRequestTestJob::test_error_headers() {
106 static const char kHeaders[] =
107 "HTTP/1.1 500 BOO HOO\0"
108 "\0";
109 return std::string(kHeaders, arraysize(kHeaders));
112 // static
113 scoped_ptr<URLRequestJobFactory::ProtocolHandler>
114 URLRequestTestJob::CreateProtocolHandler() {
115 return make_scoped_ptr(new TestJobProtocolHandler());
118 URLRequestTestJob::URLRequestTestJob(URLRequest* request,
119 NetworkDelegate* network_delegate)
120 : URLRequestJob(request, network_delegate),
121 auto_advance_(false),
122 stage_(WAITING),
123 priority_(DEFAULT_PRIORITY),
124 offset_(0),
125 async_buf_(NULL),
126 async_buf_size_(0),
127 weak_factory_(this) {
130 URLRequestTestJob::URLRequestTestJob(URLRequest* request,
131 NetworkDelegate* network_delegate,
132 bool auto_advance)
133 : URLRequestJob(request, network_delegate),
134 auto_advance_(auto_advance),
135 stage_(WAITING),
136 priority_(DEFAULT_PRIORITY),
137 offset_(0),
138 async_buf_(NULL),
139 async_buf_size_(0),
140 weak_factory_(this) {
143 URLRequestTestJob::URLRequestTestJob(URLRequest* request,
144 NetworkDelegate* network_delegate,
145 const std::string& response_headers,
146 const std::string& response_data,
147 bool auto_advance)
148 : URLRequestJob(request, network_delegate),
149 auto_advance_(auto_advance),
150 stage_(WAITING),
151 priority_(DEFAULT_PRIORITY),
152 response_headers_(new HttpResponseHeaders(response_headers)),
153 response_data_(response_data),
154 offset_(0),
155 async_buf_(NULL),
156 async_buf_size_(0),
157 weak_factory_(this) {
160 URLRequestTestJob::~URLRequestTestJob() {
161 g_pending_jobs.Get().erase(
162 std::remove(
163 g_pending_jobs.Get().begin(), g_pending_jobs.Get().end(), this),
164 g_pending_jobs.Get().end());
167 bool URLRequestTestJob::GetMimeType(std::string* mime_type) const {
168 DCHECK(mime_type);
169 if (!response_headers_.get())
170 return false;
171 return response_headers_->GetMimeType(mime_type);
174 void URLRequestTestJob::SetPriority(RequestPriority priority) {
175 priority_ = priority;
178 void URLRequestTestJob::Start() {
179 // Start reading asynchronously so that all error reporting and data
180 // callbacks happen as they would for network requests.
181 base::ThreadTaskRunnerHandle::Get()->PostTask(
182 FROM_HERE,
183 base::Bind(&URLRequestTestJob::StartAsync, weak_factory_.GetWeakPtr()));
186 void URLRequestTestJob::StartAsync() {
187 if (!response_headers_.get()) {
188 response_headers_ = new HttpResponseHeaders(test_headers());
189 if (request_->url().spec() == test_url_1().spec()) {
190 response_data_ = test_data_1();
191 stage_ = DATA_AVAILABLE; // Simulate a synchronous response for this one.
192 } else if (request_->url().spec() == test_url_2().spec()) {
193 response_data_ = test_data_2();
194 } else if (request_->url().spec() == test_url_3().spec()) {
195 response_data_ = test_data_3();
196 } else if (request_->url().spec() == test_url_4().spec()) {
197 response_data_ = test_data_4();
198 } else if (request_->url().spec() == test_url_redirect_to_url_2().spec()) {
199 response_headers_ =
200 new HttpResponseHeaders(test_redirect_to_url_2_headers());
201 } else {
202 AdvanceJob();
204 // unexpected url, return error
205 // FIXME(brettw) we may want to use WININET errors or have some more types
206 // of errors
207 NotifyDone(URLRequestStatus(URLRequestStatus::FAILED,
208 ERR_INVALID_URL));
209 // FIXME(brettw): this should emulate a network error, and not just fail
210 // initiating a connection
211 return;
215 AdvanceJob();
217 this->NotifyHeadersComplete();
220 bool URLRequestTestJob::ReadRawData(IOBuffer* buf, int buf_size,
221 int *bytes_read) {
222 if (stage_ == WAITING) {
223 async_buf_ = buf;
224 async_buf_size_ = buf_size;
225 SetStatus(URLRequestStatus(URLRequestStatus::IO_PENDING, 0));
226 return false;
229 DCHECK(bytes_read);
230 *bytes_read = 0;
232 if (offset_ >= static_cast<int>(response_data_.length())) {
233 return true; // done reading
236 int to_read = buf_size;
237 if (to_read + offset_ > static_cast<int>(response_data_.length()))
238 to_read = static_cast<int>(response_data_.length()) - offset_;
240 memcpy(buf->data(), &response_data_.c_str()[offset_], to_read);
241 offset_ += to_read;
243 *bytes_read = to_read;
244 return true;
247 void URLRequestTestJob::GetResponseInfo(HttpResponseInfo* info) {
248 if (response_headers_.get())
249 info->headers = response_headers_;
252 void URLRequestTestJob::GetLoadTimingInfo(
253 LoadTimingInfo* load_timing_info) const {
254 // Preserve the times the URLRequest is responsible for, but overwrite all
255 // the others.
256 base::TimeTicks request_start = load_timing_info->request_start;
257 base::Time request_start_time = load_timing_info->request_start_time;
258 *load_timing_info = load_timing_info_;
259 load_timing_info->request_start = request_start;
260 load_timing_info->request_start_time = request_start_time;
263 int URLRequestTestJob::GetResponseCode() const {
264 if (response_headers_.get())
265 return response_headers_->response_code();
266 return -1;
269 bool URLRequestTestJob::IsRedirectResponse(GURL* location,
270 int* http_status_code) {
271 if (!response_headers_.get())
272 return false;
274 std::string value;
275 if (!response_headers_->IsRedirect(&value))
276 return false;
278 *location = request_->url().Resolve(value);
279 *http_status_code = response_headers_->response_code();
280 return true;
283 void URLRequestTestJob::Kill() {
284 stage_ = DONE;
285 URLRequestJob::Kill();
286 weak_factory_.InvalidateWeakPtrs();
287 g_pending_jobs.Get().erase(
288 std::remove(
289 g_pending_jobs.Get().begin(), g_pending_jobs.Get().end(), this),
290 g_pending_jobs.Get().end());
293 void URLRequestTestJob::ProcessNextOperation() {
294 switch (stage_) {
295 case WAITING:
296 // Must call AdvanceJob() prior to NotifyReadComplete() since that may
297 // delete |this|.
298 AdvanceJob();
299 stage_ = DATA_AVAILABLE;
300 // OK if ReadRawData wasn't called yet.
301 if (async_buf_) {
302 int bytes_read;
303 if (!ReadRawData(async_buf_, async_buf_size_, &bytes_read))
304 NOTREACHED() << "This should not return false in DATA_AVAILABLE.";
305 SetStatus(URLRequestStatus()); // clear the io pending flag
306 if (NextReadAsync()) {
307 // Make all future reads return io pending until the next
308 // ProcessNextOperation().
309 stage_ = WAITING;
311 NotifyReadComplete(bytes_read);
313 break;
314 case DATA_AVAILABLE:
315 AdvanceJob();
316 stage_ = ALL_DATA; // done sending data
317 break;
318 case ALL_DATA:
319 stage_ = DONE;
320 return;
321 case DONE:
322 return;
323 default:
324 NOTREACHED() << "Invalid stage";
325 return;
329 bool URLRequestTestJob::NextReadAsync() {
330 return false;
333 void URLRequestTestJob::AdvanceJob() {
334 if (auto_advance_) {
335 base::ThreadTaskRunnerHandle::Get()->PostTask(
336 FROM_HERE, base::Bind(&URLRequestTestJob::ProcessNextOperation,
337 weak_factory_.GetWeakPtr()));
338 return;
340 g_pending_jobs.Get().push_back(this);
343 // static
344 bool URLRequestTestJob::ProcessOnePendingMessage() {
345 if (g_pending_jobs.Get().empty())
346 return false;
348 URLRequestTestJob* next_job(g_pending_jobs.Get().front());
349 g_pending_jobs.Get().pop_front();
351 DCHECK(!next_job->auto_advance()); // auto_advance jobs should be in this q
352 next_job->ProcessNextOperation();
353 return true;
356 } // namespace net