Path: blob/main/crates/wizer/tests/all/make_linker.rs
3073 views
use wasmtime::{Result, error::Context as _, format_err};1use wasmtime_wasi::WasiCtxBuilder;2use wasmtime_wizer::Wizer;3use wat::parse_str as wat_to_wasm;45async fn run_wasm(args: &[wasmtime::Val], expected: i32, wasm: &[u8]) -> Result<()> {6let _ = env_logger::try_init();78let mut config = wasmtime::Config::new();9wasmtime::Cache::from_file(None)10.map(|cache| config.cache(Some(cache)))11.unwrap();12config.wasm_multi_memory(true);13config.wasm_multi_value(true);1415let engine = wasmtime::Engine::new(&config)?;16let wasi_ctx = WasiCtxBuilder::new().build_p1();17let mut store = wasmtime::Store::new(&engine, wasi_ctx);18let wasm = Wizer::new()19.run(&mut store, &wasm, async |store, module| {20let mut linker = wasmtime::Linker::new(module.engine());21linker.func_wrap("foo", "bar", |x: i32| x + 1)?;22linker.instantiate_async(store, module).await23})24.await?;25log::debug!(26"=== Wizened Wasm ==========================================================\n\27{}\n\28===========================================================================",29wasmprinter::print_bytes(&wasm).unwrap()30);31if log::log_enabled!(log::Level::Debug) {32std::fs::write("test.wasm", &wasm).unwrap();33}3435let wasi_ctx = WasiCtxBuilder::new().build_p1();36let mut store = wasmtime::Store::new(&engine, wasi_ctx);37let module =38wasmtime::Module::new(store.engine(), wasm).context("Wasm test case failed to compile")?;3940let mut linker = wasmtime::Linker::new(&engine);41linker.func_wrap("foo", "bar", |_: i32| -> Result<i32> {42Err(format_err!("shouldn't be called"))43})?;4445let instance = linker.instantiate_async(&mut store, &module).await?;4647let run = instance.get_func(&mut store, "run").ok_or_else(|| {48wasmtime::format_err!("the test Wasm module does not export a `run` function")49})?;5051let mut actual = vec![wasmtime::Val::I32(0)];52run.call_async(&mut store, args, &mut actual).await?;53wasmtime::ensure!(actual.len() == 1, "expected one result");54let actual = match actual[0] {55wasmtime::Val::I32(x) => x,56_ => wasmtime::bail!("expected an i32 result"),57};58wasmtime::ensure!(59expected == actual,60"expected `{expected}`, found `{actual}`",61);6263Ok(())64}6566async fn run_wat(args: &[wasmtime::Val], expected: i32, wat: &str) -> Result<()> {67let _ = env_logger::try_init();68let wasm = wat_to_wasm(wat)?;69run_wasm(args, expected, &wasm).await70}7172#[tokio::test]73async fn custom_linker() -> Result<()> {74run_wat(75&[],761,77r#"78(module79(type (func (param i32) (result i32)))80(import "foo" "bar" (func (type 0)))81(global $g (mut i32) (i32.const 0))82(func (export "wizer-initialize")83global.get $g84call 085global.set $g86)87(func (export "run") (result i32)88(global.get $g)89)90)"#,91)92.await93}949596