use super::{opt_str_of, str_of, strings_of};
use serde_json::{Map, Value, json};
fn object(v: Value) -> Map<String, Value> {
v.as_object().expect("an object").clone()
}
#[test]
fn a_string_field_reads_back_and_a_missing_one_names_itself() {
let o = object(json!({"name": "Bash"}));
assert_eq!(str_of(&o, "name"), Ok("Bash".to_owned()));
assert_eq!(
str_of(&o, "description"),
Err("missing field \"description\"".to_owned())
);
}
#[test]
fn a_mistyped_string_field_refuses_rather_than_stringifying_it() {
let o = object(json!({"name": 7}));
assert_eq!(
str_of(&o, "name"),
Err("field \"name\" is not a string".to_owned())
);
}
#[test]
fn an_optional_field_is_absent_null_or_wrong() {
let held = object(json!({"cwd": "/srv/work"}));
assert_eq!(opt_str_of(&held, "cwd"), Ok(Some("/srv/work".to_owned())));
let nulled = object(json!({"cwd": null}));
assert_eq!(opt_str_of(&nulled, "cwd"), Ok(None));
assert_eq!(opt_str_of(&object(json!({})), "cwd"), Ok(None));
let mistyped = object(json!({"cwd": ["/srv/work"]}));
assert_eq!(
opt_str_of(&mistyped, "cwd"),
Err("field \"cwd\" is not a string".to_owned())
);
}
#[test]
fn an_array_of_strings_refuses_whole() {
let o = object(json!({"command": ["/bin/tool", "--flag"]}));
assert_eq!(
strings_of(&o, "command"),
Ok(vec!["/bin/tool".to_owned(), "--flag".to_owned()])
);
assert_eq!(
strings_of(&object(json!({})), "command"),
Err("missing field \"command\"".to_owned())
);
assert_eq!(
strings_of(&object(json!({"command": "/bin/tool"})), "command"),
Err("field \"command\" is not an array".to_owned())
);
assert_eq!(
strings_of(&object(json!({"command": ["/bin/tool", 7]})), "command"),
Err("field \"command\" holds something that is not a string".to_owned())
);
}