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 "base/bind.h"
6#include "base/message_loop/message_loop.h"
7#include "base/run_loop.h"
8#include "base/strings/string_piece.h"
9#include "device/serial/async_waiter.h"
10#include "device/serial/data_sender.h"
11#include "device/serial/data_sink_receiver.h"
12#include "device/serial/data_stream.mojom.h"
13#include "mojo/public/cpp/bindings/interface_ptr.h"
14#include "testing/gtest/include/gtest/gtest.h"
15
16namespace device {
17
18class DataSinkTest : public testing::Test {
19 public:
20  enum Event {
21    EVENT_NONE,
22    EVENT_READ_BUFFER_READY,
23    EVENT_CANCEL_RECEIVED,
24    EVENT_SEND_SUCCESS,
25    EVENT_SEND_ERROR,
26    EVENT_CANCEL_COMPLETE,
27    EVENT_ERROR,
28  };
29
30  DataSinkTest()
31      : bytes_sent_(0),
32        send_error_(0),
33        has_send_error_(false),
34        cancel_error_(0),
35        seen_connection_error_(false),
36        expected_event_(EVENT_NONE) {}
37
38  virtual void SetUp() OVERRIDE {
39    message_loop_.reset(new base::MessageLoop);
40    mojo::InterfacePtr<serial::DataSink> sink_handle;
41    sink_receiver_ = mojo::WeakBindToProxy(
42        new DataSinkReceiver(
43            base::Bind(&DataSinkTest::OnDataToRead, base::Unretained(this)),
44            base::Bind(&DataSinkTest::OnCancel, base::Unretained(this)),
45            base::Bind(&DataSinkTest::OnError, base::Unretained(this))),
46        &sink_handle);
47    sender_.reset(new DataSender(sink_handle.Pass(), kBufferSize, kFatalError));
48  }
49
50  virtual void TearDown() OVERRIDE {
51    read_buffer_.reset();
52    message_loop_.reset();
53    if (sink_receiver_.get())
54      EXPECT_TRUE(sink_receiver_->HasOneRef());
55  }
56
57  void WaitForEvent(Event event) {
58    expected_event_ = event;
59    base::RunLoop run_loop;
60    stop_run_loop_ = run_loop.QuitClosure();
61    run_loop.Run();
62  }
63
64  void EventReceived(Event event) {
65    if (event == expected_event_ && !stop_run_loop_.is_null())
66      stop_run_loop_.Run();
67  }
68
69  void OnError() {
70    seen_connection_error_ = true;
71    EventReceived(EVENT_ERROR);
72  }
73
74  void ExpectDataAndReadAll(const base::StringPiece& expected_data) {
75    ExpectData(expected_data, static_cast<uint32_t>(expected_data.size()), 0);
76  }
77
78  void ExpectData(const base::StringPiece& expected_data,
79                  uint32_t bytes_to_read,
80                  int32_t error) {
81    DCHECK(bytes_to_read <= static_cast<uint32_t>(expected_data.size()));
82    std::string data;
83    while (data.size() < static_cast<size_t>(expected_data.size())) {
84      if (!read_buffer_)
85        WaitForEvent(EVENT_READ_BUFFER_READY);
86      ASSERT_TRUE(read_buffer_);
87      data.append(read_buffer_->GetData(), read_buffer_->GetSize());
88      if (bytes_to_read <= read_buffer_->GetSize()) {
89        if (error)
90          read_buffer_->DoneWithError(bytes_to_read, error);
91        else
92          read_buffer_->Done(bytes_to_read);
93        read_buffer_.reset();
94        break;
95      } else {
96        bytes_to_read -= read_buffer_->GetSize();
97        read_buffer_->Done(read_buffer_->GetSize());
98        read_buffer_.reset();
99      }
100    }
101    // If we terminate early, we may not see all of the data. In that case,
102    // check that the part we saw matches what we expected.
103    if (static_cast<uint32_t>(data.size()) <
104            static_cast<uint32_t>(expected_data.size()) &&
105        data.size() >= bytes_to_read) {
106      EXPECT_EQ(expected_data.substr(0, data.size()), data);
107      return;
108    }
109    EXPECT_EQ(expected_data, data);
110  }
111
112  void ExpectSendSuccess(uint32_t expected_bytes_sent) {
113    bytes_sent_ = 0;
114    WaitForEvent(EVENT_SEND_SUCCESS);
115    EXPECT_EQ(expected_bytes_sent, bytes_sent_);
116    EXPECT_FALSE(has_send_error_);
117  }
118
119  void ExpectSendError(uint32_t expected_bytes_sent, int32_t expected_error) {
120    bytes_sent_ = 0;
121    has_send_error_ = 0;
122    send_error_ = 0;
123    WaitForEvent(EVENT_SEND_ERROR);
124    EXPECT_EQ(expected_bytes_sent, bytes_sent_);
125    EXPECT_TRUE(has_send_error_);
126    EXPECT_EQ(expected_error, send_error_);
127  }
128
129  void ExpectCancel(int32_t expected_error) {
130    cancel_error_ = 0;
131    WaitForEvent(EVENT_CANCEL_RECEIVED);
132    EXPECT_EQ(expected_error, cancel_error_);
133  }
134
135  void ExpectCancelResult() { WaitForEvent(EVENT_CANCEL_COMPLETE); }
136
137  bool Send(const base::StringPiece& data) {
138    return sender_->Send(
139        data,
140        base::Bind(&DataSinkTest::OnDataSent, base::Unretained(this)),
141        base::Bind(&DataSinkTest::OnSendError, base::Unretained(this)));
142  }
143
144  void OnDataSent(uint32_t bytes_sent) {
145    bytes_sent_ = bytes_sent;
146    has_send_error_ = false;
147    EventReceived(EVENT_SEND_SUCCESS);
148  }
149
150  void OnSendError(uint32_t bytes_sent, int32_t error) {
151    bytes_sent_ = bytes_sent;
152    send_error_ = error;
153    has_send_error_ = true;
154    EventReceived(EVENT_SEND_ERROR);
155  }
156
157  void OnDataToRead(scoped_ptr<ReadOnlyBuffer> buffer) {
158    read_buffer_ = buffer.Pass();
159    read_buffer_contents_ =
160        std::string(read_buffer_->GetData(), read_buffer_->GetSize());
161    EventReceived(EVENT_READ_BUFFER_READY);
162  }
163
164  bool Cancel(int32_t error) {
165    return sender_->Cancel(
166        error, base::Bind(&DataSinkTest::CancelAck, base::Unretained(this)));
167  }
168
169  void CancelAck() { EventReceived(EVENT_CANCEL_COMPLETE); }
170
171  void OnCancel(int32_t error) {
172    cancel_error_ = error;
173    EventReceived(EVENT_CANCEL_RECEIVED);
174  }
175
176 protected:
177  static const int32_t kFatalError;
178  static const uint32_t kBufferSize;
179  scoped_ptr<base::MessageLoop> message_loop_;
180  base::Closure stop_run_loop_;
181
182  scoped_refptr<DataSinkReceiver> sink_receiver_;
183  scoped_ptr<DataSender> sender_;
184
185  uint32_t bytes_sent_;
186  int32_t send_error_;
187  bool has_send_error_;
188  int32_t cancel_error_;
189  scoped_ptr<ReadOnlyBuffer> read_buffer_;
190  std::string read_buffer_contents_;
191
192  bool seen_connection_error_;
193
194  Event expected_event_;
195
196 private:
197  DISALLOW_COPY_AND_ASSIGN(DataSinkTest);
198};
199
200const int32_t DataSinkTest::kFatalError = -10;
201const uint32_t DataSinkTest::kBufferSize = 100;
202
203TEST_F(DataSinkTest, Basic) {
204  ASSERT_TRUE(Send("a"));
205  ASSERT_NO_FATAL_FAILURE(ExpectDataAndReadAll("a"));
206  ExpectSendSuccess(1);
207}
208
209TEST_F(DataSinkTest, LargeSend) {
210  std::string pattern = "1234567890";
211  std::string data;
212  for (uint32_t i = 0; i < kBufferSize; i++)
213    data.append(pattern);
214  ASSERT_TRUE(Send(data));
215  ASSERT_NO_FATAL_FAILURE(ExpectDataAndReadAll(data));
216  ExpectSendSuccess(static_cast<uint32_t>(data.size()));
217}
218
219TEST_F(DataSinkTest, ErrorAndAllData) {
220  ASSERT_TRUE(Send("a"));
221  ASSERT_NO_FATAL_FAILURE(ExpectData("a", 1, -1));
222  ExpectSendError(1, -1);
223}
224
225TEST_F(DataSinkTest, ErrorAndPartialData) {
226  ASSERT_TRUE(Send("ab"));
227  ASSERT_NO_FATAL_FAILURE(ExpectData("ab", 1, -1));
228  ExpectSendError(1, -1);
229
230  ASSERT_TRUE(Send("c"));
231  ASSERT_NO_FATAL_FAILURE(ExpectDataAndReadAll("c"));
232  ExpectSendSuccess(1);
233}
234
235TEST_F(DataSinkTest, ErrorAndPartialDataAtPacketBoundary) {
236  ASSERT_TRUE(Send("ab"));
237  ASSERT_NO_FATAL_FAILURE(ExpectData("ab", 2, -1));
238  ExpectSendError(2, -1);
239
240  ASSERT_TRUE(Send("c"));
241  ASSERT_NO_FATAL_FAILURE(ExpectDataAndReadAll("c"));
242  ExpectSendSuccess(1);
243}
244
245TEST_F(DataSinkTest, ErrorInSecondPacket) {
246  ASSERT_TRUE(Send("a"));
247  ASSERT_TRUE(Send("b"));
248  ASSERT_NO_FATAL_FAILURE(ExpectData("ab", 2, -1));
249  ExpectSendSuccess(1);
250  ExpectSendError(1, -1);
251
252  ASSERT_TRUE(Send("c"));
253  ASSERT_NO_FATAL_FAILURE(ExpectDataAndReadAll("c"));
254  ExpectSendSuccess(1);
255}
256
257TEST_F(DataSinkTest, ErrorBeforeLargeSend) {
258  ASSERT_TRUE(Send("a"));
259  std::string pattern = "123456789";
260  std::string data;
261  for (int i = 0; i < 100; i++)
262    data.append("1234567890");
263  ASSERT_TRUE(Send(data));
264  ASSERT_NO_FATAL_FAILURE(ExpectData("a" + data, 1, -1));
265  ExpectSendError(1, -1);
266  ExpectSendError(0, -1);
267}
268
269TEST_F(DataSinkTest, ErrorOnly) {
270  ASSERT_TRUE(Send("a"));
271  ASSERT_NO_FATAL_FAILURE(ExpectData("a", 0, -1));
272  ExpectSendError(0, -1);
273
274  ASSERT_TRUE(Send("b"));
275  ASSERT_NO_FATAL_FAILURE(ExpectDataAndReadAll("b"));
276  ExpectSendSuccess(1);
277}
278
279TEST_F(DataSinkTest, Cancel) {
280  ASSERT_TRUE(Send("a"));
281  WaitForEvent(EVENT_READ_BUFFER_READY);
282  ASSERT_TRUE(Cancel(-2));
283  // Check that sends fail until the cancel operation completes.
284  EXPECT_FALSE(Send("b"));
285  ASSERT_NO_FATAL_FAILURE(ExpectCancel(-2));
286  ASSERT_NO_FATAL_FAILURE(ExpectData("a", 0, -1));
287  // Check that the error reported by the sink implementation is reported to the
288  // client - not the cancellation error.
289  ExpectSendError(0, -1);
290  ExpectCancelResult();
291
292  EXPECT_TRUE(Send("c"));
293  ASSERT_NO_FATAL_FAILURE(ExpectDataAndReadAll("c"));
294  ExpectSendSuccess(1);
295}
296
297TEST_F(DataSinkTest, CancelSinkSucceeds) {
298  ASSERT_TRUE(Send("a"));
299  EXPECT_TRUE(Send("b"));
300  WaitForEvent(EVENT_READ_BUFFER_READY);
301  ASSERT_TRUE(Cancel(-2));
302  ASSERT_NO_FATAL_FAILURE(ExpectCancel(-2));
303  ASSERT_NO_FATAL_FAILURE(ExpectData("ab", 1, 0));
304  ExpectSendError(1, -2);
305  ExpectCancelResult();
306
307  EXPECT_TRUE(Send("c"));
308  ASSERT_NO_FATAL_FAILURE(ExpectDataAndReadAll("c"));
309  ExpectSendSuccess(1);
310}
311
312TEST_F(DataSinkTest, CancelTwice) {
313  ASSERT_TRUE(Send("a"));
314  WaitForEvent(EVENT_READ_BUFFER_READY);
315  ASSERT_TRUE(Cancel(-2));
316  ASSERT_NO_FATAL_FAILURE(ExpectCancel(-2));
317  ASSERT_NO_FATAL_FAILURE(ExpectData("a", 0, -2));
318  ExpectSendError(0, -2);
319  ExpectCancelResult();
320
321  EXPECT_TRUE(Send("b"));
322  WaitForEvent(EVENT_READ_BUFFER_READY);
323  ASSERT_TRUE(Cancel(-3));
324  ASSERT_NO_FATAL_FAILURE(ExpectCancel(-3));
325  ASSERT_NO_FATAL_FAILURE(ExpectData("b", 0, -3));
326  ExpectSendError(0, -3);
327  ExpectCancelResult();
328
329  EXPECT_TRUE(Send("c"));
330  ASSERT_NO_FATAL_FAILURE(ExpectDataAndReadAll("c"));
331  ExpectSendSuccess(1);
332}
333
334TEST_F(DataSinkTest, CancelTwiceWithNoSendBetween) {
335  ASSERT_TRUE(Send("a"));
336  WaitForEvent(EVENT_READ_BUFFER_READY);
337  ASSERT_TRUE(Cancel(-2));
338  ASSERT_NO_FATAL_FAILURE(ExpectCancel(-2));
339  ASSERT_NO_FATAL_FAILURE(ExpectData("a", 0, -2));
340  ExpectSendError(0, -2);
341  ExpectCancelResult();
342  ASSERT_TRUE(Cancel(-3));
343  ExpectCancelResult();
344
345  EXPECT_TRUE(Send("b"));
346  ASSERT_NO_FATAL_FAILURE(ExpectDataAndReadAll("b"));
347  ExpectSendSuccess(1);
348}
349
350TEST_F(DataSinkTest, CancelDuringError) {
351  ASSERT_TRUE(Send("a"));
352  WaitForEvent(EVENT_READ_BUFFER_READY);
353  ASSERT_TRUE(Cancel(-2));
354  ASSERT_NO_FATAL_FAILURE(ExpectData("a", 0, -1));
355  ExpectSendError(0, -1);
356  ExpectCancelResult();
357
358  EXPECT_TRUE(Send("a"));
359  ASSERT_NO_FATAL_FAILURE(ExpectDataAndReadAll("a"));
360  ExpectSendSuccess(1);
361}
362
363TEST_F(DataSinkTest, CancelWithoutSend) {
364  ASSERT_TRUE(Cancel(-2));
365  ExpectCancelResult();
366
367  EXPECT_TRUE(Send("a"));
368  ASSERT_NO_FATAL_FAILURE(ExpectDataAndReadAll("a"));
369  ExpectSendSuccess(1);
370  EXPECT_EQ(0, cancel_error_);
371}
372
373TEST_F(DataSinkTest, CancelPartialPacket) {
374  ASSERT_TRUE(Send("ab"));
375  WaitForEvent(EVENT_READ_BUFFER_READY);
376  ASSERT_TRUE(Cancel(-2));
377  ASSERT_NO_FATAL_FAILURE(ExpectCancel(-2));
378  ASSERT_NO_FATAL_FAILURE(ExpectData("ab", 1, -2));
379  ExpectSendError(1, -2);
380  ExpectCancelResult();
381
382  EXPECT_TRUE(Send("c"));
383  ASSERT_NO_FATAL_FAILURE(ExpectDataAndReadAll("c"));
384  ExpectSendSuccess(1);
385}
386
387TEST_F(DataSinkTest, SinkReceiverShutdown) {
388  ASSERT_TRUE(Send("a"));
389  ASSERT_TRUE(Send(std::string(kBufferSize * 10, 'b')));
390  ASSERT_TRUE(Cancel(-1));
391  sink_receiver_->ShutDown();
392  sink_receiver_ = NULL;
393  ExpectSendError(0, kFatalError);
394  ExpectSendError(0, kFatalError);
395  ExpectCancelResult();
396  ASSERT_FALSE(Send("a"));
397  ASSERT_FALSE(Cancel(-1));
398}
399
400TEST_F(DataSinkTest, SenderShutdown) {
401  ASSERT_TRUE(Send("a"));
402  ASSERT_TRUE(Send(std::string(kBufferSize * 10, 'b')));
403  ASSERT_TRUE(Cancel(-1));
404  sender_.reset();
405  ExpectSendError(0, kFatalError);
406  ExpectSendError(0, kFatalError);
407  ExpectCancelResult();
408  if (!seen_connection_error_)
409    WaitForEvent(EVENT_ERROR);
410  EXPECT_TRUE(seen_connection_error_);
411}
412
413}  // namespace device
414