use std::collections::BTreeMap;
use std::fs;
use std::path::Path;
use std::time::Duration;
use bitflags::bitflags;
use redup_config::{
Config, Extensible, ExtraSection, Global, HexBytes, Node, Source, flags, load, render,
render_default, render_sample, status,
};
use redup_primitives::{Hash128, Timestamp};
use time::{Date, Time};
use uuid::Uuid;
type TestResult = Result<(), Box<dyn std::error::Error>>;
fn snapshot(name: &str, text: &str) -> Result<(), Box<dyn std::error::Error>> {
let path = Path::new(env!("CARGO_MANIFEST_DIR"))
.join("tests/snapshots")
.join(format!("{name}.txt"));
if std::env::var_os("SNAPSHOT_WRITE").is_some() {
return fs::write(&path, text).map_err(|error| format!("snapshot {name}: {error}").into());
}
let expected =
fs::read_to_string(&path).map_err(|error| format!("snapshot {name}: {error}"))?;
assert_eq!(text, expected, "snapshot {name} diverged");
Ok(())
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Config)]
enum Delivery {
#[default]
Courier,
Pickup,
Post,
}
#[derive(Debug, Clone, Default, PartialEq, Config)]
struct StorageSection {
directory: String,
limit: u64,
}
#[derive(Debug, Clone, Default, PartialEq, Config)]
struct RecipientSection {
name: String,
address: String,
}
#[derive(Debug, Clone, PartialEq, Config)]
struct NotifyConfig {
port: i32,
timeout: Duration,
delivery: Delivery,
channel: Delivery,
storage: Option<StorageSection>,
recipients: Vec<RecipientSection>,
labels: BTreeMap<String, String>,
password: String,
secrets: BTreeMap<String, String>,
message: String,
}
impl Default for NotifyConfig {
fn default() -> Self {
Self {
port: 4200,
timeout: Duration::from_secs(30),
delivery: Delivery::Post,
channel: Delivery::Courier,
storage: None,
recipients: Vec::new(),
labels: BTreeMap::new(),
password: String::new(),
secrets: BTreeMap::new(),
message: String::new(),
}
}
}
fn filled_notify() -> NotifyConfig {
NotifyConfig {
port: 8443,
timeout: Duration::from_secs(90),
delivery: Delivery::Pickup,
channel: Delivery::Post,
storage: Some(StorageSection {
directory: "/var/lib/attachments".to_owned(),
limit: 1_073_741_824,
}),
recipients: vec![RecipientSection {
name: "ops".to_owned(),
address: "ops@example.com".to_owned(),
}],
labels: BTreeMap::from([
("team".to_owned(), "infra".to_owned()),
("tier".to_owned(), "gold".to_owned()),
]),
password: "hunter2".to_owned(),
secrets: BTreeMap::from([("api".to_owned(), "key-123".to_owned())]),
message: "строка\nещё\tс табуляцией".to_owned(),
}
}
bitflags! {
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
struct Layers: u8 {
const None = 0;
const GroupMap = 1;
const DocMeta = 2;
const DocDic = 4;
const All = 7;
}
}
flags!(Layers);
const DAY: i32 = 2_460_312;
#[derive(Debug, Clone, PartialEq, Config)]
struct ValuesConfig {
id: Uuid,
hash: Hash128,
header: HexBytes,
since: Date,
at: Time,
moment: Timestamp,
layers: Layers,
build: Layers,
holidays: Vec<Date>,
hashes: BTreeMap<String, Hash128>,
optional: Option<Layers>,
#[config(required)]
directory: Option<String>,
#[config(required)]
storage: Option<StorageSection>,
#[config(required)]
delivery: Option<Delivery>,
}
impl Default for ValuesConfig {
fn default() -> Self {
Self {
id: Uuid::nil(),
hash: Hash128::ZERO,
header: HexBytes::default(),
since: Date::from_julian_day(DAY).unwrap_or(Date::MIN),
at: Time::MIDNIGHT,
moment: Timestamp::UNIX_EPOCH,
layers: Layers::GroupMap | Layers::DocMeta,
build: Layers::empty(),
holidays: Vec::new(),
hashes: BTreeMap::new(),
optional: None,
directory: None,
storage: None,
delivery: None,
}
}
}
fn filled_values() -> ValuesConfig {
ValuesConfig {
id: Uuid::parse_str("01234567-89ab-cdef-0123-456789abcdef").unwrap_or_else(|_| Uuid::nil()),
hash: Hash128::from(0xDEADBEEF_u128),
header: HexBytes::from(vec![0x50, 0x4B, 0x03]),
since: Date::from_julian_day(DAY).unwrap_or(Date::MIN),
at: Time::from_hms(15, 4, 5).unwrap_or(Time::MIDNIGHT),
moment: Timestamp::from_unix_seconds(1_704_164_645).unwrap_or(Timestamp::UNIX_EPOCH),
layers: Layers::All,
build: Layers::None,
holidays: vec![
Date::from_julian_day(DAY).unwrap_or(Date::MIN),
Date::from_julian_day(DAY + 1).unwrap_or(Date::MIN),
],
hashes: BTreeMap::from([("main".to_owned(), Hash128::from(0xDEADBEEF_u128))]),
optional: Some(Layers::DocDic),
directory: Some("/var/lib".to_owned()),
storage: Some(StorageSection::default()),
delivery: Some(Delivery::Post),
}
}
#[derive(Debug, Clone, Default, PartialEq, Config)]
struct DemoHostConfig {
name: String,
}
#[derive(Debug, Clone, Default, PartialEq, Config)]
struct DemoExtraConfig {
address: String,
}
impl ExtraSection for DemoExtraConfig {
type Host = DemoHostConfig;
}
#[derive(Debug, Clone, Default, PartialEq, Config)]
struct SecretSection {
inner: String,
}
#[derive(Debug, Clone, Default, PartialEq, Config)]
struct SecretFormsConfig {
secret_section: SecretSection,
secret_map: BTreeMap<String, String>,
optional_secret: Option<String>,
plain: String,
}
#[derive(Debug, Clone, PartialEq, Config)]
struct CommentsConfig {
wrapped: String,
above: String,
short: i32,
}
impl Default for CommentsConfig {
fn default() -> Self {
Self {
wrapped: "значение".to_owned(),
above: "x".repeat(150),
short: 7,
}
}
}
#[derive(Debug, Clone, PartialEq, Config)]
struct StringsConfig {
empty: String,
padded: String,
quoted: String,
dquoted: String,
null_word: String,
trailing_newline: String,
leading_newline: String,
tabbed: String,
glob: String,
reference: String,
mapping: String,
header: String,
}
impl Default for StringsConfig {
fn default() -> Self {
Self {
empty: String::new(),
padded: " текст ".to_owned(),
quoted: "it's".to_owned(),
dquoted: "say \"hi\"".to_owned(),
null_word: "null".to_owned(),
trailing_newline: "l1\nl2\n".to_owned(),
leading_newline: "\nl1".to_owned(),
tabbed: "a\tb".to_owned(),
glob: "*.txt".to_owned(),
reference: "&".to_owned(),
mapping: "a: b".to_owned(),
header: "key:".to_owned(),
}
}
}
#[derive(Debug, Clone, PartialEq, Config)]
struct ListsConfig {
scalars: Vec<String>,
numbers: Vec<i32>,
sparse: Vec<Option<String>>,
empty: Vec<String>,
sections: Vec<RecipientSection>,
matrix: Vec<Vec<i32>>,
}
impl Default for ListsConfig {
fn default() -> Self {
Self {
scalars: vec!["a".to_owned(), "b".to_owned()],
numbers: vec![1, 2, 3],
sparse: vec![Some("a".to_owned()), None, Some("b".to_owned())],
empty: Vec::new(),
sections: vec![
RecipientSection {
name: "ops".to_owned(),
address: "ops@example.com".to_owned(),
},
RecipientSection::default(),
],
matrix: vec![vec![1, 2], vec![3]],
}
}
}
#[derive(Debug, Clone, PartialEq, Config)]
struct MapsConfig {
scalars: BTreeMap<String, String>,
sections: BTreeMap<String, StorageSection>,
optional: BTreeMap<String, Option<i32>>,
empty: BTreeMap<String, String>,
}
impl Default for MapsConfig {
fn default() -> Self {
Self {
scalars: BTreeMap::from([
("alpha".to_owned(), "1".to_owned()),
("beta".to_owned(), "2".to_owned()),
]),
sections: BTreeMap::from([
(
"main".to_owned(),
StorageSection {
directory: "/var/lib/main".to_owned(),
limit: 512,
},
),
("spare".to_owned(), StorageSection::default()),
]),
optional: BTreeMap::from([("yes".to_owned(), Some(1)), ("no".to_owned(), None)]),
empty: BTreeMap::new(),
}
}
}
#[test]
fn defaults_match_the_snapshot() -> TestResult {
snapshot("notify-default", &render_default::<NotifyConfig>())
}
#[test]
fn sample_matches_the_snapshot() -> TestResult {
snapshot("notify-sample", &render_sample::<NotifyConfig>())
}
#[test]
fn values_match_the_snapshot() -> TestResult {
snapshot("notify-render", &render(&filled_notify()))
}
#[test]
fn status_matches_the_snapshot() -> TestResult {
snapshot("notify-status", &status(&filled_notify()))
}
#[test]
fn status_of_defaults_matches_the_snapshot() -> TestResult {
snapshot("notify-status-defaults", &status(&NotifyConfig::default()))
}
#[test]
fn comments_match_the_snapshot() -> TestResult {
snapshot("comments-default", &render_default::<CommentsConfig>())
}
#[test]
fn strings_match_the_snapshot() -> TestResult {
snapshot("strings-default", &render_default::<StringsConfig>())
}
#[test]
fn lists_match_the_snapshot() -> TestResult {
snapshot("lists-default", &render_default::<ListsConfig>())
}
#[test]
fn lists_sample_matches_the_snapshot() -> TestResult {
snapshot("lists-sample", &render_sample::<ListsConfig>())
}
#[test]
fn maps_match_the_snapshot() -> TestResult {
snapshot("maps-default", &render_default::<MapsConfig>())
}
#[test]
fn global_defaults_match_the_snapshot() -> TestResult {
let global = Global::new()
.with::<NotifyConfig>()
.with::<Extensible<DemoHostConfig, (Option<DemoExtraConfig>, ())>>();
snapshot("global-default", &global.render_default())
}
#[test]
fn global_sample_matches_the_snapshot() -> TestResult {
let global = Global::new()
.with::<NotifyConfig>()
.with::<Extensible<DemoHostConfig, (Option<DemoExtraConfig>, ())>>();
snapshot("global-sample", &global.render_sample())
}
#[test]
fn render_hides_secret_section_and_secret_dictionary_entirely() -> TestResult {
let value = SecretFormsConfig {
secret_section: SecretSection {
inner: "спрятано".to_owned(),
},
secret_map: BTreeMap::from([("api".to_owned(), "ключ".to_owned())]),
optional_secret: Some("тоже спрятано".to_owned()),
plain: "видно".to_owned(),
};
let text = render(&value);
assert!(text.contains("secretSection: '*****'"), "{text}");
assert!(text.contains("secretMap: '*****'"), "{text}");
assert!(text.contains("optionalSecret: '*****'"), "{text}");
assert!(text.contains("plain: видно"), "{text}");
assert!(!text.contains("спрятано"), "{text}");
assert!(!text.contains("ключ"), "{text}");
assert!(!text.contains("inner"), "{text}");
Ok(())
}
#[test]
fn render_keeps_absent_secret_value_visible() -> TestResult {
let text = render(&SecretFormsConfig::default());
assert!(text.contains("optionalSecret: ~"), "{text}");
assert!(text.contains("secretSection: '*****'"), "{text}");
assert!(text.contains("secretMap: '*****'"), "{text}");
assert!(!text.contains("inner"), "{text}");
Ok(())
}
#[derive(Debug, Clone, PartialEq, Config)]
struct TrickyConfig {
files: Vec<String>,
notes: Vec<String>,
null_word: String,
}
impl Default for TrickyConfig {
fn default() -> Self {
Self {
files: vec![
"a,b".to_owned(),
"c#d".to_owned(),
"*.cs".to_owned(),
"NULL".to_owned(),
],
notes: vec!["первая\nвторая\n".to_owned(), "x".to_owned()],
null_word: "Null".to_owned(),
}
}
}
#[test]
fn written_text_reads_back_with_the_same_values() -> TestResult {
let text = render_default::<TrickyConfig>();
assert!(
text.contains("files: ['a,b', 'c#d', '*.cs', 'NULL']"),
"{text}"
);
assert!(text.contains("nullWord: 'Null'"), "{text}");
assert!(text.contains("\n- |2+\n первая\n вторая\n- x"), "{text}");
let sandbox = tempfile::tempdir()?;
fs::create_dir_all(sandbox.path().join("Configs"))?;
fs::write(sandbox.path().join("Configs/Tricky.yaml"), &text)?;
let loaded = load::<TrickyConfig>(&Source::directory(sandbox.path()))?;
assert_eq!(loaded.value, TrickyConfig::default());
Ok(())
}
#[test]
fn scalars_defaults_match_the_snapshot() -> TestResult {
snapshot("values-default", &render_default::<ValuesConfig>())
}
#[test]
fn scalars_sample_matches_the_snapshot() -> TestResult {
snapshot("values-sample", &render_sample::<ValuesConfig>())
}
#[test]
fn scalars_values_match_the_snapshot() -> TestResult {
snapshot("values-render", &render(&filled_values()))
}
#[test]
fn scalars_status_matches_the_snapshot() -> TestResult {
snapshot("values-status", &status(&filled_values()))
}
#[test]
fn written_scalars_read_back_with_the_same_values() -> TestResult {
let filled = filled_values();
let text = render(&filled);
assert!(text.contains("directory: /var/lib #"), "{text}");
let sandbox = tempfile::tempdir()?;
fs::create_dir_all(sandbox.path().join("Configs"))?;
fs::write(sandbox.path().join("Configs/Values.yaml"), &text)?;
let loaded = load::<ValuesConfig>(&Source::directory(sandbox.path()))?;
assert_eq!(loaded.value, filled);
assert_eq!(render(&loaded.value), text);
let cleared = text.replace("directory: /var/lib", "directory: ~");
fs::write(sandbox.path().join("Configs/Values.yaml"), &cleared)?;
let problems = load::<ValuesConfig>(&Source::directory(sandbox.path()))
.err()
.ok_or("the configuration is accepted")?;
assert_eq!(
problems.iter().map(ToString::to_string).collect::<Vec<_>>(),
[
"directory: the field is required, but the value is not set — Корневой каталог. Без него \
служба не стартует."
]
);
Ok(())
}
#[test]
fn rendered_defaults_with_missing_required_fields_are_rejected() -> TestResult {
let mut sample = ValuesConfig::default();
sample.fill();
assert!(
sample.storage.is_none(),
"the sample must not fill a required field"
);
for text in [
render_default::<ValuesConfig>(),
render_sample::<ValuesConfig>(),
] {
assert_eq!(text.matches("[required]").count(), 3, "{text}");
let sandbox = tempfile::tempdir()?;
fs::create_dir_all(sandbox.path().join("Configs"))?;
fs::write(sandbox.path().join("Configs/Values.yaml"), &text)?;
let problems = load::<ValuesConfig>(&Source::directory(sandbox.path()))
.err()
.ok_or("the configuration is accepted")?;
assert_eq!(problems.len(), 3, "{problems}");
}
Ok(())
}