rhai/tests/eval.rs

179 lines
3.3 KiB
Rust
Raw Normal View History

2021-03-01 10:17:13 +01:00
use rhai::{Engine, EvalAltResult, LexError, ParseErrorType, Scope, INT};
2020-03-19 13:55:53 +01:00
#[test]
fn test_eval() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new();
2020-03-20 17:23:13 +01:00
assert_eq!(engine.eval::<INT>(r#"eval("40 + 2")"#)?, 42);
2020-03-20 17:23:13 +01:00
2021-12-30 05:23:35 +01:00
assert_eq!(
engine.eval::<INT>(
r#"
let foo = 42;
eval("let foo = 123");
eval("let xyz = 10");
foo + xyz
"#
)?,
133
);
2020-03-20 17:23:13 +01:00
Ok(())
}
#[test]
fn test_eval_blocks() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new();
assert_eq!(
engine.eval::<INT>(
r#"
let x = 999;
2021-12-28 10:50:49 +01:00
eval("let x = x - 1000");
2021-12-28 10:50:49 +01:00
let y = if x < 0 {
eval("let x = 42");
x
} else {
0
};
x + y
"#
)?,
2021-12-28 10:50:49 +01:00
41
);
2021-12-30 05:23:35 +01:00
assert_eq!(
engine.eval::<INT>(
r#"
let foo = 42;
eval("{ let foo = 123; }");
foo
"#
)?,
42
);
assert_eq!(
engine.eval::<INT>(
r#"
let foo = 42;
{ { {
eval("let foo = 123");
} } }
foo
"#
)?,
42
);
Ok(())
}
#[cfg(not(feature = "no_function"))]
#[cfg(not(feature = "no_module"))]
#[test]
fn test_eval_globals() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new();
assert_eq!(
engine.eval::<INT>(
r#"
const XYZ = 123;
fn foo() { global::XYZ }
{
eval("const XYZ = 42;");
}
foo()
"#
)?,
123
);
assert_eq!(
engine.eval::<INT>(
r#"
const XYZ = 123;
fn foo() { global::XYZ }
eval("const XYZ = 42;");
foo()
"#
)?,
42
);
Ok(())
}
2020-03-20 17:23:13 +01:00
#[test]
#[cfg(not(feature = "no_function"))]
fn test_eval_function() -> Result<(), Box<EvalAltResult>> {
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]
fn test_eval_disabled() -> Result<(), Box<EvalAltResult>> {
let mut engine = Engine::new();
engine.disable_symbol("eval");
assert!(matches!(
engine
.compile(r#"eval("40 + 2")"#)
2023-04-10 17:23:59 +02:00
.unwrap_err()
.err_type(),
2022-02-08 02:02:15 +01:00
ParseErrorType::BadInput(LexError::ImproperSymbol(err, ..)) if err == "eval"
));
2020-03-19 13:55:53 +01:00
Ok(())
}