use serde::Deserialize;
#[derive(Debug, Deserialize, PartialEq, Eq)]
struct AppConfig {
host: String,
port: u16,
}
#[test]
fn loads_json_yaml_and_toml() {
let dir = tempfile::tempdir().expect("tempdir");
let json = dir.path().join("app.json");
let yaml = dir.path().join("app.yaml");
let toml = dir.path().join("app.toml");
std::fs::write(&json, r#"{"host":"127.0.0.1","port":8080}"#).expect("write json");
std::fs::write(&yaml, "host: 127.0.0.1\nport: 8080\n").expect("write yaml");
std::fs::write(&toml, "host = \"127.0.0.1\"\nport = 8080\n").expect("write toml");
let expected = AppConfig {
host: "127.0.0.1".to_owned(),
port: 8080,
};
assert_eq!(
zonfig::load::<AppConfig>(&json).expect("load json"),
expected
);
assert_eq!(
zonfig::load::<AppConfig>(&yaml).expect("load yaml"),
expected
);
assert_eq!(
zonfig::load::<AppConfig>(&toml).expect("load toml"),
expected
);
}
#[test]
fn can_load_with_explicit_format() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("app.conf");
std::fs::write(&path, r#"{"host":"localhost","port":3000}"#).expect("write config");
let config = zonfig::load_with_format::<AppConfig>(&path, zonfig::Format::Json)
.expect("load with format");
assert_eq!(config.host, "localhost");
assert_eq!(config.port, 3000);
}
#[test]
fn rejects_unknown_extensions() {
let dir = tempfile::tempdir().expect("tempdir");
let path = dir.path().join("app.conf");
std::fs::write(&path, "host = \"localhost\"\nport = 3000\n").expect("write config");
let error = zonfig::load::<AppConfig>(&path).expect_err("unknown format");
assert!(matches!(error, zonfig::Error::UnknownFormat { .. }));
}