Commit 98d8fe93 authored by sergeyu's avatar sergeyu Committed by Commit bot

Cleanup Fake* classes in remoting/protocol

1. Renamed FakeSocket to FakeStreamSocket and FakeUdpSocket to
   FakeDatagramSocket,
2. Added factories for both stream and datagram fake
   sockets,
3. Move fake sockets to separate files out of fake_session.h

BUG=402993

Review URL: https://codereview.chromium.org/580243003

Cr-Commit-Position: refs/heads/master@{#296270}
parent 8a610264
...@@ -15,7 +15,7 @@ ...@@ -15,7 +15,7 @@
#include "remoting/base/rsa_key_pair.h" #include "remoting/base/rsa_key_pair.h"
#include "remoting/protocol/authenticator.h" #include "remoting/protocol/authenticator.h"
#include "remoting/protocol/channel_authenticator.h" #include "remoting/protocol/channel_authenticator.h"
#include "remoting/protocol/fake_session.h" #include "remoting/protocol/fake_stream_socket.h"
#include "testing/gtest/include/gtest/gtest.h" #include "testing/gtest/include/gtest/gtest.h"
#include "third_party/webrtc/libjingle/xmllite/xmlelement.h" #include "third_party/webrtc/libjingle/xmllite/xmlelement.h"
...@@ -111,8 +111,8 @@ void AuthenticatorTestBase::ContinueAuthExchangeWith(Authenticator* sender, ...@@ -111,8 +111,8 @@ void AuthenticatorTestBase::ContinueAuthExchangeWith(Authenticator* sender,
} }
void AuthenticatorTestBase::RunChannelAuth(bool expected_fail) { void AuthenticatorTestBase::RunChannelAuth(bool expected_fail) {
client_fake_socket_.reset(new FakeSocket()); client_fake_socket_.reset(new FakeStreamSocket());
host_fake_socket_.reset(new FakeSocket()); host_fake_socket_.reset(new FakeStreamSocket());
client_fake_socket_->PairWith(host_fake_socket_.get()); client_fake_socket_->PairWith(host_fake_socket_.get());
client_auth_->SecureAndAuthenticate( client_auth_->SecureAndAuthenticate(
......
...@@ -24,7 +24,7 @@ namespace protocol { ...@@ -24,7 +24,7 @@ namespace protocol {
class Authenticator; class Authenticator;
class ChannelAuthenticator; class ChannelAuthenticator;
class FakeSocket; class FakeStreamSocket;
class AuthenticatorTestBase : public testing::Test { class AuthenticatorTestBase : public testing::Test {
public: public:
...@@ -60,8 +60,8 @@ class AuthenticatorTestBase : public testing::Test { ...@@ -60,8 +60,8 @@ class AuthenticatorTestBase : public testing::Test {
std::string host_cert_; std::string host_cert_;
scoped_ptr<Authenticator> host_; scoped_ptr<Authenticator> host_;
scoped_ptr<Authenticator> client_; scoped_ptr<Authenticator> client_;
scoped_ptr<FakeSocket> client_fake_socket_; scoped_ptr<FakeStreamSocket> client_fake_socket_;
scoped_ptr<FakeSocket> host_fake_socket_; scoped_ptr<FakeStreamSocket> host_fake_socket_;
scoped_ptr<ChannelAuthenticator> client_auth_; scoped_ptr<ChannelAuthenticator> client_auth_;
scoped_ptr<ChannelAuthenticator> host_auth_; scoped_ptr<ChannelAuthenticator> host_auth_;
MockChannelDoneCallback client_callback_; MockChannelDoneCallback client_callback_;
......
...@@ -48,7 +48,7 @@ class BufferedSocketWriterTest : public testing::Test { ...@@ -48,7 +48,7 @@ class BufferedSocketWriterTest : public testing::Test {
protected: protected:
virtual void SetUp() OVERRIDE { virtual void SetUp() OVERRIDE {
socket_.reset(new FakeSocket()); socket_.reset(new FakeStreamSocket());
writer_.reset(new BufferedSocketWriter()); writer_.reset(new BufferedSocketWriter());
writer_->Init(socket_.get(), base::Bind( writer_->Init(socket_.get(), base::Bind(
&BufferedSocketWriterTest::OnWriteFailed, base::Unretained(this))); &BufferedSocketWriterTest::OnWriteFailed, base::Unretained(this)));
...@@ -98,7 +98,7 @@ class BufferedSocketWriterTest : public testing::Test { ...@@ -98,7 +98,7 @@ class BufferedSocketWriterTest : public testing::Test {
} }
base::MessageLoop message_loop_; base::MessageLoop message_loop_;
scoped_ptr<FakeSocket> socket_; scoped_ptr<FakeStreamSocket> socket_;
scoped_ptr<BufferedSocketWriter> writer_; scoped_ptr<BufferedSocketWriter> writer_;
scoped_refptr<net::IOBufferWithSize> test_buffer_; scoped_refptr<net::IOBufferWithSize> test_buffer_;
scoped_refptr<net::IOBufferWithSize> test_buffer_2_; scoped_refptr<net::IOBufferWithSize> test_buffer_2_;
......
...@@ -72,18 +72,21 @@ class ChannelMultiplexerTest : public testing::Test { ...@@ -72,18 +72,21 @@ class ChannelMultiplexerTest : public testing::Test {
protected: protected:
virtual void SetUp() OVERRIDE { virtual void SetUp() OVERRIDE {
// Create pair of multiplexers and connect them to each other. // Create pair of multiplexers and connect them to each other.
host_mux_.reset(new ChannelMultiplexer(&host_session_, kMuxChannelName)); host_mux_.reset(new ChannelMultiplexer(
client_mux_.reset(new ChannelMultiplexer(&client_session_, host_session_.GetTransportChannelFactory(), kMuxChannelName));
kMuxChannelName)); client_mux_.reset(new ChannelMultiplexer(
client_session_.GetTransportChannelFactory(), kMuxChannelName));
} }
// Connect sockets to each other. Must be called after we've created at least // Connect sockets to each other. Must be called after we've created at least
// one channel with each multiplexer. // one channel with each multiplexer.
void ConnectSockets() { void ConnectSockets() {
FakeSocket* host_socket = FakeStreamSocket* host_socket =
host_session_.GetStreamChannel(ChannelMultiplexer::kMuxChannelName); host_session_.fake_channel_factory().GetFakeChannel(
FakeSocket* client_socket = ChannelMultiplexer::kMuxChannelName);
client_session_.GetStreamChannel(ChannelMultiplexer::kMuxChannelName); FakeStreamSocket* client_socket =
client_session_.fake_channel_factory().GetFakeChannel(
ChannelMultiplexer::kMuxChannelName);
host_socket->PairWith(client_socket); host_socket->PairWith(client_socket);
// Make writes asynchronous in one direction. // Make writes asynchronous in one direction.
...@@ -242,9 +245,9 @@ TEST_F(ChannelMultiplexerTest, WriteFailSync) { ...@@ -242,9 +245,9 @@ TEST_F(ChannelMultiplexerTest, WriteFailSync) {
ConnectSockets(); ConnectSockets();
host_session_.GetStreamChannel(kMuxChannelName)-> host_session_.fake_channel_factory().GetFakeChannel(kMuxChannelName)->
set_next_write_error(net::ERR_FAILED); set_next_write_error(net::ERR_FAILED);
host_session_.GetStreamChannel(kMuxChannelName)-> host_session_.fake_channel_factory().GetFakeChannel(kMuxChannelName)->
set_async_write(false); set_async_write(false);
scoped_refptr<net::IOBufferWithSize> buf = CreateTestBuffer(100); scoped_refptr<net::IOBufferWithSize> buf = CreateTestBuffer(100);
...@@ -280,9 +283,9 @@ TEST_F(ChannelMultiplexerTest, WriteFailAsync) { ...@@ -280,9 +283,9 @@ TEST_F(ChannelMultiplexerTest, WriteFailAsync) {
ConnectSockets(); ConnectSockets();
host_session_.GetStreamChannel(kMuxChannelName)-> host_session_.fake_channel_factory().GetFakeChannel(kMuxChannelName)->
set_next_write_error(net::ERR_FAILED); set_next_write_error(net::ERR_FAILED);
host_session_.GetStreamChannel(kMuxChannelName)-> host_session_.fake_channel_factory().GetFakeChannel(kMuxChannelName)->
set_async_write(true); set_async_write(true);
scoped_refptr<net::IOBufferWithSize> buf = CreateTestBuffer(100); scoped_refptr<net::IOBufferWithSize> buf = CreateTestBuffer(100);
...@@ -314,9 +317,9 @@ TEST_F(ChannelMultiplexerTest, DeleteWhenFailed) { ...@@ -314,9 +317,9 @@ TEST_F(ChannelMultiplexerTest, DeleteWhenFailed) {
ConnectSockets(); ConnectSockets();
host_session_.GetStreamChannel(kMuxChannelName)-> host_session_.fake_channel_factory().GetFakeChannel(kMuxChannelName)->
set_next_write_error(net::ERR_FAILED); set_next_write_error(net::ERR_FAILED);
host_session_.GetStreamChannel(kMuxChannelName)-> host_session_.fake_channel_factory().GetFakeChannel(kMuxChannelName)->
set_async_write(true); set_async_write(true);
scoped_refptr<net::IOBufferWithSize> buf = CreateTestBuffer(100); scoped_refptr<net::IOBufferWithSize> buf = CreateTestBuffer(100);
...@@ -349,8 +352,8 @@ TEST_F(ChannelMultiplexerTest, DeleteWhenFailed) { ...@@ -349,8 +352,8 @@ TEST_F(ChannelMultiplexerTest, DeleteWhenFailed) {
} }
TEST_F(ChannelMultiplexerTest, SessionFail) { TEST_F(ChannelMultiplexerTest, SessionFail) {
host_session_.set_async_creation(true); host_session_.fake_channel_factory().set_asynchronous_create(true);
host_session_.set_error(AUTHENTICATION_FAILED); host_session_.fake_channel_factory().set_fail_create(true);
MockConnectCallback cb1; MockConnectCallback cb1;
MockConnectCallback cb2; MockConnectCallback cb2;
......
...@@ -69,9 +69,10 @@ TEST_F(ConnectionToClientTest, SendUpdateStream) { ...@@ -69,9 +69,10 @@ TEST_F(ConnectionToClientTest, SendUpdateStream) {
// Verify that something has been written. // Verify that something has been written.
// TODO(sergeyu): Verify that the correct data has been written. // TODO(sergeyu): Verify that the correct data has been written.
ASSERT_TRUE(session_->GetStreamChannel(kVideoChannelName)); ASSERT_TRUE(
EXPECT_GT(session_->GetStreamChannel(kVideoChannelName)-> session_->fake_channel_factory().GetFakeChannel(kVideoChannelName));
written_data().size(), 0u); EXPECT_FALSE(session_->fake_channel_factory()
.GetFakeChannel(kVideoChannelName)->written_data().empty());
// And then close the connection to ConnectionToClient. // And then close the connection to ConnectionToClient.
viewer_->Disconnect(); viewer_->Disconnect();
......
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "remoting/protocol/fake_datagram_socket.h"
#include "base/bind.h"
#include "base/single_thread_task_runner.h"
#include "base/thread_task_runner_handle.h"
#include "net/base/address_list.h"
#include "net/base/io_buffer.h"
#include "net/base/net_errors.h"
#include "net/base/net_util.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace remoting {
namespace protocol {
FakeDatagramSocket::FakeDatagramSocket()
: input_pos_(0),
task_runner_(base::ThreadTaskRunnerHandle::Get()),
weak_factory_(this) {
}
FakeDatagramSocket::~FakeDatagramSocket() {
EXPECT_TRUE(task_runner_->BelongsToCurrentThread());
}
void FakeDatagramSocket::AppendInputPacket(const std::string& data) {
EXPECT_TRUE(task_runner_->BelongsToCurrentThread());
input_packets_.push_back(data);
// Complete pending read if any.
if (!read_callback_.is_null()) {
DCHECK_EQ(input_pos_, static_cast<int>(input_packets_.size()) - 1);
int result = CopyReadData(read_buffer_.get(), read_buffer_size_);
read_buffer_ = NULL;
net::CompletionCallback callback = read_callback_;
read_callback_.Reset();
callback.Run(result);
}
}
void FakeDatagramSocket::PairWith(FakeDatagramSocket* peer_socket) {
EXPECT_TRUE(task_runner_->BelongsToCurrentThread());
peer_socket_ = peer_socket->GetWeakPtr();
peer_socket->peer_socket_ = GetWeakPtr();
}
base::WeakPtr<FakeDatagramSocket> FakeDatagramSocket::GetWeakPtr() {
return weak_factory_.GetWeakPtr();
}
int FakeDatagramSocket::Read(net::IOBuffer* buf, int buf_len,
const net::CompletionCallback& callback) {
EXPECT_TRUE(task_runner_->BelongsToCurrentThread());
if (input_pos_ < static_cast<int>(input_packets_.size())) {
return CopyReadData(buf, buf_len);
} else {
read_buffer_ = buf;
read_buffer_size_ = buf_len;
read_callback_ = callback;
return net::ERR_IO_PENDING;
}
}
int FakeDatagramSocket::Write(net::IOBuffer* buf, int buf_len,
const net::CompletionCallback& callback) {
EXPECT_TRUE(task_runner_->BelongsToCurrentThread());
written_packets_.push_back(std::string());
written_packets_.back().assign(buf->data(), buf->data() + buf_len);
if (peer_socket_.get()) {
task_runner_->PostTask(
FROM_HERE,
base::Bind(&FakeDatagramSocket::AppendInputPacket,
peer_socket_,
std::string(buf->data(), buf->data() + buf_len)));
}
return buf_len;
}
int FakeDatagramSocket::SetReceiveBufferSize(int32 size) {
NOTIMPLEMENTED();
return net::ERR_NOT_IMPLEMENTED;
}
int FakeDatagramSocket::SetSendBufferSize(int32 size) {
NOTIMPLEMENTED();
return net::ERR_NOT_IMPLEMENTED;
}
int FakeDatagramSocket::CopyReadData(net::IOBuffer* buf, int buf_len) {
int size = std::min(
buf_len, static_cast<int>(input_packets_[input_pos_].size()));
memcpy(buf->data(), &(*input_packets_[input_pos_].begin()), size);
++input_pos_;
return size;
}
FakeDatagramChannelFactory::FakeDatagramChannelFactory()
: task_runner_(base::ThreadTaskRunnerHandle::Get()),
asynchronous_create_(false),
fail_create_(false),
weak_factory_(this) {
}
FakeDatagramChannelFactory::~FakeDatagramChannelFactory() {
for (ChannelsMap::iterator it = channels_.begin(); it != channels_.end();
++it) {
EXPECT_TRUE(it->second == NULL);
}
}
void FakeDatagramChannelFactory::PairWith(
FakeDatagramChannelFactory* peer_factory) {
peer_factory_ = peer_factory->weak_factory_.GetWeakPtr();
peer_factory_->peer_factory_ = weak_factory_.GetWeakPtr();
}
FakeDatagramSocket* FakeDatagramChannelFactory::GetFakeChannel(
const std::string& name) {
return channels_[name].get();
}
void FakeDatagramChannelFactory::CreateChannel(
const std::string& name,
const ChannelCreatedCallback& callback) {
EXPECT_TRUE(channels_[name] == NULL);
scoped_ptr<FakeDatagramSocket> channel(new FakeDatagramSocket());
channels_[name] = channel->GetWeakPtr();
if (peer_factory_) {
FakeDatagramSocket* peer_socket = peer_factory_->GetFakeChannel(name);
if (peer_socket)
channel->PairWith(peer_socket);
}
if (fail_create_)
channel.reset();
if (asynchronous_create_) {
task_runner_->PostTask(
FROM_HERE,
base::Bind(&FakeDatagramChannelFactory::NotifyChannelCreated,
weak_factory_.GetWeakPtr(), base::Passed(&channel),
name, callback));
} else {
NotifyChannelCreated(channel.Pass(), name, callback);
}
}
void FakeDatagramChannelFactory::NotifyChannelCreated(
scoped_ptr<FakeDatagramSocket> owned_socket,
const std::string& name,
const ChannelCreatedCallback& callback) {
if (channels_.find(name) != channels_.end())
callback.Run(owned_socket.PassAs<net::Socket>());
}
void FakeDatagramChannelFactory::CancelChannelCreation(
const std::string& name) {
channels_.erase(name);
}
} // namespace protocol
} // namespace remoting
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef REMOTING_PROTOCOL_FAKE_DATAGRAM_SOCKET_H_
#define REMOTING_PROTOCOL_FAKE_DATAGRAM_SOCKET_H_
#include <map>
#include <string>
#include <vector>
#include "base/memory/scoped_ptr.h"
#include "base/memory/weak_ptr.h"
#include "net/base/completion_callback.h"
#include "net/socket/socket.h"
#include "remoting/protocol/datagram_channel_factory.h"
namespace base {
class SingleThreadTaskRunner;
}
namespace remoting {
namespace protocol {
// FakeDatagramSocket implement net::StreamSocket interface. All data written to
// FakeDatagramSocket is stored in a buffer returned by written_packets().
// Read() reads data from another buffer that can be set with
// AppendInputPacket(). Pending reads are supported, so if there is a pending
// read AppendInputPacket() calls the read callback.
//
// Two fake sockets can be connected to each other using the
// PairWith() method, e.g.: a->PairWith(b). After this all data
// written to |a| can be read from |b| and vice versa. Two connected
// sockets |a| and |b| must be created and used on the same thread.
class FakeDatagramSocket : public net::Socket {
public:
FakeDatagramSocket();
virtual ~FakeDatagramSocket();
const std::vector<std::string>& written_packets() const {
return written_packets_;
}
void AppendInputPacket(const std::string& data);
// Current position in the input in number of packets, i.e. number of finished
// Read() calls.
int input_pos() const { return input_pos_; }
// Pairs the socket with |peer_socket|. Deleting either of the paired sockets
// unpairs them.
void PairWith(FakeDatagramSocket* peer_socket);
base::WeakPtr<FakeDatagramSocket> GetWeakPtr();
// net::Socket implementation.
virtual int Read(net::IOBuffer* buf, int buf_len,
const net::CompletionCallback& callback) OVERRIDE;
virtual int Write(net::IOBuffer* buf, int buf_len,
const net::CompletionCallback& callback) OVERRIDE;
virtual int SetReceiveBufferSize(int32 size) OVERRIDE;
virtual int SetSendBufferSize(int32 size) OVERRIDE;
private:
int CopyReadData(net::IOBuffer* buf, int buf_len);
base::WeakPtr<FakeDatagramSocket> peer_socket_;
scoped_refptr<net::IOBuffer> read_buffer_;
int read_buffer_size_;
net::CompletionCallback read_callback_;
std::vector<std::string> written_packets_;
std::vector<std::string> input_packets_;
int input_pos_;
scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
base::WeakPtrFactory<FakeDatagramSocket> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(FakeDatagramSocket);
};
class FakeDatagramChannelFactory : public DatagramChannelFactory {
public:
FakeDatagramChannelFactory();
virtual ~FakeDatagramChannelFactory();
void set_asynchronous_create(bool asynchronous_create) {
asynchronous_create_ = asynchronous_create;
}
void set_fail_create(bool fail_create) { fail_create_ = fail_create; }
// Pair with |peer_factory|. Once paired the factory will be automatically
// pairing created sockets with the sockets with the same name from the peer
// factory.
void PairWith(FakeDatagramChannelFactory* peer_factory);
// Can be used to retrieve FakeDatagramSocket created by this factory, e.g. to
// feed data into it. The caller doesn't get ownership of the result. Returns
// NULL if the socket doesn't exist.
FakeDatagramSocket* GetFakeChannel(const std::string& name);
// DatagramChannelFactory interface.
virtual void CreateChannel(const std::string& name,
const ChannelCreatedCallback& callback) OVERRIDE;
virtual void CancelChannelCreation(const std::string& name) OVERRIDE;
private:
typedef std::map<std::string, base::WeakPtr<FakeDatagramSocket> > ChannelsMap;
void NotifyChannelCreated(scoped_ptr<FakeDatagramSocket> owned_socket,
const std::string& name,
const ChannelCreatedCallback& callback);
base::WeakPtr<FakeDatagramChannelFactory> peer_factory_;
scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
bool asynchronous_create_;
ChannelsMap channels_;
bool fail_create_;
base::WeakPtrFactory<FakeDatagramChannelFactory> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(FakeDatagramChannelFactory);
};
} // namespace protocol
} // namespace remoting
#endif // REMOTING_PROTOCOL_FAKE_DATAGRAM_SOCKET_H_
...@@ -4,298 +4,21 @@ ...@@ -4,298 +4,21 @@
#include "remoting/protocol/fake_session.h" #include "remoting/protocol/fake_session.h"
#include "base/bind.h"
#include "base/message_loop/message_loop.h"
#include "net/base/address_list.h"
#include "net/base/io_buffer.h"
#include "net/base/net_errors.h"
#include "net/base/net_util.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace remoting { namespace remoting {
namespace protocol { namespace protocol {
const char kTestJid[] = "host1@gmail.com/chromoting123"; const char kTestJid[] = "host1@gmail.com/chromoting123";
FakeSocket::FakeSocket()
: async_write_(false),
write_pending_(false),
write_limit_(0),
next_write_error_(net::OK),
next_read_error_(net::OK),
read_pending_(false),
read_buffer_size_(0),
input_pos_(0),
message_loop_(base::MessageLoop::current()),
weak_factory_(this) {
}
FakeSocket::~FakeSocket() {
EXPECT_EQ(message_loop_, base::MessageLoop::current());
}
void FakeSocket::AppendInputData(const std::vector<char>& data) {
EXPECT_EQ(message_loop_, base::MessageLoop::current());
input_data_.insert(input_data_.end(), data.begin(), data.end());
// Complete pending read if any.
if (read_pending_) {
read_pending_ = false;
int result = std::min(read_buffer_size_,
static_cast<int>(input_data_.size() - input_pos_));
CHECK(result > 0);
memcpy(read_buffer_->data(),
&(*input_data_.begin()) + input_pos_, result);
input_pos_ += result;
read_buffer_ = NULL;
read_callback_.Run(result);
}
}
void FakeSocket::PairWith(FakeSocket* peer_socket) {
EXPECT_EQ(message_loop_, base::MessageLoop::current());
peer_socket_ = peer_socket->weak_factory_.GetWeakPtr();
peer_socket->peer_socket_ = weak_factory_.GetWeakPtr();
}
int FakeSocket::Read(net::IOBuffer* buf, int buf_len,
const net::CompletionCallback& callback) {
EXPECT_EQ(message_loop_, base::MessageLoop::current());
if (next_read_error_ != net::OK) {
int r = next_read_error_;
next_read_error_ = net::OK;
return r;
}
if (input_pos_ < static_cast<int>(input_data_.size())) {
int result = std::min(buf_len,
static_cast<int>(input_data_.size()) - input_pos_);
memcpy(buf->data(), &(*input_data_.begin()) + input_pos_, result);
input_pos_ += result;
return result;
} else {
read_pending_ = true;
read_buffer_ = buf;
read_buffer_size_ = buf_len;
read_callback_ = callback;
return net::ERR_IO_PENDING;
}
}
int FakeSocket::Write(net::IOBuffer* buf, int buf_len,
const net::CompletionCallback& callback) {
EXPECT_EQ(message_loop_, base::MessageLoop::current());
EXPECT_FALSE(write_pending_);
if (write_limit_ > 0)
buf_len = std::min(write_limit_, buf_len);
if (async_write_) {
message_loop_->PostTask(FROM_HERE, base::Bind(
&FakeSocket::DoAsyncWrite, weak_factory_.GetWeakPtr(),
scoped_refptr<net::IOBuffer>(buf), buf_len, callback));
write_pending_ = true;
return net::ERR_IO_PENDING;
} else {
if (next_write_error_ != net::OK) {
int r = next_write_error_;
next_write_error_ = net::OK;
return r;
}
DoWrite(buf, buf_len);
return buf_len;
}
}
void FakeSocket::DoAsyncWrite(scoped_refptr<net::IOBuffer> buf, int buf_len,
const net::CompletionCallback& callback) {
write_pending_ = false;
if (next_write_error_ != net::OK) {
int r = next_write_error_;
next_write_error_ = net::OK;
callback.Run(r);
return;
}
DoWrite(buf.get(), buf_len);
callback.Run(buf_len);
}
void FakeSocket::DoWrite(net::IOBuffer* buf, int buf_len) {
written_data_.insert(written_data_.end(),
buf->data(), buf->data() + buf_len);
if (peer_socket_.get()) {
message_loop_->PostTask(
FROM_HERE,
base::Bind(&FakeSocket::AppendInputData,
peer_socket_,
std::vector<char>(buf->data(), buf->data() + buf_len)));
}
}
int FakeSocket::SetReceiveBufferSize(int32 size) {
NOTIMPLEMENTED();
return net::ERR_NOT_IMPLEMENTED;
}
int FakeSocket::SetSendBufferSize(int32 size) {
NOTIMPLEMENTED();
return net::ERR_NOT_IMPLEMENTED;
}
int FakeSocket::Connect(const net::CompletionCallback& callback) {
EXPECT_EQ(message_loop_, base::MessageLoop::current());
return net::OK;
}
void FakeSocket::Disconnect() {
peer_socket_.reset();
}
bool FakeSocket::IsConnected() const {
EXPECT_EQ(message_loop_, base::MessageLoop::current());
return true;
}
bool FakeSocket::IsConnectedAndIdle() const {
NOTIMPLEMENTED();
return false;
}
int FakeSocket::GetPeerAddress(net::IPEndPoint* address) const {
net::IPAddressNumber ip(net::kIPv4AddressSize);
*address = net::IPEndPoint(ip, 0);
return net::OK;
}
int FakeSocket::GetLocalAddress(net::IPEndPoint* address) const {
NOTIMPLEMENTED();
return net::ERR_NOT_IMPLEMENTED;
}
const net::BoundNetLog& FakeSocket::NetLog() const {
EXPECT_EQ(message_loop_, base::MessageLoop::current());
return net_log_;
}
void FakeSocket::SetSubresourceSpeculation() {
NOTIMPLEMENTED();
}
void FakeSocket::SetOmniboxSpeculation() {
NOTIMPLEMENTED();
}
bool FakeSocket::WasEverUsed() const {
NOTIMPLEMENTED();
return true;
}
bool FakeSocket::UsingTCPFastOpen() const {
NOTIMPLEMENTED();
return true;
}
bool FakeSocket::WasNpnNegotiated() const {
return false;
}
net::NextProto FakeSocket::GetNegotiatedProtocol() const {
NOTIMPLEMENTED();
return net::kProtoUnknown;
}
bool FakeSocket::GetSSLInfo(net::SSLInfo* ssl_info) {
return false;
}
FakeUdpSocket::FakeUdpSocket()
: read_pending_(false),
input_pos_(0),
message_loop_(base::MessageLoop::current()) {
}
FakeUdpSocket::~FakeUdpSocket() {
EXPECT_EQ(message_loop_, base::MessageLoop::current());
}
void FakeUdpSocket::AppendInputPacket(const char* data, int data_size) {
EXPECT_EQ(message_loop_, base::MessageLoop::current());
input_packets_.push_back(std::string());
input_packets_.back().assign(data, data + data_size);
// Complete pending read if any.
if (read_pending_) {
read_pending_ = false;
int result = std::min(data_size, read_buffer_size_);
memcpy(read_buffer_->data(), data, result);
input_pos_ = input_packets_.size();
read_callback_.Run(result);
read_buffer_ = NULL;
}
}
int FakeUdpSocket::Read(net::IOBuffer* buf, int buf_len,
const net::CompletionCallback& callback) {
EXPECT_EQ(message_loop_, base::MessageLoop::current());
if (input_pos_ < static_cast<int>(input_packets_.size())) {
int result = std::min(
buf_len, static_cast<int>(input_packets_[input_pos_].size()));
memcpy(buf->data(), &(*input_packets_[input_pos_].begin()), result);
++input_pos_;
return result;
} else {
read_pending_ = true;
read_buffer_ = buf;
read_buffer_size_ = buf_len;
read_callback_ = callback;
return net::ERR_IO_PENDING;
}
}
int FakeUdpSocket::Write(net::IOBuffer* buf, int buf_len,
const net::CompletionCallback& callback) {
EXPECT_EQ(message_loop_, base::MessageLoop::current());
written_packets_.push_back(std::string());
written_packets_.back().assign(buf->data(), buf->data() + buf_len);
return buf_len;
}
int FakeUdpSocket::SetReceiveBufferSize(int32 size) {
NOTIMPLEMENTED();
return net::ERR_NOT_IMPLEMENTED;
}
int FakeUdpSocket::SetSendBufferSize(int32 size) {
NOTIMPLEMENTED();
return net::ERR_NOT_IMPLEMENTED;
}
FakeSession::FakeSession() FakeSession::FakeSession()
: event_handler_(NULL), : event_handler_(NULL),
candidate_config_(CandidateSessionConfig::CreateDefault()), candidate_config_(CandidateSessionConfig::CreateDefault()),
config_(SessionConfig::ForTest()), config_(SessionConfig::ForTest()),
message_loop_(base::MessageLoop::current()),
async_creation_(false),
jid_(kTestJid), jid_(kTestJid),
error_(OK), error_(OK),
closed_(false), closed_(false) {
weak_factory_(this) {
} }
FakeSession::~FakeSession() { } FakeSession::~FakeSession() { }
FakeSocket* FakeSession::GetStreamChannel(const std::string& name) {
return stream_channels_[name];
}
FakeUdpSocket* FakeSession::GetDatagramChannel(const std::string& name) {
return datagram_channels_[name];
}
void FakeSession::SetEventHandler(EventHandler* event_handler) { void FakeSession::SetEventHandler(EventHandler* event_handler) {
event_handler_ = event_handler; event_handler_ = event_handler;
} }
...@@ -321,46 +44,16 @@ void FakeSession::set_config(const SessionConfig& config) { ...@@ -321,46 +44,16 @@ void FakeSession::set_config(const SessionConfig& config) {
} }
StreamChannelFactory* FakeSession::GetTransportChannelFactory() { StreamChannelFactory* FakeSession::GetTransportChannelFactory() {
return this; return &channel_factory_;
} }
StreamChannelFactory* FakeSession::GetMultiplexedChannelFactory() { StreamChannelFactory* FakeSession::GetMultiplexedChannelFactory() {
return this; return &channel_factory_;
} }
void FakeSession::Close() { void FakeSession::Close() {
closed_ = true; closed_ = true;
} }
void FakeSession::CreateChannel(const std::string& name,
const ChannelCreatedCallback& callback) {
scoped_ptr<FakeSocket> channel;
// If we are in the error state then we put NULL in the channels list, so that
// NotifyChannelCreated() still calls the callback.
if (error_ == OK)
channel.reset(new FakeSocket());
stream_channels_[name] = channel.release();
if (async_creation_) {
message_loop_->PostTask(FROM_HERE, base::Bind(
&FakeSession::NotifyChannelCreated, weak_factory_.GetWeakPtr(),
name, callback));
} else {
NotifyChannelCreated(name, callback);
}
}
void FakeSession::NotifyChannelCreated(
const std::string& name,
const ChannelCreatedCallback& callback) {
if (stream_channels_.find(name) != stream_channels_.end())
callback.Run(scoped_ptr<net::StreamSocket>(stream_channels_[name]));
}
void FakeSession::CancelChannelCreation(const std::string& name) {
stream_channels_.erase(name);
datagram_channels_.erase(name);
}
} // namespace protocol } // namespace protocol
} // namespace remoting } // namespace remoting
...@@ -10,161 +10,28 @@ ...@@ -10,161 +10,28 @@
#include <vector> #include <vector>
#include "base/memory/scoped_ptr.h" #include "base/memory/scoped_ptr.h"
#include "base/memory/weak_ptr.h" #include "remoting/protocol/fake_stream_socket.h"
#include "net/base/completion_callback.h"
#include "net/socket/socket.h"
#include "net/socket/stream_socket.h"
#include "remoting/protocol/session.h" #include "remoting/protocol/session.h"
#include "remoting/protocol/stream_channel_factory.h"
namespace base {
class MessageLoop;
}
namespace remoting { namespace remoting {
namespace protocol { namespace protocol {
extern const char kTestJid[]; extern const char kTestJid[];
// FakeSocket implement net::Socket interface for FakeConnection. All data // FakeSession is a dummy protocol::Session that uses FakeStreamSocket for all
// written to FakeSocket is stored in a buffer returned by written_data().
// Read() reads data from another buffer that can be set with AppendInputData().
// Pending reads are supported, so if there is a pending read AppendInputData()
// calls the read callback.
//
// Two fake sockets can be connected to each other using the
// PairWith() method, e.g.: a->PairWith(b). After this all data
// written to |a| can be read from |b| and vica versa. Two connected
// sockets |a| and |b| must be created and used on the same thread.
class FakeSocket : public net::StreamSocket {
public:
FakeSocket();
virtual ~FakeSocket();
const std::string& written_data() const { return written_data_; }
void set_write_limit(int write_limit) { write_limit_ = write_limit; }
void set_async_write(bool async_write) { async_write_ = async_write; }
void set_next_write_error(int error) { next_write_error_ = error; }
void set_next_read_error(int error) { next_read_error_ = error; }
void AppendInputData(const std::vector<char>& data);
void PairWith(FakeSocket* peer_socket);
int input_pos() const { return input_pos_; }
bool read_pending() const { return read_pending_; }
// net::Socket implementation.
virtual int Read(net::IOBuffer* buf, int buf_len,
const net::CompletionCallback& callback) OVERRIDE;
virtual int Write(net::IOBuffer* buf, int buf_len,
const net::CompletionCallback& callback) OVERRIDE;
virtual int SetReceiveBufferSize(int32 size) OVERRIDE;
virtual int SetSendBufferSize(int32 size) OVERRIDE;
// net::StreamSocket interface.
virtual int Connect(const net::CompletionCallback& callback) OVERRIDE;
virtual void Disconnect() OVERRIDE;
virtual bool IsConnected() const OVERRIDE;
virtual bool IsConnectedAndIdle() const OVERRIDE;
virtual int GetPeerAddress(net::IPEndPoint* address) const OVERRIDE;
virtual int GetLocalAddress(net::IPEndPoint* address) const OVERRIDE;
virtual const net::BoundNetLog& NetLog() const OVERRIDE;
virtual void SetSubresourceSpeculation() OVERRIDE;
virtual void SetOmniboxSpeculation() OVERRIDE;
virtual bool WasEverUsed() const OVERRIDE;
virtual bool UsingTCPFastOpen() const OVERRIDE;
virtual bool WasNpnNegotiated() const OVERRIDE;
virtual net::NextProto GetNegotiatedProtocol() const OVERRIDE;
virtual bool GetSSLInfo(net::SSLInfo* ssl_info) OVERRIDE;
private:
void DoAsyncWrite(scoped_refptr<net::IOBuffer> buf, int buf_len,
const net::CompletionCallback& callback);
void DoWrite(net::IOBuffer* buf, int buf_len);
bool async_write_;
bool write_pending_;
int write_limit_;
int next_write_error_;
int next_read_error_;
bool read_pending_;
scoped_refptr<net::IOBuffer> read_buffer_;
int read_buffer_size_;
net::CompletionCallback read_callback_;
base::WeakPtr<FakeSocket> peer_socket_;
std::string written_data_;
std::string input_data_;
int input_pos_;
net::BoundNetLog net_log_;
base::MessageLoop* message_loop_;
base::WeakPtrFactory<FakeSocket> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(FakeSocket);
};
// FakeUdpSocket is similar to FakeSocket but behaves as UDP socket. All written
// packets are stored separetely in written_packets(). AppendInputPacket() adds
// one packet that will be returned by Read().
class FakeUdpSocket : public net::Socket {
public:
FakeUdpSocket();
virtual ~FakeUdpSocket();
const std::vector<std::string>& written_packets() const {
return written_packets_;
}
void AppendInputPacket(const char* data, int data_size);
int input_pos() const { return input_pos_; }
// net::Socket implementation.
virtual int Read(net::IOBuffer* buf, int buf_len,
const net::CompletionCallback& callback) OVERRIDE;
virtual int Write(net::IOBuffer* buf, int buf_len,
const net::CompletionCallback& callback) OVERRIDE;
virtual int SetReceiveBufferSize(int32 size) OVERRIDE;
virtual int SetSendBufferSize(int32 size) OVERRIDE;
private:
bool read_pending_;
scoped_refptr<net::IOBuffer> read_buffer_;
int read_buffer_size_;
net::CompletionCallback read_callback_;
std::vector<std::string> written_packets_;
std::vector<std::string> input_packets_;
int input_pos_;
base::MessageLoop* message_loop_;
DISALLOW_COPY_AND_ASSIGN(FakeUdpSocket);
};
// FakeSession is a dummy protocol::Session that uses FakeSocket for all
// channels. // channels.
class FakeSession : public Session, class FakeSession : public Session {
public StreamChannelFactory {
public: public:
FakeSession(); FakeSession();
virtual ~FakeSession(); virtual ~FakeSession();
EventHandler* event_handler() { return event_handler_; } EventHandler* event_handler() { return event_handler_; }
void set_async_creation(bool async_creation) {
async_creation_ = async_creation;
}
void set_error(ErrorCode error) { error_ = error; } void set_error(ErrorCode error) { error_ = error; }
bool is_closed() const { return closed_; } bool is_closed() const { return closed_; }
FakeSocket* GetStreamChannel(const std::string& name); FakeStreamChannelFactory& fake_channel_factory() { return channel_factory_; }
FakeUdpSocket* GetDatagramChannel(const std::string& name);
// Session interface. // Session interface.
virtual void SetEventHandler(EventHandler* event_handler) OVERRIDE; virtual void SetEventHandler(EventHandler* event_handler) OVERRIDE;
...@@ -177,32 +44,18 @@ class FakeSession : public Session, ...@@ -177,32 +44,18 @@ class FakeSession : public Session,
virtual StreamChannelFactory* GetMultiplexedChannelFactory() OVERRIDE; virtual StreamChannelFactory* GetMultiplexedChannelFactory() OVERRIDE;
virtual void Close() OVERRIDE; virtual void Close() OVERRIDE;
// StreamChannelFactory interface.
virtual void CreateChannel(const std::string& name,
const ChannelCreatedCallback& callback) OVERRIDE;
virtual void CancelChannelCreation(const std::string& name) OVERRIDE;
public: public:
void NotifyChannelCreated(const std::string& name,
const ChannelCreatedCallback& callback);
EventHandler* event_handler_; EventHandler* event_handler_;
scoped_ptr<const CandidateSessionConfig> candidate_config_; scoped_ptr<const CandidateSessionConfig> candidate_config_;
SessionConfig config_; SessionConfig config_;
base::MessageLoop* message_loop_;
bool async_creation_; FakeStreamChannelFactory channel_factory_;
std::map<std::string, FakeSocket*> stream_channels_;
std::map<std::string, FakeUdpSocket*> datagram_channels_;
std::string jid_; std::string jid_;
ErrorCode error_; ErrorCode error_;
bool closed_; bool closed_;
base::WeakPtrFactory<FakeSession> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(FakeSession); DISALLOW_COPY_AND_ASSIGN(FakeSession);
}; };
......
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "remoting/protocol/fake_stream_socket.h"
#include "base/bind.h"
#include "base/single_thread_task_runner.h"
#include "base/thread_task_runner_handle.h"
#include "net/base/address_list.h"
#include "net/base/io_buffer.h"
#include "net/base/net_errors.h"
#include "net/base/net_util.h"
#include "testing/gtest/include/gtest/gtest.h"
namespace remoting {
namespace protocol {
FakeStreamSocket::FakeStreamSocket()
: async_write_(false),
write_pending_(false),
write_limit_(0),
next_write_error_(net::OK),
next_read_error_(net::OK),
read_buffer_size_(0),
input_pos_(0),
task_runner_(base::ThreadTaskRunnerHandle::Get()),
weak_factory_(this) {
}
FakeStreamSocket::~FakeStreamSocket() {
EXPECT_TRUE(task_runner_->BelongsToCurrentThread());
}
void FakeStreamSocket::AppendInputData(const std::string& data) {
EXPECT_TRUE(task_runner_->BelongsToCurrentThread());
input_data_.insert(input_data_.end(), data.begin(), data.end());
// Complete pending read if any.
if (!read_callback_.is_null()) {
int result = std::min(read_buffer_size_,
static_cast<int>(input_data_.size() - input_pos_));
EXPECT_GT(result, 0);
memcpy(read_buffer_->data(),
&(*input_data_.begin()) + input_pos_, result);
input_pos_ += result;
read_buffer_ = NULL;
net::CompletionCallback callback = read_callback_;
read_callback_.Reset();
callback.Run(result);
}
}
void FakeStreamSocket::PairWith(FakeStreamSocket* peer_socket) {
EXPECT_TRUE(task_runner_->BelongsToCurrentThread());
peer_socket_ = peer_socket->GetWeakPtr();
peer_socket->peer_socket_ = GetWeakPtr();
}
base::WeakPtr<FakeStreamSocket> FakeStreamSocket::GetWeakPtr() {
return weak_factory_.GetWeakPtr();
}
int FakeStreamSocket::Read(net::IOBuffer* buf, int buf_len,
const net::CompletionCallback& callback) {
EXPECT_TRUE(task_runner_->BelongsToCurrentThread());
if (next_read_error_ != net::OK) {
int r = next_read_error_;
next_read_error_ = net::OK;
return r;
}
if (input_pos_ < static_cast<int>(input_data_.size())) {
int result = std::min(buf_len,
static_cast<int>(input_data_.size()) - input_pos_);
memcpy(buf->data(), &(*input_data_.begin()) + input_pos_, result);
input_pos_ += result;
return result;
} else {
read_buffer_ = buf;
read_buffer_size_ = buf_len;
read_callback_ = callback;
return net::ERR_IO_PENDING;
}
}
int FakeStreamSocket::Write(net::IOBuffer* buf, int buf_len,
const net::CompletionCallback& callback) {
EXPECT_TRUE(task_runner_->BelongsToCurrentThread());
EXPECT_FALSE(write_pending_);
if (write_limit_ > 0)
buf_len = std::min(write_limit_, buf_len);
if (async_write_) {
task_runner_->PostTask(FROM_HERE, base::Bind(
&FakeStreamSocket::DoAsyncWrite, weak_factory_.GetWeakPtr(),
scoped_refptr<net::IOBuffer>(buf), buf_len, callback));
write_pending_ = true;
return net::ERR_IO_PENDING;
} else {
if (next_write_error_ != net::OK) {
int r = next_write_error_;
next_write_error_ = net::OK;
return r;
}
DoWrite(buf, buf_len);
return buf_len;
}
}
void FakeStreamSocket::DoAsyncWrite(scoped_refptr<net::IOBuffer> buf,
int buf_len,
const net::CompletionCallback& callback) {
write_pending_ = false;
if (next_write_error_ != net::OK) {
int r = next_write_error_;
next_write_error_ = net::OK;
callback.Run(r);
return;
}
DoWrite(buf.get(), buf_len);
callback.Run(buf_len);
}
void FakeStreamSocket::DoWrite(net::IOBuffer* buf, int buf_len) {
written_data_.insert(written_data_.end(),
buf->data(), buf->data() + buf_len);
if (peer_socket_.get()) {
task_runner_->PostTask(
FROM_HERE,
base::Bind(&FakeStreamSocket::AppendInputData,
peer_socket_,
std::string(buf->data(), buf->data() + buf_len)));
}
}
int FakeStreamSocket::SetReceiveBufferSize(int32 size) {
EXPECT_TRUE(task_runner_->BelongsToCurrentThread());
NOTIMPLEMENTED();
return net::ERR_NOT_IMPLEMENTED;
}
int FakeStreamSocket::SetSendBufferSize(int32 size) {
EXPECT_TRUE(task_runner_->BelongsToCurrentThread());
NOTIMPLEMENTED();
return net::ERR_NOT_IMPLEMENTED;
}
int FakeStreamSocket::Connect(const net::CompletionCallback& callback) {
EXPECT_TRUE(task_runner_->BelongsToCurrentThread());
return net::OK;
}
void FakeStreamSocket::Disconnect() {
EXPECT_TRUE(task_runner_->BelongsToCurrentThread());
peer_socket_.reset();
}
bool FakeStreamSocket::IsConnected() const {
EXPECT_TRUE(task_runner_->BelongsToCurrentThread());
return true;
}
bool FakeStreamSocket::IsConnectedAndIdle() const {
EXPECT_TRUE(task_runner_->BelongsToCurrentThread());
NOTIMPLEMENTED();
return false;
}
int FakeStreamSocket::GetPeerAddress(net::IPEndPoint* address) const {
EXPECT_TRUE(task_runner_->BelongsToCurrentThread());
net::IPAddressNumber ip(net::kIPv4AddressSize);
*address = net::IPEndPoint(ip, 0);
return net::OK;
}
int FakeStreamSocket::GetLocalAddress(net::IPEndPoint* address) const {
EXPECT_TRUE(task_runner_->BelongsToCurrentThread());
NOTIMPLEMENTED();
return net::ERR_NOT_IMPLEMENTED;
}
const net::BoundNetLog& FakeStreamSocket::NetLog() const {
EXPECT_TRUE(task_runner_->BelongsToCurrentThread());
return net_log_;
}
void FakeStreamSocket::SetSubresourceSpeculation() {
EXPECT_TRUE(task_runner_->BelongsToCurrentThread());
NOTIMPLEMENTED();
}
void FakeStreamSocket::SetOmniboxSpeculation() {
EXPECT_TRUE(task_runner_->BelongsToCurrentThread());
NOTIMPLEMENTED();
}
bool FakeStreamSocket::WasEverUsed() const {
EXPECT_TRUE(task_runner_->BelongsToCurrentThread());
NOTIMPLEMENTED();
return true;
}
bool FakeStreamSocket::UsingTCPFastOpen() const {
EXPECT_TRUE(task_runner_->BelongsToCurrentThread());
NOTIMPLEMENTED();
return true;
}
bool FakeStreamSocket::WasNpnNegotiated() const {
EXPECT_TRUE(task_runner_->BelongsToCurrentThread());
return false;
}
net::NextProto FakeStreamSocket::GetNegotiatedProtocol() const {
EXPECT_TRUE(task_runner_->BelongsToCurrentThread());
NOTIMPLEMENTED();
return net::kProtoUnknown;
}
bool FakeStreamSocket::GetSSLInfo(net::SSLInfo* ssl_info) {
EXPECT_TRUE(task_runner_->BelongsToCurrentThread());
return false;
}
FakeStreamChannelFactory::FakeStreamChannelFactory()
: task_runner_(base::ThreadTaskRunnerHandle::Get()),
asynchronous_create_(false),
fail_create_(false),
weak_factory_(this) {
}
FakeStreamChannelFactory::~FakeStreamChannelFactory() {}
FakeStreamSocket* FakeStreamChannelFactory::GetFakeChannel(
const std::string& name) {
return channels_[name].get();
}
void FakeStreamChannelFactory::CreateChannel(
const std::string& name,
const ChannelCreatedCallback& callback) {
scoped_ptr<FakeStreamSocket> channel(new FakeStreamSocket());
channels_[name] = channel->GetWeakPtr();
if (fail_create_)
channel.reset();
if (asynchronous_create_) {
task_runner_->PostTask(FROM_HERE, base::Bind(
&FakeStreamChannelFactory::NotifyChannelCreated,
weak_factory_.GetWeakPtr(), base::Passed(&channel), name, callback));
} else {
NotifyChannelCreated(channel.Pass(), name, callback);
}
}
void FakeStreamChannelFactory::NotifyChannelCreated(
scoped_ptr<FakeStreamSocket> owned_channel,
const std::string& name,
const ChannelCreatedCallback& callback) {
if (channels_.find(name) != channels_.end())
callback.Run(owned_channel.PassAs<net::StreamSocket>());
}
void FakeStreamChannelFactory::CancelChannelCreation(const std::string& name) {
channels_.erase(name);
}
} // namespace protocol
} // namespace remoting
// Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef REMOTING_PROTOCOL_FAKE_STREAM_SOCKET_H_
#define REMOTING_PROTOCOL_FAKE_STREAM_SOCKET_H_
#include <map>
#include <string>
#include "base/memory/scoped_ptr.h"
#include "base/memory/weak_ptr.h"
#include "net/base/completion_callback.h"
#include "net/socket/stream_socket.h"
#include "remoting/protocol/stream_channel_factory.h"
namespace base {
class SingleThreadTaskRunner;
}
namespace remoting {
namespace protocol {
// FakeStreamSocket implement net::StreamSocket interface. All data written to
// FakeStreamSocket is stored in a buffer returned by written_data(). Read()
// reads data from another buffer that can be set with AppendInputData().
// Pending reads are supported, so if there is a pending read AppendInputData()
// calls the read callback.
//
// Two fake sockets can be connected to each other using the
// PairWith() method, e.g.: a->PairWith(b). After this all data
// written to |a| can be read from |b| and vice versa. Two connected
// sockets |a| and |b| must be created and used on the same thread.
class FakeStreamSocket : public net::StreamSocket {
public:
FakeStreamSocket();
virtual ~FakeStreamSocket();
// Returns all data written to the socket.
const std::string& written_data() const { return written_data_; }
// Sets maximum number of bytes written by each Write() call.
void set_write_limit(int write_limit) { write_limit_ = write_limit; }
// Enables asynchronous Write().
void set_async_write(bool async_write) { async_write_ = async_write; }
// Set error codes for the next Read() and Write() calls. Once returned the
// values are automatically reset to net::OK .
void set_next_read_error(int error) { next_read_error_ = error; }
void set_next_write_error(int error) { next_write_error_ = error; }
// Appends |data| to the read buffer.
void AppendInputData(const std::string& data);
// Pairs the socket with |peer_socket|. Deleting either of the paired sockets
// unpairs them.
void PairWith(FakeStreamSocket* peer_socket);
// Current input position in bytes.
int input_pos() const { return input_pos_; }
// True if a Read() call is currently pending.
bool read_pending() const { return !read_callback_.is_null(); }
base::WeakPtr<FakeStreamSocket> GetWeakPtr();
// net::Socket implementation.
virtual int Read(net::IOBuffer* buf, int buf_len,
const net::CompletionCallback& callback) OVERRIDE;
virtual int Write(net::IOBuffer* buf, int buf_len,
const net::CompletionCallback& callback) OVERRIDE;
virtual int SetReceiveBufferSize(int32 size) OVERRIDE;
virtual int SetSendBufferSize(int32 size) OVERRIDE;
// net::StreamSocket interface.
virtual int Connect(const net::CompletionCallback& callback) OVERRIDE;
virtual void Disconnect() OVERRIDE;
virtual bool IsConnected() const OVERRIDE;
virtual bool IsConnectedAndIdle() const OVERRIDE;
virtual int GetPeerAddress(net::IPEndPoint* address) const OVERRIDE;
virtual int GetLocalAddress(net::IPEndPoint* address) const OVERRIDE;
virtual const net::BoundNetLog& NetLog() const OVERRIDE;
virtual void SetSubresourceSpeculation() OVERRIDE;
virtual void SetOmniboxSpeculation() OVERRIDE;
virtual bool WasEverUsed() const OVERRIDE;
virtual bool UsingTCPFastOpen() const OVERRIDE;
virtual bool WasNpnNegotiated() const OVERRIDE;
virtual net::NextProto GetNegotiatedProtocol() const OVERRIDE;
virtual bool GetSSLInfo(net::SSLInfo* ssl_info) OVERRIDE;
private:
void DoAsyncWrite(scoped_refptr<net::IOBuffer> buf, int buf_len,
const net::CompletionCallback& callback);
void DoWrite(net::IOBuffer* buf, int buf_len);
bool async_write_;
bool write_pending_;
int write_limit_;
int next_write_error_;
int next_read_error_;
scoped_refptr<net::IOBuffer> read_buffer_;
int read_buffer_size_;
net::CompletionCallback read_callback_;
base::WeakPtr<FakeStreamSocket> peer_socket_;
std::string written_data_;
std::string input_data_;
int input_pos_;
net::BoundNetLog net_log_;
scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
base::WeakPtrFactory<FakeStreamSocket> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(FakeStreamSocket);
};
// StreamChannelFactory that creates FakeStreamSocket.
class FakeStreamChannelFactory : public StreamChannelFactory {
public:
FakeStreamChannelFactory();
virtual ~FakeStreamChannelFactory();
void set_asynchronous_create(bool asynchronous_create) {
asynchronous_create_ = asynchronous_create;
}
void set_fail_create(bool fail_create) { fail_create_ = fail_create; }
FakeStreamSocket* GetFakeChannel(const std::string& name);
// ChannelFactory interface.
virtual void CreateChannel(const std::string& name,
const ChannelCreatedCallback& callback) OVERRIDE;
virtual void CancelChannelCreation(const std::string& name) OVERRIDE;
private:
void NotifyChannelCreated(scoped_ptr<FakeStreamSocket> owned_channel,
const std::string& name,
const ChannelCreatedCallback& callback);
scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
bool asynchronous_create_;
std::map<std::string, base::WeakPtr<FakeStreamSocket> > channels_;
bool fail_create_;
base::WeakPtrFactory<FakeStreamChannelFactory> weak_factory_;
DISALLOW_COPY_AND_ASSIGN(FakeStreamChannelFactory);
};
} // namespace protocol
} // namespace remoting
#endif // REMOTING_PROTOCOL_FAKE_STREAM_SOCKET_H_
...@@ -13,7 +13,7 @@ ...@@ -13,7 +13,7 @@
#include "base/synchronization/waitable_event.h" #include "base/synchronization/waitable_event.h"
#include "net/base/net_errors.h" #include "net/base/net_errors.h"
#include "net/socket/socket.h" #include "net/socket/socket.h"
#include "remoting/protocol/fake_session.h" #include "remoting/protocol/fake_stream_socket.h"
#include "remoting/protocol/message_reader.h" #include "remoting/protocol/message_reader.h"
#include "testing/gmock/include/gmock/gmock.h" #include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h" #include "testing/gtest/include/gtest/gtest.h"
...@@ -84,7 +84,7 @@ class MessageReaderTest : public testing::Test { ...@@ -84,7 +84,7 @@ class MessageReaderTest : public testing::Test {
std::string data = std::string(4, ' ') + message; std::string data = std::string(4, ' ') + message;
rtc::SetBE32(const_cast<char*>(data.data()), message.size()); rtc::SetBE32(const_cast<char*>(data.data()), message.size());
socket_.AppendInputData(std::vector<char>(data.begin(), data.end())); socket_.AppendInputData(data);
} }
bool CompareResult(CompoundBuffer* buffer, const std::string& expected) { bool CompareResult(CompoundBuffer* buffer, const std::string& expected) {
...@@ -101,7 +101,7 @@ class MessageReaderTest : public testing::Test { ...@@ -101,7 +101,7 @@ class MessageReaderTest : public testing::Test {
base::MessageLoop message_loop_; base::MessageLoop message_loop_;
scoped_ptr<MessageReader> reader_; scoped_ptr<MessageReader> reader_;
FakeSocket socket_; FakeStreamSocket socket_;
MockMessageReceivedCallback callback_; MockMessageReceivedCallback callback_;
std::vector<CompoundBuffer*> messages_; std::vector<CompoundBuffer*> messages_;
bool in_callback_; bool in_callback_;
......
...@@ -70,8 +70,8 @@ class SslHmacChannelAuthenticatorTest : public testing::Test { ...@@ -70,8 +70,8 @@ class SslHmacChannelAuthenticatorTest : public testing::Test {
} }
void RunChannelAuth(bool expected_fail) { void RunChannelAuth(bool expected_fail) {
client_fake_socket_.reset(new FakeSocket()); client_fake_socket_.reset(new FakeStreamSocket());
host_fake_socket_.reset(new FakeSocket()); host_fake_socket_.reset(new FakeStreamSocket());
client_fake_socket_->PairWith(host_fake_socket_.get()); client_fake_socket_->PairWith(host_fake_socket_.get());
client_auth_->SecureAndAuthenticate( client_auth_->SecureAndAuthenticate(
...@@ -131,8 +131,8 @@ class SslHmacChannelAuthenticatorTest : public testing::Test { ...@@ -131,8 +131,8 @@ class SslHmacChannelAuthenticatorTest : public testing::Test {
scoped_refptr<RsaKeyPair> key_pair_; scoped_refptr<RsaKeyPair> key_pair_;
std::string host_cert_; std::string host_cert_;
scoped_ptr<FakeSocket> client_fake_socket_; scoped_ptr<FakeStreamSocket> client_fake_socket_;
scoped_ptr<FakeSocket> host_fake_socket_; scoped_ptr<FakeStreamSocket> host_fake_socket_;
scoped_ptr<ChannelAuthenticator> client_auth_; scoped_ptr<ChannelAuthenticator> client_auth_;
scoped_ptr<ChannelAuthenticator> host_auth_; scoped_ptr<ChannelAuthenticator> host_auth_;
MockChannelDoneCallback client_callback_; MockChannelDoneCallback client_callback_;
......
...@@ -32,8 +32,12 @@ ...@@ -32,8 +32,12 @@
'host/policy_hack/mock_policy_callback.h', 'host/policy_hack/mock_policy_callback.h',
'protocol/fake_authenticator.cc', 'protocol/fake_authenticator.cc',
'protocol/fake_authenticator.h', 'protocol/fake_authenticator.h',
'protocol/fake_datagram_socket.cc',
'protocol/fake_datagram_socket.h',
'protocol/fake_session.cc', 'protocol/fake_session.cc',
'protocol/fake_session.h', 'protocol/fake_session.h',
'protocol/fake_stream_socket.cc',
'protocol/fake_stream_socket.h',
'protocol/protocol_mock_objects.cc', 'protocol/protocol_mock_objects.cc',
'protocol/protocol_mock_objects.h', 'protocol/protocol_mock_objects.h',
'signaling/fake_signal_strategy.cc', 'signaling/fake_signal_strategy.cc',
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment