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
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
| //===- unittests/DirectoryWatcher/DirectoryWatcherTest.cpp ----------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "clang/DirectoryWatcher/DirectoryWatcher.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Testing/Support/Error.h"
#include "gtest/gtest.h"
#include <condition_variable>
#include <future>
#include <mutex>
#include <thread>
using namespace llvm;
using namespace llvm::sys;
using namespace llvm::sys::fs;
using namespace clang;
namespace clang {
static bool operator==(const DirectoryWatcher::Event &lhs,
const DirectoryWatcher::Event &rhs) {
return lhs.Filename == rhs.Filename &&
static_cast<int>(lhs.Kind) == static_cast<int>(rhs.Kind);
}
} // namespace clang
namespace {
typedef DirectoryWatcher::Event::EventKind EventKind;
struct DirectoryWatcherTestFixture {
std::string TestRootDir;
std::string TestWatchedDir;
DirectoryWatcherTestFixture() {
SmallString<128> pathBuf;
#ifndef NDEBUG
std::error_code UniqDirRes =
#endif
createUniqueDirectory("dirwatcher", pathBuf);
assert(!UniqDirRes);
TestRootDir = pathBuf.str();
path::append(pathBuf, "watch");
TestWatchedDir = pathBuf.str();
#ifndef NDEBUG
std::error_code CreateDirRes =
#endif
create_directory(TestWatchedDir, false);
assert(!CreateDirRes);
}
~DirectoryWatcherTestFixture() { remove_directories(TestRootDir); }
SmallString<128> getPathInWatched(const std::string &testFile) {
SmallString<128> pathBuf;
pathBuf = TestWatchedDir;
path::append(pathBuf, testFile);
return pathBuf;
}
void addFile(const std::string &testFile) {
Expected<file_t> ft = openNativeFileForWrite(getPathInWatched(testFile),
CD_CreateNew, OF_None);
if (ft) {
closeFile(*ft);
} else {
llvm::errs() << llvm::toString(ft.takeError()) << "\n";
llvm::errs() << getPathInWatched(testFile) << "\n";
llvm_unreachable("Couldn't create test file.");
}
}
void deleteFile(const std::string &testFile) {
std::error_code EC =
remove(getPathInWatched(testFile), /*IgnoreNonExisting=*/false);
ASSERT_FALSE(EC);
}
};
std::string eventKindToString(const EventKind K) {
switch (K) {
case EventKind::Removed:
return "Removed";
case EventKind::Modified:
return "Modified";
case EventKind::WatchedDirRemoved:
return "WatchedDirRemoved";
case EventKind::WatcherGotInvalidated:
return "WatcherGotInvalidated";
}
llvm_unreachable("unknown event kind");
}
struct VerifyingConsumer {
std::vector<DirectoryWatcher::Event> ExpectedInitial;
const std::vector<DirectoryWatcher::Event> ExpectedInitialCopy;
std::vector<DirectoryWatcher::Event> ExpectedNonInitial;
const std::vector<DirectoryWatcher::Event> ExpectedNonInitialCopy;
std::vector<DirectoryWatcher::Event> OptionalNonInitial;
std::vector<DirectoryWatcher::Event> UnexpectedInitial;
std::vector<DirectoryWatcher::Event> UnexpectedNonInitial;
std::mutex Mtx;
std::condition_variable ResultIsReady;
VerifyingConsumer(
const std::vector<DirectoryWatcher::Event> &ExpectedInitial,
const std::vector<DirectoryWatcher::Event> &ExpectedNonInitial,
const std::vector<DirectoryWatcher::Event> &OptionalNonInitial = {})
: ExpectedInitial(ExpectedInitial), ExpectedInitialCopy(ExpectedInitial),
ExpectedNonInitial(ExpectedNonInitial), ExpectedNonInitialCopy(ExpectedNonInitial),
OptionalNonInitial(OptionalNonInitial) {}
// This method is used by DirectoryWatcher.
void consume(DirectoryWatcher::Event E, bool IsInitial) {
if (IsInitial)
consumeInitial(E);
else
consumeNonInitial(E);
}
void consumeInitial(DirectoryWatcher::Event E) {
std::unique_lock<std::mutex> L(Mtx);
auto It = std::find(ExpectedInitial.begin(), ExpectedInitial.end(), E);
if (It == ExpectedInitial.end()) {
UnexpectedInitial.push_back(E);
} else {
ExpectedInitial.erase(It);
}
if (result()) {
L.unlock();
ResultIsReady.notify_one();
}
}
void consumeNonInitial(DirectoryWatcher::Event E) {
std::unique_lock<std::mutex> L(Mtx);
auto It =
std::find(ExpectedNonInitial.begin(), ExpectedNonInitial.end(), E);
if (It == ExpectedNonInitial.end()) {
auto OptIt =
std::find(OptionalNonInitial.begin(), OptionalNonInitial.end(), E);
if (OptIt != OptionalNonInitial.end()) {
OptionalNonInitial.erase(OptIt);
} else {
UnexpectedNonInitial.push_back(E);
}
} else {
ExpectedNonInitial.erase(It);
}
if (result()) {
L.unlock();
ResultIsReady.notify_one();
}
}
// This method is used by DirectoryWatcher.
void consume(llvm::ArrayRef<DirectoryWatcher::Event> Es, bool IsInitial) {
for (const auto &E : Es)
consume(E, IsInitial);
}
// Not locking - caller has to lock Mtx.
llvm::Optional<bool> result() const {
if (ExpectedInitial.empty() && ExpectedNonInitial.empty() &&
UnexpectedInitial.empty() && UnexpectedNonInitial.empty())
return true;
if (!UnexpectedInitial.empty() || !UnexpectedNonInitial.empty())
return false;
return llvm::None;
}
// This method is used by tests.
// \returns true on success
bool blockUntilResult() {
std::unique_lock<std::mutex> L(Mtx);
while (true) {
if (result())
return *result();
ResultIsReady.wait(L, [this]() { return result().hasValue(); });
}
return false; // Just to make compiler happy.
}
void printUnmetExpectations(llvm::raw_ostream &OS) {
// If there was any issue, print the expected state
if (
!ExpectedInitial.empty()
||
!ExpectedNonInitial.empty()
||
!UnexpectedInitial.empty()
||
!UnexpectedNonInitial.empty()
) {
OS << "Expected initial events: \n";
for (const auto &E : ExpectedInitialCopy) {
OS << eventKindToString(E.Kind) << " " << E.Filename << "\n";
}
OS << "Expected non-initial events: \n";
for (const auto &E : ExpectedNonInitialCopy) {
OS << eventKindToString(E.Kind) << " " << E.Filename << "\n";
}
}
if (!ExpectedInitial.empty()) {
OS << "Expected but not seen initial events: \n";
for (const auto &E : ExpectedInitial) {
OS << eventKindToString(E.Kind) << " " << E.Filename << "\n";
}
}
if (!ExpectedNonInitial.empty()) {
OS << "Expected but not seen non-initial events: \n";
for (const auto &E : ExpectedNonInitial) {
OS << eventKindToString(E.Kind) << " " << E.Filename << "\n";
}
}
if (!UnexpectedInitial.empty()) {
OS << "Unexpected initial events seen: \n";
for (const auto &E : UnexpectedInitial) {
OS << eventKindToString(E.Kind) << " " << E.Filename << "\n";
}
}
if (!UnexpectedNonInitial.empty()) {
OS << "Unexpected non-initial events seen: \n";
for (const auto &E : UnexpectedNonInitial) {
OS << eventKindToString(E.Kind) << " " << E.Filename << "\n";
}
}
}
};
void checkEventualResultWithTimeout(VerifyingConsumer &TestConsumer) {
std::packaged_task<int(void)> task(
[&TestConsumer]() { return TestConsumer.blockUntilResult(); });
std::future<int> WaitForExpectedStateResult = task.get_future();
std::thread worker(std::move(task));
worker.detach();
EXPECT_TRUE(WaitForExpectedStateResult.wait_for(std::chrono::seconds(3)) ==
std::future_status::ready)
<< "The expected result state wasn't reached before the time-out.";
std::unique_lock<std::mutex> L(TestConsumer.Mtx);
EXPECT_TRUE(TestConsumer.result().hasValue());
if (TestConsumer.result().hasValue()) {
EXPECT_TRUE(*TestConsumer.result());
}
if ((TestConsumer.result().hasValue() && !TestConsumer.result().getValue()) ||
!TestConsumer.result().hasValue())
TestConsumer.printUnmetExpectations(llvm::outs());
}
} // namespace
TEST(DirectoryWatcherTest, InitialScanSync) {
DirectoryWatcherTestFixture fixture;
fixture.addFile("a");
fixture.addFile("b");
fixture.addFile("c");
VerifyingConsumer TestConsumer{
{{EventKind::Modified, "a"},
{EventKind::Modified, "b"},
{EventKind::Modified, "c"}},
{},
// We have to ignore these as it's a race between the test process
// which is scanning the directory and kernel which is sending
// notification.
{{EventKind::Modified, "a"},
{EventKind::Modified, "b"},
{EventKind::Modified, "c"}}
};
llvm::Expected<std::unique_ptr<DirectoryWatcher>> DW =
DirectoryWatcher::create(
fixture.TestWatchedDir,
[&TestConsumer](llvm::ArrayRef<DirectoryWatcher::Event> Events,
bool IsInitial) {
TestConsumer.consume(Events, IsInitial);
},
/*waitForInitialSync=*/true);
ASSERT_THAT_ERROR(DW.takeError(), Succeeded());
checkEventualResultWithTimeout(TestConsumer);
}
TEST(DirectoryWatcherTest, InitialScanAsync) {
DirectoryWatcherTestFixture fixture;
fixture.addFile("a");
fixture.addFile("b");
fixture.addFile("c");
VerifyingConsumer TestConsumer{
{{EventKind::Modified, "a"},
{EventKind::Modified, "b"},
{EventKind::Modified, "c"}},
{},
// We have to ignore these as it's a race between the test process
// which is scanning the directory and kernel which is sending
// notification.
{{EventKind::Modified, "a"},
{EventKind::Modified, "b"},
{EventKind::Modified, "c"}}
};
llvm::Expected<std::unique_ptr<DirectoryWatcher>> DW =
DirectoryWatcher::create(
fixture.TestWatchedDir,
[&TestConsumer](llvm::ArrayRef<DirectoryWatcher::Event> Events,
bool IsInitial) {
TestConsumer.consume(Events, IsInitial);
},
/*waitForInitialSync=*/false);
ASSERT_THAT_ERROR(DW.takeError(), Succeeded());
checkEventualResultWithTimeout(TestConsumer);
}
TEST(DirectoryWatcherTest, AddFiles) {
DirectoryWatcherTestFixture fixture;
VerifyingConsumer TestConsumer{
{},
{{EventKind::Modified, "a"},
{EventKind::Modified, "b"},
{EventKind::Modified, "c"}}};
llvm::Expected<std::unique_ptr<DirectoryWatcher>> DW =
DirectoryWatcher::create(
fixture.TestWatchedDir,
[&TestConsumer](llvm::ArrayRef<DirectoryWatcher::Event> Events,
bool IsInitial) {
TestConsumer.consume(Events, IsInitial);
},
/*waitForInitialSync=*/true);
ASSERT_THAT_ERROR(DW.takeError(), Succeeded());
fixture.addFile("a");
fixture.addFile("b");
fixture.addFile("c");
checkEventualResultWithTimeout(TestConsumer);
}
TEST(DirectoryWatcherTest, ModifyFile) {
DirectoryWatcherTestFixture fixture;
fixture.addFile("a");
VerifyingConsumer TestConsumer{
{{EventKind::Modified, "a"}},
{{EventKind::Modified, "a"}},
{{EventKind::Modified, "a"}}};
llvm::Expected<std::unique_ptr<DirectoryWatcher>> DW =
DirectoryWatcher::create(
fixture.TestWatchedDir,
[&TestConsumer](llvm::ArrayRef<DirectoryWatcher::Event> Events,
bool IsInitial) {
TestConsumer.consume(Events, IsInitial);
},
/*waitForInitialSync=*/true);
ASSERT_THAT_ERROR(DW.takeError(), Succeeded());
// modify the file
{
std::error_code error;
llvm::raw_fd_ostream bStream(fixture.getPathInWatched("a"), error,
CD_OpenExisting);
assert(!error);
bStream << "foo";
}
checkEventualResultWithTimeout(TestConsumer);
}
TEST(DirectoryWatcherTest, DeleteFile) {
DirectoryWatcherTestFixture fixture;
fixture.addFile("a");
VerifyingConsumer TestConsumer{
{{EventKind::Modified, "a"}},
{{EventKind::Removed, "a"}},
{{EventKind::Modified, "a"}, {EventKind::Removed, "a"}}};
llvm::Expected<std::unique_ptr<DirectoryWatcher>> DW =
DirectoryWatcher::create(
fixture.TestWatchedDir,
[&TestConsumer](llvm::ArrayRef<DirectoryWatcher::Event> Events,
bool IsInitial) {
TestConsumer.consume(Events, IsInitial);
},
/*waitForInitialSync=*/true);
ASSERT_THAT_ERROR(DW.takeError(), Succeeded());
fixture.deleteFile("a");
checkEventualResultWithTimeout(TestConsumer);
}
TEST(DirectoryWatcherTest, DeleteWatchedDir) {
DirectoryWatcherTestFixture fixture;
VerifyingConsumer TestConsumer{
{},
{{EventKind::WatchedDirRemoved, ""},
{EventKind::WatcherGotInvalidated, ""}}};
llvm::Expected<std::unique_ptr<DirectoryWatcher>> DW =
DirectoryWatcher::create(
fixture.TestWatchedDir,
[&TestConsumer](llvm::ArrayRef<DirectoryWatcher::Event> Events,
bool IsInitial) {
TestConsumer.consume(Events, IsInitial);
},
/*waitForInitialSync=*/true);
ASSERT_THAT_ERROR(DW.takeError(), Succeeded());
remove_directories(fixture.TestWatchedDir);
checkEventualResultWithTimeout(TestConsumer);
}
TEST(DirectoryWatcherTest, InvalidatedWatcher) {
DirectoryWatcherTestFixture fixture;
VerifyingConsumer TestConsumer{
{}, {{EventKind::WatcherGotInvalidated, ""}}};
{
llvm::Expected<std::unique_ptr<DirectoryWatcher>> DW =
DirectoryWatcher::create(
fixture.TestWatchedDir,
[&TestConsumer](llvm::ArrayRef<DirectoryWatcher::Event> Events,
bool IsInitial) {
TestConsumer.consume(Events, IsInitial);
},
/*waitForInitialSync=*/true);
ASSERT_THAT_ERROR(DW.takeError(), Succeeded());
} // DW is destructed here.
checkEventualResultWithTimeout(TestConsumer);
}
|