use crate::RJini;
use anyhow::anyhow;
use anyhow::Result;
use itertools::Itertools;
use std::ops::Add;
impl RJini {
pub fn from(xpath: &str) -> Self {
RJini {
xpath: xpath.to_string(),
}
}
pub fn add_node(&self, node: &str) -> Result<RJini> {
if node.contains(" ") {
return Err(anyhow!(format!("#add_node: The \"{node}\" contain spaces")));
}
let b = self.xpath.clone() + &node + "/";
Ok(RJini { xpath: b })
}
pub fn remove_node(&self, node: &str) -> RJini {
let b = self.xpath.replace(&node.to_string().add("/"), "");
RJini { xpath: b }
}
pub fn replace_node(&self, origin: &str, new: &str) -> RJini {
let x = self
.xpath
.split("/")
.map(|node| {
return if String::from(node).eq(origin) {
new
} else {
node
};
})
.join("/")
.to_string();
RJini { xpath: x }
}
}
#[test]
fn checks_creates_rjini_from() -> Result<()> {
let j = RJini::from("parent/child");
assert!(j.xpath.contains("child"));
Ok(())
}
#[test]
fn checks_adds_node() -> Result<()> {
let j = RJini::from("parent/");
let j = j.add_node("child")?;
let j = j.add_node("toys")?;
println!("{}", j.xpath);
assert!(j.xpath.contains("child/") && j.xpath.contains("toys/"));
Ok(())
}
#[test]
fn checks_error_on_add_wrong_node() -> Result<()> {
let actual = format!(
"{}",
RJini::empty()
.add_node("so me no de")
.unwrap_err()
.root_cause()
);
assert!(actual.contains("#add_node: The"));
Ok(())
}
#[test]
fn checks_removes_node() -> Result<()> {
let j = RJini::empty()
.add_node("Ruby")?
.add_node("is")?
.add_node("not")?
.add_node("my")?
.add_node("dog")?
.remove_node("not");
assert_eq!("Ruby/is/my/dog/", j.xpath);
Ok(())
}
#[test]
fn checks_replaces_node() -> Result<()> {
let j = RJini::empty()
.add_node("Ruby")?
.add_node("is")?
.add_node("a")?
.add_node("bad")?
.add_node("dog")?
.replace_node("bad", "good")
.xpath;
assert_eq!("Ruby/is/a/good/dog/", j);
Ok(())
}