2020-03-19 13:55:53 +01:00
|
|
|
use rhai::{Engine, EvalAltResult, Scope, INT};
|
|
|
|
|
|
|
|
#[test]
|
2020-04-21 17:25:12 +02:00
|
|
|
fn test_eval() -> Result<(), Box<EvalAltResult>> {
|
2020-04-07 07:23:06 +02:00
|
|
|
let engine = Engine::new();
|
2020-03-20 17:23:13 +01:00
|
|
|
|
|
|
|
assert_eq!(
|
|
|
|
engine.eval::<INT>(
|
|
|
|
r#"
|
|
|
|
eval("40 + 2")
|
|
|
|
"#
|
|
|
|
)?,
|
|
|
|
42
|
|
|
|
);
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
|
|
|
#[cfg(not(feature = "no_function"))]
|
2020-04-21 17:25:12 +02:00
|
|
|
fn test_eval_function() -> Result<(), Box<EvalAltResult>> {
|
2020-04-07 07:23:06 +02:00
|
|
|
let engine = Engine::new();
|
2020-03-19 13:55:53 +01:00
|
|
|
let mut scope = Scope::new();
|
|
|
|
|
|
|
|
assert_eq!(
|
|
|
|
engine.eval_with_scope::<INT>(
|
|
|
|
&mut scope,
|
|
|
|
r#"
|
|
|
|
let x = 10;
|
|
|
|
|
|
|
|
fn foo(x) { x += 12; x }
|
|
|
|
|
|
|
|
let script = "let y = x;"; // build a script
|
|
|
|
script += "y += foo(y);";
|
|
|
|
script += "x + y";
|
|
|
|
|
2020-04-28 17:05:03 +02:00
|
|
|
eval(script) + x + y
|
2020-03-19 13:55:53 +01:00
|
|
|
"#
|
|
|
|
)?,
|
2020-04-28 17:05:03 +02:00
|
|
|
84
|
2020-03-19 13:55:53 +01:00
|
|
|
);
|
|
|
|
|
|
|
|
assert_eq!(
|
|
|
|
scope
|
|
|
|
.get_value::<INT>("x")
|
|
|
|
.expect("variable x should exist"),
|
|
|
|
10
|
|
|
|
);
|
|
|
|
|
|
|
|
assert_eq!(
|
|
|
|
scope
|
|
|
|
.get_value::<INT>("y")
|
|
|
|
.expect("variable y should exist"),
|
|
|
|
32
|
|
|
|
);
|
|
|
|
|
2020-04-28 17:05:03 +02:00
|
|
|
assert!(scope.contains("script"));
|
|
|
|
assert_eq!(scope.len(), 3);
|
2020-03-19 13:55:53 +01:00
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|
|
|
|
|
|
|
|
#[test]
|
2020-03-20 17:23:13 +01:00
|
|
|
#[cfg(not(feature = "no_function"))]
|
2020-04-21 17:25:12 +02:00
|
|
|
fn test_eval_override() -> Result<(), Box<EvalAltResult>> {
|
2020-04-07 07:23:06 +02:00
|
|
|
let engine = Engine::new();
|
2020-03-19 13:55:53 +01:00
|
|
|
|
|
|
|
assert_eq!(
|
|
|
|
engine.eval::<String>(
|
|
|
|
r#"
|
|
|
|
fn eval(x) { x } // reflect the script back
|
|
|
|
|
|
|
|
eval("40 + 2")
|
|
|
|
"#
|
|
|
|
)?,
|
|
|
|
"40 + 2"
|
|
|
|
);
|
|
|
|
|
|
|
|
Ok(())
|
|
|
|
}
|