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/test/url_request/url_request_mock_http_job.h"
7 #include "base/files/file_util.h"
8 #include "base/macros.h"
9 #include "base/message_loop/message_loop.h"
10 #include "base/strings/string_number_conversions.h"
11 #include "base/strings/string_util.h"
12 #include "base/strings/utf_string_conversions.h"
13 #include "base/task_runner_util.h"
14 #include "base/threading/sequenced_worker_pool.h"
15 #include "base/threading/thread_restrictions.h"
16 #include "net/base/filename_util.h"
17 #include "net/base/net_errors.h"
18 #include "net/base/url_util.h"
19 #include "net/http/http_response_headers.h"
20 #include "net/url_request/url_request_filter.h"
21 #include "net/url_request/url_request_interceptor.h"
27 const char kMockHostname
[] = "mock.http";
28 const base::FilePath::CharType kMockHeaderFileSuffix
[] =
29 FILE_PATH_LITERAL(".mock-http-headers");
31 // String names of failure phases matching FailurePhase enum.
32 const char* kFailurePhase
[] {
34 "readasync", // READ_ASYNC
35 "readsync", // READ_SYNC
38 class MockJobInterceptor
: public net::URLRequestInterceptor
{
40 // When |map_all_requests_to_base_path| is true, all request should return the
41 // contents of the file at |base_path|. When |map_all_requests_to_base_path|
42 // is false, |base_path| is the file path leading to the root of the directory
43 // to use as the root of the HTTP server.
45 const base::FilePath
& base_path
,
46 bool map_all_requests_to_base_path
,
47 const scoped_refptr
<base::SequencedWorkerPool
>& worker_pool
)
48 : base_path_(base_path
),
49 map_all_requests_to_base_path_(map_all_requests_to_base_path
),
50 worker_pool_(worker_pool
) {}
51 ~MockJobInterceptor() override
{}
53 // net::URLRequestJobFactory::ProtocolHandler implementation
54 net::URLRequestJob
* MaybeInterceptRequest(
55 net::URLRequest
* request
,
56 net::NetworkDelegate
* network_delegate
) const override
{
57 return new URLRequestMockHTTPJob(
60 map_all_requests_to_base_path_
? base_path_
: GetOnDiskPath(request
),
61 worker_pool_
->GetTaskRunnerWithShutdownBehavior(
62 base::SequencedWorkerPool::SKIP_ON_SHUTDOWN
));
66 base::FilePath
GetOnDiskPath(net::URLRequest
* request
) const {
67 // Conceptually we just want to "return base_path_ + request->url().path()".
68 // But path in the request URL is in URL space (i.e. %-encoded spaces).
69 // So first we convert base FilePath to a URL, then append the URL
70 // path to that, and convert the final URL back to a FilePath.
71 GURL
file_url(net::FilePathToFileURL(base_path_
));
72 std::string url
= file_url
.spec() + request
->url().path();
73 base::FilePath file_path
;
74 net::FileURLToFilePath(GURL(url
), &file_path
);
78 const base::FilePath base_path_
;
79 const bool map_all_requests_to_base_path_
;
80 const scoped_refptr
<base::SequencedWorkerPool
> worker_pool_
;
82 DISALLOW_COPY_AND_ASSIGN(MockJobInterceptor
);
85 std::string
DoFileIO(const base::FilePath
& file_path
) {
86 base::FilePath header_file
=
87 base::FilePath(file_path
.value() + kMockHeaderFileSuffix
);
89 if (!base::PathExists(header_file
)) {
90 // If there is no mock-http-headers file, fake a 200 OK.
91 return "HTTP/1.0 200 OK\n";
94 std::string raw_headers
;
95 base::ReadFileToString(header_file
, &raw_headers
);
99 // For a given file |path| and |scheme|, return the URL served by the
100 // URlRequestMockHTTPJob.
101 GURL
GetMockUrlForScheme(const base::FilePath
& path
,
102 const std::string
& scheme
) {
103 std::string url
= scheme
+ "://" + kMockHostname
+ "/";
104 std::string path_str
= path
.MaybeAsASCII();
105 DCHECK(!path_str
.empty()); // We only expect ASCII paths in tests.
106 url
.append(path_str
);
113 void URLRequestMockHTTPJob::AddUrlHandlers(
114 const base::FilePath
& base_path
,
115 const scoped_refptr
<base::SequencedWorkerPool
>& worker_pool
) {
116 // Add kMockHostname to net::URLRequestFilter, for both HTTP and HTTPS.
117 net::URLRequestFilter
* filter
= net::URLRequestFilter::GetInstance();
118 filter
->AddHostnameInterceptor(
119 "http", kMockHostname
, CreateInterceptor(base_path
, worker_pool
));
120 filter
->AddHostnameInterceptor("https", kMockHostname
,
121 CreateInterceptor(base_path
, worker_pool
));
125 GURL
URLRequestMockHTTPJob::GetMockUrl(const base::FilePath
& path
) {
126 return GetMockUrlForScheme(path
, "http");
130 GURL
URLRequestMockHTTPJob::GetMockHttpsUrl(const base::FilePath
& path
) {
131 return GetMockUrlForScheme(path
, "https");
135 GURL
URLRequestMockHTTPJob::GetMockUrlWithFailure(const base::FilePath
& path
,
138 static_assert(arraysize(kFailurePhase
) == MAX_FAILURE_PHASE
,
139 "kFailurePhase must match FailurePhase enum");
140 DCHECK_GE(phase
, START
);
141 DCHECK_LE(phase
, READ_SYNC
);
142 std::string
url(GetMockUrl(path
).spec());
144 url
.append(kFailurePhase
[phase
]);
146 url
.append(base::IntToString(net_error
));
151 scoped_ptr
<net::URLRequestInterceptor
> URLRequestMockHTTPJob::CreateInterceptor(
152 const base::FilePath
& base_path
,
153 const scoped_refptr
<base::SequencedWorkerPool
>& worker_pool
) {
154 return scoped_ptr
<net::URLRequestInterceptor
>(
155 new MockJobInterceptor(base_path
, false, worker_pool
));
159 scoped_ptr
<net::URLRequestInterceptor
>
160 URLRequestMockHTTPJob::CreateInterceptorForSingleFile(
161 const base::FilePath
& file
,
162 const scoped_refptr
<base::SequencedWorkerPool
>& worker_pool
) {
163 return scoped_ptr
<net::URLRequestInterceptor
>(
164 new MockJobInterceptor(file
, true, worker_pool
));
167 URLRequestMockHTTPJob::URLRequestMockHTTPJob(
168 net::URLRequest
* request
,
169 net::NetworkDelegate
* network_delegate
,
170 const base::FilePath
& file_path
,
171 const scoped_refptr
<base::TaskRunner
>& task_runner
)
172 : net::URLRequestFileJob(request
, network_delegate
, file_path
, task_runner
),
173 task_runner_(task_runner
),
174 weak_ptr_factory_(this) {
177 URLRequestMockHTTPJob::~URLRequestMockHTTPJob() {
180 // Public virtual version.
181 void URLRequestMockHTTPJob::GetResponseInfo(net::HttpResponseInfo
* info
) {
182 // Forward to private const version.
183 GetResponseInfoConst(info
);
186 bool URLRequestMockHTTPJob::IsRedirectResponse(GURL
* location
,
187 int* http_status_code
) {
188 // Override the net::URLRequestFileJob implementation to invoke the default
189 // one based on HttpResponseInfo.
190 return net::URLRequestJob::IsRedirectResponse(location
, http_status_code
);
193 // Public virtual version.
194 void URLRequestMockHTTPJob::Start() {
195 if (MaybeReportErrorOnPhase(START
))
197 base::PostTaskAndReplyWithResult(
200 base::Bind(&DoFileIO
, file_path_
),
201 base::Bind(&URLRequestMockHTTPJob::SetHeadersAndStart
,
202 weak_ptr_factory_
.GetWeakPtr()));
205 // Public virtual version.
206 bool URLRequestMockHTTPJob::ReadRawData(IOBuffer
* buf
,
209 if (MaybeReportErrorOnPhase(READ_SYNC
))
211 if (MaybeReportErrorOnPhase(READ_ASYNC
))
213 return URLRequestFileJob::ReadRawData(buf
, buf_size
, bytes_read
);
216 void URLRequestMockHTTPJob::SetHeadersAndStart(const std::string
& raw_headers
) {
217 if (MaybeReportErrorOnPhase(START
))
219 raw_headers_
= raw_headers
;
220 // Handle CRLF line-endings.
221 ReplaceSubstringsAfterOffset(&raw_headers_
, 0, "\r\n", "\n");
222 // ParseRawHeaders expects \0 to end each header line.
223 ReplaceSubstringsAfterOffset(&raw_headers_
, 0, "\n", std::string("\0", 1));
224 URLRequestFileJob::Start();
227 bool URLRequestMockHTTPJob::MaybeReportErrorOnPhase(
228 FailurePhase current_phase
) {
229 DCHECK_GE(current_phase
, START
);
230 DCHECK_LE(current_phase
, READ_SYNC
);
231 std::string
phase_key(kFailurePhase
[current_phase
]);
232 std::string phase_error_string
;
233 if (!GetValueForKeyInQuery(request_
->url(), phase_key
, &phase_error_string
))
237 if (!base::StringToInt(phase_error_string
, &net_error
))
240 if (net_error
!= net::ERR_IO_PENDING
&&
241 (current_phase
== START
|| current_phase
== READ_SYNC
)) {
242 NotifyDone(net::URLRequestStatus(net::URLRequestStatus::FAILED
, net_error
));
246 SetStatus(net::URLRequestStatus(net::URLRequestStatus::IO_PENDING
, 0));
248 if (current_phase
!= READ_ASYNC
)
251 base::MessageLoopProxy::current()->PostTask(
254 &URLRequestMockHTTPJob::NotifyDone
,
255 weak_ptr_factory_
.GetWeakPtr(),
256 net::URLRequestStatus(net::URLRequestStatus::FAILED
, net_error
)));
261 // Private const version.
262 void URLRequestMockHTTPJob::GetResponseInfoConst(
263 net::HttpResponseInfo
* info
) const {
264 info
->headers
= new net::HttpResponseHeaders(raw_headers_
);
267 bool URLRequestMockHTTPJob::GetMimeType(std::string
* mime_type
) const {
268 net::HttpResponseInfo info
;
269 GetResponseInfoConst(&info
);
270 return info
.headers
.get() && info
.headers
->GetMimeType(mime_type
);
273 int URLRequestMockHTTPJob::GetResponseCode() const {
274 net::HttpResponseInfo info
;
275 GetResponseInfoConst(&info
);
276 // If we have headers, get the response code from them.
277 if (info
.headers
.get())
278 return info
.headers
->response_code();
279 return net::URLRequestJob::GetResponseCode();
282 bool URLRequestMockHTTPJob::GetCharset(std::string
* charset
) {
283 net::HttpResponseInfo info
;
284 GetResponseInfo(&info
);
285 return info
.headers
.get() && info
.headers
->GetCharset(charset
);