Skip to content

Commit

Permalink
(test) add test for script helper and its reload in dev mode
Browse files Browse the repository at this point in the history
  • Loading branch information
sunng87 committed Nov 30, 2020
1 parent beddf2a commit d8f60c1
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 8 deletions.
2 changes: 1 addition & 1 deletion Cargo.toml
Expand Up @@ -28,7 +28,7 @@ pest_derive = "2.1.0"
serde = "1.0.0"
serde_json = "1.0.39"
walkdir = { version = "2.2.3", optional = true }
rhai = { version = "0.19.4", optional = true, features = ["sync", "serde"] }
rhai = { version = "0.19.6", optional = true, features = ["sync", "serde"] }

[dev-dependencies]
env_logger = "0.7.1"
Expand Down
68 changes: 61 additions & 7 deletions src/registry.rs
Expand Up @@ -329,12 +329,8 @@ impl<'reg> Registry<'reg> {
///
///
#[cfg(feature = "script_helper")]
pub fn register_script_helper(
&mut self,
name: &str,
script: String,
) -> Result<(), ScriptError> {
let compiled = self.engine.compile(&script)?;
pub fn register_script_helper(&mut self, name: &str, script: &str) -> Result<(), ScriptError> {
let compiled = self.engine.compile(script)?;
let script_helper = ScriptHelper { script: compiled };
self.helpers
.insert(name.to_string(), Rc::new(script_helper));
Expand All @@ -355,7 +351,7 @@ impl<'reg> Registry<'reg> {
let script = source.load()?;

self.script_sources.insert(name.to_owned(), Rc::new(source));
self.register_script_helper(name, script)
self.register_script_helper(name, &script)
}

/// Register a decorator
Expand Down Expand Up @@ -992,4 +988,62 @@ mod test {

dir.close().unwrap();
}

#[test]
#[cfg(feature = "script_helper")]
fn test_script_helper() {
let mut reg = Registry::new();

reg.register_script_helper(
"acc",
"params.reduce(|sum, x| if sum.type_of() == \"()\" { x } else { x + sum} )",
)
.unwrap();

assert_eq!(
reg.render_template("{{acc 1 2 3 4}}", &json!({})).unwrap(),
"10"
);
}

#[test]
#[cfg(feature = "script_helper")]
fn test_script_helper_dev_mode() {
let mut reg = Registry::new();
reg.set_dev_mode(true);

let dir = tempdir().unwrap();
let file1_path = dir.path().join("acc.rhai");
{
let mut file1: File = File::create(&file1_path).unwrap();
write!(
file1,
"params.reduce(|sum, x| if sum.type_of() == \"()\" {{ x }} else {{ x + sum }} )"
)
.unwrap();
}

reg.register_script_helper_file("acc", &file1_path).unwrap();

assert_eq!(
reg.render_template("{{acc 1 2 3 4}}", &json!({})).unwrap(),
"10"
);

{
let mut file1: File = File::create(&file1_path).unwrap();
write!(
file1,
"params.reduce(|sum, x| if sum.type_of() == \"()\" {{ x }} else {{ x * sum }} )"
)
.unwrap();
}

assert_eq!(
reg.render_template("{{acc 1 2 3 4}}", &json!({})).unwrap(),
"24"
);

dir.close().unwrap();
}
}

0 comments on commit d8f60c1

Please sign in to comment.