1 // Copyright 2014 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 "mock_url_request_delegate.h" 6 7 #include "base/run_loop.h" 8 #include "net/base/io_buffer.h" 9 #include "testing/gtest/include/gtest/gtest.h" 10 11 namespace { 12 const int kBufferSize = 1024; 13 } 14 15 namespace content { 16 17 MockURLRequestDelegate::MockURLRequestDelegate() 18 : io_buffer_(new net::IOBuffer(kBufferSize)) { 19 } 20 21 MockURLRequestDelegate::~MockURLRequestDelegate() { 22 } 23 24 void MockURLRequestDelegate::OnResponseStarted(net::URLRequest* request) { 25 if (request->status().is_success()) { 26 EXPECT_TRUE(request->response_headers()); 27 ReadSome(request); 28 } else { 29 RequestComplete(); 30 } 31 } 32 33 void MockURLRequestDelegate::OnReadCompleted(net::URLRequest* request, 34 int bytes_read) { 35 if (bytes_read > 0) 36 ReceiveData(request, bytes_read); 37 else 38 RequestComplete(); 39 } 40 41 void MockURLRequestDelegate::ReadSome(net::URLRequest* request) { 42 if (!request->is_pending()) { 43 RequestComplete(); 44 return; 45 } 46 47 int bytes_read = 0; 48 if (!request->Read(io_buffer_.get(), kBufferSize, &bytes_read)) { 49 if (!request->status().is_io_pending()) 50 RequestComplete(); 51 return; 52 } 53 54 ReceiveData(request, bytes_read); 55 } 56 57 void MockURLRequestDelegate::ReceiveData(net::URLRequest* request, 58 int bytes_read) { 59 if (bytes_read) { 60 response_data_.append(io_buffer_->data(), 61 static_cast<size_t>(bytes_read)); 62 ReadSome(request); 63 } else { 64 RequestComplete(); 65 } 66 } 67 68 void MockURLRequestDelegate::RequestComplete() { 69 base::MessageLoop::current()->Quit(); 70 } 71 72 } // namespace 73