Test for private functions.

This commit is contained in:
Stephen Chung 2020-05-13 13:49:01 +08:00
parent 8e8816cb0c
commit d613764c03
2 changed files with 39 additions and 7 deletions

View File

@ -41,13 +41,13 @@ fn test_call_fn() -> Result<(), Box<EvalAltResult>> {
",
)?;
let r: i64 = engine.call_fn(&mut scope, &ast, "hello", (42 as INT, 123 as INT))?;
let r: INT = engine.call_fn(&mut scope, &ast, "hello", (42 as INT, 123 as INT))?;
assert_eq!(r, 165);
let r: i64 = engine.call_fn(&mut scope, &ast, "hello", (123 as INT,))?;
let r: INT = engine.call_fn(&mut scope, &ast, "hello", (123 as INT,))?;
assert_eq!(r, 5166);
let r: i64 = engine.call_fn(&mut scope, &ast, "hello", ())?;
let r: INT = engine.call_fn(&mut scope, &ast, "hello", ())?;
assert_eq!(r, 42);
assert_eq!(
@ -60,6 +60,27 @@ fn test_call_fn() -> Result<(), Box<EvalAltResult>> {
Ok(())
}
#[test]
fn test_call_fn_private() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new();
let mut scope = Scope::new();
let ast = engine.compile("fn add(x, n) { x + n }")?;
let r: INT = engine.call_fn(&mut scope, &ast, "add", (40 as INT, 2 as INT))?;
assert_eq!(r, 42);
let ast = engine.compile("private fn add(x, n) { x + n }")?;
assert!(matches!(
*engine.call_fn::<_, INT>(&mut scope, &ast, "add", (40 as INT, 2 as INT))
.expect_err("should error"),
EvalAltResult::ErrorFunctionNotFound(fn_name, _) if fn_name == "add"
));
Ok(())
}
#[test]
fn test_anonymous_fn() -> Result<(), Box<EvalAltResult>> {
let calc_func = Func::<(INT, INT, INT), INT>::create_from_script(
@ -70,5 +91,16 @@ fn test_anonymous_fn() -> Result<(), Box<EvalAltResult>> {
assert_eq!(calc_func(42, 123, 9)?, 1485);
let calc_func = Func::<(INT, INT, INT), INT>::create_from_script(
Engine::new(),
"private fn calc(x, y, z) { (x + y) * z }",
"calc",
)?;
assert!(matches!(
*calc_func(42, 123, 9).expect_err("should error"),
EvalAltResult::ErrorFunctionNotFound(fn_name, _) if fn_name == "calc"
));
Ok(())
}

View File

@ -5,19 +5,19 @@ use rhai::{Engine, EvalAltResult, Func, ParseErrorType, Scope, INT};
fn test_functions() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new();
assert_eq!(engine.eval::<i64>("fn add(x, n) { x + n } add(40, 2)")?, 42);
assert_eq!(engine.eval::<INT>("fn add(x, n) { x + n } add(40, 2)")?, 42);
#[cfg(not(feature = "no_object"))]
assert_eq!(
engine.eval::<i64>("fn add(x, n) { x + n } let x = 40; x.add(2)")?,
engine.eval::<INT>("fn add(x, n) { x + n } let x = 40; x.add(2)")?,
42
);
assert_eq!(engine.eval::<i64>("fn mul2(x) { x * 2 } mul2(21)")?, 42);
assert_eq!(engine.eval::<INT>("fn mul2(x) { x * 2 } mul2(21)")?, 42);
#[cfg(not(feature = "no_object"))]
assert_eq!(
engine.eval::<i64>("fn mul2(x) { x * 2 } let x = 21; x.mul2()")?,
engine.eval::<INT>("fn mul2(x) { x * 2 } let x = 21; x.mul2()")?,
42
);