Files
Library/tests/standalone/Configuration/Bind.cpp
T

88 lines
2.6 KiB
C++

// @requires-reflection
#include <Void/Configuration/Bind.hpp>
#include <Void/Configuration/Config.hpp>
#include <Void/Testing/Assert.hpp>
#include <Void/Testing/Test.hpp>
#include <chrono>
#include <optional>
#include <string>
#include <vector>
#ifdef VOID_HAS_CONFIG_REFLECTION
using Void::Configuration::Config;
namespace
{
enum class Sink { Console, File };
struct FileSettings {
std::string path = "default.log";
int max_files = 3;
};
struct LogSettings {
std::string level = "info";
bool async = true;
Sink sink = Sink::Console;
std::chrono::milliseconds flush_every{250};
FileSettings file;
std::optional<int> sample_rate;
std::vector<std::string> tags;
};
} // namespace
Void::Testing::Test bind_fills_present_keys_keeps_defaults()
{
Config cfg;
cfg.set("log.level", "debug");
cfg.set("log.file.path", "/var/log/app.log");
cfg.set("log.flush_every", "1s");
const auto s = Void::Configuration::bind<LogSettings>(cfg, "log");
Void::Testing::expect(s.has_value());
Void::Testing::expect_eq(s->level, std::string{"debug"});
Void::Testing::expect(s->async); // default kept
Void::Testing::expect_eq(s->file.path, std::string{"/var/log/app.log"});
Void::Testing::expect_eq(s->file.max_files, 3); // nested default kept
Void::Testing::expect(s->flush_every ==
std::chrono::milliseconds{1000});
}
Void::Testing::Test bind_enum_optional_vector()
{
Config cfg;
cfg.set("log.sink", "File");
cfg.set("log.sample_rate", "10");
cfg.set("log.tags.0", "alpha");
cfg.set("log.tags.1", "beta");
const auto s = Void::Configuration::bind<LogSettings>(cfg, "log");
Void::Testing::expect(s.has_value());
Void::Testing::expect(s->sink == Sink::File);
Void::Testing::expect(s->sample_rate.has_value());
Void::Testing::expect_eq(*s->sample_rate, 10);
Void::Testing::expect_eq(s->tags.size(), std::size_t{2});
Void::Testing::expect_eq(s->tags[1], std::string{"beta"});
}
Void::Testing::Test bind_reports_conversion_errors()
{
Config cfg;
cfg.set("log.async", "not-a-bool");
const auto s = Void::Configuration::bind<LogSettings>(cfg, "log");
Void::Testing::expect(!s.has_value());
}
Void::Testing::Test bind_empty_prefix_binds_root_keys()
{
Config cfg;
cfg.set("path", "root.log");
const auto s = Void::Configuration::bind<FileSettings>(cfg);
Void::Testing::expect(s.has_value());
Void::Testing::expect_eq(s->path, std::string{"root.log"});
}
#endif // VOID_HAS_CONFIG_REFLECTION