Path: blob/main/crates/wasi/tests/all/store.rs
1693 views
use anyhow::Result;1use tempfile::TempDir;2use wasmtime::component::ResourceTable;3use wasmtime::{Engine, Store};4use wasmtime_wasi::{5DirPerms, FilePerms, WasiCtx, WasiCtxBuilder, WasiCtxView, WasiView, p2::pipe::MemoryOutputPipe,6};78pub struct Ctx<T> {9stdout: MemoryOutputPipe,10stderr: MemoryOutputPipe,11pub wasi: T,12}1314fn prepare_workspace(exe_name: &str) -> Result<TempDir> {15let prefix = format!("wasi_components_{exe_name}_");16let tempdir = tempfile::Builder::new().prefix(&prefix).tempdir()?;17Ok(tempdir)18}1920impl<T> Ctx<T> {21pub fn new(22engine: &Engine,23name: &str,24configure: impl FnOnce(&mut WasiCtxBuilder) -> T,25) -> Result<(Store<Ctx<T>>, TempDir)> {26const MAX_OUTPUT_SIZE: usize = 10 << 20;27let stdout = MemoryOutputPipe::new(MAX_OUTPUT_SIZE);28let stderr = MemoryOutputPipe::new(MAX_OUTPUT_SIZE);29let workspace = prepare_workspace(name)?;3031// Create our wasi context.32let mut builder = WasiCtxBuilder::new();33builder.stdout(stdout.clone()).stderr(stderr.clone());3435builder36.args(&[name, "."])37.inherit_network()38.allow_ip_name_lookup(true);39println!("preopen: {workspace:?}");40builder.preopened_dir(workspace.path(), ".", DirPerms::all(), FilePerms::all())?;41for (var, val) in test_programs_artifacts::wasi_tests_environment() {42builder.env(var, val);43}4445let ctx = Ctx {46wasi: configure(&mut builder),47stderr,48stdout,49};5051Ok((Store::new(&engine, ctx), workspace))52}53}5455impl<T> Drop for Ctx<T> {56fn drop(&mut self) {57let stdout = self.stdout.contents();58if !stdout.is_empty() {59println!("[guest] stdout:\n{}\n===", String::from_utf8_lossy(&stdout));60}61let stderr = self.stderr.contents();62if !stderr.is_empty() {63println!("[guest] stderr:\n{}\n===", String::from_utf8_lossy(&stderr));64}65}66}6768pub struct MyWasiCtx {69pub wasi: WasiCtx,70pub table: ResourceTable,71}7273impl WasiView for Ctx<MyWasiCtx> {74fn ctx(&mut self) -> WasiCtxView<'_> {75WasiCtxView {76ctx: &mut self.wasi.wasi,77table: &mut self.wasi.table,78}79}80}818283