#![allow(unused_crate_dependencies)]
use std::path::{Path, PathBuf};
use mogh_config::ConfigLoader;
struct TestDir(PathBuf);
impl TestDir {
fn new(name: &str) -> TestDir {
let path = std::env::temp_dir().join(format!(
"mogh_config_test_{}_{name}",
std::process::id()
));
let _ = std::fs::remove_dir_all(&path);
std::fs::create_dir_all(&path).unwrap();
TestDir(path)
}
fn write(&self, file: &str, contents: &str) -> PathBuf {
let path = self.0.join(file);
std::fs::write(&path, contents).unwrap();
path
}
}
impl Drop for TestDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
fn load(
paths: &[&Path],
match_wildcards: &[&str],
merge_nested: bool,
extend_array: bool,
) -> serde_json::Value {
ConfigLoader {
paths,
match_wildcards,
include_file_name: ".include",
merge_nested,
extend_array,
debug_print: false,
}
.load()
.unwrap()
}
#[test]
fn loads_toml_yaml_and_json_files() {
let dir = TestDir::new("formats");
let toml = dir.write("config.toml", "a = 1");
let yaml = dir.write("config.yaml", "b: 2");
let yml = dir.write("config.yml", "c: 3");
let json = dir.write("config.json", r#"{ "d": 4 }"#);
let config = load(&[&toml, &yaml, &yml, &json], &[], false, false);
assert_eq!(
config,
serde_json::json!({ "a": 1, "b": 2, "c": 3, "d": 4 })
);
}
#[test]
fn extension_matching_is_case_insensitive() {
let dir = TestDir::new("upper_ext");
let toml = dir.write("config.TOML", "a = 1");
let config = load(&[&toml], &[], false, false);
assert_eq!(config, serde_json::json!({ "a": 1 }));
}
#[test]
fn unsupported_extension_is_skipped_with_warning() {
let dir = TestDir::new("unsupported_ext");
let txt = dir.write("config.txt", "a = 1");
let toml = dir.write("config.toml", "b = 2");
let config = load(&[&txt, &toml], &[], false, false);
assert_eq!(config, serde_json::json!({ "b": 2 }));
}
#[test]
fn missing_paths_are_skipped() {
let dir = TestDir::new("missing_path");
let toml = dir.write("config.toml", "a = 1");
let missing = dir.0.join("does_not_exist.toml");
let config = load(&[&missing, &toml], &[], false, false);
assert_eq!(config, serde_json::json!({ "a": 1 }));
}
#[test]
fn later_paths_override_earlier_paths() {
let dir = TestDir::new("precedence");
let base = dir.write(
"base.toml",
"a = 1\nb = \"base\"\narr = [1]\n[nested]\nx = 1\ny = 1",
);
let override_ = dir.write(
"override.json",
r#"{ "b": "override", "arr": [2], "nested": { "y": 2 } }"#,
);
let config = load(&[&base, &override_], &[], true, true);
assert_eq!(
config,
serde_json::json!({
"a": 1,
"b": "override",
"arr": [1, 2],
"nested": { "x": 1, "y": 2 }
})
);
let config = load(&[&base, &override_], &[], false, false);
assert_eq!(
config,
serde_json::json!({
"a": 1,
"b": "override",
"arr": [2],
"nested": { "y": 2 }
})
);
}
#[test]
fn repeated_path_moves_to_highest_priority() {
let dir = TestDir::new("repeat_path");
let first = dir.write("first.toml", "a = \"first\"");
let second = dir.write("second.toml", "a = \"second\"");
let config = load(&[&first, &second, &first], &[], false, false);
assert_eq!(config, serde_json::json!({ "a": "first" }));
}
#[test]
fn directory_loading_respects_wildcard_order() {
let dir = TestDir::new("wildcards");
dir.write("01_a.toml", "key = \"a\"\nonly_a = 1");
dir.write("02_b.toml", "key = \"b\"\nonly_b = 1");
dir.write("ignored.toml", "ignored = 1");
let config =
load(&[&dir.0], &["02_*.toml", "01_*.toml"], false, false);
assert_eq!(
config,
serde_json::json!({ "key": "a", "only_a": 1, "only_b": 1 })
);
let config = load(&[&dir.0], &["0*.toml"], false, false);
assert_eq!(
config,
serde_json::json!({ "key": "b", "only_a": 1, "only_b": 1 })
);
let config = load(&[&dir.0], &["0*.toml"], false, false);
assert_eq!(config.get("ignored"), None);
}
#[test]
fn file_paths_override_directory_paths() {
let dir = TestDir::new("file_over_dir");
dir.write("config.toml", "a = \"dir\"");
let standalone = TestDir::new("file_over_dir_standalone");
let file = standalone.write("override.toml", "a = \"file\"");
let config = load(&[&dir.0, &file], &["*.toml"], false, false);
assert_eq!(config, serde_json::json!({ "a": "file" }));
}
#[test]
fn include_file_pulls_in_other_directories() {
let included = TestDir::new("included_dir");
included.write("extra.toml", "extra = 1\nkey = \"included\"");
let dir = TestDir::new("includes");
dir.write("main.toml", "key = \"main\"\nmain = 1");
dir.write(
".include",
&format!(
"# comment line\n\n{} # end of line comment\n",
included.0.display()
),
);
let config = load(&[&dir.0], &["*.toml"], false, false);
assert_eq!(config.get("extra"), Some(&serde_json::json!(1)));
assert_eq!(config.get("main"), Some(&serde_json::json!(1)));
assert_eq!(config.get("key"), Some(&serde_json::json!("included")));
}
#[test]
fn includes_apply_in_include_order() {
let main = TestDir::new("zz_order_main");
let first = TestDir::new("yy_order_first");
let second = TestDir::new("aa_order_second");
let nested = TestDir::new("bb_order_nested");
main.write("main.toml", "key = \"main\"\nmain = 1");
first.write("first.toml", "key = \"first\"\nfirst = 1");
second.write("second.toml", "key = \"second\"\nsecond = 1");
nested.write("nested.toml", "key = \"nested\"\nnested = 1");
first.write(
".include",
&format!(
"{}
",
nested.0.display()
),
);
main.write(
".include",
&format!(
"{}
{}
",
first.0.display(),
second.0.display()
),
);
let config = load(&[&main.0], &["*.toml"], false, false);
assert_eq!(
config,
serde_json::json!({
"key": "second",
"main": 1,
"first": 1,
"nested": 1,
"second": 1,
})
);
main.write(
".include",
&format!(
"{}
{}
",
second.0.display(),
first.0.display()
),
);
let config = load(&[&main.0], &["*.toml"], false, false);
assert_eq!(config.get("key"), Some(&serde_json::json!("nested")));
}
#[test]
fn wildcard_priority_is_per_directory() {
let main = TestDir::new("wc_per_dir_main");
let included = TestDir::new("wc_per_dir_included");
main.write("02_high.toml", "key = \"main-high\"");
included.write("01_low.toml", "key = \"included-low\"");
main.write(
".include",
&format!(
"{}
",
included.0.display()
),
);
let config =
load(&[&main.0], &["01_*.toml", "02_*.toml"], false, false);
assert_eq!(config, serde_json::json!({ "key": "included-low" }));
}
#[test]
fn interpolates_env_vars_into_config() {
let var = "MOGH_CONFIG_TEST_INTERPOLATION_VAR";
unsafe { std::env::set_var(var, "interpolated") };
let dir = TestDir::new("interpolation");
let toml =
dir.write("config.toml", &format!("value = \"${{{var}}}\""));
let config = load(&[&toml], &[], false, false);
assert_eq!(config, serde_json::json!({ "value": "interpolated" }));
}
#[test]
fn interpolates_unset_env_vars_to_empty_string() {
let dir = TestDir::new("interpolation_unset");
let toml = dir.write(
"config.toml",
"value = \"${MOGH_CONFIG_TEST_DEFINITELY_UNSET_VAR}\"",
);
let config = load(&[&toml], &[], false, false);
assert_eq!(config, serde_json::json!({ "value": "" }));
}
#[test]
fn include_cycles_do_not_recurse_forever() {
let a = TestDir::new("cycle_a");
let b = a.0.join("b");
std::fs::create_dir(&b).unwrap();
a.write("a.toml", "a = 1");
std::fs::write(b.join("b.toml"), "b = 2").unwrap();
a.write(".include", &format!("{}\n.\n", b.display()));
std::fs::write(
b.join(".include"),
format!("{}\n..\n", a.0.display()),
)
.unwrap();
let config = load(&[&a.0], &["*.toml"], false, false);
assert_eq!(config.get("a"), Some(&serde_json::json!(1)));
assert_eq!(config.get("b"), Some(&serde_json::json!(2)));
}
#[test]
fn diamond_includes_keep_last_occurrence_priority() {
let main = TestDir::new("diamond_main");
let first = TestDir::new("diamond_first");
let second = TestDir::new("diamond_second");
let shared = TestDir::new("diamond_shared");
main.write("main.toml", "key = \"main\"");
first.write("first.toml", "key = \"first\"");
second.write("second.toml", "key = \"second\"");
shared.write("shared.toml", "key = \"shared\"\nshared = 1");
first.write(".include", &format!("{}\n", shared.0.display()));
second.write(".include", &format!("{}\n", shared.0.display()));
main.write(
".include",
&format!("{}\n{}\n", first.0.display(), second.0.display()),
);
let config = load(&[&main.0], &["*.toml"], false, false);
assert_eq!(
config,
serde_json::json!({ "key": "shared", "shared": 1 })
);
}
#[test]
fn include_file_is_not_loaded_as_config() {
let dir = TestDir::new("include_not_config");
dir.write("config.toml", "a = 1");
dir.write(".include", "# nothing\n");
let config = load(&[&dir.0], &[], false, false);
assert_eq!(config, serde_json::json!({ "a": 1 }));
}
#[test]
fn include_paths_may_contain_hash() {
let included = TestDir::new("hash#dir");
included.write("extra.toml", "extra = 1");
let dir = TestDir::new("hash_include");
dir.write("main.toml", "main = 1");
dir.write(
".include",
&format!("{} # trailing comment\n", included.0.display()),
);
let config = load(&[&dir.0], &["*.toml"], false, false);
assert_eq!(config.get("extra"), Some(&serde_json::json!(1)));
}
#[cfg(unix)]
#[test]
fn symlinked_files_in_directories_are_loaded() {
let real = TestDir::new("symlink_real");
let target = real.write("real.toml", "linked = 1");
let dir = TestDir::new("symlink_dir");
std::os::unix::fs::symlink(&target, dir.0.join("config.toml"))
.unwrap();
let config = load(&[&dir.0], &["*.toml"], false, false);
assert_eq!(config, serde_json::json!({ "linked": 1 }));
}
#[test]
fn interpolated_values_cannot_inject_or_break_json() {
let var = "MOGH_CONFIG_TEST_INJECTION_VAR";
let value = "x\",\"admin\":true,\"y\":\"z\\\nline2 $(whoami)";
unsafe { std::env::set_var(var, value) };
let dir = TestDir::new("interpolation_injection");
let toml = dir.write(
"config.toml",
&format!("value = \"${{{var}}}\"\n[nested]\ninner = \"${{{var}}}\"\nlist = [\"${{{var}}}\"]"),
);
let config = load(&[&toml], &[], false, false);
assert_eq!(
config,
serde_json::json!({
"value": value,
"nested": { "inner": value, "list": [value] }
})
);
}
#[test]
fn shell_output_and_env_values_are_not_reinterpolated() {
let literal_var = "MOGH_CONFIG_TEST_LITERAL_VAR";
unsafe {
std::env::set_var(
literal_var,
"keep ${MOGH_CONFIG_TEST_UNSET} literal",
)
};
let outer = "MOGH_CONFIG_TEST_OUTER_VAR";
let inner = "MOGH_CONFIG_TEST_INNER_VAR";
unsafe {
std::env::set_var(outer, format!("outer ${{{inner}}} $(whoami)"));
std::env::set_var(inner, "inner $(whoami)");
}
let dir = TestDir::new("interpolation_no_reinterpolation");
let toml = dir.write(
"config.toml",
&format!("from_shell = \"$(env)\"\nfrom_env = \"${{{outer}}}\""),
);
let config = load(&[&toml], &[], false, false);
let from_shell = config["from_shell"].as_str().unwrap();
assert!(
from_shell.contains("keep ${MOGH_CONFIG_TEST_UNSET} literal"),
"{from_shell}"
);
assert_eq!(
config["from_env"],
serde_json::json!("outer inner $(whoami) $(whoami)")
);
}
#[test]
fn interpolates_shell_commands_and_keys() {
let dir = TestDir::new("interpolation_shell");
let toml = dir.write(
"config.toml",
"value = \"$(true)\"\n\"${MOGH_CONFIG_TEST_DEFINITELY_UNSET_VAR}key\" = 1",
);
let config = load(&[&toml], &[], false, false);
assert_eq!(config, serde_json::json!({ "value": "", "key": 1 }));
}
#[test]
fn errors_do_not_leak_config_values() {
#[derive(serde::Deserialize, Debug)]
#[allow(dead_code)]
struct Typed {
port: u16,
}
let dir = TestDir::new("error_redaction");
let toml = dir.write("config.toml", "port = \"hunter2secret\"");
let err = ConfigLoader {
paths: &[&toml],
match_wildcards: &[],
include_file_name: ".include",
merge_nested: false,
extend_array: false,
debug_print: false,
}
.load::<Typed>()
.unwrap_err();
let message = err.to_string();
assert!(!message.contains("hunter2secret"), "{message}");
assert!(message.contains("expected u16"), "{message}");
}