From 60d6d934038cbea7cf793d9591001418c6efbc01 Mon Sep 17 00:00:00 2001 From: peefy Date: Tue, 10 Sep 2024 11:48:31 +0800 Subject: [PATCH] test: add kcl rust plugin unit tests Signed-off-by: peefy --- Cargo.toml | 4 ++++ src/lib.rs | 3 +++ src/tests.rs | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 55 insertions(+) create mode 100644 src/tests.rs diff --git a/Cargo.toml b/Cargo.toml index 98e07f5..d83873b 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,3 +12,7 @@ license = "Apache-2.0" [dependencies] anyhow = "1" kclvm-api = { git = "https://github.com/kcl-lang/kcl", version = "0.10.0-rc.1" } +kclvm-evaluator = { git = "https://github.com/kcl-lang/kcl", version = "0.10.0-rc.1" } +kclvm-loader = { git = "https://github.com/kcl-lang/kcl", version = "0.10.0-rc.1" } +kclvm-parser = { git = "https://github.com/kcl-lang/kcl", version = "0.10.0-rc.1" } +kclvm-runtime = { git = "https://github.com/kcl-lang/kcl", version = "0.10.0-rc.1" } diff --git a/src/lib.rs b/src/lib.rs index 3cb3d82..1bb5a35 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -33,6 +33,9 @@ use anyhow::Result; pub type API = KclvmServiceImpl; +#[cfg(test)] +mod tests; + /// Call KCL API with the API name and argument protobuf bytes. #[inline] pub fn call<'a>(name: &'a [u8], args: &'a [u8]) -> Result> { diff --git a/src/tests.rs b/src/tests.rs new file mode 100644 index 0000000..85f672d --- /dev/null +++ b/src/tests.rs @@ -0,0 +1,48 @@ +use anyhow::{anyhow, Result}; +use kclvm_evaluator::Evaluator; +use kclvm_loader::{load_packages, LoadPackageOptions}; +use kclvm_parser::LoadProgramOptions; +use kclvm_runtime::{Context, IndexMap, PluginFunction, ValueRef}; +use std::{cell::RefCell, rc::Rc, sync::Arc}; + +fn my_plugin_sum(_: &Context, args: &ValueRef, _: &ValueRef) -> Result { + let a = args + .arg_i_int(0, Some(0)) + .ok_or(anyhow!("expect int value for the first param"))?; + let b = args + .arg_i_int(1, Some(0)) + .ok_or(anyhow!("expect int value for the second param"))?; + Ok((a + b).into()) +} + +fn context_with_plugin() -> Rc> { + let mut plugin_functions: IndexMap = Default::default(); + let func = Arc::new(my_plugin_sum); + plugin_functions.insert("my_plugin.add".to_string(), func); + let mut ctx = Context::new(); + ctx.plugin_functions = plugin_functions; + Rc::new(RefCell::new(ctx)) +} + +#[test] +fn test_exec_with_plugin() -> Result<()> { + let src = r#" +import kcl_plugin.my_plugin + +sum = my_plugin.add(1, 1) +"#; + let p = load_packages(&LoadPackageOptions { + paths: vec!["test.k".to_string()], + load_opts: Some(LoadProgramOptions { + load_plugins: true, + k_code_list: vec![src.to_string()], + ..Default::default() + }), + load_builtin: false, + ..Default::default() + })?; + let evaluator = Evaluator::new_with_runtime_ctx(&p.program, context_with_plugin()); + let result = evaluator.run()?; + println!("yaml result {}", result.1); + Ok(()) +}