1 // Copyright 2015 The Weave 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 <weave/test/fake_stream.h>
6
7 #include <base/bind.h>
8 #include <gtest/gtest.h>
9 #include <weave/provider/task_runner.h>
10
11 namespace weave {
12 namespace test {
13
FakeStream(provider::TaskRunner * task_runner)14 FakeStream::FakeStream(provider::TaskRunner* task_runner)
15 : task_runner_{task_runner} {}
FakeStream(provider::TaskRunner * task_runner,const std::string & read_data)16 FakeStream::FakeStream(provider::TaskRunner* task_runner,
17 const std::string& read_data)
18 : task_runner_{task_runner}, read_data_{read_data} {}
19
CancelPendingOperations()20 void FakeStream::CancelPendingOperations() {}
21
ExpectWritePacketString(base::TimeDelta,const std::string & data)22 void FakeStream::ExpectWritePacketString(base::TimeDelta,
23 const std::string& data) {
24 write_data_ += data;
25 }
26
AddReadPacketString(base::TimeDelta,const std::string & data)27 void FakeStream::AddReadPacketString(base::TimeDelta, const std::string& data) {
28 read_data_ += data;
29 }
30
Read(void * buffer,size_t size_to_read,const ReadCallback & callback)31 void FakeStream::Read(void* buffer,
32 size_t size_to_read,
33 const ReadCallback& callback) {
34 if (read_data_.empty()) {
35 task_runner_->PostDelayedTask(
36 FROM_HERE, base::Bind(&FakeStream::Read, base::Unretained(this), buffer,
37 size_to_read, callback),
38 base::TimeDelta::FromSeconds(0));
39 return;
40 }
41 size_t size = std::min(size_to_read, read_data_.size());
42 memcpy(buffer, read_data_.data(), size);
43 read_data_ = read_data_.substr(size);
44 task_runner_->PostDelayedTask(FROM_HERE, base::Bind(callback, size, nullptr),
45 base::TimeDelta::FromSeconds(0));
46 }
47
Write(const void * buffer,size_t size_to_write,const WriteCallback & callback)48 void FakeStream::Write(const void* buffer,
49 size_t size_to_write,
50 const WriteCallback& callback) {
51 size_t size = std::min(size_to_write, write_data_.size());
52 EXPECT_EQ(write_data_.substr(0, size),
53 std::string(reinterpret_cast<const char*>(buffer), size_to_write));
54 write_data_ = write_data_.substr(size);
55 task_runner_->PostDelayedTask(FROM_HERE, base::Bind(callback, nullptr),
56 base::TimeDelta::FromSeconds(0));
57 }
58
59 } // namespace test
60 } // namespace weave
61