Files
EchoionCore/tests/test_log_rotation.cpp

83 lines
2.1 KiB
C++

#include "echoion/core/LogRotation.hpp"
#include <filesystem>
#include <fstream>
#include <iostream>
#include <string_view>
namespace
{
int failures = 0;
void expect(bool condition, std::string_view message)
{
if (!condition) {
std::cerr << "FAILED: " << message << '\n';
++failures;
}
}
std::size_t archiveCount(const std::filesystem::path& history)
{
std::size_t count = 0;
std::error_code error;
for (std::filesystem::directory_iterator iterator(history, error), end;
!error && iterator != end; iterator.increment(error)) {
if (iterator->is_regular_file()) {
++count;
}
}
return count;
}
} // namespace
int main()
{
const auto root =
std::filesystem::temp_directory_path() / "echoion-log-rotation-test";
std::error_code error;
std::filesystem::remove_all(root, error);
std::filesystem::create_directories(root, error);
const auto active = root / "echoion.log";
{
std::ofstream file(active);
file << "first run\n";
}
error = Echoion::Core::rotateLogOnStartup(active, 2);
expect(!error, "first startup rotation succeeds");
expect(!std::filesystem::exists(active),
"startup rotation leaves no old active file");
expect(archiveCount(root / "history") == 1, "first run is archived");
for (int run = 0; run < 3; ++run) {
{
std::ofstream file(active);
file << "run " << run << '\n';
}
error = Echoion::Core::rotateLogOnStartup(active, 2);
expect(!error, "subsequent startup rotation succeeds");
}
expect(archiveCount(root / "history") == 2,
"startup rotation prunes to configured history count");
{
std::ofstream file(active);
}
error = Echoion::Core::rotateLogOnStartup(active, 2);
expect(!error && !std::filesystem::exists(active),
"empty active file is removed instead of archived");
std::filesystem::remove_all(root / "history", error);
{
std::ofstream invalidHistory(root / "history");
invalidHistory << "not a directory\n";
}
error = Echoion::Core::rotateLogOnStartup(active, 2);
expect(error == std::errc::invalid_argument,
"non-directory history path was accepted");
std::filesystem::remove_all(root, error);
return failures == 0 ? 0 : 1;
}