From 6d63aa72d7e423d4a5091abaab3a4a91a4e47b78 Mon Sep 17 00:00:00 2001 From: Lutz Justen Date: Fri, 2 Dec 2022 13:03:20 +0100 Subject: [PATCH] [common] Fix FileWatcherTest (#37) There is a race condition in RecreateWatchedDir where there was a brief period between the second dir change event and when the file watcher was actually watching again. If the file was written during that bried period, it would be missed. The issue could be reproduced easily by adding a sleep here: // The watched directory exists and its handle is valid. if (!first_run) { ++dir_recreate_count_; if (dir_recreated_cb_) dir_recreated_cb_(); Util::Sleep(1); } This CL waits until the watcher is watching again. --- common/file_watcher_win_test.cc | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/common/file_watcher_win_test.cc b/common/file_watcher_win_test.cc index c587026..f2653fd 100644 --- a/common/file_watcher_win_test.cc +++ b/common/file_watcher_win_test.cc @@ -135,6 +135,15 @@ class FileWatcherParameterizedTest : public ::testing::TestWithParam { return changed; } + // Polls for a second until the watcher is watching again. + bool WaitForWatching() const { + for (int n = 0; n < 1000; ++n) { + if (watcher_.IsWatching()) return true; + Util::Sleep(1); + } + return false; + } + FileMap GetChangedFiles(size_t number_of_files) { FileMap modified_files; @@ -540,6 +549,9 @@ TEST_P(FileWatcherParameterizedTest, RecreateWatchedDir) { EXPECT_TRUE(watcher_.GetModifiedFiles().empty()); EXPECT_OK(watcher_.GetStatus()); + // Wait until the watcher is watching again, or else we might miss the file. + EXPECT_TRUE(WaitForWatching()); + // Creation of a new file should be detected. EXPECT_OK(path::WriteFile(first_file_path_, kFirstData, kFirstDataSize)); @@ -572,6 +584,9 @@ TEST_P(FileWatcherParameterizedTest, RecreateUpperDir) { EXPECT_TRUE(watcher_.GetModifiedFiles().empty()); EXPECT_OK(watcher_.GetStatus()); + // Wait until the watcher is watching again, or else we might miss the file. + EXPECT_TRUE(WaitForWatching()); + // Creation of a new file should be detected. EXPECT_OK(path::WriteFile(first_file_path_, kFirstData, kFirstDataSize));