use icedwright_semantics::yaml::{self, STATE_NAMES, YamlOptions};
use icedwright_semantics::{Error, NodePath, SemanticTree, TreeBuilder};
use icedwright_types::{Point, StateName, role};
use proptest::prelude::*;
use proptest::test_runner::{Config, RngSeed};
fn seeded(name: &str) -> Config {
let seed = name.bytes().fold(0xcbf2_9ce4_8422_2325_u64, |hash, byte| {
(hash ^ u64::from(byte)).wrapping_mul(0x0100_0000_01b3)
});
Config {
rng_seed: RngSeed::Fixed(seed),
cases: 256,
..Config::default()
}
}
fn root(tree: &SemanticTree) -> icedwright_semantics::NodeId {
tree.roots()[0]
}
fn dialog_tree() -> SemanticTree {
TreeBuilder::window("Todo")
.child(role::Toolbar, "Tools", |t| {
t.child(role::Button, "Undo", |b| b.disabled(true))
})
.child(role::Dialog, "Delete item?", |d| {
d.modal(true)
.child(role::Heading, "Delete item?", |h| h.level(2))
.text("Water the beans will be removed.")
.child(role::Button, "Cancel", |b| b)
.child(role::Button, "Delete", |b| b.test_id("delete"))
})
.child(role::TextBox, "New item", |t| {
t.value("Sow the leeks")
.placeholder("What needs doing?")
.focused(true)
})
.child(role::Slider, "Volume", |s| s.range(0.5, 0.0..=1.0))
.child(role::TreeItem, "Roadmap", |t| {
t.expanded(false)
.checked(icedwright_types::Checked::Mixed)
.level(1)
.position(1, 3)
.prop("unsaved", "true")
.tooltip("A project")
.description("Next quarter")
})
.build()
}
#[test]
fn write_snapshot_default() {
let tree = dialog_tree();
insta::assert_snapshot!(yaml::write(&tree, root(&tree), &YamlOptions::default()));
}
#[test]
fn write_snapshot_with_everything() {
let tree = dialog_tree();
let options = YamlOptions {
include_bounds: true,
include_ids: true,
include_ignored: true,
mask_props: vec!["unsaved".to_owned()],
refs: true,
..YamlOptions::default()
};
insta::assert_snapshot!(yaml::write(&tree, root(&tree), &options));
}
#[test]
fn write_a_subtree() {
let tree = dialog_tree();
let dialog = tree
.iter()
.find(|n| n.role == icedwright_types::Role::Dialog)
.map(|n| n.id);
let Some(dialog) = dialog else {
panic!("no dialog");
};
let text = yaml::write(&tree, dialog, &YamlOptions::default());
assert!(
text.starts_with("- dialog \"Delete item?\" [modal]:\n"),
"{text}"
);
}
#[test]
fn depth_and_max_lines_cut_the_output() {
let tree = dialog_tree();
let shallow = YamlOptions {
depth: Some(0),
..YamlOptions::default()
};
let text = yaml::write(&tree, root(&tree), &shallow);
assert!(text.lines().all(|l| l.starts_with("- ")), "{text}");
assert_eq!(text.lines().count(), 5);
let short = YamlOptions {
max_lines: Some(4),
..YamlOptions::default()
};
let text = yaml::write(&tree, root(&tree), &short);
let lines: Vec<&str> = text.lines().collect();
assert_eq!(lines.len(), 4);
assert_eq!(lines[3].trim_start(), "- ...");
}
#[test]
fn write_then_read_gives_back_the_same_text() -> Result<(), Error> {
let tree = dialog_tree();
for options in [
YamlOptions::default(),
YamlOptions {
include_bounds: true,
include_ids: true,
..YamlOptions::default()
},
YamlOptions {
include_ignored: true,
..YamlOptions::default()
},
] {
let text = yaml::write(&tree, root(&tree), &options);
let back = yaml::read(&text)?;
assert_eq!(yaml::write(&back, root(&back), &options), text);
}
Ok(())
}
#[test]
fn read_keeps_every_field_the_format_carries() -> Result<(), Error> {
let tree = dialog_tree();
let options = YamlOptions {
include_bounds: true,
include_ids: true,
..YamlOptions::default()
};
let back = yaml::read(&yaml::write(&tree, root(&tree), &options))?;
for node in tree.iter().filter(|n| !n.ignored && n.parent.is_some()) {
let mut segments = node.path.segments().to_vec();
segments[0] = icedwright_semantics::Segment::Role {
role: icedwright_types::Role::Window,
name: None,
index: 0,
};
let Some(other) = back.node_at(&NodePath::new(segments)) else {
panic!("{} missing after reading", node.path);
};
assert_eq!(other.role, node.role);
assert_eq!(other.name, node.name);
assert_eq!(other.description, node.description);
assert_eq!(other.placeholder, node.placeholder);
assert_eq!(other.tooltip, node.tooltip);
assert_eq!(other.value, node.value);
assert_eq!(other.set, node.set);
assert_eq!(other.test_id, node.test_id);
assert_eq!(other.props, node.props);
assert_eq!(
other.states.known().collect::<Vec<_>>(),
node.states.known().collect::<Vec<_>>()
);
let rounded = |r: icedwright_types::Rect| {
(r.x.round(), r.y.round(), r.width.round(), r.height.round())
};
assert_eq!(rounded(other.bounds), rounded(node.bounds));
}
Ok(())
}
#[test]
fn read_hand_written_fixtures() -> Result<(), Error> {
let tree = yaml::read(
r#"
- list "Items":
- listitem: Water the beans
- listitem "Sow the leeks" [selected]
- textbox "Notes":
- /value: " padded "
- text: inside
- ...
"#,
)?;
let list = tree.iter().find(|n| n.name.as_deref() == Some("Items"));
assert_eq!(list.map(|n| n.children.len()), Some(3));
let notes = tree.iter().find(|n| n.name.as_deref() == Some("Notes"));
assert_eq!(
notes.and_then(|n| n.value.clone()),
Some(icedwright_semantics::Value::Text(" padded ".to_owned()))
);
let sow = tree
.iter()
.find(|n| n.name.as_deref() == Some("Sow the leeks"));
assert_eq!(sow.map(|n| tree.text_content(n.id)), Some("Sow the leeks"));
Ok(())
}
#[test]
fn read_reports_line_and_column() {
let cases = [
("- buton \"x\"", 1, 3),
("- button\n - text: x", 2, 4),
("- button [checked=maybe]", 1, 19),
("- button [nope=1]", 1, 11),
("- button \"open", 1, 10),
(" - button", 1, 3),
("- /value: x", 1, 1),
("button", 1, 1),
];
for (input, line, column) in cases {
match yaml::read(input) {
Err(Error::Yaml {
line: l, column: c, ..
}) => assert_eq!((l, c), (line, column), "{input}"),
other => panic!("{input}: {other:?}"),
}
}
}
#[test]
fn state_names_cover_every_state_in_order() {
let names: Vec<StateName> = STATE_NAMES.iter().map(|(s, _)| *s).collect();
assert_eq!(names, StateName::ALL);
for (state, name) in STATE_NAMES {
assert_eq!(state.name(), *name);
}
}
#[test]
fn serde_round_trips_a_fixture() -> Result<(), serde_json::Error> {
let tree = dialog_tree();
let json = serde_json::to_string(&tree)?;
assert_eq!(serde_json::from_str::<SemanticTree>(&json)?, tree);
let carets = TreeBuilder::window("Notes")
.child(role::Paragraph, "Body", |p| {
p.carets([(0, Point::new(0.0, 0.0))])
})
.build();
let json = serde_json::to_string(&carets)?;
assert_eq!(serde_json::from_str::<SemanticTree>(&json)?, carets);
Ok(())
}
fn name_strategy() -> impl Strategy<Value = String> {
prop_oneof![
"[a-zA-Z ]{1,12}",
any::<String>().prop_filter("non-empty", |s| !s.is_empty()),
Just("quote \" and \\ slash / >> [".to_owned()),
]
}
fn path_strategy() -> impl Strategy<Value = NodePath> {
let segment = prop_oneof![
(
proptest::sample::select(icedwright_types::Role::ALL),
proptest::option::of(name_strategy()),
0u32..4
)
.prop_map(|(role, name, index)| icedwright_semantics::Segment::Role {
role,
name,
index
}),
("[a-z0-9._-]{1,8}|[A-Z ]{1,4}", 0u32..3)
.prop_map(|(id, index)| icedwright_semantics::Segment::TestId { id, index }),
];
proptest::collection::vec(segment, 1..6).prop_map(NodePath::new)
}
proptest! {
#![proptest_config(seeded("node_paths_round_trip"))]
#[test]
fn node_paths_round_trip(path in path_strategy()) {
let text = path.to_string();
prop_assert_eq!(text.parse::<NodePath>().ok(), Some(path), "{}", text);
}
}
proptest! {
#![proptest_config(seeded("yaml_round_trips_generated_trees"))]
#[test]
fn yaml_round_trips_generated_trees(names in proptest::collection::vec(name_strategy(), 1..8), value in any::<String>()) {
let mut builder = TreeBuilder::window("Generated");
for (i, name) in names.iter().enumerate() {
let value = value.clone();
builder = builder.child(role::TextBox, name, move |t| {
let t = t.value(&value);
if i % 2 == 0 { t.focused(true) } else { t.disabled(false) }
});
}
let tree = builder.build();
let text = yaml::write(&tree, root(&tree), &YamlOptions::default());
let back = yaml::read(&text);
prop_assert!(back.is_ok(), "{:?}\n{}", back, text);
let back = back.unwrap_or_default();
prop_assert_eq!(yaml::write(&back, root(&back), &YamlOptions::default()), text);
}
}
#[derive(Debug, PartialEq)]
enum Parsed {
Leaf(String),
Value(String, String),
Parent(String, Vec<Parsed>),
}
fn scalar_text(node: &saphyr::Yaml<'_>) -> Result<String, String> {
match node {
saphyr::Yaml::Representation(text, _, _) => Ok(text.to_string()),
other => Err(format!("expected a scalar, found {other:?}")),
}
}
fn entries(node: &saphyr::Yaml<'_>) -> Result<Vec<Parsed>, String> {
let saphyr::Yaml::Sequence(items) = node else {
return Err(format!("expected a sequence, found {node:?}"));
};
items
.iter()
.map(|item| match item {
saphyr::Yaml::Mapping(map) => {
let mut pairs = map.iter();
let (Some((key, value)), None) = (pairs.next(), pairs.next()) else {
return Err(format!("expected one key, found {map:?}"));
};
let key = scalar_text(key)?;
match value {
saphyr::Yaml::Sequence(_) => Ok(Parsed::Parent(key, entries(value)?)),
value => Ok(Parsed::Value(key, scalar_text(value)?)),
}
}
leaf => Ok(Parsed::Leaf(scalar_text(leaf)?)),
})
.collect()
}
fn parse_with_saphyr(text: &str) -> Result<Vec<Parsed>, String> {
let mut loader = saphyr::YamlLoader::default();
loader.early_parse(false);
let mut parser = saphyr_parser::Parser::new_from_str(text);
parser
.load(&mut loader, true)
.map_err(|error| format!("{error}\n{text}"))?;
let documents: Vec<saphyr::Yaml<'_>> = loader.into_documents();
let [document] = documents.as_slice() else {
return Err(format!("expected one document, found {}", documents.len()));
};
entries(document)
}
fn name_in_key(key: &str) -> Result<Option<String>, Error> {
let tree = yaml::read(&format!("- '{}'\n", key.replace('\'', "''")))?;
Ok(tree.iter().find_map(|node| node.name.clone()))
}
const AWKWARD: &[&str] = &[
"a: b",
"issue #4",
"ends with a colon:",
"it's",
"- dash",
"[bracket]",
"{brace}",
"#hash",
"&anchor",
"*alias",
"!tag",
"|pipe",
">fold",
"%percent",
"@at",
"`tick",
"?question",
":colon",
"/not a regex/",
"\"quoted\"",
"'single'",
"true",
"null",
"~",
"0x1f",
"...",
"---",
" leading space",
"trailing space ",
"tab\there",
"line\nbreak",
"bell\u{7}",
"next line\u{85}",
"bom\u{feff}",
"separator\u{2028}",
"back\\slash",
"comma, and more",
];
#[test]
fn awkward_names_and_values_parse_as_yaml_and_keep_their_text() -> Result<(), String> {
let long = "x".repeat(2000);
let texts: Vec<&str> = AWKWARD.iter().copied().chain([long.as_str()]).collect();
let mut builder = TreeBuilder::window("Awkward");
for text in &texts {
builder = builder.child(role::TextBox, text, |t| t.value(text));
builder = builder.child(role::Button, text, |b| b.description(text).prop("p", text));
builder = builder.text(text);
builder = builder.child(role::TextBox, text, |l| {
l.value(text).child(role::ListItem, text, |i| i)
});
}
let tree = builder.build();
let text = yaml::write(&tree, root(&tree), &YamlOptions::default());
let parsed = parse_with_saphyr(&text)?;
let mut parsed = parsed.into_iter();
let window = root(&tree);
let mut texts_shown = tree
.iter()
.filter(|n| n.role == icedwright_types::Role::Text && n.parent == Some(window))
.map(|n| tree.text_content(n.id).to_owned());
for expected in &texts {
let expected = (*expected).to_owned();
let Some(Parsed::Value(key, value)) = parsed.next() else {
return Err(format!(
"the text box for {expected:?} is not a key and value"
));
};
assert_eq!(value, expected, "text box value in\n{text}");
assert_eq!(
name_in_key(&key).map_err(|e| e.to_string())?,
Some(expected.clone())
);
let Some(Parsed::Parent(key, label)) = parsed.next() else {
return Err(format!("the button for {expected:?} has no label"));
};
assert_eq!(
name_in_key(&key).map_err(|e| e.to_string())?,
Some(expected.clone())
);
assert!(
matches!(label.as_slice(), [Parsed::Value(key, _)] if key == "text"),
"{label:?}"
);
let Some(Parsed::Value(key, value)) = parsed.next() else {
return Err(format!("the text {expected:?} is not a key and value"));
};
let shown = texts_shown.next().unwrap_or_default();
assert_eq!((key.as_str(), value.as_str()), ("text", shown.as_str()));
let Some(Parsed::Parent(_, children)) = parsed.next() else {
return Err(format!("the list for {expected:?} has no children"));
};
let [Parsed::Value(directive, value), Parsed::Parent(item, _)] = children.as_slice() else {
return Err(format!("the list for {expected:?} has {children:?}"));
};
assert_eq!((directive.as_str(), value), ("/value", &expected));
assert_eq!(
name_in_key(item).map_err(|e| e.to_string())?,
Some(expected)
);
}
let back = yaml::read(&text).map_err(|e| e.to_string())?;
assert_eq!(
yaml::write(&back, root(&back), &YamlOptions::default()),
text
);
Ok(())
}
proptest! {
#![proptest_config(seeded("yaml_output_always_parses_as_yaml"))]
#[test]
fn yaml_output_always_parses_as_yaml(
texts in proptest::collection::vec(name_strategy(), 1..6),
value in any::<String>(),
bounds in any::<bool>(),
) {
let mut builder = TreeBuilder::window("Generated");
for text in &texts {
let value = value.clone();
builder = builder
.child(role::TextBox, text, move |t| t.value(&value).placeholder(text))
.text(text)
.child(role::Group, text, |g| g.child(role::Button, text, |b| b.tooltip(text)));
}
let tree = builder.build();
let options = YamlOptions {
include_bounds: bounds,
include_ids: bounds,
refs: bounds,
..YamlOptions::default()
};
let text = yaml::write(&tree, root(&tree), &options);
let parsed = parse_with_saphyr(&text);
prop_assert!(parsed.is_ok(), "{:?}", parsed);
let mut values = parsed.unwrap_or_default().into_iter().filter_map(|entry| match entry {
Parsed::Value(key, value) if key.starts_with("textbox") => Some(value),
_ => None,
});
if !value.is_empty() {
prop_assert_eq!(values.next(), Some(value.clone()), "{}", text);
}
let back = yaml::read(&text);
prop_assert!(back.is_ok(), "{:?}\n{}", back, text);
let back = back.unwrap_or_default();
prop_assert_eq!(yaml::write(&back, root(&back), &options), text);
}
}