CosmWasm / cosmwasm

Framework for building smart contracts in Wasm for the Cosmos SDK
https://www.cosmwasm.com/
Apache License 2.0
1.06k stars 329 forks source link

Compile and run unit tests as Wasm #348

Open webmaster128 opened 4 years ago

webmaster128 commented 4 years ago

It would be cool if we could compile our unit tests to Wasm and run them in a Wasm runner, such as Wasmer. This ensures that architecture-specific code behaves correctly, such usize being 32 bit instead of 64 bit.

Unit tests can be compiled to Wasm using cargo build --tests --target wasm32-unknown-unknown. This gives us a test binary like target/wasm32-unknown-unknown/debug/serde_json_wasm-0930ffa5c8b80699.wasm with a main function:

$ wasm2wat target/wasm32-unknown-unknown/debug/serde_json_wasm-0930ffa5c8b80699.wasm | grep '(func \$main'
  (func $main (type 7) (param i32 i32) (result i32)
  (export "main" (func $main))

I tried to run this with the Wasmer CLI but have no idea what to pass in the two arguments.


Edit: the full main function is

  (func $main (type 7) (param i32 i32) (result i32)
    (local i32 i32)
    i32.const 112
    local.set 2
    local.get 2
    local.get 0
    local.get 1
    call $_ZN3std2rt10lang_start17h80f7e41d067e27deE
    local.set 3
    local.get 3
    return)

and std::rt::lang_start is defined here.

webmaster128 commented 4 years ago

Thanks to @hjorthjort we found a way to pass and empty argc and argv.

Passing tests:

$ wasmer run target/wasm32-unknown-unknown/debug/serde_json_wasm-c815590b4f16f3c6.wasm -- 0 0
main([I32(0), I32(0)]) returned [I32(0)]

Tests with failures:

$ wasmer run target/wasm32-unknown-unknown/debug/serde_json_wasm-c815590b4f16f3c6.wasm -- 0 0 
Error: RuntimeError: Caught exception of type "Unreachable".