1 // Copyright 2013 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 "components/component_updater/test/url_request_post_interceptor.h"
7 #include "base/files/file_util.h"
8 #include "base/macros.h"
9 #include "base/memory/scoped_ptr.h"
10 #include "base/strings/stringprintf.h"
11 #include "components/component_updater/test/test_configurator.h"
12 #include "net/base/upload_bytes_element_reader.h"
13 #include "net/url_request/url_request.h"
14 #include "net/url_request/url_request_filter.h"
15 #include "net/url_request/url_request_interceptor.h"
16 #include "net/url_request/url_request_simple_job.h"
17 #include "net/url_request/url_request_test_util.h"
19 namespace component_updater {
21 // Returns a canned response.
22 class URLRequestMockJob : public net::URLRequestSimpleJob {
24 URLRequestMockJob(net::URLRequest* request,
25 net::NetworkDelegate* network_delegate,
27 const std::string& response_body)
28 : net::URLRequestSimpleJob(request, network_delegate),
29 response_code_(response_code),
30 response_body_(response_body) {}
33 virtual int GetResponseCode() const OVERRIDE { return response_code_; }
35 virtual int GetData(std::string* mime_type,
38 const net::CompletionCallback& callback) const OVERRIDE {
39 mime_type->assign("text/plain");
40 charset->assign("US-ASCII");
41 data->assign(response_body_);
46 virtual ~URLRequestMockJob() {}
49 std::string response_body_;
50 DISALLOW_COPY_AND_ASSIGN(URLRequestMockJob);
53 URLRequestPostInterceptor::URLRequestPostInterceptor(
55 const scoped_refptr<base::SequencedTaskRunner>& io_task_runner)
56 : url_(url), io_task_runner_(io_task_runner), hit_count_(0) {
59 URLRequestPostInterceptor::~URLRequestPostInterceptor() {
60 DCHECK(io_task_runner_->RunsTasksOnCurrentThread());
64 void URLRequestPostInterceptor::ClearExpectations() {
65 while (!expectations_.empty()) {
66 Expectation expectation(expectations_.front());
67 delete expectation.first;
72 GURL URLRequestPostInterceptor::GetUrl() const {
76 bool URLRequestPostInterceptor::ExpectRequest(
77 class RequestMatcher* request_matcher) {
78 expectations_.push(std::make_pair(request_matcher,
79 ExpectationResponse(kResponseCode200, "")));
83 bool URLRequestPostInterceptor::ExpectRequest(
84 class RequestMatcher* request_matcher,
87 std::make_pair(request_matcher, ExpectationResponse(response_code, "")));
91 bool URLRequestPostInterceptor::ExpectRequest(
92 class RequestMatcher* request_matcher,
93 const base::FilePath& filepath) {
95 if (filepath.empty() || !base::ReadFileToString(filepath, &response))
98 expectations_.push(std::make_pair(
99 request_matcher, ExpectationResponse(kResponseCode200, response)));
103 int URLRequestPostInterceptor::GetHitCount() const {
104 base::AutoLock auto_lock(interceptor_lock_);
108 int URLRequestPostInterceptor::GetCount() const {
109 base::AutoLock auto_lock(interceptor_lock_);
110 return static_cast<int>(requests_.size());
113 std::vector<std::string> URLRequestPostInterceptor::GetRequests() const {
114 base::AutoLock auto_lock(interceptor_lock_);
118 std::string URLRequestPostInterceptor::GetRequestsAsString() const {
119 std::vector<std::string> requests(GetRequests());
121 std::string s = "Requests are:";
124 for (std::vector<std::string>::const_iterator it = requests.begin();
125 it != requests.end();
127 s.append(base::StringPrintf("\n (%d): %s", ++i, it->c_str()));
133 void URLRequestPostInterceptor::Reset() {
134 base::AutoLock auto_lock(interceptor_lock_);
140 class URLRequestPostInterceptor::Delegate : public net::URLRequestInterceptor {
142 Delegate(const std::string& scheme,
143 const std::string& hostname,
144 const scoped_refptr<base::SequencedTaskRunner>& io_task_runner)
145 : scheme_(scheme), hostname_(hostname), io_task_runner_(io_task_runner) {}
148 DCHECK(io_task_runner_->RunsTasksOnCurrentThread());
149 net::URLRequestFilter::GetInstance()->AddHostnameInterceptor(
150 scheme_, hostname_, scoped_ptr<net::URLRequestInterceptor>(this));
154 DCHECK(io_task_runner_->RunsTasksOnCurrentThread());
155 for (InterceptorMap::iterator it = interceptors_.begin();
156 it != interceptors_.end();
159 net::URLRequestFilter::GetInstance()->RemoveHostnameHandler(scheme_,
163 void OnCreateInterceptor(URLRequestPostInterceptor* interceptor) {
164 DCHECK(io_task_runner_->RunsTasksOnCurrentThread());
165 DCHECK(interceptors_.find(interceptor->GetUrl()) == interceptors_.end());
167 interceptors_.insert(std::make_pair(interceptor->GetUrl(), interceptor));
171 virtual ~Delegate() {}
173 virtual net::URLRequestJob* MaybeInterceptRequest(
174 net::URLRequest* request,
175 net::NetworkDelegate* network_delegate) const OVERRIDE {
176 DCHECK(io_task_runner_->RunsTasksOnCurrentThread());
178 // Only intercepts POST.
179 if (!request->has_upload())
182 GURL url = request->url();
183 if (url.has_query()) {
184 GURL::Replacements replacements;
185 replacements.ClearQuery();
186 url = url.ReplaceComponents(replacements);
189 InterceptorMap::const_iterator it(interceptors_.find(url));
190 if (it == interceptors_.end())
193 // There is an interceptor hooked up for this url. Read the request body,
194 // check the existing expectations, and handle the matching case by
195 // popping the expectation off the queue, counting the match, and
196 // returning a mock object to serve the canned response.
197 URLRequestPostInterceptor* interceptor(it->second);
199 const net::UploadDataStream* stream = request->get_upload();
200 const net::UploadBytesElementReader* reader =
201 stream->element_readers()[0]->AsBytesReader();
202 const int size = reader->length();
203 scoped_refptr<net::IOBuffer> buffer(new net::IOBuffer(size));
204 const std::string request_body(reader->bytes());
207 base::AutoLock auto_lock(interceptor->interceptor_lock_);
208 interceptor->requests_.push_back(request_body);
209 if (interceptor->expectations_.empty())
211 const URLRequestPostInterceptor::Expectation& expectation(
212 interceptor->expectations_.front());
213 if (expectation.first->Match(request_body)) {
214 const int response_code(expectation.second.response_code);
215 const std::string response_body(expectation.second.response_body);
216 delete expectation.first;
217 interceptor->expectations_.pop();
218 ++interceptor->hit_count_;
220 return new URLRequestMockJob(
221 request, network_delegate, response_code, response_body);
228 typedef std::map<GURL, URLRequestPostInterceptor*> InterceptorMap;
229 InterceptorMap interceptors_;
231 const std::string scheme_;
232 const std::string hostname_;
233 scoped_refptr<base::SequencedTaskRunner> io_task_runner_;
235 DISALLOW_COPY_AND_ASSIGN(Delegate);
238 URLRequestPostInterceptorFactory::URLRequestPostInterceptorFactory(
239 const std::string& scheme,
240 const std::string& hostname,
241 const scoped_refptr<base::SequencedTaskRunner>& io_task_runner)
244 io_task_runner_(io_task_runner),
245 delegate_(new URLRequestPostInterceptor::Delegate(scheme,
248 io_task_runner_->PostTask(
250 base::Bind(&URLRequestPostInterceptor::Delegate::Register,
251 base::Unretained(delegate_)));
254 URLRequestPostInterceptorFactory::~URLRequestPostInterceptorFactory() {
255 io_task_runner_->PostTask(
257 base::Bind(&URLRequestPostInterceptor::Delegate::Unregister,
258 base::Unretained(delegate_)));
261 URLRequestPostInterceptor* URLRequestPostInterceptorFactory::CreateInterceptor(
262 const base::FilePath& filepath) {
264 base::StringPrintf("%s://%s", scheme_.c_str(), hostname_.c_str()));
265 GURL absolute_url(base_url.Resolve(filepath.MaybeAsASCII()));
266 URLRequestPostInterceptor* interceptor(
267 new URLRequestPostInterceptor(absolute_url, io_task_runner_));
268 bool res = io_task_runner_->PostTask(
270 base::Bind(&URLRequestPostInterceptor::Delegate::OnCreateInterceptor,
271 base::Unretained(delegate_),
272 base::Unretained(interceptor)));
281 bool PartialMatch::Match(const std::string& actual) const {
282 return actual.find(expected_) != std::string::npos;
285 InterceptorFactory::InterceptorFactory(
286 const scoped_refptr<base::SequencedTaskRunner>& io_task_runner)
287 : URLRequestPostInterceptorFactory(POST_INTERCEPT_SCHEME,
288 POST_INTERCEPT_HOSTNAME,
292 InterceptorFactory::~InterceptorFactory() {
295 URLRequestPostInterceptor* InterceptorFactory::CreateInterceptor() {
296 return CreateInterceptorForPath(POST_INTERCEPT_PATH);
299 URLRequestPostInterceptor* InterceptorFactory::CreateInterceptorForPath(
300 const char* url_path) {
301 return URLRequestPostInterceptorFactory::CreateInterceptor(
302 base::FilePath::FromUTF8Unsafe(url_path));
305 } // namespace component_updater