Skip to content

Commit

Permalink
Merge pull request #141 from Peefy/rust-plugin-unit-tests
Browse files Browse the repository at this point in the history
test: add kcl rust plugin unit tests
  • Loading branch information
Peefy authored Sep 10, 2024
2 parents 24046d6 + 60d6d93 commit cb0cf3b
Show file tree
Hide file tree
Showing 3 changed files with 55 additions and 0 deletions.
4 changes: 4 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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" }
3 changes: 3 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Vec<u8>> {
Expand Down
48 changes: 48 additions & 0 deletions src/tests.rs
Original file line number Diff line number Diff line change
@@ -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<ValueRef> {
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<RefCell<Context>> {
let mut plugin_functions: IndexMap<String, PluginFunction> = 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(())
}

0 comments on commit cb0cf3b

Please sign in to comment.