huangcm
2025-02-24 69ed55dec4b2116a19e4cca4393cbc014fce5fb2
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
// Copyright 2016 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 "base/files/file_descriptor_watcher_posix.h"
 
#include <unistd.h>
 
#include <memory>
 
#include "base/bind.h"
#include "base/files/file_util.h"
#include "base/macros.h"
#include "base/memory/ptr_util.h"
#include "base/message_loop/message_loop.h"
#include "base/posix/eintr_wrapper.h"
#include "base/run_loop.h"
#include "base/test/test_timeouts.h"
#include "base/threading/platform_thread.h"
#include "base/threading/thread.h"
#include "base/threading/thread_checker_impl.h"
#include "build/build_config.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
 
namespace base {
 
namespace {
 
class Mock {
 public:
  Mock() = default;
 
  MOCK_METHOD0(ReadableCallback, void());
  MOCK_METHOD0(WritableCallback, void());
 
 private:
  DISALLOW_COPY_AND_ASSIGN(Mock);
};
 
enum class FileDescriptorWatcherTestType {
  MESSAGE_LOOP_FOR_IO_ON_MAIN_THREAD,
  MESSAGE_LOOP_FOR_IO_ON_OTHER_THREAD,
};
 
class FileDescriptorWatcherTest
    : public testing::TestWithParam<FileDescriptorWatcherTestType> {
 public:
  FileDescriptorWatcherTest()
      : message_loop_(GetParam() == FileDescriptorWatcherTestType::
                                        MESSAGE_LOOP_FOR_IO_ON_MAIN_THREAD
                          ? new MessageLoopForIO
                          : new MessageLoop),
        other_thread_("FileDescriptorWatcherTest_OtherThread") {}
  ~FileDescriptorWatcherTest() override = default;
 
  void SetUp() override {
    ASSERT_EQ(0, pipe(pipe_fds_));
 
    MessageLoop* message_loop_for_io;
    if (GetParam() ==
        FileDescriptorWatcherTestType::MESSAGE_LOOP_FOR_IO_ON_OTHER_THREAD) {
      Thread::Options options;
      options.message_loop_type = MessageLoop::TYPE_IO;
      ASSERT_TRUE(other_thread_.StartWithOptions(options));
      message_loop_for_io = other_thread_.message_loop();
    } else {
      message_loop_for_io = message_loop_.get();
    }
 
    ASSERT_TRUE(message_loop_for_io->IsType(MessageLoop::TYPE_IO));
    file_descriptor_watcher_ = std::make_unique<FileDescriptorWatcher>(
        static_cast<MessageLoopForIO*>(message_loop_for_io));
  }
 
  void TearDown() override {
    if (GetParam() ==
            FileDescriptorWatcherTestType::MESSAGE_LOOP_FOR_IO_ON_MAIN_THREAD &&
        message_loop_) {
      // Allow the delete task posted by the Controller's destructor to run.
      base::RunLoop().RunUntilIdle();
    }
 
    // Ensure that OtherThread is done processing before closing fds.
    other_thread_.Stop();
 
    EXPECT_EQ(0, IGNORE_EINTR(close(pipe_fds_[0])));
    EXPECT_EQ(0, IGNORE_EINTR(close(pipe_fds_[1])));
  }
 
 protected:
  int read_file_descriptor() const { return pipe_fds_[0]; }
  int write_file_descriptor() const { return pipe_fds_[1]; }
 
  // Waits for a short delay and run pending tasks.
  void WaitAndRunPendingTasks() {
    PlatformThread::Sleep(TestTimeouts::tiny_timeout());
    RunLoop().RunUntilIdle();
  }
 
  // Registers ReadableCallback() to be called on |mock_| when
  // read_file_descriptor() is readable without blocking.
  std::unique_ptr<FileDescriptorWatcher::Controller> WatchReadable() {
    std::unique_ptr<FileDescriptorWatcher::Controller> controller =
        FileDescriptorWatcher::WatchReadable(
            read_file_descriptor(),
            Bind(&Mock::ReadableCallback, Unretained(&mock_)));
    EXPECT_TRUE(controller);
 
    // Unless read_file_descriptor() was readable before the callback was
    // registered, this shouldn't do anything.
    WaitAndRunPendingTasks();
 
    return controller;
  }
 
  // Registers WritableCallback() to be called on |mock_| when
  // write_file_descriptor() is writable without blocking.
  std::unique_ptr<FileDescriptorWatcher::Controller> WatchWritable() {
    std::unique_ptr<FileDescriptorWatcher::Controller> controller =
        FileDescriptorWatcher::WatchWritable(
            write_file_descriptor(),
            Bind(&Mock::WritableCallback, Unretained(&mock_)));
    EXPECT_TRUE(controller);
    return controller;
  }
 
  void WriteByte() {
    constexpr char kByte = '!';
    ASSERT_TRUE(
        WriteFileDescriptor(write_file_descriptor(), &kByte, sizeof(kByte)));
  }
 
  void ReadByte() {
    // This is always called as part of the WatchReadable() callback, which
    // should run on the main thread.
    EXPECT_TRUE(thread_checker_.CalledOnValidThread());
 
    char buffer;
    ASSERT_TRUE(ReadFromFD(read_file_descriptor(), &buffer, sizeof(buffer)));
  }
 
  // Mock on wich callbacks are invoked.
  testing::StrictMock<Mock> mock_;
 
  // MessageLoop bound to the main thread.
  std::unique_ptr<MessageLoop> message_loop_;
 
  // Thread running a MessageLoopForIO. Used when the test type is
  // MESSAGE_LOOP_FOR_IO_ON_OTHER_THREAD.
  Thread other_thread_;
 
 private:
  // Determines which MessageLoopForIO is used to watch file descriptors for
  // which callbacks are registered on the main thread.
  std::unique_ptr<FileDescriptorWatcher> file_descriptor_watcher_;
 
  // Watched file descriptors.
  int pipe_fds_[2];
 
  // Used to verify that callbacks run on the thread on which they are
  // registered.
  ThreadCheckerImpl thread_checker_;
 
  DISALLOW_COPY_AND_ASSIGN(FileDescriptorWatcherTest);
};
 
}  // namespace
 
TEST_P(FileDescriptorWatcherTest, WatchWritable) {
  auto controller = WatchWritable();
 
  // The write end of a newly created pipe is immediately writable.
  RunLoop run_loop;
  EXPECT_CALL(mock_, WritableCallback())
      .WillOnce(testing::Invoke(&run_loop, &RunLoop::Quit));
  run_loop.Run();
}
 
TEST_P(FileDescriptorWatcherTest, WatchReadableOneByte) {
  auto controller = WatchReadable();
 
  // Write 1 byte to the pipe, making it readable without blocking. Expect one
  // call to ReadableCallback() which will read 1 byte from the pipe.
  WriteByte();
  RunLoop run_loop;
  EXPECT_CALL(mock_, ReadableCallback())
      .WillOnce(testing::Invoke([this, &run_loop]() {
        ReadByte();
        run_loop.Quit();
      }));
  run_loop.Run();
  testing::Mock::VerifyAndClear(&mock_);
 
  // No more call to ReadableCallback() is expected.
  WaitAndRunPendingTasks();
}
 
TEST_P(FileDescriptorWatcherTest, WatchReadableTwoBytes) {
  auto controller = WatchReadable();
 
  // Write 2 bytes to the pipe. Expect two calls to ReadableCallback() which
  // will each read 1 byte from the pipe.
  WriteByte();
  WriteByte();
  RunLoop run_loop;
  EXPECT_CALL(mock_, ReadableCallback())
      .WillOnce(testing::Invoke([this]() { ReadByte(); }))
      .WillOnce(testing::Invoke([this, &run_loop]() {
        ReadByte();
        run_loop.Quit();
      }));
  run_loop.Run();
  testing::Mock::VerifyAndClear(&mock_);
 
  // No more call to ReadableCallback() is expected.
  WaitAndRunPendingTasks();
}
 
TEST_P(FileDescriptorWatcherTest, WatchReadableByteWrittenFromCallback) {
  auto controller = WatchReadable();
 
  // Write 1 byte to the pipe. Expect one call to ReadableCallback() from which
  // 1 byte is read and 1 byte is written to the pipe. Then, expect another call
  // to ReadableCallback() from which the remaining byte is read from the pipe.
  WriteByte();
  RunLoop run_loop;
  EXPECT_CALL(mock_, ReadableCallback())
      .WillOnce(testing::Invoke([this]() {
        ReadByte();
        WriteByte();
      }))
      .WillOnce(testing::Invoke([this, &run_loop]() {
        ReadByte();
        run_loop.Quit();
      }));
  run_loop.Run();
  testing::Mock::VerifyAndClear(&mock_);
 
  // No more call to ReadableCallback() is expected.
  WaitAndRunPendingTasks();
}
 
TEST_P(FileDescriptorWatcherTest, DeleteControllerFromCallback) {
  auto controller = WatchReadable();
 
  // Write 1 byte to the pipe. Expect one call to ReadableCallback() from which
  // |controller| is deleted.
  WriteByte();
  RunLoop run_loop;
  EXPECT_CALL(mock_, ReadableCallback())
      .WillOnce(testing::Invoke([&run_loop, &controller]() {
        controller = nullptr;
        run_loop.Quit();
      }));
  run_loop.Run();
  testing::Mock::VerifyAndClear(&mock_);
 
  // Since |controller| has been deleted, no call to ReadableCallback() is
  // expected even though the pipe is still readable without blocking.
  WaitAndRunPendingTasks();
}
 
TEST_P(FileDescriptorWatcherTest,
       DeleteControllerBeforeFileDescriptorReadable) {
  auto controller = WatchReadable();
 
  // Cancel the watch.
  controller = nullptr;
 
  // Write 1 byte to the pipe to make it readable without blocking.
  WriteByte();
 
  // No call to ReadableCallback() is expected.
  WaitAndRunPendingTasks();
}
 
TEST_P(FileDescriptorWatcherTest, DeleteControllerAfterFileDescriptorReadable) {
  auto controller = WatchReadable();
 
  // Write 1 byte to the pipe to make it readable without blocking.
  WriteByte();
 
  // Cancel the watch.
  controller = nullptr;
 
  // No call to ReadableCallback() is expected.
  WaitAndRunPendingTasks();
}
 
TEST_P(FileDescriptorWatcherTest, DeleteControllerAfterDeleteMessageLoopForIO) {
  auto controller = WatchReadable();
 
  // Delete the MessageLoopForIO.
  if (GetParam() ==
      FileDescriptorWatcherTestType::MESSAGE_LOOP_FOR_IO_ON_MAIN_THREAD) {
    message_loop_ = nullptr;
  } else {
    other_thread_.Stop();
  }
 
  // Deleting |controller| shouldn't crash even though that causes a task to be
  // posted to the MessageLoopForIO thread.
  controller = nullptr;
}
 
INSTANTIATE_TEST_CASE_P(
    MessageLoopForIOOnMainThread,
    FileDescriptorWatcherTest,
    ::testing::Values(
        FileDescriptorWatcherTestType::MESSAGE_LOOP_FOR_IO_ON_MAIN_THREAD));
INSTANTIATE_TEST_CASE_P(
    MessageLoopForIOOnOtherThread,
    FileDescriptorWatcherTest,
    ::testing::Values(
        FileDescriptorWatcherTestType::MESSAGE_LOOP_FOR_IO_ON_OTHER_THREAD));
 
}  // namespace base