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 "content/test/net/url_request_failed_job.h" 6 7 #include "base/bind.h" 8 #include "base/logging.h" 9 #include "base/message_loop/message_loop.h" 10 #include "base/strings/string_number_conversions.h" 11 #include "net/base/net_errors.h" 12 #include "net/url_request/url_request.h" 13 #include "net/url_request/url_request_filter.h" 14 15 namespace content { 16 namespace { 17 18 const char kMockHostname[] = "mock.failed.request"; 19 20 // Gets the numeric net error code from URL of the form: 21 // scheme://kMockHostname/error_code. The error code must be a valid 22 // net error code, and not net::OK or net::ERR_IO_PENDING. 23 int GetErrorCode(net::URLRequest* request) { 24 int net_error; 25 std::string path = request->url().path(); 26 if (path[0] == '/' && base::StringToInt(path.c_str() + 1, &net_error)) { 27 CHECK_LT(net_error, 0); 28 CHECK_NE(net_error, net::ERR_IO_PENDING); 29 return net_error; 30 } 31 NOTREACHED(); 32 return net::ERR_UNEXPECTED; 33 } 34 35 GURL GetMockUrl(const std::string& scheme, int net_error) { 36 CHECK_LT(net_error, 0); 37 CHECK_NE(net_error, net::ERR_IO_PENDING); 38 return GURL(scheme + "://" + kMockHostname + "/" + 39 base::IntToString(net_error)); 40 } 41 42 } // namespace 43 44 URLRequestFailedJob::URLRequestFailedJob(net::URLRequest* request, 45 net::NetworkDelegate* network_delegate, 46 int net_error) 47 : net::URLRequestJob(request, network_delegate), 48 net_error_(net_error), 49 weak_factory_(this) {} 50 51 URLRequestFailedJob::~URLRequestFailedJob() {} 52 53 void URLRequestFailedJob::Start() { 54 base::MessageLoop::current()->PostTask( 55 FROM_HERE, 56 base::Bind(&URLRequestFailedJob::StartAsync, weak_factory_.GetWeakPtr())); 57 } 58 59 // static 60 void URLRequestFailedJob::AddUrlHandler() { 61 // Add kMockHostname to net::URLRequestFilter for HTTP and HTTPS. 62 net::URLRequestFilter* filter = net::URLRequestFilter::GetInstance(); 63 filter->AddHostnameHandler("http", kMockHostname, 64 URLRequestFailedJob::Factory); 65 filter->AddHostnameHandler("https", kMockHostname, 66 URLRequestFailedJob::Factory); 67 } 68 69 // static 70 GURL URLRequestFailedJob::GetMockHttpUrl(int net_error) { 71 return GetMockUrl("http", net_error); 72 } 73 74 // static 75 GURL URLRequestFailedJob::GetMockHttpsUrl(int net_error) { 76 return GetMockUrl("https", net_error); 77 } 78 79 // static 80 net::URLRequestJob* URLRequestFailedJob::Factory( 81 net::URLRequest* request, 82 net::NetworkDelegate* network_delegate, 83 const std::string& scheme) { 84 return new URLRequestFailedJob( 85 request, network_delegate, GetErrorCode(request)); 86 } 87 88 void URLRequestFailedJob::StartAsync() { 89 NotifyStartError(net::URLRequestStatus(net::URLRequestStatus::FAILED, 90 net_error_)); 91 } 92 93 } // namespace content 94