Files
iZo/tests/directory_watcher.cpp

72 lines
2.5 KiB
C++
Raw Permalink Normal View History

#include "test_support.hpp"
#include <izo/DirectoryWatcher.hpp>
#include <algorithm>
#include <fstream>
#include <mutex>
#include <vector>
int main() {
std::string error;
CHECK(!izo::WatchDirectory({"/izo/missing", false}, [](const auto&) {}, &error));
CHECK(!error.empty());
error.clear();
const auto directory = test_directory("watcher");
CHECK(!izo::WatchDirectory({directory, false}, {}, &error));
CHECK(!error.empty());
error.clear();
CHECK(!izo::WatchDirectory({directory, false, std::chrono::milliseconds(0)},
[](const auto&) {}, &error));
std::mutex mutex;
std::vector<izo::FileEvent> events;
auto watcher = izo::WatchDirectory(
{directory, true, std::chrono::milliseconds(10)},
[&](const izo::FileEvent& event) {
std::lock_guard<std::mutex> lock(mutex);
events.push_back(event);
}, &error);
CHECK(watcher);
std::this_thread::sleep_for(std::chrono::milliseconds(50));
const auto original = directory / "original.txt";
const auto renamed = directory / "renamed.txt";
{ std::ofstream file(original); file << "a"; }
CHECK(wait_until([&] {
std::lock_guard<std::mutex> lock(mutex);
return std::any_of(events.begin(), events.end(), [&](const auto& event) {
return event.change == izo::FileChange::Added && event.path == original;
});
}));
{ std::ofstream file(original, std::ios::app); file << "more"; }
CHECK(wait_until([&] {
std::lock_guard<std::mutex> lock(mutex);
return std::any_of(events.begin(), events.end(), [&](const auto& event) {
return event.change == izo::FileChange::Modified && event.path == original;
});
}));
std::filesystem::rename(original, renamed);
CHECK(wait_until([&] {
std::lock_guard<std::mutex> lock(mutex);
return std::any_of(events.begin(), events.end(), [&](const auto& event) {
return event.change == izo::FileChange::Renamed && event.path == renamed &&
event.previousPath == original;
});
}));
std::filesystem::remove(renamed);
CHECK(wait_until([&] {
std::lock_guard<std::mutex> lock(mutex);
return std::any_of(events.begin(), events.end(), [&](const auto& event) {
return event.change == izo::FileChange::Removed && event.path == renamed;
});
}));
watcher.Stop();
CHECK(!watcher);
std::filesystem::remove_all(directory);
}