TestLibCoreFileWatcher.cpp 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /*
  2. * Copyright (c) 2021, the SerenityOS developers.
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <Kernel/API/InodeWatcherEvent.h>
  7. #include <LibCore/EventLoop.h>
  8. #include <LibCore/FileWatcher.h>
  9. #include <LibCore/Timer.h>
  10. #include <LibTest/TestCase.h>
  11. #include <fcntl.h>
  12. #include <unistd.h>
  13. // FIXME: Figure out why this breaks on macOS.
  14. #ifndef AK_OS_MACOS
  15. TEST_CASE(file_watcher_child_events)
  16. {
  17. auto event_loop = Core::EventLoop();
  18. auto maybe_file_watcher = Core::FileWatcher::create();
  19. EXPECT_NE(maybe_file_watcher.is_error(), true);
  20. auto file_watcher = maybe_file_watcher.release_value();
  21. auto watch_result = file_watcher->add_watch("/tmp/",
  22. Core::FileWatcherEvent::Type::ChildCreated
  23. | Core::FileWatcherEvent::Type::ChildDeleted);
  24. EXPECT_NE(watch_result.is_error(), true);
  25. int event_count = 0;
  26. file_watcher->on_change = [&](Core::FileWatcherEvent const& event) {
  27. // Ignore path events under /tmp that can occur for anything else the OS is
  28. // doing to create/delete files there.
  29. if (event.event_path != "/tmp/testfile"sv)
  30. return;
  31. if (event_count == 0) {
  32. EXPECT(has_flag(event.type, Core::FileWatcherEvent::Type::ChildCreated));
  33. } else if (event_count == 1) {
  34. EXPECT(has_flag(event.type, Core::FileWatcherEvent::Type::ChildDeleted));
  35. EXPECT(MUST(file_watcher->remove_watch("/tmp/"sv)));
  36. event_loop.quit(0);
  37. }
  38. event_count++;
  39. };
  40. auto timer1 = MUST(Core::Timer::create_single_shot(500, [&] {
  41. int rc = creat("/tmp/testfile", 0777);
  42. EXPECT_NE(rc, -1);
  43. }));
  44. timer1->start();
  45. auto timer2 = MUST(Core::Timer::create_single_shot(1000, [&] {
  46. int rc = unlink("/tmp/testfile");
  47. EXPECT_NE(rc, -1);
  48. }));
  49. timer2->start();
  50. auto catchall_timer = MUST(Core::Timer::create_single_shot(2000, [&] {
  51. VERIFY_NOT_REACHED();
  52. }));
  53. catchall_timer->start();
  54. event_loop.exec();
  55. }
  56. #endif