Add test of functions with context.

This commit is contained in:
Stephen Chung 2021-03-15 21:30:45 +08:00
parent e9f280f917
commit 12e3a5b050

View File

@ -1,5 +1,5 @@
#![cfg(not(feature = "no_function"))] #![cfg(not(feature = "no_function"))]
use rhai::{Engine, EvalAltResult, FnNamespace, Module, ParseErrorType, INT}; use rhai::{Engine, EvalAltResult, FnNamespace, Module, NativeCallContext, ParseErrorType, INT};
#[test] #[test]
fn test_functions() -> Result<(), Box<EvalAltResult>> { fn test_functions() -> Result<(), Box<EvalAltResult>> {
@ -51,6 +51,20 @@ fn test_functions() -> Result<(), Box<EvalAltResult>> {
Ok(()) Ok(())
} }
#[test]
fn test_functions_context() -> Result<(), Box<EvalAltResult>> {
let mut engine = Engine::new();
engine.set_max_modules(40);
engine.register_fn("test", |context: NativeCallContext, x: INT| {
context.engine().max_modules() as INT + x
});
assert_eq!(engine.eval::<INT>("test(2)")?, 42);
Ok(())
}
#[test] #[test]
fn test_functions_params() -> Result<(), Box<EvalAltResult>> { fn test_functions_params() -> Result<(), Box<EvalAltResult>> {
let engine = Engine::new(); let engine = Engine::new();
@ -67,7 +81,6 @@ fn test_functions_params() -> Result<(), Box<EvalAltResult>> {
Ok(()) Ok(())
} }
#[cfg(not(feature = "no_function"))]
#[test] #[test]
fn test_functions_namespaces() -> Result<(), Box<EvalAltResult>> { fn test_functions_namespaces() -> Result<(), Box<EvalAltResult>> {
let mut engine = Engine::new(); let mut engine = Engine::new();
@ -81,12 +94,16 @@ fn test_functions_namespaces() -> Result<(), Box<EvalAltResult>> {
engine.register_static_module("hello", m.into()); engine.register_static_module("hello", m.into());
assert_eq!(engine.eval::<INT>("test()")?, 999); assert_eq!(engine.eval::<INT>("test()")?, 999);
#[cfg(not(feature = "no_function"))]
assert_eq!(engine.eval::<INT>("fn test() { 123 } test()")?, 123); assert_eq!(engine.eval::<INT>("fn test() { 123 } test()")?, 123);
} }
engine.register_fn("test", || 42 as INT); engine.register_fn("test", || 42 as INT);
assert_eq!(engine.eval::<INT>("test()")?, 42); assert_eq!(engine.eval::<INT>("test()")?, 42);
#[cfg(not(feature = "no_function"))]
assert_eq!(engine.eval::<INT>("fn test() { 123 } test()")?, 123); assert_eq!(engine.eval::<INT>("fn test() { 123 } test()")?, 123);
Ok(()) Ok(())