TestLibCoreFileWatcher.cpp 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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. TEST_CASE(file_watcher_child_events)
  14. {
  15. auto event_loop = Core::EventLoop();
  16. auto maybe_file_watcher = Core::FileWatcher::create();
  17. EXPECT_NE(maybe_file_watcher.is_error(), true);
  18. auto file_watcher = maybe_file_watcher.release_value();
  19. auto watch_result = file_watcher->add_watch("/tmp/",
  20. Core::FileWatcherEvent::Type::ChildCreated
  21. | Core::FileWatcherEvent::Type::ChildDeleted);
  22. EXPECT_NE(watch_result.is_error(), true);
  23. int event_count = 0;
  24. file_watcher->on_change = [&](Core::FileWatcherEvent const& event) {
  25. if (event_count == 0) {
  26. EXPECT_EQ(event.event_path, "/tmp/testfile");
  27. EXPECT_EQ(event.type, Core::FileWatcherEvent::Type::ChildCreated);
  28. } else if (event_count == 1) {
  29. EXPECT_EQ(event.event_path, "/tmp/testfile");
  30. EXPECT_EQ(event.type, Core::FileWatcherEvent::Type::ChildDeleted);
  31. event_loop.quit(0);
  32. }
  33. event_count++;
  34. };
  35. auto timer1 = MUST(Core::Timer::create_single_shot(500, [&] {
  36. int rc = creat("/tmp/testfile", 0777);
  37. EXPECT_NE(rc, -1);
  38. }));
  39. timer1->start();
  40. auto timer2 = MUST(Core::Timer::create_single_shot(1000, [&] {
  41. int rc = unlink("/tmp/testfile");
  42. EXPECT_NE(rc, -1);
  43. }));
  44. timer2->start();
  45. auto catchall_timer = MUST(Core::Timer::create_single_shot(2000, [&] {
  46. VERIFY_NOT_REACHED();
  47. }));
  48. catchall_timer->start();
  49. event_loop.exec();
  50. }