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.
4
5#include "chrome/browser/component_updater/test/url_request_post_interceptor.h"
6
7#include "content/public/test/test_browser_thread.h"
8#include "net/url_request/url_request.h"
9#include "net/url_request/url_request_filter.h"
10#include "net/url_request/url_request_test_util.h"
11
12using content::BrowserThread;
13
14URLRequestPostInterceptor::URLRequestPostInterceptor(
15    RequestCounter* counter) : delegate_(new Delegate(counter)) {
16  BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
17                          base::Bind(&Delegate::Register,
18                                     base::Unretained(delegate_)));
19}
20
21URLRequestPostInterceptor::~URLRequestPostInterceptor() {
22  BrowserThread::PostTask(BrowserThread::IO, FROM_HERE,
23                          base::Bind(&Delegate::Unregister,
24                                     base::Unretained(delegate_)));
25}
26
27URLRequestPostInterceptor::Delegate::Delegate(
28    RequestCounter* counter) : counter_(counter) {
29}
30
31void URLRequestPostInterceptor::Delegate::Register() {
32  net::URLRequestFilter::GetInstance()->AddHostnameProtocolHandler(
33      "http", "localhost2",
34      scoped_ptr<net::URLRequestJobFactory::ProtocolHandler>(this));
35}
36
37void URLRequestPostInterceptor::Delegate::Unregister() {
38  net::URLRequestFilter::GetInstance()->
39      RemoveHostnameHandler("http", "localhost2");
40}
41
42net::URLRequestJob* URLRequestPostInterceptor::Delegate::MaybeCreateJob(
43    net::URLRequest* request,
44    net::NetworkDelegate* network_delegate) const {
45  CHECK(BrowserThread::CurrentlyOn(BrowserThread::IO));
46  if (request->has_upload()) {
47    counter_->Trial(request);
48    return new URLRequestPingMockJob(request, network_delegate);
49  }
50  return NULL;
51}
52
53URLRequestPingMockJob::URLRequestPingMockJob(
54    net::URLRequest* request,
55    net::NetworkDelegate* network_delegate)
56    : net::URLRequestSimpleJob(request, network_delegate) {
57}
58
59int URLRequestPingMockJob::GetData(
60    std::string* mime_type,
61    std::string* charset,
62    std::string* data,
63    const net::CompletionCallback& callback) const {
64  mime_type->assign("text/plain");
65  charset->assign("US-ASCII");
66  data->assign("");  // There is no reason to have a response body.
67  return net::OK;
68}
69