[go: nahoru, domu]

Skip to content

Commit

Permalink
use new test framework
Browse files Browse the repository at this point in the history
Signed-off-by: Jorge Prendes <jorge.prendes@gmail.com>
  • Loading branch information
jprendes committed Sep 12, 2023
1 parent c3c9c77 commit 3271f53
Show file tree
Hide file tree
Showing 13 changed files with 213 additions and 457 deletions.
3 changes: 3 additions & 0 deletions .cargo/config.toml
Original file line number Diff line number Diff line change
Expand Up @@ -3,3 +3,6 @@ rustflags = [
"-Adead_code",
"-Awarnings",
]

[target.'cfg(unix)']
runner = 'scripts/test-runner.sh'
17 changes: 7 additions & 10 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 1 addition & 2 deletions crates/containerd-shim-wasmedge/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,9 @@ wasmedge-sys = "*"
libcontainer = { workspace = true }

[dev-dependencies]
env_logger = { workspace = true }
containerd-shim-wasm-test = { workspace = true }
libc = { workspace = true }
serial_test = "*"
tempfile = "3.8"

[features]
default = ["standalone", "static"]
Expand Down
3 changes: 2 additions & 1 deletion crates/containerd-shim-wasmedge/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,5 @@ pub fn parse_version() {

#[cfg(unix)]
#[cfg(test)]
mod tests;
#[path = "tests.rs"]
mod wasmedge_tests;
208 changes: 63 additions & 145 deletions crates/containerd-shim-wasmedge/src/tests.rs
Original file line number Diff line number Diff line change
@@ -1,186 +1,103 @@
use std::fs::read_to_string;

use anyhow::Result;
use containerd_shim_wasm::function;
use containerd_shim_wasm::sandbox::testutil::{
has_cap_sys_admin, run_test_with_sudo, run_wasi_test,
};
use containerd_shim_wasm::sandbox::{Instance as SandboxInstance, InstanceConfig, Stdio};
use serial_test::serial;
use tempfile::tempdir;

use crate::WasmEdgeInstance as Instance;

// This is taken from https://github.com/bytecodealliance/wasmtime/blob/6a60e8363f50b936e4c4fc958cb9742314ff09f3/docs/WASI-tutorial.md?plain=1#L270-L298
fn hello_world_module(start_fn: Option<&str>) -> Vec<u8> {
let start_fn = start_fn.unwrap_or("_start");
format!(r#"(module
;; Import the required fd_write WASI function which will write the given io vectors to stdout
;; The function signature for fd_write is:
;; (File Descriptor, *iovs, iovs_len, nwritten) -> Returns number of bytes written
(import "wasi_snapshot_preview1" "fd_write" (func $fd_write (param i32 i32 i32 i32) (result i32)))
(memory 1)
(export "memory" (memory 0))
;; Write 'hello world\n' to memory at an offset of 8 bytes
;; Note the trailing newline which is required for the text to appear
(data (i32.const 8) "hello world\n")
(func $main (export "{start_fn}")
;; Creating a new io vector within linear memory
(i32.store (i32.const 0) (i32.const 8)) ;; iov.iov_base - This is a pointer to the start of the 'hello world\n' string
(i32.store (i32.const 4) (i32.const 12)) ;; iov.iov_len - The length of the 'hello world\n' string
(call $fd_write
(i32.const 1) ;; file_descriptor - 1 for stdout
(i32.const 0) ;; *iovs - The pointer to the iov array, which is stored at memory location 0
(i32.const 1) ;; iovs_len - We're printing 1 string stored in an iov - so one.
(i32.const 20) ;; nwritten - A place in memory to store the number of bytes written
)
drop ;; Discard the number of bytes written from the top of the stack
)
)
"#).as_bytes().to_vec()
}
use std::time::Duration;

fn module_with_exit_code(exit_code: u32) -> Vec<u8> {
format!(r#"(module
;; Import the required proc_exit WASI function which terminates the program with an exit code.
;; The function signature for proc_exit is:
;; (exit_code: i32) -> !
(import "wasi_snapshot_preview1" "proc_exit" (func $proc_exit (param i32)))
(memory 1)
(export "memory" (memory 0))
(func $main (export "_start")
(call $proc_exit (i32.const {exit_code}))
unreachable
)
)
"#).as_bytes().to_vec()
}
//use containerd_shim_wasm::sandbox::Instance;
use containerd_shim_wasm_test::modules::*;
use containerd_shim_wasm_test::WasiTest;
use serial_test::serial;

const WASI_RETURN_ERROR: &[u8] = r#"(module
(func $main (export "_start")
(unreachable)
)
)
"#
.as_bytes();
use crate::instance::WasmEdgeInstance as WasiInstance;

#[test]
#[serial]
fn test_delete_after_create() -> Result<()> {
// start logging
let _ = env_logger::try_init();
let _guard = Stdio::init_from_std().guard();

let cfg = InstanceConfig::new(
Default::default(),
"test_namespace".into(),
"/containerd/address".into(),
);

let i = Instance::new("".to_string(), Some(&cfg));
i.delete()?;

fn test_delete_after_create() -> anyhow::Result<()> {
WasiTest::<WasiInstance>::builder()?.build()?.delete()?;
Ok(())
}

#[test]
#[serial]
fn test_wasi_entrypoint() -> Result<()> {
if !has_cap_sys_admin() {
println!("running test with sudo: {}", function!());
return run_test_with_sudo(function!());
}

// start logging
// to enable logging run `export RUST_LOG=trace` and append cargo command with
// --show-output before running test
let _ = env_logger::try_init();
let _guard = Stdio::init_from_std().guard();

let dir = tempdir()?;
let path = dir.path();
let wasm_bytes = hello_world_module(None);

let res = run_wasi_test::<Instance>(&dir, wasm_bytes, None)?;
fn test_hello_world() -> anyhow::Result<()> {
let (exit_code, stdout, _) = WasiTest::<WasiInstance>::builder()?
.with_wasm(HELLO_WORLD)?
.build()?
.start()?
.wait(Duration::from_secs(10))?;

assert_eq!(res.0, 0);

let output = read_to_string(path.join("stdout"))?;
assert_eq!(output, "hello world\n");
assert_eq!(exit_code, 0);
assert_eq!(stdout, "hello world\n");

Ok(())
}

#[test]
#[serial]
fn test_wasi_custom_entrypoint() -> Result<()> {
if !has_cap_sys_admin() {
println!("running test with sudo: {}", function!());
return run_test_with_sudo(function!());
}

// start logging
let _ = env_logger::try_init();
let _guard = Stdio::init_from_std().guard();
fn test_custom_entrypoint() -> anyhow::Result<()> {
let (exit_code, stdout, _) = WasiTest::<WasiInstance>::builder()?
.with_start_fn("foo")?
.with_wasm(CUSTOM_ENTRYPOINT)?
.build()?
.start()?
.wait(Duration::from_secs(10))?;

let dir = tempdir()?;
let path = dir.path();
let wasm_bytes = hello_world_module(Some("foo"));
assert_eq!(exit_code, 0);
assert_eq!(stdout, "hello world\n");

let res = run_wasi_test::<Instance>(&dir, wasm_bytes, Some("foo"))?;
Ok(())
}

assert_eq!(res.0, 0);
#[test]
#[serial]
fn test_unreachable() -> anyhow::Result<()> {
let (exit_code, _, _) = WasiTest::<WasiInstance>::builder()?
.with_wasm(UNREACHABLE)?
.build()?
.start()?
.wait(Duration::from_secs(10))?;

let output = read_to_string(path.join("stdout"))?;
assert_eq!(output, "hello world\n");
assert_ne!(exit_code, 0);

Ok(())
}

#[test]
#[serial]
fn test_wasi_error() -> Result<()> {
if !has_cap_sys_admin() {
println!("running test with sudo: {}", function!());
return run_test_with_sudo(function!());
}

// start logging
let _ = env_logger::try_init();
let _guard = Stdio::init_from_std().guard();

let dir = tempdir()?;
let res = run_wasi_test::<Instance>(&dir, WASI_RETURN_ERROR, None)?;
fn test_exit_code() -> anyhow::Result<()> {
let (exit_code, _, _) = WasiTest::<WasiInstance>::builder()?
.with_wasm(EXIT_CODE)?
.build()?
.start()?
.wait(Duration::from_secs(10))?;

// Expect error code from the run.
assert_eq!(res.0, 137);
assert_eq!(exit_code, 42);

Ok(())
}

#[test]
#[serial]
fn test_wasi_exit_code() -> Result<()> {
if !has_cap_sys_admin() {
println!("running test with sudo: {}", function!());
return run_test_with_sudo(function!());
}
fn test_seccomp() -> anyhow::Result<()> {
let (exit_code, stdout, _) = WasiTest::<WasiInstance>::builder()?
.with_wasm(SECCOMP)?
.build()?
.start()?
.wait(Duration::from_secs(10))?;

// start logging
let _ = env_logger::try_init();
let _guard = Stdio::init_from_std().guard();
assert_eq!(exit_code, 0);
assert_eq!(stdout.trim(), "current working dir: /");

let expected_exit_code: u32 = 42;
Ok(())
}

let dir = tempdir()?;
let wasm_bytes = module_with_exit_code(expected_exit_code);
let (actual_exit_code, _) = run_wasi_test::<Instance>(&dir, wasm_bytes, None)?;
#[test]
#[serial]
fn test_has_default_devices() -> anyhow::Result<()> {
let (exit_code, _, _) = WasiTest::<WasiInstance>::builder()?
.with_wasm(HAS_DEFAULT_DEVICES)?
.build()?
.start()?
.wait(Duration::from_secs(10))?;

assert_eq!(actual_exit_code, expected_exit_code);
assert_eq!(exit_code, 0);

Ok(())
}
Expand All @@ -190,6 +107,7 @@ fn test_wasi_exit_code() -> Result<()> {
// If wasmedge is statically linked, this will be the path to the current executable.
fn get_wasmedge_binary_path() -> Option<std::path::PathBuf> {
use std::os::unix::prelude::OsStrExt;

let f = wasmedge_sys::ffi::WasmEdge_VersionGet;
let mut info = unsafe { std::mem::zeroed() };
if unsafe { libc::dladdr(f as *const libc::c_void, &mut info) } == 0 {
Expand Down
3 changes: 1 addition & 2 deletions crates/containerd-shim-wasmer/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,8 @@ wasmer-wasix = { version = "0.12.0" }
libcontainer = { workspace = true }

[dev-dependencies]
env_logger = { workspace = true }
containerd-shim-wasm-test = { workspace = true }
serial_test = "*"
tempfile = "3.8"

[[bin]]
name = "containerd-shim-wasmer-v1"
Expand Down
4 changes: 3 additions & 1 deletion crates/containerd-shim-wasmer/src/instance_linux.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ use containerd_shim_wasm::container::{
Engine, Instance, PathResolve, RuntimeContext, Stdio, WasiEntrypoint,
};
use wasmer::{Module, Store};
use wasmer_wasix::virtual_fs::host_fs::FileSystem;
use wasmer_wasix::{WasiEnv, WasiError};

pub type WasmerInstance = Instance<WasmerEngine>;
Expand Down Expand Up @@ -45,10 +46,11 @@ impl Engine for WasmerEngine {
.build()?;
let _guard = runtime.enter();

log::info!("Creating `WasiEnv`...: args {:?}, envs: {:?}", args, envs);
log::info!("Creating `WasiEnv`...: args {args:?}, envs: {envs:?}");
let (instance, wasi_env) = WasiEnv::builder(mod_name)
.args(&args[1..])
.envs(envs)
.fs(Box::<FileSystem>::default())
.preopen_dir("/")?
.instantiate(module, &mut store)?;

Expand Down
3 changes: 2 additions & 1 deletion crates/containerd-shim-wasmer/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,5 @@ pub fn parse_version() {

#[cfg(unix)]
#[cfg(test)]
mod tests;
#[path = "tests.rs"]
mod wasmer_tests;
Loading

0 comments on commit 3271f53

Please sign in to comment.