1 // Copyright 2018 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 "mojo/public/cpp/system/data_pipe_drainer.h"
6
7 #include "base/bind.h"
8 #include "base/callback.h"
9 #include "base/run_loop.h"
10 #include "base/test/task_environment.h"
11 #include "base/values.h"
12 #include "testing/gtest/include/gtest/gtest.h"
13
14 namespace mojo {
15 namespace test {
16
17 template <typename Functor>
BindLambda(Functor callable)18 base::RepeatingClosure BindLambda(Functor callable) {
19 return base::BindRepeating([](Functor callable) { callable(); }, callable);
20 }
21
22 class DataPipeDrainerTest : public testing::Test,
23 public DataPipeDrainer::Client {
24 protected:
DataPipeDrainerTest()25 DataPipeDrainerTest() {
26 DataPipe pipe;
27 drainer_ = std::make_unique<DataPipeDrainer>(
28 this, std::move(pipe.consumer_handle));
29 producer_handle_ = std::move(pipe.producer_handle);
30 }
31
32 ScopedDataPipeProducerHandle producer_handle_;
33 base::RepeatingClosure completion_callback_;
34
OnDataAvailable(const void * data,size_t num_bytes)35 void OnDataAvailable(const void* data, size_t num_bytes) override {
36 data_.append(static_cast<const char*>(data), num_bytes);
37 }
38
OnDataComplete()39 void OnDataComplete() override { completion_callback_.Run(); }
40
41 base::test::SingleThreadTaskEnvironment task_environment_;
42 std::string data_;
43 std::unique_ptr<DataPipeDrainer> drainer_;
44
45 DISALLOW_COPY_AND_ASSIGN(DataPipeDrainerTest);
46 };
47
TEST_F(DataPipeDrainerTest,TestCompleteIsCalledOnce)48 TEST_F(DataPipeDrainerTest, TestCompleteIsCalledOnce) {
49 bool had_data_complete = false;
50
51 completion_callback_ = BindLambda([&had_data_complete]() {
52 EXPECT_FALSE(had_data_complete);
53 had_data_complete = true;
54 });
55 uint32_t size = 5;
56 EXPECT_EQ(MOJO_RESULT_OK, producer_handle_->WriteData(
57 "hello", &size, MOJO_WRITE_DATA_FLAG_NONE));
58 base::RunLoop().RunUntilIdle();
59 producer_handle_.reset();
60 base::RunLoop().RunUntilIdle();
61 }
62
63 } // namespace test
64 } // namespace mojo
65