Files
Library/tests/standalone/Logging/FileLogger.cpp
T
faumaray e7186f17f0 Testing module
Signed-off-by: faumaray <faumaray@gmail.com>
2026-04-29 22:49:33 +03:00

128 lines
3.0 KiB
C++

#include <Void/Logging/Logger.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Fixture.hpp>
#include <Void/Testing/Test.hpp>
#include <filesystem>
#include <format>
#include <fstream>
#include <span>
#include <stdexcept>
#include <string>
namespace
{
class FileLogger final : public Void::Logging::Logger
{
public:
explicit FileLogger(const std::filesystem::path &path,
std::size_t capacity = 64)
: Logger(Void::Logging::Mode::Buffered, capacity),
m_file(path, std::ios::app)
{
if (!m_file.is_open())
throw std::runtime_error(
std::format("FileLogger: cannot open '{}'",
path.string()));
}
~FileLogger() noexcept override { flush(); }
FileLogger(const FileLogger &) = delete;
FileLogger &operator=(const FileLogger &) = delete;
FileLogger(FileLogger &&) = delete;
FileLogger &operator=(FileLogger &&) = delete;
protected:
void on_flush(
std::span<const Void::Logging::Entry> entries) override
{
for (const auto &e : entries)
m_file << std::format("[{}] {}\n",
Void::Logging::to_string(e.level),
e.message);
m_file.flush();
}
void write(const Void::Logging::Entry &entry) override
{
m_file << std::format("[{}] {}\n",
Void::Logging::to_string(entry.level),
entry.message);
m_file.flush();
}
private:
std::ofstream m_file;
};
} // namespace
class FileLoggerTests : public Void::Testing::Fixture
{
public:
std::filesystem::path path;
void setup() override
{
path = std::filesystem::temp_directory_path()
/ "void_filelogger_test.log";
std::filesystem::remove(path);
}
void teardown() override { std::filesystem::remove(path); }
Void::Testing::Test creates_file()
{
{
FileLogger log(path);
log.info("hello");
}
Void::Testing::expect(std::filesystem::exists(path));
}
Void::Testing::Test writes_messages()
{
{
FileLogger log(path, /*capacity=*/1);
log.info("test message");
}
std::ifstream f(path);
std::string content((std::istreambuf_iterator<char>(f)), {});
Void::Testing::expect(content.find("test message")
!= std::string::npos);
}
Void::Testing::Test level_filtering()
{
{
FileLogger log(path, /*capacity=*/1);
log.set_level(Void::Logging::Level::Warning);
log.debug("should be dropped");
log.warning("should appear");
}
std::ifstream f(path);
std::string content((std::istreambuf_iterator<char>(f)), {});
Void::Testing::expect(content.find("should be dropped")
== std::string::npos);
Void::Testing::expect(content.find("should appear")
!= std::string::npos);
}
Void::Testing::Test buffered_flush()
{
{
FileLogger log(path, /*capacity=*/100);
for (int i = 0; i < 5; ++i)
log.info(std::format("entry {}", i));
}
std::ifstream f(path);
std::string content((std::istreambuf_iterator<char>(f)), {});
Void::Testing::expect(content.find("entry 4")
!= std::string::npos);
}
};