use serde_json::{Value, json};
use super::super::{GenerateOptions, generate};
const OWN_VALUES: [(&str, &str); 9] = [
(
"maps:\n - &m {a: 1}\n - *m\n",
r#"{"maps": [{"a": 1}, {"a": 1}]}"#,
),
(
"matrix:\n - [1, 2]\n - [a]\n",
r#"{"matrix": [[1, 2], ["a"]]}"#,
),
("deep:\n - [[1]]\n", r#"{"deep": [[[1]]]}"#),
(
"anchors:\n - &s hello\n - *s\n",
r#"{"anchors": ["hello", "hello"]}"#,
),
(
"seqs:\n - &l [1, 2]\n - *l\n",
r#"{"seqs": [[1, 2], [1, 2]]}"#,
),
(
"base: &base {a: 1}\nderived: {<<: *base, c: 3}\n",
r#"{"base": {"a": 1}, "derived": {"a": 1, "c": 3}}"#,
),
(
"base: &base {a: 1, b: 2}\nderived:\n <<: *base\n a: 9\n",
r#"{"base": {"a": 1, "b": 2}, "derived": {"a": 9, "b": 2}}"#,
),
(
"x: &x {a: 1}\ny: &y {a: 2, b: 2}\nz:\n <<: [*x, *y]\n c: 3\n",
r#"{"x": {"a": 1}, "y": {"a": 2, "b": 2}, "z": {"a": 1, "b": 2, "c": 3}}"#,
),
(
"base: &base {a: 1}\nlist:\n - <<: *base\n c: 3\n",
r#"{"base": {"a": 1}, "list": [{"a": 1, "c": 3}]}"#,
),
];
#[test]
fn generated_schemas_accept_nested_arrays_and_aliased_items() {
for (values, json_values) in OWN_VALUES {
let schema = generate(values, &GenerateOptions::default()).expect("generates");
let validator = jsonschema::validator_for(&schema).expect("compiles");
let instance: Value = serde_json::from_str(json_values).expect("json");
assert!(validator.is_valid(&instance), "{values}: {schema}");
}
}
#[test]
fn a_nested_array_item_is_an_array_schema() {
let schema = generate("matrix:\n - [1, 2]\n", &GenerateOptions::default()).expect("generates");
let items = &schema["properties"]["matrix"]["items"]["anyOf"];
assert_eq!(items[0]["type"], json!("array"));
assert_eq!(items[0]["items"]["anyOf"][0]["type"], json!("integer"));
}
#[test]
fn an_alias_that_contains_itself_is_an_error() {
for values in [
"a: &a\n b: *a\n",
"a: &a\n b:\n c: *a\n",
"a: &a\n - *a\n",
"a: &a\n - - *a\n",
"a: &a\n l:\n - *a\n",
] {
let error = generate(values, &GenerateOptions::default()).expect_err("fails");
assert_eq!(
error.to_string(),
"yaml: anchor 'a' value contains itself",
"{values}"
);
}
}
#[test]
fn a_merge_key_is_merged_not_a_property() {
let schema = generate(
"base: &base {a: 1}\nderived: {<<: *base, c: 3}\n",
&GenerateOptions::default(),
)
.expect("generates");
let derived = &schema["properties"]["derived"];
assert_eq!(derived["required"], json!(["c", "a"]));
assert!(derived["properties"].get("<<").is_none(), "{schema}");
let error = generate("d:\n <<: 5\n", &GenerateOptions::default()).expect_err("fails");
assert_eq!(
error.to_string(),
"yaml: map merge requires map or sequence of maps as the value"
);
}