From 464228c5edbe6a93fbfc634220e106b6edd62b10 Mon Sep 17 00:00:00 2001 From: Bailey Hayes Date: Wed, 28 Dec 2022 11:38:16 -0500 Subject: [PATCH] fix: cargo wasi test preopen cwd This PR defaults `cargo wasi test` to always be run with the current working directory preopened. The goal is to allow existing tests to run without modification. Fixes #128 --- src/lib.rs | 11 ++++++++--- tests/tests/main.rs | 48 +++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+), 3 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index 09b305e..a968222 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -115,7 +115,7 @@ fn rmain(config: &mut Config) -> Result<()> { .map(|runner_override| (runner_override, false)) .unwrap_or_else(|_| ("wasmtime".to_string(), true)); - // Treat the wasi_runner variable as an exectable, followed by a whitespace- + // Treat the wasi_runner variable as an executable, followed by a whitespace- // separated list of arguments to the executable. This allows the user to // provide arguments which are passed to wasmtime without having to add more // command-line argument parsing to this crate. @@ -124,10 +124,15 @@ fn rmain(config: &mut Config) -> Result<()> { let runner = words .next() .ok_or_else(|| anyhow!("$CARGO_TARGET_WASM32_WASI_RUNNER must not be empty"))?; - let extra_args = words.collect::>(); + let mut extra_args = words.collect::>(); + + // Tests should be run with the current working directory preopened. + if let Subcommand::Test = subcommand { + extra_args.push("--dir=."); + } + (runner, extra_args) }; - match subcommand { Subcommand::Run | Subcommand::Bench | Subcommand::Test => { if !using_default { diff --git a/tests/tests/main.rs b/tests/tests/main.rs index c39144a..5035857 100644 --- a/tests/tests/main.rs +++ b/tests/tests/main.rs @@ -584,6 +584,54 @@ $", Ok(()) } +#[test] +fn test_read_file() -> Result<()> { + support::project() + .file("tests/data.txt", "42") + .file( + "src/lib.rs", + r#" +use std::fs; +use std::io; +use std::path::Path; +#[allow(dead_code)] +fn readfile() -> Result { + let contents = fs::read_to_string(Path::new("tests/data.txt")) + .expect("Should have been able to read the file"); + Ok(contents) +} + +#[test] +fn read() { + let contents = readfile().unwrap(); + assert_eq!(contents, "42"); +} + "#, + ) + .build() + .cargo_wasi("test") + .assert() + .stdout( + " +running 1 test +test read ... ok + +test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out + +", + ) + .stderr(is_match( + "^\ +.*Compiling foo v1.0.0 .* +.*Finished .* +.*Running .* +.*Running `.*` +$", + )?) + .success(); + Ok(()) +} + #[test] fn run_nothing() -> Result<()> { support::project()