Skip to content

Commit aa2639d

Browse files
committed
[Fix] Fix unit test
Signed-off-by: csh <[email protected]>
1 parent 9c95c51 commit aa2639d

19 files changed

+413
-4864
lines changed

crates/wasmedge-sys/src/ast_module.rs

+4-37
Original file line numberDiff line numberDiff line change
@@ -392,8 +392,7 @@ pub(crate) struct InnerExportType(pub(crate) *const ffi::WasmEdge_ExportTypeCont
392392
unsafe impl Send for InnerExportType {}
393393
unsafe impl Sync for InnerExportType {}
394394

395-
// #[cfg(test)]
396-
#[cfg(ignore)]
395+
#[cfg(test)]
397396
mod tests {
398397
use crate::{Config, Loader};
399398
use std::{
@@ -402,38 +401,6 @@ mod tests {
402401
};
403402
use wasmedge_types::{ExternalInstanceType, Mutability, RefType, ValType};
404403

405-
#[test]
406-
fn test_module_clone() {
407-
let path = std::env::current_dir()
408-
.unwrap()
409-
.ancestors()
410-
.nth(2)
411-
.unwrap()
412-
.join("examples/wasmedge-sys/data/import.wat");
413-
414-
let result = Config::create();
415-
assert!(result.is_ok());
416-
let mut config = result.unwrap();
417-
config.bulk_memory_operations(true);
418-
assert!(config.bulk_memory_operations_enabled());
419-
420-
// load module from file
421-
let result = Loader::create(Some(&config));
422-
assert!(result.is_ok());
423-
let loader = result.unwrap();
424-
let result = loader.from_file(path);
425-
assert!(result.is_ok());
426-
let module = result.unwrap();
427-
assert!(!module.inner.0.is_null());
428-
429-
// clone module
430-
let module_clone = module.clone();
431-
432-
drop(module);
433-
assert_eq!(std::sync::Arc::strong_count(&module_clone.inner), 1);
434-
drop(module_clone);
435-
}
436-
437404
#[test]
438405
fn test_module_import() {
439406
let path = std::env::current_dir()
@@ -617,7 +584,7 @@ mod tests {
617584
// check exports
618585

619586
assert_eq!(module.count_of_exports(), 16);
620-
let exports = module.exports();
587+
let exports = module.export();
621588

622589
// check the ty and name functions
623590
let result = exports[0].ty();
@@ -772,7 +739,7 @@ mod tests {
772739
// check exports
773740

774741
assert_eq!(module.count_of_exports(), 16);
775-
let exports = module.exports();
742+
let exports = module.export();
776743

777744
// check the ty and name functions
778745
let result = exports[0].ty();
@@ -934,7 +901,7 @@ mod tests {
934901
// check exports
935902

936903
assert_eq!(module.count_of_exports(), 16);
937-
let exports = module.exports();
904+
let exports = module.export();
938905

939906
// check the ty and name functions
940907
let result = exports[0].ty();

crates/wasmedge-sys/src/async/function.rs

+91-126
Original file line numberDiff line numberDiff line change
@@ -128,140 +128,105 @@ impl AsMut<Function> for AsyncFunction {
128128
}
129129
}
130130

131-
#[cfg(ignore)]
132-
/// Defines the signature of a host function.
133-
pub(crate) type HostFn<T> = fn(
134-
CallingFrame,
135-
Vec<WasmValue>,
136-
Option<&'static mut T>,
137-
) -> Result<Vec<WasmValue>, HostFuncError>;
138-
139-
#[cfg(ignore)]
140-
extern "C" fn wrap_sync_wasi_fn<T: 'static>(
141-
key_ptr: *mut std::ffi::c_void,
142-
data: *mut std::ffi::c_void,
143-
call_frame_ctx: *const ffi::WasmEdge_CallingFrameContext,
144-
params: *const ffi::WasmEdge_Value,
145-
param_len: u32,
146-
returns: *mut ffi::WasmEdge_Value,
147-
return_len: u32,
148-
) -> ffi::WasmEdge_Result {
149-
let frame = CallingFrame::create(call_frame_ctx);
150-
151-
// recover the async host function
152-
let real_func: HostFn<T> = unsafe { std::mem::transmute(key_ptr) };
153-
154-
// recover the context data
155-
let data = if std::any::TypeId::of::<T>() == std::any::TypeId::of::<NeverType>() {
156-
None
157-
} else {
158-
let data: &'static mut T = unsafe { &mut *(data as *mut T) };
159-
Some(data)
131+
#[cfg(test)]
132+
mod tests {
133+
use super::*;
134+
use crate::{
135+
instance::function::AsFunc, r#async::fiber::AsyncState, types::WasmValue, Executor,
160136
};
161137

162-
// input arguments
163-
let input = {
164-
let raw_input = unsafe {
165-
std::slice::from_raw_parts(
166-
params,
167-
param_len
168-
.try_into()
169-
.expect("len of params should not greater than usize"),
170-
)
171-
};
172-
raw_input.iter().map(|r| (*r).into()).collect::<Vec<_>>()
173-
};
138+
use wasmedge_types::{error::CoreExecutionError, FuncType, ValType};
174139

175-
// returns
176-
let return_len = return_len
177-
.try_into()
178-
.expect("len of returns should not greater than usize");
179-
let raw_returns = unsafe { std::slice::from_raw_parts_mut(returns, return_len) };
180-
181-
match real_func(frame, input, data) {
182-
Ok(returns) => {
183-
assert!(returns.len() == return_len, "[wasmedge-sys] check the number of returns of host function. Expected: {}, actual: {}", return_len, returns.len());
184-
for (idx, wasm_value) in returns.into_iter().enumerate() {
185-
raw_returns[idx] = wasm_value.as_raw();
186-
}
187-
ffi::WasmEdge_Result { Code: 0 }
140+
#[tokio::test]
141+
async fn test_func_basic() {
142+
#[derive(Debug)]
143+
struct Data<T, S> {
144+
_x: i32,
145+
_y: String,
146+
_v: Vec<T>,
147+
_s: Vec<S>,
188148
}
189-
Err(err) => match err {
190-
HostFuncError::User(code) => unsafe {
191-
ffi::WasmEdge_ResultGen(ffi::WasmEdge_ErrCategory_UserLevelError, code)
192-
},
193-
HostFuncError::Runtime(code) => unsafe {
194-
ffi::WasmEdge_ResultGen(ffi::WasmEdge_ErrCategory_WASM, code)
195-
},
196-
},
197-
}
198-
}
199-
#[cfg(ignore)]
200-
extern "C" fn wrap_async_wasi_fn<T: 'static>(
201-
key_ptr: *mut std::ffi::c_void,
202-
data: *mut std::ffi::c_void,
203-
call_frame_ctx: *const ffi::WasmEdge_CallingFrameContext,
204-
params: *const ffi::WasmEdge_Value,
205-
param_len: u32,
206-
returns: *mut ffi::WasmEdge_Value,
207-
return_len: u32,
208-
) -> ffi::WasmEdge_Result {
209-
let frame = CallingFrame::create(call_frame_ctx);
210149

211-
// recover the async host function
212-
let real_func: AsyncHostFn<T> = unsafe { std::mem::transmute(key_ptr) };
213-
214-
// recover the context data
215-
let data = if std::any::TypeId::of::<T>() == std::any::TypeId::of::<NeverType>() {
216-
None
217-
} else {
218-
let data: &'static mut T = unsafe { &mut *(data as *mut T) };
219-
Some(data)
220-
};
221-
222-
// arguments
223-
let input = {
224-
let raw_input = unsafe {
225-
std::slice::from_raw_parts(
226-
params,
227-
param_len
228-
.try_into()
229-
.expect("len of params should not greater than usize"),
230-
)
150+
let mut data: Data<i32, &str> = Data {
151+
_x: 12,
152+
_y: "hello".to_string(),
153+
_v: vec![1, 2, 3],
154+
_s: vec!["macos", "linux", "windows"],
231155
};
232-
raw_input.iter().map(|r| (*r).into()).collect::<Vec<_>>()
233-
};
234156

235-
// returns
236-
let return_len = return_len
237-
.try_into()
238-
.expect("len of returns should not greater than usize");
239-
let raw_returns = unsafe { std::slice::from_raw_parts_mut(returns, return_len) };
157+
fn real_add<T: core::fmt::Debug>(
158+
_host_data: &mut Data<i32, &str>,
159+
_inst: &mut AsyncInstance,
160+
_frame: &mut CallingFrame,
161+
input: Vec<WasmValue>,
162+
) -> Box<dyn Future<Output = Result<Vec<WasmValue>, CoreError>> + Send> {
163+
Box::new(async move {
164+
println!("Rust: Entering Rust function real_add");
165+
166+
if input.len() != 2 {
167+
return Err(CoreError::Execution(CoreExecutionError::FuncTypeMismatch));
168+
}
169+
170+
let a = if input[0].ty() == ValType::I32 {
171+
input[0].to_i32()
172+
} else {
173+
return Err(CoreError::Execution(CoreExecutionError::FuncTypeMismatch));
174+
};
175+
176+
let b = if input[1].ty() == ValType::I32 {
177+
input[1].to_i32()
178+
} else {
179+
return Err(CoreError::Execution(CoreExecutionError::FuncTypeMismatch));
180+
};
181+
182+
tokio::time::sleep(std::time::Duration::from_millis(300)).await;
183+
184+
let c = a + b;
185+
println!("Rust: calcuating in real_add c: {c:?}");
186+
187+
println!("Rust: Leaving Rust function real_add");
188+
Ok(vec![WasmValue::from_i32(c)])
189+
})
190+
}
240191

241-
let async_cx = AsyncCx::new();
242-
let mut future = Pin::from(real_func(frame, input, data));
243-
let result = match unsafe { async_cx.block_on(future.as_mut()) } {
244-
Ok(Ok(ret)) => Ok(ret),
245-
Ok(Err(err)) => Err(err),
246-
Err(_err) => Err(HostFuncError::Runtime(0x07)),
247-
};
192+
// create a FuncType
193+
let func_ty = FuncType::new(vec![ValType::I32; 2], vec![ValType::I32]);
194+
// create a host function
195+
let result =
196+
AsyncFunction::create_async_func(&func_ty, real_add::<Data<i32, &str>>, &mut data, 0);
197+
assert!(result.is_ok());
198+
let mut host_func = result.unwrap();
199+
200+
// get func type
201+
let result = host_func.ty();
202+
assert!(result.is_some());
203+
let ty = result.unwrap();
204+
205+
// check parameters
206+
assert_eq!(ty.args_len(), 2);
207+
assert_eq!(ty.args(), &[ValType::I32; 2]);
208+
209+
// check returns
210+
assert_eq!(ty.returns_len(), 1);
211+
assert_eq!(ty.returns(), &[ValType::I32]);
212+
213+
// run this function
214+
let result = Executor::create(None, None);
215+
assert!(result.is_ok());
216+
let mut executor = result.unwrap();
217+
218+
let async_state = AsyncState::new();
219+
220+
let result = executor
221+
.call_func_async(
222+
&async_state,
223+
host_func.as_mut(),
224+
vec![WasmValue::from_i32(1), WasmValue::from_i32(2)],
225+
)
226+
.await;
248227

249-
// parse result
250-
match result {
251-
Ok(returns) => {
252-
assert!(returns.len() == return_len, "[wasmedge-sys] check the number of returns of async host function. Expected: {}, actual: {}", return_len, returns.len());
253-
for (idx, wasm_value) in returns.into_iter().enumerate() {
254-
raw_returns[idx] = wasm_value.as_raw();
255-
}
256-
ffi::WasmEdge_Result { Code: 0 }
257-
}
258-
Err(err) => match err {
259-
HostFuncError::User(code) => unsafe {
260-
ffi::WasmEdge_ResultGen(ffi::WasmEdge_ErrCategory_UserLevelError, code)
261-
},
262-
HostFuncError::Runtime(code) => unsafe {
263-
ffi::WasmEdge_ResultGen(ffi::WasmEdge_ErrCategory_WASM, code)
264-
},
265-
},
228+
assert!(result.is_ok());
229+
let returns = result.unwrap();
230+
assert_eq!(returns[0].to_i32(), 3);
266231
}
267232
}

crates/wasmedge-sys/src/async/module.rs

+7-16
Original file line numberDiff line numberDiff line change
@@ -2442,21 +2442,13 @@ impl async_wasi::snapshots::common::memory::Memory for Memory {
24422442
}
24432443
}
24442444

2445-
// #[cfg(test)]
2446-
#[cfg(ignore)]
2445+
#[cfg(test)]
24472446
mod tests {
24482447
use super::*;
2449-
use crate::{
2450-
r#async::fiber::AsyncState, Config, Executor, Loader, Store, Validator, WasiInstance,
2451-
};
2448+
use crate::{r#async::fiber::AsyncState, Executor, Loader, Store, Validator};
24522449

24532450
#[tokio::test]
24542451
async fn test_async_wasi_module() -> Result<(), Box<dyn std::error::Error>> {
2455-
// create a Config
2456-
let mut config = Config::create()?;
2457-
config.wasi(true);
2458-
assert!(config.wasi_enabled());
2459-
24602452
// create an Executor
24612453
let result = Executor::create(None, None);
24622454
assert!(result.is_ok());
@@ -2471,11 +2463,10 @@ mod tests {
24712463
// create an AsyncWasiModule
24722464
let result = AsyncWasiModule::create(Some(vec!["abc"]), Some(vec![("ENV", "1")]), None);
24732465
assert!(result.is_ok());
2474-
let async_wasi_module = result.unwrap();
2466+
let mut async_wasi_module = result.unwrap();
24752467

24762468
// register async_wasi module into the store
2477-
let wasi_import = WasiInstance::AsyncWasi(async_wasi_module);
2478-
let result = executor.register_wasi_instance(&mut store, &wasi_import);
2469+
let result = executor.register_import_module(&mut store, async_wasi_module.as_mut());
24792470
assert!(result.is_ok());
24802471

24812472
let wasm_file = std::env::current_dir()
@@ -2486,8 +2477,8 @@ mod tests {
24862477
.join("examples/wasmedge-sys/async_hello.wasm");
24872478
let module = Loader::create(None)?.from_file(&wasm_file)?;
24882479
Validator::create(None)?.validate(&module)?;
2489-
let instance = executor.register_active_module(&mut store, &module)?;
2490-
let fn_start = instance.get_func("_start")?;
2480+
let mut instance = executor.register_active_module(&mut store, &module)?;
2481+
let mut fn_start = instance.get_func_mut("_start")?;
24912482

24922483
async fn tick() {
24932484
let mut i = 0;
@@ -2501,7 +2492,7 @@ mod tests {
25012492

25022493
let async_state = AsyncState::new();
25032494
let _ = executor
2504-
.call_func_async(&async_state, &fn_start, [])
2495+
.call_func_async(&async_state, &mut fn_start, [])
25052496
.await?;
25062497

25072498
Ok(())

0 commit comments

Comments
 (0)