use super::*;
#[cfg(feature = "serde")]
#[test]
fn a_forged_history_tree_is_rejected() {
let cyclic = r#"{"nodes":[
{"id":0,"parent":1,"children":[],"label":"a","state":"a","group":null,"timestamp":0},
{"id":1,"parent":0,"children":[],"label":"b","state":"b","group":null,"timestamp":0}
],"current":0}"#;
assert!(serde_json::from_str::<History<String>>(cyclic).is_err());
let out_of_range = r#"{"nodes":[
{"id":0,"parent":null,"children":[],"label":"a","state":"a","group":null,"timestamp":0}
],"current":9}"#;
assert!(serde_json::from_str::<History<String>>(out_of_range).is_err());
}
#[test]
fn undo_and_branch_keep_the_abandoned_path() {
let mut history = History::new("a".to_owned());
let second = history.record("b", "ab".to_owned());
let third = history.record("c", "abc".to_owned());
assert!(history.can_undo());
assert!(!history.can_redo());
history.undo();
assert_eq!(history.state(), "ab");
let branch = history.record("!", "a!".to_owned());
assert_eq!(history.node(third).map(|node| node.label.as_str()), Some("c"));
assert_eq!(history.node(second).map(|node| node.children.len()), Some(2));
assert_eq!(history.node(branch).map(|node| node.state.as_str()), Some("a!"));
assert_eq!(history.len(), 4);
}
#[test]
fn redo_follows_the_last_child_and_jump_time_travels() {
let mut history = History::new(0);
history.record("one", 1);
let two = history.record("two", 2);
history.undo();
history.undo();
assert_eq!(history.state(), &0);
history.redo();
assert_eq!(history.state(), &1);
history.jump_to(two).expect("node exists");
assert_eq!(history.state(), &2);
assert!(history.jump_to(NodeId(99)).is_err());
}
#[test]
fn undo_then_redo_returns_to_the_undone_node() {
let mut history = History::new(0);
let branch = history.record("a", 1);
history.undo();
assert_eq!(history.redo(), Some(&1));
assert_eq!(history.current(), branch);
}
#[test]
fn a_group_coalesces_typing() {
let mut history = History::new(String::new());
history.begin_group("typing").expect("group");
let first = history.record("t", "t".to_owned());
let second = history.record("typing", "typing".to_owned());
assert_eq!(first, second, "the open group updates the same node");
history.end_group().expect("end");
history.record("!", "typing!".to_owned());
assert_eq!(history.len(), 3);
assert!(history.end_group().is_err());
}
#[test]
fn no_op_records_do_not_add_nodes() {
let mut history = History::new(1);
history.record("same", 1);
assert_eq!(history.len(), 1);
}
#[cfg(feature = "serde")]
#[test]
fn the_undo_tree_survives_json() {
let mut history = History::new("a".to_owned());
history.record("b", "ab".to_owned());
history.record("c", "abc".to_owned());
history.undo();
history.record("!", "a!".to_owned());
let json = serde_json::to_string(&history).expect("serialize");
let back: History<String> = serde_json::from_str(&json).expect("deserialize");
assert_eq!(back.state(), "a!");
assert_eq!(back.len(), history.len());
assert_eq!(back.current(), history.current());
}