1 // Copyright (c) 2012 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/files/file_path_watcher.h"
6
7 #if defined(OS_WIN)
8 #include <windows.h>
9 #include <aclapi.h>
10 #elif defined(OS_POSIX)
11 #include <sys/stat.h>
12 #endif
13
14 #include <set>
15
16 #include "base/bind.h"
17 #include "base/bind_helpers.h"
18 #include "base/compiler_specific.h"
19 #include "base/files/file_path.h"
20 #include "base/files/file_util.h"
21 #include "base/files/scoped_temp_dir.h"
22 #include "base/location.h"
23 #include "base/macros.h"
24 #include "base/run_loop.h"
25 #include "base/single_thread_task_runner.h"
26 #include "base/stl_util.h"
27 #include "base/strings/stringprintf.h"
28 #include "base/synchronization/waitable_event.h"
29 #include "base/test/test_file_util.h"
30 #include "base/test/test_timeouts.h"
31 #include "base/thread_task_runner_handle.h"
32 #include "base/threading/thread.h"
33 #include "build/build_config.h"
34 #include "testing/gtest/include/gtest/gtest.h"
35
36 #if defined(OS_ANDROID)
37 #include "base/android/path_utils.h"
38 #endif // defined(OS_ANDROID)
39
40 namespace base {
41
42 namespace {
43
44 class TestDelegate;
45
46 // Aggregates notifications from the test delegates and breaks the message loop
47 // the test thread is waiting on once they all came in.
48 class NotificationCollector
49 : public base::RefCountedThreadSafe<NotificationCollector> {
50 public:
NotificationCollector()51 NotificationCollector() : task_runner_(base::ThreadTaskRunnerHandle::Get()) {}
52
53 // Called from the file thread by the delegates.
OnChange(TestDelegate * delegate)54 void OnChange(TestDelegate* delegate) {
55 task_runner_->PostTask(
56 FROM_HERE, base::Bind(&NotificationCollector::RecordChange, this,
57 base::Unretained(delegate)));
58 }
59
Register(TestDelegate * delegate)60 void Register(TestDelegate* delegate) {
61 delegates_.insert(delegate);
62 }
63
Reset()64 void Reset() {
65 signaled_.clear();
66 }
67
Success()68 bool Success() {
69 return signaled_ == delegates_;
70 }
71
72 private:
73 friend class base::RefCountedThreadSafe<NotificationCollector>;
~NotificationCollector()74 ~NotificationCollector() {}
75
RecordChange(TestDelegate * delegate)76 void RecordChange(TestDelegate* delegate) {
77 // Warning: |delegate| is Unretained. Do not dereference.
78 ASSERT_TRUE(task_runner_->BelongsToCurrentThread());
79 ASSERT_TRUE(delegates_.count(delegate));
80 signaled_.insert(delegate);
81
82 // Check whether all delegates have been signaled.
83 if (signaled_ == delegates_)
84 task_runner_->PostTask(FROM_HERE, MessageLoop::QuitWhenIdleClosure());
85 }
86
87 // Set of registered delegates.
88 std::set<TestDelegate*> delegates_;
89
90 // Set of signaled delegates.
91 std::set<TestDelegate*> signaled_;
92
93 // The loop we should break after all delegates signaled.
94 scoped_refptr<base::SingleThreadTaskRunner> task_runner_;
95 };
96
97 class TestDelegateBase : public SupportsWeakPtr<TestDelegateBase> {
98 public:
TestDelegateBase()99 TestDelegateBase() {}
~TestDelegateBase()100 virtual ~TestDelegateBase() {}
101
102 virtual void OnFileChanged(const FilePath& path, bool error) = 0;
103
104 private:
105 DISALLOW_COPY_AND_ASSIGN(TestDelegateBase);
106 };
107
108 // A mock class for testing. Gmock is not appropriate because it is not
109 // thread-safe for setting expectations. Thus the test code cannot safely
110 // reset expectations while the file watcher is running.
111 // Instead, TestDelegate gets the notifications from FilePathWatcher and uses
112 // NotificationCollector to aggregate the results.
113 class TestDelegate : public TestDelegateBase {
114 public:
TestDelegate(NotificationCollector * collector)115 explicit TestDelegate(NotificationCollector* collector)
116 : collector_(collector) {
117 collector_->Register(this);
118 }
~TestDelegate()119 ~TestDelegate() override {}
120
OnFileChanged(const FilePath & path,bool error)121 void OnFileChanged(const FilePath& path, bool error) override {
122 if (error)
123 ADD_FAILURE() << "Error " << path.value();
124 else
125 collector_->OnChange(this);
126 }
127
128 private:
129 scoped_refptr<NotificationCollector> collector_;
130
131 DISALLOW_COPY_AND_ASSIGN(TestDelegate);
132 };
133
SetupWatchCallback(const FilePath & target,FilePathWatcher * watcher,TestDelegateBase * delegate,bool recursive_watch,bool * result,base::WaitableEvent * completion)134 void SetupWatchCallback(const FilePath& target,
135 FilePathWatcher* watcher,
136 TestDelegateBase* delegate,
137 bool recursive_watch,
138 bool* result,
139 base::WaitableEvent* completion) {
140 *result = watcher->Watch(target, recursive_watch,
141 base::Bind(&TestDelegateBase::OnFileChanged,
142 delegate->AsWeakPtr()));
143 completion->Signal();
144 }
145
146 class FilePathWatcherTest : public testing::Test {
147 public:
FilePathWatcherTest()148 FilePathWatcherTest()
149 : file_thread_("FilePathWatcherTest") {}
150
~FilePathWatcherTest()151 ~FilePathWatcherTest() override {}
152
153 protected:
SetUp()154 void SetUp() override {
155 // Create a separate file thread in order to test proper thread usage.
156 base::Thread::Options options(MessageLoop::TYPE_IO, 0);
157 ASSERT_TRUE(file_thread_.StartWithOptions(options));
158 #if defined(OS_ANDROID)
159 // Watching files is only permitted when all parent directories are
160 // accessible, which is not the case for the default temp directory
161 // on Android which is under /data/data. Use /sdcard instead.
162 // TODO(pauljensen): Remove this when crbug.com/475568 is fixed.
163 FilePath parent_dir;
164 ASSERT_TRUE(android::GetExternalStorageDirectory(&parent_dir));
165 ASSERT_TRUE(temp_dir_.CreateUniqueTempDirUnderPath(parent_dir));
166 #else // defined(OS_ANDROID)
167 ASSERT_TRUE(temp_dir_.CreateUniqueTempDir());
168 #endif // defined(OS_ANDROID)
169 collector_ = new NotificationCollector();
170 }
171
TearDown()172 void TearDown() override { RunLoop().RunUntilIdle(); }
173
DeleteDelegateOnFileThread(TestDelegate * delegate)174 void DeleteDelegateOnFileThread(TestDelegate* delegate) {
175 file_thread_.task_runner()->DeleteSoon(FROM_HERE, delegate);
176 }
177
test_file()178 FilePath test_file() {
179 return temp_dir_.path().AppendASCII("FilePathWatcherTest");
180 }
181
test_link()182 FilePath test_link() {
183 return temp_dir_.path().AppendASCII("FilePathWatcherTest.lnk");
184 }
185
186 // Write |content| to |file|. Returns true on success.
WriteFile(const FilePath & file,const std::string & content)187 bool WriteFile(const FilePath& file, const std::string& content) {
188 int write_size = ::base::WriteFile(file, content.c_str(), content.length());
189 return write_size == static_cast<int>(content.length());
190 }
191
192 bool SetupWatch(const FilePath& target,
193 FilePathWatcher* watcher,
194 TestDelegateBase* delegate,
195 bool recursive_watch) WARN_UNUSED_RESULT;
196
WaitForEvents()197 bool WaitForEvents() WARN_UNUSED_RESULT {
198 collector_->Reset();
199 loop_.Run();
200 return collector_->Success();
201 }
202
collector()203 NotificationCollector* collector() { return collector_.get(); }
204
205 MessageLoop loop_;
206 base::Thread file_thread_;
207 ScopedTempDir temp_dir_;
208 scoped_refptr<NotificationCollector> collector_;
209
210 private:
211 DISALLOW_COPY_AND_ASSIGN(FilePathWatcherTest);
212 };
213
SetupWatch(const FilePath & target,FilePathWatcher * watcher,TestDelegateBase * delegate,bool recursive_watch)214 bool FilePathWatcherTest::SetupWatch(const FilePath& target,
215 FilePathWatcher* watcher,
216 TestDelegateBase* delegate,
217 bool recursive_watch) {
218 base::WaitableEvent completion(false, false);
219 bool result;
220 file_thread_.task_runner()->PostTask(
221 FROM_HERE, base::Bind(SetupWatchCallback, target, watcher, delegate,
222 recursive_watch, &result, &completion));
223 completion.Wait();
224 return result;
225 }
226
227 // Basic test: Create the file and verify that we notice.
TEST_F(FilePathWatcherTest,NewFile)228 TEST_F(FilePathWatcherTest, NewFile) {
229 FilePathWatcher watcher;
230 scoped_ptr<TestDelegate> delegate(new TestDelegate(collector()));
231 ASSERT_TRUE(SetupWatch(test_file(), &watcher, delegate.get(), false));
232
233 ASSERT_TRUE(WriteFile(test_file(), "content"));
234 ASSERT_TRUE(WaitForEvents());
235 DeleteDelegateOnFileThread(delegate.release());
236 }
237
238 // Verify that modifying the file is caught.
TEST_F(FilePathWatcherTest,ModifiedFile)239 TEST_F(FilePathWatcherTest, ModifiedFile) {
240 ASSERT_TRUE(WriteFile(test_file(), "content"));
241
242 FilePathWatcher watcher;
243 scoped_ptr<TestDelegate> delegate(new TestDelegate(collector()));
244 ASSERT_TRUE(SetupWatch(test_file(), &watcher, delegate.get(), false));
245
246 // Now make sure we get notified if the file is modified.
247 ASSERT_TRUE(WriteFile(test_file(), "new content"));
248 ASSERT_TRUE(WaitForEvents());
249 DeleteDelegateOnFileThread(delegate.release());
250 }
251
252 // Verify that moving the file into place is caught.
TEST_F(FilePathWatcherTest,MovedFile)253 TEST_F(FilePathWatcherTest, MovedFile) {
254 FilePath source_file(temp_dir_.path().AppendASCII("source"));
255 ASSERT_TRUE(WriteFile(source_file, "content"));
256
257 FilePathWatcher watcher;
258 scoped_ptr<TestDelegate> delegate(new TestDelegate(collector()));
259 ASSERT_TRUE(SetupWatch(test_file(), &watcher, delegate.get(), false));
260
261 // Now make sure we get notified if the file is modified.
262 ASSERT_TRUE(base::Move(source_file, test_file()));
263 ASSERT_TRUE(WaitForEvents());
264 DeleteDelegateOnFileThread(delegate.release());
265 }
266
TEST_F(FilePathWatcherTest,DeletedFile)267 TEST_F(FilePathWatcherTest, DeletedFile) {
268 ASSERT_TRUE(WriteFile(test_file(), "content"));
269
270 FilePathWatcher watcher;
271 scoped_ptr<TestDelegate> delegate(new TestDelegate(collector()));
272 ASSERT_TRUE(SetupWatch(test_file(), &watcher, delegate.get(), false));
273
274 // Now make sure we get notified if the file is deleted.
275 base::DeleteFile(test_file(), false);
276 ASSERT_TRUE(WaitForEvents());
277 DeleteDelegateOnFileThread(delegate.release());
278 }
279
280 // Used by the DeleteDuringNotify test below.
281 // Deletes the FilePathWatcher when it's notified.
282 class Deleter : public TestDelegateBase {
283 public:
Deleter(FilePathWatcher * watcher,MessageLoop * loop)284 Deleter(FilePathWatcher* watcher, MessageLoop* loop)
285 : watcher_(watcher),
286 loop_(loop) {
287 }
~Deleter()288 ~Deleter() override {}
289
OnFileChanged(const FilePath &,bool)290 void OnFileChanged(const FilePath&, bool) override {
291 watcher_.reset();
292 loop_->task_runner()->PostTask(FROM_HERE,
293 MessageLoop::QuitWhenIdleClosure());
294 }
295
watcher() const296 FilePathWatcher* watcher() const { return watcher_.get(); }
297
298 private:
299 scoped_ptr<FilePathWatcher> watcher_;
300 MessageLoop* loop_;
301
302 DISALLOW_COPY_AND_ASSIGN(Deleter);
303 };
304
305 // Verify that deleting a watcher during the callback doesn't crash.
TEST_F(FilePathWatcherTest,DeleteDuringNotify)306 TEST_F(FilePathWatcherTest, DeleteDuringNotify) {
307 FilePathWatcher* watcher = new FilePathWatcher;
308 // Takes ownership of watcher.
309 scoped_ptr<Deleter> deleter(new Deleter(watcher, &loop_));
310 ASSERT_TRUE(SetupWatch(test_file(), watcher, deleter.get(), false));
311
312 ASSERT_TRUE(WriteFile(test_file(), "content"));
313 ASSERT_TRUE(WaitForEvents());
314
315 // We win if we haven't crashed yet.
316 // Might as well double-check it got deleted, too.
317 ASSERT_TRUE(deleter->watcher() == NULL);
318 }
319
320 // Verify that deleting the watcher works even if there is a pending
321 // notification.
322 // Flaky on MacOS (and ARM linux): http://crbug.com/85930
TEST_F(FilePathWatcherTest,DISABLED_DestroyWithPendingNotification)323 TEST_F(FilePathWatcherTest, DISABLED_DestroyWithPendingNotification) {
324 scoped_ptr<TestDelegate> delegate(new TestDelegate(collector()));
325 FilePathWatcher* watcher = new FilePathWatcher;
326 ASSERT_TRUE(SetupWatch(test_file(), watcher, delegate.get(), false));
327 ASSERT_TRUE(WriteFile(test_file(), "content"));
328 file_thread_.task_runner()->DeleteSoon(FROM_HERE, watcher);
329 DeleteDelegateOnFileThread(delegate.release());
330 }
331
TEST_F(FilePathWatcherTest,MultipleWatchersSingleFile)332 TEST_F(FilePathWatcherTest, MultipleWatchersSingleFile) {
333 FilePathWatcher watcher1, watcher2;
334 scoped_ptr<TestDelegate> delegate1(new TestDelegate(collector()));
335 scoped_ptr<TestDelegate> delegate2(new TestDelegate(collector()));
336 ASSERT_TRUE(SetupWatch(test_file(), &watcher1, delegate1.get(), false));
337 ASSERT_TRUE(SetupWatch(test_file(), &watcher2, delegate2.get(), false));
338
339 ASSERT_TRUE(WriteFile(test_file(), "content"));
340 ASSERT_TRUE(WaitForEvents());
341 DeleteDelegateOnFileThread(delegate1.release());
342 DeleteDelegateOnFileThread(delegate2.release());
343 }
344
345 // Verify that watching a file whose parent directory doesn't exist yet works if
346 // the directory and file are created eventually.
TEST_F(FilePathWatcherTest,NonExistentDirectory)347 TEST_F(FilePathWatcherTest, NonExistentDirectory) {
348 FilePathWatcher watcher;
349 FilePath dir(temp_dir_.path().AppendASCII("dir"));
350 FilePath file(dir.AppendASCII("file"));
351 scoped_ptr<TestDelegate> delegate(new TestDelegate(collector()));
352 ASSERT_TRUE(SetupWatch(file, &watcher, delegate.get(), false));
353
354 ASSERT_TRUE(base::CreateDirectory(dir));
355
356 ASSERT_TRUE(WriteFile(file, "content"));
357
358 VLOG(1) << "Waiting for file creation";
359 ASSERT_TRUE(WaitForEvents());
360
361 ASSERT_TRUE(WriteFile(file, "content v2"));
362 VLOG(1) << "Waiting for file change";
363 ASSERT_TRUE(WaitForEvents());
364
365 ASSERT_TRUE(base::DeleteFile(file, false));
366 VLOG(1) << "Waiting for file deletion";
367 ASSERT_TRUE(WaitForEvents());
368 DeleteDelegateOnFileThread(delegate.release());
369 }
370
371 // Exercises watch reconfiguration for the case that directories on the path
372 // are rapidly created.
TEST_F(FilePathWatcherTest,DirectoryChain)373 TEST_F(FilePathWatcherTest, DirectoryChain) {
374 FilePath path(temp_dir_.path());
375 std::vector<std::string> dir_names;
376 for (int i = 0; i < 20; i++) {
377 std::string dir(base::StringPrintf("d%d", i));
378 dir_names.push_back(dir);
379 path = path.AppendASCII(dir);
380 }
381
382 FilePathWatcher watcher;
383 FilePath file(path.AppendASCII("file"));
384 scoped_ptr<TestDelegate> delegate(new TestDelegate(collector()));
385 ASSERT_TRUE(SetupWatch(file, &watcher, delegate.get(), false));
386
387 FilePath sub_path(temp_dir_.path());
388 for (std::vector<std::string>::const_iterator d(dir_names.begin());
389 d != dir_names.end(); ++d) {
390 sub_path = sub_path.AppendASCII(*d);
391 ASSERT_TRUE(base::CreateDirectory(sub_path));
392 }
393 VLOG(1) << "Create File";
394 ASSERT_TRUE(WriteFile(file, "content"));
395 VLOG(1) << "Waiting for file creation";
396 ASSERT_TRUE(WaitForEvents());
397
398 ASSERT_TRUE(WriteFile(file, "content v2"));
399 VLOG(1) << "Waiting for file modification";
400 ASSERT_TRUE(WaitForEvents());
401 DeleteDelegateOnFileThread(delegate.release());
402 }
403
404 #if defined(OS_MACOSX)
405 // http://crbug.com/85930
406 #define DisappearingDirectory DISABLED_DisappearingDirectory
407 #endif
TEST_F(FilePathWatcherTest,DisappearingDirectory)408 TEST_F(FilePathWatcherTest, DisappearingDirectory) {
409 FilePathWatcher watcher;
410 FilePath dir(temp_dir_.path().AppendASCII("dir"));
411 FilePath file(dir.AppendASCII("file"));
412 ASSERT_TRUE(base::CreateDirectory(dir));
413 ASSERT_TRUE(WriteFile(file, "content"));
414 scoped_ptr<TestDelegate> delegate(new TestDelegate(collector()));
415 ASSERT_TRUE(SetupWatch(file, &watcher, delegate.get(), false));
416
417 ASSERT_TRUE(base::DeleteFile(dir, true));
418 ASSERT_TRUE(WaitForEvents());
419 DeleteDelegateOnFileThread(delegate.release());
420 }
421
422 // Tests that a file that is deleted and reappears is tracked correctly.
TEST_F(FilePathWatcherTest,DeleteAndRecreate)423 TEST_F(FilePathWatcherTest, DeleteAndRecreate) {
424 ASSERT_TRUE(WriteFile(test_file(), "content"));
425 FilePathWatcher watcher;
426 scoped_ptr<TestDelegate> delegate(new TestDelegate(collector()));
427 ASSERT_TRUE(SetupWatch(test_file(), &watcher, delegate.get(), false));
428
429 ASSERT_TRUE(base::DeleteFile(test_file(), false));
430 VLOG(1) << "Waiting for file deletion";
431 ASSERT_TRUE(WaitForEvents());
432
433 ASSERT_TRUE(WriteFile(test_file(), "content"));
434 VLOG(1) << "Waiting for file creation";
435 ASSERT_TRUE(WaitForEvents());
436 DeleteDelegateOnFileThread(delegate.release());
437 }
438
TEST_F(FilePathWatcherTest,WatchDirectory)439 TEST_F(FilePathWatcherTest, WatchDirectory) {
440 FilePathWatcher watcher;
441 FilePath dir(temp_dir_.path().AppendASCII("dir"));
442 FilePath file1(dir.AppendASCII("file1"));
443 FilePath file2(dir.AppendASCII("file2"));
444 scoped_ptr<TestDelegate> delegate(new TestDelegate(collector()));
445 ASSERT_TRUE(SetupWatch(dir, &watcher, delegate.get(), false));
446
447 ASSERT_TRUE(base::CreateDirectory(dir));
448 VLOG(1) << "Waiting for directory creation";
449 ASSERT_TRUE(WaitForEvents());
450
451 ASSERT_TRUE(WriteFile(file1, "content"));
452 VLOG(1) << "Waiting for file1 creation";
453 ASSERT_TRUE(WaitForEvents());
454
455 #if !defined(OS_MACOSX)
456 // Mac implementation does not detect files modified in a directory.
457 ASSERT_TRUE(WriteFile(file1, "content v2"));
458 VLOG(1) << "Waiting for file1 modification";
459 ASSERT_TRUE(WaitForEvents());
460 #endif // !OS_MACOSX
461
462 ASSERT_TRUE(base::DeleteFile(file1, false));
463 VLOG(1) << "Waiting for file1 deletion";
464 ASSERT_TRUE(WaitForEvents());
465
466 ASSERT_TRUE(WriteFile(file2, "content"));
467 VLOG(1) << "Waiting for file2 creation";
468 ASSERT_TRUE(WaitForEvents());
469 DeleteDelegateOnFileThread(delegate.release());
470 }
471
TEST_F(FilePathWatcherTest,MoveParent)472 TEST_F(FilePathWatcherTest, MoveParent) {
473 FilePathWatcher file_watcher;
474 FilePathWatcher subdir_watcher;
475 FilePath dir(temp_dir_.path().AppendASCII("dir"));
476 FilePath dest(temp_dir_.path().AppendASCII("dest"));
477 FilePath subdir(dir.AppendASCII("subdir"));
478 FilePath file(subdir.AppendASCII("file"));
479 scoped_ptr<TestDelegate> file_delegate(new TestDelegate(collector()));
480 ASSERT_TRUE(SetupWatch(file, &file_watcher, file_delegate.get(), false));
481 scoped_ptr<TestDelegate> subdir_delegate(new TestDelegate(collector()));
482 ASSERT_TRUE(SetupWatch(subdir, &subdir_watcher, subdir_delegate.get(),
483 false));
484
485 // Setup a directory hierarchy.
486 ASSERT_TRUE(base::CreateDirectory(subdir));
487 ASSERT_TRUE(WriteFile(file, "content"));
488 VLOG(1) << "Waiting for file creation";
489 ASSERT_TRUE(WaitForEvents());
490
491 // Move the parent directory.
492 base::Move(dir, dest);
493 VLOG(1) << "Waiting for directory move";
494 ASSERT_TRUE(WaitForEvents());
495 DeleteDelegateOnFileThread(file_delegate.release());
496 DeleteDelegateOnFileThread(subdir_delegate.release());
497 }
498
TEST_F(FilePathWatcherTest,RecursiveWatch)499 TEST_F(FilePathWatcherTest, RecursiveWatch) {
500 FilePathWatcher watcher;
501 FilePath dir(temp_dir_.path().AppendASCII("dir"));
502 scoped_ptr<TestDelegate> delegate(new TestDelegate(collector()));
503 bool setup_result = SetupWatch(dir, &watcher, delegate.get(), true);
504 if (!FilePathWatcher::RecursiveWatchAvailable()) {
505 ASSERT_FALSE(setup_result);
506 DeleteDelegateOnFileThread(delegate.release());
507 return;
508 }
509 ASSERT_TRUE(setup_result);
510
511 // Main directory("dir") creation.
512 ASSERT_TRUE(base::CreateDirectory(dir));
513 ASSERT_TRUE(WaitForEvents());
514
515 // Create "$dir/file1".
516 FilePath file1(dir.AppendASCII("file1"));
517 ASSERT_TRUE(WriteFile(file1, "content"));
518 ASSERT_TRUE(WaitForEvents());
519
520 // Create "$dir/subdir".
521 FilePath subdir(dir.AppendASCII("subdir"));
522 ASSERT_TRUE(base::CreateDirectory(subdir));
523 ASSERT_TRUE(WaitForEvents());
524
525 // Create "$dir/subdir/subdir_file1".
526 FilePath subdir_file1(subdir.AppendASCII("subdir_file1"));
527 ASSERT_TRUE(WriteFile(subdir_file1, "content"));
528 ASSERT_TRUE(WaitForEvents());
529
530 // Create "$dir/subdir/subdir_child_dir".
531 FilePath subdir_child_dir(subdir.AppendASCII("subdir_child_dir"));
532 ASSERT_TRUE(base::CreateDirectory(subdir_child_dir));
533 ASSERT_TRUE(WaitForEvents());
534
535 // Create "$dir/subdir/subdir_child_dir/child_dir_file1".
536 FilePath child_dir_file1(subdir_child_dir.AppendASCII("child_dir_file1"));
537 ASSERT_TRUE(WriteFile(child_dir_file1, "content v2"));
538 ASSERT_TRUE(WaitForEvents());
539
540 // Write into "$dir/subdir/subdir_child_dir/child_dir_file1".
541 ASSERT_TRUE(WriteFile(child_dir_file1, "content"));
542 ASSERT_TRUE(WaitForEvents());
543
544 // Apps cannot change file attributes on Android in /sdcard as /sdcard uses the
545 // "fuse" file system, while /data uses "ext4". Running these tests in /data
546 // would be preferable and allow testing file attributes and symlinks.
547 // TODO(pauljensen): Re-enable when crbug.com/475568 is fixed and SetUp() places
548 // the |temp_dir_| in /data.
549 #if !defined(OS_ANDROID)
550 // Modify "$dir/subdir/subdir_child_dir/child_dir_file1" attributes.
551 ASSERT_TRUE(base::MakeFileUnreadable(child_dir_file1));
552 ASSERT_TRUE(WaitForEvents());
553 #endif
554
555 // Delete "$dir/subdir/subdir_file1".
556 ASSERT_TRUE(base::DeleteFile(subdir_file1, false));
557 ASSERT_TRUE(WaitForEvents());
558
559 // Delete "$dir/subdir/subdir_child_dir/child_dir_file1".
560 ASSERT_TRUE(base::DeleteFile(child_dir_file1, false));
561 ASSERT_TRUE(WaitForEvents());
562 DeleteDelegateOnFileThread(delegate.release());
563 }
564
565 #if defined(OS_POSIX)
566 #if defined(OS_ANDROID)
567 // Apps cannot create symlinks on Android in /sdcard as /sdcard uses the
568 // "fuse" file system, while /data uses "ext4". Running these tests in /data
569 // would be preferable and allow testing file attributes and symlinks.
570 // TODO(pauljensen): Re-enable when crbug.com/475568 is fixed and SetUp() places
571 // the |temp_dir_| in /data.
572 #define RecursiveWithSymLink DISABLED_RecursiveWithSymLink
573 #endif // defined(OS_ANDROID)
TEST_F(FilePathWatcherTest,RecursiveWithSymLink)574 TEST_F(FilePathWatcherTest, RecursiveWithSymLink) {
575 if (!FilePathWatcher::RecursiveWatchAvailable())
576 return;
577
578 FilePathWatcher watcher;
579 FilePath test_dir(temp_dir_.path().AppendASCII("test_dir"));
580 ASSERT_TRUE(base::CreateDirectory(test_dir));
581 FilePath symlink(test_dir.AppendASCII("symlink"));
582 scoped_ptr<TestDelegate> delegate(new TestDelegate(collector()));
583 ASSERT_TRUE(SetupWatch(symlink, &watcher, delegate.get(), true));
584
585 // Link creation.
586 FilePath target1(temp_dir_.path().AppendASCII("target1"));
587 ASSERT_TRUE(base::CreateSymbolicLink(target1, symlink));
588 ASSERT_TRUE(WaitForEvents());
589
590 // Target1 creation.
591 ASSERT_TRUE(base::CreateDirectory(target1));
592 ASSERT_TRUE(WaitForEvents());
593
594 // Create a file in target1.
595 FilePath target1_file(target1.AppendASCII("file"));
596 ASSERT_TRUE(WriteFile(target1_file, "content"));
597 ASSERT_TRUE(WaitForEvents());
598
599 // Link change.
600 FilePath target2(temp_dir_.path().AppendASCII("target2"));
601 ASSERT_TRUE(base::CreateDirectory(target2));
602 ASSERT_TRUE(base::DeleteFile(symlink, false));
603 ASSERT_TRUE(base::CreateSymbolicLink(target2, symlink));
604 ASSERT_TRUE(WaitForEvents());
605
606 // Create a file in target2.
607 FilePath target2_file(target2.AppendASCII("file"));
608 ASSERT_TRUE(WriteFile(target2_file, "content"));
609 ASSERT_TRUE(WaitForEvents());
610
611 DeleteDelegateOnFileThread(delegate.release());
612 }
613 #endif // OS_POSIX
614
TEST_F(FilePathWatcherTest,MoveChild)615 TEST_F(FilePathWatcherTest, MoveChild) {
616 FilePathWatcher file_watcher;
617 FilePathWatcher subdir_watcher;
618 FilePath source_dir(temp_dir_.path().AppendASCII("source"));
619 FilePath source_subdir(source_dir.AppendASCII("subdir"));
620 FilePath source_file(source_subdir.AppendASCII("file"));
621 FilePath dest_dir(temp_dir_.path().AppendASCII("dest"));
622 FilePath dest_subdir(dest_dir.AppendASCII("subdir"));
623 FilePath dest_file(dest_subdir.AppendASCII("file"));
624
625 // Setup a directory hierarchy.
626 ASSERT_TRUE(base::CreateDirectory(source_subdir));
627 ASSERT_TRUE(WriteFile(source_file, "content"));
628
629 scoped_ptr<TestDelegate> file_delegate(new TestDelegate(collector()));
630 ASSERT_TRUE(SetupWatch(dest_file, &file_watcher, file_delegate.get(), false));
631 scoped_ptr<TestDelegate> subdir_delegate(new TestDelegate(collector()));
632 ASSERT_TRUE(SetupWatch(dest_subdir, &subdir_watcher, subdir_delegate.get(),
633 false));
634
635 // Move the directory into place, s.t. the watched file appears.
636 ASSERT_TRUE(base::Move(source_dir, dest_dir));
637 ASSERT_TRUE(WaitForEvents());
638 DeleteDelegateOnFileThread(file_delegate.release());
639 DeleteDelegateOnFileThread(subdir_delegate.release());
640 }
641
642 // Verify that changing attributes on a file is caught
643 #if defined(OS_ANDROID)
644 // Apps cannot change file attributes on Android in /sdcard as /sdcard uses the
645 // "fuse" file system, while /data uses "ext4". Running these tests in /data
646 // would be preferable and allow testing file attributes and symlinks.
647 // TODO(pauljensen): Re-enable when crbug.com/475568 is fixed and SetUp() places
648 // the |temp_dir_| in /data.
649 #define FileAttributesChanged DISABLED_FileAttributesChanged
650 #endif // defined(OS_ANDROID
TEST_F(FilePathWatcherTest,FileAttributesChanged)651 TEST_F(FilePathWatcherTest, FileAttributesChanged) {
652 ASSERT_TRUE(WriteFile(test_file(), "content"));
653 FilePathWatcher watcher;
654 scoped_ptr<TestDelegate> delegate(new TestDelegate(collector()));
655 ASSERT_TRUE(SetupWatch(test_file(), &watcher, delegate.get(), false));
656
657 // Now make sure we get notified if the file is modified.
658 ASSERT_TRUE(base::MakeFileUnreadable(test_file()));
659 ASSERT_TRUE(WaitForEvents());
660 DeleteDelegateOnFileThread(delegate.release());
661 }
662
663 #if defined(OS_LINUX)
664
665 // Verify that creating a symlink is caught.
TEST_F(FilePathWatcherTest,CreateLink)666 TEST_F(FilePathWatcherTest, CreateLink) {
667 FilePathWatcher watcher;
668 scoped_ptr<TestDelegate> delegate(new TestDelegate(collector()));
669 // Note that we are watching the symlink
670 ASSERT_TRUE(SetupWatch(test_link(), &watcher, delegate.get(), false));
671
672 // Now make sure we get notified if the link is created.
673 // Note that test_file() doesn't have to exist.
674 ASSERT_TRUE(CreateSymbolicLink(test_file(), test_link()));
675 ASSERT_TRUE(WaitForEvents());
676 DeleteDelegateOnFileThread(delegate.release());
677 }
678
679 // Verify that deleting a symlink is caught.
TEST_F(FilePathWatcherTest,DeleteLink)680 TEST_F(FilePathWatcherTest, DeleteLink) {
681 // Unfortunately this test case only works if the link target exists.
682 // TODO(craig) fix this as part of crbug.com/91561.
683 ASSERT_TRUE(WriteFile(test_file(), "content"));
684 ASSERT_TRUE(CreateSymbolicLink(test_file(), test_link()));
685 FilePathWatcher watcher;
686 scoped_ptr<TestDelegate> delegate(new TestDelegate(collector()));
687 ASSERT_TRUE(SetupWatch(test_link(), &watcher, delegate.get(), false));
688
689 // Now make sure we get notified if the link is deleted.
690 ASSERT_TRUE(base::DeleteFile(test_link(), false));
691 ASSERT_TRUE(WaitForEvents());
692 DeleteDelegateOnFileThread(delegate.release());
693 }
694
695 // Verify that modifying a target file that a link is pointing to
696 // when we are watching the link is caught.
TEST_F(FilePathWatcherTest,ModifiedLinkedFile)697 TEST_F(FilePathWatcherTest, ModifiedLinkedFile) {
698 ASSERT_TRUE(WriteFile(test_file(), "content"));
699 ASSERT_TRUE(CreateSymbolicLink(test_file(), test_link()));
700 FilePathWatcher watcher;
701 scoped_ptr<TestDelegate> delegate(new TestDelegate(collector()));
702 // Note that we are watching the symlink.
703 ASSERT_TRUE(SetupWatch(test_link(), &watcher, delegate.get(), false));
704
705 // Now make sure we get notified if the file is modified.
706 ASSERT_TRUE(WriteFile(test_file(), "new content"));
707 ASSERT_TRUE(WaitForEvents());
708 DeleteDelegateOnFileThread(delegate.release());
709 }
710
711 // Verify that creating a target file that a link is pointing to
712 // when we are watching the link is caught.
TEST_F(FilePathWatcherTest,CreateTargetLinkedFile)713 TEST_F(FilePathWatcherTest, CreateTargetLinkedFile) {
714 ASSERT_TRUE(CreateSymbolicLink(test_file(), test_link()));
715 FilePathWatcher watcher;
716 scoped_ptr<TestDelegate> delegate(new TestDelegate(collector()));
717 // Note that we are watching the symlink.
718 ASSERT_TRUE(SetupWatch(test_link(), &watcher, delegate.get(), false));
719
720 // Now make sure we get notified if the target file is created.
721 ASSERT_TRUE(WriteFile(test_file(), "content"));
722 ASSERT_TRUE(WaitForEvents());
723 DeleteDelegateOnFileThread(delegate.release());
724 }
725
726 // Verify that deleting a target file that a link is pointing to
727 // when we are watching the link is caught.
TEST_F(FilePathWatcherTest,DeleteTargetLinkedFile)728 TEST_F(FilePathWatcherTest, DeleteTargetLinkedFile) {
729 ASSERT_TRUE(WriteFile(test_file(), "content"));
730 ASSERT_TRUE(CreateSymbolicLink(test_file(), test_link()));
731 FilePathWatcher watcher;
732 scoped_ptr<TestDelegate> delegate(new TestDelegate(collector()));
733 // Note that we are watching the symlink.
734 ASSERT_TRUE(SetupWatch(test_link(), &watcher, delegate.get(), false));
735
736 // Now make sure we get notified if the target file is deleted.
737 ASSERT_TRUE(base::DeleteFile(test_file(), false));
738 ASSERT_TRUE(WaitForEvents());
739 DeleteDelegateOnFileThread(delegate.release());
740 }
741
742 // Verify that watching a file whose parent directory is a link that
743 // doesn't exist yet works if the symlink is created eventually.
TEST_F(FilePathWatcherTest,LinkedDirectoryPart1)744 TEST_F(FilePathWatcherTest, LinkedDirectoryPart1) {
745 FilePathWatcher watcher;
746 FilePath dir(temp_dir_.path().AppendASCII("dir"));
747 FilePath link_dir(temp_dir_.path().AppendASCII("dir.lnk"));
748 FilePath file(dir.AppendASCII("file"));
749 FilePath linkfile(link_dir.AppendASCII("file"));
750 scoped_ptr<TestDelegate> delegate(new TestDelegate(collector()));
751 // dir/file should exist.
752 ASSERT_TRUE(base::CreateDirectory(dir));
753 ASSERT_TRUE(WriteFile(file, "content"));
754 // Note that we are watching dir.lnk/file which doesn't exist yet.
755 ASSERT_TRUE(SetupWatch(linkfile, &watcher, delegate.get(), false));
756
757 ASSERT_TRUE(CreateSymbolicLink(dir, link_dir));
758 VLOG(1) << "Waiting for link creation";
759 ASSERT_TRUE(WaitForEvents());
760
761 ASSERT_TRUE(WriteFile(file, "content v2"));
762 VLOG(1) << "Waiting for file change";
763 ASSERT_TRUE(WaitForEvents());
764
765 ASSERT_TRUE(base::DeleteFile(file, false));
766 VLOG(1) << "Waiting for file deletion";
767 ASSERT_TRUE(WaitForEvents());
768 DeleteDelegateOnFileThread(delegate.release());
769 }
770
771 // Verify that watching a file whose parent directory is a
772 // dangling symlink works if the directory is created eventually.
TEST_F(FilePathWatcherTest,LinkedDirectoryPart2)773 TEST_F(FilePathWatcherTest, LinkedDirectoryPart2) {
774 FilePathWatcher watcher;
775 FilePath dir(temp_dir_.path().AppendASCII("dir"));
776 FilePath link_dir(temp_dir_.path().AppendASCII("dir.lnk"));
777 FilePath file(dir.AppendASCII("file"));
778 FilePath linkfile(link_dir.AppendASCII("file"));
779 scoped_ptr<TestDelegate> delegate(new TestDelegate(collector()));
780 // Now create the link from dir.lnk pointing to dir but
781 // neither dir nor dir/file exist yet.
782 ASSERT_TRUE(CreateSymbolicLink(dir, link_dir));
783 // Note that we are watching dir.lnk/file.
784 ASSERT_TRUE(SetupWatch(linkfile, &watcher, delegate.get(), false));
785
786 ASSERT_TRUE(base::CreateDirectory(dir));
787 ASSERT_TRUE(WriteFile(file, "content"));
788 VLOG(1) << "Waiting for dir/file creation";
789 ASSERT_TRUE(WaitForEvents());
790
791 ASSERT_TRUE(WriteFile(file, "content v2"));
792 VLOG(1) << "Waiting for file change";
793 ASSERT_TRUE(WaitForEvents());
794
795 ASSERT_TRUE(base::DeleteFile(file, false));
796 VLOG(1) << "Waiting for file deletion";
797 ASSERT_TRUE(WaitForEvents());
798 DeleteDelegateOnFileThread(delegate.release());
799 }
800
801 // Verify that watching a file with a symlink on the path
802 // to the file works.
TEST_F(FilePathWatcherTest,LinkedDirectoryPart3)803 TEST_F(FilePathWatcherTest, LinkedDirectoryPart3) {
804 FilePathWatcher watcher;
805 FilePath dir(temp_dir_.path().AppendASCII("dir"));
806 FilePath link_dir(temp_dir_.path().AppendASCII("dir.lnk"));
807 FilePath file(dir.AppendASCII("file"));
808 FilePath linkfile(link_dir.AppendASCII("file"));
809 scoped_ptr<TestDelegate> delegate(new TestDelegate(collector()));
810 ASSERT_TRUE(base::CreateDirectory(dir));
811 ASSERT_TRUE(CreateSymbolicLink(dir, link_dir));
812 // Note that we are watching dir.lnk/file but the file doesn't exist yet.
813 ASSERT_TRUE(SetupWatch(linkfile, &watcher, delegate.get(), false));
814
815 ASSERT_TRUE(WriteFile(file, "content"));
816 VLOG(1) << "Waiting for file creation";
817 ASSERT_TRUE(WaitForEvents());
818
819 ASSERT_TRUE(WriteFile(file, "content v2"));
820 VLOG(1) << "Waiting for file change";
821 ASSERT_TRUE(WaitForEvents());
822
823 ASSERT_TRUE(base::DeleteFile(file, false));
824 VLOG(1) << "Waiting for file deletion";
825 ASSERT_TRUE(WaitForEvents());
826 DeleteDelegateOnFileThread(delegate.release());
827 }
828
829 #endif // OS_LINUX
830
831 enum Permission {
832 Read,
833 Write,
834 Execute
835 };
836
837 #if defined(OS_MACOSX)
ChangeFilePermissions(const FilePath & path,Permission perm,bool allow)838 bool ChangeFilePermissions(const FilePath& path, Permission perm, bool allow) {
839 struct stat stat_buf;
840
841 if (stat(path.value().c_str(), &stat_buf) != 0)
842 return false;
843
844 mode_t mode = 0;
845 switch (perm) {
846 case Read:
847 mode = S_IRUSR | S_IRGRP | S_IROTH;
848 break;
849 case Write:
850 mode = S_IWUSR | S_IWGRP | S_IWOTH;
851 break;
852 case Execute:
853 mode = S_IXUSR | S_IXGRP | S_IXOTH;
854 break;
855 default:
856 ADD_FAILURE() << "unknown perm " << perm;
857 return false;
858 }
859 if (allow) {
860 stat_buf.st_mode |= mode;
861 } else {
862 stat_buf.st_mode &= ~mode;
863 }
864 return chmod(path.value().c_str(), stat_buf.st_mode) == 0;
865 }
866 #endif // defined(OS_MACOSX)
867
868 #if defined(OS_MACOSX)
869 // Linux implementation of FilePathWatcher doesn't catch attribute changes.
870 // http://crbug.com/78043
871 // Windows implementation of FilePathWatcher catches attribute changes that
872 // don't affect the path being watched.
873 // http://crbug.com/78045
874
875 // Verify that changing attributes on a directory works.
TEST_F(FilePathWatcherTest,DirAttributesChanged)876 TEST_F(FilePathWatcherTest, DirAttributesChanged) {
877 FilePath test_dir1(temp_dir_.path().AppendASCII("DirAttributesChangedDir1"));
878 FilePath test_dir2(test_dir1.AppendASCII("DirAttributesChangedDir2"));
879 FilePath test_file(test_dir2.AppendASCII("DirAttributesChangedFile"));
880 // Setup a directory hierarchy.
881 ASSERT_TRUE(base::CreateDirectory(test_dir1));
882 ASSERT_TRUE(base::CreateDirectory(test_dir2));
883 ASSERT_TRUE(WriteFile(test_file, "content"));
884
885 FilePathWatcher watcher;
886 scoped_ptr<TestDelegate> delegate(new TestDelegate(collector()));
887 ASSERT_TRUE(SetupWatch(test_file, &watcher, delegate.get(), false));
888
889 // We should not get notified in this case as it hasn't affected our ability
890 // to access the file.
891 ASSERT_TRUE(ChangeFilePermissions(test_dir1, Read, false));
892 loop_.PostDelayedTask(FROM_HERE,
893 MessageLoop::QuitWhenIdleClosure(),
894 TestTimeouts::tiny_timeout());
895 ASSERT_FALSE(WaitForEvents());
896 ASSERT_TRUE(ChangeFilePermissions(test_dir1, Read, true));
897
898 // We should get notified in this case because filepathwatcher can no
899 // longer access the file
900 ASSERT_TRUE(ChangeFilePermissions(test_dir1, Execute, false));
901 ASSERT_TRUE(WaitForEvents());
902 ASSERT_TRUE(ChangeFilePermissions(test_dir1, Execute, true));
903 DeleteDelegateOnFileThread(delegate.release());
904 }
905
906 #endif // OS_MACOSX
907 } // namespace
908
909 } // namespace base
910