use std::fmt;
use std::path::PathBuf;
use serde::de::{self, Deserializer, Visitor};
use serde::Deserialize;
use super::types::{Config, FailOn, LogFormat, LogLevel};
pub(crate) const FILE_CONFIG_OVERLAY_KEYS: &[&str] = &[
"file",
"log_level",
"log_format",
"db_path",
"max_concurrency",
"timeout_seconds",
"user_agent",
"rate_limit_rps",
"fingerprints",
"geoip",
"status_port",
"enable_whois",
"cache_dir",
"scan_external_scripts",
"fail_on",
"fail_on_pct_threshold",
"log_file",
"drain_timeout_secs",
];
#[derive(Debug, Clone, Default, PartialEq, Eq, Deserialize)]
pub struct FileConfig {
pub file: Option<PathBuf>,
#[serde(default, deserialize_with = "deserialize_option_log_level")]
pub log_level: Option<LogLevel>,
#[serde(default, deserialize_with = "deserialize_option_log_format")]
pub log_format: Option<LogFormat>,
pub db_path: Option<PathBuf>,
pub max_concurrency: Option<usize>,
pub timeout_seconds: Option<u64>,
pub user_agent: Option<String>,
pub rate_limit_rps: Option<u32>,
pub fingerprints: Option<String>,
pub geoip: Option<String>,
pub status_port: Option<u16>,
#[serde(default, deserialize_with = "deserialize_option_bool")]
pub enable_whois: Option<bool>,
pub cache_dir: Option<PathBuf>,
#[serde(default, deserialize_with = "deserialize_option_bool")]
pub scan_external_scripts: Option<bool>,
#[serde(default, deserialize_with = "deserialize_option_fail_on")]
pub fail_on: Option<FailOn>,
pub fail_on_pct_threshold: Option<u8>,
pub log_file: Option<PathBuf>,
pub drain_timeout_secs: Option<u64>,
}
fn parse_log_level(s: &str) -> Option<LogLevel> {
match s.to_lowercase().as_str() {
"error" => Some(LogLevel::Error),
"warn" => Some(LogLevel::Warn),
"info" => Some(LogLevel::Info),
"debug" => Some(LogLevel::Debug),
"trace" => Some(LogLevel::Trace),
_ => None,
}
}
fn parse_log_format(s: &str) -> Option<LogFormat> {
match s.to_lowercase().as_str() {
"plain" => Some(LogFormat::Plain),
"json" => Some(LogFormat::Json),
_ => None,
}
}
fn parse_fail_on(s: &str) -> Option<FailOn> {
match s.to_lowercase().as_str() {
"never" => Some(FailOn::Never),
"any-failure" | "any_failure" | "anyfailure" => Some(FailOn::AnyFailure),
"pct>" => Some(FailOn::PctGreaterThan),
_ => None,
}
}
fn parse_bool(s: &str) -> Option<bool> {
match s.trim().to_lowercase().as_str() {
"true" | "1" | "yes" | "on" => Some(true),
"false" | "0" | "no" | "off" => Some(false),
_ => None,
}
}
fn deserialize_option_bool<'de, D>(deserializer: D) -> Result<Option<bool>, D::Error>
where
D: Deserializer<'de>,
{
struct OptBoolVisitor;
impl<'de> Visitor<'de> for OptBoolVisitor {
type Value = Option<bool>;
fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("a boolean or bool-like string (true/false, 1/0, yes/no, on/off)")
}
fn visit_bool<E: de::Error>(self, v: bool) -> Result<Self::Value, E> {
Ok(Some(v))
}
fn visit_str<E: de::Error>(self, v: &str) -> Result<Self::Value, E> {
parse_bool(v)
.map(Some)
.ok_or_else(|| E::custom(format!("invalid boolean value: {v:?}")))
}
fn visit_string<E: de::Error>(self, v: String) -> Result<Self::Value, E> {
self.visit_str(&v)
}
fn visit_u64<E: de::Error>(self, v: u64) -> Result<Self::Value, E> {
match v {
0 => Ok(Some(false)),
1 => Ok(Some(true)),
_ => Err(E::custom(format!("invalid boolean integer: {v}"))),
}
}
fn visit_i64<E: de::Error>(self, v: i64) -> Result<Self::Value, E> {
match v {
0 => Ok(Some(false)),
1 => Ok(Some(true)),
_ => Err(E::custom(format!("invalid boolean integer: {v}"))),
}
}
fn visit_unit<E: de::Error>(self) -> Result<Self::Value, E> {
Ok(None)
}
fn visit_none<E: de::Error>(self) -> Result<Self::Value, E> {
Ok(None)
}
fn visit_some<D2: Deserializer<'de>>(
self,
deserializer: D2,
) -> Result<Self::Value, D2::Error> {
deserializer.deserialize_any(OptBoolVisitor)
}
}
deserializer.deserialize_any(OptBoolVisitor)
}
fn deserialize_option_fail_on<'de, D>(deserializer: D) -> Result<Option<FailOn>, D::Error>
where
D: Deserializer<'de>,
{
struct OptFailOnVisitor;
impl<'de> Visitor<'de> for OptFailOnVisitor {
type Value = Option<FailOn>;
fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("fail_on: never | any-failure | any_failure | pct>")
}
fn visit_str<E: de::Error>(self, v: &str) -> Result<Self::Value, E> {
parse_fail_on(v)
.map(Some)
.ok_or_else(|| E::custom(format!("invalid fail_on value: {v:?}")))
}
fn visit_string<E: de::Error>(self, v: String) -> Result<Self::Value, E> {
self.visit_str(&v)
}
fn visit_unit<E: de::Error>(self) -> Result<Self::Value, E> {
Ok(None)
}
fn visit_none<E: de::Error>(self) -> Result<Self::Value, E> {
Ok(None)
}
fn visit_some<D2: Deserializer<'de>>(
self,
deserializer: D2,
) -> Result<Self::Value, D2::Error> {
deserializer.deserialize_any(OptFailOnVisitor)
}
}
deserializer.deserialize_any(OptFailOnVisitor)
}
fn deserialize_option_log_level<'de, D>(deserializer: D) -> Result<Option<LogLevel>, D::Error>
where
D: Deserializer<'de>,
{
struct OptLogLevelVisitor;
impl<'de> Visitor<'de> for OptLogLevelVisitor {
type Value = Option<LogLevel>;
fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("log_level: error | warn | info | debug | trace")
}
fn visit_str<E: de::Error>(self, v: &str) -> Result<Self::Value, E> {
parse_log_level(v)
.map(Some)
.ok_or_else(|| E::custom(format!("invalid log_level value: {v:?}")))
}
fn visit_string<E: de::Error>(self, v: String) -> Result<Self::Value, E> {
self.visit_str(&v)
}
fn visit_unit<E: de::Error>(self) -> Result<Self::Value, E> {
Ok(None)
}
fn visit_none<E: de::Error>(self) -> Result<Self::Value, E> {
Ok(None)
}
fn visit_some<D2: Deserializer<'de>>(
self,
deserializer: D2,
) -> Result<Self::Value, D2::Error> {
deserializer.deserialize_any(OptLogLevelVisitor)
}
}
deserializer.deserialize_any(OptLogLevelVisitor)
}
fn deserialize_option_log_format<'de, D>(deserializer: D) -> Result<Option<LogFormat>, D::Error>
where
D: Deserializer<'de>,
{
struct OptLogFormatVisitor;
impl<'de> Visitor<'de> for OptLogFormatVisitor {
type Value = Option<LogFormat>;
fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
f.write_str("log_format: plain | json")
}
fn visit_str<E: de::Error>(self, v: &str) -> Result<Self::Value, E> {
parse_log_format(v)
.map(Some)
.ok_or_else(|| E::custom(format!("invalid log_format value: {v:?}")))
}
fn visit_string<E: de::Error>(self, v: String) -> Result<Self::Value, E> {
self.visit_str(&v)
}
fn visit_unit<E: de::Error>(self) -> Result<Self::Value, E> {
Ok(None)
}
fn visit_none<E: de::Error>(self) -> Result<Self::Value, E> {
Ok(None)
}
fn visit_some<D2: Deserializer<'de>>(
self,
deserializer: D2,
) -> Result<Self::Value, D2::Error> {
deserializer.deserialize_any(OptLogFormatVisitor)
}
}
deserializer.deserialize_any(OptLogFormatVisitor)
}
pub fn apply_file_config(config: &mut Config, file: &FileConfig) {
if let Some(ref path) = file.file {
config.file.clone_from(path);
}
if let Some(ref path) = file.db_path {
config.db_path.clone_from(path);
}
if let Some(ref path) = file.log_file {
config.log_file = Some(path.clone());
}
if let Some(ref lvl) = file.log_level {
config.log_level = lvl.clone();
}
if let Some(fmt) = file.log_format {
config.log_format = fmt;
}
if let Some(n) = file.max_concurrency {
config.max_concurrency = n;
}
if let Some(n) = file.timeout_seconds {
config.timeout_seconds = n;
}
if let Some(n) = file.drain_timeout_secs {
config.drain_timeout_secs = n;
}
if let Some(ref ua) = file.user_agent {
config.user_agent.clone_from(ua);
}
if let Some(n) = file.rate_limit_rps {
config.rate_limit_rps = n;
}
if let Some(ref fp) = file.fingerprints {
config.fingerprints = Some(fp.clone());
}
if let Some(ref geo) = file.geoip {
config.geoip = Some(geo.clone());
}
if let Some(n) = file.status_port {
config.status_port = Some(n);
}
if let Some(b) = file.enable_whois {
config.enable_whois = b;
}
if let Some(ref path) = file.cache_dir {
config.cache_dir = Some(path.clone());
}
if let Some(b) = file.scan_external_scripts {
config.scan_external_scripts = b;
}
if let Some(ref f) = file.fail_on {
config.fail_on = f.clone();
}
if let Some(n) = file.fail_on_pct_threshold {
config.fail_on_pct_threshold = n;
}
}
#[must_use]
pub fn merge_file_and_cli(
file: Option<&FileConfig>,
cli_config: Config,
cli_explicit: Option<&[&str]>,
) -> Config {
let overwrite = |key: &str| -> bool { cli_explicit.is_none_or(|keys| keys.contains(&key)) };
let mut config = Config::default();
if let Some(file) = file {
apply_file_config(&mut config, file);
}
if overwrite("file") {
config.file = cli_config.file;
}
if overwrite("log_level") {
config.log_level = cli_config.log_level;
}
if overwrite("log_level_filter_override") {
config.log_level_filter_override = cli_config.log_level_filter_override;
}
if overwrite("log_format") {
config.log_format = cli_config.log_format;
}
if overwrite("db_path") {
config.db_path = cli_config.db_path;
}
if overwrite("max_concurrency") {
config.max_concurrency = cli_config.max_concurrency;
}
if overwrite("timeout_seconds") {
config.timeout_seconds = cli_config.timeout_seconds;
}
if overwrite("user_agent") {
config.user_agent = cli_config.user_agent;
}
if overwrite("rate_limit_rps") {
config.rate_limit_rps = cli_config.rate_limit_rps;
}
if overwrite("fingerprints") {
config.fingerprints = cli_config.fingerprints;
}
if overwrite("geoip") {
config.geoip = cli_config.geoip;
}
if overwrite("status_port") {
config.status_port = cli_config.status_port;
}
if overwrite("enable_whois") {
config.enable_whois = cli_config.enable_whois;
}
if overwrite("no_whois") {
config.enable_whois = false;
}
if overwrite("cache_dir") {
config.cache_dir = cli_config.cache_dir;
}
if overwrite("scan_external_scripts") {
config.scan_external_scripts = cli_config.scan_external_scripts;
}
if overwrite("fail_on") {
config.fail_on = cli_config.fail_on;
}
if overwrite("fail_on_pct_threshold") {
config.fail_on_pct_threshold = cli_config.fail_on_pct_threshold;
}
if overwrite("log_file") {
config.log_file = cli_config.log_file;
}
if overwrite("drain_timeout_secs") {
config.drain_timeout_secs = cli_config.drain_timeout_secs;
}
config.progress_callback = None;
config.dependency_overrides = None;
config.allow_localhost_for_tests = false; config
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn file_config_from_json(value: serde_json::Value) -> Result<FileConfig, serde_json::Error> {
serde_json::from_value(value)
}
#[test]
fn test_merge_preserves_file_when_cli_not_explicit() {
let file = FileConfig {
file: Some(PathBuf::from("/path/to/urls.txt")),
log_level: Some(LogLevel::Debug),
max_concurrency: Some(100),
..Default::default()
};
let cli_config = Config {
file: PathBuf::from("/cli/urls.txt"),
log_level: LogLevel::Info,
max_concurrency: 30,
..Default::default()
};
let merged = merge_file_and_cli(Some(&file), cli_config.clone(), Some(&[]));
assert!(
matches!(merged.log_level, LogLevel::Debug),
"file log_level preserved when not explicit"
);
assert_eq!(
merged.max_concurrency, 100,
"file max_concurrency preserved when not explicit"
);
let merged2 = merge_file_and_cli(Some(&file), cli_config.clone(), Some(&["log_level"]));
assert!(
matches!(merged2.log_level, LogLevel::Info),
"cli log_level overwrites when explicit"
);
assert_eq!(
merged2.max_concurrency, 100,
"file max_concurrency still preserved"
);
let merged3 = merge_file_and_cli(Some(&file), cli_config, None);
assert!(matches!(merged3.log_level, LogLevel::Info));
assert_eq!(merged3.max_concurrency, 30);
}
#[test]
fn test_merge_applies_explicit_drain_timeout_secs() {
let file = FileConfig {
drain_timeout_secs: Some(45),
..Default::default()
};
let cli_config = Config {
drain_timeout_secs: 90,
..Default::default()
};
let merged = merge_file_and_cli(Some(&file), cli_config.clone(), Some(&[]));
assert_eq!(merged.drain_timeout_secs, 45);
let merged2 = merge_file_and_cli(Some(&file), cli_config, Some(&["drain_timeout_secs"]));
assert_eq!(merged2.drain_timeout_secs, 90);
}
#[test]
fn test_merge_fail_on_invalid_rejected_valid_applied_cli_overrides() {
let err = file_config_from_json(json!({"fail_on": "boom"})).unwrap_err();
let err_s = err.to_string();
assert!(
err_s.contains("fail_on"),
"invalid fail_on must name the field, got: {err_s}"
);
let valid = FileConfig {
fail_on: Some(FailOn::PctGreaterThan),
..Default::default()
};
let merged_valid = merge_file_and_cli(
Some(&valid),
Config {
fail_on: FailOn::Never,
..Default::default()
},
Some(&[]),
);
assert!(
matches!(merged_valid.fail_on, FailOn::PctGreaterThan),
"valid file fail_on=pct> must apply"
);
let merged_cli = merge_file_and_cli(
Some(&valid),
Config {
fail_on: FailOn::AnyFailure,
..Default::default()
},
Some(&["fail_on"]),
);
assert!(
matches!(merged_cli.fail_on, FailOn::AnyFailure),
"explicit CLI fail_on must override file"
);
let bool_err = file_config_from_toml(r#"enable_whois = "maybe""#).unwrap_err();
let bool_s = bool_err.to_string();
assert!(
bool_s.contains("enable_whois"),
"invalid enable_whois must name the field, got: {bool_s}"
);
let any_failure = file_config_from_json(json!({"fail_on": "any-failure"})).unwrap();
let merged_any = merge_file_and_cli(
Some(&any_failure),
Config {
fail_on: FailOn::Never,
..Default::default()
},
Some(&[]),
);
assert!(
matches!(merged_any.fail_on, FailOn::AnyFailure),
"fail_on=any-failure must apply from file"
);
}
#[test]
fn test_invalid_bool_deserialize_fails_instead_of_forcing_false() {
let err = file_config_from_toml(r#"enable_whois = "maybe""#).unwrap_err();
let err_s = err.to_string();
assert!(
err_s.contains("enable_whois"),
"invalid enable_whois must name the field, got: {err_s}"
);
assert!(parse_bool("maybe").is_none());
assert!(parse_bool(" nah ").is_none());
}
#[test]
fn test_no_whois_cli_flag_overrides_toml_enable_whois_true() {
let file = FileConfig {
enable_whois: Some(true),
..Default::default()
};
let merged = merge_file_and_cli(
Some(&file),
Config {
enable_whois: true, ..Default::default()
},
Some(&["no_whois"]),
);
assert!(
!merged.enable_whois,
"--no-whois must force enable_whois=false even though the TOML file says true"
);
}
#[test]
fn test_enable_whois_true_from_file_applies_without_no_whois_flag() {
let file = FileConfig {
enable_whois: Some(true),
..Default::default()
};
let merged = merge_file_and_cli(Some(&file), Config::default(), Some(&[]));
assert!(
merged.enable_whois,
"file enable_whois=true must apply when --no-whois was not set"
);
}
#[test]
fn test_scan_external_scripts_parses_permissive_truthy_strings() {
for truthy in ["yes", "true", "1", "on", "YES", "True"] {
let file = file_config_from_json(json!({"scan_external_scripts": truthy})).unwrap();
let merged = merge_file_and_cli(Some(&file), Config::default(), Some(&[]));
assert!(
merged.scan_external_scripts,
"scan_external_scripts={truthy:?} must parse to true"
);
}
for falsy in ["no", "false", "0", "off"] {
let file = file_config_from_json(json!({"scan_external_scripts": falsy})).unwrap();
let merged = merge_file_and_cli(Some(&file), Config::default(), Some(&[]));
assert!(
!merged.scan_external_scripts,
"scan_external_scripts={falsy:?} must parse to false"
);
}
}
#[test]
fn test_fail_on_aliases_deserialize() {
for alias in ["any-failure", "any_failure", "anyfailure", "ANY-FAILURE"] {
let fc = file_config_from_json(json!({"fail_on": alias})).unwrap();
assert_eq!(fc.fail_on, Some(FailOn::AnyFailure), "alias={alias}");
}
let pct = file_config_from_json(json!({"fail_on": "pct>"})).unwrap();
assert_eq!(pct.fail_on, Some(FailOn::PctGreaterThan));
}
#[test]
fn test_file_config_deserializes_via_config_crate_toml() {
let settings = config::Config::builder()
.add_source(config::File::from_str(
r#"
max_concurrency = 42
enable_whois = true
fail_on = "any-failure"
scan_external_scripts = "yes"
log_level = "debug"
"#,
config::FileFormat::Toml,
))
.build()
.expect("build");
let fc: FileConfig = settings.try_deserialize().expect("deserialize FileConfig");
assert_eq!(fc.max_concurrency, Some(42));
assert_eq!(fc.enable_whois, Some(true));
assert_eq!(fc.fail_on, Some(FailOn::AnyFailure));
assert_eq!(fc.scan_external_scripts, Some(true));
assert_eq!(fc.log_level, Some(LogLevel::Debug));
}
#[test]
fn file_config_overlay_keys_are_unique() {
let mut seen = std::collections::HashSet::new();
for key in FILE_CONFIG_OVERLAY_KEYS {
assert!(seen.insert(*key), "duplicate overlay key {key}");
}
}
fn overlay_key_sentinel_toml(key: &str) -> String {
let line = match key {
"file" => r#"file = "/sentinel/urls.txt""#,
"log_level" => r#"log_level = "debug""#,
"log_format" => r#"log_format = "json""#,
"db_path" => r#"db_path = "/sentinel/scan.db""#,
"max_concurrency" => "max_concurrency = 77",
"timeout_seconds" => "timeout_seconds = 42",
"user_agent" => r#"user_agent = "SentinelAgent/1.0""#,
"rate_limit_rps" => "rate_limit_rps = 3",
"fingerprints" => r#"fingerprints = "/sentinel/fp.json""#,
"geoip" => r#"geoip = "/sentinel/geo.mmdb""#,
"status_port" => "status_port = 9999",
"enable_whois" => "enable_whois = false",
"cache_dir" => r#"cache_dir = "/sentinel/cache""#,
"scan_external_scripts" => "scan_external_scripts = true",
"fail_on" => r#"fail_on = "any-failure""#,
"fail_on_pct_threshold" => "fail_on_pct_threshold = 25",
"log_file" => r#"log_file = "/sentinel/scan.log""#,
"drain_timeout_secs" => "drain_timeout_secs = 99",
other => panic!(
"overlay key {other} has no sentinel TOML; add a line here and assert Config"
),
};
line.to_string()
}
fn assert_overlay_sentinel_on_config(config: &Config, key: &str) {
match key {
"file" => assert_eq!(config.file, PathBuf::from("/sentinel/urls.txt")),
"log_level" => assert_eq!(config.log_level, LogLevel::Debug),
"log_format" => assert_eq!(config.log_format, LogFormat::Json),
"db_path" => assert_eq!(config.db_path, PathBuf::from("/sentinel/scan.db")),
"max_concurrency" => assert_eq!(config.max_concurrency, 77),
"timeout_seconds" => assert_eq!(config.timeout_seconds, 42),
"user_agent" => assert_eq!(config.user_agent, "SentinelAgent/1.0"),
"rate_limit_rps" => assert_eq!(config.rate_limit_rps, 3),
"fingerprints" => {
assert_eq!(config.fingerprints.as_deref(), Some("/sentinel/fp.json"));
}
"geoip" => assert_eq!(config.geoip.as_deref(), Some("/sentinel/geo.mmdb")),
"status_port" => assert_eq!(config.status_port, Some(9999)),
"enable_whois" => assert!(!config.enable_whois),
"cache_dir" => {
assert_eq!(
config.cache_dir.as_deref(),
Some(PathBuf::from("/sentinel/cache").as_path())
);
}
"scan_external_scripts" => assert!(config.scan_external_scripts),
"fail_on" => assert_eq!(config.fail_on, FailOn::AnyFailure),
"fail_on_pct_threshold" => assert_eq!(config.fail_on_pct_threshold, 25),
"log_file" => {
assert_eq!(
config.log_file.as_deref(),
Some(PathBuf::from("/sentinel/scan.log").as_path())
);
}
"drain_timeout_secs" => assert_eq!(config.drain_timeout_secs, 99),
other => panic!("overlay key {other} has no Config assertion"),
}
}
#[test]
fn file_config_overlay_toml_sentinels_land_on_config() {
let toml = FILE_CONFIG_OVERLAY_KEYS
.iter()
.map(|key| overlay_key_sentinel_toml(key))
.collect::<Vec<_>>()
.join("\n");
let settings = config::Config::builder()
.add_source(config::File::from_str(&toml, config::FileFormat::Toml))
.build()
.expect("build overlay sentinel TOML");
let fc: FileConfig = settings
.try_deserialize()
.expect("deserialize FileConfig from overlay sentinels");
let mut config = Config::default();
apply_file_config(&mut config, &fc);
for key in FILE_CONFIG_OVERLAY_KEYS {
assert_overlay_sentinel_on_config(&config, key);
}
}
fn file_config_from_toml(toml: &str) -> Result<FileConfig, config::ConfigError> {
let settings = config::Config::builder()
.add_source(config::File::from_str(toml, config::FileFormat::Toml))
.build()?;
settings.try_deserialize()
}
#[rstest::rstest]
#[case("error", Some(LogLevel::Error))]
#[case("warn", Some(LogLevel::Warn))]
#[case("info", Some(LogLevel::Info))]
#[case("debug", Some(LogLevel::Debug))]
#[case("trace", Some(LogLevel::Trace))]
#[case("ERROR", Some(LogLevel::Error))]
#[case("unknown", None)]
#[case("", None)]
fn test_parse_log_level_exact(#[case] raw: &str, #[case] expected: Option<LogLevel>) {
assert_eq!(parse_log_level(raw), expected);
}
#[rstest::rstest]
#[case("plain", Some(LogFormat::Plain))]
#[case("json", Some(LogFormat::Json))]
#[case("PLAIN", Some(LogFormat::Plain))]
#[case("yaml", None)]
#[case("", None)]
fn test_parse_log_format_exact(#[case] raw: &str, #[case] expected: Option<LogFormat>) {
assert_eq!(parse_log_format(raw), expected);
}
#[rstest::rstest]
#[case("never", Some(FailOn::Never))]
#[case("any-failure", Some(FailOn::AnyFailure))]
#[case("any_failure", Some(FailOn::AnyFailure))]
#[case("anyfailure", Some(FailOn::AnyFailure))]
#[case("pct>", Some(FailOn::PctGreaterThan))]
#[case("NEVER", Some(FailOn::Never))]
#[case("always", None)]
#[case("", None)]
fn test_parse_fail_on_exact(#[case] raw: &str, #[case] expected: Option<FailOn>) {
assert_eq!(parse_fail_on(raw), expected);
}
#[rstest::rstest]
#[case("enable_whois = 1", true)]
#[case("enable_whois = 0", false)]
#[case(r#"enable_whois = "yes""#, true)]
#[case(r#"enable_whois = "no""#, false)]
#[case("enable_whois = true", true)]
#[case("enable_whois = false", false)]
fn test_enable_whois_toml_synonyms(#[case] toml: &str, #[case] expected: bool) {
let fc = file_config_from_toml(toml).expect("valid enable_whois TOML");
assert_eq!(fc.enable_whois, Some(expected), "toml={toml}");
}
#[test]
fn test_enable_whois_json_integer_synonyms() {
let one = file_config_from_json(json!({"enable_whois": 1})).expect("1");
assert_eq!(one.enable_whois, Some(true));
let zero = file_config_from_json(json!({"enable_whois": 0})).expect("0");
assert_eq!(zero.enable_whois, Some(false));
}
#[rstest::rstest]
#[case(r#"fail_on = "boom""#, "fail_on")]
#[case(r#"log_level = "silent""#, "log_level")]
#[case(r#"log_format = "yaml""#, "log_format")]
#[case(r#"enable_whois = "maybe""#, "enable_whois")]
fn test_unknown_config_value_err_names_field(#[case] toml: &str, #[case] field: &str) {
let err = file_config_from_toml(toml).expect_err("unknown value must fail");
let err_s = err.to_string();
assert!(
err_s.contains(field),
"reject must name {field}, got: {err_s}"
);
}
}